Categories
discuss

Empty diamond shape with numbers

So I have been asked this question and I could only solve the top part of the code, I am stuck on the bottom part.

Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:

  1
 2 2
3   3
 2 2
  1

Here’s my code so far:

public static void shape(int n) {
    //TOP PART
    for (int i = 1; i <= (n - 1); i++) {
        System.out.print(" ");
    }
    System.out.println(1);
    for (int i = 2; i <= n; i++) {
        for (int j = 1; j <= (n - i); j++) {
            System.out.print(" ");
        }
        System.out.print(i);
        for (int j = 1; j <= 2 * i - n + 1; j++) {
            System.out.print(" ");
        }
        System.out.println(i);
    }

    //BOTTOM PART (The messed up part)
    for (int i = n + 1; i <= 2 * n - 2; i++) {
        for (int j = 1; j <= n - i; j++) {
            System.out.print(" ");
        }
        System.out.print(i);
        for (int j = 1; j <= n; j++) {
            System.out.print(" ");
        }
        System.out.print(i);
    }
    for (int i = 1; i <= (n - 1); i++) {
        System.out.print(" ");
    }
    System.out.println(1);
}
public static void main(String[] args) {
    shape(4);
}

Answer

Maybe a little bit late, but because the bottom part of your message is just the first part mirrored you can use a Stack to print the message in reverse order:

public static void main(String[] args) {
    int maxNumber = 3;
    Stack<String> message = new Stack<>();
    // upper part
    for (int row = 0; row < maxNumber; row++) {
        int prefix = maxNumber - (row + 1);
        int spaces = row >= 2 ? row * 2 - 1 : row;

        String line = getLine(row, prefix, spaces);
        System.out.println(line);
        if (row != maxNumber - 1)
            message.add(line);
    }
    // bottom part
    while (!message.isEmpty())
        System.out.println(message.pop());
}

public static String getLine(int row, int prefix, int spaces) {
    StringBuilder line = new StringBuilder("_".repeat(prefix));
    line.append(row + 1);
    if (row != 0) {
        line.append("_".repeat(spaces));
        line.append(row + 1);
    }
    return line.toString();
}

Output:

__1
_2_2
3___3
_2_2
__1

You can of course use any method you want to fill the stack (i.e. to generate the upper part of your message) like with the method this question suggessted. This upper part I describe contains the first line (inclusive) up to the middle line (exclusive).

Categories
discuss

React contenteditable in stateless component

I am trying to implement a contenteditable div inside a stateless react component.

I keep getting the below warning:

warning.js:36 Warning: A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.

How do I fix this?

Also how do I read contents of div on change?

Answer

As with any React application, browser plugins and extensions that modify the DOM can cause Draft editors to break.

Grammar checkers, for instance, may modify the DOM within contentEditable elements, adding styles like underlines and backgrounds. Since React cannot reconcile the DOM if the browser does not match its expectations, the editor state may fail to remain in sync with the DOM.

https://github.com/facebook/draft-js/issues/53

A known error. As for reading whats in a div, assign the element an id and..

oDoc = document.getElementById("divelement");
sDefTxt = oDoc.innerHTML;
Categories
discuss

Overriding @Value in Integration Test

For one of my Spring beans(say Application class), I’m fetching the value of a property(my.property.flag=true/false) from a properties file(prop.properties) using @Value annotation. That works perfectly fine.

I need to write an integration test(say ApplicationIt class) where I need to test with both the values of the property i.e. for both true and false.

In my properties file, the value of the property is set to true. Is it possible to set the value dynamically to false from my Integration test?

For Example,

prop.properties:

    my.property.flag=true

Application class file:

    @Component
    class Application {
        //This value is fetched from properties file
        //the value is set to true.
        @Value(${my.property.flag})
        private String isTrue;
        ......
        ..........
    }

Integration Test:

    class ApplicationIT {
        //how can I set the value of isTrue here to false?
    }

Answer

You can specify test properties on the test class as follows:

@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"spring.main.banner-mode=off", "my.property.flag=false"})
public class MyTest {

Since Spring has a whole hierarchy of property overrides, this works pretty well, the downside being you need separate test classes for different values. If you’re using Spring Boot, there’s another annotation that provides the same functionality but also has more options for configuring your test environment. Example:

@SpringBootTest(properties = {"spring.main.banner-mode=off", "my.property.flag=false"})

Again, you will need separate test classes to handle hard-coded test properties.

Categories
discuss

Get index of item in Javascript Set

I’m having a hard time finding a dupe of this question, but I assume it’s been asked before….

If I add three items to a Set:

var s = new Set();
undefined
s.add(1); s.add(2); s.add(3);
Set(3) {1, 2, 3}

… How can I find out the index of an item?

There is no indexOf method for Set and I’m not sure if iterating over the Set is the best way. I’ve tried using the forEach API but can neither break nor return from this function:

  if (s.size < cells.length) {
    var count = 0;
    s.forEach(function (value) {
      if (cell.id.slice(0, -5) == value) {
        break;  //return fails here too...
      }
      count ++;
    });
    return count;
  }

Answer

The purpose of Sets is not so much to give an order number, but if you need one, the pragmatic solution is to temporarily turn it into an array with the spread syntax:

count = [...s].indexOf(cell.id.slice(0, -5));

If for some reason you prefer looping, then use some instead of forEach:

[...s].some(function (value) {
  if (cell.id.slice(0, -5) == value) {
    return true; // this will stop the iteration
  }
  count ++;
});

Or why not use the ES6 for of loop:

for (const value of s) {
  if (cell.id.slice(0, -5) == value) {
    break; // this will stop the iteration
  }
  count ++;
}

NB: Although the use of the old-style for ... in loop is discouraged for use with arrays, this does not hold for the for ... of loop.

Categories
discuss

Building C++ and Java code using CMake and Maven and bundle in a jar

I have legacy C++ code that is built using CMake. It generates a .so file. I need to wrap this code in Java and build a jar that includes Java code as well as C++ for deployment.

Steps for building C++ code with CMake is simple:

cd /to/pkg/dir
cmake .
make

The .so file is generated under a build/ directory. If I convert the whole project into maven, I will have to modify the directory structure (here is a blog post that explains how that could work: http://blog.bigpixel.ro/2012/07/building-cc-applications-with-maven/). However, I don’t want to do that. Could there be an option to call the first two lines shown above from maven to build the .so file and then include it with the final jar?

Answer

In Apache Hadoop, the build does something similar to what you described. We use the Apache Maven AntRun Plugin during the compile phase to make an external call to cmake and then call make on the build output generated by CMake to compile and link the C portion of our codebase. This output then feeds into our final build artifacts. In our case, those build artifacts are tarballs rather than bundled straight into a jar file, but you could accomplish it by controlling configuration of the Apache Maven JAR Plugin. Specifically, you may need to override content include/exclude settings.

If you’d like to use it as a starting point, the relevant part of the Hadoop build is visible here:

https://github.com/apache/hadoop/blob/release-2.7.3-RC2/hadoop-common-project/hadoop-common/pom.xml#L598-L615

<execution>
  <id>make</id>
  <phase>compile</phase>
  <goals><goal>run</goal></goals>
  <configuration>
    <target>
      <exec executable="cmake" dir="${project.build.directory}/native" failonerror="true">
        <arg line="${basedir}/src/ -DGENERATED_JAVAH=${project.build.directory}/native/javah -DJVM_ARCH_DATA_MODEL=${sun.arch.data.model} -DREQUIRE_BZIP2=${require.bzip2} -DREQUIRE_SNAPPY=${require.snappy} -DCUSTOM_SNAPPY_PREFIX=${snappy.prefix} -DCUSTOM_SNAPPY_LIB=${snappy.lib} -DCUSTOM_SNAPPY_INCLUDE=${snappy.include} -DREQUIRE_OPENSSL=${require.openssl} -DCUSTOM_OPENSSL_PREFIX=${openssl.prefix} -DCUSTOM_OPENSSL_LIB=${openssl.lib} -DCUSTOM_OPENSSL_INCLUDE=${openssl.include} -DEXTRA_LIBHADOOP_RPATH=${extra.libhadoop.rpath}"/>
      </exec>
      <exec executable="make" dir="${project.build.directory}/native" failonerror="true">
        <arg line="VERBOSE=1"/>
      </exec>
      <!-- The second make is a workaround for HADOOP-9215.  It can
           be removed when version 2.6 of cmake is no longer supported . -->
      <exec executable="make" dir="${project.build.directory}/native" failonerror="true"></exec>
    </target>
  </configuration>
</execution>
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..