ERROR transform{component_kind="transform" component_id=cut_field component_type=lua component_name=cut_field}: vector::internal_events::lua: Error in lua script; discarding event. error=RuntimeErrorHooksProcess { source: RuntimeError("[string "src/transforms/lua/v2/mod.rs:158:17"]:23: attempt to index a nil value (global 'json')\nstack traceback:\n\t[string "src/transforms/lua/v2/mod.rs:158:17"]:23: in function 'hook_process'") } internal_log_rate_secs=30
This is my config:
`[transforms.cut_field]
type = "lua"
inputs = ["log_source"]
version = "2"
search_dirs = [ "/usr/lib64/lua" ]
source = """
function hook_process(event, emit)
if next(event) == nil then
print("event empty")
end
if event == nil then
print("event is nil")
end
local str = json.encode(event)
print(str)
emit(event)
end
"""
hooks.process = "hook_process"`
My vector version is: vector 0.17.0 (x86_64-unknown-linux-gnu 3d34cde 2021-10-08)
Related
So recently I'm trying to make a GlobalBan script for my admin module in ROBLOX, but I came across an error when I tried to do GlobalBan.
Below is the error and script:
local defaultDatabase = "Private";
local authenticationToken = "Private"
local HttpService = game:GetService("HttpService");
local DataStoreService = game:GetService("DataStoreService");
local FirebaseService = {};
local UseFirebase = true;
--== Script;
function FirebaseService:SetUseFirebase(value)
UseFirebase = value and true or false;
end
function FirebaseService:GetFirebase(name, database)
database = database or defaultDatabase;
local datastore = DataStoreService:GetDataStore(name);
local databaseName = database..HttpService:UrlEncode(name);
local authentication = ".json?auth="..authenticationToken;
local Firebase = {};
function Firebase.GetDatastore()
return datastore;
end
function Firebase:GetAsync(directory)
local data = nil;
--== Firebase Get;
local getTick = tick();
local tries = 0; repeat until pcall(function() tries = tries +1;
data = HttpService:GetAsync(databaseName..HttpService:UrlEncode(directory and "/"..directory or "")..authentication, true);
end) or tries > 2;
if type(data) == "string" then
if data:sub(1,1) == '"' then
return data:sub(2, data:len()-1);
elseif data:len() <= 0 then
return nil;
end
end
return tonumber(data) or data ~= "null" and data or nil;
end
function Firebase:SetAsync(directory, value, header)
if not UseFirebase then return end
if value == "[]" then self:RemoveAsync(directory); return end;
--== Firebase Set;
header = header or {["X-HTTP-Method-Override"]="PUT"};
local replyJson = "";
if type(value) == "string" and value:len() >= 1 and value:sub(1,1) ~= "{" and value:sub(1,1) ~= "[" then
value = '"'..value..'"';
end
local success, errorMessage = pcall(function()
replyJson = HttpService:PostAsync(databaseName..HttpService:UrlEncode(directory and "/"..directory or "")..authentication, value,
Enum.HttpContentType.ApplicationUrlEncoded, false, header);
end);
if not success then
warn("FirebaseService>> [ERROR] "..errorMessage);
pcall(function()
replyJson = HttpService:JSONDecode(replyJson or "[]");
end)
end
end
function Firebase:RemoveAsync(directory)
if not UseFirebase then return end
self:SetAsync(directory, "", {["X-HTTP-Method-Override"]="DELETE"});
end
function Firebase:IncrementAsync(directory, delta)
delta = delta or 1;
if type(delta) ~= "number" then warn("FirebaseService>> increment delta is not a number for key ("..directory.."), delta(",delta,")"); return end;
local data = self:GetAsync(directory) or 0;
if data and type(data) == "number" then
data = data+delta;
self:SetAsync(directory, data);
else
warn("FirebaseService>> Invalid data type to increment for key ("..directory..")");
end
return data;
end
function Firebase:UpdateAsync(directory, callback)
local data = self:GetAsync(directory);
local callbackData = callback(data);
if callbackData then
self:SetAsync(directory, callbackData);
end
end
return Firebase;
end
return FirebaseService;
Error Code:
23:50:36.033 TestService: Data table for bans is currently nil. - Studio
23:50:36.255 FirebaseService>> [ERROR] HTTP 401 (Unauthorized) - Studio
I have tried to create new database + renewing my auth token, still getting Error code 401.
I feel like its my auth token issue but at the same time I don't think it is either, hope you guys can help me figure out the error. Feel free to ask if you need more info regarding this issue.
It turns out my auth token was the wrong one, everything's good now
I'm new to LUA and tried learning coding this language with Garrys Mod.
I want to get the messages from the Garrys Mod chat and send them into a Discord channel with a webhook.
It works, but I tried expanding this project with embeded messages. I need JSON for this and used json.lua as a library.
But as soon as I send a message I retrieve the following error message:
attempt to index global 'json' (a nil value)
The code that causes the error is the following:
json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
The complete code:
AddCSLuaFile()
json = require("json")
webhookURL = "https://discordapp.com/api/webhooks/XXX"
local DiscordWebhook = DiscordWebhook or {}
hook.Add( "PlayerSay", "SendMsg", function( ply, text )
t_post = {
content = json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
username = "Log",
}
http.Post(webhookURL, t_post)
end )
I hope somebody can help me
Garry's Mod does provide two functions to work with json.
They are:
util.TableToJSON( table table, boolean prettyPrint=false )
and
util.JSONToTable( string json )
There is no need to import json and if I recall correctly it isn't even possible.
For what you want to do you need to build your arguments as a table like this:
local arguments = {
["key"] = "Some value",
["42"] = "Not always the answer",
["deeper"] = {
["my_age"] = 22,
["my_name"] = getMyName()
},
["even more"] = from_some_variable
and then call
local args_as_json = util.TableToJSON(arguments)
Now you can pass args_as_json to your
http.Post( string url, table parameters, function onSuccess=nil, function onFailure=nil, table headers={} )
I have tasked myself with writing a file writer in Ceylon and in the process of doing so I have been hit by the crushing difficulty of writing an if statement in Ceylon, that will be allowed to pass when facing the mighty Wizard of Type Correctness on the narrow Bridge of Compilation in the far far land of Ceylon:
The error I get is "Error:(10, 1) ceylon: incorrect syntax: missing EOF at 'if'"
This is my if statement (the first line is line 10):
if (is Nil fileResource || is File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
EDIT:
this is my if statement updated according to Bastien Jansens recommendation. The error, however, remains the same :(
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
This is the full source code of my application:
import ceylon.http.server { newServer, startsWith, Endpoint, Request, Response }
import ceylon.io { SocketAddress }
import ceylon.file { Path, parsePath, File, createFileIfNil, FResource = Resource }
// let's create a file with "hello world":
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
shared void runServer() {
//create a HTTP server
value server = newServer {
//an endpoint, on the path /hello
Endpoint {
path = startsWith("/postBPset");
//handle requests to this path
function service(Request request, Response response) {
variable String logString;
variable String jsonString;
variable String contentType;
contentType = request.contentType
else "(not specified)";
logString = "Received " + request.method.string + " request \n"
+ "Content type: " + contentType + "\n"
+ "Request method: " + request.method.string + "\n";
jsonString = request.read();
print(logString);
return response;
}
}
};
//start the server on port 8080
server.start(SocketAddress("127.0.0.1",8080));
}
The || operator cannot be used in conjunction with if (is ...), the correct way to achieve what you want is using a union type:
if (is Nil|File fileResource) {
...
}
|| would be valid in the following syntax, but you would lose the refinement (it would only be a boolean expression, not a type refinement):
if (fileResource is Nil || fileResource is File ) {
...
}
The || operator only works on Boolean expressions (which foo is Bar is), whereas is Bar foo is a Boolean condition, which is a different construct. The same applies for exists conditions vs exists operators.
EDIT: oh, and of course you need to put that if statement in a function, toplevel elements can only be declarations (classes, functions or values, if statements are not allowed).
for (character <- content) {
if (character == '\n') {
val current_line = line.mkString
line.clear()
current_line match {
case docStartRegex(_*) => {
startDoc = true
endText = false
endDoc = false
}
case docnoRegex(group) => {
docID = group.trim
}
case docTextStartRegex(_*) => {
startText = true
}
case docTextEndRegex(_*) => {
endText = true
startText = false
}
case docEndRegex(_*) => {
endDoc = true
startDoc = false
es_json = Json.obj(
"_index" -> "ES_SPARK_AP",
"_type" -> "document",
"_id" -> docID,
"_source" -> Json.obj(
"text" -> textChunk.mkString(" ")
)
)
// yield es_json
textChunk.clear()
}
case _ => {
if (startDoc && !endDoc && startText) {
textChunk += current_line.trim
}
}
}
} else {
line += character
}
}
The above for-loop parses through a text file and creates a JSON object of each chunk parsed in a loop. This is JSON will be sent to for further processing to Elasticsearch. In python, we can yield the JSON and use generator easily like:
def func():
for i in range(num):
... some computations ...
yield {
JSON ## JSON is yielded
}
for json in func(): ## we parse through the generator here.
process(json)
I cannot understand how I can use yield in similar fashion using scala?
If you want lazy returns, scala does this using Iterator types. Specifically if you want to handle line by line values, I'd split it into lines first with .lines
val content: String = ???
val results: Iterator[Json] =
for {
lines <- content.lines
line <- lines
} yield {
line match {
case docEndRegex(_*) => ...
}
}
You can also use a function directly
def toJson(line: String): Json =
line match {
case "hi" => Json.obj("line" -> "hi")
case "bye" => Json.obj("what" -> "a jerk")
}
val results: Iterator[Json] =
for {
lines <- content.lines
line <- lines
} yield toJson(line)
This is equivalent to doing
content.lines.map(line => toJson(line))
Or somewhat equivalently in python
lines = (line.strip() for line in content.split("\n"))
jsons = (toJson(line) for line in lines)
Scenario:
Trying to call the .AttachAll method on a table in my LinqToSql DataContext object.
Here's the relevant simplified snippet:
public void Update(Customer cust){
MyDataContext db = new MyDataContext();
db.CustomerInvoices.AttachAll(cust.Invoices); //exception raised here!
db.Customer.Attach(cust);
}
Exception raised by the Compiler:
The type arguments for method
'System.Data.Linq.Table(Invoices).AttachAll(TSubEntity)(System.Collections.Generic.IEnumerable(TSubEntity))'
cannot be inferred from the usage. Try
specifying the type arguments
explicitly.
Question: What is the proper way to cast the collection properly? Any other solutions besides a cast?
Tf cust.Invoices already refers to instances of the CustomerInvoices table, just doing
db.Customers.Attach(cust); db.Update(); should be all you need to do.
If CustomerInvoices is a different type from Customer.Invoice, you'll probably need to iterate through the collection, and cast each one.
else if (((CheckBox)item.Cells[2].FindControl("ckbSelect")).Checked == true && ((Label)item.Cells[2].FindControl("lblIsInuse")).Text == "1")
{
RolePage objTemp = new RolePage();
objTemp = new Helper().GetRolePagebyID(roleId, Convert.ToInt32(item.Cells[0].Text));
rp.RoleId = objTemp.RoleId;
rp.PageId = objTemp.PageId;
rp.RolePageId = objTemp.RolePageId;
rp.CreatedOn = objTemp.CreatedOn;
rp.Timestamp = objTemp.Timestamp;
//rp.RoleId = roleId;
//rp.PageId = Convert.ToInt32(item.Cells[0].Text);
//rp.RolePageId =Convert.ToInt32(((Label)item.Cells[2].FindControl("lblRolePageId")).Text.Trim());
rp.IsNew = false;
rp.IsDeleted = false;
rp.UpdatedOn = DateTime.Now;
erp.Add(rp);
}
public string Save(Role objRole)
{
string message = string.Empty;
System.Data.Common.DbTransaction trans = null;
try
{
Objdb.Connection.Open();
trans = Objdb.Connection.BeginTransaction();
Objdb.Transaction = trans;
if (objRole.RoleId == 0)
{
Objdb.Roles.InsertOnSubmit(objRole);
}
else
{
Objdb.Roles.Attach(objRole, true);
Objdb.RolePages.AttachAll(objRole.RolePages.Where(a => a.IsNew == false && a.IsDeleted == false), true);
Objdb.RolePages.InsertAllOnSubmit(objRole.RolePages.Where(a => a.IsNew == true && a.IsDeleted == false));
Objdb.RolePages.DeleteAllOnSubmit(objRole.RolePages.Where(a => a.IsNew == false && a.IsDeleted == true));
}
Objdb.SubmitChanges();
trans.Commit();
message = "Record saved successfully.";
}
catch (Exception ex)
{
trans.Rollback();
message = "Error : " + ex.Message;
}
return message;
}