|
Learning programming.
Step 1: Learn English.
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
I have a program I am working on. First I will explain what I have done and then get to the question. I have created a undo and redo functions that when undo, it deletes one character at a time from the string and puts it in a 'List<char>'. Then when you click redo, it goes to the 'List' and adds each character back to the string and deletes it from the list, one character at a time. You can see in the pictures the undo and redo menu button click events for them in the 1st pic. They get their functions from the 2nd pic., the undo redo class. I also have a keydown and text change function shown in pic. 3. All functions work good but the clearing of the 'list' that remains if they don't 'redo' all commands. I can undo and redo and have no problems, but I want it to delete the list contents after the user starts to type again after undoing and redoing. I have tried to put it in the text change but it keeps firing every time the list is over '0' and after the menu redo is enabled. I have tried putting in the buttons function, and I even tried to do the stack<char> process, but I could not get my head wrapped around that option. I know that 'richTxtDirections.Text = richTxtDirections.Text.Remove(richTxtDirections.Text.Length - 1);' deletes 1 character, but how do you say if the 'text.length +1' from where you stop to undo and redo, how to add a character. I hope I am explaining this fine for you to understand and that someone can possibly help me with this part, even if it is not adding 1 to the text.length. Thank you.
private void menuUndoEdit_Click(object sender, EventArgs e)
{
menuUndoEditClicked = true;
UndoRedo.undo();
if (richTxtDirections.Text.Length > 0)
{
richTxtDirections.Text = richTxtDirections.Text.Remove(richTxtDirections.Text.Length - 1);
richTxtDirections.Select(richTxtDirections.Text.Length, 0);
}
if (menuRedoEdit.Enabled == false)
{
menuRedoEdit.Enabled = true;
menuRedoEdit.Font = new Font(menuRedoEdit.Font, FontStyle.Regular);
menuRedoEdit.ForeColor = Color.Black;
menuRedoEdit.Text = "Redo";
}
menuUndoEditClicked = false;
}
private void menuRedoEdit_Click(object sender, EventArgs e)
{
menuRedoEditClicked = true;
UndoRedo.redo();
if (UndoRedo.charList.Count == 0)
{
menuRedoEdit.Enabled = false;
menuRedoEdit.Font = new Font(menuRedoEdit.Font, FontStyle.Italic);
menuRedoEdit.ForeColor = Color.DarkGray;
menuRedoEdit.Text = "Can't Redo";
}
menuRedoEditClicked = false;
richTxtDirections.Focus();
}
private void richTxtDirections_KeyDown(object sender, KeyEventArgs e)
{
lblCount2.Text = richTxtDirections.Text.Length + "/750";
if (richTxtDirections.Focused == true && richTxtDirections.Text != string.Empty)
{
if (menuUndoEdit.Enabled == false)
{
menuUndoEdit.Enabled = true;
menuUndoEdit.Font = new Font(menuUndoEdit.Font, FontStyle.Regular);
menuUndoEdit.ForeColor = Color.Black;
}
if (e.KeyCode == Keys.Z && (e.Control))
{
e.Handled = true;
menuUndoEdit.PerformClick();
}
else if (e.KeyCode == Keys.Y && e.Control)
{
e.Handled = true;
menuRedoEdit.PerformClick();
}
}
}
private void richTxtDirections_TextChanged(object sender, EventArgs e)
{
if (UndoRedo.charList.Count > 0 && menuRedoEditClicked == false)
{
UndoRedo.clearList();
}
}
public void undo()
{
if (frmDashboard.instance.tbrdDirections.Text.Length > 0)
{
charList.Add(frmDashboard.instance.tbrdDirections.Text[frmDashboard.instance.tbrdDirections.Text.Length - 1]);
}
}
public void redo()
{
if (charList.Count > 0)
{
var lastItem = charList.Last();
frmDashboard.instance.tbrdDirections.AppendText(lastItem.ToString());
charList.RemoveAt(charList.Count - 1);
}
}
public void clearList()
{
if (charList.Count > 0)
{
charList.Clear();
frmDashboard.instance.mnuRedoEdit.Enabled = false;
}
}
|
|
|
|
|
If you want to clear the list when someone "types", why do you have extra conditions in the text changed event?
if (UndoRedo.charList.Count > 0 && menuRedoEditClicked == false)
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Because I don't want it to clear it every time the text changes or keydown event fires but just after the user starts to type and quit. So I tried to put an extra condition to help stop it but its not. I hope I am explaining myself right.
|
|
|
|
|
I think you need to better explain what "type and quit" means. And you're talking as if "text changes" and "key down" are somehow independent. Maybe you should be looking at individual key presses in the preview key down event.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
I'm sorry Gerry. I wondered if I explained it wrong. Let me try this again. I was looking for help on how to delete the list<char> after the user is finished 'undo' commands or 'redo' commands, and the user starts typing on the keyboard, in the rich textbox, the rest of the directions for a recipe. I have used the the 'keydown' function to add the command that if a key was pressed, to delete the list if its greater than 0, but it deletes the list every time the user clicks the 'ctrl' and 'z' shortcut. I don't want it to empty the new characters added to the list by the 'undo' function, because there would be nothing left if he needs to 'redo' one or two. I was thinking if there was a text change, something like typing then stop to 'undo' and start typing again, that it may work, but it does not. Still deletes each character. I'm not even sure if that would be considered text change also. So now I am at a point I am asking if someone knows what how. I'm am fairly new at programming and have learned everything about it myself and doing it all myself. I know I explain things wrong or have the wrong terms for whatever, and I'm sorry if I did not explain better. My hubby always tells me I cant explain things the way they should be.
|
|
|
|
|
Your "key down" goes off and does something in "PerformClick()". I'd look there.
menuUndoEdit.PerformClick();
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
mjcs100 wrote: I have created a undo and redo functions that when undo, it deletes one character at a time from the string and puts it in a 'List<char>' Yah, that changes a char, but doesn't do/undo the last action.
You want a memento-pattern. It's easier, cleaner, and better, because it also can do/undo any font-changes.
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
I am not sure what controls you are using, but have you checked undo/redo is not already supported by the control - I would expect it is.
For example:
Windows Forms Redo[^]
WPF Redo[^]
Your implementation is very limited. As already mentioned you do not handle formatting - but you also assume the last character is the last one entered.
|
|
|
|
|
You might consider using Stack<t> versus List<t> for charList.
It has Push() (add to list), Peek() (look at the "topmost" list member), and Pop() (retrieve value and remove the topmost list member).
It is just the sort of LIFO collection it sounds like you may want.
|
|
|
|
|
I have this class User:
[Serializable()]
[XmlRoot("Users")]
public class Users
{
[XmlArrayItem(typeof(User))]
public List<User> UsersList { get; set; }
}
[Serializable()]
public class User
{
[System.Xml.Serialization.XmlAttribute("ID")]
public string ID { get; set; }
[System.Xml.Serialization.XmlElementAttribute("Name")]
public string Name { get; set; }
[System.Xml.Serialization.XmlElementAttribute("Username")]
public string Username { get; set; }
[System.Xml.Serialization.XmlElementAttribute("Password")]
public string Password { get; set; }
[System.Xml.Serialization.XmlElementAttribute("Email")]
public string Email { get; set; } = string.Empty;
}
And this:
private void Serialization()
{
var path = @"D:\Projects\repo\xml\users.xml";
var newUsers = new Users();
newUsers.UsersList = new List<User>();
var user = new User
();
user.Email = txtEmail.Text;
user.Name = txtName.Text;
user.Password = txtPass.Text;
user.ID =txtID.Text;
newUsers.UsersList.Add(user);
XmlSerializer serializer = new XmlSerializer(typeof(Users));
using (TextWriter writer = new StreamWriter(path,true))
{
serializer.Serialize(writer, newUsers);
}
}
And it saves this xml:
<?xml version="1.0" encoding="utf-8"?>
<Users xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UsersList>
<User ID="A">
<Name>a</Name>
<Password>a</Password>
<Email>a</Email>
</User>
</UsersList>
</Users><?xml version="1.0" encoding="utf-8"?>
<Users xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UsersList>
<User ID="SSSS">
<Name>s</Name>
<Password>s</Password>
<Email>ss</Email>
</User>
</UsersList>
</Users>
But I want to save the xml file in this format:
<?xml version="1.0" encoding="utf-8"?>
<Users xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UsersList>
<User ID="A">
<Name>a</Name>
<Password>a</Password>
<Email>a</Email>
</User>
<User ID="SSSS">
<Name>s</Name>
<Password>s</Password>
<Email>ss</Email>
</User>
</UsersList>
The most important thing is that I have a windows form with some textboxes and every time I run the application and register a new user I want it to pe added in <UsersList> not overwritten over the existing ones
|
|
|
|
|
You need to deserialize the existing file contents, and overwrite the entire file. If you just serialize the new users and append it to the file, you'll end up with multiple XML documents in a single file, which is not valid.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Take a look at your Serialization method. Why are you creating a new list of Users, adding one user to it, and then overwriting the file you already have?
Method should do one thing and only one thing. Your Serialization method is not responsible for creating a list of users and adding users to it. It should be renamed SerializeUsersToFile and do only that job.
Maintaining a list of users should be done by your Users class. It should expose methods for adding and removing them.
Another class can be created that handles Serializing and Deserializing a Users class to the file. When you want to update the file, you call the SerializeUsersToFile method and pass the Users object to it. When you want the users to be loaded from the file, you call another method, DeserializeUsersFromFile, and it should return a populated Users object.
|
|
|
|
|
To add to what the others have said, I'd suggest that you read this: That's not a database, dude![^] XML is a transfer format, not a data storage format.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Please help make this code work. I'm trying to run it in Visual Studio 2022. Thanks.
<pre lang="C#">
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Numpy;
using Python.Runtime;
using Keras;
using Keras.Layers;
using Keras.Models;
using Keras.Optimizers;
using Keras.losses;
namespace SQLInjectionDetection
{
class Program
{
static void Main(string[] args)
{
var trainData = File.ReadAllLines("tokens.csv")
.Select(l => l.Split(','))
.Select(s => new { Token = s[0], Label = int.Parse(s[1]) })
.ToList();
var random = new Random();
trainData = trainData.OrderBy(d => random.Next()).ToList();
var splitIndex = (int)(trainData.Count * 0.8);
var trainDataSubset = trainData.Take(splitIndex).ToList();
var testDataSubset = trainData.Skip(splitIndex).ToList();
var vocabulary = new HashSet<char>(trainDataSubset.SelectMany(d => d.Token).Distinct());
var tokenToIndex = vocabulary.Select((c, i) => new { Token = c, Index = i }).ToDictionary(t => t.Token, t => t.Index);
var maxSequenceLength = trainDataSubset.Max(d => d.Token.Length);
var trainTokenized = Tokenize(trainDataSubset, tokenToIndex, maxSequenceLength);
var testTokenized = Tokenize(testDataSubset, tokenToIndex, maxSequenceLength);
using (Py.GIL())
{
dynamic keras = Py.Import("keras");
dynamic np = Py.Import("numpy");
var input = new Input(shape: 1000);
var embedding = new Embedding(vocabulary.Count, 32).Apply(input);
var lstm = new LSTM(32).Apply(embedding);
var output = new Dense(1, activation: keras.activations.sigmoid).Apply(lstm);
var model = new Model(inputs: input, outputs: output);
model.Compile(optimizer: new Adam(), loss: new BinaryCrossentropy(), metrics: new[] { "accuracy" });
var trainX = trainTokenized.Item1;
var trainY = trainTokenized.Item2;
var testX = testTokenized.Item1;
var testY = testTokenized.Item2;
model.Fit(trainX, trainY, batchSize: 32, epochs: 10, validationData: (testX, testY));
Console.Write("Enter user input: ");
var userInput = Console.ReadLine();
var inputTokenized = TokenizeInput(userInput, tokenToIndex, maxSequenceLength);
var prediction = model.Predict(inputTokenized).GetData<float>()[0, 0];
Console.WriteLine($"Prediction: {(prediction > 0.5 ? "Malicious" : "Safe")} (Score: {prediction:F4})");
var testMetrics = model.Evaluate(testX, testY);
Console.WriteLine($"Test loss: {testMetrics[0]:F4}");
Console.WriteLine($"Test accuracy: {testMetrics[1]:F4}");
}
}
private static (NDarray, NDarray) Tokenize(List<dynamic> data, Dictionary<char, int> tokenToIndex, int maxSequenceLength)
{
var numExamples = data.Count;
var X = np.zeros((numExamples, maxSequenceLength));
var Y = np.zeros((numExamples, 1));
for (var i = 0; i < numExamples; i++)
{
var tokens = data[i].Token;
var label = data[i].Label;
Y[i] = label;
for (var j = 0; j < tokens.Length; j++)
{
var token = tokens[j];
var index = tokenToIndex[token];
X[i, j] = index;
}
}
return (X, Y);
}
}
}
|
|
|
|
|
We have no idea what it is fully supposed to do, or what it does that you didn't expect / doesn't do that you did. And we have no access to your data so we couldn't test it if we wanted to.
So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.
Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.
Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hello, I just started working with NAudio with the hope that it will provide the required MIDI and audio routines for a personal project I am working on. I have been programming since 1980 but basically stopped for several decades until I recently retired from Engineering. I have attempted an initial small app with NAudio in .netMAUI but it is not working. I used the following link (http://truelogic.org/wordpress/2021/01/28/using-midi-with-naudio/) to input a small console app based upon the creators description of the midi capabilities. This worked great. I then tried to make it into a MAUI app. The devices are found but it never passes into the "midiIn_MessageReceived" function??
The project can be found at https://github.com/handysharp/Maui-NAudio.
Can you think of any reason why this simple app would not be picking up the keyboard midi messages. The setup works, as it runs great with the console app.
TIA
Dave Handy
|
|
|
|
|
I think mating Naudio (".Net") and Maui (cross-platform) would be considered a kludge when "native" audio controls are available.
Dave's Tech Blog: Playing audio with .NET MAUI
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Thx Gerry, forgive my ignorance but I am new to all of this .Net, Maui, UI3, etc. I would really like to do the prog in C# with .Net MAUI because I have devoted the most learning time to them...seemed to be the best way to go at the time. What "native" audio controls do you speak of???
|
|
|
|
|
Also, kludge, great word. Just looked it up.
|
|
|
|
|
Quote: Android has MediaPlayer, iOS/Mac Catalyst has AVPlayer, and WinUI has MediaPlayerElement (only available in WinAppSDK 1.2-preview).
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
i am doing an application of online examination system and i want to design the test page that contain count down timer and when time is end expired time is showhing
thanks
|
|
|
|
|
And?
What have you tried?
Where are you stuck?
What help do you need?
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Member 15923846 wrote: online examination system
Then you will not be doing it in C#. At least not the UI part.
I suppose a true formal testing system would need to retrieve the time from a server and show that. But for a simple system you can probably find something in javascript that does that.
|
|
|
|
|
What is the difference between the following, or is there anything?
public async Task SomeFunc()
{
await Task.Run(() =>
{
var reader = com.ExecuteReader();
...
}
}
public async Task SomeFunc()
{
var reader = await com.ExecuteReaderAsync();
....
}
|
|
|
|
|