Roblox: Data is Saving, But Fails when trying to load? - roblox

So what I've been trying is to Save a certain "Text" to the DataStore from a TextLabel, The Data Saves Successfully, But when trying to load it gives me just gives me a "Failed", Any Help?
Here's a Quick Video: https://www.youtube.com/watch?v=W-J6U8zmATk&feature=youtu.be
Script:
local DataStoreService = game:GetService("DataStoreService")
local IDStorage = DataStoreService:GetDataStore("IDStorage3")
elseif Player.Team.Name == "Intelligence Agency" then
if Player:IsInGroup(7503826) or Player:GetRankInGroup(7465879) >= 251 then
Rank.User.Text = "[REDACTED]"
Rank.User.Back.Text = "[REDACTED]"
Rank.Rank.TextColor3 = Color3.new(0.827451, 0, 0)
game.ReplicatedStorage.NewID.OnServerEvent:Connect(function(player, playerToID, AssignedID)
if player:IsInGroup(7465879) then
local success, err = pcall(function()
IDStorage:SetAsync(playerToID, AssignedID)
end)
if success then
print("Data Assigned") -- Data Works and Saves
else
warn("Failed to Save")
end
end
end)
local ID = IDStorage:GetAsync(Player)
if ID then
print(ID)
else
warn("Failed") -- Always Returns me this.
Rank.Rank.Text = "0"
end
Rank.User.Text = "[REDACTED]"
Rank.User.Back.Text = "[REDACTED]"
end

The DataStore:GetAsync(key) function expects a string for the key. It looks like you're passing in a Player object and not the player's username, which you said was the key that you were storing the data in.
Try this swapping this line
local ID = IDStorage:GetAsync(Player)
for this instead :
local success, result = pcall(function()
local key = Player.Name
return IDStorage:GetAsync(key)
end
if success then
print("Got Id : ", result)
local ID = result
if ID then
-- do stuff with the result
else
-- looks like a new player with no saved data
end
else
warn("failed to get id with error :", result)
-- do something to handle the error, like retry
end
Something to be careful about when saving data is that usernames can change. If I were to change my name, the next time I joined this game, all of my progress would be gone because the name doesn't match up with the saved key. That is why a player's userId tends to be the recommend key.

Related

Attempt to index nil to 'Takedamage'

the thing is that im making a combat system, and there is the situation with line 56 that says: enemyHumanoid:TakeDamage(Damage) and the error says: ServerScriptService.CombatSystem:56: attempt to index nil with 'TakeDamage' and i dont know what to do (also this is the entire code)
local rp = game:GetService("ReplicatedStorage")
local Combat = rp:WaitForChild("Combat")
local Debris = game:GetService("Debris")
local Animations = script:WaitForChild("Animations")
local Meshes = script:WaitForChild("Meshes")
local anims =
{
Animations:WaitForChild("Right"),
Animations:WaitForChild("Left"),
Animations:WaitForChild("Gut"),
Animations:WaitForChild("Kick"),
}
local limbs =
{
"RightHand",
"LeftHand",
"RightHand",
"RightFoot"
}
local Damage = 10
Combat.OnServerEvent:Connect(function(player,count)
local Character = player.Character
local Humanoid = Character:WaitForChild("Humanoid")
local attack = Humanoid:LoadAnimation(anims[count])
attack:Play()
local Limb = Character:WaitForChild(limbs[count])
local folder = Instance.new("Folder",Character)
folder.Name = player.Name.."Melee"
local Hitbox = Meshes:WaitForChild("Hitbox"):Clone()
Hitbox.CFrame = Limb.CFrame
Hitbox.Parent = folder
Debris:AddItem(Hitbox,.5)
local weld = Instance.new("ManualWeld")
weld.Part0 = Hitbox
weld.Part1 = Limb
weld.C0 = weld.Part0.CFrame:ToObjectSpace(weld.Part1.CFrame)
weld.Parent = weld.Part0
Hitbox.Touched:Connect(function(Hit)
if Hit:IsA("BasePart") then
if not Hit:IsDescendantOf(Character) then
local enemyHumanoid = Hitbox.Parent:FindFirstChild("Humanoid")
if Humanoid then
Hitbox:Destroy()
enemyHumanoid:TakeDamage(Damage)
end
end
end
end)
Combat:FireClient(player)
end)
i haven't try a lot but it keeps getting errors
Welcome to StackOverflow! :FindFirstChild("Humanoid") returns nil if the Humanoid doesn't exist, which is why enemyHumanoid:TakeDamage() isn't working. Try using this snippet in place of the current Hitbox.Touched function:
Hitbox.Touched:Connect(function(Hit)
if Hit:IsA("BasePart") and not Hit:IsDescendantOf(Character) then
local enemyHumanoid = Hitbox.Parent:FindFirstChild("Humanoid")
if Humanoid then
Hitbox:Destroy()
if enemyHumanoid then -- Make sure enemyHumanoid exists and isn't nil
enemyHumanoid:TakeDamage(Damage)
end
end
end
end)

Flutter list stores values using for loop, but loses these values when used outside the loop

I am trying to read data from a firebase real time database and store it in a list to use in my flutter app.
As seen in the code below, I start by creating a reference to the database. I also create some global variables, where "itemName" stores the name of the item in the database, "itemID" stores the id of each item in the database and "itemNames" is a list of all the item names in the database.
The "activate listeners" method listens to the database, and returns any values if they are changed. Each item ID starts with a J, and continues onto J1, J2, J3 etc. Hence I am using a for loop to access all the item IDs.
The issue I am having is that the itemNames are successfully being stored in the itemNames list, and can be see when I print the list within the for loop (The first print line).
However, when I try print the list value OUTSIDE the for loop, it prints an empty list for loop (second print line).
So in other words, the list is not retaining the elements added to it during the for loop.
Any help would be much appreciated!
final DatabaseReference _dbRef = FirebaseDatabase.instance.ref();
late StreamSubscription _dailySpecialStream;
//Stores the description of each menu item in the DB
String itemName = "";
String itemID = "";
List<String> itemNames = [];
//"Listens for any changes being made to the DB, and updates our app in real time"
void _activateListeners() {
for (int i = 0; i <= 10; i++) {
itemID = "J$i";
_dailySpecialStream =
_dbRef.child("menuItem/$itemID/itemName").onValue.listen((event) {
itemName = event.snapshot.value.toString();
itemNames.addAll([itemName]);
print(itemNames);
});
}
print(itemNames);
}
That is the expected behavior. Data is loaded from Firebase (and most modern cloud APIs) asynchronously, and while that is happening your main code continues to run.
You can most easily see this by placing some print statements:
print('before starting to load data');
for (int i = 0; i <= 10; i++) {
itemID = "J$i";
_dailySpecialStream =
_dbRef.child("menuItem/$itemID/itemName").onValue.listen((event) {
print('loaded data: %i');
});
}
print('after starting to load data');
If you run this, you'll see something like:
before starting to load data
after starting to load data
loaded data: 0
loaded data: 1
loaded data: 2
loaded data: 3
...
So as you can see the after print statement that is lowest in your code, actually printed before any of the data was loaded. This is probably not what you expected, but explains perfectly why the print statement you had outside the loop doesn't print the data: it hasn't been loaded yet!
The solution for this type of problem is always the same: you have to make sure the code that requires the data is inside the callback, or it is called from there, or it is otherwise synchronized.
A simple way to do the latter is by using get() instead of onValue, and then use await on the Future that is returns:
print('before starting to load data');
for (int i = 0; i <= 10; i++) {
itemID = "J$i";
_dailySpecial = await _dbRef.child("menuItem/$itemID/itemName").get();
print('loaded data %i: ${_dailySpecial.value}');
}
print('after starting to load data');
Now with this, the print statements will be in the order you expected.

Neovim lsp auto-fix / fix-current?

I was looking for a solution similar to CoC's coc-fix-current but using native lsp for Neovim 0.5 but I did not find such thing in the documentation, is there any way to achieve this through other method?
I had this problem and by hacking up the code that the telescope.nvim plugin uses to list and run code actions, came up with this monstrosity:
local function run_action(action, offse)
if action.edit or type(action.command) == "table" then
if action.edit then
vim.lsp.util.apply_workspace_edit(action.edit, offse)
end
if type(action.command) == "table" then
vim.lsp.buf.execute_command(action.command)
end
else
vim.lsp.buf.execute_command(action)
end
end
local function do_action(action, client)
if
not action.edit
and client
and type(client.resolved_capabilities.code_action) == "table"
and client.resolved_capabilities.code_action.resolveProvider
then
client.request("codeAction/resolve", action, function(err, real)
if err then
return
end
if real then
run_action(real, client.offset_encoding)
else
run_action(action, client.offset_encoding)
end
end)
else
run_action(action, client.offset_encoding)
end
end
return function()
local params = vim.lsp.util.make_range_params() -- get params for current position
params.context = {
diagnostics = vim.lsp.diagnostic.get_line_diagnostics(),
only = {"quickfix"}
}
local results, err = vim.lsp.buf_request_sync(
0, -- current buffer
"textDocument/codeAction", -- get code actions
params,
900
)
if err then return end
if not results or vim.tbl_isempty(results) then
print "No quickfixes!"
return
end
-- we have an action!
for cid, resp in pairs(results) do
if resp.result then
for _, result in pairs(resp.result) do
-- this is the first action, run it
do_action(result, vim.lsp.get_client_by_id(cid))
return
end
end
end
print "No quickfixes!"
end
Since it's lua, you'll need to place it in a .lua file somewhere that nvim searches for modules (for example, as ~/.config/nvim/lua/lsp_fixcurrent.lua) and then bind to :lua require("lsp_fixcurrent")()
As of neovim 0.8, thanks to this PR, there's an apply boolean which does just that.
To make sure you only apply relevant fixes, you can use the filter attribute and look for the "prefered" fixes.
Here's what I've put in my config :
local opts = { noremap=true, silent=true }
local function quickfix()
vim.lsp.buf.code_action({
filter = function(a) return a.isPreferred end,
apply = true
})
end
vim.keymap.set('n', '<leader>qf', quickfix, opts)
mincrmatt12 answer, updated for newer neovim (0.8?) which complains client.resolved_capabilities should not be used.
local function run_action(action, offse)
if action.edit or type(action.command) == "table" then
if action.edit then
vim.lsp.util.apply_workspace_edit(action.edit, offse)
end
if type(action.command) == "table" then
vim.lsp.buf.execute_command(action.command)
end
else
vim.lsp.buf.execute_command(action)
end
end
local function do_action(action, client)
if
not action.edit
and client
and type(client.server_capabilities) == "table"
and client.server_capabilities.resolveProvider
then
client.request("codeAction/resolve", action, function(err, real)
if err then
return
end
if real then
run_action(real, client.offset_encoding)
else
run_action(action, client.offset_encoding)
end
end)
else
run_action(action, client.offset_encoding)
end
end
return function()
local params = vim.lsp.util.make_range_params() -- get params for current position
params.context = {
diagnostics = vim.lsp.diagnostic.get_line_diagnostics(),
only = { "quickfix" },
}
local results, err = vim.lsp.buf_request_sync(
0, -- current buffer
"textDocument/codeAction", -- get code actions
params,
900
)
if err then
return
end
if not results or vim.tbl_isempty(results) then
print("No quickfixes!")
return
end
-- we have an action!
for cid, resp in pairs(results) do
if resp.result then
for _, result in pairs(resp.result) do
-- this is the first action, run it
do_action(result, vim.lsp.get_client_by_id(cid))
return
end
end
end
print("No quickfixes!")
end
Maybe you are looking for: vim.lsp.buf.code_action()?

Saving jTextPane text not working properly

I'm trying to save a "history" I'm building after you sent a command from a line, so every time you press Enter the commands goes to the jTextPane with a line separator... However when I save the file it doesn't seem to get the line separator. Example, my jTextPane has something like:
Create database user
use database user
show tables from database
Instead of saving the workspace just like that, it gives me this:
Create database useruse database usershow tables from database
What should I do? Here's my code
String ar;
String TEXTO = jTextPane1.getText() + System.lineSeparator();
FileFilter ft = new FileNameExtensionFilter("Text Files", ".txt");
FC.setFileFilter(ft);
int returnVal = FC.showSaveDialog(this);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
java.io.File saved_file = FC.getSelectedFile();
String file_name = saved_file.toString();
File archivo;
ar = "" + file_name + ".txt";
archivo = new File(ar);
try {
if (saved_file != null) {
try (FileWriter GUARDADO = new FileWriter(ar)) {
GUARDADO.write(TEXTO);
}
}
} catch (IOException exp) {
System.out.println(exp);
}
}
You need to use :
jTextPane1.getDocument().getText(0,jTextPane1.getDocument().getLength());
The issue is that you need to use /n instead of System.lineSeparator. The JTextPane behavior doesn't depends on the System.

NotesSession.GetDataBase method is returning null value

I have a c# class which was written to read the lotus emails for any attachments and save it to the local drive. It was working fine when I pass "" as first parameter to GetDataBase method and full path of .nsf file of my local system as second argument. But, if I remove "" and I specify my local system full name as first argument it is returning null value.
Is it problem with any permissions? If so, it should not work even when I pass "" as first parameter. Otherwise, should I have any other permissions at system/server level?
Please help me in this issue.
Finally, I could do it in the following way. And I thought of posting it to some one can atleast not to suffer again.
Following code is to read the attachment from the lotus emails and save it to the physical location.
string lotusServerName = ConfigurationSettings.AppSettings["Lotus_Server"].ToString();
string lotusDBFilePath = ConfigurationSettings.AppSettings["Lotus_DB_File_Path"].ToString();
string password = ConfigurationSettings.AppSettings["Password"].ToString();
string sourceFolder = ConfigurationSettings.AppSettings["Source_Folder"].ToString();
string targetFolder = ConfigurationSettings.AppSettings["Target_Folder"].ToString();
string documentsFolder = ConfigurationSettings.AppSettings["Documents_Folder"].ToString();
//Creating the notes session and passing password
NotesSession session = new NotesSession();
session.Initialize(password);
//Getting the DB instance by passing the servername and path of the mail file.
//third param "false" will try to check the DB availability by opening the connection
//if it cannot open, then it returns null.
NotesDatabase NotesDb = session.GetDatabase(lotusServerName, lotusDBFilePath, false);
//Get the view of the source folder
NotesView inbox = NotesDb.GetView(sourceFolder);
//looping through each email/document and looking for the attachments
//if any attachments found, saving them to the given specified location
//moving the read mails to the target folder
NotesDocument docInbox = null;
int docCnt = inbox.EntryCount;
for (int currDoc = 0; currDoc < docCnt; currDoc++) {
docInbox = inbox.GetFirstDocument();
object[] items = (object[])docInbox.Items;
foreach (NotesItem nItem in items) {
if (nItem.Name == "$FILE") {
NotesItem file = docInbox.GetFirstItem("$File");
string fileName = ((object[])nItem.Values)[0].ToString();
NotesEmbeddedObject attachfile = (NotesEmbeddedObject)docInbox.GetAttachment(fileName);
if (attachfile != null) {
attachfile.ExtractFile(documentsFolder + fileName);
}
}
}
docInbox.PutInFolder(targetFolder, true);//"true" creates the folder if it doesn't exists
docInbox.RemoveFromFolder(sourceFolder);
}
//releasing resources
if (session != null)
session = null;
if (NotesDb != null)
NotesDb = null;
if (inbox != null)
inbox = null;
if (docInbox != null)
docInbox = null;
Following is values read from .config file.
The above code will work properly if you alredy have lotus mail client in your system and you are able to access mails from your mail server. You don't require any other previliges.