Categories
discuss

Number with decimal input in React?

I have a number input within a React component, and it needs to accept numbers with a decimal point. Usually, entries will be in the fractions of a cent, like 0.0073, that kind of thing.

<div className="form-group">
  <label htmlFor="rate" className="col-sm-6 control-label">Rate:</label>
  <div className="col-sm-2"> 
    <input type="number"
      title="Rate"
      id="rate"
      className="form-control"
      value={this.props.rate}
      min="0.00"
      step="0.001"
      max="1.00"
      onChange={()=>{
        console.log('page rate changed');
        this.props.setrate($('#rate').val());
      }} />
  </div>
</div>

The issue is that with every keystroke, it’s resetting the rate for the app, and then putting that value into the input. So it goes like this:

  • User types 0, the value is set to 0, and 0 is displayed.
  • User types ., 0. isn’t a valid number, so the input is cleared.

Can anyone think of a workaround? I know I could just use a normal input, but type="number" leads to some nice stuff in various browsers.

Answer

I’ve tried your code and wasn’t really affected by your issue, the value is indeed empty when you type the last dot, but the input is not reset.

The thing I changed from your implementation is that I get the input value from the onChange event rather than use jQuery.

<input onChange={e => this.props.setrate(e.target.value)} />

But I doubt your issue comes from that though.

What you could do is not to call your setrate function when you detect an ending dot in your string. Your state will not be modified until the user types a valid number, so one keystroke after the 0..

<input onChange={e => {
  const str = e.target.value
  if (str.charAt(str.length - 1) === '.') { return }
  this.props.setrate(str)
}} />
Categories
discuss

How to compare two Streams in Java 8

What would be a good way to compare two Stream instances in Java 8 and find out whether they have the same elements, specifically for purposes of unit testing?

What I’ve got now is:

@Test
void testSomething() {
  Stream<Integer> expected;
  Stream<Integer> thingUnderTest;
  // (...)
  Assert.assertArrayEquals(expected.toArray(), thingUnderTest.toArray());
}

or alternatively:

Assert.assertEquals(
    expected.collect(Collectors.toList()),
    thingUnderTest.collect(Collectors.toList()));

But that means I’m constructing two collections and discarding them. It’s not a performance issue, given the size of my test streams, but I’m wondering whether there’s a canonical way to compare two streams.

Answer

static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
    Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
    while(iter1.hasNext() && iter2.hasNext())
        assertEquals(iter1.next(), iter2.next());
    assert !iter1.hasNext() && !iter2.hasNext();
}
Categories
discuss

JavaScript Regex URL extract domain only

Currently I can extract the ‘domain’ from any URL with the following regex:

/^(?:https?://)?(?:[^@n]+@)?(?:www.)?([^:/n?=]+)/im

However I’m also getting subdomain’s too which I want to avoid. For example if I have sites:

  • www.google.com
  • yahoo.com/something
  • freds.meatmarket.co.uk?someparameter
  • josh.meatmarket.co.uk/asldf/asdf

I currently get:

  • google.com
  • yahoo.com
  • freds.meatmarket.co.uk
  • josh.meatmarket.co.uk

Those last two I would like to exclude the freds and josh subdomain portion and extract only the true domain which would just be meatmarket.co.uk.

I did find another SOF that tries to solve in PHP, unfortunately I don’t know PHP. is this translatable to JS (I’m actually using Google Script FYI)?

  function topDomainFromURL($url) {
    $url_parts = parse_url($url);
    $domain_parts = explode('.', $url_parts['host']);
    if (strlen(end($domain_parts)) == 2 ) { 
      // ccTLD here, get last three parts
      $top_domain_parts = array_slice($domain_parts, -3);
    } else {
      $top_domain_parts = array_slice($domain_parts, -2);
    }
    $top_domain = implode('.', $top_domain_parts);
    return $top_domain;
  }

Answer

So, you need firstmost hostname stripped from your result, unless there only two parts already?

Just postprocess your result from first match with regexp matching that condition:

function domain_from_url(url) {
    var result
    var match
    if (match = url.match(/^(?:https?://)?(?:[^@n]+@)?(?:www.)?([^:/n?=]+)/im)) {
        result = match[1]
        if (match = result.match(/^[^.]+.(.+..+)$/)) {
            result = match[1]
        }
    }
    return result
}

console.log(domain_from_url("www.google.com"))
console.log(domain_from_url("yahoo.com/something"))
console.log(domain_from_url("freds.meatmarket.co.uk?someparameter"))
console.log(domain_from_url("josh.meatmarket.co.uk/asldf/asdf"))

// google.com
// yahoo.com
// meatmarket.co.uk
// meatmarket.co.uk
Categories
discuss

Passing superclass object as parameter to subclass constructor (java)

I’ve done a bit of searching, but I’m either not asking the right question or not remembering correctly. In any case, in Java, I am wondering if it is possible to pass the super class object in as a parameter to a subclass and what the most efficient way of making that object’s data available to the class’s super class.

Code examples:

public class superclass {
  String myparm1;
  String myParm2;
  int myParmN;

  public superclass(String p1, String p2, int pn)
  {
    this.myparm1 = p1;
    this.myparm2 = p2;
    this.myParmN = pn;
  }
  // other methods here
}

public class subclass extends superclass {
  double b1;
  double b2;

  public subclass(superclass sc, double b1, double b2) {
    // easy way to make sc data available to this class?
    // Do I create a copy or clone method, or some other way?
    // calling super(sc); wouldn't exactly work 
    this.b1 = b1;
    this.b2 = b2;
  }
}

if I had a constructor in superclass that was public superclass(superclass sc) { // assign sc properties to this properties, correct? } then I could simply use super(sc);

Answer

There’s no point to passing in a reference to the superclass of an object in the constructor. Your subclass is already an instance of the superclass.

Even though you can’t directly see the private components of the superclass, but they still exist and calls to public accessor methods will still produce normal behavior.

In answer to your second question, the most efficient way to access the data inside the parent class is with the accessor methods of that parent class. If it has get/set properties methods that populate some data structure full of properties, just call those methods from your child class and they’ll work exactly the same as they did for the parent. Now, if those internal data structures are populated by the constructor of the parent class, you’ll have to invoke that constructor with the correct methods when you create an instance of the child constructor that needs them- typically by calling the appropriate super() at the beginning of the child’s constructor.

If you’re trying to get around the restriction that you can’t see the private parts of the superclass, java intentionally doesn’t let you do that. You can get around this with reflection unless you’re stuck inside an execution environment that disallows this, but I generally wouldn’t consider this a safe or elegant approach.

From comment below, I understand what the OP is trying to do and this should work, though obviously it depends upon your ability to make changes to the super class:

public class Super
{
    public Super (Super other)
    {
        //copy stuff from other to this
    }
}

public class Child extends Super
{
    public Child (Super other)
    {
        super(other);
        //continue constructor
    }

}
Categories
discuss

Add dimen resource to layout using Android Binding Library

I’m using Android’s binding library and I’m trying to add or remove the margin on a TextView depending on the value of a boolean. If it’s true, I want the TextView to have a margin on the right and no margin on the left and if not then the opposite. All the other resources work fine but when I compile the code I get this error about the margins on the TextView: Cannot find the setter for attribute ‘android:layout_marginRight’ with parameter type float.

Can anyone spot the error?

This is my xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="comment" type="mx.com.corpogas.dataModels.FeedbackComment"/>
        <import type="android.view.View"/>
    </data>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@{comment.isMine ? @drawable/comment_background_white : @drawable/comment_background_green}"
            android:textSize="15sp"
            android:textColor="@{comment.isSent ? (comment.isMine ? @color/colorPrimaryDark : @android:color/white) : @color/unsent_text}"
            android:layout_marginRight="@{comment.isMine ? @dimen/feedback_comment_margin : @dimen/feedback_comment_no_margin}"
            android:layout_marginLeft="@{comment.isMine ? @dimen/feedback_comment_no_margin : @dimen/feedback_comment_margin}"
            android:text="@{comment.content}"/>


</layout>

And this are my margins:

<dimen name="feedback_comment_margin">16dp</dimen>
<dimen name="feedback_comment_no_margin">0dp</dimen>

When I remove the margins the program compiles and runs perfectly.

Answer

Data Binding for layout properties is not supported though you could technically add them yourself. The problem is these can be easily abused with people trying to animate them. To implement these for your application, create a binding adapter:

@BindingAdapter("android:layout_width")
public static void setLayoutWidth(View view, int width) {
  LayoutParams layoutParams = view.getLayoutParams();
  layoutParams.width = width;
  view.setLayoutParams(layoutParams);
}
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..