Categories
discuss

Multiple Statements in the Ternary Operator

What is the right syntax to have multiple statements in my ternary operator statement?

str.length() == 1 ? (str = str.replace(0, str.length(), "00")  && flag = false) : str = str.deleteCharAt(str.length() - 1);

I need to execute a couple of statements when the length of my StringBuilder str is 1

  1. Replace the str with “00”
  2. Unset flag

Any help would be greatly appreciated.

Answer

AFAIK it is not possible. In other languages you can achieve that using the coma operator, but it is not allowed in java.

That being said, doing more than one action in a ternary operation is usually a very bad practice: Yes you gonna save about 4 or 5 lines of code, but it will be way harder to read, edit, and therefore, to debug.

Categories
discuss

Call methods on React children components

I want to write a Form component that can export a method to validate its children. Unfortunately a Form does not “see” any methods on its children.

Here is how I define a potential children of Form:

var Input = React.createClass({
  validate: function() {
    ...
  },
});

And here is how I define Form class:

var Form = React.createClass({
  isValid: function() {
    var valid = true;
    this.props.children.forEach(function(component) {
      // --> This iterates over all children that I pass
      if (typeof component.validate === 'function') {
        // --> code never reaches this point
        component.validate();
        valid = valid && component.isValid();
      }
    });
    return valid;
  }
});

I noticed that I can call a method on a child component using refs, but I cannot call a method via props.children.

Is there a reason for this React behaviour?

How can I fix this?

Answer

The technical reason is that at the time you try to access the child component, they do not yet really exist (in the DOM). They have not been mounted yet. They have been passed to your<Form> component as a constructor prop or method as a react class. (hence the name class in React.createClass()).

As you point out, this can be circumvented by using refs, but I would not recommend it. In many cases, refs tend to be shortcuts for something that react wasn’t intended for, and therefore should be avoided.

It is probably by design that react makes it hard/ impossible for parents to access a child’s methods. They are not supposed to. The child’s methods should be in the child if they are private to the child: they do something inside the child that should not directly be communicated upward to the parent. If that were the case, than handling should have been done inside the parent. Because the parent has at least all info and data the child has.

Now in your case, I imagine each input (child) component to have some sort of specific validation method, that checks the input value, and based on outcome, does some error message feedback. Let’s say a red outline around incorrect fields.

In the react way, this could be achieved as follows:

  • the <Form> component has state, which includes a runValidation boolean.
  • as soon as runValidation is set to true, inside a setState( { runValidation: true }); react automatically re-renders all children.
  • if you include runValidation as a prop to all children.
  • then each child can check inside their render() function with something like if (this.props.runValidation) { this.validate() }
  • which will execute the validate() function in the child
  • the validate function can even use the child’s state (state is not changed when new props come in), and use that for the validation message (e.g. ‘please add more complicated symbols to your password`)

Now what this does not yet fix, is that you may want to do some checking at form level after all children have validated themselves: e.g. when all children are OK, submit the form.

To solve that, you could apply the refs shortcut to the final check and submit. And implement a method in your <Form> inside a componentDidUpdate() function, to check if each child is OK (e.g. has green border) AND if submit is clicked, and then submit. But as a general rule, I strongly recommend against using refs.

For final form validation, a better approach is:

  • add a non-state variable inside your <Form> which holds booleans for each child. NB, it has to be non-state, to prevent children from triggering a new render cycle.
  • pass a validateForm function as a (callback) prop to each child.
  • inside validate() in each child, call this.props.validateForm(someChildID) which updates the corresponding boolean in the variable in the Form.
  • at the end of the validateForm function in the Form, check if all booleans are true, and if so, submit the form (or change Form state or whatever).

For an even more lengthy (and way more complicated) solution to form validation in react (with flux) you could check this article.

Categories
discuss

FormData and checkboxes

Currently when creating a FormData object, a checked checkbox is added with a value of “on”, and an unchecked checkbox is not passed at all.

Do I have to hack in some hidden inputs to properly set checkboxes, or is there some customization I can do with FormData, or pre processing?

I would prefer a checked checkbox to be 1 and an unchecked to be 0. I can already do this myself (ie ugly hack), but I don’t see any native way with FormData.

Answer

Currently when creating a FormData object, a checked checkbox is added with a value of “on”, and an unchecked checkbox is not passed at all.

on is only used if the checkbox is missing a value attribute

Do I have to hack in some hidden inputs to properly set checkboxes

No. That is properly handling checkboxes. It is how they have worked in forms since the form element was added to HTML.

Test for the presence or absence of the checkbox in the code that handles it.

Categories
discuss

flink: applying multiple aggregations on a windowed stream

I have some data coming in as id, float, float, float. I want to min(), max() and sum() the fields in order and group this by the id value.

Using flatMap I have a Tuple4 with the bits but I’m not sure how to send it to the next step.

What I have:

dataStream.flatMap(new mapper()).keyBy(0)  
   .timeWindowAll(Time.of(5, TimeUnit.SECONDS)).min(1)  
   .timeWindowAll(Time.of(5, TimeUnit.SECONDS)).sum(2)
   .timeWindowAll(Time.of(5, TimeUnit.SECONDS)).sum(3)
   .map(new printstuff());

Is this the correct way to handle this? Or do I need to put each timeWindowAll in its own statement with keyBy and so forth?

Answer

Chaining of multiple aggregation functions is not supported in the DataStream API yet.

In your example, you create three distinct 5-second windows each of which applies a single aggregation. This is probably not what you want to do. I would implement a custom ReduceFunction that performs all aggregations at once in a single window. See Window Reduce in the DataStream documentation for an example.

Categories
discuss

Can I use Mockito to insert a delay and then call the real method?

OK, I have some test code where I want to insert a short delay whenever a specific method is called (to simulate a network disturbance or the like).

example code:

MyObject foobar = Mockito.spy(new MyObject(param1, param2, param3));
Mockito.doAnswer(e -> {
    Thread.sleep(2000);
    foobar.myRealMethodName();
    return null;
}).when(foobar).myRealMethodName();

Or something like that. Basically, whenever myRealMethodName() gets called, I want a 2 second delay, and then the actual method to be called.

Answer

UPDATE: My answer is quite old. There is a built-in method in Mockito now to insert the delay directly: AnswersWithDelay. See Bogdan’s response for more details.


There is already a CallsRealMethods Answer that you can extend and decorate with your delay:

public class CallsRealMethodsWithDelay extends CallsRealMethods {

    private final long delay;

    public CallsRealMethodsWithDelay(long delay) {
        this.delay = delay;
    }

    public Object answer(InvocationOnMock invocation) throws Throwable {
        Thread.sleep(delay);
        return super.answer(invocation);
    }

}

And then use it like that:

MyObject foobar = Mockito.spy(new MyObject(param1, param2, param3));
Mockito.doAnswer(new CallsRealMethodsWithDelay(2000))
           .when(foobar).myRealMethodName();

You can of course also use a static method to make everything even more beautiful:

public static Stubber doAnswerWithRealMethodAndDelay(long delay) {
    return Mockito.doAnswer(new CallsRealMethodsWithDelay(delay));
}

And use it like:

doAnswerWithRealMethodAndDelay(2000)
           .when(foobar).myRealMethodName();
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..