Categories
discuss

Proper Flow type for React render method?

I’m curious what the proper Flow annotation is for both render methods in React classes, and simple returns in stateless functions:

const UserProfilePage = () => {
  return <div className="container page">
    <UserProfileContainer />
  </div>
};

By setting the return type intentionally incorrect (to a number), I got this error:

  8:   return <div className="container page">
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ React element: `div`
  8:   return <div className="container page">
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ React$Element. This type is incompatible with the expected return type of
  7: const UserProfilePage = (): number => {
                                 ^^^^^^ number

So, changing the code to this seems to satisfy Flow:

const UserProfilePage = (): React$Element => {
  return <div className="container page">
    <UserProfileContainer />
  </div>
};

I’m wondering if this is correct, and if so, where is this documented?

Answer

You don’t need to annotate the render method, Flow should be able to infer the output type because it knows what JSX desugars to.

Flow has a built-in React interface, where all this stuff is defined:

declare class React$Element<Config> {
  type: ReactClass<Config>;
  props: $PropsOf<Config>;
  key: ?string;
  ref: any;
}

And then

render(): ?React$Element<any>;

So if you want to provide an explicit return type of a render method, you can use that signature. Well, maybe without a question mark if know you’re not returning null. Not sure if there’s any effect to omitting <any>.

Categories
discuss

How to replace everything but a specified string using regex

I’ve been looking through and out of stackoverflow for this, but I haven’t had any luck.

The string I want to work with is “xbananay”, where ‘x’ and ‘y’ can be any random combination of letters or numbers with any length. So my string could simply be “qrstbananag”, but it could also be “abcbanana12345” for example.

I want to use, and only use, javascript’s replace function to replace everything BUT “banana”. I already have some regex that can find banana, but the replace function, as intended, will replace what I am looking for, when I want to find everything else. Example:

var fullString = "qrstbananag"
var strippedBanana = fullString.replace(/(?:banana)/g, ''); //returns qrstg

I also have a regex expression that ALMOST gets me what I am looking for, but includes all characters in the string “banana”. Another example:

var fullString2 = "abcbanana12345"
var strippedBanana = fullString2.replace(/[^(?:banana)]/g, ''); //returns abbanana

How might I accomplish this using only the replace function? Thanks in advance.

Answer

You could use this:

var test = 'abcbananadefbananaghi';

var result = test.replace(/(banana)|[^]/g, '$1');

console.log(result);

The thing is to match banana and put it back in the result with $1. When banana doesn’t match, the next character ([^], which also matches newlines) is not captured in a capture group, and so does not get included in the $1.

Instead of [^] you can also use [Ss]: same behaviour.

About classes

In your second attempt you used

[^(?:banana)]

But be aware that the characters in a class (between [...]) are treated more literally than they would otherwise. So (?: is treated as three separate characters, and so are the characters of banana. You are in fact saying: remove any character that is not any of these: ()?:abn.

Categories
discuss

Sorting JavaPairRDD first by value and then by key

I’m trying to sort an RDD by value, and if multiple values are equal then I need to these values by key lexicographically.

code :

JavaPairRDD <String,Long> rddToSort = rddMovieReviewReducedByKey.mapToPair(new PairFunction < Tuple2 < String, MovieReview > , String, Long > () {

    @Override
    public Tuple2 < String, Long > call(Tuple2 < String, MovieReview > t) throws Exception {
        return new Tuple2 < String, Long > (t._1, t._2.count);
    }
});

What I have done so far is this, using takeOrdered and providing a CustomComperator, but since takeOrdered can’t handle a large amount of data, when running the code it keeps exiting (it eats a lot of memory that the OS can’t handle) :

List < Tuple2 < String, Long >> rddSorted = rddMovieReviewReducedByKey.mapToPair(new PairFunction < Tuple2 < String, MovieReview > , String, Long > () {

    @Override
    public Tuple2 < String, Long > call(Tuple2 < String, MovieReview > t) throws Exception {
        return new Tuple2 < String, Long > (t._1, t._2.count);
    }
}).takeOrdered(newTopMovies, MapLongValueComparator.VALUE_COMP);

Comperator:

    static class MapLongValueComparator implements Comparator < Tuple2 < String, Long >> , Serializable {
        private static final long serialVersionUID = 1L;

        private static final MapLongValueComparator VALUE_COMP = new MapLongValueComparator();

        @Override
        public int compare(Tuple2 < String, Long > o1, Tuple2 < String, Long > o2) {
            if (o1._2.compareTo(o2._2) == 0) {
                return o1._1.compareTo(o2._1);
            }
            return -o1._2.compareTo(o2._2);
        }
}

ERROR:

16/06/30 21:09:23 INFO scheduler.DAGScheduler: Job 18 failed: takeOrdered at MovieAnalyzer.java:708, took 418.149182 s

How would you sort this RDD? How would you take the TopKMovies considering value, and in case of equality keys lexicographically.

Thanks.

Answer

Solved the problem using sortByKey with a comparator & partitions, after maping the <String, Long> PairRDD to < Tuple2<String,Long> , Long> PairRDD

JavaPairRDD <Tuple2<String,Long>, Long> sortedRdd = rddMovieReviewReducedByKey.mapToPair(new PairFunction < Tuple2 < String, MovieReview > , Tuple2<String,Long>, Long > () {

    @Override
    public Tuple2 < Tuple2<String,Long>, Long > call(Tuple2 < String, MovieReview > t) throws Exception {
        return new Tuple2 < Tuple2<String,Long>, Long > (new Tuple2<String,Long>(t._1,t._2.count), t._2.count);
    }
}).sortByKey(new TupleMapLongComparator(), true, 100);


JavaPairRDD <String,Long> sortedRddToPairs = sortedRdd.mapToPair(new PairFunction<Tuple2<Tuple2<String,Long>,Long>, String, Long>() {

    @Override
    public Tuple2<String, Long> call(
            Tuple2<Tuple2<String, Long>, Long> t) throws Exception {
        return new Tuple2 < String, Long > (t._1._1, t._1._2);
    }

});

Comparator:

private class TupleMapLongComparator implements Comparator<Tuple2<String,Long>>, Serializable {
    @Override
    public int compare(Tuple2<String,Long> tuple1, Tuple2<String,Long> tuple2) {

        if (tuple1._2.compareTo(tuple2._2) == 0) {
            return tuple1._1.compareTo(tuple2._1);
        }
        return -tuple1._2.compareTo(tuple2._2);
    }
}
Categories
discuss

Mixing Java And Kotlin In Gradle Project, Kotlin Cannot Find Java Class

As the title says, I am trying to mix Java and Kotlin in a single project. There’s a good example found here. mixed-java-kotlin-hello-world. Everything is working properly besides kotlin cannot find any of my Java classes which are found in src/main/java/somepackage/SomeClass.java

What would be the cause of this?

This is the error I am getting. enter image description here

When I try to edit my build.gradle, it shows I’m not spelling kotlin correctly and giving me errors on plugin but I’m copying and pasting from kotlins website. enter image description here

My build.gradle looks like this

group 'Battle-OS'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.2-1"
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'kotlin'

repositories {
    mavenCentral()
}

dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:1.0.2-1"
testCompile  'junit:junit:4.11'
testCompile "org.jetbrains.kotlin:kotlin-test-junit:1.0.2-1"

compile 'org.slf4j:slf4j-api:1.7.18'
testCompile 'junit:junit:4.12'

    // https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'

// https://mvnrepository.com/artifact/com.google.guava/guava
compile group: 'com.google.guava', name: 'guava', version: '19.0'

// https://mvnrepository.com/artifact/io.netty/netty-all
compile group: 'io.netty', name: 'netty-all', version: '4.0.37.Final'

// https://mvnrepository.com/artifact/com.moandjiezana.toml/toml4j
compile group: 'com.moandjiezana.toml', name: 'toml4j', version: '0.6.0'

// https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib
compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: '1.0.2-1'

}

Instead of starting off trying to make this work on a larger project. I tried to make this work by creating a new gradle project. I created a test java class which contains a method to print hello world. Then I created a test kotlin class which creates a new object of the java class and calls the method from the java class to print hello world.

This solves the problem I had above, now I can call java classes from kotlin and kotlin from java but now it gives me errors upon running it.

enter image description here

Exception in thread "main" java.lang.NoClassDefFoundError:      kotlin/jvm/internal/Intrinsics
at AKotlinClassKt.main(AKotlinClass.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more

Answer

you should override sourceSets like this

sourceSets {
    main.java.srcDirs = []
    main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
    main.resources.srcDirs = ['src/main/resources']
}
Categories
discuss

Is there a way to set a breakpoint on a JS variable?

I have a variable in my javascript file that keeps getting changed and I can’t figure out why or when it is getting changed.

Is there a way to set a breakpoint or something when the variable gets changed? I’m currently using Safari on a Mac but also have Chrome installed so if there is an easier way in Chrome Developer Tools I can do that as well. Or of course if there is a separate tool that allows for this type of debugging that is awesome as well.

Is this even possible? If so how?

Thanks so much in advance.

Answer

I haven’t used Mac or Safari but it should still definitely be possible with Chrome’s debugger.

Alt-click on the page and choose “Inspect” to bring up Developer Tools. From the tabs, choose “Sources” and make sure your page is selected on the index on the left. Breakpoints and other debugging tools are available there.

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