Categories
discuss

React input onChange won’t fire

I currently have this simple react app and I cannot get these onchange events to fire for the life of me.

var BlogForm = React.createClass({
getInitialState: function() {
    return {
        title: '',
        content: ''
    };
},
changeTitle: function(event) {

    var text = event.target.value;

    console.log(text);

    this.setState({
        title: event.target.value
    });
},
changeContent: function(event) {
    this.setState({
        content: event.target.value
     });
},
addBlog: function(ev) {
    console.log("hit hit");
},
render: function() {
    return (
                <form onSubmit={this.addBlog(this)}>
                    <div>
                        <label htmlFor='picure'>Picture</label>
                        <div><input type='file' id='picture' value={this.state.picture} /></div>
                    </div>
                    <div>
                        <input className="form-control" type='text' id='content' value={this.state.title} onChange={this.changeTitle} placeholder='Title' />
                    </div>
                    <div>
                        <input className="form-control" type='text' id='content' value={this.state.content} onChange={this.changeContent} placeholder='Content' />
                    </div>
                    <div>
                        <button className="btn btn-default">Add Blog</button>
                    </div>
                </form>

    );
  }
});

Funny thing is when I use onChange={this.changeTitle (this)}, the event fires but the ev variable in the changeTitle function is not the correct one.

Answer

Try:

onChange={(evt) => this.changeTitle(evt)}

or:

onChange={this.changeTitle.bind(this)}

instead of:

onChange={this.changeTitle}
Categories
discuss

Android face detection – Vision API or Camera API

I need a simple way of detecting faces in my Camera app. All I care about is a callback saying that a face was detected in certain place or with coordinates where it was detected on the preview. I’ve noticed that there seem to be several face detection APIs – in Google Play services and in both legacy and camera2 APIs. Which one should I use for the simple requirement described above?

Answer

The legacy version is older, and has much lower accuracy than the new Google Play services API.

The camera2 API depends upon face detection capabilities built into the camera hardware, so it isn’t necessarily available on all devices. I have not done an exhaustive comparison, but I think that the accuracy is also lower than that of the new Google Play services API.

See this tutorial for using the Google Play services API for tracking faces in the camera preview:

https://developers.google.com/vision/face-tracker-tutorial

The callback that you’d define would be a subclass of Tracker, similar to the GraphicFaceTracker in the tutorial.

If you don’t need to track faces or you have other code that manages the camera, you can call the face detector directly like this:

Frame frame = Frame.Builder().setBitmap(myBitmap).build();
SparseArray<Face> faces = faceDetector.detect(frame);

See for information here:

https://developers.google.com/android/reference/com/google/android/gms/vision/package-summary

Categories
discuss

JSDoc: arrow function params

I’m trying to document my code with JSDoc (EcmaScript 2015, WebStorm 12 Build 144.3357.8).

I have an arrow function which I want to document its parameters. This two examples work (I get auto-completion):

/** @param {Number} num1*/
var a = num1 => num1 * num1;
//------------------------------
/** @param {Number} num1*/
var a = num1 => {
    return num1 * num1;
};

But when I want to document an arrow function in forEach function, for example, the auto-completion isn’t working (all of the below):

/** @param {Number} num1*/
[].forEach(num1 => {
    return num1 * num1;
});
//------------------------------
/** @param {Number} num1*/
[].forEach(num1 => num1 * num1);
//------------------------------
[].forEach(/** @param {Number} num1*/num1 => num1 * num1);
//------------------------------
[].forEach(/** @param {Number} num1*/num1 => {
    return num1 * num1;
});

Has anyone managed to get this work?

Answer

Starting from the next EAP build, WebStorm will understand this:

[].forEach(/**Number*/num1 => {
    return num1 * num1;
});

Please look at WEB-19280 for details.

Categories
discuss

Passed time with nanoTime()

For a long time I measured passed time using System.currentTimeMillis() and only recently figured out that I can also use nanoTime(). However some results were not what I expected, as nanoTime measures the time from an arbitrary point in time instead of 01-01-1970 as currentTimeMillis does.

From the JavaDoc for nanoTime:

Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

For example, to measure how long some code takes to execute:

long startTime = System.nanoTime();
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

I am confused by the arbitrary part. Measuring the passed time is only accurate if the reference timestamp is the same for both calls. However in the API documentation this is not guaranteed. I think that this was the cause for my mentioned issues. The time that is used is an implementation detail and therefore I cannot rely on it.

I am wondering about, when I can make good use of nanoTime and in which cases it goes horribly wrong. The main use cases that come to mind are:

  • Comparing nanoTime timestamps from different threads
  • Comparing nanoTime timestamps from different instances of the same JVM (think, serialized timestamp from a previous application run, or passed as part of a message to a different JVM)
  • Comparing nanoTime timestamps in different JVM implementations

There are some posts here on StackOverflow that address part of the issue, but largely leave the issue of the choosing of the time open:

Especially the link in the last one makes it clear that there are limitations when nanoTime can be used, but without knowing these limitations exactly it seems inherently unsafe to use it at all as the functionality that is built upon it may fail.

Answer

The documentation should perhaps be explicit about this, but what they mean by “fixed but arbitrary” is that within the same JVM (i.e. within the same running JVM instance), the reference value is fixed.

So (1) is safe, but not beyond that.

Anything beyond that is depending on implementation quirks.

Categories
discuss

Java StringBuilder.setLength() – is time complexity O(1)?

I’m planning to perform lots of deletes of the last character in StringBuilders. The solution to use sb.setLength(sb.length() - 1); looks good to me. However, since these deletions will be in a loop, I need to know complexity of it.

The way I understand it is that this operation simply decrements some private attribute of my StringBuilder object and does not perform any copying/cloning/duplicating of the characters themselves, thus it is O(1) in time and should work fast.

Am I right?

Answer

From the documentation:

Sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. For every nonnegative index k less than newLength, the character at index k in the new character sequence is the same as the character at index k in the old sequence if k is less than the length of the old character sequence; otherwise, it is the null character ‘u0000’. In other words, if the newLength argument is less than the current length, the length is changed to the specified length.
If the newLength argument is greater than or equal to the current length, sufficient null characters (‘u0000’) are appended so that length becomes the newLength argument.

The newLength argument must be greater than or equal to 0.

I would say yes. But I wouldn’t see it from the point of view of time complexity. The reason we use StringBuilder instead of String in a loop is because Strings are immutable. Hence a new string object will always be created when we try to change it. When you change the length of a StringBuilder object, no new object is created.

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..