How to clear React-hook-form dependent field errors - react-hook-form

I want to create a form with min, max and desired fields.
The logic can be this:
Min, Desired, Max cannot be Zero or negative
Desired should be greater than or equal to Min. And less than or
equal to Max
Max should be greater than or equal to Desired/Min
I provider default value as 1 for all fields
const { register, getValues, handleSubmit, formState: { errors }} = useForm({
mode: "onChange",
defaultValues: {
min: 1,
desired: 1,
max: 1
}
});
and validated inside the field
<MyField
{...register("desired", {
validate: (value) => {
const min = getValues("min");
const max = getValues("max");
if (value < min)
return "Desired must be greater than or equal to min";
if (value > max) return "Desired must be less than max";
}
})
}
/>
When the user increase the desired number error will happen(due to max is low than desired). After user increase the max number the error still there...
CSB

You can use deps to trigger validation on others fields
https://react-hook-form.com/api/useform/register
You can user trigger from useForm as well
We recommend to use watch instead of getValues to get a field value. watch have better performances.
The working example: https://codesandbox.io/s/rhf-interactive-field-forked-yb7jo?file=/src/App.js
You might adjust some settings to match your needs.

Related

Why is this C++ min and max currency algorithm code not working? Using this code, I want to extract min and max prices from a currency trading

Take a look at this code. I want to extract the minimum and maximum ask prices and print these out as part of the statistics:
double OrderBook::getHighPrice(std::vector<OrderBookEntry>& orders)
{
// find the highest value in array of value
double max = orders[0].price;
for (OrderBookEntry& e : orders)
{
if (e.price > max)
{
max = e.price;
}
return max;
}
}
double OrderBook::getLowPrice(std::vector<OrderBookEntry>& orders)
{
// find the lowest value in array of value
double min = orders[0].price;
for (OrderBookEntry& e : orders)
{
if (e.price < min)
{
min = e.price;
}
return min;
}
}
Here is an extract of the output I am getting, max and min are the same:
Product: BTC/USDT
Asks seen: 50
Max ask: 5352
Min ask: 5352
Product: DOGE/BTC
Asks seen: 50
Max ask: 3.1e-07
Min ask: 3.1e-07
Product: DOGE/USDT
Asks seen: 50
Max ask: 0.00165524
Min ask: 0.00165524
Product: ETH/BTC
Asks seen: 50
Max ask: 0.0218909
Min ask: 0.0218909
Product: ETH/USDT
Asks seen: 50
Max ask: 117.329
Min ask: 117.329
1: Print help
2: Print exchange stats
3: Make an offer
4: Make a bid
5: Print wallet
6: Continue
==============
Current time is: 2020/03/17 17:01:24.884492
Type in 1-6
I want to make sure that max and min are different and correct. Where am I going wrong? Please help.
You're returning from inside the for loops. You need to wait until all the prices have been checked and then return after the for loops:
double OrderBook::getHighPrice(std::vector<OrderBookEntry>& orders)
{
// find the highest value in array of value
double max = orders[0].price;
for (OrderBookEntry& e : orders)
{
if (e.price > max)
{
max = e.price;
}
}
return max;
}
double OrderBook::getLowPrice(std::vector<OrderBookEntry>& orders)
{
// find the lowest value in array of value
double min = orders[0].price;
for (OrderBookEntry& e : orders)
{
if (e.price < min)
{
min = e.price;
}
}
return min;
}

In Google Sheets how can I randomize the order of a set of values?

Maybe I'm missing a keyword in my searches for a solution, but I didn't find what I'm looking for.
In Google Sheets I want to take a set of numbers and reorder it randomly. For example, start with the set [1,2,3,4] and get back [4,2,1,3].
Any ideas which function or a combination of functions may achieve this goal?
The entire process that I want to achieve is something like this:
I have a set of 4 fields. Their sum is fixed. I want to assign them randomized values.
So, I was thinking to iterate through this process:
Create a random integer between 0 and the max possible value (in the first iteration it's the fixed sum)
The new max value is the last max value minus the new random number.
Check if the new max is zero.
If not:
Return to the 1st step and repeat - This goes on until there are four values
If needed the 4th value shall be increased so the total will match the fixed sum.
Else, continue.
Randomize the order of the 4 values.
Assign the values to the 4 fields.
try:
=INDEX(SORT({{1; 2; 3; 4}, RANDARRAY(4, 1)}, 2, ),, 1)
or:
=INDEX(SORT({ROW(1:4), RANDARRAY(4, 1)}, 2, ),, 1)
Here are a couple of app script examples as well
function DiceRolls(nNumRolls) {
var anRolls = [];
nNumRolls = DefaultTo(nNumRolls, 1000)
for (var i = 1;i <= nNumRolls; i++) {
anRolls.push(parseInt((Math.random() * 6))+1);
}
return anRolls;
}
function CoinFlips(nNumFlips) {
var anFlips = [];
nNumFlips = DefaultTo(nNumFlips, 1000)
for (var i = 1;i <= nNumFlips; i++) {
anFlips.push(getRndInteger(1,2));
}
return anFlips;
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}

Convert a number to Human readable format (e.g. 1.5k, 5m, 1b) in Dart?

i'm developing an app related to social messanging and i want to convert big numbers to Human readable format (e.g. 1500 to 1.5k) and also i'm new to Dart.
Your help will be appreciated.
You can use the NumberFormat class of flutter which has some in built functions for results you want..
Check out this link for NumberFormat class of flutter
Example:
This is one way if you want to use currency..
var _formattedNumber = NumberFormat.compactCurrency(
decimalDigits: 2,
symbol: '', // if you want to add currency symbol then pass that in this else leave it empty.
).format(numberToFormat);
print('Formatted Number is: $_formattedNumber');
Example:
This example is with locale.
var _formattedNumber = NumberFormat.compactCurrency(
decimalDigits: 2,
locale: 'en_IN'
symbol: '',
).format(numberToFormat);
print('Formatted Number is: $_formattedNumber');
The output of this is code would be:
If 1000 is entered then 1K is the output
Another way is by just using NumberFormat.compact() which gives the desired output...
// In this you won't have to worry about the symbol of the currency.
var _formattedNumber = NumberFormat.compact().format(numberToFormat);
print('Formatted Number is: $_formattedNumber');
The output of above example will also be:
If 1000 is entered then 1K is the output
I tried this and is working...
Make a class and used its static method every where.
class NumberFormatter{
static String formatter(String currentBalance) {
try{
// suffix = {' ', 'k', 'M', 'B', 'T', 'P', 'E'};
double value = double.parse(currentBalance);
if(value < 1000000){ // less than a million
return value.toStringAsFixed(2);
}else if(value >= 1000000 && value < (1000000*10*100)){ // less than 100 million
double result = value/1000000;
return result.toStringAsFixed(2)+"M";
}else if(value >= (1000000*10*100) && value < (1000000*10*100*100)){ // less than 100 billion
double result = value/(1000000*10*100);
return result.toStringAsFixed(2)+"B";
}else if(value >= (1000000*10*100*100) && value < (1000000*10*100*100*100)){ // less than 100 trillion
double result = value/(1000000*10*100*100);
return result.toStringAsFixed(2)+"T";
}
}catch(e){
print(e);
}
}
}

Finding Max/Min values in a linked list

When the while loop iterates, it skips both "if" loops and when the "q=q->next" statement runs, both the max and min values are changed as well. Am I not initializing the max/min integers correctly?
void FindMaxMin(int& max, int& min)
{
NODE* q;
q=List; //to start over
while(q != NULL)
{
max=min=q->info; //Sets max and min to first value
if(q->info>max)
max=q->info;
if(q->info<min)
min=q->info;
q=q->next;
}
}
Max/min are initialized every loop cycle to the current element value. That's why ifs are skipped (since the data is neither more nor less than the actual value - it's the same).
You should write something like this to correctly initialize max/min data:
void FindMaxMin(int& max, int& min)
{
NODE* q;
q=List; //to start over
max=min=q->info; //Sets max and min to first value
while(q != NULL)
{
if(q->info>max)
max=q->info;
if(q->info<min)
min=q->info;
q=q->next;
}
}
You reset max and min to the info value of the current node for each node iteration.
Take that initialization outside of the while loop.

Set min/max for each range handle in jQuery UI slider?

I'm using a jQuery slider where users can select a time range between 00:00 and 1d+12:00. 36 hours all together.
Anyway.
I would like to apply min and max values to my handles based on what they're set to. These are my requirements:
left handle can never go over midnight on the next day (max is 24 hours)
left handle can never go more left than -24 hours from right handle (min is right handle value minus 24 hours)
right handle can never go more than +24 hours from the left handle (max is left handle value plus 24 hours)
As I understand, minimum and maximum values can only be applied to single handle slider control and not to range slider?
Is it possible to set minimums and maximums individually to both handles?
I've tried initializing it this way but no luck:
$(".timing-slider", timing).slider({
range: true,
min: [0, 0],
max: [24, 36],
}
This jQuery UI slider extension satisfies all upper requirements
I've managed to change default jQuery UI slider to include a few more configuration properties:
minRangeSize - sets minimum range size so ranges can't be narrower than this setting
maxRangeSize - sets maximum range size so ranges can't be wider than this setting
autoShift - when set to true it automatically drags the other handle along when range width reaches maximum; when set to false handle just can't be moved beyond maximum range width
lowMax - sets the lower handle upper boundary so it's impossible to set lower handle beyond this value
topMin - sets the upper handle lower boundary so it's impossible to set upper handle below this value
This is a working example of such range slider.
This is the extra code that has to be run after jQuery slider. It actually rewrites one of its internal functions to also check the new settings. This code will only change slider code when slider script has been loaded (hence the first if statement that checks whether slider widget has been loaded):
(function ($) {
if ($.ui.slider)
{
// add minimum range length option
$.extend($.ui.slider.prototype.options, {
minRangeSize: 0,
maxRangeSize: 100,
autoShift: false,
lowMax: 100,
topMin: 0
});
$.extend($.ui.slider.prototype, {
_slide: function (event, index, newVal) {
var otherVal,
newValues,
allowed,
factor;
if (this.options.values && this.options.values.length)
{
otherVal = this.values(index ? 0 : 1);
factor = index === 0 ? 1 : -1;
if (this.options.values.length === 2 && this.options.range === true)
{
// lower bound max
if (index === 0 && newVal > this.options.lowMax)
{
newVal = this.options.lowMax;
}
// upper bound min
if (index === 1 && newVal < this.options.topMin)
{
newVal = this.options.topMin;
}
// minimum range requirements
if ((otherVal - newVal) * factor < this.options.minRangeSize)
{
newVal = otherVal - this.options.minRangeSize * factor;
}
// maximum range requirements
if ((otherVal - newVal) * factor > this.options.maxRangeSize)
{
if (this.options.autoShift === true)
{
otherVal = newVal + this.options.maxRangeSize * factor;
}
else
{
newVal = otherVal - this.options.maxRangeSize * factor;
}
}
}
if (newVal !== this.values(index))
{
newValues = this.values();
newValues[index] = newVal;
newValues[index ? 0 : 1] = otherVal;
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger("slide", event, {
handle: this.handles[index],
value: newVal,
values: newValues
});
if (allowed !== false)
{
this.values(index, newVal, true);
this.values((index + 1) % 2, otherVal, true);
}
}
} else
{
if (newVal !== this.value())
{
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger("slide", event, {
handle: this.handles[index],
value: newVal
});
if (allowed !== false)
{
this.value(newVal);
}
}
}
}
});
}
})(jQuery);

Resources