Generate random QString yields same result every time - c++

I'm working on a QT project where a user inputs their full name and the program generates a random 5 character password based off of the letters in their name. Unfortunate I've run into an issue where it works but every time I rerun the program it yields the same result. So it clearly isn't very random. Even after exiting QT Creator and opening it again and running the program with the same user input it yields the same results.
I also am required to generate the password without spaces.
Here is my code:
while(password.length() < 5) {
int index = qrand() % fullName.length();
QChar nextChar = fullName.at(index);
if (!nextChar.isSpace()) {
password.append(nextChar);
}
}
Any solution would be much appreciated.

You need to provide qrand with a suitable seed (usually at program startup). Try:
QTime now= QTime::currentTime() ;
qsrand( now.msec() );
You don't ask about this, but are you checking that fullName's length is not zero (as the program would attempt to divide by zero)? Or that it's not composed of blanks only (as it would loop forever)? A simple solution to both is to trim fullName and check that its length is strictly greater than zero.

Related

QProcess How to deal with too much input?

I'm using 3 command line tools via QProcesses to play music on my Linux (Mint) desktop via the Jack server. It's all working very well, but the input from one of the tools 'jack_showtime' arrives at about 12,000 lines per second.
I only need to see one line every 0.1 seconds, but the only way I've found to get a full recent line is like:
j_s->readAll(); // j_s is the jack_showtime QProcess
waitAbit(20); // a 20 mS delay
QString aShowtimeLine = j_s->readLine();
aShowtimeLine = j_s->readLine();
What would be a better way to deal with so much unwanted input? It seems that; without the readAll, a line will be much too old. Without the delay, I get a blank line and without the two readLines I get part of a line.
I'd also be interested in a Bash script that could absorb most of the input, or similar.
I suggest something like this, such that no matter how fast or how slow you get input from the child process, you always use the only most recent value, every 100mS:
// at startup or in your class constructor or wherever
connect(j_s, SIGNAL(readyRead()), this, SLOT(ReadDataFromJack()));
connect(&_myQTimer, SIGNAL(timeout()), this, SLOT(UseOneLine()));
_myQTimer.start(100);
void MyClass :: ReadDataFromJack()
{
while(j_s->canReadLine())
{
char buf[1024];
qint64 bytesRead = j_s->readLine(buf, sizeof(buf));
if ((bytes > 0)&&(CanParseText(buf))
{
this->_mostRecentResult = ParseText(buf);
}
}
}
void MyClass :: UseOneLine()
{
printf("100mS have elapsed, time to use _mostRecentResult=%i for something!\n", this->_mostRecentResult)
}
(Note that CanParseText(buf) and ParseText(buf) above are imaginary placeholders for whatever code you use to parse ASCII text coming from your child process into data to be used by your program)
Bulls eye! Thank you. You seem to know what I already had, so it was easy to add the bits I didn't have. Mainly the limited size buffer and, as I've never seen a line longer than 79 characters, I reduced it to 100. I may have been on the right track, while looking for a script solution, when I tried to use 'stdbuf', but dealing with it all in my program is much better.
Lines received are easy to parse. I only want the first number (which can be as low as zero) from something like this:
frame = 293532731 frame_time = 114978548 usecs = 2421437949 state: Rolling
I use the following, which seems reasonably minimal:
QString recentLine = QString::fromLocal8Bit(buf);
recentLine.remove(0,8);
recentLine.chop(recentLine.length() - recentLine.indexOf(" "));
int numSamples = recentLine.toInt();
I put a counter in the ReadDataFromJack() class and see between 2,000 and 3,000 visits per 100mS!
The number represents the position of the 'play head' in samples (at 48k per second) and wont exceed the integer range in Qt, but I see you use a qint64 (long long) in your example. Should I do the same for my number?
Sorry it's an answer (and a further question), but it's too long for a comment.

Weird output for RGB

I am trying to manage some LED strips with my mobile device using bluetooth + Adafruit NeoPixel. I almost had the sketch finished but I have found the numbers for RGB are not appearing as I expected and I cannot find what I am doing wrong.
Imagine that from my mobile I have sent the following RGB code "0,19,255", when I check the console I see the following result:
As you can see the first two lines are ok, but the third one we can see 2550. The 0 should no be there and I cannot figure it out the problem.
So I decided isolate the code and try to keep the minimum to identify the root cause and this is the code:
#include <SoftwareSerial.h>
#include <Adafruit_NeoPixel.h>
SoftwareSerial BT (10, 11);
#define PIN 2
#define NUMPIXELS 144
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);
int red = "";
void setup() {
Serial.begin(9600);
Serial.println("Ready");
BT.begin(38400);
pixels.begin();
pixels.show();
pixels.setBrightness(20);
}
void loop() {
while (BT.available()>0){
red = BT.parseInt();
Serial.println(red);
}
}
You describe that for the shown output you sent via mobile "0,19,255".
Yet in the shown output that obviously is only the second part of a longer sequence of numbers sent, which starts with "0,21".
Assuming that what you send is always of the format you have described, i.e. three numbers, separated by two ",", the shown output is most likely the result of you sending first "0,21,255" and then another triplet "0,19,255".
These two messages together would end up in an input buffer "0,21,2550,19,255".
Now I have to do some speculation. Most parsers, when told to look for numbers within the buffer, will look for digits followed by non-digits. They would end up yielding "0,21,2550".
Without knowing details of the parsers working it is hard to say how to fix your problem.
I would however definitly experiment with sending triplets which end in a non-digit.
For example:
"0,21,255,"
or
"0,21,255 "
or
"0,21,255;"
If none of them work you might need to explicitly expect the non-digit, i.e. between triplets of numbers read a character and either ignore it or compare it to " ,", " " or ";" for additional self-checking features.
(Writing this I rely on user zdf not intending to make an answer, because while I did spot the "2550" as "255""0", zdf spotted the only two "," inside the question body in sample input, which I missed. I will of course adapt my answer to one created by zdf, to not use their contribution without their consent.)

Change variable value of the already running program

I think it is impossible, but I should try.
I have a program, that is doing a physical simulation and recording frames to files. It is recording until the breakup value is not achieved, like:
int counter=0; //global variable
void SomeFunction()
{
...
if(counter == 400) //written exactly by this way, i.e. 400 is not a variable, just a number
PostQuitMessage(0);
else
MakeScreenshot();
counter++;
...
}
The problem is that I forgot to change if(counter == 400) to if(counter == 1000) and now program will be finished with 400 frames, although I need exactly 1000.
I can’t just recompile the program because calculations are very heavy and the program is already running for 2 days, I can’t wait.
It is very important for me, is there any way to change the if statement, or exactly the variable value during the program running?
The only hope I have, is, as far as I remember there was programs that could like change money/health/another stuff in games, and there user exactly could search a variable by value, and change it
Currently it is on about 200-300 frame, I have so little time to fix it.
You can use the Windows functions ReadProcessMemory and WriteProcessMemory.
But you need to determine the position of the value 400. Looking for the value in the running program can be done with the above functions. Depending on the size of the constant, it should be either a USHORT or an UINT.
So you can use the following steps:
Look for the value in a second instance
Isolate the surrounding OpCode sequence.
For example, a cmp xxx, 400
Look for this OpCode sequence in the running executable to find the unique location and replace the crucial value by 1000.
This can be called "hot-patch". It's how simple in-memory cheats do work and requires root privileges.
I downloaded Cheat engine and found address of the counter variable by its value. Through all addresses, the address I need was colored in green.
I changed the value stored at that address to 401, and now all is ok.

Arduino random() affecting string output

I am currently working on an arduino project using a Teensy 3.2.
The project uses some encryption code that exists in the library folder. When building the encryption code, any padding that was needed was hard-coded until the rest of the encryption worked. With the encryption working, I moved to randomize the padding process.
I am currently using the random() function from Wprogram.h.
When using manual padding, the output seems fine. However as soon as the random number generator is used, the output becomes wild and unintelligible.
When using manual padding:
//st is defined as byte[4][4]
st[0][0]=message; //character from original message, usually 'a' for testing
st[0][1]='1';
st[0][2]='2';
st[0][3]='3';
...
st[3][3]='k';
//Output
//set state: a123CDEF89fghijk //state prior to encryption
//encrypted: ⸮$2⸮⸮k6⸮tʠ&⸮⸮ //this should look funny
//decrypted to: a123CDEF89fghijk //matches plaintext
When using random padding, I've tried a few different ways:
//starting off with one random char for ease of testing
//random value seeded by randomSeed(analogRead(7));
st[0][0]=message;
st[0][1]=byte(random(33,127));//using 33 to 127 to avoid non-print chars
st[0][2]='2';
st[0][3]='3';
...
st[3][3]='k';
//-----Also Trying------
//It almost seemed like the data from the random number generator was flawed
//So I put in a scheme to ensure a hard coded character
if(random(100)%2)
st[0][1]='a';
else
st[0][1]='b';
//--------Also trying----------
//Since it seems like it is simply the existance of the random value that is
// problematic, I tried calling it without using it
int randval=random(100);
st[0][0]=message;
st[0][1]='1';
st[0][2]='2';
st[0][3]='3';
...
st[3][3]='k';
//Typical Output
//set state: a123CDEF89fghijk //state prior to encrypting(random char shows)
//encrypted: *3}3⸮⸮⸮⸮⸮⸮⸮⸮⸮N //this should look funny
//decrypted to: ⸮⸮⸮⸮⸮⸮⸮⸮k⸮-⸮⸮ //this should not look funny
From trying several different ways to create a random character and from also seeing that just the existence of the random value is causing trouble. I am suspecting that there is something buggy about how the random() function works on arduino/teensy.
Something else I noticed after setting up the random number and not using it, is that when I remove this line of code I have to recompile a couple of times before the code works correctly again. This is causing me to suspect the function even more or being buggy.
As I noted in the code samples, I am seeding the random number generator with a unused pin. Even though I would suspect it would be an issue here, I have tried a few different pins just to be safe.
So I guess my questions here might be: does anybody know what might be causing this problem or can possibly suggest and alternate way to get a random value?

keeping program running using "for" loop

I have been given a homework but don't know how to write some part of it explained as following:
..."In addition make sure your program keeps running until the user enters “quit”. To keep your program running you should use “for” statements. However, for statements doesn’t provide your program to run to infinity. Therefore, for your range value, give the maximum value that your OS can handle. For example; if you are using a 32 bit OS and interpreter, your computer should use 2^31 as the maximum value. "
What did our teacher mean do you think?(PYTHON 2.7)
You have to make mention about the language.
Java program:
do {
//Show information
//Execute preliminar code
//Here you can get the Exit command
} while (Exit command is true);
Hope this helps!
Maybe you could write a code that consistently asks the user for an input. For example:
number = int(input("Enter integer less than 5: "))
while number>5:
print("Try again")
number = int(input("enter integer number"))
if number == quit:
break
If I did this correctly, this program will continue until one of two conditions is met, 1) you enter a number less than five OR 2) you enter the word quit
As I learned later,we were supposed to use
for i in range(2**31):
#Your program codes apart from function definitions are here.
.
string=raw_input("Enter quit to exit.")
if (string == "quit"):
break