Why does my QIntValidator allow inputs not in my specified range? - c++

I am trying to set up a QIntValidator to validate input on a QLineEdit. This is what I did:
userInput = new QLineEdit("1");
userInput->setValidator(new QIntValidator ( 1, 20, this ) );
This appears to work: it does not allow any letters in. However, I can type in 0, which is out of range, and I can also type in numbers like 21, 39 and 80, all out of range of 1-20. Basically, I expect that the QIntValidator will only allow number inputs in the range 1-20, but, instead, I find that it allows all nonnegative number inputs less than 100 (I can also do 00000.)
Why is the QIntValidator not working as I expected it to and how do I fix it?

The 0 is accepted as QValidator::Intermediate state, because the user may intend to type e.g. 05, which would be valid. You won't be able to actually input the undesired value. After you press Return or move focus from the widget, having 0 in the input field, the value should return to the original (well, at least spinboxes behave so, not sure about QLineEdit).

Related

Is it possible to round user input to the nearest dictionary value in python?

I am writing a script that takes user input values, and it matches it to a dictionary, and returns the point grade of the value, (e.g. user input the number 340, which matches to the dictionary key 340, and returns a 100 as the grade value). But if the value is no exact match(e.g. 335), it returns an error as 335 is not an exact match to a key in the dictionary. I have all values set as an integer(except one that must be a float), but am unsure of how to iterate through each value in order to reach the nearest key value that is lower than the one the user input, OR a way to match it to the nearest lower value without having to iterate through values if that is less efficient. It is using a defined function as that is part of the requirement for the task. Small code dump for reference:
MDL_M = {
340:100,330:99,320:96,310:95,300:93,290:91,280:90,270:
140:60,130:50,120:40,110:30,100:20,90:10,80:0
}
if sex=="male" or sex=="Male":
def true_score1(yourwt):
print(MDL_M[yourwt])
true_score1(yourwt)

Make =IF Function Output Numbers For "Scoring": Google Sheets

I'm am exploring methods of giving scores to different datapoints within a dataset. These points come from a mix of numbers and text string attributes looking for certain characteristics, e.g. if Col. A contains more than X number of "|", then give it a 1. If not, it gets a 0 for that category. I also have some that give the point when the value is >X.
I have been trying to do this with =IF, for example, =IF([sheet] = [Text], "1","0").
I can get it to give me 1 or 0, but I am unable to get a point total with sum.
I have tried changing the formatting of the text to both "number", "plain text", and have left it as automatic, but I can't get it to sum. Thoughts? Is there maybe a better way to do this?
FWIW - I'm trying to score based on about 12 factors.
Best,
Alex
The issue here might be that you're having the cell evaluate to either the string "0" or the string "1" rather than the number 0 or the number 1. That would explain why you're seeing the right things but the math isn't coming out right - the cell contents look like numbers, but they're really text, which the summation would then ignore.
One option would be to drop the quotation marks and write something like this:
=IF(condition, 1, 0)
This has the condition evaluate to 1 if it's true and 0 if it's false.
Alternatively, you could write something like this:
=(condition) * 1
This will take the boolean TRUE or FALSE returned by condition and convert it to either the numeric value 1 (true) or the numeric value 0 (false).

How to validate password using express-validator npm

I am writing rest API using node , express web module. For validation I am using express-validator npm. I want to apply some validation rules on password field.
How can I achieve it using express-validator?
What validation rules I want to apply for password as:
min 8 char long.
At least one uppercase.
At least one lower case.
At least one special character.
I read in this link that there is a function available called regex() . So I tried it but not working at all.
My approach:
req.check("password", "Password should be combination of one uppercase , one lower case, one special char, one digit and min 8 , max 20 char long").regex("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/", "i");
Error
In express-js they have listed all the methods but did not find method / trick which solve my problem.
The link you're referring to is almost 3 years old. Since then, the API of validator changed.
To check against a regular expression, use .matches():
req.check("password", "...").matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/, "i");
I believe the accepted answer is outdated. RegExp and express-validator are not the best ways to validate passwords in 2017, as the obscurity of regular expressions makes the app unmaintainable and prone to bugs.
password-validator makes it easy to define password rules and maintain them. Here's a sample:
var passwordValidator = require('password-validator');
var schema = new passwordValidator();
schema
.is().min(8)
.is().max(100)
.has().uppercase()
.has().lowercase();
console.log(schema.validate(req.body.password)); // prints a boolean
PS: I'm the author of the password-validator.
Theres a new solution for this. From the documentation:
Check if a password is strong or not. Allows for custom requirements or scoring rules. If returnScore is true, then the function returns an integer score for the password rather than a boolean.
Default options:
body('password').isStrongPassword({
minLength: 8,
minLowercase: 1,
minUppercase: 1,
minNumbers: 1,
minSymbols: 1,
returnScore: false,
pointsPerUnique: 1,
pointsPerRepeat: 0.5,
pointsForContainingLower: 10,
pointsForContainingUpper: 10,
pointsForContainingNumber: 10,
pointsForContainingSymbol: 10,
})
Using the built in validators of express-validator I was able to use built in validators without a regex to check the password.
const validateStrongPassword = body("password")
.isString()
.isLength({ min: 8 })
.not()
.isLowercase()
.not()
.isUppercase()
.not()
.isNumeric()
.not()
.isAlpha();
This verifies that there is at least one non letter character, one lowercase letter, one uppercase letter, a minimum length and that there are letters in the password.
Chosen answer is incomplete as it's missing validation for special characters. Correct answer should be:
req.checkBody("password", "Password must include one lowercase character, one uppercase character, a number, and a special character.").matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/, "i");
Only real difference is that I added the (?=.*[^a-zA-Z0-9]) expression which ensures a user is using a character that's not a number or letter.
check(
"password1",
"Please enter a password at least 8 character and contain At least one uppercase.At least one lower case.At least one special character. ",
)
.isLength({ min: 8 })
.matches(
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d#$.!%*#?&]/,
)
In case you are using an array for validation and therefore the req object is not available, you can also do the following:
body('field_name').matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/, "i").withMessage('Password should be combination of one uppercase , one lower case, one special char, one digit and min 8 , max 20 char long'),
matches method work but I think it's not a stable for this use case, I think you should use the custom() method my code's :
this method work with tow parameters first is the value of your fieldset that in check method for example check('name field or password field') and the second value is an object that includes req object and you can use them and return a true or false if your returned value is true it's ok but if you return false its problem and validation is failed.
I write code in different shapes.
router.post('/adduser', [check('name').isLength({
min: 2,
max: 25
}).withMessage('min character 2 nad max character 25').custom((value, {req}) => {
return !req.body.name.match(/[^a-zA-Z]/g)
}).withMessage('please write a correct name'),
check('family').isLength({
min: 2,
max: 25
}).withMessage('min character 2 nad max character 25').custom((value, {req}) => {
return !req.body.name.match(/[^a-zA-Z]/g)
}).withMessage('please write a correct family'),
check('number').custom((value, {req}) => {
return !req.body.name.match(/[^a-zA-Z]/g)
})], (req, res, next) => {
console.log(validationResult(req).errors)
})

QDoubleValidator is not working?

I'm trying to apply validator in a line edit box in Qt 4.2 and it is not working:
QDoubleValidator *haha= new QDoubleValidator(this);
haha->setBottom(0.00);
haha->setDecimals(2);
haha->setTop(100.00);
get_line_edit()->setValidator(haha);
or
QDoubleValidator *haha= new QDoubleValidator(0.00,100.00,2,this);
Neither way, I can still enter what ever value I want.
But if I switch to QIntValidator, it works!
So I went onto Google and did a bit search, and many people used to having the same issue. Is it a bug? or there should be some other set up I should do?
Just tripped over this one. Try setting the QDoubleValidator notation to:
doubleValidator->setNotation(QDoubleValidator::StandardNotation);
The validator documentation says that it returns "Intermediate" from "validate" when the input is an arbitrary double but out of range.
You need to distinguish intermediate input and the final input the user wants to submit by use of a line edit control (e.g. by emitting the "returnPressed" signal). If the user typed "10000" that is still a valid intermediate input for a number between 0 and 100 because the user can prefix this input with "0.".
You have to set notation to your validator
QLineEdit *firstX;
QDoubleValidator* validFirstX = new QDoubleValidator(-1000, 1000, 3, ui.firstX);
validFirstX->setNotation(QDoubleValidator::StandardNotation);
then it works but not fully correct. Interesting part is that it controls the digit numbers not number itself. For example, In this example, you can enter to QLineEdit 1000 either 9999.
&& ( input.toDouble() > top() || input.toDouble() < bottom())
This example works fine in 4.8. It doesn't look like its changed since 4.2 so I suspect the problem lies in how you are creating your QLineEdit. This is the relevent code from that example.
QLineEdit* validatorLineEdit;
validatorLineEdit = new QLineEdit;
validatorLineEdit->setValidator( new QDoubleValidator(-999.0, 999.0, 2, validatorLineEdit));
How have you created your line edit?
To clarify, use QDoubleValidator::setNotation(QDoubleValidator::StandardNotation)
Example:
QDoubleValidator* doubleValidator = new QDoubleValidator(-999.0, 999.0, 2, validatorLineEdit);
doubleValidator->setNotation(QDoubleValidator::StandardNotation);
validatorLineEdit->setValidator(doubleValidator);
If you set a validator to a QLineEdit then you can use the function hasAcceptableInput() to check whether inputed value is valid or invalid. For example:
if (!ui->lineEdit_planned_count_vrt->hasAcceptableInput())
{
slot_show_notification_message("EDIT_PLAN_COUNT_VRT", notification_types::ERROR, INVALID_INPUTED_VALUE);
return;
}
bool isOk = false;
double value = ui->lineEdit_planned_count_vrt->text().toDouble(&isOk);
//do something with the value here....

Format mask for number field items: trailing and 'leading' zero

I'm having some trouble with displaying numbers in apex, but only when i fill them in through code. When numbers are fetched through an automated row fetch, they're fine!
Leading Zero
For example, i have a report where a user can click a link, which runs a javascript function. There i get detailed values for that record through an application process. The returned values are in JSON. Several fields are number fields.
My response looks as follows (fe):
{"AVAILABLE_STOCK": "15818", "WEIGHT": ".001", "VOLUME": ".00009", "BASIC_PRICE": ".06", "COST_PRICE": ".01"}
Already the numbers here 'not correct': values less than one do not have a zero before the .
I kind of hoped that the format mask on the items would catch this. If i specify FM999G990D000 for the item weight, i'd expect it to show '0.001' .
But okay, i suppose it only works that way when it comes through session state, and not when you set an item value through $("#").val() ?
Where do i go wrong? Is my only option to change my select in the app process?
Now:
SELECT '"AVAILABLE_STOCK": "' || AVAILABLE_STOCK ||'", '||
'"WEIGHT": "' || WEIGHT ||'", '||
'"VOLUME": "' || VOLUME ||'", '||
'"BASIC_PRICE": "' || BASIC_PRICE ||'", '||
Do i need to provide my numberfields a to_char with the format mask here (to_char(available_stock, 'FM999G990D000')) ?
Right now i need to put my numbers between quotes ofcourse, or i get invalid json when i parse it.
Trailing Zero
I have an application process on a page on the after header point, right after an automated row fetch. Several fields are calculated here (totals). The variables used are all specified as number(10, 2). All values are correct and rounded to 2 values after the comma. My format masks on the items are also specified as FM999G999G990D00.
However, when one of the calculated values has only one meaningfull value after the comma, the trailing zeros get dropped. Instead of '987.50', it is displayed as '987.5'.
So, i have a number variable, and assign it like this: :P12_NDB_TOTAL_INCL := v_totI;
Would i need to convert my numbers here too, with format mask?
What am i doing wrong, or what am i missing?
If you aren't doing math on it and are more concerned with formatting, I suggest treating it as a varchar/string instead of as a number wherever you can.