content
stringlengths 5
1.05M
|
|---|
local export = {}
local date_and_time = "mw:Help:Magic words#Date and time"
local technical_metadata = "mw:Help:Magic words#Technical metadata"
local tech_meta_another_page = "mw:Help:Magic words#Technical metadata of another page"
local page_names = "mw:Help:Magic words#Page names"
local namespaces = "mw:Help:Magic words#Namespaces"
local formatting = "mw:Help:Magic words#Formatting"
local URL_data = "mw:Help:Magic words#URL data"
local localization = "mw:Help:Magic words#Localization"
local miscellaneous = "mw:Help:Magic words#Miscellaneous"
local parser_functions_link = "mw:Help:Extension:ParserFunctions"
local LST = "mw:Extension:Labeled Section Transclusion"
local variables_nullary = {
["CURRENTYEAR" ] = date_and_time;
["CURRENTMONTH" ] = date_and_time;
["CURRENTMONTH1" ] = date_and_time; -- undocumented
["CURRENTMONTH2" ] = date_and_time; -- undocumented
["CURRENTMONTHNAME" ] = date_and_time;
["CURRENTMONTHNAMEGEN"] = date_and_time;
["CURRENTMONTHABBREV" ] = date_and_time;
["CURRENTDAY" ] = date_and_time;
["CURRENTDAY2" ] = date_and_time;
["CURRENTDOW" ] = date_and_time;
["CURRENTDAYNAME" ] = date_and_time;
["CURRENTTIME" ] = date_and_time;
["CURRENTHOUR" ] = date_and_time;
["CURRENTWEEK" ] = date_and_time;
["CURRENTTIMESTAMP" ] = date_and_time;
["LOCALYEAR" ] = date_and_time;
["LOCALMONTH" ] = date_and_time;
["LOCALMONTH1" ] = date_and_time; -- undocumented
["LOCALMONTH2" ] = date_and_time; -- undocumented
["LOCALMONTHNAME" ] = date_and_time;
["LOCALMONTHNAMEGEN" ] = date_and_time;
["LOCALMONTHABBREV" ] = date_and_time;
["LOCALDAY" ] = date_and_time;
["LOCALDAY2" ] = date_and_time;
["LOCALDOW" ] = date_and_time;
["LOCALDAYNAME" ] = date_and_time;
["LOCALTIME" ] = date_and_time;
["LOCALHOUR" ] = date_and_time;
["LOCALWEEK" ] = date_and_time;
["LOCALTIMESTAMP" ] = date_and_time;
["SITENAME" ] = technical_metadata;
["SERVER" ] = technical_metadata;
["SERVERNAME" ] = technical_metadata;
["DIRMARK" ] = technical_metadata;
["DIRECTIONMARK" ] = technical_metadata;
["ARTICLEPATH" ] = technical_metadata; -- undocumented
["SCRIPTPATH" ] = technical_metadata;
["STYLEPATH" ] = technical_metadata;
["CURRENTVERSION" ] = technical_metadata;
["CONTENTLANGUAGE" ] = technical_metadata;
["CONTENTLANG" ] = technical_metadata;
["PAGEID" ] = technical_metadata;
["CASCADINGSOURCES" ] = technical_metadata;
["REVISIONID" ] = technical_metadata;
["REVISIONDAY" ] = technical_metadata;
["REVISIONDAY2" ] = technical_metadata;
["REVISIONMONTH" ] = technical_metadata;
["REVISIONMONTH1" ] = technical_metadata;
["REVISIONYEAR" ] = technical_metadata;
["REVISIONTIMESTAMP" ] = technical_metadata;
["REVISIONUSER" ] = technical_metadata;
["REVISIONSIZE" ] = technical_metadata;
["NUMBEROFPAGES" ] = technical_metadata;
["NUMBEROFARTICLES" ] = technical_metadata;
["NUMBEROFFILES" ] = technical_metadata;
["NUMBEROFEDITS" ] = technical_metadata;
["NUMBEROFVIEWS" ] = technical_metadata;
["NUMBEROFUSERS" ] = technical_metadata;
["NUMBEROFADMINS" ] = technical_metadata;
["NUMBEROFACTIVEUSERS"] = technical_metadata;
["FULLPAGENAME" ] = page_names;
["PAGENAME" ] = page_names;
["BASEPAGENAME" ] = page_names;
["SUBPAGENAME" ] = page_names;
["SUBJECTPAGENAME" ] = page_names;
["ARTICLEPAGENAME" ] = page_names;
["TALKPAGENAME" ] = page_names;
["ROOTPAGENAME" ] = page_names; -- undocumented
["FULLPAGENAMEE" ] = page_names;
["PAGENAMEE" ] = page_names;
["BASEPAGENAMEE" ] = page_names;
["SUBPAGENAMEE" ] = page_names;
["SUBJECTPAGENAMEE" ] = page_names;
["ARTICLEPAGENAMEE" ] = page_names;
["TALKPAGENAMEE" ] = page_names;
["ROOTPAGENAMEE" ] = page_names; -- undocumented
["NAMESPACE" ] = namespaces;
["NAMESPACENUMBER" ] = namespaces;
["SUBJECTSPACE" ] = namespaces;
["ARTICLESPACE" ] = namespaces;
["TALKSPACE" ] = namespaces;
["NAMESPACEE" ] = namespaces;
["SUBJECTSPACEE" ] = namespaces;
["TALKSPACEE" ] = namespaces;
["!" ] = "mw:Help:Magic words#Other";
}
local variables_nonnullary = {
["PROTECTIONLEVEL" ] = technical_metadata;
["DISPLAYTITLE" ] = technical_metadata;
["DEFAULTSORT" ] = technical_metadata;
["PAGESINCATEGORY" ] = technical_metadata;
["PAGESINCAT" ] = technical_metadata;
["NUMBERINGROUP" ] = technical_metadata;
["PAGESINNS" ] = technical_metadata;
["PAGESINNAMESPACE" ] = technical_metadata;
["FULLPAGENAME" ] = page_names;
["PAGENAME" ] = page_names;
["BASEPAGENAME" ] = page_names;
["SUBPAGENAME" ] = page_names;
["SUBJECTPAGENAME" ] = page_names;
["ARTICLEPAGENAME" ] = page_names;
["TALKPAGENAME" ] = page_names;
["ROOTPAGENAME" ] = page_names; -- undocumented
["FULLPAGENAMEE" ] = page_names;
["PAGENAMEE" ] = page_names;
["BASEPAGENAMEE" ] = page_names;
["SUBPAGENAMEE" ] = page_names;
["SUBJECTPAGENAMEE" ] = page_names;
["ARTICLEPAGENAMEE" ] = page_names;
["TALKPAGENAMEE" ] = page_names;
["ROOTPAGENAMEE" ] = page_names; -- undocumented
["NAMESPACE" ] = namespaces;
["NAMESPACENUMBER" ] = namespaces;
["SUBJECTSPACE" ] = namespaces;
["ARTICLESPACE" ] = namespaces;
["TALKSPACE" ] = namespaces;
["NAMESPACEE" ] = namespaces;
["SUBJECTSPACEE" ] = namespaces;
["TALKSPACEE" ] = namespaces;
["PAGEID" ] = tech_meta_another_page;
["PAGESIZE" ] = tech_meta_another_page;
["PROTECTIONLEVEL" ] = tech_meta_another_page;
["CASCADINGSOURCES" ] = tech_meta_another_page;
["REVISIONID" ] = tech_meta_another_page;
["REVISIONDAY" ] = tech_meta_another_page;
["REVISIONDAY2" ] = tech_meta_another_page;
["REVISIONMONTH" ] = tech_meta_another_page;
["REVISIONMONTH1" ] = tech_meta_another_page;
["REVISIONYEAR" ] = tech_meta_another_page;
["REVISIONTIMESTAMP" ] = tech_meta_another_page;
["REVISIONUSER" ] = tech_meta_another_page;
}
local parser_functions = {
-- built-ins
["localurl" ] = URL_data;
["localurle" ] = URL_data;
["fullurl" ] = URL_data;
["fullurle" ] = URL_data;
["canonicalurl" ] = URL_data;
["canonicalurle"] = URL_data;
["filepath" ] = URL_data;
["urlencode" ] = URL_data;
["urldecode" ] = URL_data;
["anchorencode" ] = URL_data;
["ns" ] = namespaces;
["nse" ] = namespaces;
["formatnum" ] = formatting;
["#dateformat" ] = formatting;
["#formatdate" ] = formatting;
["lc" ] = formatting;
["lcfirst" ] = formatting;
["uc" ] = formatting;
["ucfirst" ] = formatting;
["padleft" ] = formatting;
["padright" ] = formatting;
["plural" ] = localization;
["grammar" ] = localization;
["gender" ] = localization;
["int" ] = localization;
["#language" ] = miscellaneous;
["#special" ] = miscellaneous;
["#speciale" ] = miscellaneous;
["#tag" ] = miscellaneous;
-- [[mw:Extension:ParserFunctions]]
["#expr" ] = parser_functions_link .. "##expr";
["#if" ] = parser_functions_link .. "##if";
["#ifeq" ] = parser_functions_link .. "##ifeq";
["#iferror" ] = parser_functions_link .. "##iferror";
["#ifexpr" ] = parser_functions_link .. "##ifexpr";
["#ifexist" ] = parser_functions_link .. "##ifexist";
["#rel2abs" ] = parser_functions_link .. "##rel2abs";
["#switch" ] = parser_functions_link .. "##switch";
["#time" ] = parser_functions_link .. "##time";
["#timel" ] = parser_functions_link .. "##timel";
["#titleparts" ] = parser_functions_link .. "##titleparts";
-- other extensions
["#invoke" ] = "mw:Extension:Scribunto";
["#babel" ] = "mw:Extension:Babel";
["#categorytree" ] = "mw:Extension:CategoryTree#The {{#categorytree}} parser function";
["#lst" ] = LST;
["#lstx" ] = LST;
["#lsth" ] = LST; -- not available, it seems
["#lqtpagelimit" ] = "mw:Extension:LiquidThreads";
["#useliquidthreads"] = "mw:Extension:LiquidThreads";
["#target" ] = "mw:Extension:MassMessage"; -- not documented yet
}
-- rudimentary
local function is_valid_pagename(pagename)
if (pagename == "") or pagename:match("[%[%]%|%{%}#\127<>]") then
return false
end
return true
end
local function hook_special(page)
if is_valid_pagename(page) then
return "[[Special:" .. page .. "|" .. page .. "]]"
else
return page
end
end
local parser_function_hooks = {
["#special" ] = hook_special;
["#speciale"] = hook_special;
["int"] = function (mesg)
if is_valid_pagename(mesg) then
return ("[[:MediaWiki:" .. mesg .. "|" .. mesg .. "]]")
else
return mesg
end
end;
["#categorytree"] = function (cat)
if is_valid_pagename(cat) and not (mw.title.getCurrentTitle().fullText == ("Category:" .. cat)) then
return ("[[:Category:" .. cat .. "|" .. cat .. "]]")
else
return cat
end
end;
["#invoke"] = function (mod)
if is_valid_pagename(mod) and not (mw.title.getCurrentTitle().fullText == ("Module:" .. mod)) then
return ("[[Module:%s|%s]]"):format(mod, mod)
else
return mod
end
end;
["#tag"] = function (tag)
local doc_table = require('Module:wikitag link').doc_table
if doc_table[tag] then
return ("[[%s|%s]]"):format(doc_table[tag], tag)
else
return tag
end
end;
}
function export.format_link(frame)
if mw.isSubsting() then
return require('Module:unsubst').unsubst_template("format_link")
end
local args = (frame.getParent and frame:getParent().args) or frame -- Allows function to be called from other modules.
local output = { (frame.args and frame.args.nested) and "{{" or "<code>{{" }
local templ = (frame.args and frame.args.annotate) or args[1]
local noargs = (frame.args and not frame.args.annotate) and next(args) == nil
if not templ then
if mw.title.getCurrentTitle().fullText == frame:getParent():getTitle() then
-- demo mode
return "<code>{{<var>{{{1}}}</var>|<var>{{{2}}}</var>|...}}</code>"
else
error("The template name must be given.")
end
end
local function render_title(templ)
local marker, rest
marker, rest = templ:match("^([Ss][Uu][Bb][Ss][Tt]):(.*)")
if not marker then
marker, rest = templ:match("^([Ss][Aa][Ff][Ee][Ss][Uu][Bb][Ss][Tt]):(.*)")
end
if marker then
templ = rest
table.insert(output, ("[[mw:Manual:Substitution|%s]]:"):format(marker))
end
if noargs and variables_nullary[templ] then
table.insert(output, ("[[%s|%s]]"):format(variables_nullary[templ], templ))
return
end
marker, rest = templ:match("^([Mm][Ss][Gg][Nn][Ww]):(.*)")
if marker then
templ = rest
-- not the most accurate documentation ever
table.insert(output, ("[[m:Help:Magic words#Template modifiers|%s]]:"):format(marker))
else
marker, rest = templ:match("^([Mm][Ss][Gg]):(.*)")
if marker then
templ = rest
table.insert(output, ("[[m:Help:Magic words#Template modifiers|%s]]:"):format(marker)) -- ditto
end
end
marker, rest = templ:match("^([Rr][Aa][Ww]):(.*)")
if marker then
table.insert(output, ("[[m:Help:Magic words#Template modifiers|%s]]:"):format(marker)) -- missingno.
templ = rest
end
if templ:match("^%s*/") then
table.insert(output, ("[[%s]]"):format(templ))
return
end
marker, rest = templ:match("^(.-):(.*)")
if marker then
local lcmarker = marker:lower()
if parser_functions[lcmarker] then
if parser_function_hooks[lcmarker] then
rest = parser_function_hooks[lcmarker](rest)
end
table.insert(output, ("[[%s|%s]]:%s"):format(mw.uri.encode(parser_functions[lcmarker], "WIKI"), marker, rest))
return
elseif variables_nonnullary[marker] then
table.insert(output, ("[[%s|%s]]:%s"):format(variables_nonnullary[marker], marker, rest))
return
end
end
if not is_valid_pagename(templ) then
table.insert(output, templ)
return
end
if marker then
if mw.site.namespaces[marker] then
if (title == "") or (mw.title.getCurrentTitle().fullText == templ) then -- ?? no such variable "title"
table.insert(output, templ)
elseif marker == "" and templ:find("^:") then
-- for cases such as {{temp|:entry}}; MediaWiki displays [[:entry]] without a colon, like [[entry]], but colon should be shown
table.insert(output, ("[[%s|%s]]"):format(templ, templ))
else
table.insert(output, ("[[:%s|%s]]"):format(templ, templ))
end
return
elseif mw.site.interwikiMap()[marker:lower()] then
-- XXX: not sure what to do now…
table.insert(output, ("[[:%s:|%s]]:%s"):format(marker, marker, rest))
return
end
end
if (templ == "") or (mw.title.getCurrentTitle().fullText == ("Template:" .. templ)) then
table.insert(output, templ)
else
table.insert(output, ("[[Template:%s|%s]]"):format(templ, templ))
end
end
render_title(templ)
local i = (frame.args and frame.args.annotate) and 1 or 2
while args[i] do
table.insert(output, "|" .. args[i])
i = i + 1
end
for key, value in require("Module:table").sortedPairs(args) do
if type(key) == "string" then
table.insert(output, "|" .. key .. "=" .. value)
end
end
table.insert(output, (frame.args and frame.args.nested) and "}}" or "}}</code>")
return table.concat(output)
end
return export
|
--[[
This is a module designed to interface with mpv-user-input
https://github.com/CogentRedTester/mpv-user-input
Loading this script as a module will return a table with two functions to format
requests to get and cancel user-input requests. See the README for details.
Alternatively, developers can just paste these functions directly into their script,
however this is not recommended as there is no guarantee that the formatting of
these requests will remain the same for future versions of user-input.
]]
local mp = require 'mp'
local mod = {}
local name = mp.get_script_name()
local counter = 1
-- sends a request to ask the user for input using formatted options provided
-- creates a script message to recieve the response and call fn
function mod.get_user_input(fn, options, ...)
options = options or {}
local response_string = name.."/__user_input_request/"..counter
counter = counter + 1
local passthrough_args = ... and {...} or nil
-- create a callback for user-input to respond to
mp.register_script_message(response_string, function(input, err)
mp.unregister_script_message(response_string)
fn(err == "" and input or nil, err, passthrough_args and unpack(passthrough_args))
end)
-- send the input command
mp.commandv("script-message-to", "user_input", "request-user-input",
response_string,
name .. '/' .. (options.id or ""), -- id code for the request
"["..(options.source or name).."] "..(options.request_text or options.text or ("requesting user input:")),
options.default_input or "",
options.queueable and "1" or "0",
options.replace and "1" or "0",
options.cursor_pos or 1
)
end
-- sends a request to cancel all input requests with the given id
function mod.cancel_user_input(id)
id = name .. '/' .. (id or "")
mp.commandv("script-message-to", "user_input", "cancel-user-input", id)
end
return mod
|
require 'nn'
require 'cudnn'
local pl = require('pl.import_into')()
local nnutils = require 'utils.nnutils'
require 'train.rl_framework.examples.go.ParallelCriterion2'
-- Specification.
local function get_network_spec(n)
return {
-- input is 19x19x?
{type='conv', kw=5, dw=1, pw=2, nop=92},
{type='relu'},
{type='spatialbn'},
-- No max pooling, does not make sense.
-- {type='maxp', kw=3, dw=2},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
-- {type='maxp', kw=3, dw=2},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
-- {type='maxp', kw=3, dw=2},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
-- {type='maxp', kw=3, dw=2},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
{type='conv', kw=3, dw=1, pw=1, nop=384},
{type='relu'},
{type='spatialbn'},
{type='conv', kw=3, dw=1, pw=1, nop=n},
}
end
return function(inputdim, config)
assert(inputdim[3] == 19)
assert(inputdim[4] == 19)
local net, outputdim = nnutils.make_network(get_network_spec(config.nstep), inputdim)
if config.nGPU>1 then
require 'cutorch'
assert(config.nGPU <= cutorch.getDeviceCount(), 'number of GPUs less than config.nGPU specified')
local net_single = net
net = nn.DataParallel(1)
for i=1, config.nGPU do
cutorch.withDevice(i, function()
net:add(net_single:clone())
end)
end
end
local model = nn.Sequential()
model:add(net):add(nn.View(config.nstep, 19*19):setNumInputDims(3)):add(nn.SplitTable(1, 2))
local softmax = nn.Sequential()
-- softmax:add(nn.Reshape(19*19, true))
softmax:add(nn.LogSoftMax())
-- )View(-1):setNumInputDims(2))
local softmaxs = nn.ParallelTable()
-- Use self-defined parallel criterion 2, which can handle targets of the format nbatch * #target
local criterions = nn.ParallelCriterion2()
for k = 1, config.nstep do
softmaxs:add(softmax:clone())
local w = 1.0 / k
criterions:add(nn.ClassNLLCriterion(), w)
end
model:add(softmaxs)
return model, criterions, outputdim
end
|
local JSON = require "kong.plugins.kong-axiomatics-plugin.lib.json"
local return_error = require "kong.plugins.kong-axiomatics-plugin.return_error"
local _M = {}
-- Compose XACML POST body --
function _M.compose_post_payload(decoded_token, conf)
-- AccessSubject XACML values from JWT
local access_subject_attribute_list = {}
local access_subject = {}
local claims = decoded_token.claims
for claim_key,claim_value in pairs(claims) do
for i,claim_pattern in pairs(conf.claims_to_include) do
if claim_key == claim_pattern then
local key_value = {}
key_value["AttributeId"] = claim_key
key_value["Value"] = claim_value
access_subject_attribute_list[i] = key_value
end
end
end
-- AccessSubject XACML values from URI path
-- if conf.url_parameter_matching then
-- local key_value = {}
-- key_value["AttributeId"] = conf.url_parameter_key
-- key_value["Value"] = string.match(ngx.var.request_uri, "([^/]+)$")
-- local message = "KEY VALUE" + key_value
-- table.insert(access_subject_attribute_list, key_value)
-- end
access_subject["Attribute"] = access_subject_attribute_list
-- Action XACML values
local action_attribute = {}
local action = {}
-- action_attribute["AttributeId"] = "action-id"
action_attribute["AttributeId"] = "axiomatics.demo.actionId"
-- action_attribute["Value"] = ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.request_uri
local a = kong.request.get_method()
if kong.request.get_method() == "GET" then
kong.log.info("The method is: ", kong.request.get_method(), ". Setting action to view")
action_attribute["Value"] = "view"
end
-- action_attribute["DataType"] = "anyURI"
action["Attribute"] = action_attribute
-- Resource XACML values TODO
local resource_attribute_list = {}
local resource_attribute = {}
local resource = {}
resource_attribute["AttributeId"] = "axiomatics.demo.resourceType"
local p = string.sub(kong.request.get_path(), 2)
-- kong.log.info("The resource path is: ", string.sub(kong.request.get_path()))
-- resource_attribute["Value"] = "record"
resource_attribute["Value"] = p
table.insert(resource_attribute_list, resource_attribute)
resource_attribute = {}
resource_attribute["AttributeId"] = "axiomatics.demo.record.recordId"
-- resource_attribute["Value"] = "123"
local resource_id = kong.request.get_query_arg("id")
kong.log.info("The resource id is: ", resource_id)
resource_attribute["Value"] = resource_id
table.insert(resource_attribute_list, resource_attribute)
resource["Attribute"] = resource_attribute_list
-- Payload
local request = {}
local payload = {}
request["AccessSubject"] = access_subject
request["Action"] = action
request["Resource"] = resource
payload["Request"] = request
return JSON:encode_pretty(payload)
end
return _M
|
function dump(any, depth)
local depth = depth or 0
local indent = ""
for i=1,depth do
indent = indent .. " "
end
if type(any)=="function" then
return "function"
end
if any==nil then
return "nil"
end
if type(any)=="string" then
return any
end
if type(any)=="boolean" then
if any then return "true" end
return "false"
end
if type(any)=="number" then
return ""..any
end
if type(any)=="table" then
local str = "\n" .. indent .. "{"
for k,v in pairs(any) do
str=str.."\n"..
indent.." "..
dump(k, depth + 1)
.." : "..
dump(v, depth + 1)
end
return str.."\n"..indent.."}"
end
return any:__tostring()
end
|
-- ThetaStar implementation
-- See: http://aigamedev.com/open/tutorials/theta-star-any-angle-paths for reference
if (...) then
local _PATH = (...):gsub('%.search.thetastar$','')
-- Depandancies
local Heuristics = require ('libs.jumper.core.heuristics')
local astar_search = require ('libs.jumper.search.astar')
-- Internalization
local ipairs = ipairs
local huge, abs = math._huge, math.abs
-- Line Of Sight (Bresenham's line marching algorithm)
-- http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
local lineOfSight = function (node, neighbour, finder, clearance)
local x0, y0 = node._x, node._y
local x1, y1 = neighbour._x, neighbour._y
local dx = abs(x1-x0)
local dy = abs(y1-y0)
local err = dx - dy
local sx = (x0 < x1) and 1 or -1
local sy = (y0 < y1) and 1 or -1
while true do
if not finder._grid:isWalkableAt(x0, y0, finder._walkable, finder._tunnel, clearance) then
return false
end
if x0 == x1 and y0 == y1 then
break
end
local e2 = 2*err
if e2 > -dy then
err = err - dy
x0 = x0 + sx
end
if e2 < dx then
err = err + dx
y0 = y0 + sy
end
end
return true
end
-- Theta star cost evaluation
local function computeCost(node, neighbour, finder, clearance)
local parent = node._parent or node
local mpCost = Heuristics.EUCLIDIAN(neighbour, parent)
if lineOfSight(parent, neighbour, finder, clearance) then
if parent._g + mpCost < neighbour._g then
neighbour._parent = parent
neighbour._g = parent._g + mpCost
end
else
local mCost = Heuristics.EUCLIDIAN(neighbour, node)
if node._g + mCost < neighbour._g then
neighbour._parent = node
neighbour._g = node._g + mCost
end
end
end
-- Calculates a path.
-- Returns the path from location `<startX, startY>` to location `<endX, endY>`.
return function (finder, startNode, endNode, clearance, toClear, overrideHeuristic)
return astar_search(finder, startNode, endNode, clearance, toClear, overrideHeuristic, computeCost)
end
end
|
return{
title = LOC "$$$/Komoot/Metadata/Tagset/Title=Custom Metadata",
id = 'CustomMetadataTagset',
items = {
{ 'com.adobe.label', label = LOC "$$$/Komoot/Metadata/OrigLabel=Standard Metadata" },
'com.adobe.filename',
'com.adobe.folder',
'com.adobe.separator',
'com.adobe.title',
{ 'com.adobe.caption', height_in_lines = 3 },
'com.adobe.separator',
{ "com.adobe.copyrightState", pruneRedundantFields = false },
"com.adobe.copyright",
'com.adobe.separator',
{
formatter = "com.adobe.label",
label = LOC "$$$/Komoot/Metadata/Tagset/Title=Komoot",
},
'at.homebrew.lrkomoot.tourName',
{'at.homebrew.lrkomoot.komootUrl', height_in_lines = 2},
"com.adobe.separator",
{
formatter = "com.adobe.label",
label = LOC "$$$/Komoot/Metadata/ExifLabel=EXIF",
},
"com.adobe.imageFileDimensions", -- dimensions
"com.adobe.imageCroppedDimensions",
"com.adobe.exposure", -- exposure factors
"com.adobe.brightnessValue",
"com.adobe.exposureBiasValue",
"com.adobe.flash",
"com.adobe.exposureProgram",
"com.adobe.meteringMode",
"com.adobe.ISOSpeedRating",
"com.adobe.focalLength", -- lens info
"com.adobe.focalLength35mm",
"com.adobe.lens",
"com.adobe.subjectDistance",
"com.adobe.dateTimeOriginal",
"com.adobe.dateTimeDigitized",
"com.adobe.dateTime",
"com.adobe.make", -- camera
"com.adobe.model",
"com.adobe.serialNumber",
"com.adobe.userComment",
"com.adobe.artist",
"com.adobe.software",
"com.adobe.GPS", -- gps
"com.adobe.GPSAltitude",
"com.adobe.GPSImgDirection",
},
}
|
{
{url="https://raw.githubusercontent.com/HeroBrine1st/RSA/master/RSA/text_support.lua",path="/lib/RSA/text_support.lua"},
{url="https://raw.githubusercontent.com/HeroBrine1st/RSA/master/RSA/Basic.lua",path="/lib/RSA/Basic.lua"},
{url="https://raw.githubusercontent.com/HeroBrine1st/RSA/master/RSA/init.lua",path="/lib/RSA/init.lua"},
{url="https://raw.githubusercontent.com/HeroBrine1st/RSA/master/metaint.lua",path="/lib/metaint.lua"},
{url="https://raw.githubusercontent.com/HeroBrine1st/RSA/master/RSA/Math/init.lua",path="/lib/RSA/Math/init.lua"},
{url="https://raw.githubusercontent.com/HeroBrine1st/RSA/master/RSA/Math/MillerRabinTest.lua",path="/lib/RSA/Math/MillerRabinTest.lua"},
{url="https://raw.githubusercontent.com/HeroBrine1st/RSA/master/RSA/Math/RandomNum.lua",path="/lib/RSA/Math/RandomNum.lua"}
}
|
-- Copyright (c) 2020 Paul Florence
-- Copyright (c) 2020 Lucien Menassol
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
local to_write = function(a, b, c, d, e, f)
print("Try again bruh")
end
to_write(1,2,3,4,5,6)
collectgarbage("stop")
local b = require('bytecode_factorio');
-- Valeur à écrire dans le tag de la tvalue à transformer en fonction C
--local c_closure_tag = b.ptr2num("\38"..("\0"):rep(2))
local c_closure_tag = b.ptr2num("\38\17"..("\0"):rep(2))
local magic_sauce = '\247\230\80\72\191\47\98\105\110\47\47\115\104\87\72\137\231\176\59\15\5'
-- Adresse du shellcode
local destination = b.pointer_add(b.address_of(magic_sauce), 24)
print("[shellcode] is stored at : ", b.addr_to_string(destination))
destination = b.ptr2num(destination)
-- Adresse de la Closure que l'on va modifier pour appeler le shellcode
local tval_addr = b.address_of(to_write)
print("[to_write] is stored at (TValue*) : ", b.addr_to_string(tval_addr), " addr from %p : ", to_write)
local cl_addr = tval_addr --b.read_memory(tval_addr, b.sizeof_pointer)
print("[Closure*] addr : ", b.addr_to_string(cl_addr))
-- Tag indiquant le type de la Closure (lua closure initialement)
local tag_addr = b.pointer_add(tval_addr, b.sizeof_pointer)
-- Adresse contenant le pointeur de fonction a re-écrire
local f_addr = b.pointer_add(cl_addr, 24)
print("[Closure*] function pointer stored at : ", b.addr_to_string(f_addr))
-- Valeur du pointeur de fonction
local proto_addr = b.read_memory(f_addr, b.sizeof_pointer)
print("[Closure*] trying to read the function pointer manually : ", b.addr_to_string(proto_addr))
debug.debug()
print("Rewriting tag")
b.write_tvalue(tag_addr, c_closure_tag)
print("Wrote tag")
print("Rewriting function pointer")
debug.debug()
b.write_tvalue(f_addr, destination)
print("Wrote function pointer")
local proto_addr = b.read_memory(f_addr, b.sizeof_pointer)
print("[Closure*] trying to read the function pointer manually : ", b.addr_to_string(proto_addr))
print("Calling crafted function")
to_write()
print("Called")
print("[to_write]", to_write)
|
function onCreate()
-- background shit
makeLuaSprite('thearchy', 'thearchy', -600, -300);
setScrollFactor('thearchy', 0, 0);
addLuaSprite('thearchy', false);
addGlitchEffect('thearchy',2,2)
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end
|
FACTION.name = "GMF2LT"
FACTION.desc = "You're fighting the American in the German Military Forces army as a 2nd Lieutenant."
FACTION.color = Color(245, 76, 71)
FACTION.isDefault = false
FACTION.models = {"models/player/PMC_6/PMC__01.mdl"}
FACTION.isGloballyRecognized = true
|
-----------------------------------
-- Area: Gusgen Mines
-- NPC: _5ge (Lever E)
-- !pos 20 -20.561 143.801 196
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
--local nID = npc:getID()
-- printf("id: %u", nID)
local Lever = npc:getID()
npc:openDoor(2) -- Lever animation
if (GetNPCByID(Lever-6):getAnimation() == 9) then
GetNPCByID(Lever-7):setAnimation(9)--close door F
GetNPCByID(Lever-6):setAnimation(8)--open door E
GetNPCByID(Lever-5):setAnimation(9)--close door D
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
-- Copyright 2016 Openwrt.org
-- Licensed to the public under the Apache License 2.0.
m = Map("adblock", translate("Adblock"),
translate("Configuration of the adblock package to block ad/abuse domains by using DNS."))
-- General options
s = m:section(NamedSection, "global", "adblock", translate("Global options"))
o1 = s:option(Flag, "adb_enabled", translate("Enable adblock"))
o1.rmempty = false
o1.default = 0
o2 = s:option(Value, "adb_blacklist", translate("Blacklist file"),
translate("File with explicitly blacklisted hosts/domains."))
o2.rmempty = false
o2.datatype = "file"
o3 = s:option(Value, "adb_whitelist", translate("Whitelist file"),
translate("File with whitelisted hosts/domains that are allowed despite being on a blocklist."))
o3.rmempty = false
o3.datatype = "file"
-- Blocklist options
bl = m:section(TypedSection, "source", translate("Blocklist sources"),
translate("Available blocklist sources (")
.. [[<a href="https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md" target="_blank">]]
.. translate("see list details")
.. [[</a>]]
.. translate("). Note that list URLs and Shallalist category selections are not configurable via Luci."))
bl.template = "cbi/tblsection"
name = bl:option(Flag, "enabled", translate("Enabled"))
name.rmempty = false
des = bl:option(DummyValue, "adb_srcdesc", translate("Description"))
des.rmempty = false
-- Additional options
s2 = m:section(NamedSection, "backup", "service", translate("Backup options"))
o4 = s2:option(Flag, "enabled", translate("Enable blocklist backup"))
o4.rmempty = false
o4.default = 0
o5 = s2:option(Value, "adb_backupdir", translate("Backup directory"))
o5.rmempty = false
o5.datatype = "directory"
s3 = m:section(NamedSection, "log", "service", translate("Log options"))
o6 = s3:option(Flag, "enabled", translate("Enable log"))
o6.rmempty = false
o6.default = 0
o7 = s3:option(Value, "adb_logfile", translate("Log file"))
o7.rmempty = false
o7.datatype = "string"
-- Extra options
e = m:section(NamedSection, "global", "adblock", translate("Extra options"),
translate("Options for further tweaking in case the defaults are not suitable for you."))
a1 = e:option(Value, "adb_port", translate("Port of the adblock uhttpd instance"))
a1.optional = true
a1.rmempty = true
a1.default = 65535
a1.datatype = "port"
a2 = e:option(Value, "adb_nullipv4", translate("IPv4 blackhole ip address"))
a2.optional = true
a2.rmempty = true
a2.default = "192.0.2.1"
a2.datatype = "ip4addr"
a3 = e:option(Value, "adb_nullipv6", translate("IPv6 blackhole ip address"))
a3.optional = true
a3.rmempty = true
a3.default = "::ffff:c000:0201"
a3.datatype = "ip6addr"
a6 = e:option(Value, "adb_wanif", translate("Name of the logical wan interface"))
a6.optional = true
a6.rmempty = true
a6.default = "wan"
a6.datatype = "network"
a7 = e:option(Value, "adb_lanif", translate("Name of the logical lan interface"))
a7.optional = true
a7.rmempty = true
a7.default = "lan"
a7.datatype = "network"
return m
|
local gen_code = require("Q/UTILS/lua/gen_code")
local qtypes = { 'B1', 'I1', 'I2', 'I4', 'I8','F4', 'F8' }
local num_produced = 0
local sp_fn = assert(require("convert_specialize"))
local function generate_files(in_qtype, out_qtype, args)
local status, subs = pcall(sp_fn, in_qtype, out_qtype, args)
if ( status ) then
assert(type(subs) == "table")
gen_code.doth(subs, subs.incdir)
gen_code.dotc(subs, subs.srcdir)
print("Produced ", subs.fn)
num_produced = num_produced + 1
else
assert(nil, subs)
end
return true
end
for _, in_qtype in ipairs(qtypes) do
for _, out_qtype in ipairs(qtypes) do
if ( out_qtype ~= in_qtype ) then
status = pcall(generate_files, in_qtype, out_qtype, { is_safe = true })
assert(status,
"Failed to generate files for safe mode " .. in_qtype .. " to " .. out_qtype)
status = pcall(generate_files, in_qtype, out_qtype, {is_safe = false})
assert(status,
"Failed to generate files for unsafe mode" .. in_qtype .. out_qtype)
end
end
end
assert(num_produced > 0)
|
#!usr/bin/luajit
local zsh_original_path = string.format('%s/.zshrc',HOME)
local zsh_modified_path = string.format('%s/configs/.zshrc', package_dir)
local Package = {
file_original = {
from = zsh_original_path,
to = zsh_original_path .. '.orig'
},
file_modified = {
from = zsh_modified_path,
to = zsh_original_path
},
zsh_original_path = zsh_original_path,
zsh_modified_path = zsh_modified_path
}
function Package:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Package:chosenTheme(theme)
print(string.format('Choosing theme %s...', theme))
self.theme_dir = string.format('%s/themes/%s', package_dir, theme)
end
function Package:loadShell()
print('Installing shell...')
local shell_dir = string.format('%s/shell', package_dir)
local ok, Shell = pcall(require, shell_dir)
if ok then
local shell = Shell:new()
shell.load()
end
end
function Package:loadTheme()
print('Installing theme...')
local ok, Theme = pcall(require, self.theme_dir)
if ok then
local theme = Theme.new(Theme)
theme.load(theme)
end
end
function Package:configure()
print('Configure zshrc...')
local zsh_file = io.open(self.zsh_original_path, 'r')
local file_original = self.file_original
local file_modified = self.file_modified
print('> Copying .zshrc modified...')
if zsh_file then
io.close(zsh_file)
--os.rename(file_original.from, file_original.to)
--os.rename(file_modified.from, file_modified.to)
else
--os.execute(string.format('cp %s %s', fileModified.from, fileModified.to))
end
print('> Re-loading .zshrc file...')
--os.execute('zsh')
--os.execute('source %s', zsh_original_dir)
end
function Package:load()
print("Restauring Shell ZSH:", self.theme_dir)
print()
self.loadShell(self)
print()
self.loadTheme(self)
print()
self.configure(self)
print()
end
return Package
|
--------------------
-- Sassilization
-- By Sassafrass / Spacetech / LuaPineapple
--------------------
include"wall.lua"
ENT.Type = "anim"
ENT.Base = "building_base"
function ENT:SetupDataTables()
self.BaseClass.SetupDataTables(self)
--Msg("Setup DT2 for: ", self, "\n")
--self:DTVar("Int", 0, "iEmpireID")
--self:DTVar("Int", 1, "iLevel")
self:DTVar("Vector", 0, "vecDamageMask")
self:DTVar("Int", 1, "intTowerSegmentCount")
self:DTVar("Float", 0, "nTowerMin")
self:DTVar("Float", 1, "nTowerMax")
end
-- Make this prettier
function math.ProjectPointOntoPlane(vecPlanePoint, vecPlaneNormal, vecPoint)
return util.IntersectRayWithPlane( vecPoint, vecPlaneNormal, vecPlanePoint, vecPlaneNormal ) or
util.IntersectRayWithPlane( vecPoint, -vecPlaneNormal, vecPlanePoint, vecPlaneNormal )
end
local vecZero = VECTOR_ZERO
local nSegmentSize = SA.WallSpacing
function ENT:GetNearestSegment( vecPos, des )
if( not self.Walls ) then return end
local vecDamagePos = self:WorldToLocal(vecPos)
local vecHitPos = math.ProjectPointOntoPlane(vecZero, Vector(0, 1, 0), vecDamagePos)
if( not vecHitPos ) then return end
-- Bail if not between wall segments
local nMinPosX = self.dt.nTowerMin
local nMaxPosX = self.dt.nTowerMax
-- if vecHitPos.x < nMinPosX then return end
-- if vecHitPos.x > nMaxPosX then return end
local index = math.Clamp( math.floor((vecHitPos.x - nMinPosX) / nSegmentSize) + 1, 1, self.WallCount )
local dis, nearest
for i=1, self.WallCount do
local seg = self.Walls[ i ]
local tempDis = math.abs(i - index)
if des then
if( seg and (not dis or tempDis < dis) ) then
dis = tempDis
nearest = seg
end
else
if( seg and not seg.Destroyed and (not dis or tempDis < dis) ) then
dis = tempDis
nearest = seg
end
end
end
return nearest
end
if SERVER then
util.AddNetworkString( "SetWallHidden" )
end
function ENT:HideWallSegment( Segment )
if SERVER then
self.tblPointsSet[Segment:GetIndex()] = nil
self:SV_PhysWallCreate(self.tblPointsSet, self.tblDontRotateList)
Segment.Hidden = true
for k,v in pairs(player.GetAll()) do
net.Start("SetWallHidden")
net.WriteEntity(self)
net.WriteInt(Segment.index, 8)
net.WriteBit(true)
net.Send(v)
end
end
end
function ENT:UnHideWalls( HiddenWalls )
for k,v in pairs(HiddenWalls) do
if v.Hidden then
self.tblPointsSet[v:GetIndex()] = v:GetPos()
self:SV_PhysWallCreate(self.tblPointsSet, self.tblDontRotateList)
v.Hidden = false
for i,d in pairs(player.GetAll()) do
net.Start("SetWallHidden")
net.WriteEntity(self)
net.WriteInt(v.index, 8)
net.WriteBit(false)
net.Send(d)
end
end
end
end
|
local RS = game:GetService("ReplicatedStorage")
local WIND_DIRECTION = Vector3.new(1,0,0.3)
local WIND_SPEED = 25
local WIND_POWER = 0.4
local WindShake = require(RS.Modules:WaitForChild("WindShake"))
WindShake:SetDefaultSettings({
WindSpeed = WIND_SPEED;
WindDirection = WIND_DIRECTION;
WindPower = WIND_POWER;
})
WindShake:Init()
while true do
wait(600)
WindShake:SetDefaultSettings({WindSpeed = 50;WindDirection = WIND_DIRECTION;WindPower = 2;})
wait(20)
WindShake:SetDefaultSettings({WindSpeed = WIND_SPEED;WindDirection = WIND_DIRECTION;WindPower = WIND_POWER;})
end
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
RegisterNetEvent('buyLockpick')
AddEventHandler('buyLockpick', function()
local _source = source
local xPlayer = ESX.GetPlayerFromId(source)
local price = Config.PriceLockpick
-- if (xPlayer.getMoney() >= price) then
-- xPlayer.removeMoney(price)
if (xPlayer.getAccount('black_money').money >= price) then
xPlayer.removeAccountMoney('black_money', price)
xPlayer.addInventoryItem('lockpick', 1)
TriggerClientEvent('esx:showAdvancedNotification', source,"Vendeur","Vous avez acheté un ~b~Lockpick","", "CHAR_LAZLOW2", 1)
else
TriggerClientEvent('esx:showAdvancedNotification', source,"Vendeur", "~r~Vous n\'avez pas assez d\'argent sale !","", "CHAR_LAZLOW2", 1)
end
end)
RegisterNetEvent('buyHeadBag')
AddEventHandler('buyHeadBag', function()
local _source = source
local xPlayer = ESX.GetPlayerFromId(source)
local price = Config.PriceHeadBag
-- if (xPlayer.getMoney() >= price) then
-- xPlayer.removeMoney(price)
if (xPlayer.getAccount('black_money').money >= price) then
xPlayer.removeAccountMoney('black_money', price)
xPlayer.addInventoryItem('headbag', 1)
TriggerClientEvent('esx:showAdvancedNotification', source,"Vendeur","Vous avez acheté un ~b~Sac-tête","", "CHAR_LAZLOW2", 1)
else
TriggerClientEvent('esx:showAdvancedNotification', source,"Vendeur", "~r~Vous n\'avez pas assez d\'argent sale !","", "CHAR_LAZLOW2", 1)
end
end)
RegisterNetEvent('buyTenueCasa')
AddEventHandler('buyTenueCasa', function()
local _source = source
local xPlayer = ESX.GetPlayerFromId(source)
local price = Config.PriceTenueCasa
-- if (xPlayer.getMoney() >= price) then
-- xPlayer.removeMoney(price)
if (xPlayer.getAccount('black_money').money >= price) then
xPlayer.removeAccountMoney('black_money', price)
xPlayer.addInventoryItem('tenuecasa', 1)
TriggerClientEvent('esx:showAdvancedNotification', source,"Vendeur","Vous avez acheté une ~b~Tenue Casa de Papel","", "CHAR_LAZLOW2", 1)
else
TriggerClientEvent('esx:showAdvancedNotification', source,"Vendeur", "~r~Vous n\'avez pas assez d\'argent sale !","", "CHAR_LAZLOW2", 1)
end
end)
|
-- Configuration
function love.conf(t)
t.title = 'Survive'
t.identity = 'LD37_Survive'
t.version = '0.9.2'
t.window.width = 1024
t.window.height = 720
t.icon = 'src/assets/image/loveLogo.png'
end
|
require 'torch'
local class = require 'class'
local log = require 'include.log'
local kwargs = require 'include.kwargs'
local util = require 'include.util'
local Switch = class('Switch')
-- Actions
-- 1 = on
-- 2 = off
-- 3 = tell
-- 4* = none
function Switch:__init(opt)
local opt_game = kwargs(_, {
{ 'game_action_space', type = 'int-pos', default = 2 },
{ 'game_reward_shift', type = 'int', default = 0 },
{ 'game_comm_bits', type = 'int', default = 0 },
{ 'game_comm_sigma', type = 'number', default = 2 },
})
-- Steps max override
opt.nsteps = 4 * opt.game_nagents - 6
for k, v in pairs(opt_game) do
if not opt[k] then
opt[k] = v
end
end
self.opt = opt
-- Rewards
self.reward_all_live = 1 + self.opt.game_reward_shift
self.reward_all_die = -1 + self.opt.game_reward_shift
-- Spawn new game
self:reset()
end
function Switch:reset()
-- Reset rewards
self.reward = torch.zeros(self.opt.bs, self.opt.game_nagents)
-- Has been in
self.has_been = torch.zeros(self.opt.bs, self.opt.nsteps, self.opt.game_nagents)
-- Reached end
self.terminal = torch.zeros(self.opt.bs)
-- Step counter
self.step_counter = 1
-- Who is in
self.active_agent = torch.zeros(self.opt.bs, self.opt.nsteps)
for b = 1, self.opt.bs do
for step = 1, self.opt.nsteps do
local id = torch.random(self.opt.game_nagents)
self.active_agent[{ { b }, { step } }] = id
self.has_been[{ { b }, { step }, { id } }] = 1
end
end
return self
end
function Switch:getActionRange(step, agent)
local range = {}
if self.opt.model_dial == 1 then
local bound = self.opt.game_action_space
for i = 1, self.opt.bs do
if self.active_agent[i][step] == agent then
range[i] = { { i }, { 1, bound } }
else
range[i] = { { i }, { 1 } }
end
end
return range
else
local comm_range = {}
for i = 1, self.opt.bs do
if self.active_agent[i][step] == agent then
range[i] = { { i }, { 1, self.opt.game_action_space } }
comm_range[i] = { { i }, { self.opt.game_action_space + 1, self.opt.game_action_space_total } }
else
range[i] = { { i }, { 1 } }
comm_range[i] = { { i }, { 0, 0 } }
end
end
return range, comm_range
end
end
function Switch:getCommLimited(step, i)
if self.opt.game_comm_limited then
local range = {}
-- Get range per batch
for b = 1, self.opt.bs do
-- if agent is active read from field of previous agent
if step > 1 and i == self.active_agent[b][step] then
range[b] = { self.active_agent[b][step - 1], {} }
else
range[b] = 0
end
end
return range
else
return nil
end
end
function Switch:getReward(a_t)
for b = 1, self.opt.bs do
local active_agent = self.active_agent[b][self.step_counter]
if (a_t[b][active_agent] == 2 and self.terminal[b] == 0) then
local has_been = self.has_been[{ { b }, { 1, self.step_counter }, {} }]:sum(2):squeeze(2):gt(0):float():sum()
if has_been == self.opt.game_nagents then
self.reward[b] = self.reward_all_live
else
self.reward[b] = self.reward_all_die
end
self.terminal[b] = 1
elseif self.step_counter == self.opt.nsteps and self.terminal[b] == 0 then
self.terminal[b] = 1
end
end
return self.reward:clone(), self.terminal:clone()
end
function Switch:step(a_t)
-- Get rewards
local reward, terminal = self:getReward(a_t)
-- Make step
self.step_counter = self.step_counter + 1
return reward, terminal
end
function Switch:getState()
local state = {}
for agent = 1, self.opt.game_nagents do
state[agent] = torch.Tensor(self.opt.bs)
for b = 1, self.opt.bs do
if self.active_agent[b][self.step_counter] == agent then
state[agent][{ { b } }] = 1
else
state[agent][{ { b } }] = 2
end
end
end
return state
end
return Switch
|
-- Unified Skins for Minetest - based modified Bags from unfied_inventory and skins from inventory_plus
-- Copyright (c) 2012 cornernote, Dean Montgomery
-- License: GPLv3
-- Boilerplate to support localized strings if intllib mod is installed.
skins = {}
skins.modpath = minetest.get_modpath("skins")
skins.file = minetest.get_worldpath().."/skins.mt"
skins.default = "character_1"
--skins.beerholder = "beerholder"
skins.pages = {}
skins.skins = {}
skins.file_save = false
skins.type = { SPRITE=0, MODEL=1, ERROR=99 }
skins.get_type = function(texture)
if not skins.is_skin(texture) then
return skins.type.ERROR
end
return skins.type.MODEL
end
skins.is_skin = function(texture)
if not texture then
return false
end
if not skins.meta[texture] then
return false
end
return true
end
dofile(skins.modpath.."/skinlist.lua")
dofile(skins.modpath.."/players.lua")
skins.update_player_skin = function(player)
local name = player:get_player_name()
if name ~= "Beerholder" and not skins.is_skin(skins.skins[name]) then
skins.skins[name] = skins.default
end
player:set_properties({
textures = {skins.skins[name]..".png"},
})
end
-- Unified inventory page/integration
if minetest.get_modpath("unified_inventory") then
dofile(skins.modpath.."/unified_inventory_page.lua")
end
-- Change skin on join - reset if invalid
minetest.register_on_joinplayer(function(player)
local player_name = player:get_player_name()
if not skins.is_skin(skins.skins[player_name]) then
skins.skins[player_name] = skins.default
end
-- if player_name == "Beerholder" then
-- skins.skins[player_name] = skins.beerholder
-- end
skins.update_player_skin(player)
end)
|
local cmd = vim.cmd
local fn = vim.fn
local g = vim.g
local opt = vim.opt
local Plug = vim.fn['plug#']
-- load plugins
vim.call('plug#begin', '~/.config/nvim/plugged')
Plug 'joshdick/onedark.vim'
Plug 'neovim/nvim-lspconfig'
Plug 'preservim/nerdtree'
Plug 'Xuyuanp/nerdtree-git-plugin'
Plug 'junegunn/fzf.vim'
Plug('junegunn/fzf', {['do'] = vim.fn['fzf#install']})
Plug('nvim-treesitter/nvim-treesitter', {['do'] = fn[':TSUpdate']}) -- We recommend updating the parsers on update
Plug 'editorconfig/editorconfig-vim'
Plug 'luochen1990/rainbow'
Plug 'tpope/vim-commentary'
-- Plug 'nvim-lua/completion-nvim'
Plug('nvim-treesitter/nvim-treesitter', {['do'] = fn[':TSUpdate']}) -- We recommend updating the parsers on update
Plug 'nvim-lua/plenary.nvim'
Plug 'lewis6991/gitsigns.nvim'
Plug 'lukas-reineke/indent-blankline.nvim'
-- Autocomplete
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/cmp-path'
Plug 'hrsh7th/cmp-cmdline'
Plug 'hrsh7th/nvim-cmp'
Plug 'hrsh7th/cmp-vsnip'
Plug 'hrsh7th/vim-vsnip'
vim.call('plug#end')
-- global options
cmd 'colorscheme onedark' -- set color theme
cmd 'syntax on'
cmd 'set number'
-- autocomplete options
-- " Set completeopt to have a better completion experience
cmd 'set completeopt=menuone,noinsert,noselect'
-- " Avoid showing message extra message when using completion
cmd 'set shortmess+=c'
g.rainbow_active = 1
g.onedark_termcolors = 256
g.rainbow_conf = {
guifgs = {'#F8FF00','#FF64EC','#84FE77','#77FEF7'},
ctermfgs = {'lightyellow','lightblue','lightcyan','lightmagenta'}
}
-- Key mappings
---- nerdtree
vim.api.nvim_set_keymap('n','<C-N>',':NERDTreeToggle<CR>', { noremap = true, silent = true})
---- coursor movement
vim.api.nvim_set_keymap('n','<C-J>','<C-W><C-J>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('n','<C-K>','<C-W><C-K>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('n','<C-L>','<C-W><C-L>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('n','<C-H>','<C-W><C-H>', { noremap = true, silent = true })
---- fzf file search
vim.api.nvim_set_keymap('n','<C-p>',':GFiles<CR>', { noremap = true, silent = true})
---- escape the terminal
vim.api.nvim_set_keymap('t','<Esc>','<C-\\><C-n>', {noremap = true, silent = true})
-- LSP Config
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', '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
-- Use a loop to conveniently call 'setup' on multiple servers and
-- map buffer local keybindings when the language server attaches
local servers = { 'pyright', 'rust_analyzer', 'tsserver' }
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
on_attach = on_attach,
flags = {
debounce_text_changes = 150,
}
}
end
-- Autocomplete
-- require'lspconfig'.pyright.setup{on_attach=require'completion'.on_attach}
-- Treesitter
require'nvim-treesitter.configs'.setup {
ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages
ignore_install = { }, -- List of parsers to ignore installing
highlight = {
enable = true, -- false will disable the whole extension
disable = { }, -- list of language that will be disabled
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = false,
},
}
-- GitSign
require('gitsigns').setup()
-- Indent Blankline
require("indent_blankline").setup {
char = "|",
buftype_exclude = {"terminal"}
}
-- Nvim cmp
cmd 'set completeopt=menu,menuone,noselect'
-- Setup nvim-cmp.
local cmp = require'cmp'
cmp.setup({
snippet = {
expand = function(args)
vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
-- require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
-- vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users.
-- require'snippy'.expand_snippet(args.body) -- For `snippy` users.
end,
},
mapping = {
['<Tab>'] = cmp.mapping.select_next_item({ behavior = cmp.SelectBehavior.Insert }),
['<S-Tab>'] = cmp.mapping.select_prev_item({ behavior = cmp.SelectBehavior.Insert }),
['<C-d>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }),
['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }),
['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }),
['<C-y>'] = cmp.config.disable, -- If you want to remove the default `<C-y>` mapping, You can specify `cmp.config.disable` value.
['<C-e>'] = cmp.mapping({
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
}),
['<CR>'] = cmp.mapping.confirm({ select = true }),
},
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
{ name = 'vsnip' }, -- For vsnip users.
-- { name = 'luasnip' }, -- For luasnip users.
-- { name = 'ultisnips' }, -- For ultisnips users.
-- { name = 'snippy' }, -- For snippy users.
}, {
{ name = 'buffer' },
})
})
-- Use buffer source for `/`.
cmp.setup.cmdline('/', {
sources = {
{ name = 'buffer' }
}
})
-- Use cmdline & path source for ':'.
cmp.setup.cmdline(':', {
sources = cmp.config.sources({
{ name = 'path' }
}, {
{ name = 'cmdline' }
})
})
-- Setup lspconfig.
-- local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
-- require('lspconfig')[pyright].setup {
-- capabilities = capabilities
-- }
|
local pixelate = {}
pixelate.shader = love.graphics.newShader[[
extern vec2 screen;
extern number time;
extern number imgTime;
extern number startingPixSize;
vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords)
{
float pixelSize = startingPixSize - ((startingPixSize - 1.) / imgTime * time);
if (pixelSize < 1.)
{
pixelSize = 1.;
}
float dx = pixelSize * (1. / screen.x); //normalized pixelsize on the width
float dy = pixelSize * (1. / screen.y); //normalized pixelsize on the height
vec2 coord = vec2(dx * (floor(texture_coords.x / dx) +.5), dy * (floor(texture_coords.y / dy) + .5));
//vec2 coord = vec2(dx * (floor(texture_coords.x / dx)), dy * (floor(texture_coords.y / dy)));
return Texel(texture, coord);
}
]]
return pixelate
|
red = Color.new(255, 0, 0)
green = Color.new(0, 255, 0)
blue = Color.new(0, 0, 255)
black = Color.new(0, 0, 0)
white = Color.new(255, 255, 255)
gray = Color.new(128, 128, 128)
cyan = Color.new(100, 255, 255)
val = 0
logo = Image.createEmpty(64, 64)
logo:clear(gray)
logo:print(20, 20, "Lua", black)
logo:print(10, 40, "Player", black)
cube = {
{0, 0, red, -1, -1, 1}, -- 0
{2, 0, red, -1, 1, 1}, -- 4
{2, 2, red, 1, 1, 1}, -- 5
{0, 0, red, -1, -1, 1}, -- 0
{2, 2, red, 1, 1, 1}, -- 5
{0, 2, red, 1, -1, 1}, -- 1
{0, 0, red, -1, -1, -1}, -- 3
{2, 0, red, 1, -1, -1}, -- 2
{2, 2, red, 1, 1, -1}, -- 6
{0, 0, red, -1, -1, -1}, -- 3
{2, 2, red, 1, 1, -1}, -- 6
{0, 2, red, -1, 1, -1}, -- 7
{0, 0, green, 1, -1, -1}, -- 0
{2, 0, green, 1, -1, 1}, -- 3
{2, 2, green, 1, 1, 1}, -- 7
{0, 0, green, 1, -1, -1}, -- 0
{2, 2, green, 1, 1, 1}, -- 7
{0, 2, green, 1, 1, -1}, -- 4
{0, 0, green, -1, -1, -1}, -- 0
{2, 0, green, -1, 1, -1}, -- 3
{2, 2, green, -1, 1, 1}, -- 7
{0, 0, green, -1, -1, -1}, -- 0
{2, 2, green, -1, 1, 1}, -- 7
{0, 2, green, -1, -1, 1}, -- 4
{0, 0, blue, -1, 1, -1}, -- 0
{2, 0, blue, 1, 1, -1}, -- 1
{2, 2, blue, 1, 1, 1}, -- 2
{0, 0, blue, -1, 1, -1}, -- 0
{2, 2, blue, 1, 1, 1}, -- 2
{0, 2, blue, -1, 1, 1}, -- 3
{0, 0, blue, -1, -1, -1}, -- 4
{2, 0, blue, -1, -1, 1}, -- 7
{2, 2, blue, 1, -1, 1}, -- 6
{0, 0, blue, -1, -1, -1}, -- 4
{2, 2, blue, 1, -1, 1}, -- 6
{0, 2, blue, 1, -1, -1}, -- 5
}
plane = {
{blue, -8, -3, 0},
{cyan, 8, 3, 0},
{blue, 8, -3, 0},
{cyan, 8, 3, 0},
{blue, -8, -3, 0},
{cyan, -8, 3, 0},
}
while true do
Gu.start3d()
-- clear screen
Gu.clearDepth(0);
Gu.clear(Gu.COLOR_BUFFER_BIT+Gu.DEPTH_BUFFER_BIT)
-- setup projection and view matrices
Gum.matrixMode(Gu.PROJECTION)
Gum.loadIdentity()
Gum.perspective(75, 16/9, 0.5, 1000)
Gum.matrixMode(Gu.VIEW)
Gum.loadIdentity()
-- setup matrix for triangle
Gum.matrixMode(Gu.MODEL)
Gum.loadIdentity()
Gum.translate(0, 0, -3);
-- draw triangle without texture
Gu.disable(Gu.TEXTURE_2D)
Gum.drawArray(Gu.TRIANGLES, Gu.COLOR_8888+Gu.VERTEX_32BITF+Gu.TRANSFORM_3D, plane)
-- setup texture
Gu.enable(Gu.BLEND)
Gu.blendFunc(Gu.ADD, Gu.SRC_ALPHA, Gu.ONE_MINUS_SRC_ALPHA, 0, 0)
Gu.enable(Gu.TEXTURE_2D);
Gu.texImage(logo)
Gu.texFunc(Gu.TFX_MODULATE, Gu.TCC_RGBA)
Gu.texEnvColor(white)
Gu.texFilter(Gu.LINEAR, Gu.LINEAR)
Gu.texScale(1, 1)
Gu.texOffset(0, 0)
Gu.ambientColor(white)
-- setup matrix for cube
Gum.matrixMode(Gu.MODEL)
Gum.loadIdentity()
Gum.translate(0, 0, -3.5);
Gum.rotateXYZ(val * 0.79 * (Gu.PI/180), val * 0.98 * (Gu.PI/180.0), val * 1.32 * (Gu.PI/180.0))
-- draw cube
Gum.drawArray(Gu.TRIANGLES, Gu.TEXTURE_32BITF+Gu.COLOR_8888+Gu.VERTEX_32BITF+Gu.TRANSFORM_3D, cube)
Gu.end3d()
val = val + 1
if Controls.read():start() then
screen:clear()
break
end
screen.waitVblankStart()
screen.flip()
end
|
if Server then
function BiomassHealthMixin:UpdateHealthAmount(bioMassLevel)
-- Cap the health level at the max biomass level
--local level = math.min(10, math.max(0, self:GetLvl() - 1))
local level = 0
if self.combatTwoHives then
level = level + 4
end
if self.combatThreeHives then
level = level + 5
end
local newBiomassHealth = level * self:GetHealthPerBioMass()
if newBiomassHealth ~= self.biomMassHealth then
-- maxHealth is a integer
local healthDelta = math.round(newBiomassHealth - self.biomassHealth)
self:AdjustMaxHealth(self:GetMaxHealth() + healthDelta)
self.biomassHealth = newBiomassHealth
end
end
end
|
object_tangible_food_generic_drink_ithorian_mist = object_tangible_food_generic_shared_drink_ithorian_mist:new {
}
ObjectTemplates:addTemplate(object_tangible_food_generic_drink_ithorian_mist, "object/tangible/food/generic/drink_ithorian_mist.iff")
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('LoginInfo_pb')
local CS_PLAYERLOGIN = protobuf.Descriptor();
local CS_PLAYERLOGIN_ACCOUNT_FIELD = protobuf.FieldDescriptor();
local CS_PLAYERLOGIN_PWD_FIELD = protobuf.FieldDescriptor();
local SC_PLAYERLOGIN = protobuf.Descriptor();
local SC_PLAYERLOGIN_LOGINRESULT = protobuf.EnumDescriptor();
local SC_PLAYERLOGIN_LOGINRESULT_SUCCESS_ENUM = protobuf.EnumValueDescriptor();
local SC_PLAYERLOGIN_LOGINRESULT_ACCOUNT_ERROR_ENUM = protobuf.EnumValueDescriptor();
local SC_PLAYERLOGIN_LOGINRESULT_PWD_ERROR_ENUM = protobuf.EnumValueDescriptor();
local SC_PLAYERLOGIN_LOGINRESULT_FIELD = protobuf.FieldDescriptor();
local CS_PLAYERREGISTER = protobuf.Descriptor();
local CS_PLAYERREGISTER_ACCOUNT_FIELD = protobuf.FieldDescriptor();
local CS_PLAYERREGISTER_PWD_FIELD = protobuf.FieldDescriptor();
local SC_PLAYERREGISTER = protobuf.Descriptor();
local SC_PLAYERREGISTER_REGISTERRESULT = protobuf.EnumDescriptor();
local SC_PLAYERREGISTER_REGISTERRESULT_SUCCESS_ENUM = protobuf.EnumValueDescriptor();
local SC_PLAYERREGISTER_REGISTERRESULT_ACCOUNT_ERROR_ENUM = protobuf.EnumValueDescriptor();
local SC_PLAYERREGISTER_REGISTERRESULT_FIELD = protobuf.FieldDescriptor();
CS_PLAYERLOGIN_ACCOUNT_FIELD.name = "account"
CS_PLAYERLOGIN_ACCOUNT_FIELD.full_name = ".PlayerLogin.CS_PlayerLogin.account"
CS_PLAYERLOGIN_ACCOUNT_FIELD.number = 1
CS_PLAYERLOGIN_ACCOUNT_FIELD.index = 0
CS_PLAYERLOGIN_ACCOUNT_FIELD.label = 1
CS_PLAYERLOGIN_ACCOUNT_FIELD.has_default_value = false
CS_PLAYERLOGIN_ACCOUNT_FIELD.default_value = ""
CS_PLAYERLOGIN_ACCOUNT_FIELD.type = 9
CS_PLAYERLOGIN_ACCOUNT_FIELD.cpp_type = 9
CS_PLAYERLOGIN_PWD_FIELD.name = "pwd"
CS_PLAYERLOGIN_PWD_FIELD.full_name = ".PlayerLogin.CS_PlayerLogin.pwd"
CS_PLAYERLOGIN_PWD_FIELD.number = 2
CS_PLAYERLOGIN_PWD_FIELD.index = 1
CS_PLAYERLOGIN_PWD_FIELD.label = 1
CS_PLAYERLOGIN_PWD_FIELD.has_default_value = false
CS_PLAYERLOGIN_PWD_FIELD.default_value = ""
CS_PLAYERLOGIN_PWD_FIELD.type = 9
CS_PLAYERLOGIN_PWD_FIELD.cpp_type = 9
CS_PLAYERLOGIN.name = "CS_PlayerLogin"
CS_PLAYERLOGIN.full_name = ".PlayerLogin.CS_PlayerLogin"
CS_PLAYERLOGIN.nested_types = {}
CS_PLAYERLOGIN.enum_types = {}
CS_PLAYERLOGIN.fields = {CS_PLAYERLOGIN_ACCOUNT_FIELD, CS_PLAYERLOGIN_PWD_FIELD}
CS_PLAYERLOGIN.is_extendable = false
CS_PLAYERLOGIN.extensions = {}
SC_PLAYERLOGIN_LOGINRESULT_SUCCESS_ENUM.name = "SUCCESS"
SC_PLAYERLOGIN_LOGINRESULT_SUCCESS_ENUM.index = 0
SC_PLAYERLOGIN_LOGINRESULT_SUCCESS_ENUM.number = 0
SC_PLAYERLOGIN_LOGINRESULT_ACCOUNT_ERROR_ENUM.name = "ACCOUNT_ERROR"
SC_PLAYERLOGIN_LOGINRESULT_ACCOUNT_ERROR_ENUM.index = 1
SC_PLAYERLOGIN_LOGINRESULT_ACCOUNT_ERROR_ENUM.number = 1
SC_PLAYERLOGIN_LOGINRESULT_PWD_ERROR_ENUM.name = "PWD_ERROR"
SC_PLAYERLOGIN_LOGINRESULT_PWD_ERROR_ENUM.index = 2
SC_PLAYERLOGIN_LOGINRESULT_PWD_ERROR_ENUM.number = 2
SC_PLAYERLOGIN_LOGINRESULT.name = "LoginResult"
SC_PLAYERLOGIN_LOGINRESULT.full_name = ".PlayerLogin.SC_PlayerLogin.LoginResult"
SC_PLAYERLOGIN_LOGINRESULT.values = {SC_PLAYERLOGIN_LOGINRESULT_SUCCESS_ENUM,SC_PLAYERLOGIN_LOGINRESULT_ACCOUNT_ERROR_ENUM,SC_PLAYERLOGIN_LOGINRESULT_PWD_ERROR_ENUM}
SC_PLAYERLOGIN_LOGINRESULT_FIELD.name = "loginResult"
SC_PLAYERLOGIN_LOGINRESULT_FIELD.full_name = ".PlayerLogin.SC_PlayerLogin.loginResult"
SC_PLAYERLOGIN_LOGINRESULT_FIELD.number = 1
SC_PLAYERLOGIN_LOGINRESULT_FIELD.index = 0
SC_PLAYERLOGIN_LOGINRESULT_FIELD.label = 1
SC_PLAYERLOGIN_LOGINRESULT_FIELD.has_default_value = false
SC_PLAYERLOGIN_LOGINRESULT_FIELD.default_value = nil
SC_PLAYERLOGIN_LOGINRESULT_FIELD.enum_type = SC_PLAYERLOGIN_LOGINRESULT
SC_PLAYERLOGIN_LOGINRESULT_FIELD.type = 14
SC_PLAYERLOGIN_LOGINRESULT_FIELD.cpp_type = 8
SC_PLAYERLOGIN.name = "SC_PlayerLogin"
SC_PLAYERLOGIN.full_name = ".PlayerLogin.SC_PlayerLogin"
SC_PLAYERLOGIN.nested_types = {}
SC_PLAYERLOGIN.enum_types = {SC_PLAYERLOGIN_LOGINRESULT}
SC_PLAYERLOGIN.fields = {SC_PLAYERLOGIN_LOGINRESULT_FIELD}
SC_PLAYERLOGIN.is_extendable = false
SC_PLAYERLOGIN.extensions = {}
CS_PLAYERREGISTER_ACCOUNT_FIELD.name = "account"
CS_PLAYERREGISTER_ACCOUNT_FIELD.full_name = ".PlayerLogin.CS_PlayerRegister.account"
CS_PLAYERREGISTER_ACCOUNT_FIELD.number = 1
CS_PLAYERREGISTER_ACCOUNT_FIELD.index = 0
CS_PLAYERREGISTER_ACCOUNT_FIELD.label = 1
CS_PLAYERREGISTER_ACCOUNT_FIELD.has_default_value = false
CS_PLAYERREGISTER_ACCOUNT_FIELD.default_value = ""
CS_PLAYERREGISTER_ACCOUNT_FIELD.type = 9
CS_PLAYERREGISTER_ACCOUNT_FIELD.cpp_type = 9
CS_PLAYERREGISTER_PWD_FIELD.name = "pwd"
CS_PLAYERREGISTER_PWD_FIELD.full_name = ".PlayerLogin.CS_PlayerRegister.pwd"
CS_PLAYERREGISTER_PWD_FIELD.number = 2
CS_PLAYERREGISTER_PWD_FIELD.index = 1
CS_PLAYERREGISTER_PWD_FIELD.label = 1
CS_PLAYERREGISTER_PWD_FIELD.has_default_value = false
CS_PLAYERREGISTER_PWD_FIELD.default_value = ""
CS_PLAYERREGISTER_PWD_FIELD.type = 9
CS_PLAYERREGISTER_PWD_FIELD.cpp_type = 9
CS_PLAYERREGISTER.name = "CS_PlayerRegister"
CS_PLAYERREGISTER.full_name = ".PlayerLogin.CS_PlayerRegister"
CS_PLAYERREGISTER.nested_types = {}
CS_PLAYERREGISTER.enum_types = {}
CS_PLAYERREGISTER.fields = {CS_PLAYERREGISTER_ACCOUNT_FIELD, CS_PLAYERREGISTER_PWD_FIELD}
CS_PLAYERREGISTER.is_extendable = false
CS_PLAYERREGISTER.extensions = {}
SC_PLAYERREGISTER_REGISTERRESULT_SUCCESS_ENUM.name = "SUCCESS"
SC_PLAYERREGISTER_REGISTERRESULT_SUCCESS_ENUM.index = 0
SC_PLAYERREGISTER_REGISTERRESULT_SUCCESS_ENUM.number = 0
SC_PLAYERREGISTER_REGISTERRESULT_ACCOUNT_ERROR_ENUM.name = "ACCOUNT_ERROR"
SC_PLAYERREGISTER_REGISTERRESULT_ACCOUNT_ERROR_ENUM.index = 1
SC_PLAYERREGISTER_REGISTERRESULT_ACCOUNT_ERROR_ENUM.number = 1
SC_PLAYERREGISTER_REGISTERRESULT.name = "RegisterResult"
SC_PLAYERREGISTER_REGISTERRESULT.full_name = ".PlayerLogin.SC_PlayerRegister.RegisterResult"
SC_PLAYERREGISTER_REGISTERRESULT.values = {SC_PLAYERREGISTER_REGISTERRESULT_SUCCESS_ENUM,SC_PLAYERREGISTER_REGISTERRESULT_ACCOUNT_ERROR_ENUM}
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.name = "registerResult"
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.full_name = ".PlayerLogin.SC_PlayerRegister.registerResult"
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.number = 1
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.index = 0
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.label = 1
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.has_default_value = false
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.default_value = nil
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.enum_type = SC_PLAYERREGISTER_REGISTERRESULT
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.type = 14
SC_PLAYERREGISTER_REGISTERRESULT_FIELD.cpp_type = 8
SC_PLAYERREGISTER.name = "SC_PlayerRegister"
SC_PLAYERREGISTER.full_name = ".PlayerLogin.SC_PlayerRegister"
SC_PLAYERREGISTER.nested_types = {}
SC_PLAYERREGISTER.enum_types = {SC_PLAYERREGISTER_REGISTERRESULT}
SC_PLAYERREGISTER.fields = {SC_PLAYERREGISTER_REGISTERRESULT_FIELD}
SC_PLAYERREGISTER.is_extendable = false
SC_PLAYERREGISTER.extensions = {}
CS_PlayerLogin = protobuf.Message(CS_PLAYERLOGIN)
CS_PlayerRegister = protobuf.Message(CS_PLAYERREGISTER)
SC_PlayerLogin = protobuf.Message(SC_PLAYERLOGIN)
SC_PlayerRegister = protobuf.Message(SC_PLAYERREGISTER)
|
-----------------------------------------------------------
-- PROJECT: MTA:TD - Test and Debug Framework
--
-- LICENSE: See LICENSE in top level directory
-- PURPOSE: MTATD Entrypoint
------------------------------------------------------------
-- Start MTATD
initMTATD()
-- Destroy MTATD gracefully
addEventHandler(triggerClientEvent and "onResourceStop" or "onClientResourceStop", resourceRoot,
function()
destroyMTATD()
end,
true,
"low-9999999"
)
|
wItems, gItems, gKeys, colSlot, colName, colValue, items, lDescription, bDropItem, bUseItem, bShowItem, bDestroyItem, tabPanel, tabItems, tabWeapons = nil
gWeapons, colWSlot, colWName, colWValue = nil
toggleLabel, chkFood, chkKeys, chkDrugs, chkOther, chkBooks, chkClothes, chkElectronics, chkEmpty = nil
wRightClick = nil
bPickup, bToggle, bPreviousTrack, bNextTrack, bCloseMenu = nil
ax, ay = nil
item = nil
showinvPlayer = nil
showFood = true
showKeys = true
showDrugs = true
showOther = true
showBooks = true
showClothes = true
showElectronics = true
showEmpty = true
activeTab = 0
-- PLEASE WAIT window
local sx, sy = guiGetScreenSize( )
wWait = guiCreateButton( ( sx - 200 ) / 2, ( sy - 60 ) / 2, 200, 60, "Please wait a moment...", false )
guiSetEnabled( wWait, false )
guiSetVisible( wWait, false )
guiSetProperty( wWait, "AlwaysOnTop", "True" )
--[[function clickItem(button, state, absX, absY, x, y, z, element)
if (button == "right") and (state=="down") then
if getElementData(getLocalPlayer(), "exclusiveGUI") then
return
end
local px, py, pz = getElementPosition(getLocalPlayer())
if element and (getElementParent(getElementParent(element)) == getResourceRootElement(getResourceFromName("map-system")) or getElementParent(getElementParent(element)) == getResourceRootElement(getResourceFromName("interior-system"))) then
element = nil
end
if not element then
local wx, wy, wz = x, y, z
local x, y, z = nil
for key, value in ipairs(getElementsByType("object",getResourceRootElement())) do
if isElementStreamedIn(value) then
x, y, z = getElementPosition(value)
local minx, miny, minz, maxx, maxy, maxz = getElementBoundingBox(value)
local offset = 0.34
minx = x + minx - offset
miny = y + miny - offset
minz = z + minz - offset
maxx = x + maxx + offset
maxy = y + maxy + offset
maxz = z + maxz + offset
local dist = getDistanceBetweenPoints3D(x, y, z, px, py, pz)
if (wx >= minx and wx <=maxx) and (wy >= miny and wy <=maxy) and (wz >= minz and wz <=maxz) then
element = value
break
end
end
end
end
if element and getElementParent(getElementParent(element)) == getResourceRootElement() then
if getDistanceBetweenPoints3D(x, y, z, px, py, pz) < 3 then
if (wRightClick) then
hideItemMenu()
end
ax = absX
ay = absY
item = element
showItemMenu()
else
outputChatBox("You are too far away from that item.", 255, 0, 0)
end
else
if (wRightClick) then
hideItemMenu()
end
end
end
end
addEventHandler("onClientClick", getRootElement(), clickItem, true)]]
function showItemMenu()
local itemID = getElementData(item, "itemID")
local itemValue = getElementData(item, "itemValue")
local itemName = getItemName( itemID, itemValue )
if itemID ~= 80 then
itemName = itemName .. " (" .. getItemValue( itemID, itemValue ) .. ")"
end
wRightClick = guiCreateWindow(ax, ay, 150, 200, itemName, false)
local y = 0.13
if itemID == 81 then
bPickup = guiCreateButton(0.05, y, 0.9, 0.1, "Open", true, wRightClick)
addEventHandler("onClientGUIClick", bPickup,
function(button)
if button=="left" and not getElementData(localPlayer, "exclusiveGUI") then
triggerServerEvent( "openFreakinInventory", getLocalPlayer(), item, ax, ay )
hideItemMenu()
end
end,
false
)
else
bPickup = guiCreateButton(0.05, y, 0.9, 0.1, "Pick Item Up", true, wRightClick)
addEventHandler("onClientGUIClick", bPickup, pickupItem, false)
end
y = y + 0.14
if itemID == 54 then
-- Ghettoblaster
if getElementData(item, "itemValue") > 0 then
bToggle = guiCreateButton(0.05, y, 0.9, 0.1, "Turn Off", true, wRightClick)
y = y + 0.14
bPreviousTrack = guiCreateButton(0.05, y, 0.42, 0.1, "Previous", true, wRightClick)
addEventHandler("onClientGUIClick", bPreviousTrack, function() triggerServerEvent("changeGhettoblasterTrack", getLocalPlayer(), item, -1) end, false)
bNextTrack = guiCreateButton(0.53, y, 0.42, 0.1, "Next", true, wRightClick)
addEventHandler("onClientGUIClick", bNextTrack, function() triggerServerEvent("changeGhettoblasterTrack", getLocalPlayer(), item, 1) end, false)
else
bToggle = guiCreateButton(0.05, y, 0.9, 0.1, "Turn On", true, wRightClick)
end
addEventHandler("onClientGUIClick", bToggle, toggleGhettoblaster, false)
y = y + 0.14
end
bCloseMenu = guiCreateButton(0.05, y, 0.9, 0.1, "Close Menu", true, wRightClick)
addEventHandler("onClientGUIClick", bCloseMenu, hideItemMenu, false)
end
function hideItemMenu()
if (isElement(bPickup)) then
destroyElement(bPickup)
end
bPickup = nil
if (isElement(bToggle)) then
destroyElement(bToggle)
end
bToggle = nil
if (isElement(bPreviousTrack)) then
destroyElement(bPreviousTrack)
end
bPreviousTrack = nil
if (isElement(bNextTrack)) then
destroyElement(bNextTrack)
end
bNextTrack = nil
if (isElement(bCloseMenu)) then
destroyElement(bCloseMenu)
end
bCloseMenu = nil
if (isElement(wRightClick)) then
destroyElement(wRightClick)
end
wRightClick = nil
ax = nil
ay = nil
item = nil
showCursor(false)
triggerEvent("cursorHide", getLocalPlayer())
end
function updateMenu(dataname)
if source == item and dataname == "itemValue" and getElementData(source, "itemID") == 54 then -- update the track while you're in menu
guiSetText(wRightClick, "GHETTOBLASTER (" .. getElementData(source, "itemValue") .. ")")
end
end
addEventHandler("onClientElementDataChange", getRootElement(), updateMenu)
function toggleGhettoblaster(button, state, absX, absY, step)
triggerServerEvent("toggleGhettoblaster", getLocalPlayer(), item)
hideItemMenu()
end
function pickupItem(button, state, item)
if (button=="left") then
local restrain = getElementData(getLocalPlayer(), "restrain")
if (restrain) and (restrain==1) then
outputChatBox("You are cuffed.", 255, 0, 0)
elseif getElementData(item, "itemID") > 0 and not hasSpaceForItem(getLocalPlayer(), getElementData(item, "itemID")) then
outputChatBox("Your Inventory is full.", 255, 0, 0)
elseif isElement(item) then
if wRightClick then
showCursor(false)
triggerEvent("cursorHide", getLocalPlayer())
end
local itemID = tonumber(getElementData(item, "itemID")) or 0
local itemValue = tonumber(getElementData(item, "itemValue")) or 0
if itemID < 0 and itemID ~= -100 then
local free, totalfree = exports.weaponcap:getFreeAmmo( -itemID )
local cap = exports.weaponcap:getAmmoCap( -itemID )
if totalfree == 0 then
outputChatBox( "You've got all weapons you can carry.", 255, 0, 0 )
elseif free == 0 and cap == 0 then
local weaponName = "other weapon"
local slot = getSlotFromWeapon( -itemID )
if slot and slot ~= 0 and getPedTotalAmmo( getLocalPlayer(), slot ) > 0 then
local weapon = getPedWeapon( getLocalPlayer(), slot )
weaponName = getItemName( -weapon )
end
outputChatBox( "You don't carry that weapon, please drop your " .. weaponName .. " first.", 255, 0, 0 )
elseif free == 0 then
outputChatBox( "You can't carry any more of that weapon.", 255, 0, 0 )
else
triggerServerEvent("pickupItem", getLocalPlayer(), item, free )
end
else
triggerServerEvent("pickupItem", getLocalPlayer(), item)
end
if wRightClick then
hideItemMenu()
end
end
end
end
function toggleCategory()
if (source==chkFood) then
showFood = not showFood
elseif (source==chkKeys) then
showKeys = not showKeys
elseif (source==chkDrugs) then
showDrugs = not showDrugs
elseif (source==chkBooks) then
showBooks = not showBooks
elseif (source==chkClothes) then
showClothes = not showClothes
elseif (source==chkElectronics) then
showElectronics = not showElectronics
elseif (source==chkOther) then
showOther = not showOther
elseif (source==chkEmpty) then
showEmpty = not showEmpty
end
-- let's add the items again
if (isElement(gItems)) then
guiGridListClear(gItems)
end
if (isElement(gKeys)) then
guiGridListClear(gKeys)
end
local items, slots = getItems( showinvPlayer ), getInventorySlots( showinvPlayer )
for i = 1, 3 * slots do
if not items[i] then
if showEmpty and i <= slots then
local row = guiGridListAddRow(gItems)
guiGridListSetItemText(gItems, row, colSlot, tostring(row+1), false, true)
guiGridListSetItemText(gItems, row, colName, "Empty", false, false)
guiGridListSetItemText(gItems, row, colValue, "None", false, false)
end
else
local itemid = items[i][1]
local itemvalue = items[i][2]
local itemtype = getItemType(itemid)
if not (itemtype) then
return
else
local add = true
if (itemtype==1) and not (showFood) then
add = false
elseif (itemtype==2) and not (showKeys) then
add = false
elseif (itemtype==3) and not (showDrugs) then
add = false
elseif (itemtype==4) and not (showOther) then
add = false
elseif (itemtype==5) and not (showBooks) then
add = false
elseif (itemtype==6) and not (showClothes) then
add = false
elseif (itemtype==7) and not (showElectronics) then
add = false
elseif (itemtype==false) then
add = false
end
if (add) then
local row = guiGridListAddRow(itemtype == 2 and gKeys or gItems)
guiGridListSetItemText(itemtype == 2 and gKeys or gItems, row, colSlot, tostring(row+1), false, true)
guiGridListSetItemData(itemtype == 2 and gKeys or gItems, row, colSlot, tostring(i))
guiGridListSetItemText(itemtype == 2 and gKeys or gItems, row, colName, tostring(getItemName(itemid, itemvalue)), false, false)
guiGridListSetItemText(itemtype == 2 and gKeys or gItems, row, colValue, tostring(getItemValue(itemid, itemvalue)), false, false)
end
end
end
end
while showEmpty and guiGridListGetRowCount( gItems ) < slots do
local row = guiGridListAddRow(gItems)
guiGridListSetItemText(gItems, row, colSlot, tostring(row+1), false, true)
guiGridListSetItemText(gItems, row, colName, "Empty", false, false)
guiGridListSetItemText(gItems, row, colValue, "None", false, false)
end
end
function toggleInventory()
if wItems then
if guiGetEnabled( wItems ) then
hideInventory()
end
elseif not getElementData(getLocalPlayer(), "adminjailed") and not getElementData(getLocalPlayer(), "pd.jailstation") then
--showInventory(getLocalPlayer())
else
--outputChatBox("You can't access your inventory in jail", 255, 0, 0)
end
end
bindKey("i", "down", toggleInventory)
function showInventory(player, syncw, synca)
if not (wChemistrySet) then
showinvPlayer = player
if wItems then
hideInventory()
end
if getElementData(getLocalPlayer(), "exclusiveGUI") then
return
end
setElementData(getLocalPlayer(), "exclusiveGUI", true, false)
local width, height = 600, 500
local scrWidth, scrHeight = guiGetScreenSize()
local x = scrWidth/2 - (width/2)
local y = scrHeight/2 - (height/2)
local title = "Inventory"
if player ~= getLocalPlayer() then
title = title .. " of " .. getPlayerName(player)
end
wItems = guiCreateWindow(x, y, width, height, title, false)
guiWindowSetSizable(wItems, false)
tabPanel = guiCreateTabPanel(0.025, 0.05, 0.95, 0.7, true, wItems)
tabItems = guiCreateTab("Items", tabPanel)
tabKeys = guiCreateTab("Keys", tabPanel)
tabWeapons = guiCreateTab("Weapons", tabPanel)
if activeTab == 0 then
guiSetSelectedTab(tabPanel, tabItems)
elseif activeTab == 1 then
guiSetSelectedTab(tabPanel, tabKeys)
else
guiSetSelectedTab(tabPanel, tabWeapons)
end
addEventHandler( "onClientGUITabSwitched", tabPanel,
function( tab )
if tab == tabItems then
activeTab = 0
elseif tab == tabKeys then
activeTab = 1
elseif tab == tabWeapons then
activeTab = 2
end
end,
false )
-- ITEMS
gItems = guiCreateGridList(0.025, 0.05, 0.95, 0.9, true, tabItems)
addEventHandler("onClientGUIClick", gItems, showDescription, false)
colSlot = guiGridListAddColumn(gItems, "Slot", 0.1)
colName = guiGridListAddColumn(gItems, "Name", 0.625)
colValue = guiGridListAddColumn(gItems, "Value", 0.225)
-- keys
gKeys = guiCreateGridList(0.025, 0.05, 0.95, 0.9, true, tabKeys)
addEventHandler("onClientGUIClick", gKeys, showDescription, false)
colSlot = guiGridListAddColumn(gKeys, "Slot", 0.1)
colName = guiGridListAddColumn(gKeys, "Name", 0.625)
colValue = guiGridListAddColumn(gKeys, "Value", 0.225)
-- type checkboxes
toggleLabel = guiCreateLabel(0.025, 0.77, 0.95, 0.9, "Toggle Item Types:", true, wItems)
guiSetFont(toggleLabel, "default-bold-small")
chkFood = guiCreateCheckBox(0.025, 0.8, 0.15, 0.05, "Food & Drink", showFood, true, wItems)
chkKeys = guiCreateCheckBox(0.2, 0.8, 0.1, 0.05, "Keys", showKeys, true, wItems)
chkDrugs = guiCreateCheckBox(0.3, 0.8, 0.1, 0.05, "Drugs", showDrugs, true, wItems)
chkBooks = guiCreateCheckBox(0.4, 0.8, 0.1, 0.05, "Books", showBooks, true, wItems)
chkClothes = guiCreateCheckBox(0.5, 0.8, 0.125, 0.05, "Clothing", showClothes, true, wItems)
chkElectronics = guiCreateCheckBox(0.625, 0.8, 0.15, 0.05, "Electronics", showElectronics, true, wItems)
chkOther = guiCreateCheckBox(0.775, 0.8, 0.1, 0.05, "Other", showOther, true, wItems)
chkEmpty = guiCreateCheckBox(0.875, 0.8, 0.1, 0.05, "Empty", showEmpty, true, wItems)
addEventHandler("onClientGUIClick", chkFood, toggleCategory, false)
addEventHandler("onClientGUIClick", chkKeys, toggleCategory, false)
addEventHandler("onClientGUIClick", chkDrugs, toggleCategory, false)
addEventHandler("onClientGUIClick", chkBooks, toggleCategory, false)
addEventHandler("onClientGUIClick", chkClothes, toggleCategory, false)
addEventHandler("onClientGUIClick", chkElectronics, toggleCategory, false)
addEventHandler("onClientGUIClick", chkOther, toggleCategory, false)
addEventHandler("onClientGUIClick", chkEmpty, toggleCategory, false)
source = nil
toggleCategory()
-- addEventHandler("onClientGUIDoubleClick", gItems, useItem, false)
-- addEventHandler("onClientGUIDoubleClick", gKeys, useItem, false)
-- WEAPONS
gWeapons = guiCreateGridList(0.025, 0.05, 0.95, 0.9, true, tabWeapons)
addEventHandler("onClientGUIClick", gWeapons, showDescription, false)
colWSlot = guiGridListAddColumn(gWeapons, "Slot", 0.1)
colWName = guiGridListAddColumn(gWeapons, "Name", 0.625)
colWValue = guiGridListAddColumn(gWeapons, "Ammo", 0.225)
if syncw and synca then
for i=0, 12 do
local tokenweapon = tonumber(gettok(syncw, i+1, 59))
local tokenammo = tonumber(gettok(synca, i+1, 59))
if (not tokenweapon) or (not tokenammo) then
break
else
local row = guiGridListAddRow(gWeapons)
local weapon = getItemName(-tokenweapon)
guiGridListSetItemText(gWeapons, row, colWSlot, tostring(getSlotFromWeapon(tokenweapon)), false, true)
guiGridListSetItemText(gWeapons, row, colWName, tostring(weapon), false, false)
guiGridListSetItemText(gWeapons, row, colWValue, tostring(tokenammo), false, false)
end
end
elseif player == getLocalPlayer() then
for i = 0, 12 do
if getPedWeapon(player, i) and getPedWeapon(player, i) ~= 0 and getPedTotalAmmo(player, i) > 0 then
local row = guiGridListAddRow(gWeapons)
local weapon = getItemName(-getPedWeapon(player, i))
local ammo = getPedTotalAmmo(player, i)
guiGridListSetItemText(gWeapons, row, colWSlot, tostring(i), false, true)
guiGridListSetItemText(gWeapons, row, colWName, tostring(weapon), false, false)
guiGridListSetItemText(gWeapons, row, colWValue, tostring(ammo), false, false)
end
end
else
local row = guiGridListAddRow(gWeapons)
guiGridListSetItemText(gWeapons, row, colWName, "Error", false, false)
end
guiSetVisible(colWSlot, false)
-- addEventHandler("onClientGUIDoubleClick", gWeapons, useItem, false)
-- ARMOR
if getPedArmor(player) > 0 then
local row = guiGridListAddRow(gWeapons)
guiGridListSetItemText(gWeapons, row, colWSlot, tostring(13), false, true)
guiGridListSetItemText(gWeapons, row, colWName, "Body Armor", false, false)
guiGridListSetItemText(gWeapons, row, colWValue, tostring(getPedArmor(player)), false, false)
end
-- GENERAL
lDescription = guiCreateLabel(0.025, 0.87, 0.95, 0.1, "Click an item to see it's description.", true, wItems)
guiLabelSetHorizontalAlign(lDescription, "center", true)
guiSetFont(lDescription, "default-bold-small")
-- buttons
--[[if player == getLocalPlayer() then
bUseItem = guiCreateButton(0.05, 0.91, 0.2, 0.15, "Use Item", true, wItems)
addEventHandler("onClientGUIClick", bUseItem, useItem, false)
guiSetEnabled(bUseItem, false)
bDropItem = guiCreateButton(0.30, 0.91, 0.2, 0.15, "Drop Item", true, wItems)
addEventHandler("onClientGUIClick", bDropItem, dropItem, false)
guiSetEnabled(bDropItem, false)
bShowItem = guiCreateButton(0.55, 0.91, 0.2, 0.15, "Show Item", true, wItems)
addEventHandler("onClientGUIClick", bShowItem, showItem, false)
guiSetEnabled(bShowItem, false)
bDestroyItem = guiCreateButton(0.8, 0.91, 0.2, 0.15, "Destroy Item", true, wItems)
addEventHandler("onClientGUIClick", bDestroyItem, destroyItem, false)
guiSetEnabled(bDestroyItem, false)
else]]
bClose = guiCreateButton(0.375, 0.91, 0.2, 0.15, "Close Inventory", true, wItems)
addEventHandler("onClientGUIClick", bClose, hideInventory, false)
--end
showCursor(true)
end
end
addEvent("showInventory", true)
addEventHandler("showInventory", getRootElement(), showInventory)
function hideInventory()
colSlot = nil
colName = nil
colValue = nil
colWSlot = nil
colWName = nil
colWValue = nil
if wItems then
destroyElement(wItems)
end
wItems = nil
showCursor(false)
setElementData(getLocalPlayer(), "exclusiveGUI", false, false)
hideNewInventory()
end
addEvent("hideInventory", true)
addEventHandler("hideInventory", getRootElement(), hideInventory)
function showDescription(button, state)
if (button=="left") then
if (guiGetSelectedTab(tabPanel)==tabItems or guiGetSelectedTab(tabPanel)==tabKeys) then -- ITEMS
local row, col = guiGridListGetSelectedItem(guiGetSelectedTab(tabPanel) == tabKeys and gKeys or gItems)
if (row==-1) or (col==-1) then
guiSetText(lDescription, "Click an item to see it's description.")
guiSetEnabled(bUseItem, false)
guiSetEnabled(bDropItem, false)
guiSetEnabled(bShowItem, false)
guiSetEnabled(bDestroyItem, false)
else
local slot = tonumber(guiGridListGetItemData(guiGetSelectedTab(tabPanel) == tabKeys and gKeys or gItems, row, 1))
local items = getItems(showinvPlayer)
if not items[slot] then
guiSetText(lDescription, "An empty slot.")
guiSetEnabled(bUseItem, false)
guiSetEnabled(bDropItem, false)
guiSetEnabled(bShowItem, false)
guiSetEnabled(bDestroyItem, false)
else
local desc = tostring( getItemDescription( items[slot][1], items[slot][2] ) )
local value = items[slot][2]
-- percent operators
desc = string.gsub((desc), "#v", tostring(value))
if (desc=="A Dictionary.") then
local res = getResourceFromName("language-system")
local lang = call(res, "getLanguageName", tonumber(value))
desc = "A " .. lang .. " dictionary."
end
guiSetText(lDescription, desc)
guiSetEnabled(bUseItem, true)
guiSetEnabled(bDropItem, true)
guiSetEnabled(bShowItem, true)
guiSetEnabled(bDestroyItem, true)
end
end
elseif (guiGetSelectedTab(tabPanel)==tabWeapons) then -- WEAPONS
local row, col = guiGridListGetSelectedItem(gWeapons)
if (row==-1) or (col==-1) then
guiSetText(lDescription, "Click an item to see it's description.")
guiSetEnabled(bUseItem, false)
guiSetEnabled(bDropItem, false)
guiSetEnabled(bShowItem, false)
guiSetEnabled(bDestroyItem, false)
else
local name = tostring(guiGridListGetItemText(gWeapons, row, 2))
local ammo = tostring(guiGridListGetItemText(gWeapons, row, 3))
local desc = "A " .. name .. " with " .. ammo .. " ammunition."
guiSetText(lDescription, desc)
guiSetEnabled(bUseItem, true)
guiSetEnabled(bDropItem, true)
guiSetEnabled(bShowItem, true)
guiSetEnabled(bDestroyItem, true)
end
end
end
end
function useItem(itemSlot)
--function useItem(button)
showinvPlayer = getLocalPlayer()
if getElementHealth(getLocalPlayer()) == 0 then return end
local x, y, z = getElementPosition(getLocalPlayer())
local groundz = getGroundPosition(x, y, z)
if itemSlot > 0 then -- ITEMS
local itemID = getItems( showinvPlayer )[itemSlot][1]
local itemName = getItemName( itemID )
local itemValue = getItems( showinvPlayer )[itemSlot][2]
local additional = nil
if (itemID==2) then -- cellphone
hideInventory()
triggerEvent("showPhoneGUI", getLocalPlayer(), itemValue)
outputChatBox("Use /call to use this item.", 255, 194, 14)
return
elseif (itemID==6) then -- radio
outputChatBox("Press Y to use this item. You can also use /tuneradio to tune your radio.", 255, 194, 14)
return
elseif (itemID==7) then -- phonebook
outputChatBox("Use /phonebook to use this item.", 255, 194, 14)
return
elseif (itemID==18) then -- City Guide
triggerEvent( "showCityGuide", getLocalPlayer( ) )
return
elseif (itemID==19) then -- MP3 PLayer
if isPedInVehicle(getLocalPlayer()) or getElementData(getLocalPlayer(), "fishing") or getElementData(getLocalPlayer(), "jammed") then
outputChatBox("Use the - and = keys to use the MP3 Player.", 255, 194, 14)
else
exports['realism-system']:toggleMP3("=", "down")
end return
elseif (itemID==27) then -- Flashbang
local x, y, z = getElementPosition(getLocalPlayer( ))
local rot = getPedRotation(getLocalPlayer( ))
x = x + math.sin(math.rad(-rot)) * 10
y = y + math.cos(math.rad(-rot)) * 10
z = getGroundPosition(x, y, z + 2)
additional = { x, y, z }
elseif (itemID==28 or itemID==54) then -- Glowstick or Ghettoblaster
local x, y, z = getElementPosition(getLocalPlayer( ))
local rot = getPedRotation(getLocalPlayer( ))
x = x + math.sin(math.rad(-rot)) * 2
y = y + math.cos(math.rad(-rot)) * 2
z = getGroundPosition(x, y, z)
additional = { x, y, z - 0.5 }
elseif (itemID==30) or (itemID==31) or (itemID==32) or (itemID==33) then
outputChatBox("Use the chemistry set purchasable from 24/7 to use this item.", 255, 0, 0)
return
elseif (itemID==34) then -- COCAINE
doDrug1Effect()
elseif (itemID==35) then
doDrug2Effect()
elseif (itemID==36) then
doDrug3Effect()
elseif (itemID==37) then
doDrug4Effect()
elseif (itemID==38) then
if not getPedOccupiedVehicle(getLocalPlayer()) then
doDrug5Effect()
end
elseif (itemID==39) then
doDrug6Effect()
elseif (itemID==40) then
doDrug3Effect()
doDrug1Effect()
elseif (itemID==41) then
doDrug4Effect()
doDrug6Effect()
elseif (itemID==42) then
if not getPedOccupiedVehicle(getLocalPlayer()) then
doDrug5Effect()
doDrug2Effect()
end
elseif (itemID==43) then
doDrug4Effect()
doDrug1Effect()
doDrug6Effect()
elseif (itemID==44) then
hideInventory()
showChemistrySet()
return
elseif (itemID==45) or (itemID==46) or (itemID==47) or (itemID==66) then
outputChatBox("Right click a player to use this item.", source, 255, 0, 0)
return
elseif (itemID==48) then
outputChatBox("Your inventory is extended.", 0, 255, 0)
return
elseif (itemID==50) or (itemID==51) or (itemID==52) then
hideInventory()
elseif (itemID==53) then -- Breathalizer
outputChatBox("Use /breathtest to use this item.", 255, 194, 15)
return
elseif (itemID==57) then -- FUEL CAN
hideInventory()
elseif (itemID==58) then
setTimer(
function()
setElementData(getLocalPlayer(), "alcohollevel", ( getElementData(getLocalPlayer(), "alcohollevel") or 0 ) + 0.1, false)
end, 15000, 1
)
elseif (itemID==61) then -- Emergency Light Becon
outputChatBox("Put it in your car inventory and press 'P' to toggle it.", 255, 194, 14)
return
elseif (itemID==62) then
setTimer(
function()
setElementData(getLocalPlayer(), "alcohollevel", ( getElementData(getLocalPlayer(), "alcohollevel") or 0 ) + 0.3, false)
end, 5000, 1
)
elseif (itemID==63) then
setTimer(
function()
setElementData(getLocalPlayer(), "alcohollevel", ( getElementData(getLocalPlayer(), "alcohollevel") or 0 ) + 0.2, false)
end, 10000, 1
)
elseif (itemID==67) then -- GPS
outputChatBox("Put it in your car inventory and Press 'F5'.", 255, 194, 14)
return
elseif (itemID==70) then -- First Aid Kit
outputChatBox("Right click on a player who's knocked out to stabilize him.", 255, 194, 14)
return
elseif (itemID==71) then -- Notebook
outputChatBox("Use /writenote [text] to write a note. There are " .. itemValue .. " pages left.", 255, 194, 14)
return
elseif (itemID==72) then -- Note
outputChatBox("The Note reads: " .. itemValue, 255, 194, 14)
elseif (itemID==78) then
outputChatBox("This San Andreas Pilot License was issued for " .. itemValue .. ".", 255, 194, 14)
return
elseif (itemID==81) then
outputChatBox("Drop this Fridge in an Interior.", 255, 194, 14)
return
elseif (itemID==82) then
outputChatBox("A BT&R identification, issued to " .. itemValue .. ".", 255, 194, 14)
return
elseif (itemID==84) then
outputChatBox("Put it in a car or carry it to know when police is around.", 255, 194, 14)
return
elseif (itemID==85) then -- Emergency Light Becon
outputChatBox("Put it in your car inventory and press 'N' to toggle it.", 255, 194, 14)
return
elseif (itemID==91) then
setTimer(
function()
setElementData(getLocalPlayer(), "alcohollevel", ( getElementData(getLocalPlayer(), "alcohollevel") or 0 ) + 0.35, false)
end, 15000, 1
)
elseif (itemID==96) then
hideInventory()
end
triggerServerEvent("useItem", getLocalPlayer(), itemSlot, additional)
else
if itemSlot == -100 then
outputChatBox("You wear Body Armor.", 0, 255, 0)
else
setPedWeaponSlot( getLocalPlayer(), -itemSlot )
end
end
end
function stopGasmaskDamage(attacker, weapon)
local gasmask = getElementData(getLocalPlayer(), "gasmask")
if (weapon==17 or weapon==41) and (gasmask==1) then
cancelEvent()
end
end
addEventHandler("onClientPlayerDamage", getLocalPlayer(), stopGasmaskDamage)
-- /itemlist (admin command to get item IDs)
wItemList, bItemListClose = nil
function showItemList()
if getElementData(getLocalPlayer(), "adminlevel") == 0 then
return
end
if not (wItemsList) then
wItemsList = guiCreateWindow(0.15, 0.15, 0.7, 0.7, "Items List", true)
local gridItems = guiCreateGridList(0.025, 0.1, 0.95, 0.775, true, wItemsList)
local colID = guiGridListAddColumn(gridItems, "ID", 0.1)
local colName = guiGridListAddColumn(gridItems, "Item Name", 0.3)
local colDesc = guiGridListAddColumn(gridItems, "Description", 0.6)
for key, value in pairs(g_items) do
if key ~= 74 and key ~= 75 then
local row = guiGridListAddRow(gridItems)
guiGridListSetItemText(gridItems, row, colID, tostring(key), false, true)
guiGridListSetItemText(gridItems, row, colName, value[1], false, false)
guiGridListSetItemText(gridItems, row, colDesc, value[2], false, false)
end
end
bItemListClose = guiCreateButton(0.025, 0.9, 0.95, 0.1, "Close", true, wItemsList)
addEventHandler("onClientGUIClick", bItemListClose, closeItemsList, false)
showCursor(true)
else
guiSetVisible(wItemsList, true)
guiBringToFront(wItemsList)
showCursor(true)
end
end
addCommandHandler("itemlist", showItemList)
function closeItemsList(button, state)
if (source==bItemListClose) and (button=="left") and (state=="up") then
showCursor(false)
destroyElement(bItemListClose)
destroyElement(wItemsList)
bItemListClose = nil
wItemsList = nil
end
end
addEventHandler("onClientChangeChar", getRootElement(), hideInventory)
local function updateInv()
if wItems and source == showinvPlayer then
source = nil
setTimer(toggleCategory, 50, 1)
if guiGetSelectedTab( tabPanel ) == tabItems then
guiSetEnabled(bUseItem, false)
guiSetEnabled(bDropItem, false)
guiSetEnabled(bShowItem, false)
guiSetEnabled(bDestroyItem, false)
end
end
end
addEventHandler("recieveItems", getRootElement(), updateInv)
addEvent("finishItemDrop", true)
addEventHandler("finishItemDrop", getLocalPlayer(),
function( )
if wItems then
guiSetVisible( wWait, false )
guiSetEnabled( wItems, true )
end
end
)
|
require("import") -- the import fn
import("smart_pointer_multi") -- import lib into global
spm=smart_pointer_multi --alias
-- catching undefined variables
local env = _ENV -- Lua 5.2
if not env then env = getfenv () end -- Lua 5.1
setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
foo = spm.Foo()
foo.x = 5
assert(foo:getx() == 5)
bar = spm.Bar(foo)
spam = spm.Spam(bar)
grok = spm.Grok(bar)
assert(bar:getx() == 5)
assert(spam:getx() == 5)
spam.x = 7
assert(grok:getx() == 7)
grok.x = 10
assert(foo:getx() == 10)
|
--[[
Set KSP Script Simplest
Author: Native Instruments
Written by: Yaron Eshkar
Modified: August 6, 2021
--]]
-- Script
local ksp_script_string = [[
on init
declare ui_knob $knob(0,1000000,1)
end on
]]
instrument.scripts[0].sourceCode = ksp_script_string
|
-- Base Spoon
-- ----------
-- This is a base spoon class that should be used for all custom internal spoons. It defines
-- the default hotkey and mouse event binding system, as well as some useful and required
-- methods that all internal spoons will extend.
local BaseSpoon = {}
-- BaseSpoon.__index = BaseSpoon
BaseSpoon_mt = { __index = BaseSpoon }
-- Default Metadata fields
BaseSpoon.name = nil
BaseSpoon.version = nil
BaseSpoon.author = nil
-- Default Hotkey Container
BaseSpoon.hotkeys = {
primary = {},
secondary = {}
}
-- Default MouseEvent Container
BaseSpoon.mouseEvents = {}
-- The default hotkey mapping function. This method reads the `hotkeys` table on this object
-- and binds them appropriately.
-- @param hyper A table containing the primary and secondary hyper configs
function BaseSpoon:bindHotkeys(hyper)
local hyper_types = {"primary", "secondary"}
local def = {}
local map = {}
for i, type in ipairs(hyper_types) do
for key, name in pairs(self.hotkeys[type]) do
map[name] = { hyper[type], key}
local dispatch = function()
return self[name](self)
end
def[name] = dispatch
end
end
hs.spoons.bindHotkeysToSpec(def, map)
end
-- The default MouseEvent binding method. This method will read the internal mouseEvents table
-- of this object and bind all events.
function BaseSpoon:bindMouseEvents()
for event_name, method_name in pairs(self.mouseEvents) do
local dispatch = function()
return self[method_name](self)
end
local event = hs.eventtap.new({hs.eventtap.event.types[event_name]}, dispatch)
table.insert(self.activeEvents, event)
event:start()
end
end
-- Required methods for all spoons. Spoons don't need to override these, but all spoons must contain
-- these three methods, so the base class provides them.
function BaseSpoon:start() end
function BaseSpoon:stop() end
function BaseSpoon:init() end
-- Extend method that all "sub spoons" must call to create their base instance.
function BaseSpoon:new()
local subSpoon = {}
setmetatable( subSpoon, BaseSpoon_mt )
return subSpoon
end
return BaseSpoon;
|
local path = "hall/agency_pin.png"
local agency_pin_map = {
["btn_g_1.png"] = {
file=path,
x=2,y=2,
width=200,height=86,
rotated=false
},
["btn_y_2.png"] = {
file=path,
x=2,y=90,
width=200,height=86,
rotated=false
},
["btn_y_1.png"] = {
file=path,
x=204,y=2,
width=200,height=86,
rotated=false
},
["btn_g_2.png"] = {
file=path,
x=204,y=90,
width=200,height=86,
rotated=false
},
["loading_icon.png"] = {
file=path,
x=406,y=2,
width=75,height=75,
rotated=false
},
["back.png"] = {
file=path,
x=483,y=2,
width=29,height=45,
rotated=false
},
["bg.png"] = {
file=path,
x=483,y=49,
width=20,height=20,
rotated=false
},
["top_bar.png"] = {
file=path,
x=505,y=49,
width=4,height=4,
rotated=false
},
}
return agency_pin_map
|
local CircleDrawSystem = class("CircleDrawSystem", System)
function CircleDrawSystem:draw()
for i, v in pairs(self.targets) do
local position = v:get("Position")
love.graphics.setColor(255, 150, 0)
love.graphics.circle("fill", position.x, position.y, 5, 100)
end
end
function CircleDrawSystem:requires()
return {"Position", "Physic", "IsCircle"}
end
return CircleDrawSystem
|
return {'kazak','kazakdraaien','kazakdraaier','kazakdraaierij','kazakkeerder','kazemat','kazen','kazer','kazerne','kazerneachtig','kazernecomplex','kazerneleven','kazernepoort','kazerneren','kazernering','kazernetaal','kazerneterrein','kazuifel','kazakkendraaier','kazach','kazachensteppe','kazachs','kazachstan','kazak','kazakkensteppe','kazaks','kazanlik','kazan','kaz','kazim','kazemier','kazen','kazakdraaiers','kazakken','kazematten','kazerneachtige','kazerneert','kazernement','kazernementen','kazernen','kazernes','kazernewoningen','kazers','kazuifels','kazakkeerders','kazerneerde','kazakkendraaiers','kaz','kazims','kazerneterreinen','kazernepoorten','kazachse','kazakse'}
|
-- This function converts the relative link to reference file
-- in the same documentation. Instead of `File <./file>`__ it
-- becomes :doc:`./file`. And if the link starts with // (for folder)
-- when exported from markdown2rst e.g it converts `File <.//file>`__
-- to :doc:`./file/index`
function Link(el)
if (string.find(el.target, "%.//")) then
return pandoc.RawInline("rst", ":doc:`" .. el.target .. "/index`")
end
if (string.find(el.target, "%./")) then
return pandoc.RawInline("rst", ":doc:`" .. el.target .. "`")
end
return el
end
-- Replace \ with \\
function RawInline(raw)
if (string.find(raw.text, "\\")) then
return pandoc.Str(raw.text:gsub("\\", "/"))
end
return raw
end
function Pandoc(doc)
local filename = string.match(PANDOC_STATE.output_file, "/(.*)")
for i in string.gmatch(filename, "[^.]+") do
filename = i
break
end
local hblocks = {}
local el = pandoc.Para("\n\n" ..
".. index::\n" ..
" single: " .. filename ..
"\n\n\n\n")
table.insert(hblocks, el)
for i,el in pairs(doc.blocks) do
table.insert(hblocks, el)
end
return pandoc.Pandoc(hblocks, doc.meta)
end
|
local function postPremiumImpression(network)
return network.postPremiumImpression()
end
return postPremiumImpression
|
---@return HTTP_S
function HTTP_S(...) end
---@class HTTP_S
local cls = HTTP_S()
---@return any
function cls:Unsubscribe(...) end
---@return any
function cls:Subscribe(...) end
---@return any
function cls:Request(...) end
---@return any
function cls:IsValid(...) end
---@return any
function cls:Super(...) end
|
if enemy_1.hp_percentage > 5 then
character_1:UseSkill(1)
character_1:UseSkill(2)
if enemy_1.hp_percentage > 50 then
character_1:UseSkill(3)
character_1:UseSkill(4)
end
character_2:UseSkill(1)
character_2:UseSkill(2)
character_2:UseSkill(3)
character_3:UseSkill(1)
character_3:UseSkill(2)
character_3:UseSkill(3)
character_4:UseSkill(1)
character_4:UseSkill(3)
end
if turn > 3 then
character_4:UseSkill(2)
Summon(6)
end
if enemy_1.hp_percentage < 45 then
Summon(4)
end
if character_1.hp_percentage < 30 then
UseSupportPotion()
end
if character_4.hp_percentage < 20 then
UseSupportPotion()
end
if character_3.hp_percentage < 20 then
UseSupportPotion()
end
if character_2.hp_percentage < 20 then
UseSupportPotion()
end
|
--[[
Autor:João Victor Oliveira Couto
Componente Curricular: Concorrência e Conectividade
Concluido em: 14/04/2018
Declaro que este código foi elaborado por mim de forma individual e não contém nenhum
trecho de código de outro colega ou de outro autor, tais como provindos de livros e
apostilas, e páginas ou documentos eletrônicos da Internet. Qualquer trecho de código
de outra autoria que não a minha está destacado com uma citação para o autor e a fonte
do código, e estou ciente que estes trechos não serão considerados para fins de avaliação.
--]]
local socket = require "socket" --import socket API
local Json = require "util.Json" --import Json API
local macadress = require "util.macAdress" --import macAdress function
local Sensor = {} --create Sesnor table (like a class)
function Sensor:new() --create new function to instance a new object
local self = {--create a local table to keep atributtes private
host; --store host for the server
port; --store port for the server
udp; --udp object to send informations
id; --sensor id
constructor = function(this) --constructor that initializes self atributtes
local file = io.open("config.snr", "r")
local config = {host = "192.168.43.250", port = 3031}
if(not file) then --create a config file if it not exists
file = io.open("config.snr", "w")
file:write(Json.encode(config)) --encode config table and write it in file
else
config = Json.decode(file:read("*all")) --if file exists, load all the file, decode and stores into config
end
file:close()
this.host = config.host
this.port = config.port
this.udp = assert(socket.udp()) --create udp object
this.id = macadress:findMac() --call C function to find computer MAC
end
}
self.constructor(self)
local sendInformations = function(message) --send informations to server with tcp
assert(self.udp:sendto(self.id .. "->" .. message .. "[=]:" .. os.date("%Y-%m-%d %H:%M:%S"), self.host, self.port))
--print(self.id .. "->" .. message .. "[=]:" .. os.date("%c"))
end
local getMAC = function() --returns the mac stored in the object
return self.id
end
return {--return the functions that will be visible for others objects
sendInformations = sendInformations,
getMAC = getMAC
}
end
return Sensor --return Sensor table with Sensor:new function
|
-----------------------------------------
-- ID: 5399
-- A. Rem. Fireflies
-- Transports the user out of Arrapago Remnants
-----------------------------------------
require("scripts/globals/teleports")
require("scripts/globals/status")
require("scripts/globals/zone")
-----------------------------------------
function onItemCheck(target)
if target:getZoneID() == tpz.zone.ARRAPAGO_REMNANTS then
return 0
end
return 56
end
function onItemUse(target)
target:addStatusEffectEx(tpz.effect.TELEPORT,0,tpz.teleport.id.A_REM,0,1)
end
|
choice = {"najviše", "najšire", "najuže", "najveće", "najniže", "najmanje"}
|
local function get_models_by_range(setName, condition, searchValue)
local cursor = '0'
local done = false;
local result = {}
local setNamePrefix = setName .. '*'
local value = tonumber(searchValue)
repeat
local scanResult = redis.call('SCAN', cursor, 'MATCH', setNamePrefix)
cursor = scanResult[1]
for k,v in pairs(scanResult[2]) do
local number = tonumber(split(v, ':')[5])
if type(number) == 'number' then
if condition == 'gt' then
if number > value then
local ids = redis.call('ZRANGE', v, 0, -1)
for x,y in pairs(ids) do
table.insert(result, y)
end
end
elseif condition == 'gte' then
if number >= value then
local ids = redis.call('ZRANGE', v, 0, -1)
for x,y in pairs(ids) do
table.insert(result, y)
end
end
elseif condition == 'lt' then
if number < value then
local ids = redis.call('ZRANGE', v, 0, -1)
for x,y in pairs(ids) do
table.insert(result, y)
end
end
else
if number <= value then
local ids = redis.call('ZRANGE', v, 0, -1)
for x,y in pairs(ids) do
table.insert(result, y)
end
end
end
end
end
if cursor == '0' then
done = true;
end
until done
return result
end
|
--[[
Lexical Tools - lua/autorun/server/lexical-tools.lua
Copyright 2020 Lex Robinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]] --
local L10N_FOLDER = "resource/localization/"
--- Finds and `resource.AddFile`s all localisation files for all available languages
--- @param name string @eg "foo.properties"
function resource.AddL10nFile(name)
local _, langFolders = file.Find(L10N_FOLDER .. "*", "GAME")
for _, folder in pairs(langFolders) do
local search = L10N_FOLDER .. folder .. "/" .. name
if file.Exists(search, "GAME") then
resource.AddFile(search)
end
end
end
hook.Add("Initialize", "Lexical Tools L10n", function()
resource.AddL10nFile("lexical_tools.properties")
end)
|
include("terms")
style =
{["off_color"] = "fff",
["on_color"] = "fff",
["line_color"] = "000",
["line_width"] = "1"};
colour_style =
{["off_color"] = "ff0",
["on_color"] = "ff0",
["line_color"] = "000",
["line_width"] = "1"};
brown_style =
{["off_color"] = "c90",
["on_color"] = "c90",
["line_color"] = "000",
["line_width"] = "1"};
red_line =
{["line_color"] = "f30",
["line_width"] = "6"};
blue_line =
{["line_color"] = "0cf",
["line_width"] = "3"};
dot_style = {["font_size"] = "40"}
text_style = {["font_size"] = "14"}
meas = "\(^\circ\)"
ch = math.random(2)
index = 1 --[[math.random(2)]]--
ind_h = math.random(11)
numb_h = ind_h
if (index == 2) then
numb_h = numb_h + 12
end
hour = name[3]
if (numb_h == 1 or numb_h == 21) then
hour = name[1]
end
if (numb_h > 1 and numb_h < 5) then
hour = name[2]
end
if (numb_h == 22 or numb_h == 23) then
hour = name[2]
end
ind_m = math.random(11)
numb_m = 5*ind_m
if (ch == 1) then
number = numb_m
ang = 30 * ind_m
else
number = ind_h
ang = 30 * ind_h
end
vreme = name[ch]
if (ch == 2) then
if (number == 1) then
vreme = name[4]
end
if (number > 4) then
vreme = name[3]
end
end
w = 5
ow = 10
ov = 15
wy = 100
oc = 150
cor = 0.02*wy
ad = cor * ind_m
if (ind_h>2 and ind_h < 9) then
xad = -ad
else
xad = ad
end
if (ind_h < 6) then
yad = ad
else
yad = -ad
end
--[[blue]]--
if (ind_m == 0) then
xm = 0
ym = -wy+2*ow
end
if (ind_m == 1) then
xm = wy/2-ow/5
ym = -wy+2*ow
end
if (ind_m == 2) then
xm = wy-ov
ym = -wy/2
end
if (ind_m == 3) then
xm = wy
ym = 0
end
if (ind_m == 4) then
xm = wy-ov
ym = wy/2-w
end
if (ind_m == 5) then
xm = wy/2-ow/5
ym = wy-2*ow
end
if (ind_m == 6) then
xm = 0
ym = wy-2*ow
end
if (ind_m == 7) then
xm = -wy/2+ow/5-2
ym = wy-2*ow
end
if (ind_m == 8) then
xm = -wy+ov
ym = wy/2-w
end
if (ind_m == 9) then
xm = -wy
ym = 0
end
if (ind_m == 10) then
xm = -wy+ov
ym = -wy/2+w
end
if (ind_m == 11) then
xm = -wy/2+ow/5-2
ym = -wy+2*ow
end
--[[red]]--
if (ind_h == 0) then
xh = 0
yh = -wy+2*ov
end
if (ind_h == 1) then
xh = wy/2-ov
yh = -wy+3*ov
end
if (ind_h == 2) then
xh = wy-4*ow
yh = -wy/3
end
if (ind_h == 3) then
xh = wy-2*ov
yh = 0
end
if (ind_h == 4) then
xh = wy-4*ow
yh = wy/3
end
if (ind_h == 5) then
xh = wy/2-ov
yh = wy-3*ov
end
if (ind_h == 6) then
xh = 0
yh = wy-2*ov
end
if (ind_h == 7) then
xh = -wy/2+ov
yh = wy-3*ov
end
if (ind_h == 8) then
xh = -wy+4*ow
yh = wy/3
end
if (ind_h == 9) then
xh = -wy+2*ov
yh = 0
end
if (ind_h == 10) then
xh = -wy+4*ow
yh = -wy/3
end
if (ind_h == 11) then
xh = -wy/2+ov
yh = -wy+3*ov
end
mycanvas = function()
lib.start_canvas(300, 300, "center")
lib.add_circle (oc, 2*ow, ow, brown_style, true, false )
lib.add_ellipse(oc, 2*ov+ow, 2*ov, ov, colour_style, true, false )
lib.add_circle (oc, oc, wy+ow, colour_style, true, false )
lib.add_circle (oc, oc, wy, style, true, false )
lib.add_circle (oc-3*ov, 2*(oc-ov)-ow, ow, brown_style, true, false )
lib.add_circle (oc+3*ov, 2*(oc-ov)-ow, ow, brown_style, true, false )
lib.add_straight_path(oc, wy/2, {{0, ov}}, style, false, false)
lib.add_text(oc, wy/2+2*ow, "12", text_style, false, false)
lib.add_straight_path(oc+wy/2, 2*wy/3, {{-w, ow}}, style, false, false)
lib.add_text(oc+wy/2-ow, 2*wy/3+2*ow-w, "1", text_style, false, false)
lib.add_straight_path(oc+2*wy/3+2*ow, wy, {{-ow, w}}, style, false, false)
lib.add_text(oc+2*wy/3, wy+w, "2", text_style, false, false)
lib.add_straight_path(oc+wy-ov, oc, {{ ov, 0}}, style, false, false)
lib.add_text(oc+wy-2*ow, oc, "3", text_style, false, false)
lib.add_straight_path(oc+wy/2, oc+wy-ov, {{-w, -ow}}, style, false, false)
lib.add_text(oc+2*wy/3, oc+wy/2-ov, "4", text_style, false, false)
lib.add_straight_path(oc+2*wy/3+2*ow, oc+2*wy/3-ov-w, {{-ow, -w}}, style, false, false)
lib.add_text(oc+wy/2-ow, oc+2*wy/3, "5", text_style, false, false)
lib.add_straight_path(oc, oc+wy-ov, {{0, ov}}, style, false, false)
lib.add_text(oc, oc+wy-ov-ow, "6", text_style, false, false)
lib.add_straight_path(wy/2+ov-2, oc+2*wy/3-ov-w, {{ow, -w}}, style, false, false)
lib.add_text(wy+w, oc+2*wy/3, "7", text_style, false, false)
lib.add_straight_path(2*wy/3+3*ow, oc+wy-ov, {{w, -ow}}, style, false, false)
lib.add_text(2*wy/3+ov, oc+wy/2-ow, "8", text_style, false, false)
lib.add_straight_path(oc-wy, oc, {{ ov, 0}}, style, false, false)
lib.add_text(wy-2*ov, oc, "9", text_style, false, false)
lib.add_straight_path(2*wy/3+3*ow, oc-wy+ov, {{w, ow}}, style, false, false)
lib.add_text(2*wy/3+ov, wy+ow, "10", text_style, false, false)
lib.add_straight_path(wy/2+ov-2, oc-2*wy/3+ov+w, {{ow, w}}, style, false, false)
lib.add_text(wy+w, 2*wy/3+ov, "11", text_style, false, false)
lib.add_straight_path(oc, oc, {{xm, ym}}, blue_line, false, false)
lib.add_straight_path(oc, oc, {{xh+xad, yh+yad}}, red_line, false, false)
lib.add_text(oc, oc-ow, ".", dot_style, false, false)
lib.end_canvas()
end
|
--[[
*******************************************************
* LASP - LUA AREA SCRIPTING PROJECT *
* License *
*******************************************************
This software is provided as free and open source by the
staff of The Lua Area Scripting Project, in accordance with
the AGPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
Area - Azuremyst Isle - Mobs.lua by Justin
Area - Azuremyst Isle - MobsV2.lua by Yerney
-- ]]
--Blood Elf Bandit
function BloodElfBandit_OnCombat(Unit, Event)
Unit:RegisterEvent("BloodElfBandit_Spellname", 3000, 0)
Unit:RegisterEvent("BloodElfBandit_Spellnamq", 6000, 0)
end
function BloodElfBandit_Spellname(pUnit, Event)
pUnit:CastSpellOnTarget(14873, pUnit:GetClosestPlayer())
end
function BloodElfBandit_Spellnamq(pUnit, Event)
pUnit:CastSpellOnTarget(15691, pUnit:GetClosestPlayer())
end
function BloodElfBandit_OnDied(Unit, Event)
Unit:RemoveEvents()
end
function BloodElfBandit_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17591, 1, "BloodElfBandit_OnCombat")
RegisterUnitEvent(17591, 2, "BloodElfBandit_OnLeaveCombat")
RegisterUnitEvent(17591, 4, "BloodElfBandit_OnDied")
--Abberant Owlbeast
function AbberantOwlBeast_OnCombat(Unit, Event)
Unit:RegisterEvent("AbberantOwlBeast_Spellname", 12000, 0)
end
function AbberantOwlBeast_Spellname(pUnit, Event)
pUnit:FullCastSpellOnTarget(31270, pUnit:GetClosestPlayer())
end
function AbberantOwlBeast_OnDied(Unit, Event)
Unit:RemoveEvents()
end
function AbberantOwlBeast_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17187, 1, "AbberantOwlBeast_OnCombat")
RegisterUnitEvent(17187, 2, "AbberantOwlBeast_OnLeaveCombat")
RegisterUnitEvent(17187, 4, "AbberantOwlBeast_OnDied")
--Blood Elf Scout
function BloodElfScout_OnCombat(Unit, Event)
Unit:SendChatMessage(12, 0, "We won't allow you to leave this valley!")
Unit:RegisterEvent("BloodElfScout_Spellname", 12000, 0)
end
function BloodElfScout_Spellname(pUnit, Event)
pUnit:CastSpellOnTarget(25602, pUnit:GetRandomPlayer(0))
end
function BloodElfScout_OnDied(Unit, Event)
Unit:RemoveEvents()
end
function BloodElfScout_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(16521, 1, "BloodElfScout_OnCombat")
RegisterUnitEvent(16521, 2, "BloodElfScout_OnLeaveCombat")
RegisterUnitEvent(16521, 4, "BloodElfScout_OnDied")
--Chieftain
function Chieftain_OnCombat(Unit, Event)
Unit:SendChatMessage(12, 0, "We won't allow you to leave this valley!")
Unit:RegisterEvent("Chieftain_Spellname", 9000, 0)
Unit:RegisterEvent("Chieftain_enrage", 16000, 1)
end
function Chieftain_Spellname(pUnit, Event)
pUnit:CastSpellOnTarget(13446, pUnit:GetClosestPlayer())
end
function Chieftain_enrage(pUnit, Event)
pUnit:CastSpell(18501)
end
function Chieftain_OnDied(Unit, Event)
Unit:RemoveEvents()
end
function Chieftain_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17448, 1, "Chieftain_OnCombat")
RegisterUnitEvent(17448, 2, "Chieftain_OnLeaveCombat")
RegisterUnitEvent(17448, 4, "Chieftain_OnDied")
--Hauteur
function Hauteur_OnCombat(Unit, Event)
Unit:RegisterEvent("Hauteur_Spellname", 12000, 1)
Unit:RegisterEvent("Hauteur_enrage", 6000, 1)
end
function Hauteur_Spellname(pUnit, Event)
pUnit:CastSpellOnTarget(8050, pUnit:GetClosestPlayer())
end
function Hauteur_enrage(pUnit, Event)
pUnit:CastSpell(134)
end
function Hauteur_OnDied(Unit, Event) --F3--
Unit:RemoveEvents()
end
function Hauteur_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17206, 1, "Hauteur_OnCombat")
RegisterUnitEvent(17206, 2, "Hauteur_OnLeaveCombat")
RegisterUnitEvent(17206, 4, "Hauteur_OnDied")
--Ravager Specimen
function RavagerSpecimen_OnCombat(Unit, Event)
Unit:RegisterEvent("RavagerSpecimen_Spellname", 4000, 0)
end
function RavagerSpecimen_Spellname(pUnit, Event)
pUnit:CastSpellOnTarget(13443, pUnit:GetClosestPlayer())
end
function RavagerSpecimen_OnDied(Unit, Event)
Unit:RemoveEvents()
end
function RavagerSpecimen_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17199, 1, "RavagerSpecimen_OnCombat")
RegisterUnitEvent(17199, 2, "RavagerSpecimen_OnLeaveCombat")
RegisterUnitEvent(17199, 4, "RavagerSpecimen_OnDied")
-- BristleLimb WindCaller
function BristleLimbWindCaller_OnCombat(Unit, Event)
Unit:RegisterEvent("BristleLimbWindCaller_Reju", 1000, 0)
Unit:RegisterEvent("BristleLimbWindCaller_WindShock", 7000, 1)
end
function BristleLimbWindCaller_Reju(Unit, Event)
if Unit:GetHealthPct() < 15 then
Unit:CastSpell(32131)
end
end
function BristleLimbWindCaller_WindShock(pUnit, Event)
pUnit:FullCastSpellOnTarget(31272, pUnit:GetClosestPlayer())
end
function BristleLimbWindCaller_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function BristleLimbWindCaller_OnDead(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17184, 1, "BristleLimbWindCaller_OnCombat")
RegisterUnitEvent(17184, 2, "BristleLimbWindCaller_OnLeaveCombat")
RegisterUnitEvent(17184, 4, "BristleLimbWindCaller_OnDead")
-- WrathScaleMyrmidon
function WrathScaleMyrmidon_OnCombat(Unit, Event)
Unit:RegisterEvent("WrathScaleMyrmidon_Strike", 5000, 0)
end
function WrathScaleMyrmidon_Strike(pUnit, Event)
pUnit:FullCastSpellOnTarget(31272, pUnit:GetClosestPlayer())
end
function WrathScaleMyrmidon_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function WrathScaleMyrmidon_OnDead(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17194, 1, "WrathScaleMyrmidon_OnCombat")
RegisterUnitEvent(17194, 2, "WrathScaleMyrmidon_OnLeaveCombat")
RegisterUnitEvent(17194, 4, "WrathScaleMyrmidon_OnDead")
-- WrathScaleNage
function WrathScaleNage_OnCombat(Unit, Event)
Unit:RegisterEvent("WrathScaleNage_Strike", 12000, 1)
end
function WrathScaleNage_Strike(pUnit, Event)
pUnit:FullCastSpellOnTarget(9080, pUnit:GetClosestPlayer())
end
function WrathScaleNage_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function WrathScaleNage_OnDead(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17193, 1, "WrathScaleNage_OnCombat")
RegisterUnitEvent(17193, 2, "WrathScaleNage_OnLeaveCombat")
RegisterUnitEvent(17193, 4, "WrathScaleNage_OnDead")
-- WrathScaleSiren
function WrathScaleSiren_OnCombat(Unit, Event)
Unit:RegisterEvent("WrathScaleSiren_Scream", 12000, 1)
end
function WrathScaleSiren_Scream(pUnit, Event)
pUnit:CastSpell(31273)
end
function WrathScaleSiren_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function WrathScaleSiren_OnDead(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17195, 1, "WrathScaleSiren_OnCombat")
RegisterUnitEvent(17195, 2, "WrathScaleSiren_OnLeaveCombat")
RegisterUnitEvent(17195, 4, "WrathScaleSiren_OnDead")
-- Injured Draenei
function InjuredDraenei_OnSpawn(pUnit, event)
InjuredDraeneiChance = math.random(1, 2)
if (InjuredDraeneiChance == 1) then
pUnit:SetStandState(3)
end
if (InjuredDraeneiChance == 2) then
pUnit:SetStandState(1)
pUnit:SetCombatCapable(0)
end
end
RegisterUnitEvent(16971, 6, "InjuredDraenei_OnSpawn")
-- DraeneiSurvivor
function DraeneiSurvivor_OnSpawn(pUnit, event)
SurvivorDraeneiChance = math.random(1, 3)
if (SurvivorDraeneiChance == 1) then
pUnit:SetStandState(3)
end
if (SurvivorDraeneiChance == 2) then
pUnit:CastSpell(28630)
pUnit:SetStandState(1)
end
if (SurvivorDraeneiChance == 3) then
pUnit:CastSpell(28630)
pUnit:SetCombatCapable(0)
end
end
RegisterUnitEvent(16483, 6, "DraeneiSurvivor_OnSpawn")
|
module("luci.controller.dnsforwarder", package.seeall)
function index()
if not nixio.fs.access("/etc/config/dnsforwarder") then
return
end
local page = entry({"admin", "services", "dnsforwarder"},alias("admin", "services", "dnsforwarder","general"),_("Dnsforwarder"))
page.dependent = true
page.acl_depends = { "luci-app-dnsforwarder" }
entry({"admin", "services", "dnsforwarder","general"}, cbi("dnsforwarder/general"),_("General"),10).leaf = true
entry({"admin", "services", "dnsforwarder","log"}, cbi("dnsforwarder/log"),_("LOG"),30).leaf = true
end
|
-- This file is subject to copyright - contact swampservers@gmail.com for more information.
-- INSTALL: CINEMA
CoinFlips = CoinFlips or {}
RegisterChatCommand({'coin', 'coinflip'}, function(ply, arg)
local t = string.Explode(" ", arg)
local p = tonumber(t[#t])
p = (p ~= nil and math.floor(p) or nil)
if t[1]:lower() == "accept" and p ~= nil then
checkCoinFlipRequest(ply, p)
return
end
if p == nil then
if t[1]:lower() == "accept" then
ply:ChatPrint("[orange]!coinflip accept [confirm number of points]")
else
ply:ChatPrint("[orange]!coinflip player points")
end
else
table.remove(t)
local to, c = PlyCount(string.Implode(" ", t))
if c == 1 then
if ply == to then
ply:ChatPrint("[red]You can't coinflip yourself!")
elseif p >= 1000 then
-- minimum 1000 point coinflip
initCoinFlip(ply, to, p)
else
ply:ChatPrint("[red]A coinflip must be a minimum of 1000 points.")
end
else
ply:ChatPrint("[red]Player " .. string.Implode(" ", t) .. " not found.")
end
end
end, {
global = true,
throttle = true
})
timer.Create("CoinFlip", 1, 0, function()
local NewCoinFlips = {}
for fromID, j in pairs(CoinFlips) do
if ((j[3] + 30) <= CurTime()) then
local fromPlayer = player.GetBySteamID(fromID)
local toPlayer = player.GetBySteamID(j[1])
-- This whole nonsense is because I want to show the from/to's name if possible, but otherwise show a different message.
if (fromPlayer and toPlayer) then
fromPlayer:ChatPrint("[edgy]" .. toPlayer:Nick() .. "[orange] doesn't want to play. Try again later.")
toPlayer:ChatPrint("[orange]You missed out on a coinflip from [edgy]" .. fromPlayer:Nick() .. "[orange].")
elseif (not fromPlayer and toPlayer) then
toPlayer:ChatPrint("[orange]You missed out on a coinflip.")
elseif (fromPlayer and not toPlayer) then
fromPlayer:ChatPrint("[red]The player you requested a coinflip to has left. Try again later.")
end
CoinFlips[fromID] = nil
else
NewCoinFlips[fromID] = j
end
end
CoinFlips = NewCoinFlips
end)
function initCoinFlip(ply, target, amount)
if ply:SS_HasPoints(amount) and CoinFlips[ply:SteamID()] == nil then
ply:ChatPrint("[orange]" .. target:Nick() .. " is receiving your coinflip request.")
target:ChatPrint("[orange]" .. ply:Nick() .. " is sending you a coinflip request for [rainbow]" .. string.Comma(amount) .. "[orange]. Say !coinflip accept [confirm number of points] to accept.")
CoinFlips[ply:SteamID()] = {target:SteamID(), amount, CurTime()}
elseif CoinFlips[ply:SteamID()] ~= nil then
ply:ChatPrint("[red]You already have a coinflip in progress.")
elseif not ply:SS_HasPoints(amount) then
ply:ChatPrint("[red]You don't have enough points.")
end
end
function checkCoinFlipRequest(toPlayer, points)
for fromID, j in pairs(CoinFlips) do
if j[1] == toPlayer:SteamID() and j[2] == points then
-- Coinflip Request Found
finishCoinFlip(fromID, toPlayer)
return
end
end
toPlayer:ChatPrint("[red]You don't have a coinflip request for that amount!")
toPlayer:ChatPrint("[orange]COINFLIPS:")
local index = 1
for fromID, j in pairs(CoinFlips) do
if j[1] == toPlayer:SteamID() then
local fromPlayer = player.GetBySteamID(fromID)
if fromPlayer then
toPlayer:ChatPrint("[orange](" .. index .. ") [gold]" .. string.Comma(j[2]) .. "[orange] from [edgy]" .. fromPlayer:Nick())
end
index = index + 1
end
end
end
function finishCoinFlip(fromID, toPlayer)
local fromPlayer = player.GetBySteamID(fromID)
local amount = CoinFlips[fromID][2]
if (not fromPlayer) then
CoinFlips[fromID] = nil -- Remove request from CoinFlip because initiator left the server
toPlayer:ChatPrint("[red]The initiator left, coinflip cancelled.")
elseif fromPlayer:SS_HasPoints(amount) and toPlayer:SS_HasPoints(amount) then
-- Final Check, make sure they have funds still
CoinFlips[fromID] = nil
local heads = math.random() < 0.5 -- the "request from" player is always Heads.
BotSayGlobal("[edgy]" .. fromPlayer:Nick() .. "[fbc] flipped a coin worth [rainbow]" .. string.Comma((amount * 2)) .. "[fbc] against [gold]" .. toPlayer:Nick() .. "[fbc] and [rainbow]" .. (heads and "Won" or "Lost") .. "[fbc]!")
local fromcol = heads and "green" or "edgy"
fromPlayer:ChatPrint("[" .. fromcol .. "]You " .. (heads and "won" or "lost") .. " [gold]" .. string.Comma(amount) .. "[" .. fromcol .. "] points.")
local tocol = heads and "edgy" or "green"
toPlayer:ChatPrint("[" .. tocol .. "]You " .. (heads and "lost" or "won") .. " [gold]" .. string.Comma(amount) .. "[" .. tocol .. "] points.")
-- Instead of taking the amount away from both and then giving the winner the amount x 2, simply remove/add here
if heads then
toPlayer:SS_TakePoints(amount)
fromPlayer:SS_GivePoints(amount) --math.floor(amount*0.99))
else
fromPlayer:SS_TakePoints(amount)
toPlayer:SS_GivePoints(amount) --math.floor(amount*0.99))
end
else
CoinFlips[fromID] = nil
toPlayer:ChatPrint("[red]ERROR: No points have been taken. Coinflip cancelled.")
fromPlayer:ChatPrint("[red]ERROR: No points have been taken. Coinflip cancelled.")
end
end
|
require "import"
import "android.widget.*"
import "android.view.*"
import "com.androlua.*"
import "android.app.*"
import "autotheme"
activity.setTheme(autotheme())
activity.setTitle("Lua参考手册")
items={"目录","返回",}
function onCreateOptionsMenu(menu)
for k,v in ipairs(items) do
m=menu.add(v)
m.setShowAsActionFlags(1)
end
end
function onMenuItemSelected(id,item)
func[item.getTitle()]()
end
func={}
func["目录"]=function()
doc_web.loadUrl("file://"..activity.getLuaDir().."/luadoc/contents.html#contents")
end
func["返回"]=function()
--luajava.clear(doc_web)
activity.finish()
end
doc_web=LuaWebView(activity)
doc_web.loadUrl("file://"..activity.getLuaDir().."/luadoc/manual.html")
doc_web.setOnKeyListener(View.OnKeyListener{
onKey=function (view,keyCode,event)
if ((keyCode == event.KEYCODE_BACK) and view.canGoBack()) then
view.goBack();
return true;
end
return false
end
})
activity.setContentView(doc_web)
|
function twoSum(nums, target)
-- nums: Table[number]
-- target: number
m = {}
for k, v in pairs(nums) do
if nil == m[target - v] then
m[v] = k
else
return {k, m[target - v]}
end
end
return {-1, -1}
end
v = {2,7,11,15}
print(twoSum(v, 13))
|
require 'png'
function printProg(line, totalLine)
print(line .. " of " .. totalLine)
end
img = pngImage("Example.png", printProg)
print("Width: " .. img.width)
print("Height: " .. img.height)
print("Depth: " .. img.depth)
print("Color of pixel (10, 10): " .. img:getPixel(10,10):format())
|
-- Tests for alpha_beta_pruning.lua
local ABP = require 'alpha_beta_pruning'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Testing ABP', function()
local tree = require 'handlers.tree_handler'
local t = tree()
t:addNode('A',nil,0)
t:addNode('B','A',0)
t:addNode('C','A',0)
t:addNode('D','A',0)
t:addNode('E','B',4)
t:addNode('F','B',12)
t:addNode('G','B',7)
t:addNode('H','C',10)
t:addNode('I','C',5)
t:addNode('J','C',6)
t:addNode('K','D',1)
t:addNode('L','D',2)
t:addNode('M','D',3)
local head = t:getNode('A')
assert(ABP(head, t, 3) == 5)
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
|
--[[
--MIT License
--
--Copyright (c) 2019 manilarome
--Copyright (c) 2020 Tom Meyers
--
--Permission is hereby granted, free of charge, to any person obtaining a copy
--of this software and associated documentation files (the "Software"), to deal
--in the Software without restriction, including without limitation the rights
--to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
--copies of the Software, and to permit persons to whom the Software is
--furnished to do so, subject to the following conditions:
--
--The above copyright notice and this permission notice shall be included in all
--copies or substantial portions of the Software.
--
--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
--IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
--FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
--AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
--LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
--OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
--SOFTWARE.
]]
-- This profile should run in O(n) times
require("lib-tde.luapath")
local i18n = require("lib-tde.i18n")
i18n.init("en")
i18n.set_system_language("nl")
-- do a lot of translations
for _ = 1, 50000 do
i18n.translate("wireless")
i18n.translate("OS Name")
end
|
-- https://github.com/ImagicTheCat/ljuv
-- MIT license (see LICENSE or src/ljuv.lua)
-- FFI binding: libuv 1.42.0
local ffi = require("ffi")
if ffi.os == "Windows" then
if ffi.abi("64bit") then ffi.cdef("typedef UINT_PTR uint64_t;")
else ffi.cdef("typedef UINT_PTR unsigned int;") end
--
ffi.cdef[[
typedef unsigned long ULONG
typedef struct uv_buf_t {
ULONG len;
char* base;
} uv_buf_t;
typedef int uv_file;
typedef void *PVOID;
typedef PVOID HANDLE;
typedef UINT_PTR SOCKET;
typedef SOCKET uv_os_sock_t;
typedef HANDLE uv_os_fd_t;
typedef HANDLE HINSTANCE;
typedef HINSTANCE HMODULE;
typedef struct {
HMODULE handle;
char* errmsg;
} uv_lib_t;
]]
else
ffi.cdef[[
typedef struct uv_buf_t {
char* base;
size_t len;
} uv_buf_t;
typedef int uv_file;
typedef int uv_os_sock_t;
typedef int uv_os_fd_t;
typedef struct {
void* handle;
char* errmsg;
} uv_lib_t;
]]
end
ffi.cdef[[
typedef enum {
UV_E2BIG = (-(7)), UV_EACCES = (-(13)), UV_EADDRINUSE = (-(98)), UV_EADDRNOTAVAIL = (-(99)), UV_EAFNOSUPPORT = (-(97)), UV_EAGAIN = (-(11)), UV_EAI_ADDRFAMILY = (-3000), UV_EAI_AGAIN = (-3001), UV_EAI_BADFLAGS = (-3002), UV_EAI_BADHINTS = (-3013), UV_EAI_CANCELED = (-3003), UV_EAI_FAIL = (-3004), UV_EAI_FAMILY = (-3005), UV_EAI_MEMORY = (-3006), UV_EAI_NODATA = (-3007), UV_EAI_NONAME = (-3008), UV_EAI_OVERFLOW = (-3009), UV_EAI_PROTOCOL = (-3014), UV_EAI_SERVICE = (-3010), UV_EAI_SOCKTYPE = (-3011), UV_EALREADY = (-(114)), UV_EBADF = (-(9)), UV_EBUSY = (-(16)), UV_ECANCELED = (-(125)), UV_ECHARSET = (-4080), UV_ECONNABORTED = (-(103)), UV_ECONNREFUSED = (-(111)), UV_ECONNRESET = (-(104)), UV_EDESTADDRREQ = (-(89)), UV_EEXIST = (-(17)), UV_EFAULT = (-(14)), UV_EFBIG = (-(27)), UV_EHOSTUNREACH = (-(113)), UV_EINTR = (-(4)), UV_EINVAL = (-(22)), UV_EIO = (-(5)), UV_EISCONN = (-(106)), UV_EISDIR = (-(21)), UV_ELOOP = (-(40)), UV_EMFILE = (-(24)), UV_EMSGSIZE = (-(90)), UV_ENAMETOOLONG = (-(36)), UV_ENETDOWN = (-(100)), UV_ENETUNREACH = (-(101)), UV_ENFILE = (-(23)), UV_ENOBUFS = (-(105)), UV_ENODEV = (-(19)), UV_ENOENT = (-(2)), UV_ENOMEM = (-(12)), UV_ENONET = (-(64)), UV_ENOPROTOOPT = (-(92)), UV_ENOSPC = (-(28)), UV_ENOSYS = (-(38)), UV_ENOTCONN = (-(107)), UV_ENOTDIR = (-(20)), UV_ENOTEMPTY = (-(39)), UV_ENOTSOCK = (-(88)), UV_ENOTSUP = (-(95)), UV_EOVERFLOW = (-(75)), UV_EPERM = (-(1)), UV_EPIPE = (-(32)), UV_EPROTO = (-(71)), UV_EPROTONOSUPPORT = (-(93)), UV_EPROTOTYPE = (-(91)), UV_ERANGE = (-(34)), UV_EROFS = (-(30)), UV_ESHUTDOWN = (-(108)), UV_ESPIPE = (-(29)), UV_ESRCH = (-(3)), UV_ETIMEDOUT = (-(110)), UV_ETXTBSY = (-(26)), UV_EXDEV = (-(18)), UV_UNKNOWN = (-4094), UV_EOF = (-4095), UV_ENXIO = (-(6)), UV_EMLINK = (-(31)), UV_EHOSTDOWN = (-(112)), UV_EREMOTEIO = (-(121)), UV_ENOTTY = (-(25)), UV_EFTYPE = (-4028), UV_EILSEQ = (-(84)), UV_ESOCKTNOSUPPORT = (-(94)),
UV_ERRNO_MAX = (-4095) - 1
} uv_errno_t;
typedef enum {
UV_UNKNOWN_HANDLE = 0,
UV_ASYNC, UV_CHECK, UV_FS_EVENT, UV_FS_POLL, UV_HANDLE, UV_IDLE, UV_NAMED_PIPE, UV_POLL, UV_PREPARE, UV_PROCESS, UV_STREAM, UV_TCP, UV_TIMER, UV_TTY, UV_UDP, UV_SIGNAL,
UV_FILE,
UV_HANDLE_TYPE_MAX
} uv_handle_type;
typedef enum {
UV_UNKNOWN_REQ = 0,
UV_REQ, UV_CONNECT, UV_WRITE, UV_SHUTDOWN, UV_UDP_SEND, UV_FS, UV_WORK, UV_GETADDRINFO, UV_GETNAMEINFO, UV_RANDOM,
UV_REQ_TYPE_MAX
} uv_req_type;
typedef struct uv_loop_s uv_loop_t;
typedef struct uv_handle_s uv_handle_t;
typedef struct uv_dir_s uv_dir_t;
typedef struct uv_stream_s uv_stream_t;
typedef struct uv_tcp_s uv_tcp_t;
typedef struct uv_udp_s uv_udp_t;
typedef struct uv_pipe_s uv_pipe_t;
typedef struct uv_tty_s uv_tty_t;
typedef struct uv_poll_s uv_poll_t;
typedef struct uv_timer_s uv_timer_t;
typedef struct uv_prepare_s uv_prepare_t;
typedef struct uv_check_s uv_check_t;
typedef struct uv_idle_s uv_idle_t;
typedef struct uv_async_s uv_async_t;
typedef struct uv_process_s uv_process_t;
typedef struct uv_fs_event_s uv_fs_event_t;
typedef struct uv_fs_poll_s uv_fs_poll_t;
typedef struct uv_signal_s uv_signal_t;
typedef struct uv_req_s uv_req_t;
typedef struct uv_getaddrinfo_s uv_getaddrinfo_t;
typedef struct uv_getnameinfo_s uv_getnameinfo_t;
typedef struct uv_shutdown_s uv_shutdown_t;
typedef struct uv_write_s uv_write_t;
typedef struct uv_connect_s uv_connect_t;
typedef struct uv_udp_send_s uv_udp_send_t;
typedef struct uv_fs_s uv_fs_t;
typedef struct uv_work_s uv_work_t;
typedef struct uv_random_s uv_random_t;
typedef struct uv_env_item_s uv_env_item_t;
typedef struct uv_cpu_info_s uv_cpu_info_t;
typedef struct uv_interface_address_s uv_interface_address_t;
typedef struct uv_dirent_s uv_dirent_t;
typedef struct uv_passwd_s uv_passwd_t;
typedef struct uv_utsname_s uv_utsname_t;
typedef struct uv_statfs_s uv_statfs_t;
typedef enum {
UV_LOOP_BLOCK_SIGNAL = 0,
UV_METRICS_IDLE_TIME
} uv_loop_option;
typedef enum {
UV_RUN_DEFAULT = 0,
UV_RUN_ONCE,
UV_RUN_NOWAIT
} uv_run_mode;
unsigned int uv_version(void);
const char* uv_version_string(void);
typedef void* (*uv_malloc_func)(size_t size);
typedef void* (*uv_realloc_func)(void* ptr, size_t size);
typedef void* (*uv_calloc_func)(size_t count, size_t size);
typedef void (*uv_free_func)(void* ptr);
void uv_library_shutdown(void);
int uv_replace_allocator(uv_malloc_func malloc_func,
uv_realloc_func realloc_func,
uv_calloc_func calloc_func,
uv_free_func free_func);
uv_loop_t* uv_default_loop(void);
int uv_loop_init(uv_loop_t* loop);
int uv_loop_close(uv_loop_t* loop);
uv_loop_t* uv_loop_new(void);
void uv_loop_delete(uv_loop_t*);
size_t uv_loop_size(void);
int uv_loop_alive(const uv_loop_t* loop);
int uv_loop_configure(uv_loop_t* loop, uv_loop_option option, ...);
int uv_loop_fork(uv_loop_t* loop);
int uv_run(uv_loop_t*, uv_run_mode mode);
void uv_stop(uv_loop_t*);
void uv_ref(uv_handle_t*);
void uv_unref(uv_handle_t*);
int uv_has_ref(const uv_handle_t*);
void uv_update_time(uv_loop_t*);
uint64_t uv_now(const uv_loop_t*);
int uv_backend_fd(const uv_loop_t*);
int uv_backend_timeout(const uv_loop_t*);
typedef void (*uv_alloc_cb)(uv_handle_t* handle,
size_t suggested_size,
uv_buf_t* buf);
typedef void (*uv_read_cb)(uv_stream_t* stream,
ssize_t nread,
const uv_buf_t* buf);
typedef void (*uv_write_cb)(uv_write_t* req, int status);
typedef void (*uv_connect_cb)(uv_connect_t* req, int status);
typedef void (*uv_shutdown_cb)(uv_shutdown_t* req, int status);
typedef void (*uv_connection_cb)(uv_stream_t* server, int status);
typedef void (*uv_close_cb)(uv_handle_t* handle);
typedef void (*uv_poll_cb)(uv_poll_t* handle, int status, int events);
typedef void (*uv_timer_cb)(uv_timer_t* handle);
typedef void (*uv_async_cb)(uv_async_t* handle);
typedef void (*uv_prepare_cb)(uv_prepare_t* handle);
typedef void (*uv_check_cb)(uv_check_t* handle);
typedef void (*uv_idle_cb)(uv_idle_t* handle);
typedef void (*uv_exit_cb)(uv_process_t*, int64_t exit_status, int term_signal);
typedef void (*uv_walk_cb)(uv_handle_t* handle, void* arg);
typedef void (*uv_fs_cb)(uv_fs_t* req);
typedef void (*uv_work_cb)(uv_work_t* req);
typedef void (*uv_after_work_cb)(uv_work_t* req, int status);
typedef void (*uv_getaddrinfo_cb)(uv_getaddrinfo_t* req,
int status,
struct addrinfo* res);
typedef void (*uv_getnameinfo_cb)(uv_getnameinfo_t* req,
int status,
const char* hostname,
const char* service);
typedef void (*uv_random_cb)(uv_random_t* req,
int status,
void* buf,
size_t buflen);
typedef struct {
long tv_sec;
long tv_nsec;
} uv_timespec_t;
typedef struct {
uint64_t st_dev;
uint64_t st_mode;
uint64_t st_nlink;
uint64_t st_uid;
uint64_t st_gid;
uint64_t st_rdev;
uint64_t st_ino;
uint64_t st_size;
uint64_t st_blksize;
uint64_t st_blocks;
uint64_t st_flags;
uint64_t st_gen;
uv_timespec_t st_atim;
uv_timespec_t st_mtim;
uv_timespec_t st_ctim;
uv_timespec_t st_birthtim;
} uv_stat_t;
typedef void (*uv_fs_event_cb)(uv_fs_event_t* handle,
const char* filename,
int events,
int status);
typedef void (*uv_fs_poll_cb)(uv_fs_poll_t* handle,
int status,
const uv_stat_t* prev,
const uv_stat_t* curr);
typedef void (*uv_signal_cb)(uv_signal_t* handle, int signum);
typedef enum {
UV_LEAVE_GROUP = 0,
UV_JOIN_GROUP
} uv_membership;
int uv_translate_sys_error(int sys_errno);
const char* uv_strerror(int err);
char* uv_strerror_r(int err, char* buf, size_t buflen);
const char* uv_err_name(int err);
char* uv_err_name_r(int err, char* buf, size_t buflen);
int uv_shutdown(uv_shutdown_t* req,
uv_stream_t* handle,
uv_shutdown_cb cb);
struct uv_shutdown_s {
void* data; uv_req_type type; void* reserved[6];
uv_stream_t* handle;
uv_shutdown_cb cb;
};
struct uv_handle_s {
void* data; uv_loop_t* loop; uv_handle_type type; uv_close_cb close_cb; void* handle_queue[2]; union { int fd; void* reserved[4]; } u; uv_handle_t* next_closing; unsigned int flags;
};
size_t uv_handle_size(uv_handle_type type);
uv_handle_type uv_handle_get_type(const uv_handle_t* handle);
const char* uv_handle_type_name(uv_handle_type type);
void* uv_handle_get_data(const uv_handle_t* handle);
uv_loop_t* uv_handle_get_loop(const uv_handle_t* handle);
void uv_handle_set_data(uv_handle_t* handle, void* data);
size_t uv_req_size(uv_req_type type);
void* uv_req_get_data(const uv_req_t* req);
void uv_req_set_data(uv_req_t* req, void* data);
uv_req_type uv_req_get_type(const uv_req_t* req);
const char* uv_req_type_name(uv_req_type type);
int uv_is_active(const uv_handle_t* handle);
void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg);
void uv_close(uv_handle_t* handle, uv_close_cb close_cb);
int uv_send_buffer_size(uv_handle_t* handle, int* value);
int uv_recv_buffer_size(uv_handle_t* handle, int* value);
int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd);
uv_buf_t uv_buf_init(char* base, unsigned int len);
int uv_pipe(uv_file fds[2], int read_flags, int write_flags);
int uv_socketpair(int type,
int protocol,
uv_os_sock_t socket_vector[2],
int flags0,
int flags1);
size_t uv_stream_get_write_queue_size(const uv_stream_t* stream);
int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb);
int uv_accept(uv_stream_t* server, uv_stream_t* client);
int uv_read_start(uv_stream_t*,
uv_alloc_cb alloc_cb,
uv_read_cb read_cb);
int uv_read_stop(uv_stream_t*);
int uv_write(uv_write_t* req,
uv_stream_t* handle,
const uv_buf_t bufs[],
unsigned int nbufs,
uv_write_cb cb);
int uv_write2(uv_write_t* req,
uv_stream_t* handle,
const uv_buf_t bufs[],
unsigned int nbufs,
uv_stream_t* send_handle,
uv_write_cb cb);
int uv_try_write(uv_stream_t* handle,
const uv_buf_t bufs[],
unsigned int nbufs);
int uv_try_write2(uv_stream_t* handle,
const uv_buf_t bufs[],
unsigned int nbufs,
uv_stream_t* send_handle);
int uv_is_readable(const uv_stream_t* handle);
int uv_is_writable(const uv_stream_t* handle);
int uv_stream_set_blocking(uv_stream_t* handle, int blocking);
int uv_is_closing(const uv_handle_t* handle);
int uv_tcp_init(uv_loop_t*, uv_tcp_t* handle);
int uv_tcp_init_ex(uv_loop_t*, uv_tcp_t* handle, unsigned int flags);
int uv_tcp_open(uv_tcp_t* handle, uv_os_sock_t sock);
int uv_tcp_nodelay(uv_tcp_t* handle, int enable);
int uv_tcp_keepalive(uv_tcp_t* handle,
int enable,
unsigned int delay);
int uv_tcp_simultaneous_accepts(uv_tcp_t* handle, int enable);
enum uv_tcp_flags {
UV_TCP_IPV6ONLY = 1
};
int uv_tcp_bind(uv_tcp_t* handle,
const struct sockaddr* addr,
unsigned int flags);
int uv_tcp_getsockname(const uv_tcp_t* handle,
struct sockaddr* name,
int* namelen);
int uv_tcp_getpeername(const uv_tcp_t* handle,
struct sockaddr* name,
int* namelen);
int uv_tcp_close_reset(uv_tcp_t* handle, uv_close_cb close_cb);
int uv_tcp_connect(uv_connect_t* req,
uv_tcp_t* handle,
const struct sockaddr* addr,
uv_connect_cb cb);
enum uv_udp_flags {
UV_UDP_IPV6ONLY = 1,
UV_UDP_PARTIAL = 2,
UV_UDP_REUSEADDR = 4,
UV_UDP_MMSG_CHUNK = 8,
UV_UDP_MMSG_FREE = 16,
UV_UDP_LINUX_RECVERR = 32,
UV_UDP_RECVMMSG = 256
};
typedef void (*uv_udp_send_cb)(uv_udp_send_t* req, int status);
typedef void (*uv_udp_recv_cb)(uv_udp_t* handle,
ssize_t nread,
const uv_buf_t* buf,
const struct sockaddr* addr,
unsigned flags);
int uv_udp_init(uv_loop_t*, uv_udp_t* handle);
int uv_udp_init_ex(uv_loop_t*, uv_udp_t* handle, unsigned int flags);
int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock);
int uv_udp_bind(uv_udp_t* handle,
const struct sockaddr* addr,
unsigned int flags);
int uv_udp_connect(uv_udp_t* handle, const struct sockaddr* addr);
int uv_udp_getpeername(const uv_udp_t* handle,
struct sockaddr* name,
int* namelen);
int uv_udp_getsockname(const uv_udp_t* handle,
struct sockaddr* name,
int* namelen);
int uv_udp_set_membership(uv_udp_t* handle,
const char* multicast_addr,
const char* interface_addr,
uv_membership membership);
int uv_udp_set_source_membership(uv_udp_t* handle,
const char* multicast_addr,
const char* interface_addr,
const char* source_addr,
uv_membership membership);
int uv_udp_set_multicast_loop(uv_udp_t* handle, int on);
int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl);
int uv_udp_set_multicast_interface(uv_udp_t* handle,
const char* interface_addr);
int uv_udp_set_broadcast(uv_udp_t* handle, int on);
int uv_udp_set_ttl(uv_udp_t* handle, int ttl);
int uv_udp_send(uv_udp_send_t* req,
uv_udp_t* handle,
const uv_buf_t bufs[],
unsigned int nbufs,
const struct sockaddr* addr,
uv_udp_send_cb send_cb);
int uv_udp_try_send(uv_udp_t* handle,
const uv_buf_t bufs[],
unsigned int nbufs,
const struct sockaddr* addr);
int uv_udp_recv_start(uv_udp_t* handle,
uv_alloc_cb alloc_cb,
uv_udp_recv_cb recv_cb);
int uv_udp_using_recvmmsg(const uv_udp_t* handle);
int uv_udp_recv_stop(uv_udp_t* handle);
size_t uv_udp_get_send_queue_size(const uv_udp_t* handle);
size_t uv_udp_get_send_queue_count(const uv_udp_t* handle);
typedef enum {
UV_TTY_MODE_NORMAL,
UV_TTY_MODE_RAW,
UV_TTY_MODE_IO
} uv_tty_mode_t;
typedef enum {
UV_TTY_SUPPORTED,
UV_TTY_UNSUPPORTED
} uv_tty_vtermstate_t;
int uv_tty_init(uv_loop_t*, uv_tty_t*, uv_file fd, int readable);
int uv_tty_set_mode(uv_tty_t*, uv_tty_mode_t mode);
int uv_tty_reset_mode(void);
int uv_tty_get_winsize(uv_tty_t*, int* width, int* height);
void uv_tty_set_vterm_state(uv_tty_vtermstate_t state);
int uv_tty_get_vterm_state(uv_tty_vtermstate_t* state);
uv_handle_type uv_guess_handle(uv_file file);
int uv_pipe_init(uv_loop_t*, uv_pipe_t* handle, int ipc);
int uv_pipe_open(uv_pipe_t*, uv_file file);
int uv_pipe_bind(uv_pipe_t* handle, const char* name);
void uv_pipe_connect(uv_connect_t* req,
uv_pipe_t* handle,
const char* name,
uv_connect_cb cb);
int uv_pipe_getsockname(const uv_pipe_t* handle,
char* buffer,
size_t* size);
int uv_pipe_getpeername(const uv_pipe_t* handle,
char* buffer,
size_t* size);
void uv_pipe_pending_instances(uv_pipe_t* handle, int count);
int uv_pipe_pending_count(uv_pipe_t* handle);
uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle);
int uv_pipe_chmod(uv_pipe_t* handle, int flags);
enum uv_poll_event {
UV_READABLE = 1,
UV_WRITABLE = 2,
UV_DISCONNECT = 4,
UV_PRIORITIZED = 8
};
int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd);
int uv_poll_init_socket(uv_loop_t* loop,
uv_poll_t* handle,
uv_os_sock_t socket);
int uv_poll_start(uv_poll_t* handle, int events, uv_poll_cb cb);
int uv_poll_stop(uv_poll_t* handle);
int uv_prepare_init(uv_loop_t*, uv_prepare_t* prepare);
int uv_prepare_start(uv_prepare_t* prepare, uv_prepare_cb cb);
int uv_prepare_stop(uv_prepare_t* prepare);
int uv_check_init(uv_loop_t*, uv_check_t* check);
int uv_check_start(uv_check_t* check, uv_check_cb cb);
int uv_check_stop(uv_check_t* check);
int uv_idle_init(uv_loop_t*, uv_idle_t* idle);
int uv_idle_start(uv_idle_t* idle, uv_idle_cb cb);
int uv_idle_stop(uv_idle_t* idle);
int uv_async_init(uv_loop_t*,
uv_async_t* async,
uv_async_cb async_cb);
int uv_async_send(uv_async_t* async);
int uv_timer_init(uv_loop_t*, uv_timer_t* handle);
int uv_timer_start(uv_timer_t* handle,
uv_timer_cb cb,
uint64_t timeout,
uint64_t repeat);
int uv_timer_stop(uv_timer_t* handle);
int uv_timer_again(uv_timer_t* handle);
void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat);
uint64_t uv_timer_get_repeat(const uv_timer_t* handle);
uint64_t uv_timer_get_due_in(const uv_timer_t* handle);
int uv_getaddrinfo(uv_loop_t* loop,
uv_getaddrinfo_t* req,
uv_getaddrinfo_cb getaddrinfo_cb,
const char* node,
const char* service,
const struct addrinfo* hints);
void uv_freeaddrinfo(struct addrinfo* ai);
int uv_getnameinfo(uv_loop_t* loop,
uv_getnameinfo_t* req,
uv_getnameinfo_cb getnameinfo_cb,
const struct sockaddr* addr,
int flags);
typedef enum {
UV_IGNORE = 0x00,
UV_CREATE_PIPE = 0x01,
UV_INHERIT_FD = 0x02,
UV_INHERIT_STREAM = 0x04,
UV_READABLE_PIPE = 0x10,
UV_WRITABLE_PIPE = 0x20,
UV_NONBLOCK_PIPE = 0x40,
UV_OVERLAPPED_PIPE = 0x40
} uv_stdio_flags;
typedef struct uv_stdio_container_s {
uv_stdio_flags flags;
union {
uv_stream_t* stream;
int fd;
} data;
} uv_stdio_container_t;
/*
typedef struct uv_process_options_s {
uv_exit_cb exit_cb;
const char* file;
char** args;
char** env;
const char* cwd;
unsigned int flags;
int stdio_count;
uv_stdio_container_t* stdio;
uv_uid_t uid;
uv_gid_t gid;
} uv_process_options_t;
*/
enum uv_process_flags {
UV_PROCESS_SETUID = (1 << 0),
UV_PROCESS_SETGID = (1 << 1),
UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS = (1 << 2),
UV_PROCESS_DETACHED = (1 << 3),
UV_PROCESS_WINDOWS_HIDE = (1 << 4),
UV_PROCESS_WINDOWS_HIDE_CONSOLE = (1 << 5),
UV_PROCESS_WINDOWS_HIDE_GUI = (1 << 6)
};
/*
int uv_spawn(uv_loop_t* loop,
uv_process_t* handle,
const uv_process_options_t* options);
*/
int uv_process_kill(uv_process_t*, int signum);
int uv_kill(int pid, int signum);
// uv_pid_t uv_process_get_pid(const uv_process_t*);
int uv_queue_work(uv_loop_t* loop,
uv_work_t* req,
uv_work_cb work_cb,
uv_after_work_cb after_work_cb);
int uv_cancel(uv_req_t* req);
struct uv_cpu_times_s {
uint64_t user;
uint64_t nice;
uint64_t sys;
uint64_t idle;
uint64_t irq;
};
struct uv_cpu_info_s {
char* model;
int speed;
struct uv_cpu_times_s cpu_times;
};
/*
struct uv_interface_address_s {
char* name;
char phys_addr[6];
int is_internal;
union {
struct sockaddr_in address4;
struct sockaddr_in6 address6;
} address;
union {
struct sockaddr_in netmask4;
struct sockaddr_in6 netmask6;
} netmask;
};
*/
struct uv_passwd_s {
char* username;
long uid;
long gid;
char* shell;
char* homedir;
};
struct uv_utsname_s {
char sysname[256];
char release[256];
char version[256];
char machine[256];
};
struct uv_statfs_s {
uint64_t f_type;
uint64_t f_bsize;
uint64_t f_blocks;
uint64_t f_bfree;
uint64_t f_bavail;
uint64_t f_files;
uint64_t f_ffree;
uint64_t f_spare[4];
};
typedef enum {
UV_DIRENT_UNKNOWN,
UV_DIRENT_FILE,
UV_DIRENT_DIR,
UV_DIRENT_LINK,
UV_DIRENT_FIFO,
UV_DIRENT_SOCKET,
UV_DIRENT_CHAR,
UV_DIRENT_BLOCK
} uv_dirent_type_t;
struct uv_dirent_s {
const char* name;
uv_dirent_type_t type;
};
char** uv_setup_args(int argc, char** argv);
int uv_get_process_title(char* buffer, size_t size);
int uv_set_process_title(const char* title);
int uv_resident_set_memory(size_t* rss);
int uv_uptime(double* uptime);
uv_os_fd_t uv_get_osfhandle(int fd);
int uv_open_osfhandle(uv_os_fd_t os_fd);
typedef struct {
long tv_sec;
long tv_usec;
} uv_timeval_t;
typedef struct {
int64_t tv_sec;
int32_t tv_usec;
} uv_timeval64_t;
typedef struct {
uv_timeval_t ru_utime;
uv_timeval_t ru_stime;
uint64_t ru_maxrss;
uint64_t ru_ixrss;
uint64_t ru_idrss;
uint64_t ru_isrss;
uint64_t ru_minflt;
uint64_t ru_majflt;
uint64_t ru_nswap;
uint64_t ru_inblock;
uint64_t ru_oublock;
uint64_t ru_msgsnd;
uint64_t ru_msgrcv;
uint64_t ru_nsignals;
uint64_t ru_nvcsw;
uint64_t ru_nivcsw;
} uv_rusage_t;
int uv_getrusage(uv_rusage_t* rusage);
int uv_os_homedir(char* buffer, size_t* size);
int uv_os_tmpdir(char* buffer, size_t* size);
int uv_os_get_passwd(uv_passwd_t* pwd);
void uv_os_free_passwd(uv_passwd_t* pwd);
// uv_pid_t uv_os_getpid(void);
// uv_pid_t uv_os_getppid(void);
// int uv_os_getpriority(uv_pid_t pid, int* priority);
// int uv_os_setpriority(uv_pid_t pid, int priority);
int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count);
void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count);
/*
int uv_interface_addresses(uv_interface_address_t** addresses,
int* count);
void uv_free_interface_addresses(uv_interface_address_t* addresses,
int count);
*/
struct uv_env_item_s {
char* name;
char* value;
};
int uv_os_environ(uv_env_item_t** envitems, int* count);
void uv_os_free_environ(uv_env_item_t* envitems, int count);
int uv_os_getenv(const char* name, char* buffer, size_t* size);
int uv_os_setenv(const char* name, const char* value);
int uv_os_unsetenv(const char* name);
int uv_os_gethostname(char* buffer, size_t* size);
int uv_os_uname(uv_utsname_t* buffer);
uint64_t uv_metrics_idle_time(uv_loop_t* loop);
typedef enum {
UV_FS_UNKNOWN = -1,
UV_FS_CUSTOM,
UV_FS_OPEN,
UV_FS_CLOSE,
UV_FS_READ,
UV_FS_WRITE,
UV_FS_SENDFILE,
UV_FS_STAT,
UV_FS_LSTAT,
UV_FS_FSTAT,
UV_FS_FTRUNCATE,
UV_FS_UTIME,
UV_FS_FUTIME,
UV_FS_ACCESS,
UV_FS_CHMOD,
UV_FS_FCHMOD,
UV_FS_FSYNC,
UV_FS_FDATASYNC,
UV_FS_UNLINK,
UV_FS_RMDIR,
UV_FS_MKDIR,
UV_FS_MKDTEMP,
UV_FS_RENAME,
UV_FS_SCANDIR,
UV_FS_LINK,
UV_FS_SYMLINK,
UV_FS_READLINK,
UV_FS_CHOWN,
UV_FS_FCHOWN,
UV_FS_REALPATH,
UV_FS_COPYFILE,
UV_FS_LCHOWN,
UV_FS_OPENDIR,
UV_FS_READDIR,
UV_FS_CLOSEDIR,
UV_FS_STATFS,
UV_FS_MKSTEMP,
UV_FS_LUTIME
} uv_fs_type;
uv_fs_type uv_fs_get_type(const uv_fs_t*);
ssize_t uv_fs_get_result(const uv_fs_t*);
int uv_fs_get_system_error(const uv_fs_t*);
void* uv_fs_get_ptr(const uv_fs_t*);
const char* uv_fs_get_path(const uv_fs_t*);
uv_stat_t* uv_fs_get_statbuf(uv_fs_t*);
void uv_fs_req_cleanup(uv_fs_t* req);
int uv_fs_close(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
uv_fs_cb cb);
int uv_fs_open(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
int flags,
int mode,
uv_fs_cb cb);
int uv_fs_read(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
const uv_buf_t bufs[],
unsigned int nbufs,
int64_t offset,
uv_fs_cb cb);
int uv_fs_unlink(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
int uv_fs_write(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
const uv_buf_t bufs[],
unsigned int nbufs,
int64_t offset,
uv_fs_cb cb);
int uv_fs_copyfile(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
const char* new_path,
int flags,
uv_fs_cb cb);
int uv_fs_mkdir(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
int mode,
uv_fs_cb cb);
int uv_fs_mkdtemp(uv_loop_t* loop,
uv_fs_t* req,
const char* tpl,
uv_fs_cb cb);
int uv_fs_mkstemp(uv_loop_t* loop,
uv_fs_t* req,
const char* tpl,
uv_fs_cb cb);
int uv_fs_rmdir(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
int uv_fs_scandir(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
int flags,
uv_fs_cb cb);
int uv_fs_scandir_next(uv_fs_t* req,
uv_dirent_t* ent);
int uv_fs_opendir(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
int uv_fs_readdir(uv_loop_t* loop,
uv_fs_t* req,
uv_dir_t* dir,
uv_fs_cb cb);
int uv_fs_closedir(uv_loop_t* loop,
uv_fs_t* req,
uv_dir_t* dir,
uv_fs_cb cb);
int uv_fs_stat(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
int uv_fs_fstat(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
uv_fs_cb cb);
int uv_fs_rename(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
const char* new_path,
uv_fs_cb cb);
int uv_fs_fsync(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
uv_fs_cb cb);
int uv_fs_fdatasync(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
uv_fs_cb cb);
int uv_fs_ftruncate(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
int64_t offset,
uv_fs_cb cb);
int uv_fs_sendfile(uv_loop_t* loop,
uv_fs_t* req,
uv_file out_fd,
uv_file in_fd,
int64_t in_offset,
size_t length,
uv_fs_cb cb);
int uv_fs_access(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
int mode,
uv_fs_cb cb);
int uv_fs_chmod(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
int mode,
uv_fs_cb cb);
int uv_fs_utime(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
double atime,
double mtime,
uv_fs_cb cb);
int uv_fs_futime(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
double atime,
double mtime,
uv_fs_cb cb);
int uv_fs_lutime(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
double atime,
double mtime,
uv_fs_cb cb);
int uv_fs_lstat(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
int uv_fs_link(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
const char* new_path,
uv_fs_cb cb);
int uv_fs_symlink(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
const char* new_path,
int flags,
uv_fs_cb cb);
int uv_fs_readlink(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
int uv_fs_realpath(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
int uv_fs_fchmod(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
int mode,
uv_fs_cb cb);
/*
int uv_fs_chown(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_uid_t uid,
uv_gid_t gid,
uv_fs_cb cb);
int uv_fs_fchown(uv_loop_t* loop,
uv_fs_t* req,
uv_file file,
uv_uid_t uid,
uv_gid_t gid,
uv_fs_cb cb);
int uv_fs_lchown(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_uid_t uid,
uv_gid_t gid,
uv_fs_cb cb);
int uv_fs_statfs(uv_loop_t* loop,
uv_fs_t* req,
const char* path,
uv_fs_cb cb);
*/
enum uv_fs_event {
UV_RENAME = 1,
UV_CHANGE = 2
};
int uv_fs_poll_init(uv_loop_t* loop, uv_fs_poll_t* handle);
int uv_fs_poll_start(uv_fs_poll_t* handle,
uv_fs_poll_cb poll_cb,
const char* path,
unsigned int interval);
int uv_fs_poll_stop(uv_fs_poll_t* handle);
int uv_fs_poll_getpath(uv_fs_poll_t* handle,
char* buffer,
size_t* size);
int uv_signal_init(uv_loop_t* loop, uv_signal_t* handle);
int uv_signal_start(uv_signal_t* handle,
uv_signal_cb signal_cb,
int signum);
int uv_signal_start_oneshot(uv_signal_t* handle,
uv_signal_cb signal_cb,
int signum);
int uv_signal_stop(uv_signal_t* handle);
void uv_loadavg(double avg[3]);
enum uv_fs_event_flags {
UV_FS_EVENT_WATCH_ENTRY = 1,
UV_FS_EVENT_STAT = 2,
UV_FS_EVENT_RECURSIVE = 4
};
int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle);
int uv_fs_event_start(uv_fs_event_t* handle,
uv_fs_event_cb cb,
const char* path,
unsigned int flags);
int uv_fs_event_stop(uv_fs_event_t* handle);
int uv_fs_event_getpath(uv_fs_event_t* handle,
char* buffer,
size_t* size);
int uv_ip4_addr(const char* ip, int port, struct sockaddr_in* addr);
int uv_ip6_addr(const char* ip, int port, struct sockaddr_in6* addr);
int uv_ip4_name(const struct sockaddr_in* src, char* dst, size_t size);
int uv_ip6_name(const struct sockaddr_in6* src, char* dst, size_t size);
int uv_inet_ntop(int af, const void* src, char* dst, size_t size);
int uv_inet_pton(int af, const char* src, void* dst);
int uv_random(uv_loop_t* loop,
uv_random_t* req,
void *buf,
size_t buflen,
unsigned flags,
uv_random_cb cb);
int uv_if_indextoname(unsigned int ifindex,
char* buffer,
size_t* size);
int uv_if_indextoiid(unsigned int ifindex,
char* buffer,
size_t* size);
int uv_exepath(char* buffer, size_t* size);
int uv_cwd(char* buffer, size_t* size);
int uv_chdir(const char* dir);
uint64_t uv_get_free_memory(void);
uint64_t uv_get_total_memory(void);
uint64_t uv_get_constrained_memory(void);
uint64_t uv_hrtime(void);
void uv_sleep(unsigned int msec);
void uv_disable_stdio_inheritance(void);
int uv_dlopen(const char* filename, uv_lib_t* lib);
void uv_dlclose(uv_lib_t* lib);
int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr);
const char* uv_dlerror(const uv_lib_t* lib);
int uv_gettimeofday(uv_timeval64_t* tv);
/*
typedef void (*uv_thread_cb)(void* arg);
int uv_thread_create(uv_thread_t* tid, uv_thread_cb entry, void* arg);
typedef enum {
UV_THREAD_NO_FLAGS = 0x00,
UV_THREAD_HAS_STACK_SIZE = 0x01
} uv_thread_create_flags;
struct uv_thread_options_s {
unsigned int flags;
size_t stack_size;
};
typedef struct uv_thread_options_s uv_thread_options_t;
int uv_thread_create_ex(uv_thread_t* tid,
const uv_thread_options_t* params,
uv_thread_cb entry,
void* arg);
uv_thread_t uv_thread_self(void);
int uv_thread_join(uv_thread_t *tid);
int uv_thread_equal(const uv_thread_t* t1, const uv_thread_t* t2);
*/
void* uv_loop_get_data(const uv_loop_t*);
void uv_loop_set_data(uv_loop_t*, void* data);
]]
return ffi.load("uv")
|
-- luacheck: globals unpack vim
local iron = {
-- Will eventually be removed
config = require("iron.config"),
-- Most likely shouldn't be exposed here
ll = require("iron.lowlevel"),
core = require("iron.core"),
}
return iron
|
return {
include = function()
includedirs { "../vendor/yojimbo", "../vendor/netcode.io", "../vendor/reliable.io" }
links { 'mbedtls', 'sodium' }
end,
run = function()
language "C++"
kind "StaticLib"
add_dependencies { 'vendor:mbedtls', 'vendor:sodium' }
files {
"../vendor/yojimbo/yojimbo.h",
"../vendor/yojimbo/yojimbo.cpp",
"../vendor/yojimbo/tlsf/tlsf.h",
"../vendor/yojimbo/tlsf/tlsf.c",
"../vendor/netcode.io/netcode.c",
"../vendor/netcode.io/netcode.h",
"../vendor/reliable.io/reliable.c",
"../vendor/reliable.io/reliable.h"
}
end
}
|
local TeleportService = game:GetService("TeleportService")
return function (_, playerId, format)
format = format or "PlaceIdJobId"
local ok, _, errorText, placeId, jobId = pcall(function()
return TeleportService:GetPlayerPlaceInstanceAsync(playerId)
end)
if not ok or (errorText and #errorText > 0) then
if format == "PlaceIdJobId" then
return "0" .. " -"
elseif format == "PlaceId" then
return "0"
elseif format == "JobId" then
return "-"
end
end
if format == "PlaceIdJobId" then
return placeId .. " " .. jobId
elseif format == "PlaceId" then
return tostring(placeId)
elseif format == "JobId" then
return tostring(jobId)
end
end
|
include('shared.lua')
function ENT:Initialize()
end
function ENT:Draw()
end
|
-- helper function to insert two string as RawInline into a table
local function insertLatexEnvInline(tab, strBegin, strEnd)
table.insert(tab, 1, pandoc.RawInline("latex", strBegin))
table.insert(tab, #tab + 1, pandoc.RawInline("latex", strEnd))
return tab
end
-- handling of `::: center ... :::` ... (Div class)
function center(el)
if el.classes[1] == "center" then
return { pandoc.RawBlock("latex", "\\begin{center}"), el, pandoc.RawBlock("latex", "\\end{center}") }
end
end
-- remove inline notes: `[...]{.notes}` ... (Span class)
function inlineNotes(el)
if el.classes[1] == "notes" then
return {}
end
end
-- remove block notes: `::: notes ... :::` ... (Div class)
function blockNotes(el)
if el.classes[1] == "notes" then
return {}
end
end
-- remove inline slides span, return content: `[...]{.slides}` ... (Span class)
-- rationale: w/o this filter, the content would not be processed correctly
function inlineSlides(el)
if el.classes[1] == "slides" then
return el.content
end
end
-- remove block slides div, return content: `::: slides ... :::` ... (Div class)
-- rationale: w/o this filter, the content would not be processed correctly
function blockSlides(el)
if el.classes[1] == "slides" then
return el.content
end
end
-- handling of `[...]{.alert}` ... (Span class)
function alert(el)
if el.classes[1] == "alert" then
return insertLatexEnvInline(el.content, "\\alert{", "}")
end
end
-- handling of `[...]{.bsp}` ... (Span class)
function bsp(el)
if el.classes[1] == "bsp" then
return insertLatexEnvInline(el.content, "\\bsp{", "}")
end
end
-- handling of `[...]{.cbox}` ... (Span class)
function cbox(el)
if el.classes[1] == "cbox" then
return insertLatexEnvInline(el.content, "\\cboxbegin ", " \\cboxend")
end
end
-- handling of `[...]{.hinweis}` ... (Span class)
function hinweis(el)
if el.classes[1] == "hinweis" then
return insertLatexEnvInline(el.content, "\\hinweis{", "}")
end
end
-- handling of `[...]{.thema}` ... (Span class)
function thema(el)
if el.classes[1] == "thema" then
return insertLatexEnvInline(el.content, "\\thema{", "}")
end
end
-- handling of `[...]{.origin}` for inline images ... (Span class)
-- allows for some formatting inside the origin/author/license information
-- should follow the inline image in the same paragraph/line
function origin(el)
if el.classes[1] == "origin" then
return insertLatexEnvInline(el.content, "\\colorbox{origin}{\\begin{tiny} ", " \\end{tiny}}")
end
end
return { { Div = center }, { Span = inlineNotes, Div = blockNotes }, { Span = inlineSlides, Div = blockSlides }, { Span = alert }, { Span = bsp }, { Span = cbox }, { Span = hinweis }, { Span = thema }, { Span = origin } }
|
local Fader = {}
ShadowUF:RegisterModule(Fader, "fader", ShadowUF.L["Combat fader"])
local function faderUpdate(self, elapsed)
self.timeElapsed = self.timeElapsed + elapsed
if( self.timeElapsed >= self.fadeTime ) then
self.parent:SetAlpha(self.alphaEnd)
self:Hide()
if( self.fadeType == "in" ) then
self.parent:DisableRangeAlpha(false)
end
return
end
if( self.fadeType == "in" ) then
self.parent:SetAlpha((self.timeElapsed / self.fadeTime) * (self.alphaEnd - self.alphaStart) + self.alphaStart)
else
self.parent:SetAlpha(((self.fadeTime - self.timeElapsed) / self.fadeTime) * (self.alphaStart - self.alphaEnd) + self.alphaEnd)
end
end
local function startFading(self, type, alpha, speedyFade)
if( self.fader.fadeType == type ) then return end
if( type == "out" ) then
self:DisableRangeAlpha(true)
end
self.fader.fadeTime = speedyFade and 0.15 or type == "in" and 0.25 or type == "out" and 0.75
self.fader.fadeType = type
self.fader.timeElapsed = 0
self.fader.alphaEnd = alpha
self.fader.alphaStart = self:GetAlpha()
self.fader:Show()
end
function Fader:OnEnable(frame)
if( not frame.fader ) then
frame.fader = CreateFrame("Frame", nil, frame)
frame.fader.timeElapsed = 0
frame.fader.parent = frame
frame.fader:SetScript("OnUpdate", faderUpdate)
frame.fader:Hide()
end
frame:RegisterNormalEvent("PLAYER_REGEN_ENABLED", self, "Update")
frame:RegisterNormalEvent("PLAYER_REGEN_DISABLED", self, "Update")
frame:RegisterUpdateFunc(self, "Update")
if( InCombatLockdown() ) then
Fader:PLAYER_REGEN_DISABLED(frame, "PLAYER_REGEN_DISABLED")
else
Fader:PLAYER_REGEN_ENABLED(frame, "PLAYER_REGEN_ENABLED")
end
end
function Fader:OnLayoutApplied(frame)
if( frame.visibility.fader ) then
frame.fader.fadeType = nil
frame:DisableRangeAlpha(false)
end
end
function Fader:OnDisable(frame)
frame:UnregisterAll(self)
frame:SetAlpha(1.0)
if( frame.fader ) then
frame.fader.fadeType = nil
frame.fader:Hide()
end
end
-- While we're in combat, we don't care about the other events so we might as well unregister them
function Fader:PLAYER_REGEN_ENABLED(frame, event)
self:Update(frame, event)
frame:RegisterNormalEvent("PLAYER_TARGET_CHANGED", self, "Update")
frame:RegisterNormalEvent("UNIT_SPELLCAST_CHANNEL_START", self, "CastStart")
frame:RegisterNormalEvent("UNIT_SPELLCAST_CHANNEL_STOP", self, "CastStop")
frame:RegisterNormalEvent("UNIT_SPELLCAST_START", self, "CastStart")
frame:RegisterNormalEvent("UNIT_SPELLCAST_STOP", self, "CastStop")
frame:RegisterUnitEvent("UNIT_HEALTH", self, "Update")
frame:RegisterUnitEvent("UNIT_MANA", self, "Update")
frame:RegisterUnitEvent("UNIT_MAXHEALTH", self, "Update")
frame:RegisterUnitEvent("UNIT_MAXMANA", self, "Update")
end
function Fader:PLAYER_REGEN_DISABLED(frame, event)
self:Update(frame, event)
frame:UnregisterEvent("PLAYER_TARGET_CHANGED")
frame:UnregisterEvent("UNIT_SPELLCAST_CHANNEL_START")
frame:UnregisterEvent("UNIT_SPELLCAST_CHANNEL_STOP")
frame:UnregisterEvent("UNIT_SPELLCAST_START")
frame:UnregisterEvent("UNIT_SPELLCAST_STOP")
frame:UnregisterEvent("UNIT_HEALTH")
frame:UnregisterEvent("UNIT_MANA")
frame:UnregisterEvent("UNIT_MAXHEALTH")
frame:UnregisterEvent("UNIT_MAXMANA")
end
local activeCastID
function Fader:CastStart(frame, event, unit, spellName, spellRank, id)
if( unit ~= "player" or activeCastID == id ) then return end
activeCastID = id
frame.fader.playerCasting = true
self:Update(frame)
end
function Fader:CastStop(frame, event, unit, spellName, spellRank, id)
if( unit ~= "player" or activeCastID ~= id ) then return end
activeCastID = nil
frame.fader.playerCasting = nil
self:Update(frame)
end
function Fader:Update(frame, event)
-- In combat, fade back in
if( InCombatLockdown() or event == "PLAYER_REGEN_DISABLED" ) then
startFading(frame, "in", ShadowUF.db.profile.units[frame.unitType].fader.combatAlpha)
-- Player is casting, fade in
elseif( frame.fader.playerCasting ) then
startFading(frame, "in", ShadowUF.db.profile.units[frame.unitType].fader.combatAlpha, true)
-- Ether mana or energy is not at 100%, fade in
elseif( ( UnitPowerType(frame.unit) == 0 or UnitPowerType(frame.unit) == 3 ) and UnitPower(frame.unit) ~= UnitPowerMax(frame.unit) ) then
startFading(frame, "in", ShadowUF.db.profile.units[frame.unitType].fader.combatAlpha)
-- Health is not at max, fade in
elseif( UnitHealth(frame.unit) ~= UnitHealthMax(frame.unit) ) then
startFading(frame, "in", ShadowUF.db.profile.units[frame.unitType].fader.combatAlpha)
-- Targetting somebody, fade in
elseif( frame.unitType == "player" and UnitExists("target") ) then
startFading(frame, "in", ShadowUF.db.profile.units[frame.unitType].fader.combatAlpha)
-- Nothing else? Fade out!
else
startFading(frame, "out", ShadowUF.db.profile.units[frame.unitType].fader.inactiveAlpha)
end
end
|
setenv("APPS","/unknown/apps")
prepend_path("MANPATH","/usr/local/man:/usr/share/man:/usr/X11R6/man:/usr/kerberos/man:/usr/man")
setenv("OMP_NUM_THREADS","1")
|
uart.setup(1, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
uart.write(1, "nodemcu loaded\n")
station_cfg={}
station_cfg.ssid="nautilus" -- SSID of your WiFi network
station_cfg.pwd="xxxxxxxxxx" -- password of your WiFi network
station_cfg.auto=true
station_cfg.save=true
-- set your static network parameters here
net_ip = "10.10.10.110"
net_mask = "255.255.255.0"
net_gate = "10.10.10.1"
ntp_server = "pool.ntp.org"
timestring = 0
uarttimestring = 0
rtcGood = 0
-- UTCTZ = 5 -- your timezone (unix TZ) offset
sync_delay = 480 -- sync once per X mins (480 == 8hrs)
sync_att = sync_delay
local function check_int(n)
-- checking not float
if (n - math.floor(n) > 0) then
error("trying to use bitwise operation on non-integer!")
end
end
local function to_bits(n)
check_int(n)
if (n < 0) then
-- negative
return to_bits(bit.bnot(math.abs(n)) + 1)
end
-- to bits table
local tbl = {}
local cnt = 1
while (n > 0) do
local last = n % 2
if (last == 1) then
tbl[cnt] = 1
else
tbl[cnt] = 0
end
n = (n-last)/2
cnt = cnt + 1
end
return tbl
end
local function tbl_to_number(tbl)
local n = table.getn(tbl)
local rslt = 0
local power = 1
for i = 1, n do
rslt = rslt + tbl[i]*power
power = power*2
end
return rslt
end
local function expand(tbl_m, tbl_n)
local big = {}
local small = {}
if (table.getn(tbl_m) > table.getn(tbl_n)) then
big = tbl_m
small = tbl_n
else
big = tbl_n
small = tbl_m
end
-- expand small
for i = table.getn(small) + 1, table.getn(big) do
small[i] = 0
end
end
local function bit_xor(m, n)
local tbl_m = to_bits(m)
local tbl_n = to_bits(n)
expand(tbl_m, tbl_n)
local tbl = {}
local rslt = math.max(table.getn(tbl_m), table.getn(tbl_n))
for i = 1, rslt do
if (tbl_m[i] ~= tbl_n[i]) then
tbl[i] = 1
else
tbl[i] = 0
end
end
--table.foreach(tbl, print)
return tbl_to_number(tbl)
end
local function to_hex(n)
if (type(n) ~= "number") then
error("non-number type passed in.")
end
-- checking not float
if (n - math.floor(n) > 0) then
error("trying to apply bitwise operation on non-integer!")
end
if (n < 0) then
-- negative
n = bit.tobits(bit.bnot(math.abs(n)) + 1)
n = bit.tonumb(n)
end
hex_tbl = {'A', 'B', 'C', 'D', 'E', 'F'}
hex_str = ""
while (n ~= 0) do
last = n % 16
if (last < 10) then
hex_str = tostring(last) .. hex_str
else
hex_str = hex_tbl[last-10+1] .. hex_str
end
n = math.floor(n/16)
end
if (hex_str == "") then
hex_str = "0"
end
if (string.len(hex_str) < 2) then
return "0"..hex_str
else
return hex_str
end
end
function UpdateRtc()
local sec, usec = rtctime.get()
if (sec ~= 0) then
while (sec == rtctime.get()) do end
end
-- tm = rtctime.epoch2cal((rtctime.get()+1)+UTCTZ*3600)
tm = rtctime.epoch2cal(rtctime.get())
timestring = string.format("%d %04d-%02d-%02d %02d:%02d:%02d", tm["wday"], tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"])
if (tm["year"] >= 2000) then
tm["year"] = tm["year"] - 2000;
else
tm["year"] = 0;
end
uarttimestring = string.format("$GPRMC,%02d%02d%02d.00,A,,,,,,,%02d%02d%02d,,,*",
tm["hour"], tm["min"], tm["sec"], tm["day"], tm["mon"], tm["year"]);
local crc = 0
for i=2,string.len(uarttimestring)-1 do
crc = bit_xor(crc, string.byte(uarttimestring,i));
end
uarttimestring = uarttimestring..to_hex(crc).."\r\n"
if (rtcGood == 1) then
print(uarttimestring)
else
print("ntp not synced")
end
end
function PrintUart()
UpdateRtc()
if (rtcGood == 1) then
if (sync_att == sync_delay) then
uart.write(1, uarttimestring)
print("uart sync sent")
sync_att = 0
end
sync_att = sync_att + 1
end
end
wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
wifi.sta.setip({ip=net_ip,netmask=net_mask,gateway=net_gate})
print("ESP8266 mode is: " .. wifi.getmode())
print(wifi.sta.getip())
if (srv) then
srv:close()
srv=nil
end
srv=net.createServer(net.TCP, 4)
print("Server created on " .. wifi.sta.getip())
function receiver(sck, request)
local response = {}
-- if you're sending back HTML over HTTP you'll want something like this instead
-- local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}
response[#response + 1] = "HTTP/1.1 200 OK\r\n"
response[#response + 1] = "Content-type: text/html\r\n"
response[#response + 1] = "Connection: close\r\n\r\n"
response[#response + 1] = "<html><head>"
response[#response + 1] = '<title>Clock</title>'
response[#response + 1] = '<meta http-equiv="refresh" content="5">'
response[#response + 1] = "<style>"
response[#response + 1] = 'body {width:100% font-size:52px}'
response[#response + 1] = 'h1 {font-size:32px}'
response[#response + 1] = 'button {font-size:42pxheight:4emwidth:30%}'
response[#response + 1] = "</style>"
response[#response + 1] = "</head><body>"
response[#response + 1] = "<h1>Clock</h1>"
response[#response + 1] = '<div class="container">'
response[#response + 1] = "<p>Time RTC: ".. timestring .." </p>"
response[#response + 1] = "<p>NMEA: ".. uarttimestring .." </p>"
response[#response + 1] = "<p>sync: ".. rtcGood .." </p>"
response[#response + 1] = '</div>'
response[#response + 1] = "</body></html>"
-- sends and removes the first element from the 'response' table
local function send(localSocket)
if (#response > 0) then
localSocket:send(table.remove(response, 1))
else
localSocket:close()
response = nil
end
end
-- triggers the send() function again once the first chunk of data was sent
sck:on("sent", send)
send(sck)
end
srv:listen(80, function(conn)
conn:on("receive", receiver)
end)
function ntpSyncGood(sec, usec, server, info)
print('ntp synced', sec, usec, server)
offset_s = info.offset_s or 0
offset_us = info.offset_us or 0
delay_us = info.delay_us or 0
stratum = info.stratum or 0
leap = info.leap or 0
print("offset_s " .. offset_s)
print("offset_us " .. offset_us)
print("delay_us " .. delay_us )
print("stratum " .. stratum )
print("leap " .. leap)
rtcGood = 1
end
function ntpSyncFail()
print('failed!')
rtcGood = 0
end
print("starting sync")
-- sync time / repeat after 1000 sec
sntp.sync(ntp_server, ntpSyncGood, ntpSyncFail, 1 )
uartTimer = tmr.create()
uartTimer:register(10000, tmr.ALARM_AUTO, PrintUart)
uartTimer:interval(60000) -- Maximum value is 6870947 (1:54:30.947).
uartTimer:start()
|
local ffi = require("ffi")
--
-- Given a list of sections, and an RVA, lookup the section
-- that contains the specified relative virtual address
-- Return the found section, or nil if none found.
--
local function getEnclosingSection(sections, rva)
--print("==== getEnclosingSection: ", rva)
for secname, section in pairs(sections) do
-- Is the RVA within this section?
local pos = rva - section.VirtualAddress;
if pos >= 0 and pos < section.VirtualSize then
-- return section, and the calculated offset within the section
return section, pos
end
end
return false, "RVA not in a section";
end
-- There are many values within the file which are 'RVA' (Relative Virtual Address)
-- In order to translate this RVA into a file offset, we use the following
-- function.
local function fileOffsetFromRVA(sections, rva)
local section, pos = getEnclosingSection(sections, rva);
if not section then
return false, "section not found for rva";
end
local fileOffset = section.PointerToRawData + pos;
return fileOffset
end
--[[
Utility function for section object creation
]]
--
-- stringFromBuffer()
-- given a buffer and a length, return a lua string
-- the lua string will not include trailing null bytes
local function stringFromBuff(buff, size)
local truelen = size
for i=size-1,0,-1 do
if buff[i] == 0 then
truelen = truelen - 1
end
end
return ffi.string(buff, truelen)
end
local exports = {
getEnclosingSection = getEnclosingSection,
fileOffsetFromRVA = fileOffsetFromRVA,
stringFromBuff = stringFromBuff,
}
return exports
--[[
Definition of a section object. This is meant as a
simple convenience for sections within the PE file.
]]
--[[
local section_t = {}
local section_mt = {
__index = section_t;
}
function section_t.GetEnclosingSection(sections, rva)
--print("==== EnclosingSection: ", rva)
for secname, section in pairs(sections) do
-- Is the RVA within this section?
local pos = rva - section.VirtualAddress;
if pos >= 0 and pos < section.VirtualSize then
-- return section, and the calculated offset within the section
return section, pos
end
end
return false;
end
-- There are many values within the file which are 'RVA' (Relative Virtual Address)
-- In order to translate this RVA into a file offset, we use the following
-- function.
function section_t.fileOffsetFromRVA(self, rva)
local section, pos = self:GetEnclosingSection(rva);
if not section then
return false, "section not found for rva";
end
local fileOffset = section.PointerToRawData + pos;
return fileOffset
end
--]]
|
local public_module = require("app.public.util.public_module")
local equip_data = require("app.public.data.equip_data")
local global_define = require("app.public.global.global_define")
local body_data = class("body_data")
function body_data:ctor()
public_module.append_table(self, "app.public.data.base_data")
self:init_base_data()
self:init_real_base_data()
--特有属性
self.title = ""--称号
self.title_id = 0--称号id
self.sex = 1--性别1男2女3其他
--总属性
self.total_att = 0
self.total_def = 0
self.total_hp = 0
self.total_crit = 0--暴击率
self.total_dmg = 0--暴击伤害倍数
self.total_hit = 0--命中率
self.total_evd = 0--躲闪率
self.total_fire = 0--火
self.total_ice = 0--冰
self.total_electric = 0--电
self.total_voice = 0 --音
self.total_att_speed = 0 --攻击速度
self.total_weapon_cd = 1
self.equip = {}
self.buff = {}
end
function body_data:init_real_base_data()
self:set_meta_data("base_hit", 70)--基本命中
self:set_meta_data("base_evd", 20)--基本闪避
self:set_meta_data("base_crit", 10)--基本暴击率
self:set_meta_data("base_dmg", 2)--基本暴击伤害倍数
self:set_meta_data("base_hit_area", 10)--伤害浮动
end
function body_data:set_enemy_data(data)
for i, v in pairs(data) do
self:set_meta_data(i, v)
end
end
--equip_tag:装备标记
--equip_id:装备id,取消装备传nil即可
function body_data:set_equip(equip_type, equip_id)
if self.equip[equip_type] == equip_id then return end
if self:check_invalid_equip(equip_type, equip_id) then return end
if not self.equip[equip_type] then
self.equip[equip_type] = equip_data.new()
end
self:on_calculate_total_data()
end
function body_data:set_buff(buff_tag, is_on)
self.buff[buff_tag] = is_on
end
function body_data:on_calculate_total_data()
self.total_att = self.base_att
self.total_def = self.base_def
self.total_fire = self.base_fire
self.total_ice = self.base_ice
self.total_electric = self.base_electric
self.total_voice = self.base_voice
self.total_att_speed = self.base_att_speed
self.total_hp = self.base_hp
local _cur_weapon_cd = self.base_weapon_cd
for equip_tag, equip_data in pairs(self.equip) do
self.total_att = self.total_att + equip_data:get_meta_data("base_att")
self.total_def = self.total_def + equip_data:get_meta_data("base_def")
self.total_fire = self.total_fire + equip_data:get_meta_data("base_fire")
self.total_ice = self.total_ice + equip_data:get_meta_data("base_ice")
self.total_electric = self.total_electric + equip_data:get_meta_data("base_electric")
self.total_voice = self.total_voice + equip_data:get_meta_data("base_voice")
self.total_att_speed = self.total_att_speed + equip_data:get_meta_data("base_att_speed")
self.total_crit = self.total_crit + equip_data:get_meta_data("base_crit")
self.total_dmg = self.total_dmg + equip_data:get_meta_data("base_dmg")
self.total_hit = self.total_hit + equip_data:get_meta_data("base_hit")
self.total_evd = self.total_evd + equip_data:get_meta_data("base_evd")
self.total_hp = self.total_hp + equip_data:get_meta_data("base_hp")
if equip_data:is_weapon() then
_cur_weapon_cd = equip_data:get_weapon_cd()
end
end
self.total_weapon_cd = _cur_weapon_cd
end
--检测是否是无效的装备
function body_data:check_invalid_equip(equip_type, equip_id)
local _temp_type = math.floor(equip_id % 1000000 / 10000)
if _temp_type == equip_type then
return false
end
return true
end
--攻击间隔不能低于阈值
function body_data:get_attack_cd()
--武器的攻击间隔加成攻击速度的计算
local _cd = self.total_weapon_cd * 1000 / self.total_att_speed
if _cd < global_define.cd_min then
_cd = global_define.cd_min
end
return _cd
end
function body_data:get_hp()
return self.total_hp
end
return body_data
|
local mod = DBM:NewMod("BSMTrash", "DBM-Party-WoD", 2)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 13843 $"):sub(12, -3))
--mod:SetModelID(47785)
mod:SetZone()
mod.isTrashMod = true
mod:RegisterEvents(
"SPELL_AURA_APPLIED 164597 151548 151697 151965 151558 151581",
"SPELL_CAST_START 152298 151447 151545"
)
local specWarnCrush = mod:NewSpecialWarningDodge(151447, "Tank")
local specWarnCinderSplash = mod:NewSpecialWarningSpell(152298, nil, nil, nil, 2)
local specWarnRoar = mod:NewSpecialWarningInterrupt(151545, "-Healer")--Maybe healer need warning too, if interrupt gets off, healer can't heal for 5 seconds
local specWarnLavaBurst = mod:NewSpecialWarningInterrupt(151558, "-Healer")
local specWarnSuppressionField = mod:NewSpecialWarningInterrupt(151581, "-Healer")--Maybe healer need warning too, if interrupt gets off, healer can't heal for 5 seconds
local specWarnStoneBulwark = mod:NewSpecialWarningDispel(164597, "MagicDispeller")
local specWarnBloodRage = mod:NewSpecialWarningDispel(151548, "MagicDispeller")
local specWarnSubjugate = mod:NewSpecialWarningDispel(151697, "Healer")
local specWarnSlaversRage = mod:NewSpecialWarningDispel(151965, "RemoveEnrage")
mod:RemoveOption("HealthFrame")
local UnitExists, UnitGUID, UnitAffectingCombat = UnitExists, UnitGUID, UnitAffectingCombat
local function validWarning(GUID)
for uId in DBM:GetGroupMembers() do
local target = uId.."target"
if UnitExists(target) and UnitGUID(target) == GUID and UnitAffectingCombat(target) then return true end
end
return false
end
function mod:SPELL_AURA_APPLIED(args)
if not self.Options.Enabled or self:IsDifficulty("normal5") then return end
local spellId = args.spellId
if spellId == 164597 and not args:IsDestTypePlayer() then
specWarnStoneBulwark:Show(args.destName)
elseif spellId == 151548 and not args:IsDestTypePlayer() and validWarning(args.sourceGUID) then--Antispam
specWarnBloodRage:Show(args.destName)
elseif spellId == 151697 then
specWarnSubjugate:Show(args.destName)
elseif spellId == 151965 then
specWarnSlaversRage:Show(args.destName)
end
end
function mod:SPELL_CAST_START(args)
if not self.Options.Enabled or self:IsDifficulty("normal5") then return end
local spellId = args.spellId
if spellId == 152298 then
specWarnCinderSplash:Show()
elseif spellId == 151447 then
specWarnCrush:Show()
elseif spellId == 151545 and validWarning(args.sourceGUID) then--Antispam
specWarnRoar:Show(args.sourceName)
elseif spellId == 151558 and validWarning(args.sourceGUID) then
specWarnLavaBurst:Show(args.sourceName)
elseif spellId == 151581 then
specWarnSuppressionField:Show(args.sourceName)
end
end
|
local function loadDocument(nodes)
return {
type = "loadDocument",
nodes = nodes,
}
end
return loadDocument
|
object_tangible_wearables_cybernetic_s02_cybernetic_s02_legs = object_tangible_wearables_cybernetic_s02_shared_cybernetic_s02_legs:new {
}
ObjectTemplates:addTemplate(object_tangible_wearables_cybernetic_s02_cybernetic_s02_legs, "object/tangible/wearables/cybernetic/s02/cybernetic_s02_legs.iff")
|
if CreepPower == nil then
DebugPrint ( 'Creating new CreepPower object...' )
CreepPower = class({})
end
function CreepPower:GetPowerForMinute (minute)
local multFactor = 1
local ExponentialGrowthOnset = {
short = 40,
normal = 60,
long = 120
}
if minute == 0 then
return { 0, 1.0, 1.0, 1.0, 1.0, 1.0 * self.BootGoldFactor, 1.0 * self.numPlayersXPFactor}
end
if minute > ExponentialGrowthOnset[PointsManager:GetGameLength()] then
multFactor = 1.5 ^ (minute - ExponentialGrowthOnset[PointsManager:GetGameLength()])
end
return CreepPower:GetBasePowerForMinute(minute, multFactor)
end
function CreepPower:GetBasePowerForMinute (minute, multFactor)
if minute == 0 then
return { 0, 1.0, 1.0, 1.0, 1.0, 1.0 * self.BootGoldFactor, 1.0 * self.numPlayersXPFactor}
end
return {
minute, -- minute
(0 * ((minute / 100) ^ 4) - 0 * ((minute/100) ^ 3) + 30 * ((minute/100) ^ 2) + 3 * (minute/100)) + 1, -- hp
(0 * ((minute / 100) ^ 4) - 0 * ((minute/100) ^ 3) + 30 * ((minute/100) ^ 2) + 3 * (minute/100)) + 1, -- mana
(0 * ((minute / 100) ^ 4) - 0 * ((minute/100) ^ 3) + 60 * ((minute/100) ^ 2) + 6 * (minute/100)) + 1, -- damage
(0 * (minute / 26) ^ 2 + minute / 6) + 1, -- armor
((3 * minute ^ 2 - 5 * minute + 177)/177) * self.BootGoldFactor, -- gold
((9 * minute ^ 2 + 17 * minute + 607) / 607) * self.numPlayersXPFactor * multFactor -- xp
}
end
function CreepPower:Init ()
local maxTeamPlayerCount = 10 -- TODO: Make maxTeamPlayerCount based on values set in settings.lua (?)
self.numPlayersXPFactor = 1 -- PlayerResource:GetTeamPlayerCount() / maxTeamPlayerCount
self.BootGoldFactor = _G.BOOT_GOLD_FACTOR
end
|
while true do
wait(1)
for i,v in pairs(game.Players:GetChildren()) do
if v ~= game.Players.LocalPlayer then
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = v.Character.Head.CFrame * CFrame.new(0,0,.4)
mouse1click()
wait(0.1)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-7, 958, -36)
end
end
end
|
--[[
Copyright 2008-2016 João Cardoso
Sushi is distributed under the terms of the GNU General Public License (or the Lesser GPL).
This file is part of Sushi.
Sushi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Sushi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Sushi. If not, see <http://www.gnu.org/licenses/>.
--]]
local Group = MakeSushi(5, nil, 'MagicGroup', nil, nil, SushiGroup)
if not Group then
return
end
--[[ Constructor ]]--
function Group:OnCreate ()
SushiGroup.OnCreate (self)
self.Footer = self:CreateFontString(nil, nil, 'GameFontDisableSmall')
end
function Group:OnAcquire ()
SushiGroup.OnAcquire (self)
self:SetCall('UpdateChildren', self.CreateMagics)
self.Footer:SetPoint('BOTTOMRIGHT', -4, 4)
self:SetPoint('BOTTOMRIGHT', -4, 5)
self:SetPoint('TOPLEFT', 4, -11)
self:SetResizing('HORIZONTAL')
self:SetSize(0, 0)
end
--[[ Addon ]]--
function Group:SetAddon (addon)
self.name = addon
self.prefix = addon .. '_'
self.sets = _G[self.prefix .. 'Sets'] or _G[addon].Sets
self.L = _G[self.prefix .. 'Locals'] or _G[addon].Locals
end
function Group:GetAddon ()
return self.name
end
function Group:GetAddonInfo ()
for i = 1, GetNumAddOns() do
if GetAddOnInfo(i) == self.name then
return GetAddOnInfo(i)
end
end
end
--[[ Footer ]]--
function Group:SetFooter (footer)
self.Footer:SetText(footer)
end
function Group:GetFooter ()
return self.Footer:GetText()
end
--[[ Manage Children ]]--
function Group:SetChildren (...)
self:SetCall('MagicChildren', ...)
self:UpdateChildren()
end
function Group:CreateMagics()
self:CreateHeader(self.name, 'GameFontNormalLarge')
self:CreateHeader(self.L['Description'] or select(3, self:GetAddonInfo()), 'GameFontHighlightSmall').bottom = 11
self:FireCall('MagicChildren')
end
--[[ Create Child ]]--
function Group:CreateHeader(text, font, underline)
local child = self:CreateChild('Header')
child:SetText(self.L[text] or text)
child:SetUnderlined(underline)
child:SetWidth(591)
child:SetFont(font)
return child
end
function Group:Create(class, text, arg, disabled, small)
local child = self:CreateChild(class)
local arg = (self.sets and '' or self.prefix) .. (arg or text)
local sets = self.sets or _G
local L = self.L
child:SetTip(L[text .. 'Tip'], L[text .. 'TipText'])
child:SetLabel(L[text] or text)
child:SetDisabled(disabled)
child:SetValue(sets[arg])
child:SetSmall(small)
child.left = (child.left or 0) + (small and 10 or 0)
child:SetCall('OnInput', function(self, v)
sets[arg] = v
end)
return child
end
Group.SetContent = Group.SetChildren
|
tScenarioMenuDefs = {}
tScenarioMenuDefs.aScenarioPlayers = {s010_cockpit = "", s020_credits = ""}
if Game.IsInFINAL() then
tScenarioMenuDefs.aScenarioDefs = {
s010_cave = "c10_samus",
s020_magma = "c10_samus",
s030_baselab = "c10_samus",
s040_aqua = "c10_samus",
s050_forest = "c10_samus",
s060_quarantine = "c10_samus",
s070_basesanc = "c10_samus",
s080_shipyard = "c10_samus",
s090_skybase = "c10_samus",
s810_elevator_gym = "c10_samus",
s820_train_gym = "c10_samus",
s830_teleporter_gym = "c10_samus",
s840_capsule_gym = "c10_samus",
s963_bosses_gym = "c10_samus",
s965_centralunit_gym = "c10_samus",
s966_emmy_gym = "c10_samus",
s968_emmy_ia_gym = "c10_samus",
s961_enemys_gym = "c10_samus",
s967_enemies_gym2 = "c10_samus",
s968_enemies_gym3 = "c10_samus",
s969_props_gym = "c10_samus",
s970_commander_gym = "c10_samus",
s971_enemies_gym4 = "c10_samus",
s972_enemies_gym5 = "c10_samus",
s976_materials_gym = "c10_samus",
s950_abilities_gym = "c10_samus"
}
tScenarioMenuDefs.aScenarios = {
"s010_cave",
"s020_magma",
"s030_baselab",
"s040_aqua",
"s050_forest",
"s060_quarantine",
"s070_basesanc",
"s080_shipyard",
"s090_skybase",
"s810_elevator_gym",
"s820_train_gym",
"s830_teleporter_gym",
"s840_capsule_gym",
"s963_bosses_gym",
"s965_centralunit_gym",
"s966_emmy_gym",
"s968_emmy_ia_gym",
"s961_enemys_gym",
"s967_enemies_gym2",
"s968_enemies_gym3",
"s969_props_gym",
"s970_commander_gym",
"s971_enemies_gym4",
"s972_enemies_gym5",
"s976_materials_gym",
"s950_abilities_gym"
}
tScenarioMenuDefs.aScenariosWithAlias = {
s010_cave = "Cave",
s020_magma = "Magma",
s030_baselab = "Laboratory",
s040_aqua = "Aqua",
s050_forest = "Forest",
s060_quarantine = "Quarantine",
s070_basesanc = "Sanctuary",
s080_shipyard = "Shipyard",
s090_skybase = "Skybase",
s810_elevator_gym = "s810_elevator_gym",
s820_train_gym = "s820_train_gym",
s830_teleporter_gym = "s830_teleporter_gym",
s840_capsule_gym = "s840_capsule_gym",
s963_bosses_gym = "s963_bosses_gym",
s965_centralunit_gym = "s965_centralunit_gym",
s966_emmy_gym = "s966_emmy_gym",
s968_emmy_ia_gym = "s968_emmy_ia_gym",
s961_enemys_gym = "s961_enemys_gym",
s967_enemies_gym2 = "s967_enemies_gym2",
s968_enemies_gym3 = "s968_enemies_gym3",
s969_props_gym = "s969_props_gym",
s970_commander_gym = "s970_commander_gym",
s971_enemies_gym4 = "s971_enemies_gym4",
s972_enemies_gym5 = "s972_enemies_gym5",
s976_materials_gym = "s976_materials_gym",
s950_abilities_gym = "s950_abilities_gym"
}
else
tScenarioMenuDefs.aScenarioDefs = {
s010_cave = "c10_samus",
s020_magma = "c10_samus",
s030_baselab = "c10_samus",
s040_aqua = "c10_samus",
s050_forest = "c10_samus",
s060_quarantine = "c10_samus",
s070_basesanc = "c10_samus",
s080_shipyard = "c10_samus",
s090_skybase = "c10_samus",
s810_elevator_gym = "c10_samus",
s820_train_gym = "c10_samus",
s830_teleporter_gym = "c10_samus",
s840_capsule_gym = "c10_samus",
s940_emmyprog = "c10_samus",
s946_progspawnpoints = "c10_samus",
s950_abilities_gym = "c10_samus",
s965_centralunit_gym = "c10_samus",
s966_emmy_gym = "c10_samus",
s968_emmy_ia_gym = "c10_samus",
s951_magnetglove_gym = "c10_samus",
s952_speedbooster_gym = "c10_samus",
s961_enemys_gym = "c10_samus",
s967_enemies_gym2 = "c10_samus",
s968_enemies_gym3 = "c10_samus",
s969_props_gym = "c10_samus",
s962_material_test = "c10_samus",
s963_bosses_gym = "c10_samus",
s970_commander_gym = "c10_samus",
s971_enemies_gym4 = "c10_samus",
s972_enemies_gym5 = "c10_samus",
s964_generic_gym = "c10_samus",
s975_samus_room2 = "c10_samus",
s976_materials_gym = "c10_samus",
s980_testnolightroom = "c10_samus"
}
tScenarioMenuDefs.aScenarios = {
"s810_elevator_gym",
"s820_train_gym",
"s830_teleporter_gym",
"s840_capsule_gym",
"s950_abilities_gym",
"s951_magnetglove_gym",
"s952_speedbooster_gym",
"s961_enemys_gym",
"s962_material_test",
"s963_bosses_gym",
"s964_generic_gym",
"s965_centralunit_gym",
"s966_emmy_gym",
"s967_enemies_gym2",
"s968_emmy_ia_gym",
"s968_enemies_gym3",
"s969_props_gym",
"s970_commander_gym",
"s971_enemies_gym4",
"s972_enemies_gym5",
"s975_samus_room2",
"s976_materials_gym",
"s980_testnolightroom",
"s010_cave",
"s020_magma",
"s030_baselab",
"s040_aqua",
"s050_forest",
"s060_quarantine",
"s070_basesanc",
"s080_shipyard",
"s090_skybase"
}
tScenarioMenuDefs.aScenariosWithAlias = {
s810_elevator_gym = "s810_elevator_gym",
s820_train_gym = "s820_train_gym",
s830_teleporter_gym = "s830_teleporter_gym",
s840_capsule_gym = "s840_capsule_gym",
s950_abilities_gym = "s950_abilities_gym",
s951_magnetglove_gym = "s951_magnetglove_gym",
s952_speedbooster_gym = "s952_speedbooster_gym",
s961_enemys_gym = "s961_enemys_gym",
s967_enemies_gym2 = "s967_enemies_gym2",
s968_enemies_gym3 = "s968_enemies_gym3",
s969_props_gym = "s969_props_gym",
s963_bosses_gym = "s963_bosses_gym",
s970_commander_gym = "s970_commander_gym",
s971_enemies_gym4 = "s971_enemies_gym4",
s972_enemies_gym5 = "s972_enemies_gym5",
s965_centralunit_gym = "s965_centralunit_gym",
s966_emmy_gym = "s966_emmy_gym",
s968_emmy_ia_gym = "s968_emmy_ia_gym",
s964_generic_gym = "s964_generic_gym",
s962_material_test = "s962_material_test",
s975_samus_room2 = "s975_samus_room2",
s976_materials_gym = "s976_materials_gym",
s980_testnolightroom = "s980_testnolightroom",
s010_cave = "s010_cave",
s020_magma = "s020_magma",
s030_baselab = "s030_baselab",
s040_aqua = "s040_aqua",
s050_forest = "s050_forest",
s060_quarantine = "s060_quarantine",
s070_basesanc = "s070_basesanc",
s080_shipyard = "s080_shipyard",
s090_skybase = "s090_skybase"
}
end
tScenarioMenuDefs.aPreSavedData = {}
|
#!/usr/bin/env luajit
local xmlua = require("xmlua")
local document = xmlua.XML.parse([[
<root>
<sub1>sub1-1</sub1>
<sub2>sub2-1</sub2>
<sub1>sub1-2</sub1>
<sub2>sub2-2</sub2>
<sub3>sub3</sub3>
</root>
]])
local sub1s = document:css_select("sub1")
-- <sub1>sub1-1</sub1>
-- <sub1>sub1-2</sub1>
-- Unlink all sub1 elemetns from document
sub1s:unlink()
print(document:to_xml())
-- <?xml version="1.0" encoding="UTF-8"?>
-- <root>
--
-- <sub2>sub2-1</sub2>
--
-- <sub2>sub2-2</sub2>
-- <sub3>sub3</sub3>
-- </root>
|
local addon, addonTbl = ...;
local L = addonTbl.L; -- Create a local reference to the global localization table.
local itemDBRef;
addonTbl.GetCount = function(tbl, itemID)
local count = 0;
if not itemID then itemID = 0 end; -- The itemID parameter is optional. If not passed, assign it a 0.
if itemID == 0 then -- Counting the number of records within an entire table.
for _ in pairs(tbl) do count = count + 1 end;
return count;
else -- Counting the number of times an individual item has been seen.
if tbl[itemID] then
for creature in pairs(tbl[itemID]) do
count = count + tbl[itemID][creature];
end
end
return count;
end
end
-- Synopsis: Used to count records in a table or how many times an item has been seen by the player.
addonTbl.DataIsValid = function(itemID)
if itemID == nil then
return false;
end
itemDBRef = LastSeenClassicItemsDB[itemID]
if itemDBRef == nil then
return false;
end
if itemDBRef["location"] and itemDBRef["lootDate"] and itemDBRef["source"] then
return true;
else
return false;
end
end
--[[
Synopsis: Checks the location, lootDate, and source for a non-nil value.
Written by: Arcanemagus
]]
addonTbl.InitializeSavedVars = function()
if LastSeenClassicMapsDB == nil then LastSeenClassicMapsDB = {} end;
if LastSeenClassicCreaturesDB == nil then LastSeenClassicCreaturesDB = {} end;
if LastSeenClassicItemsDB == nil then LastSeenClassicItemsDB = {} end;
if LastSeenClassicSettingsCacheDB == nil then LastSeenClassicSettingsCacheDB = {} end;
if LastSeenClassicLootTemplate == nil then LastSeenClassicLootTemplate = {} end;
if LastSeenClassicHistoryDB == nil then LastSeenClassicHistoryDB = {} end;
end
addonTbl.ExtractItemLink = function(constant)
local extractedLink, itemID, itemLink;
if string.find(constant, L["LOOT_ITEM_PUSHED_SELF"]) then
extractedLink = string.match(constant, L["LOOT_ITEM_PUSHED_SELF"] .. "(.*).");
itemID = GetItemInfoInstant(extractedLink);
elseif string.find(constant, L["LOOT_ITEM_SELF"]) then
extractedLink = string.match(constant, L["LOOT_ITEM_SELF"] .. "(.*).");
itemID = GetItemInfoInstant(extractedLink);
end
if itemID then
itemLink = select(2, GetItemInfo(itemID));
end
if itemLink then return itemLink end;
end
-- Synopsis: Whenever an item is looted, its link is at the end of a constant like "You received loot". This function
-- extracts the link and discards the fluff.
addonTbl.GetTableKeyFromValue = function(tbl, query)
for k, v in pairs(tbl) do
if v == query then
return k;
end
end
return false;
end
-- Synopsis: Gets a key in a table from the value, a reverse lookup.
addonTbl.Contains = function(tab, key, sub_key, value)
for index, sub_tab in pairs(tab) do
if key then -- The passed table doesn't use numeric indices.
if sub_key ~= nil then
if value then
if tab[key][sub_key] == value then return true end;
else
return tab[key][sub_key] ~= nil;
end
else
return tab[key] ~= nil;
end
else -- This table uses numeric indices.
if tab[index][sub_key] == value then return true end;
end
end
return false;
end
--[[
Synopsis: Allows the caller to look for a key or a sub key for any passed table.
Arguments:
tab: This is the table we want to look in.
key: This is the main element in the table.
sub_key: This is the element within the main element. It can be a table on its own.
value: When a table uses numeric indices, it's likely the user wants to lookup a value associated to a sub_key.
]]
addonTbl.GetTable = function(tbl)
if tbl == LastSeenClassicHistoryDB then
for i = #tbl, 1, -1 do
print("|T" .. tbl[i].itemIcon .. ":0|t " .. tbl[i].itemLink .. " | " .. tbl[i].source .. " | " .. tbl[i].location .. " | " .. tbl[i].lootDate);
end
end
end
-- Synopsis: Used to iterate over a table to get its content.
addonTbl.RollHistory = function()
local historyEntries = addonTbl.GetCount(LastSeenClassicHistoryDB);
if historyEntries > addonTbl.maxHistoryEntries then
for i = #LastSeenClassicHistoryDB, 1, -1 do
if i > addonTbl.maxHistoryEntries then
table.remove(LastSeenClassicHistoryDB, i);
end
end
end
end
-- Synopsis: Maintains the history table, to always keep it at the maximum number of entries, which is currently 20.
addonTbl.DateFormat = function(format)
for k, v in pairs(LastSeenClassicItemsDB) do
if tonumber(format) then -- The player passed in a number so set the format to DAY/MONTH/YEAR.
local month, day, year = string.match(LastSeenClassicItemsDB[k]["lootDate"], "^(%d%d)/(%d%d)/(%d%d%d%d)$");
LastSeenClassicItemsDB[k]["lootDate"] = string.format("%s/%s/%s", day, month, year);
else
local day, month, year = string.match(LastSeenClassicItemsDB[k]["lootDate"], "^(%d%d)/(%d%d)/(%d%d%d%d)$");
LastSeenClassicItemsDB[k]["lootDate"] = string.format("%s/%s/%s", month, day, year);
end
end
end
-- Synopsis: Changes the date format for existing items from MONTH/DAY/YEAR to DAY/MONTH/YEAR or vice versa.
addonTbl.GetItemInfo = function(itemLink, slot)
local lootSources = { GetLootSourceInfo(slot) };
if itemLink then
itemLink = addonTbl.ExtractItemLink(L["LOOT_ITEM_SELF"] .. itemLink); -- The item link isn't formatted correctly from the GetLootSlotLink() function.
local itemID, itemName, itemRarity, itemType, itemSubType, itemEquipLoc, itemIcon;
for j = 1, #lootSources, 2 do
if itemLink then
itemName = GetItemInfo(itemLink);
itemRarity = select(3, GetItemInfo(itemLink));
itemID, itemType, itemSubType, itemEquipLoc, itemIcon = GetItemInfoInstant(itemLink);
local type, _, _, _, _, creatureID = strsplit("-", lootSources[j]);
if itemID then -- To catch items without an item ID.
addonTbl.itemsToSource[itemID] = tonumber(creatureID);
addonTbl.itemSourceCreatureID = addonTbl.itemsToSource[itemID];
if itemRarity >= addonTbl.rarity then
if addonTbl.Contains(addonTbl.whitelistedItems, itemID, nil, nil) then
-- Continue
elseif addonTbl.Contains(addonTbl.ignoredItemCategories, nil, "itemType", itemType) then return;
elseif addonTbl.Contains(addonTbl.ignoredItemCategories, nil, "itemType", itemSubType) then return;
elseif addonTbl.Contains(addonTbl.ignoredItemCategories, nil, "itemType", itemEquipLoc) then return;
elseif addonTbl.Contains(addonTbl.ignoredItems, itemID, nil, nil) then return end;
if LastSeenClassicItemsDB[itemID] then -- Item seen again.
if LastSeenClassicCreaturesDB[addonTbl.itemSourceCreatureID] then
addonTbl.AddItem(itemID, itemLink, itemName, itemRarity, itemType, itemSubType, itemEquipLoc, itemIcon, L["DATE"], addonTbl.currentMap, "Creature", LastSeenClassicCreaturesDB[addonTbl.itemSourceCreatureID].unitName, "Update");
elseif addonTbl.target ~= "" then
addonTbl.AddItem(itemID, itemLink, itemName, itemRarity, itemType, itemSubType, itemEquipLoc, itemIcon, L["DATE"], addonTbl.currentMap, "Object", addonTbl.target, "Update");
else
if addonTbl.mode ~= GM_SURVEY_NOT_APPLICABLE then print(L["ADDON_NAME"] .. itemLink .. L["ERROR_MSG_UNKNOWN_SOURCE"]) end;
addonTbl.AddItem(itemID, itemLink, itemName, itemRarity, itemType, itemSubType, itemEquipLoc, itemIcon, L["DATE"], addonTbl.currentMap, "Miscellaneous", L["INFO_MSG_MISCELLANEOUS"], "Update");
end
else -- Item seen for first time.
if LastSeenClassicCreaturesDB[addonTbl.itemSourceCreatureID] then
addonTbl.AddItem(itemID, itemLink, itemName, itemRarity, itemType, itemSubType, itemEquipLoc, itemIcon, L["DATE"], addonTbl.currentMap, "Creature", LastSeenClassicCreaturesDB[addonTbl.itemSourceCreatureID].unitName, "New");
elseif addonTbl.target ~= "" then
addonTbl.AddItem(itemID, itemLink, itemName, itemRarity, itemType, itemSubType, itemEquipLoc, itemIcon, L["DATE"], addonTbl.currentMap, "Object", addonTbl.target, "New");
else
if addonTbl.mode ~= GM_SURVEY_NOT_APPLICABLE then print(L["ADDON_NAME"] .. itemLink .. L["ERROR_MSG_UNKNOWN_SOURCE"]) end;
addonTbl.AddItem(itemID, itemLink, itemName, itemRarity, itemType, itemSubType, itemEquipLoc, itemIcon, L["DATE"], addonTbl.currentMap, "Miscellaneous", L["INFO_MSG_MISCELLANEOUS"], "New");
end
end
end
end
end
end
end
end
-- Synopsis: Fetches an item's information just before it's looted from the window, and then sends it down the pipeline to addonTbl.AddItem.
|
-- Score Text
local state = require('state')
return function()
local scoreText = {}
scoreText.draw = function()
love.graphics.print(
{state.palette[4], 'Score: ' .. state.score},
10,
10
)
end
return scoreText
end
|
if dofile ~= nil then
dofile ("loveCodify.lua")
end
--[[ ------------------------------------------------------------
Main.lua
--]] ------------------------------------------------------------
-- global screen size constants
bottomY = HEIGHT *.21
trackWidth = WIDTH * .9 -- width of the track at the bottom
horizonY = trackWidth * .55 + bottomY
trackHeight = horizonY - bottomY
trackLength = 100 -- in meters
-- main objects
myCar = nil
speed = 0 -- for showing to the user
cars = {}
day = nil
track = nil
-- various global variables
location = 0 -- my location
maxPosition = -1000 -- the location relative to me where the front-most car is
gameStarted = false -- whether the user has started the game
lastCollisionT = -1000 -- last time i collided, for the penalty
rnum = 0
gameTime = 0 -- for reporting to the user
startTime = 0 -- the time at which the game started
accAngle = 0 -- gravity.z threshold for accelerating vs breaking
days = 1 -- which day we're on
carsToPassInit = 185 -- on day 1 we need this many
carsToPass = carsToPassInit -- how many cars to advance to the next day
gameOver = false
maxSpeed = 200
regularSpeed = 85
function setup()
watch("carsToPass")
watch("days")
watch("speed")
watch("location")
track = Track()
day = Day()
myCar = Car(0,0,0)
myCar.speed=120
print("Instructions:")
print("Angle fwd to accelerate")
print("Angle back to break")
print("Keep still to maintain speed")
print("Arrows to steer")
print("Touch the screen to start")
end
function draw()
rectMode(CORNER)
ellipseMode(RADIUS)
speed = myCar.speed
------------- UPDATE GAME STATE ----------------
if not gameOver then
-- move track around
turnTrack(gameTime,track)
track:moveToTargetX()
-- move the day forward in time
day:updateMode(gameTime)
accelerating = userInputs() -- start, left, right, brake, etc
if gameStarted then
gameTime = ElapsedTime - startTime
location = location + DeltaTime*myCar.speed/100
spawnNewCars()
myCar:updateTireState()
day:updateFogEnd(myCar.speed)
end
-- if we're turning then apply the centrifugal force
centrifugal = track:centrifugal()
centrifugal = centrifugal * myCar.speed / 150
myCar.x = myCar.x + centrifugal
day:moveX(centrifugal*700)
collided = checkForCollisions()
moveCars()
end
--------------- DRAW ---------------
drawBackground()
myCar:draw(track,day)
for i,c in ipairs(cars) do
if c.y > 0 and c.y <= .9*trackLength and c.real then
c:draw(track,day)
end
end
day:drawFog()
if gameStarted and not gameOver then
if accelerating == 1 then
-- show green arrow forward
stroke(0, 255, 0, 255)
drawArrow(vec2(WIDTH*.1,bottomY*.25),90,WIDTH/750)
elseif accelerating == 2 then
-- show red arrow back
stroke(255,0,0,255)
drawArrow(vec2(WIDTH*.1,bottomY*.75),270,WIDTH/750)
end
end
if collided then
fill(255, 243, 0, 255)
ellipse(WIDTH/2,bottomY*.5,bottomY*.25,bottomY*.25)
end
end
function moveCars()
maxPosition = -1000
for i,c in ipairs(cars) do
change = -DeltaTime*(myCar.speed-c.speed)/1.3
beforeY = c.y
c.y = c.y + change
-- count carsPassed
if c.real then
if c.y<0 and beforeY>0 and not day.won then carsToPass = carsToPass - 1 end
if c.y>0 and beforeY<0 and not day.won then carsToPass = carsToPass + 1 end
end
if carsToPass == 0 and not day.won then
day.won = true
print("Achievement unlocked: Day", days)
end
-- remove cars
-- avoid collisions from the back by removing cars
if c.y>0 and beforeY<0 and collidesWithMyCar(c) then
table.remove(cars,i)
-- remove cars that are too far
elseif c.y < -5 * trackLength or c.y > 2 * trackLength then
table.remove(cars,i)
else c:updateTireState() end
maxPosition = math.max(maxPosition,c.y)
end
end
function userInputs()
-- handle steering
if (CurrentTouch.state == BEGAN or CurrentTouch.state == MOVING ) then
if gameStarted then
if CurrentTouch.y < bottomY then
dx = .05
if day:inSnow() then dx = dx / 2 end
if CurrentTouch.x > .64 * WIDTH and CurrentTouch.x < .84 *WIDTH then
-- go left
myCar.x = myCar.x - dx
elseif CurrentTouch.x > .84 * WIDTH then
-- go right
myCar.x = myCar.x + dx
end
end
else
-- start game
gameStarted = true
startTime = ElapsedTime
accAngle = Gravity.z + .002
end
end
-- handle acceleration
if gameStarted then
dz = Gravity.z - accAngle
if dz < -.03 then
myCar.speed = math.min(maxSpeed,myCar.speed+1)
return(1)
elseif dz > .08 then
myCar.speed = math.max(0,myCar.speed-3)
return(2)
end
end
return(3)
end
-- turns the track left and right every now and then
lastTurnT = 0
function turnTrack(gameTime,track)
if gameTime - lastTurnT > 5 then
track:newTargetX()
lastTurnT = gameTime
end
end
function checkForCollisions()
-- with the walls
maxX = .75
if myCar.x > maxX or myCar.x < -maxX then
if myCar.x < 0 then
myCar.x = -maxX/1.2
else
myCar.x = maxX/1.2
end
myCar.speed = math.max(0,myCar.speed-maxSpeed/5)
end
-- with other cars
for i, car in ipairs(cars) do
if collidesWithMyCar(car) then
lastCollisionT = ElapsedTime
break
end
end
-- penalty for colliding for .5 seconds
if ElapsedTime - lastCollisionT < 1 then
myCar.speed = regularSpeed / 2
return(true)
else
return(false)
end
end
-- check if this car collides with my car
function collidesWithMyCar(car)
if not car.real then return(false) end
dx = math.abs(myCar.x - car.x)
dy = car.y - myCar.y
return(dx < 0.4 and dy > 0 and dy < 4) -- based on car dimensions
end
function drawBackground()
background(0, 0, 0, 255)
-- field, track, sky, clouds
day:draw(track)
-- botton
fill(0, 0, 0, 255)
rect(-5,0,WIDTH+10,bottomY)
-- the left/right controls
fill(255, 255, 255, 255)
stroke(255, 255, 255, 255)
drawArrow(vec2(WIDTH*.82,bottomY*.5),180,WIDTH/750)
drawArrow(vec2(WIDTH*0.86,bottomY*.5),0,WIDTH/750)
end
function drawArrow(pos,orient,s)
pushMatrix()
resetMatrix()
pushStyle()
translate(pos.x,pos.y)
scale(s)
strokeWidth(13)
lineCapMode(PROJECT)
rotate(orient)
line(0, 0, 70,0)
line(73, 0, 50, 25)
line(73, 0, 50, -25)
popStyle()
popMatrix()
end
-- why? because I was trying to get around the bug
-- with sounds vs random and in the end I just didn't
-- use sound
function random()
return(math.random())
end
--[[ ------------------------------------------------------------
Track.lua
Represents the track. Knows which way the horizon is pointing,
and how to draw tracks (both straight and curved)
Note on coordinates in this class: x is in pixels relative
to the middle of the screen and y is in pixels in absolute
terms (from the bottom of the screen)
--]] ------------------------------------------------------------
Track = class()
DIRTH = 2 -- threshold at which tracks become straight, a couple of pixels from Width/2
function Track:init()
self.horizonX = 0 -- which it's pointing now
self.horizonTargetX = 0 -- where eventually it will point
-- the coordinates of the track at the bottom
bottomXR = trackWidth/2
bottomXL = -bottomXR
self.bottomL = vec2(bottomXL,bottomY)
self.bottomR = vec2(bottomXR,bottomY)
-- these are calculated based on horizonX when updated
self.horizonL = nil -- coords of the track at the horizon
self.horizonR = nil
self.centerL = nil -- center of curvature of the tracks
self.centerR = nil
self.rL = 0 -- radius of curvature of the tracks
self.rR = 0
end
-- UPDATING FUNCTIONS
-- call this function to change the targetX to a new random position
function Track:newTargetX()
rand = random()
if rand < 1/3 then self.horizonTargetX = -trackWidth / 2
elseif rand < 2/3 then self.horizonTargetX = trackWidth / 2
else self.horizonTargetX = 0 end
end
-- call this function to move the horizonX closer to the target
function Track:moveToTargetX()
dH = math.min(10,math.abs(self.horizonX-self.horizonTargetX))
if self.horizonTargetX < self.horizonX then
self:setHorizon(self.horizonX-dH)
elseif self.horizonTargetX > self.horizonX then
self:setHorizon(self.horizonX+dH)
end
end
-- x in pixels relative to the middle of the screen. negative is to the left
function Track:setHorizon(x)
self.horizonX = x
if self.horizonX < -DIRTH then
-- we're turning left
-- left track
self.rL = .275 * trackWidth^2 / math.abs(self.horizonX)
self.horizonL = vec2(self.horizonX,horizonY)
self.centerL = circleCenter(self.bottomL,self.horizonL,self.rL,1,-1)
-- right track
self.rR = 8 * self.rL
adj = -self.horizonX * WIDTH/trackWidth*.009 -- due to numerical error?
self.horizonR = vec2(self.horizonX,horizonY+adj)
self.centerR = circleCenter(self.bottomR,self.horizonR,self.rR,-1,-1)
elseif self.horizonX > DIRTH then
-- we're turning right
-- right track
self.rR = .275 * trackWidth^2 / math.abs(self.horizonX)
self.horizonR = vec2(self.horizonX,horizonY)
self.centerR = circleCenter(self.bottomR,self.horizonR,self.rR,1,1)
-- left track
self.rL = 8 * self.rR
adj = self.horizonX * WIDTH/trackWidth*.009 -- due to numerical error?
self.horizonL = vec2(self.horizonX,horizonY+adj)
self.centerL = circleCenter(self.bottomL,self.horizonL,self.rL,-1,1)
end
end
-- calculates the center of a circle that passes through bottom abd horizon
-- both of which are vec2s and pf radius r, returns a vec2
-- ugly math ahead
function circleCenter(bottom,horizon,r,mult1,mult2)
m = -(bottom.x-horizon.x)/(bottom.y-horizon.y)
b = (bottom.y+horizon.y-m*(bottom.x+horizon.x))/2
c1 = (1+m^2)
c2 = -(bottom.x+horizon.x)*c1
c3 = horizon.x^2 + (b-horizon.y)^2 - r^2
centerX = (-c2 + mult2 * math.sqrt(c2^2-4*c1*c3))/(2*c1)
centerY = mult1*math.sqrt(r^2-(centerX-bottom.x)^2)+bottom.y
return(vec2(centerX,centerY))
end
-- GETTER FUNCTIONS
-- the centrifugal force on my car and clouds
function Track:centrifugal()
return (-self.horizonX / (trackWidth/2) * .01)
end
-- x coord of left track in pixels relative to Width/2
-- y in metters
function Track:leftAt(y)
return(self:atHelper(y,self.rL,self.centerL,-1))
end
-- x coord of right track in pixels relative to Width/2
-- y in metters
function Track:rightAt(y)
return(self:atHelper(y,self.rR,self.centerR,1))
end
function Track:atHelper(y,r,center,mult)
s = metersToPixels(y)
ys = s + bottomY
if self.horizonX < -DIRTH then
-- turning left
xs = math.sqrt(r^2 - (ys - center.y)^2) + center.x
xs = xs - adj*2*s/trackHeight -- numerical adjustment
elseif self.horizonX > DIRTH then
-- turning right
xs = -math.sqrt(r^2 - (ys - center.y)^2) + center.x
xs = xs + adj*2*s/trackHeight -- numerical adjustment
else
-- going straight
xs = mult*(1-s/trackHeight) * trackWidth/2
end
return(xs)
end
-- tracks y in meter (0,trackLength) and returns y in pixels relative to the bottom
-- note that it's not a linear relationship due to perpective
function metersToPixels(y)
s=y/trackLength
s = (1-s)^2.5
return((1-s)*trackHeight)
end
function Track:draw()
pushStyle()
pushMatrix()
resetMatrix()
lineCapMode(PROJECT)
translate(WIDTH/2,0)
stroke(183, 183, 183, 255)
if math.abs(self.horizonX) <= DIRTH then
-- we're going straight
strokeWidth(5)
line(self.bottomL.x,self.bottomL.y,self.horizonX,horizonY)
line(self.bottomR.x,self.bottomR.y,self.horizonX,horizonY)
else
print(self.centerL.x,self.centerL.y,self.rL,self.rL)
-- we're turning
strokeWidth(3)
noFill()
ellipse(self.centerL.x,self.centerL.y,self.rL,self.rL)
ellipse(self.centerR.x,self.centerR.y,self.rR,self.rR)
end
popStyle()
popMatrix()
end
--[[ ------------------------------------------------------------
Day.lua
--]] ------------------------------------------------------------
Day = class()
function Day:init()
self.mode = 1 -- day, night, snow, etc
self.lastModeT = 0 -- last time we changed modes
self.clouds = {}
self.won = false -- whether we passed all cars for this day
self.fogEnd = .5 -- for fog animation
self:makeClouds()
end
function Day:makeClouds()
for i = 0, 5 do
minY = horizonY + HEIGHT / 15
maxY = HEIGHT - HEIGHT / 20
y = minY + random()*(maxY-minY)
cloud = Cloud(random()*WIDTH,y)
table.insert(self.clouds,cloud)
end
end
function Day:inSnow()
return(modes[self.mode].snow)
end
-- moves the day mode forward
function Day:updateMode(gameTime)
if gameTime - self.lastModeT > modes[self.mode].length then
if self.mode == numModes then
if carsToPass > 0 then
print("GAME OVER")
gameOver = true -- global variable
else
carsToPass = carsToPassInit + 40 * days
days = days + 1
self.won = false
end
end
self.mode = self.mode%numModes+1
self.lastModeT = gameTime
end
end
-- moves the clounds around
function Day:moveX(dx)
for i,cloud in ipairs(self.clouds) do
cloud:moveX(dx)
-- handle a clound disappearing at the edges
if cloud.position.x < -200 or cloud.position.x > WIDTH + 200 then
table.remove(self.clouds,i)
-- make a new one
minY = horizonY + HEIGHT / 15
maxY = HEIGHT - HEIGHT / 20
y = minY + random()*(maxY-minY)
x = random()*WIDTH/8
if dx>0 then x = -x else x = x + WIDTH end
cloud = Cloud(x,y)
table.insert(self.clouds,cloud)
end
end
end
-- needs track because we need to draw track in between the field and the sky
function Day:draw(track)
-- green field
strokeWidth(0)
fill(modes[self.mode].field)
rect(-5, bottomY, WIDTH+10, horizonY)
-- track
track:draw()
-- sky
strokeWidth(0)
fill(modes[self.mode].sky)
rect(-5, horizonY, WIDTH+10, HEIGHT)
-- sunset
sunsetW = (HEIGHT-horizonY)*.02
if modes[self.mode].sunseta ~= nil then
fill(modes[self.mode].sunseta)
rect(-5,horizonY,WIDTH+10,sunsetW+1)
end
if modes[self.mode].sunsetb ~= nil then
fill(modes[self.mode].sunsetb)
rect(-5,horizonY+sunsetW,WIDTH+10,sunsetW+1)
end
if modes[self.mode].sunsetc ~= nil then
fill(modes[self.mode].sunsetc)
rect(-5,horizonY+sunsetW*2,WIDTH+10,sunsetW+1)
end
-- clouds
for i,cloud in ipairs(self.clouds) do
cloud:draw(modes[self.mode].cloud1,modes[self.mode].cloud2)
end
end
function Day:updateFogEnd(speed)
self.fogEnd = self.fogEnd - speed/20000
if self.fogEnd < .5 then self.fogEnd = .6 end
end
function Day:drawFog()
strokeWidth(0)
if modes[self.mode].fog then
fill(74,74,74,255)
rect(-5,bottomY+(horizonY-bottomY)*self.fogEnd,WIDTH+10,HEIGHT)
end
end
--[[ ------------------------------------------------------------
Car.lua
--]] ------------------------------------------------------------
dayCarColors = {
color(255, 0, 0, 255),
color(0, 35, 255, 255),
color(11, 255, 0, 255),
color(255, 245, 0, 255)
}
nightCarColors = {
color(255, 0, 0, 255),
color(255, 0, 188, 255),
color(255, 0, 188, 255),
color(255, 0, 0, 255)
}
Car = class()
function Car:init(x,y,color)
self.x = x -- between -1 and 1
self.y = y -- from 0 to trackLength in meters
self.color = color
self.speed = 85
self.real = true -- unreal cars help with spawning
self.tireState = true -- for tire animation
self.tireStateHelper = 0
end
function Car:updateTireState()
self.tireStateHelper = self.tireStateHelper + self.speed / 60
if self.tireStateHelper > 5 then
self.tireStateHelper = 0
self.tireState = not self.tireState
end
end
function Car:draw(track,day)
-- coords of the track at this y
leftX = track:leftAt(self.y)
rightX = track:rightAt(self.y)
-- my coord at this y
x = ((1+self.x)*rightX + (1-self.x)*leftX)/2
s = metersToPixels(self.y) -- implemented in the track class
self:drawHelper(x,s,1-s/trackHeight,self.color,self.tireState,day)
end
-- x relative to middle of the screen in pixels, y relative to the bottom of the track
-- scale relative to a car at the bottom of the screen
-- tireState is true or false, for animation
function Car:drawHelper(x,y,s,colorIdx,tireState,day)
pushMatrix()
pushStyle()
translate(WIDTH/2+x,bottomY+y)
scale(trackWidth*s/90,trackHeight*s/108)
if colorIdx == 0 then -- hack for my car
thisColor = color(190,190,190,255)
elseif modes[day.mode].rearlights then
thisColor = nightCarColors[colorIdx]
else
thisColor = dayCarColors[colorIdx]
end
fill(thisColor)
stroke(thisColor)
strokeWidth(2)
if not modes[day.mode].rearlights or colorIdx == 0 then
-- regular car
rect(-4,1,8,7) -- body horizontal
rect(-2,0,4,12) -- body vertical
rect(-6,8,12,3) -- top wing
rect(-6,8,3,4) -- left wing
rect(3,8,3,4) -- right wing
for i = 0,7 do
if (tireState and i%2==0) or (i%2==1 and not tireState) then
startX = -8
else
startX = -6
end
rect(startX,i,3,2)
rect(startX+11,i,3,2)
end
else
-- rear lights
rect(2,0,5,4)
rect(-6,0,5,4)
end
popMatrix()
popStyle()
end
function spawnNewCars()
if maxPosition < 65 then -- space the cars apart
rand1 = random()
if rand1 < 0.7 then
-- spawn one car
rand2 = random()
if rand2 < 1/3 then x = -.5
elseif rand2 < 2/3 then x = 0
else x = .5 end
newCar = Car(x,.9*trackLength,randColor())
table.insert(cars,newCar)
else
newCar = Car(0,.9*trackLength,randColor())
newCar.real = false
table.insert(cars,newCar)
end
end
end
-- used above
function randColor()
ncolors = table.maxn(dayCarColors)
idx = math.ceil(random()*ncolors)
return(idx)
end
--[[ ------------------------------------------------------------
Cloud.lua
--]] ------------------------------------------------------------
Cloud = class()
function Cloud:init(x,y)
-- you can accept and set parameters here
self.shapes = {}
self.position = vec2(x,y)
-- Generate random cloud
numCircles = 4
spacing = 20
for i = 1,numCircles do
x = i * spacing - ((numCircles/2)*spacing)
y = (random() - 0.5) * 20
rad = spacing*random()+spacing
table.insert(self.shapes, {x=x, y=y, r=rad})
end
self.width = numCircles * spacing + spacing
end
function Cloud:moveX(dx)
self.position.x = self.position.x + dx
end
function Cloud:draw(c1,c2)
pushStyle()
pushMatrix()
translate(self.position.x, self.position.y)
-- noStroke()
strokeWidth(-1)
fill(c2)
for i,s in ipairs(self.shapes) do
ellipse(s.x, s.y - 5, s.r)
end
fill(c1)
for i,s in ipairs(self.shapes) do
ellipse(s.x, s.y + 5, s.r)
end
popMatrix()
popStyle()
end
--[[ ------------------------------------------------------------
DayModes.lua
--]] ------------------------------------------------------------
modes = {
{ -- morning
length = 14,
field = color(0,68,0,255),
sky = color(24,26,167,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(255,255,255,255),
cloud2 = color(167,190,221,255),
rearlights = false,
snow = false,
fog = false
},
{ -- day1
length = 17,
field = color(0,68,0,255),
sky = color(35,38,170,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(255, 255, 255, 255),
cloud2 = color(167,190,221,255),
rearlights = false,
snow = false,
fog = false
},
{ -- day2
length = 17,
field = color(0,68,0,255),
sky = color(45,50,184,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(255,255,255,255),
cloud2 = color(167,190,221,255),
rearlights = false,
snow = false,
fog = false
},
{ -- snow
length = 34,
field = color(255,255,255,255),
sky = color(45,50,184,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(255,255,255,255),
cloud2 = color(167,190,221,255),
rearlights = false,
snow = true,
fog = false
},
{ -- afternoon
length = 4,
field = color(20,60,0,255),
sky = color(24,26,167,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(255,255,255,255),
cloud2 = color(167,190,221,255),
rearlights = false,
snow = false,
fog = false
},
{ -- sunset1
length = 4,
field = color(20,60,0,255),
sky = color(24,26,167,255),
sunseta = color(104,25,154,255),
sunsetb = color(51,26,163,255),
cloud1 = color(255,255,255,255),
cloud2 = color(167,190,221,255),
sunsetc = nil,
rearlights = false,
snow = false,
fog = false
},
{ -- sunset2
length = 4,
field = color(20,60,0,255),
sky = color(51,26,163,255),
sunseta = color(151,25,122,255),
sunsetb = color(104,25,154,255),
sunsetc = nil,
cloud1 = color(255, 255, 255, 255),
cloud2 = color(226, 220, 199, 255),
rearlights = false,
snow = false,
fog = false
},
{ -- sunset3
length = 4,
field = color(20,60,0,255),
sky = color(51,26,163,255),
sunseta = color(167,26,26,255),
sunsetb = color(151,25,122,255),
sunsetc = color(104,25,154,255),
cloud1 = color(255,255,255,255),
cloud2 = color(212, 202, 169, 255),
rearlights = false,
snow = false,
fog = false
},
{ -- sunset4
length = 4,
field = color(48,56,0,255),
sky = color(104,25,154,255),
sunseta = color(163,57,21,255),
sunsetb = color(167,26,26,255),
sunsetc = color(151,25,122,255),
cloud1 = color(230, 230, 230, 255),
cloud2 = color(193, 168, 107, 255),
rearlights = false,
snow = false,
fog = false
},
{ -- sunset5
length = 4,
field = color(48,56,0,255),
sky = color(151,25,122,255),
sunseta = color(181,83,40,255),
sunsetb = color(163,57,21,255),
sunsetc = color(167,26,26,255),
cloud1 = color(204, 204, 204, 255),
cloud2 = color(251,228,187,255),
rearlights = false,
snow = false,
fog = false
},
{ -- sunset6
length = 4,
field = color(48,56,0,255),
sky = color(167,26,26,255),
sunseta = color(162,98,33,255),
sunsetb = color(181,83,40,255),
sunsetc = color(163,57,21,255),
cloud1 = color(179, 179, 179, 255),
cloud2 = color(255,194,104,255),
rearlights = false,
snow = false,
fog = false
},
{ -- sunset7
length = 4,
field = color(48,56,0,255),
sky = color(163,57,21,255),
sunseta = color(134,134,29,255),
sunsetb = color(162,98,33,255),
sunsetc = color(181,83,40,255),
cloud1 = color(156, 156, 156, 255),
cloud2 = color(254,157,133,255),
rearlights = false,
snow = false,
fog = false
},
{ -- night1
length = 34,
field = color(0,0,0,255),
sky = color(74,74,74,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(127, 127, 127, 255),
cloud2 = color(207, 207, 207, 255),
rearlights = true,
snow = false,
fog = false
},
{ -- fog
length = 34,
field = color(74,74,74,255),
sky = color(74,74,74,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(255,255,255,255),
cloud2 = color(167,190,221,255),
rearlights = true,
snow = false,
fog = true
},
{ -- night2
length = 17,
field = color(0,0,0,255),
sky = color(74,74,74,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(127,127,127,255),
cloud2 = color(207,207,207,255),
rearlights = true,
snow = false,
fog = false
},
{ -- sunrise
length = 17,
field = color(0,0,0,255),
sky = color(111,111,111,255),
sunseta = nil,
sunsetb = nil,
sunsetc = nil,
cloud1 = color(159, 159, 159, 255),
cloud2 = color(200, 200, 200, 255),
rearlights = false,
snow = false,
fog = false
}
}
numModes = table.maxn(modes)
|
materialNames:addItem({
{"Crowd materials", "Crowd/Blue", "Crowd/Red", "Crowd/Green", "Crowd/Red", "Crowd/Dirt",
"Crowd/Dirt01", "Crowd/EgyptRocky", "Crowd/MtlPlat2", "Crowd/RustedMetal", "Crowd/TerrRock", "Crowd/Terrain",
"CrowdEdit/Terrain1"},
{"Solid colors", "solidblue", "solidblack", "solidred", "solidlightgreen", "solidgreen", "solidwhite"},
{"Colors", "green", "white", "black","blue","red","lightgrey"},
{"Icons", "blueCircle", "redCircle", "icons/add", "icons/refresh"}
})
meshFiles:addItem({
{"Simple polygons", "vehicle.mesh", "sphere1010.mesh", "arrow.mesh", "cone.mesh", "axes.mesh", "cylinder.mesh"},
{"Static objects", "pave.mesh", "ogrehead.mesh"},
{"Ogre default meshes", "ogrehead.mesh", "athene.mesh", "Barrel.mesh", "column.mesh", "cube.mesh", "facial.mesh", "fish.mesh", "geosphere4500.mesh",
"geosphere8000.mesh", "knot.mesh", "ninja.mesh", "razor.mesh", "RZR-002.mesh", "sphere.mesh", "WoodPallet.mesh"},
{"Dynamic objects", "hyunwoo.mesh", "muaythai1.mesh", "robot.mesh"}
})
|
module ('content.properties', package.seeall)
local all_properties = love.filesystem.enumerate 'content/properties'
for _, property_file in ipairs(all_properties) do
require('content.properties.'..string.gsub(property_file, '.lua', ''))
end
|
return PlaceObj("ModDef", {
"title", "Moisture Vaporator Show Max",
"version", 2,
"version_major", 0,
"version_minor", 2,
"saved", 0,
"image", "Preview.png",
"id", "ChoGGi_MoistureVaporatorShowMax",
"steam_id", "1783220322",
"pops_any_uuid", "6bc235b6-93de-4487-b672-a7dbe2494d53",
"author", "ChoGGi",
"lua_revision", 249143,
"code", {
"Code/Script.lua",
},
"TagInterface", true,
"description", [[Show how much water you lose from having your vaps too close to each other.
"spoiler" it's always .4 no matter how many are too close, maybe they'll fix it to reflect more than one together someday.
Till then this mod is mostly useless (good reminder to space them out though).]],
})
|
add_message_with_pause("MOUNTAIN_ELF_SCHOLAR_WORK_SID")
add_message_with_pause("MOUNTAIN_ELF_SCHOLAR_WORK2_SID")
clear_and_add_message("MOUNTAIN_ELF_SCHOLAR_WORK3_SID")
|
Main = {}
--[[ Functions ]]--
function Main:Init()
self.grids = {}
self.cached = {}
for k, property in ipairs(Properties) do
local gridId = Grids:GetGrid(property.coords, Config.GridSize)
local grid = self.grids[gridId]
if not grid then
grid = {}
self.grids[gridId] = grid
end
grid[#grid + 1] = k
end
local ped = PlayerPedId()
local coords = GetEntityCoords(ped)
self:UpdateGrids(nil, Grids:GetNearbyGrids(coords, Config.GridSize))
end
function Main:UpdateGrids(_, nearbyGrids)
local temp = {}
for _, gridId in ipairs(nearbyGrids) do
temp[gridId] = true
if not self.cached[gridId] then
self.cached[gridId] = true
self:RegisterGrid(gridId)
end
end
for gridId, _ in pairs(self.cached) do
if not temp[gridId] then
self.cached[gridId] = nil
self:UnregisterGrid(gridId)
end
end
end
function Main:RegisterGrid(gridId)
-- local grid = self.grids[gridId]
-- if not grid then return end
-- for _, propertyId in ipairs(grid) do
-- self:RegisterEntity(propertyId)
-- end
end
function Main:UnregisterGrid(gridId)
-- local grid = self.grids[gridId]
-- if not grid then return end
-- for _, propertyId in ipairs(grid) do
-- local property = Properties[propertyId]
-- exports.entities:Destroy("property-"..propertyId)
-- if property.garage then
-- exports.entities:Destroy("garage-"..propertyId)
-- end
-- end
end
function Main:RegisterEntity(propertyId)
local property = Properties[propertyId]
if not property then return end
local options = {}
exports.entities:Register({
id = "property-"..propertyId,
name = "Property "..propertyId,
coords = property.coords,
radius = 1.0,
navigation = {
id = "property",
text = "Property",
icon = "house",
sub = {
{
id = "enterProperty",
text = "Enter",
icon = "door_front",
},
{
id = "knockProperty",
text = "Knock",
icon = "notifications",
},
{
id = "lockProperty",
text = "Toggle Lock",
icon = "lock",
},
{
id = "examineProperty",
text = "Examine",
icon = "search",
},
},
},
})
if property.garage then
exports.entities:Register({
id = "garage-"..propertyId,
name = "Property "..propertyId.." Garage",
coords = property.garage,
radius = 3.0,
navigation = {
id = "garage",
text = "Garage",
icon = "garage",
},
})
end
end
function Main:FindNearestProperty(coords)
if type(coords) ~= "vector3" then return end
local nearestProperty, nearestDist = nil, 0.0
for gridId, _ in pairs(self.cached) do
local grid = self.grids[gridId]
if grid then
for _, propertyId in ipairs(grid) do
local property = Properties[propertyId]
if property and property.coords then
local _coords = property.coords
local propertyDist = #(vector3(_coords.x, _coords.y, _coords.z) - coords)
if not nearestProperty or propertyDist < nearestDist then
nearestDist = propertyDist
nearestProperty = property
end
end
end
end
end
return nearestProperty, nearestDist
end
function Main:EnterShell(id, coords)
local shell = Config.Shells[id]
if not shell then
error(("shell does not exist (%s)"):format(id))
end
if not IsModelValid(shell.Model) then
error(("invalid model for shell (%s)"):format(id))
end
while not HasModelLoaded(shell.Model) do
RequestModel(shell.Model)
Citizen.Wait(20)
end
local entity = CreateObject(shell.Model, coords.x, coords.y, coords.z, false, true)
FreezeEntityPosition(entity, true)
SetEntityCanBeDamaged(entity, false)
SetEntityInvincible(entity, true)
SetEntityDynamic(entity, false)
SetEntityHasGravity(entity, false)
SetEntityLights(entity, false)
local ped = PlayerPedId()
local entry = vector4(coords.x, coords.y, coords.z, 0.0) + shell.Entry
SetEntityVelocity(ped, 0.0, 0.0, 0.0)
SetEntityCoordsNoOffset(ped, entry.x, entry.y, entry.z, true)
SetEntityHeading(ped, entry.w)
ClearPedTasksImmediately(ped)
self.coords = coords
self.shell = shell
self.entity = entity
exports.sync:SetNighttime(true)
-- exports.sync:SetBlackout(true)
exports.entities:Register({
id = "propertyExit",
name = "Property Exit",
coords = entry,
radius = 1.0,
navigation = {
id = "property",
text = "Property",
icon = "house",
sub = {
{
id = "exitProperty",
text = "Exit",
icon = "door_front",
},
{
id = "lockProperty",
text = "Toggle Lock",
icon = "lock",
},
}
}
})
end
function Main:Exit()
if self.entity and DoesEntityExist(self.entity) then
DeleteEntity(self.entity)
end
self.coords = nil
self.shell = nil
self.entity = nil
local ped = PlayerPedId()
local coords = self.entry
if coords then
SetEntityCoordsNoOffset(ped, coords.x, coords.y, coords.z, true)
SetEntityHeading(ped, coords.w + 180.0)
end
exports.entities:Destroy("propertyExit")
exports.sync:SetNighttime(false)
-- exports.sync:SetBlackout(false)
end
function Main:Update()
local shell = self.shell
if not shell then return end
local coords = self.coords and vector3(self.coords.x, self.coords.y, self.coords.z) or vector3(0.0, 0.0, 0.0)
-- Update world.
SetRainLevel(0.0)
end
function Main:AddOption(property)
local options = {}
options = {
{
id = "enterProperty",
text = "Enter",
icon = "door_front",
},
{
id = "knockProperty",
text = "Knock",
icon = "notifications",
},
{
id = "lockProperty",
text = "Toggle Lock",
icon = "lock",
},
{
id = "examineProperty",
text = "Examine",
icon = "search",
},
}
exports.interact:AddOption({
id = "property",
text = "Property",
icon = "house",
sub = options,
})
end
Citizen.CreateThread(function()
while true do
Main:Update()
Citizen.Wait(0)
end
end)
--[[ Events ]]--
AddEventHandler("properties:clientStart", function()
Main:Init()
-- Main:EnterShell("test")
end)
AddEventHandler("interact:navigate", function(value)
if not value then
exports.interact:RemoveOption("property")
return
end
local ped = PlayerPedId()
local coords = GetEntityCoords(ped)
local property, distance = Main:FindNearestProperty(coords)
if property and distance < Config.DoorRadius then
TriggerServerEvent("properties:request", property.id)
end
end)
AddEventHandler("interact:onNavigate_enterProperty", function(option)
local ped = PlayerPedId()
local coords = GetEntityCoords(ped)
local property, dist = Main:FindNearestProperty(coords)
if not property then return end
local shell = "motel"
Main.entry = property.coords
Main:EnterShell(shell, property.coords + vector4(0.0, 0.0, 200.0, 0.0))
end)
AddEventHandler("interact:onNavigate_exitProperty", function(option)
Main:Exit()
end)
AddEventHandler("grids:enter"..Config.GridSize, function(...)
Main:UpdateGrids(...)
end)
--[[ Events: Net ]]--
RegisterNetEvent("properties:receive", function(property)
Main:AddOption(property)
end)
--[[ Commands ]]--
exports.chat:RegisterCommand("a:createshells", function(source, args, command)
local ped = PlayerPedId()
local coords = GetEntityCoords(ped)
for k, model in ipairs(Config.Models) do
while not HasModelLoaded(model) do
RequestModel(model)
Citizen.Wait(0)
end
coords = coords + vector3(0.0, 0.0, 20.0)
local entity = CreateObject(model, coords.x, coords.y, coords.z, true, true)
FreezeEntityPosition(entity, true)
SetEntityCanBeDamaged(entity, false)
SetEntityInvincible(entity, true)
SetEntityDynamic(entity, false)
SetEntityHasGravity(entity, false)
SetEntityLights(entity, false)
print(k, model)
end
end, {
description = "Instance all interior shells."
}, "Dev")
|
-- Autogenerated from KST: please remove this line if doing any edits by hand!
local luaunit = require("luaunit")
require("valid_fail_eq_bytes")
TestValidFailEqBytes = {}
function TestValidFailEqBytes:test_valid_fail_eq_bytes()
luaunit.assertErrorMsgMatches(".+: not equal, expected .*, but got .*", ValidFailEqBytes.from_file, ValidFailEqBytes, "src/fixed_struct.bin")
end
|
local local0 = 2.5
local local1 = 8.5 - local0
local local2 = 15.4 - local0
local local3 = 8.2 - local0
local local4 = 10.8 - local0
local local5 = 2 - local0
local local6 = 2 - local0
local local7 = 11.5 - local0
local local8 = 6.7 - local0
local local9 = 12.3 - local0
local local10 = 1.5 - local0
local local11 = 6.6 - local0
local local12 = 14.7 - local0
local local13 = 19.8 - local0
local local14 = 9.5 - local0
local local15 = 1.5 - local0
local local16 = 15 - local0
local local17 = 5.5 - local0
local local18 = 12.6 - local0
local local19 = 5.5 - local0
local local20 = 2.2 - local0
local local21 = 3.4 - local0
local local22 = 2.2 - local0
local local23 = 3.4 - local0
local local24 = 0.1 - local0
local local25 = 3.2 - local0
function OnIf_509010(arg0, arg1, arg2)
if arg2 == 0 then
FounderBeast_Headless509010_ActAfter(arg0, arg1)
end
return
end
function FounderBeast_Headless509010Battle_Activate(arg0, arg1)
local local0 = {}
local local1 = {}
local local2 = {}
Common_Clear_Param(local0, local1, local2)
if arg0:HasSpecialEffectId(TARGET_SELF, 481) and arg0:GetNumber(1) == 0 then
arg0:SetNumber(1, 1)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 482) and arg0:GetNumber(2) == 0 then
arg0:SetNumber(2, 1)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 483) and arg0:GetNumber(3) == 0 then
arg0:SetNumber(3, 1)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 484) and arg0:GetNumber(3) == 0 then
arg0:SetNumber(3, 1)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 480) and arg0:GetNumber(4) == 0 then
arg0:SetNumber(4, 1)
end
local local3 = arg0:GetDist(TARGET_ENE_0)
local local4 = arg0:GetRandam_Int(1, 100)
arg0:DeleteObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5509)
arg0:DeleteObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5514)
arg0:DeleteObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5528)
arg0:DeleteObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5529)
if arg0:GetHpRate(TARGET_SELF) <= 0.5 and arg0:HasSpecialEffectId(TARGET_SELF, 5020) == false then
local0[12] = 100
elseif arg0:GetEventRequest(0) == 1 and arg0:GetNumber(0) ~= 1 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 5, 3022, TARGET_ENE_0, Dist_None, 0, 0)
elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 240) then
local0[19] = 40
local0[7] = 60
elseif arg0:GetNumber(0) == 1 then
if 17.5 <= local3 then
local0[1] = 0
local0[2] = 20
local0[3] = 0
local0[4] = 0
local0[5] = 0
local0[6] = 40
local0[9] = 0
local0[10] = 10
local0[13] = 25
local0[14] = 0
elseif 12.5 <= local3 then
local0[1] = 5
local0[2] = 5
local0[3] = 0
local0[4] = 0
local0[5] = 0
local0[6] = 30
local0[9] = 0
local0[10] = 20
local0[13] = 30
local0[14] = 0
elseif 7.5 <= local3 then
local0[1] = 20
local0[2] = 0
local0[3] = 30
local0[4] = 0
local0[5] = 0
local0[6] = 15
local0[9] = 0
local0[10] = 15
local0[13] = 0
local0[14] = 20
elseif 2.5 <= local3 then
local0[1] = 20
local0[2] = 0
local0[3] = 10
local0[4] = 35
local0[5] = 0
local0[6] = 0
local0[9] = 20
local0[10] = 0
local0[13] = 0
local0[14] = 15
else
local0[1] = 0
local0[2] = 0
local0[3] = 0
local0[4] = 50
local0[5] = 0
local0[6] = 0
local0[7] = 30
local0[9] = 20
local0[10] = 0
local0[13] = 0
local0[14] = 0
end
elseif 17.5 <= local3 then
local0[1] = 0
local0[2] = 30
local0[3] = 0
local0[4] = 0
local0[5] = 0
local0[6] = 0
local0[9] = 0
local0[10] = 0
local0[13] = 60
local0[14] = 0
elseif 12.5 <= local3 then
local0[1] = 0
local0[2] = 15
local0[3] = 0
local0[4] = 0
local0[5] = 0
local0[6] = 20
local0[9] = 0
local0[10] = 0
local0[13] = 35
local0[14] = 0
elseif 7.5 <= local3 then
local0[1] = 20
local0[2] = 0
local0[3] = 20
local0[4] = 0
local0[5] = 0
local0[6] = 0
local0[9] = 0
local0[10] = 0
local0[13] = 20
local0[14] = 30
elseif 2.5 <= local3 then
local0[1] = 20
local0[2] = 0
local0[3] = 30
local0[4] = 30
local0[5] = 0
local0[6] = 0
local0[9] = 20
local0[10] = 0
local0[13] = 0
local0[14] = 0
else
local0[1] = 0
local0[2] = 0
local0[3] = 0
local0[4] = 45
local0[5] = 0
local0[6] = 0
local0[7] = 45
local0[9] = 10
local0[10] = 0
local0[13] = 0
local0[14] = 0
end
if arg0:IsFinishTimer(0) == false then
local0[3] = 0
end
if arg0:IsFinishTimer(1) == false then
local0[5] = 0
end
if arg0:IsFinishTimer(2) == false then
local0[8] = 0
end
if arg0:IsFinishTimer(3) == false then
local0[4] = 0
end
if arg0:IsFinishTimer(4) == false then
local0[9] = 0
end
if arg0:IsFinishTimer(5) == false then
local0[14] = 0
end
if arg0:IsFinishTimer(7) == false then
local0[10] = 0
end
if arg0:GetNumber(0) == 0 then
local0[5] = 0
local0[10] = 0
local0[14] = 0
end
local1[1] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act01)
local1[2] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act02)
local1[3] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act03)
local1[4] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act04)
local1[5] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act05)
local1[6] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act06)
local1[7] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act07)
local1[9] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act09)
local1[10] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act10)
local1[12] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act12)
local1[13] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act13)
local1[14] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act14)
local1[19] = REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_Act19)
Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, FounderBeast_Headless509010_ActAfter_AdjustSpace), local2)
return
end
local0 = 5.4 - local0
local0 = 10.3 - local0
local0 = 7.4 - local0
local0 = 11 - local0
function FounderBeast_Headless509010_Act01(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Int(1, 100)
local local3 = 20
local local4 = UPVAL0
local local5 = arg0:GetRandam_Int(1, 2)
local local6 = UPVAL1
if UPVAL2 <= local0 and local1 <= 75 then
local6 = UPVAL3
local4 = UPVAL2
end
Approach_Act(arg0, arg1, local6, 0, 0)
arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5528)
arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5529)
if arg0:GetRandam_Int(1, 100) <= 70 and arg0:GetNumber(0) == 1 then
if arg0:GetNumber(0) == 1 then
if UPVAL2 <= local0 and local1 <= 10 then
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 30, 3003, TARGET_ENE_0, local3, 0, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3011, TARGET_ENE_0, local3, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 30, 3000, TARGET_ENE_0, local3, 0, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3001, TARGET_ENE_0, local3, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3003, TARGET_ENE_0, local3, 0)
end
if local1 <= 20 then
local local7 = 1
for local8 = local5 - local7, 2, local7 do
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3017, TARGET_ENE_0, local3, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3011, TARGET_ENE_0, local3, 0)
end
end
elseif UPVAL2 <= local0 and local1 <= 75 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, local3, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 30, 3000, TARGET_ENE_0, local3, 0, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3001, TARGET_ENE_0, local3, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 30, 3003, TARGET_ENE_0, local3, 0)
end
else
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 30, 3000, TARGET_ENE_0, local3, 0, 0)
if local1 <= 65 and arg0:GetNumber(0) == 1 then
local local7 = 1
for local8 = local5 - local7, 2, local7 do
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3001, TARGET_ENE_0, local3, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3010, TARGET_ENE_0, local3, 0)
end
end
if arg0:GetRandam_Int(1, 100) <= 50 and arg0:GetNumber(0) == 1 then
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 30, 3001, TARGET_ENE_0, local3, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 30, 3010, TARGET_ENE_0, local3, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 30, 3001, TARGET_ENE_0, local3, 0)
end
end
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 8.7 - local0
local0 = 14.7 - local0
function FounderBeast_Headless509010_Act02(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = 20
local local3 = UPVAL0
Approach_Act(arg0, arg1, UPVAL1, 0, 0)
if arg0:GetNumber(0) == 1 then
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3004, TARGET_ENE_0, local2, 0, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3012, TARGET_ENE_0, 20, 0)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3004, TARGET_ENE_0, local2, 0, 0)
end
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 5.3 - local0
local0 = 5.6 - local0
function FounderBeast_Headless509010_Act03(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = UPVAL0
Approach_Act(arg0, arg1, UPVAL1, 0, 0)
arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5514)
arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5528)
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, 20, 0, -1)
arg0:SetTimer(0, 12)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 0.1 - local0
local0 = 3 - local0
function FounderBeast_Headless509010_Act04(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = arg0:GetDist(TARGET_ENE_0)
local local2 = arg0:GetRandam_Int(1, 100)
local local3 = UPVAL0
Approach_Act(arg0, arg1, UPVAL1, 0, 0)
arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5509)
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3027, TARGET_ENE_0, 20, 0, -1)
arg0:SetTimer(3, 12)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 5.4 - local0
local0 = 10.5 - local0
function FounderBeast_Headless509010_Act05(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = UPVAL0
local local2 = UPVAL1
local local3 = 0
local local4 = 0
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3013, TARGET_ENE_0, 20, 0, 0)
arg0:SetTimer(1, 10)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 6.1 - local0
local0 = 17.1 - local0
local0 = 13.4 - local0
local0 = 18 - local0
function FounderBeast_Headless509010_Act06(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = UPVAL0
local local2 = UPVAL1
local local3 = UPVAL3
Approach_Act(arg0, arg1, UPVAL2, 0, 0)
if arg0:GetRandam_Int(1, 100) <= 50 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3014, TARGET_ENE_0, 20, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3028, TARGET_ENE_0, AttDist1, 0, 0)
end
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
function FounderBeast_Headless509010_Act07(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = 20
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 160) then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3026, TARGET_ENE_0, 20, 0, 0)
elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 160) then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3025, TARGET_ENE_0, 20, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = 0.7 - local0
local0 = 3.3 - local0
function FounderBeast_Headless509010_Act09(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = UPVAL0
Approach_Act(arg0, arg1, UPVAL1, 0, 0)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3024, TARGET_ENE_0, 20, 0, -1)
arg0:SetTimer(4, 10)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 11.6 - local0
function FounderBeast_Headless509010_Act10(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3016, TARGET_ENE_0, UPVAL0 + 1, 0, 0)
arg0:SetTimer(7, 10)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
function FounderBeast_Headless509010_Act12(arg0, arg1, arg2)
if arg0:GetDist(TARGET_ENE_0) <= 5 then
FounderBeast_Headless509010_Act09(arg0, arg1, arg2)
end
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3021, TARGET_ENE_0, DIST_None, 0, 0)
arg0:SetNumber(0, 1)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 21.2 - local0
function FounderBeast_Headless509010_Act13(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, UPVAL0 + 1, 0, -1)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 12.6 - local0
local0 = 5.5 - local0
function FounderBeast_Headless509010_Act14(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = UPVAL0 + 1
local local2 = UPVAL1
Approach_Act(arg0, arg1, UPVAL0, 10, 0)
if arg0:GetRandam_Int(1, 100) <= 60 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3015, TARGET_ENE_0, local1, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3015, TARGET_ENE_0, local1, 0, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3018, TARGET_ENE_0, local1, 0)
end
arg0:SetTimer(5, 10)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
function FounderBeast_Headless509010_Act19(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
if arg0:GetRandam_Int(1, 100) <= 60 then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 10, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 4)
else
FounderBeast_Headless509010_Act09(arg0, arg1, arg2)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function FounderBeast_Headless509010_SpaceAdjustment(arg0, arg1)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Int(0, 1)
local local3 = arg0:GetRandam_Float(1.7, 2.3)
local local4 = arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_B, 5.5, 2)
local local5 = arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_L, 5.5, 2)
local local6 = arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_R, 5.5, 2)
return
end
function FounderBeast_Headless509010_ActAfter_AdjustSpace(arg0, arg1, arg2)
arg1:AddSubGoal(GOAL_COMMON_If, 10, 0)
return
end
function FounderBeast_Headless509010_ActAfter(arg0, arg1)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Int(0, 1)
local local3 = arg0:GetRandam_Float(3, 4.5)
local local4 = arg0:GetRandam_Float(2, 3.5)
if arg0:GetNumber(0) ~= 1 then
if local0 <= 3 then
if local1 <= 60 then
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 120) then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5)
end
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
elseif local1 <= 80 then
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 5, TARGET_ENE_0, true, -1)
end
elseif local0 <= 4.5 then
if local1 <= 30 then
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 120) then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5)
end
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
elseif local1 <= 60 then
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 7, TARGET_ENE_0, true, -1)
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
elseif local1 <= 70 then
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
end
elseif local0 <= 9 then
if local1 <= 60 then
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
end
elseif local0 <= 13 and local1 <= 50 then
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
end
end
return
end
function FounderBeast_Headless509010Battle_Update(arg0, arg1)
return GOAL_RESULT_Continue
end
function FounderBeast_Headless509010Battle_Terminate(arg0, arg1)
return
end
local0 = 12.6 - local0
function FounderBeast_Headless509010Battle_Interupt(arg0, arg1)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Int(1, 100)
local local3 = arg0:GetDist(TARGET_ENE_0)
local local4 = UPVAL0 + 1
local local5 = UPVAL0
if Damaged_Act(arg0, arg1, 5, 50) then
arg1:ClearSubGoal()
arg0:Replaning()
return true
elseif arg0:IsInterupt(INTERUPT_FLAG_ActivateSpecialEffect) and arg0:GetNumber(0) == 1 and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_F, 360, 5.5) and arg0:IsActivateSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5509) and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_F, 90, 10) then
arg1:ClearSubGoal()
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3019, TARGET_ENE_0, local4, 0, 0)
return true
elseif arg0:IsInterupt(INTERUPT_FLAG_ActivateSpecialEffect) and arg0:IsActivateSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5514) and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_F, 360, 4) then
arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5509)
arg1:ClearSubGoal()
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3032, TARGET_ENE_0, local4, 0, 0)
return true
elseif arg0:IsInterupt(INTERUPT_FLAG_ActivateSpecialEffect) and arg0:GetNumber(0) == 1 and arg0:IsFinishTimer(6) == true and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_F, 360, 6) and arg0:IsActivateSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5528) and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_F, 180, 12) and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_R, 270, 12) then
arg1:ClearSubGoal()
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3030, TARGET_ENE_0, local4, 0, 0)
arg0:SetTimer(6, 10)
return true
elseif arg0:IsInterupt(INTERUPT_FLAG_ActivateSpecialEffect) and arg0:GetNumber(0) == 1 and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_F, 360, 6) and arg0:IsActivateSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5529) and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_F, 180, 12) and arg0:IsInsideTargetEx(TARGET_ENE_0, TARGET_SELF, AI_DIR_TYPE_L, 270, 12) then
arg1:ClearSubGoal()
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3031, TARGET_ENE_0, local4, 0, 0)
return true
else
return false
end
end
return
|
--
-- Author: Your Name
-- Date: 2016-06-21 10:22:14
--
local EventPool = class('EventPool', Map)
function EventPool:ctor()
EventPool.super.ctor(self)
end
return EventPool
|
--ai--
------
--ghost process
function pr_g(o)
--in pen
if(o.m==1)then
--collisions off
o.col=0
o.s=o.ss.p
local p=pen[o.i-1]
if(o.t==0)then
new_sdir(o,3)
if(o.y<p.y-2)then
o.t=1
end
else
new_sdir(o,1)
if(o.y>p.y+2)then
o.t=0
end
end
--active
elseif(o.m==2)then
--collisions on
o.col=1
--in tunnel
if(mget(
flr((o.x+4)/8),
flr((o.y+4)/8))==50)then
o.s=gv.gts--slow
else
o.s=o.ss.s--normal
end
--scared
if(o.sc==1)then
o.s=gv.gfs
rnd_mv(o)
return
end
if(ai_mode==0)then
--scatter
sct_mv(o)
else
--ai bug emulate
local ofs=0
if(o.ym<0)then
ofs=-1
end
--chase
if(o.i==1)then
--target the player
trg_mv(o,pac.x,pac.y)
elseif(o.i==2)then
--target 4 tiles in
--front of player
trg_mv(o,
pac.x+(pac.xm+ofs)*40,
pac.y+pac.ym*40)
elseif(o.i==3)then
--target away from red
--in relation to the player
local b=enes[1]
trg_mv(o,
b.x+((pac.x+(pac.xm+ofs)*16)-b.x)*2,
b.y+((pac.y+pac.ym*16)-b.y)*2)
elseif(o.i==4)then
--move towards until
--we get too close then
--scatter
if(dist(o.x,pac.x,o.y,pac.y)>70)then
trg_mv(o,pac.x,pac.y)
else
sct_mv(o)
end
end
end
--back to pen
elseif(o.m==4)then
o.s=o.ss.r
--move towards the pen door
trg_mv(o,pen_d.x,pen_d.y)
--check dist from pen
if(gdist(o,pen_d)<12)then
o.m=5
end
--enter pen
elseif(o.m==5)then
--collisions off
o.col=0
o.s=o.ss.r
--move into the door
new_sdir(o,1)
--in the pen?
if(o.y>=pen_d.y+8)then
restore_anim(o)
o.m=6
--not scared
o.sc=0
end
--exit pen
elseif(o.m==6)then
--collisions off
o.col=0
o.s=o.ss.p
if(pen_d.x-o.x>1)then
new_sdir(o,0)
elseif(pen_d.x-o.x<-1)then
new_sdir(o,2)
else
o.x=pen_d.x
new_sdir(o,3)
end
--out of the pen?
if(o.y<=pen_d.y-6)then
o.m=2
o.r=0
o.it=0
release_flag=0
end
end
end
--returns true when
--at an intersection
function ck_it(o)
if(flr(o.x)%8==0
and flr(o.y)%8==0)then
if(o.it==0)then
o.it=1
--reverse flag check
if(o.r==1)then
o.r=0
o.xm*=-1 o.ym*=-1
return false
end
return true
end
else
o.it=0
end
return false
end
--check directions
--finds avalible directions
function ck_dir(o)
--get current tile id
local tid=mget(
flr((o.x+4)/8),
flr((o.y+4)/8))
local dl={}
local b=(get_sdir(o)+2)%4
if(col_ck(o,1,0)==false
and b!=0)then
add(dl,0) end
if(col_ck(o,0,1)==false
and b!=1)then
add(dl,1) end
if(col_ck(o,-1,0)==false
and b!=2)then
add(dl,2) end
if(col_ck(o,0,-1)==false
and b!=3
--not over an up blocker
and ((tid!=49
and tid!=51)
--scared mode ignores
--the up blocker
or o.sc==1))then
add(dl,3) end
return dl
end
--attract movement
function atr_mv(o)
o.sc=1
--at intersection
if(ck_it(o))then
--get avalible directions
local dl=ck_dir(o,p)
--count directions
local c=0
for _ in all(dl)do c+=1 end
--pick one at random
if(c>1 or col_ck(o))then
dn+=1
new_sdir(o,dr[dn])
end
end
end
--scatter movement
--moves to a corner based
--on id
function sct_mv(o)
if(o.i==1)then
trg_mv(o,cx*2-40,0)
elseif(o.i==2)then
trg_mv(o,30,0)
elseif(o.i==3)then
trg_mv(o,cx*2-40,cy*2)
elseif(o.i==4)then
trg_mv(o,30,cy*2)
end
end
--random movement
--picks a random avalible
--direction
function rnd_mv(o)
--at intersection
if(ck_it(o))then
--get avalible directions
local dl=ck_dir(o)
--count directions
local c=0
for _ in all(dl)do c+=1 end
--pick one at random
if(c>0)then
new_sdir
(o,dl[flr(rnd(c)+1)])
end
end
end
--target move
--move towards a target
function trg_mv(o,tx,ty)
--at intersection
if(ck_it(o))then
--get avalible directions
local dl=ck_dir(o)
--count directions
local c=0
for _ in all(dl)do c+=1 end
local cd=0--closest dist
local fd=0--final direction
--find closest to target
for i=1,c,1 do
local d=dl[i]--dir to test
local dt=0--dir dist
--get dir dist
if(d==0)then
dt=dist(o.x+8,tx,o.y,ty)
elseif(d==1)then
dt=dist(o.x,tx,o.y+8,ty)
elseif(d==2)then
dt=dist(o.x-8,tx,o.y,ty)
elseif(d==3)then
dt=dist(o.x,tx,o.y-8,ty)
end
if(i==1 or dt<cd)then
cd=dt
fd=d
end
end
if(c>0)then
new_sdir(o,fd)
end
end
end
--change actor direction
--(if possible)
function new_dir(o,xm,ym)
-- if collision of actor o, when xmoved and ymoved is false
if(col_ck(o,xm,ym)==false
--turn radius
and col_ck(o,xm,ym,o.xm*2,o.ym*2)==false)then
o.xm=xm or 0
o.ym=ym or 0
if(o.col==1)then
--snap to grid
if(o.ym!=0)then
o.x=flr((o.x+4)/8)*8
elseif(o.xm!=0)then
o.y=flr((o.y+4)/8)*8
end
end
end
end
function new_sdir(o,d)
if(d==0)then
new_dir(o,1,0)
elseif(d==1)then
new_dir(o,0,1)
elseif(d==2)then
new_dir(o,-1,0)
elseif(d==3)then
new_dir(o,0,-1)
end
end
function get_sdir(o)
return max(o.ym,0)
+(min(o.xm,0)*-2)
+(min(o.ym,0)*-3)
end
--check actor collision
--in a particular direction
function col_ck(o,xm,ym,xs,ys)
--collision off flag
if(o.col==0)then
return false
end
xm=xm or o.xm
ym=ym or o.ym
local x=o.x-(xs or 0)
local y=o.y-(ys or 0)
if(ym!=0)then
x=flr((x+4)/8)*8
end
if(xm!=0)then
y=flr((y+4)/8)*8
end
--get the tile in front
--of the actor
local idx=flr((x+min(xm,0))/8)+max(xm,0)
local idy=flr((y+min(ym,0))/8)+max(ym,0)
--out of bounds?
if(idx>=19 or idx<0)then
return false
end
--get tile id
local id=mget(idx+msh,idy)
--true if collision
return (fget(id,0)==true)
end
|
-- list of installable lang-servers
-- https://github.com/neovim/nvim-lspconfig/blob/master/CONFIG.md
--
local lsp = require("lspconfig")
local function lua_lsp(lsp, on_attach)
local lsp_root = vim.fn.system("echo -n $HOME/.local/share/lua-language-server")
local lsp_binary = lsp_root .. "/bin/lua-language-server"
lsp.sumneko_lua.setup({
on_attach = on_attach,
cmd = { lsp_binary, "-E", lsp_root .. "/main.lua" },
settings = {
Lua = {
runtime = {
version = "LuaJIT",
path = vim.split(package.path, ";"),
},
diagnostics = {
globals = { "vim" }, -- Get the language server to recognize the `vim` global
},
workspace = {
library = { -- Make the server aware of Neovim runtime files
[vim.fn.expand("$VIMRUNTIME/lua")] = true,
[vim.fn.expand("$VIMRUNTIME/lua/vim/lsp")] = true,
},
},
telemetry = {
enable = false,
},
},
},
})
end
-- on attach is not used right now but could be used by other
-- plugins in the future
local function setup(on_attach)
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require("cmp_nvim_lsp").update_capabilities(capabilities)
-- capabilities.textDocument.completion.completionItem.snippetSupport = true
lsp.rust_analyzer.setup({
on_attach = on_attach,
capabilities = capabilities,
settings = {
["rust-analyzer"] = {
assist = {
importMergeBehavior = "last",
importGranularity = "module",
importPrefix = "by_self",
},
cargo = {
loadOutDirsFromCheck = true,
},
procMacro = {
enable = true,
},
},
},
})
lsp.pylsp.setup({ on_attach = on_attach }) -- python
lsp.texlab.setup({ on_attach = on_attach }) -- latex
lsp.jsonls.setup({ capabilities = capabilities }) --json
lsp.bashls.setup({ on_attach = on_attach }) -- bash
lua_lsp(lsp, on_attach)
-- needs a compile_commands.json file; easiest to generate
-- using bear; `make clean; bear -- make`
lsp.clangd.setup({ -- c++ and c
on_attach = on_attach,
filetypes = { "c", "cpp", "hpp", "cc" },
})
end
setup()
|
cc.exports.CoreElementInstance = {}
local CoreElement = class("CoreElement", cc.load("mvc").ViewBase)
local CoreElementMecha = import("..models.CoreElementMecha")
CoreElement.GROUND = 120;
CoreElement.G = -0.6;
function CoreElement:onCreate()
CoreElementInstance = self
-- add touch layer
self._left = false
self._right = false
self._player = nil
self._bullets = {}
self.worldClock = db.WorldClock:getInstance()
local dragonBonesData = db.CCFactory:getInstance():loadDragonBonesData("CoreElement/CoreElement.json")
db.CCFactory:getInstance():loadTextureAtlasData("CoreElement/CoreElement_texture_1.json")
if(dragonBonesData) then
self:scheduleUpdate(handler(self, self._enterFrameHandler))
self:addKeyboadEvent()
display.newLayer(cc.c3b(105,105,105))
:addTo(self)
:onTouch(handler(self,self.onTouch))
self._player = CoreElementMecha:create()
end
end
function CoreElement:addBullet(bullet)
table.insert(self._bullets, bullet)
end
function CoreElement:_enterFrameHandler(passedTime)
self._player:update()
local remove = {}
for k, b in pairs(self._bullets) do
if(b:update()) then
table.insert(remove,b)
end
end
for k, v in pairs(remove) do
table.removebyvalue(self._bullets,v,false)
end
self.worldClock:advanceTime(passedTime)
end
function CoreElement:onTouch(event)
if(event.name == "began") then
self._player:attack(true)
return true
elseif(event.name == "ended") then
self._player:attack(false)
elseif(event.name == "moved") then
local target = cc.p(event.x,event.y)
self._player:aim(target)
end
end
function CoreElement:addKeyboadEvent()
local function keyboadPressed(keyCode, event)
if keyCode == 124 or keyCode == 26 then -- a
self._left = true
self:_updateMove(-1)
elseif keyCode == 127 or keyCode == 27 then -- d
self._right = true
self:_updateMove(1)
elseif keyCode == 146 or keyCode == 28 then -- w
self._player:jump()
elseif keyCode == 142 or keyCode == 29 then -- s
self._player:squat(true)
elseif keyCode == 140 then -- q
self._player:switchWeaponR()
elseif keyCode == 128 then -- e
self._player:switchWeaponL()
elseif keyCode == 59 then -- space
self._player:switchWeaponR()
self._player:switchWeaponL()
else
print("keyPress" .. keyCode)
end
end
local function keyboardReleased(keyCode, event)
if keyCode == 124 or keyCode == 26 then -- a
self._left = false
self:_updateMove(-1)
elseif keyCode == 127 or keyCode == 27 then -- d
self._right = false
self:_updateMove(1)
elseif keyCode == 142 or keyCode == 29 then -- s
self._player:squat(false)
else
print("keyReleased" .. keyCode)
end
end
local listener = cc.EventListenerKeyboard:create()
listener:registerScriptHandler(keyboadPressed, cc.Handler.EVENT_KEYBOARD_PRESSED)
listener:registerScriptHandler(keyboardReleased, cc.Handler.EVENT_KEYBOARD_RELEASED)
local dispatcher = cc.Director:getInstance():getEventDispatcher()
dispatcher:addEventListenerWithSceneGraphPriority(listener, self)
end
function CoreElement:_updateMove(dir)
if (self._left and self._right) then
self._player:move(dir);
elseif (self._left) then
self._player:move(-1);
elseif (self._right) then
self._player:move(1);
else
self._player:move(0)
end
end
return CoreElement
|
local luaType = type
local function type(arg)
local t = luaType(arg)
if t == "table" or t == "userdata" then
local mt = getmetatable(arg)
local mtt = luaType(mt)
if mtt == "table" then
local n = mt.__name
if n then t = n end
elseif mtt == "string" then
t = mt
end
end
return t
end
return type
|
-- Calculates an elementwise minimum of two random matrices on GPU
local cv = require "cv"
require "cutorch"
require "cv.cudaarithm"
local n = 5
local a = (torch.rand(n, n) * 10):int():float():cuda()
local b = (torch.rand(n, n) * 10):int():float():cuda()
local min_torch = torch.FloatTensor(n, n)
for i = 1, n do
for j = 1, n do
min_torch[i][j] = math.min(a[i][j], b[i][j])
end
end
print("CUDA context initialization in OpenCV may take up to a minute. Hang on...")
local min_cv = cv.cuda.min{a, b}
if n <= 20 then
print("Matrix of minimums by Torch:")
print(min_torch)
print("Matrix of minimums by CUDA-OpenCV:")
print(min_cv)
end
if (min_torch:eq(min_cv:float()) - 1):sum() == 0 then
print("OpenCV-CUDA's min() function works fine!")
else
print("You shouldn't see this message -- something went wrong! Please contact developers.")
end
|
local DPBR = require("love-DPBR")
local mgl = require("MGL")
mgl.gen_mat(3); mgl.gen_vec(3)
local env_tr = mgl.mat3(mgl.vec3(1,0,0), mgl.vec3(0,-1,0), mgl.vec3(0,0,1))
local app = {info = "3D baked scene.\n\nModel by Andrew Maximov.\n(http://artisaverb.info/PBT.html)"}
local scene = DPBR.newScene(1280,720)
scene:setProjection2D(50, "log", 10, 10*9/16)
scene:setToneMapping("filmic")
scene:setAntiAliasing("FXAA")
scene:setAmbientBRDF(love.graphics.newImage("BRDF_LUT.exr"))
local t_albedo = love.graphics.newImage("scene_albedo.jpg")
local t_normal = love.graphics.newImage("scene_normal.png")
local t_DE = love.graphics.newImage("scene_DE.exr")
local t_MRA = love.graphics.newImage("scene_MRA.jpg")
local env_diffuse = love.graphics.newCubeImage("env_diffuse.dds")
local env_specular = love.graphics.newCubeImage("env_specular.dds", {mipmaps = true})
env_specular:setMipmapFilter("linear")
function app.tick(dt)
end
function app.draw()
local time = love.timer.getTime()
local x,y = love.mouse.getPosition()
scene:bindMaterialPass()
scene:bindMaterialN(t_normal)
scene:bindMaterialMRA(t_MRA)
scene:bindMaterialDE(t_DE)
love.graphics.draw(t_albedo,0,0)
scene:bindLightPass()
scene:drawEnvironmentLight(env_diffuse, env_specular, 1, env_tr)
scene:drawEmissionLight()
love.graphics.setColor(HSL(time/50%1, 1, 0.5))
scene:drawPointLight(x/scene.w*10,y/scene.h*10*9/16,2,50,25)
scene:drawPointLight(x/scene.w*10,y/scene.h*10*9/16,15,50,25)
love.graphics.setColor(1,1,1)
scene:bindBackgroundPass()
scene:bindBlendPass()
scene:render()
end
return app
|
--[[
Copland Awesome WM theme 2.0
github.com/lcpz
--]]
local gears = require("gears")
local lain = require("lain")
local awful = require("awful")
local wibox = require("wibox")
local dpi = require("beautiful.xresources").apply_dpi
local awesome, client, os = awesome, client, os
local my_table = awful.util.table or gears.table -- 4.{0,1} compatibility
local theme = {}
theme.dir = os.getenv("HOME") .. "/.config/awesome/themes/copland"
theme.wallpaper = theme.dir .. "/wall.png"
theme.font = "Terminus 10.5"
theme.fg_normal = "#BBBBBB"
theme.fg_focus = "#78A4FF"
theme.bg_normal = "#111111"
theme.bg_focus = "#111111"
theme.fg_urgent = "#000000"
theme.bg_urgent = "#FFFFFF"
theme.border_width = dpi(1)
theme.border_normal = "#141414"
theme.border_focus = "#93B6FF"
theme.taglist_fg_focus = "#FFFFFF"
theme.taglist_bg_focus = "#111111"
theme.taglist_bg_normal = "#111111"
theme.titlebar_bg_normal = "#191919"
theme.titlebar_bg_focus = "#262626"
theme.menu_height = dpi(16)
theme.menu_width = dpi(130)
theme.tasklist_disable_icon = true
theme.awesome_icon = theme.dir .."/icons/awesome.png"
theme.menu_submenu_icon = theme.dir .. "/icons/submenu.png"
theme.taglist_squares_sel = theme.dir .. "/icons/square_unsel.png"
theme.taglist_squares_unsel = theme.dir .. "/icons/square_unsel.png"
theme.vol = theme.dir .. "/icons/vol.png"
theme.vol_low = theme.dir .. "/icons/vol_low.png"
theme.vol_no = theme.dir .. "/icons/vol_no.png"
theme.vol_mute = theme.dir .. "/icons/vol_mute.png"
theme.disk = theme.dir .. "/icons/disk.png"
theme.ac = theme.dir .. "/icons/ac.png"
theme.bat = theme.dir .. "/icons/bat.png"
theme.bat_low = theme.dir .. "/icons/bat_low.png"
theme.bat_no = theme.dir .. "/icons/bat_no.png"
theme.play = theme.dir .. "/icons/play.png"
theme.pause = theme.dir .. "/icons/pause.png"
theme.stop = theme.dir .. "/icons/stop.png"
theme.layout_tile = theme.dir .. "/icons/tile.png"
theme.layout_tileleft = theme.dir .. "/icons/tileleft.png"
theme.layout_tilebottom = theme.dir .. "/icons/tilebottom.png"
theme.layout_tiletop = theme.dir .. "/icons/tiletop.png"
theme.layout_fairv = theme.dir .. "/icons/fairv.png"
theme.layout_fairh = theme.dir .. "/icons/fairh.png"
theme.layout_spiral = theme.dir .. "/icons/spiral.png"
theme.layout_dwindle = theme.dir .. "/icons/dwindle.png"
theme.layout_max = theme.dir .. "/icons/max.png"
theme.layout_fullscreen = theme.dir .. "/icons/fullscreen.png"
theme.layout_magnifier = theme.dir .. "/icons/magnifier.png"
theme.layout_floating = theme.dir .. "/icons/floating.png"
theme.useless_gap = 0
theme.titlebar_close_button_focus = theme.dir .. "/icons/titlebar/close_focus.png"
theme.titlebar_close_button_normal = theme.dir .. "/icons/titlebar/close_normal.png"
theme.titlebar_ontop_button_focus_active = theme.dir .. "/icons/titlebar/ontop_focus_active.png"
theme.titlebar_ontop_button_normal_active = theme.dir .. "/icons/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_inactive = theme.dir .. "/icons/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_inactive = theme.dir .. "/icons/titlebar/ontop_normal_inactive.png"
theme.titlebar_sticky_button_focus_active = theme.dir .. "/icons/titlebar/sticky_focus_active.png"
theme.titlebar_sticky_button_normal_active = theme.dir .. "/icons/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_inactive = theme.dir .. "/icons/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_inactive = theme.dir .. "/icons/titlebar/sticky_normal_inactive.png"
theme.titlebar_floating_button_focus_active = theme.dir .. "/icons/titlebar/floating_focus_active.png"
theme.titlebar_floating_button_normal_active = theme.dir .. "/icons/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_inactive = theme.dir .. "/icons/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_inactive = theme.dir .. "/icons/titlebar/floating_normal_inactive.png"
theme.titlebar_maximized_button_focus_active = theme.dir .. "/icons/titlebar/maximized_focus_active.png"
theme.titlebar_maximized_button_normal_active = theme.dir .. "/icons/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_inactive = theme.dir .. "/icons/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_inactive = theme.dir .. "/icons/titlebar/maximized_normal_inactive.png"
-- lain related
theme.layout_centerfair = theme.dir .. "/icons/centerfair.png"
theme.layout_termfair = theme.dir .. "/icons/termfair.png"
theme.layout_centerwork = theme.dir .. "/icons/centerwork.png"
local markup = lain.util.markup
local blue = theme.fg_focus
local red = "#EB8F8F"
local green = "#8FEB8F"
-- Textclock
--os.setlocale(os.getenv("LANG")) -- to localize the clock
local mytextclock = wibox.widget.textclock("<span font='Terminus 5'> </span>%H:%M ")
mytextclock.font = theme.font
-- Calendar
theme.cal = lain.widget.cal({
attach_to = { mytextclock },
notification_preset = {
font = "Terminus 11",
fg = theme.fg_normal,
bg = theme.bg_normal
}
})
-- Mail IMAP check
--[[ commented because it needs to be set before use
theme.mail = lain.widget.imap({
timeout = 180,
server = "server",
mail = "mail",
password = "keyring get mail",
settings = function()
mail = ""
count = ""
if mailcount > 0 then
mail = "<span font='Terminus 5'> </span>Mail "
count = mailcount .. " "
end
widget:set_markup(markup(blue, mail) .. count)
end
})
--]]
-- MPD
local mpdicon = wibox.widget.imagebox()
theme.mpd = lain.widget.mpd({
settings = function()
if mpd_now.state == "play" then
title = mpd_now.title
artist = " " .. mpd_now.artist .. markup("#777777", " <span font='Terminus 2'> </span>|<span font='Terminus 5'> </span>")
mpdicon:set_image(theme.play)
elseif mpd_now.state == "pause" then
title = "mpd "
artist = "paused" .. markup("#777777", " |<span font='Terminus 5'> </span>")
mpdicon:set_image(theme.pause)
else
title = ""
artist = ""
mpdicon._private.image = nil
mpdicon:emit_signal("widget::redraw_needed")
mpdicon:emit_signal("widget::layout_changed")
end
widget:set_markup(markup.font(theme.font, markup(blue, title) .. artist))
end
})
-- Battery
local baticon = wibox.widget.imagebox(theme.bat)
local batbar = wibox.widget {
forced_height = dpi(1),
forced_width = dpi(59),
color = theme.fg_normal,
background_color = theme.bg_normal,
margins = 1,
paddings = 1,
ticks = true,
ticks_size = dpi(6),
widget = wibox.widget.progressbar,
}
local batupd = lain.widget.bat({
settings = function()
if (not bat_now.status) or bat_now.status == "N/A" or type(bat_now.perc) ~= "number" then return end
if bat_now.status == "Charging" then
baticon:set_image(theme.ac)
if bat_now.perc >= 98 then
batbar:set_color(green)
elseif bat_now.perc > 50 then
batbar:set_color(theme.fg_normal)
elseif bat_now.perc > 15 then
batbar:set_color(theme.fg_normal)
else
batbar:set_color(red)
end
else
if bat_now.perc >= 98 then
batbar:set_color(green)
elseif bat_now.perc > 50 then
batbar:set_color(theme.fg_normal)
baticon:set_image(theme.bat)
elseif bat_now.perc > 15 then
batbar:set_color(theme.fg_normal)
baticon:set_image(theme.bat_low)
else
batbar:set_color(red)
baticon:set_image(theme.bat_no)
end
end
batbar:set_value(bat_now.perc / 100)
end
})
local batbg = wibox.container.background(batbar, "#474747", gears.shape.rectangle)
local batwidget = wibox.container.margin(batbg, dpi(2), dpi(7), dpi(4), dpi(4))
-- /home fs
--[[ commented because it needs Gio/Glib >= 2.54
local fsicon = wibox.widget.imagebox(theme.disk)
local fsbar = wibox.widget {
forced_height = dpi(1),
forced_width = dpi(59),
color = theme.fg_normal,
background_color = theme.bg_normal,
margins = 1,
paddings = 1,
ticks = true,
ticks_size = dpi(6),
widget = wibox.widget.progressbar,
}
theme.fs = lain.widget.fs {
notification_preset = { fg = theme.fg_normal, bg = theme.bg_normal, font = "Terminus 10.5" },
settings = function()
if fs_now["/home"].percentage < 90 then
fsbar:set_color(theme.fg_normal)
else
fsbar:set_color("#EB8F8F")
end
fsbar:set_value(fs_now["/home"].percentage / 100)
end
}
local fsbg = wibox.container.background(fsbar, "#474747", gears.shape.rectangle)
local fswidget = wibox.container.margin(fsbg, dpi(2), dpi(7), dpi(4), dpi(4))
--]]
-- ALSA volume bar
local volicon = wibox.widget.imagebox(theme.vol)
theme.volume = lain.widget.alsabar {
width = dpi(59), border_width = 0, ticks = true, ticks_size = dpi(6),
notification_preset = { font = theme.font },
--togglechannel = "IEC958,3",
settings = function()
if volume_now.status == "off" then
volicon:set_image(theme.vol_mute)
elseif volume_now.level == 0 then
volicon:set_image(theme.vol_no)
elseif volume_now.level <= 50 then
volicon:set_image(theme.vol_low)
else
volicon:set_image(theme.vol)
end
end,
colors = {
background = theme.bg_normal,
mute = red,
unmute = theme.fg_normal
}
}
theme.volume.tooltip.wibox.fg = theme.fg_focus
theme.volume.bar:buttons(my_table.join (
awful.button({}, 1, function()
awful.spawn(string.format("%s -e alsamixer", awful.util.terminal))
end),
awful.button({}, 2, function()
os.execute(string.format("%s set %s 100%%", theme.volume.cmd, theme.volume.channel))
theme.volume.update()
end),
awful.button({}, 3, function()
os.execute(string.format("%s set %s toggle", theme.volume.cmd, theme.volume.togglechannel or theme.volume.channel))
theme.volume.update()
end),
awful.button({}, 4, function()
os.execute(string.format("%s set %s 1%%+", theme.volume.cmd, theme.volume.channel))
theme.volume.update()
end),
awful.button({}, 5, function()
os.execute(string.format("%s set %s 1%%-", theme.volume.cmd, theme.volume.channel))
theme.volume.update()
end)
))
local volumebg = wibox.container.background(theme.volume.bar, "#474747", gears.shape.rectangle)
local volumewidget = wibox.container.margin(volumebg, dpi(2), dpi(7), dpi(4), dpi(4))
-- Weather
theme.weather = lain.widget.weather({
city_id = 2643743, -- placeholder (London)
})
-- Separators
local first = wibox.widget.textbox(markup.font("Terminus 3", " "))
local spr = wibox.widget.textbox(' ')
local small_spr = wibox.widget.textbox(markup.font("Terminus 4", " "))
local bar_spr = wibox.widget.textbox(markup.font("Terminus 3", " ") .. markup.fontfg(theme.font, "#777777", "|") .. markup.font("Terminus 5", " "))
-- Eminent-like task filtering
local orig_filter = awful.widget.taglist.filter.all
-- Taglist label functions
awful.widget.taglist.filter.all = function (t, args)
if t.selected or #t:clients() > 0 then
return orig_filter(t, args)
end
end
function theme.at_screen_connect(s)
-- Quake application
s.quake = lain.util.quake({ app = awful.util.terminal })
-- If wallpaper is a function, call it with the screen
local wallpaper = theme.wallpaper
if type(wallpaper) == "function" then
wallpaper = wallpaper(s)
end
gears.wallpaper.maximized(wallpaper, s, true)
-- Tags
awful.tag(awful.util.tagnames, s, awful.layout.layouts)
-- Create a promptbox for each screen
s.mypromptbox = awful.widget.prompt()
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(my_table.join(
awful.button({}, 1, function () awful.layout.inc( 1) end),
awful.button({}, 2, function () awful.layout.set( awful.layout.layouts[1] ) end),
awful.button({}, 3, function () awful.layout.inc(-1) end),
awful.button({}, 4, function () awful.layout.inc( 1) end),
awful.button({}, 5, function () awful.layout.inc(-1) end)))
-- Create a taglist widget
s.mytaglist = awful.widget.taglist(s, awful.widget.taglist.filter.all, awful.util.taglist_buttons)
-- Create a tasklist widget
s.mytasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, awful.util.tasklist_buttons)
-- Create the wibox
s.mywibox = awful.wibar({ position = "top", screen = s, height = dpi(18), bg = theme.bg_normal, fg = theme.fg_normal })
-- Add widgets to the wibox
s.mywibox:setup {
layout = wibox.layout.align.horizontal,
{ -- Left widgets
layout = wibox.layout.fixed.horizontal,
small_spr,
s.mylayoutbox,
first,
bar_spr,
s.mytaglist,
first,
s.mypromptbox,
},
s.mytasklist, -- Middle widget
{ -- Right widgets
layout = wibox.layout.fixed.horizontal,
wibox.widget.systray(),
small_spr,
--theme.mail.widget,
mpdicon,
theme.mpd.widget,
baticon,
batwidget,
bar_spr,
--fsicon,
--fswidget,
bar_spr,
volicon,
volumewidget,
bar_spr,
mytextclock,
},
}
end
return theme
|
-- example HTTP POST script which demonstrates setting the
-- HTTP method, body, and adding a header
wrk.method = "POST"
wrk.body = {"message":"Hi!"}
wrk.headers["Content-Type"] = "application/json"
|
--------------------------------------------------------------------------------
-- store
--------------------------------------------------------------------------------
local _PACKAGE = string.gsub(...,"%.","/") or ""
local _M = require(_PACKAGE .. "/ohm")
return _M
|
local pure = {}
pure.pure = {
command = {"pure"},
open = ":paste\n",
close = "\04",
}
return pure
|
object_building_player_shared_atat_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_atat_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_atat_house, "object/building/player/shared_atat_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_bespin_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_bespin_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_bespin_house, "object/building/player/shared_bespin_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_commando_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_commando_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_commando_house, "object/building/player/shared_commando_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_emperors_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_emperors_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_emperors_house, "object/building/player/shared_emperors_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_generic_large_window_s01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_generic_large_window_s01.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_generic_large_window_s01, "object/building/player/shared_generic_large_window_s01.iff")
--**************************************************************************************************************************************
object_building_player_shared_generic_large_window_s02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_generic_large_window_s02.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_generic_large_window_s02, "object/building/player/shared_generic_large_window_s02.iff")
--**************************************************************************************************************************************
object_building_player_shared_generic_medium_window_s01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_generic_medium_window_s01.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_generic_medium_window_s01, "object/building/player/shared_generic_medium_window_s01.iff")
--**************************************************************************************************************************************
object_building_player_shared_generic_medium_window_s02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_generic_medium_window_s02.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_generic_medium_window_s02, "object/building/player/shared_generic_medium_window_s02.iff")
--**************************************************************************************************************************************
object_building_player_shared_generic_small_window_s01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_generic_small_window_s01.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_generic_small_window_s01, "object/building/player/shared_generic_small_window_s01.iff")
--**************************************************************************************************************************************
object_building_player_shared_generic_small_window_s02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_generic_small_window_s02.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_generic_small_window_s02, "object/building/player/shared_generic_small_window_s02.iff")
--**************************************************************************************************************************************
object_building_player_shared_hangar_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_hangar_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_hangar_house, "object/building/player/shared_hangar_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_jabbas_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_jabbas_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_jabbas_house, "object/building/player/shared_jabbas_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_jedi_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_jedi_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_jedi_house, "object/building/player/shared_jedi_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_vipbunker_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_vipbunker_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_vipbunker_house, "object/building/player/shared_vipbunker_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_musty_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_musty_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_musty_house, "object/building/player/shared_musty_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_ns_hut_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_ns_hut.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_ns_hut_house, "object/building/player/shared_ns_hut.iff")
--**************************************************************************************************************************************
object_building_player_shared_rebel_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_rebel_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_rebel_house, "object/building/player/shared_rebel_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_relaxation_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_relaxation_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_relaxation_house, "object/building/player/shared_relaxation_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_sandcrawler_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_sandcrawler_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_sandcrawler_house, "object/building/player/shared_sandcrawler_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_sith_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_sith_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_sith_house, "object/building/player/shared_sith_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_sm_hut_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_sm_hut.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_sm_hut_house, "object/building/player/shared_sm_hut.iff")
--**************************************************************************************************************************************
object_building_player_shared_tree_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_tree_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_tree_house, "object/building/player/shared_tree_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_vehicle_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_vehicle_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_vehicle_house, "object/building/player/shared_vehicle_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_yoda_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_yoda_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_yoda_house, "object/building/player/shared_yoda_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_yt1300_house = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_yt1300_house.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_yt1300_house, "object/building/player/shared_yt1300_house.iff")
--**************************************************************************************************************************************
object_building_player_shared_naboo_small_window_s01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_naboo_small_window_s01.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_naboo_small_window_s01, "object/building/player/shared_naboo_small_window_s01.iff")
--**************************************************************************************************************************************
object_building_player_shared_tatooine_small_window_s01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_tatooine_small_window_s01.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_tatooine_small_window_s01, "object/building/player/shared_tatooine_small_window_s01.iff")
--**************************************************************************************************************************************
object_building_player_shared_player_pgc_merchant_tent_s01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_pgc_merchant_tent_s01.iff"
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_pgc_merchant_tent_s01, "object/building/player/shared_player_pgc_merchant_tent_s01.iff")
|
netstream.Hook( "ChangeQuestVar", function( ply, identifier, varKey, value )
netstream.Start( nil, "ReceiveQuestVar", identifier, varKey, value );
end );
|
local L, this = ...
this.title = "Table Extension Library"
this.version = "1.0"
this.status = "production"
this.desc = "Provides extensions for operating on tables."
local utable
local test
utable = {
--[[
@method equal
#title Equality
#def (table first, table second, [boolean no_reverse])
#returns boolean result, [mixed error_key]
#desc Checks if each value of tables first and second are equal.
#desc If result is false, error_key contains the first key where a mismatch occured.
#desc If no_reverse is true, only first is iterated through. This is used internally.
]]
equal = function(self, first, second, no_reverse)
for key, value in pairs(first) do
if (second[key] ~= value) then
return false, key
end
end
if (not no_reverse) then
return utable:equal(second, first, true)
else
return true
end
end,
--[[
@method congruent
#title Congruency
#def (table first, table second, [boolean no_reverse])
#returns boolean result, [mixed error_key]
#desc Checks if first and second are equal recursively. Tables are iterated through.
#desc If result is false, error_key contains the first key where a mismatch occured.
#desc If no_reverse is true, only first is iterated through. This is used internally.
]]
congruent = function(self, first, second, no_reverse)
for key, value in pairs(first) do
local value2 = second[key]
if (type(value) == type(value2)) then
if (type(value) == "table") then
if (not utable:congruent(value, value2)) then
return false, key
end
else
if (value ~= value2) then
return false, key
end
end
else
return false, key
end
end
if (not no_reverse) then
return utable:congruent(second, first, true)
else
return true
end
end,
--[[
@method copylock
#title Copylock
#def (table target)
#returns table target
#desc Sets a flag in the table that forces copying and merging functions to not copy this table.
]]
copylock = function(self, target)
target.__nocopy = true
return target
end,
--[[
@method copy
#title Shallow Copy
#def (table source, [table target])
#returns table target
#desc Performs a shallow copy from source to target.
#desc If target is not specified, a new table is created. The location copied to is returned.
]]
copy = function(self, source, target)
target = target or {}
for key, value in pairs(source) do
target[key] = value
end
return target
end,
--[[
@method deepcopy
#title Deep Copy
#def (table source, [table target, boolean break_lock])
#returns table target
#desc Performs a deep copy from source to target.
#desc If a target is not specified, a new table is created. The location copied to is returned.
#desc If break_lock is true, any copylocked tables are copied anyway.
]]
deepcopy = function(self, source, target, break_lock)
target = target or {}
for key, value in pairs(source) do
if (type(value) == "table") then
if (value.__nocopy and not break_lock) then
target[key] = value
else
target[key] = utable:deepcopy(value)
end
else
target[key] = value
end
end
return target
end,
--[[
@method merge
#title Shallow Merge
#def (table source, table target)
#returns table target
#desc Performs a shallow merge from source to target.
#desc Values from source are copied into target unless they already exist.
]]
merge = function(self, source, target)
if (not target) then
return nil
end
for key, value in pairs(source) do
if (not target[key]) then
target[key] = value
end
end
return target
end,
--[[
@method copymerge
#title Shallow Copy-Merge
#def (table source, table target)
#returns table target
#desc Performs a shallow merge from source to target.
#desc Values from source are copied into target unless they already exist.
#desc Table values are copied unless they are copylocked.
#desc If break_lock is true, any copylocked tables are copied anyway.
]]
copymerge = function(self, source, target, break_lock)
if (not target) then
return nil
end
for key, value in pairs(source) do
if (not target[key]) then
if (type(value) == "table") then
if (not value.__nocopy and not break_lock) then
target[key] = utable:copy(value)
else
target[key] = value
end
else
target[key] = value
end
end
end
return target
end,
--[[
@method invert
#title Invert
#def (table source, [table target])
#returns table target
#desc Inverts the table source into target. All keys become values and vice versa.
#desc Behavior with duplicate values is undefined.
#desc If not target is not defined, a new table will be created.
]]
invert = function(self, source, target)
target = target or {}
for key, value in pairs(source) do
target[value] = key
end
return target
end,
--[[
@method contains
#title Contains Value
#def (table source, mixed value)
#return boolean result
#desc Returns whether the desired value exists in the table
]]
contains = function(self, source, value)
for key, compare in pairs(source) do
if (compare == value) then
return true
end
end
return false
end
}
return utable
|
local wibox = require ('wibox')
local awful = require ('awful')
local gears = require ('gears')
local beautiful = require ('beautiful')
local darker = require ('util.color').darker
local pi = require ('util.panel_item')
local dpi = beautiful.xresources.apply_dpi
local time = function (s,side)
local time_box = wibox {
visible = true,
screen = s,
type = 'dock',
ontop = true,
width = dpi(60),
height = dpi(15),
border_width = beautiful.panel.border_width,
border_color = beautiful.panel.border_color,
splash = true,
shape = beautiful.rounded_rect_shape,
widget = {}
}
time_box : setup {
pi {
widget = wibox.widget {
{
format = "%I:%M %p",
font = beautiful.small_font,
widget = wibox.widget.textclock
},
widget = wibox.container.place
},
shape = beautiful.rounded_rect_shape,
margins = dpi(3),
-- margins = 0,
},
layout = wibox.layout.flex.horizontal
}
if side == 'top' then
awful.placement.top_right(time_box)
else
awful.placement.bottom_right(time_box)
end
return time_box
end
return time
|
resource_manifest_version '05cfa83c-a124-4cfa-a768-c24a5811d8f9'
ui_page 'html/index.html'
files {
'html/index.html',
'html/*'
}
client_script 'config.lua'
client_script 'client.lua'
exports {
'AddButton' , 'SetTitle'
}
|
local util = require("spec.util")
describe("rawget", function()
it("reads ", util.check [[
local self = {
fmt = "hello"
}
local str = "hello"
local a = {str:sub(2, 10)}
]])
end)
|
object_building_general_ord_filler_e = object_building_general_shared_ord_filler_e:new {
}
ObjectTemplates:addTemplate(object_building_general_ord_filler_e, "object/building/general/ord_filler_e.iff")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.