问:
How refactor two methods which are very similar
I have following classes:

```<code>public interface IBaseInterface {
    String baseMethod();
}

public class BaseClass implements IBaseInterface{

    @Override
    public String baseMethod() {
        return "baseInterface";
    }

    public String otherBaseMethod(){
        return "otherBaseMethod";
    }

}

public class ClassA implements IBaseInterface{

    @Override
    public String baseMethod() {
        return "ClassA";
    }

    public String getAttribiuteA(){
        return "A";
    }

}

public class ClassB implements IBaseInterface {

    @Override
    public String baseMethod() {
        return "ClassB";
    }

    public String getAttribiuteB(){
        return "B";
    }

}
</code>```

And now I have two very similar methods:

```<code>private String getBaseMethod(){

    /** Do something */

    if(/**    */){
        BaseClass base = new BaseClass();
        return base.baseMethod();
    }else if (/**    */){
        ClassA a = new ClassA();
        return a.baseMethod();
    } else {
        ClassB b = new ClassB();
        return b.baseMethod();
    }
}

private String getOtherMethod(){

    /** Do something */

    if(/**    */){
        BaseClass base = new BaseClass();
        if(/**    */){
            return base.baseMethod();
        } else{
            return base.otherBaseMethod()
        }
    } else if(/**    */){
        ClassA a = new ClassA();
        return a.getAttribiuteA()
    } else{
        ClassB b = new ClassB();
        return b.getAttribiuteB();
    }
}
</code>```

These two methods are very similar. In if-Clause are the same conditions. Can we make these two methods better? More "abstractly" ?

I can not make any changes in my classes, only in methods.

答:
I assume what is being asked here is to use 'Polymorphism'

Because all three classes, BaseClass, ClassA, and ClassB, all implement interfcae IBaseInterface, so you can do such thing like following example:

```<code> IBaseInterface i1 = new BaseClass();
 IBaseInterface i2 = new ClassA();
 IbaseInterface i3 = new ClassB();
</code>```

And as you already noticed at this point, you may use List to save your classes too.

```<code> List<IBaseInterface> interfaces = new ArrayList<>();
 interfaces.add(i1);
 ....
</code>```

and so on

Because IBaseInterface has method baseMethod(), now you can simply iterate through the list and invoke baseMethod() method for each IBaseInterface objects.

take a look for 'Polymorphic Behavior'

Body:
I have following classes:

public interface IBaseInterface {
    String baseMethod();
}

public class BaseClass implements IBaseInterface{

    @Override
    public String baseMethod() {
        return "baseInterface";
    }

    public String otherBaseMethod(){
        return "otherBaseMethod";
    }

}

public class ClassA implements IBaseInterface{

    @Override
    public String baseMethod() {
        return "ClassA";
    }

    public String getAttribiuteA(){
        return "A";
    }

}

public class ClassB implements IBaseInterface {

    @Override
    public String baseMethod() {
        return "ClassB";
    }

    public String getAttribiuteB(){
        return "B";
    }

}

And now I have two very similar methods:

private String getBaseMethod(){

    /** Do something */

    if(/**    */){
        BaseClass base = new BaseClass();
        return base.baseMethod();
    }else if (/**    */){
        ClassA a = new ClassA();
        return a.baseMethod();
    } else {
        ClassB b = new ClassB();
        return b.baseMethod();
    }
}

private String getOtherMethod(){

    /** Do something */

    if(/**    */){
        BaseClass base = new BaseClass();
        if(/**    */){
            return base.baseMethod();
        } else{
            return base.otherBaseMethod()
        }
    } else if(/**    */){
        ClassA a = new ClassA();
        return a.getAttribiuteA()
    } else{
        ClassB b = new ClassB();
        return b.getAttribiuteB();
    }
}

These two methods are very similar. In if-Clause are the same conditions. Can we make these two methods better? More "abstractly" ?

I can not make any changes in my classes, only in methods.

Body:
I assume what is being asked here is to use 'Polymorphism'

Because all three classes, BaseClass, ClassA, and ClassB, all implement interfcae IBaseInterface, so you can do such thing like following example:

 IBaseInterface i1 = new BaseClass();
 IBaseInterface i2 = new ClassA();
 IbaseInterface i3 = new ClassB();

And as you already noticed at this point, you may use List to save your classes too.

 List<IBaseInterface> interfaces = new ArrayList<>();
 interfaces.add(i1);
 ....

and so on

Because IBaseInterface has method baseMethod(), now you can simply iterate through the list and invoke baseMethod() method for each IBaseInterface objects.

take a look for 'Polymorphic Behavior'


来源: stackexchange

问:
Query to get name from a table with 2 ID columns
I have 2 tables. The first has a structure like

```<code>id (int)
parent_id (int)
category_name (varchar)
</code>```

The second has a structure like:

```<code>id (int)
old_category (int)
new_category (int)
</code>```

I want to make a query to pull the old category and new category names all in one query for the parents. That is, I want to get the name of the old parent, then get the name of the new parent. The second table contains a historical list of all the parent ID changes made in the first table. How can I do this? Thanks!

答:
```<code>   SELECT old_cat.category_name, new_cat.category_name
     FROM join_table
LEFT JOIN category_table as old_cat
       ON old_cat.id = join_table.old_category
LEFT JOIN category_table as new_cat
       ON new_cat.id = join_table.new_category;
</code>```

If you've managed to get this far, it's time to stop coding and start learning MySQL JOIN Syntax.

ContentLicense: CC BY-SA 2.5

Body:
I have 2 tables. The first has a structure like

id (int)
parent_id (int)
category_name (varchar)

The second has a structure like:

id (int)
old_category (int)
new_category (int)

I want to make a query to pull the old category and new category names all in one query for the parents. That is, I want to get the name of the old parent, then get the name of the new parent. The second table contains a historical list of all the parent ID changes made in the first table. How can I do this? Thanks!

Body:
   SELECT old_cat.category_name, new_cat.category_name
     FROM join_table
LEFT JOIN category_table as old_cat
       ON old_cat.id = join_table.old_category
LEFT JOIN category_table as new_cat
       ON new_cat.id = join_table.new_category;

If you've managed to get this far, it's time to stop coding and start learning MySQL JOIN Syntax.


问:
What's wrong with the for() loop in my case?
I'm a beginner in Java and HBase, I want to shorten my code so I use a for-loop in my code. If the input String stumber is "AAAA0000?0", the results should be "AAAA000000","AAAA000010","AAAA000020","AAAA000030" …… "AAAA000090"

This origin code works well:

```<code>    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
        get = new Get((stumber.replace(stumber.charAt(8), '0')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '1')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '2')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '3')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '4')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '5')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '6')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '7')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '8')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '9')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);
</code>```

But after I modify with for-loop, the code failed to give out the results. Why?

```<code>    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
            for (int i =0; i<10; i++){
                get = new Get((stumber.replace(stumber.charAt(8), 'i')).getBytes());
                get.setMaxVersions(versions);
                gets.add(get);
            }
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);
</code>```

答:
You can use Character.forDigit() to convert int i to char like :</p>

```<code>get = new Get((stumber.replace(stumber.charAt(8), Character.forDigit(i, 10))).getBytes());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm a beginner in Java and HBase, I want to shorten my code so I use a for-loop in my code. If the input String stumber is "AAAA0000?0", the results should be "AAAA000000","AAAA000010","AAAA000020","AAAA000030" …… "AAAA000090"

This origin code works well:

    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
        get = new Get((stumber.replace(stumber.charAt(8), '0')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '1')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '2')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '3')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '4')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '5')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '6')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '7')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '8')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '9')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);

But after I modify with for-loop, the code failed to give out the results. Why?

    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
            for (int i =0; i<10; i++){
                get = new Get((stumber.replace(stumber.charAt(8), 'i')).getBytes());
                get.setMaxVersions(versions);
                gets.add(get);
            }
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);

Body:
You can use Character.forDigit() to convert int i to char like :

get = new Get((stumber.replace(stumber.charAt(8), Character.forDigit(i, 10))).getBytes());


问:
Cannot center div above another Bootstrap
I am trying to center:

```<code><div style="text-align:center; margin-top:16px;" class="hidden-xs">
  <div>Free Estimates</div>
  <div>Licensed & Insured #C98354</div>
</div>
</code>```

I want it to be centered above the div below it at all times.

```<code>        <div class="collapse navbar-collapse" id="navbar-collapse-02">
          <ul class="nav navbar-nav navbar-right">
            <li>
              <a href="#slider-wrapper">Home</a>
            </li>
            <li>
              <a href="#services">Services</a>
            </li>
            <li>
              <a href="#about">About Us</a>
            </li>
            <li>
              <a href="#portfolio">Ideas</a>
            </li>
            <li>
              <a href="#contact">Contact</a>
            </li>
          </ul>
        </div>
</code>```

Unfortunately I can't quite figure out how to make it center above the div properly.

Desired output would kinda look like:

Full Header Code for Ref:

```<code><header class="item header margin-top-0 padding-bottom-70" id="header1">
  <div class="wrapper">
    <div class="container">
      <nav class="navbar navbar-default navbar-lg navbar-fixed-top" role="navigation">
        <div class="container">
          <div class="col-lg-1">
            <div class="navbar-header">
              <button class="navbar-toggle" data-target="#navbar-collapse-02" data-toggle="collapse" type="button">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand brand" href="#">
                <img src="images/new-logo-small.png">
              </a>
              <div class="hidden-xs">     A+ Rating BBB</div>
            </div>
          </div>
          <div class="col-lg-6">
            <div style="padding-top:67px; padding-left:125px; text-align:center; font-size:16px" class="hidden-md hidden-sm hidden-xs">
              <div>
                <div>Some Address</div>
                <span class="fa fa-envelope"></span><span> <a  style="text-decoration:none; color:#333">email@email.com</a> | </span>
                <span class="fa fa-phone"></span><span> (727) 876-5309</span>
              </div>
            </div>
          </div>
          <div class="col-lg-5">
            <!-- I want this to stay centered above the div below it -->
            <div style="text-align:center; margin-top:16px;" class="hidden-xs">
              <div>Free Estimates</div>
              <div>Licensed & Insured #C98354</div>
            </div>
            <div class="collapse navbar-collapse" id="navbar-collapse-02">
              <ul class="nav navbar-nav navbar-right">
                <li>
                  <a href="#slider-wrapper">Home</a>
                </li>
                <li>
                  <a href="#services">Services</a>
                </li>
                <li>
                  <a href="#about">About Us</a>
                </li>
                <li>
                  <a href="#portfolio">Ideas</a>
                </li>
                <li>
                  <a href="#contact">Contact</a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </nav>
    </div>
  </div>
</header>
</code>```

答:
I use percentage in a margin to center navbar and navbarnav. I hope that this help you.</p>

```<code>    <div class="makenavbarcenter">
    <div class="hidden-xs headertitle">
        <div>Free Estimates</div>
        <div>Licensed & Insured #C98354</div>
    </div>

    <nav class="navbar navbar-default navbarmain">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

              <ul class="nav navbar-nav makenavbarnavcenter">
                    <li class="headerlinks"><a href="#">Home</a>
                    </li>
                    <li class="headerlinks"><a href="#">Services</a>
                    </li>
                    <li class="headerlinks"><a href="#">About Us</a>
                    </li>
                    <li class="headerlinks"><a href="#">Ideas</a>
                    </li>
                    <li class="headerlinks"><a href="#">Contact</a>
                    </li>
                </ul>

            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->
    </nav>
</div>
<style type="text/css">
    .makenavbarcenter {
        margin-left: 20%;
        margin-right: 20%;
    }
    .navbarmain {
        background-color: transparent;
        border-color: transparent;
    }
    .makenavbarnavcenter {
        margin-right: 20%;
        margin-left: 20%
    }
    .headertitle {
        text-align: center;
        margin-top: 16px;
    }
    .headerlinks {
        padding: 0px;
        margin: 0px;
    }
</style>
</code>```

Body:
I am trying to center:

Free Estimates

Licensed & Insured #C98354

I want it to be centered above the div below it at all times.

              Home

              Services

              About Us

              Ideas

              Contact

Unfortunately I can't quite figure out how to make it center above the div properly.

Desired output would kinda look like:

Full Header Code for Ref:

              <button class="navbar-toggle" data-target="#navbar-collapse-02" data-toggle="collapse" type="button">
                Toggle navigation

              </button>

     A+ Rating BBB

Some Address

                 email@email.com |
                 (727) 876-5309

Free Estimates

Licensed & Insured #C98354

                  Home

                  Services

                  About Us

                  Ideas

                  Contact

Body:
I use percentage in a margin to center navbar and navbarnav. I hope that this help you.

    <div class="makenavbarcenter">
    <div class="hidden-xs headertitle">
        <div>Free Estimates</div>
        <div>Licensed &amp; Insured #C98354</div>
    </div>

    <nav class="navbar navbar-default navbarmain">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

              <ul class="nav navbar-nav makenavbarnavcenter">
                    <li class="headerlinks"><a href="#">Home</a>
                    </li>
                    <li class="headerlinks"><a href="#">Services</a>
                    </li>
                    <li class="headerlinks"><a href="#">About Us</a>
                    </li>
                    <li class="headerlinks"><a href="#">Ideas</a>
                    </li>
                    <li class="headerlinks"><a href="#">Contact</a>
                    </li>
                </ul>

            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->
    </nav>
</div>
<style type="text/css">
    .makenavbarcenter {
        margin-left: 20%;
        margin-right: 20%;
    }
    .navbarmain {
        background-color: transparent;
        border-color: transparent;
    }
    .makenavbarnavcenter {
        margin-right: 20%;
        margin-left: 20%
    }
    .headertitle {
        text-align: center;
        margin-top: 16px;
    }
    .headerlinks {
        padding: 0px;
        margin: 0px;
    }
</style>


问:
Java sorting parallel arrays, help needed (NullPointerException Error)
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

```<code>    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }
</code>```

It has to be done in java. I am getting an error in the 15th line consisting of

```<code>if(a.compareTo(b) != 0)
</code>```

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.

答:
Assuming you need to stay at array level (and not create higher level data structures, which in the real world you should) and use a bubble sort (which you seem to be basically using, but in the real world you often shouldn't, too slow)...

You're getting yourself tied up with too many temp positions/variables.  All you really need to do loop outer for a max of the whole length, and inner for each non-examined index (see bubble sort), then compare "i" to "i+1" based on your criteria (which consider two values at most in this case) and "swap" them if they're backwards.

Body:
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }

It has to be done in java. I am getting an error in the 15th line consisting of

if(a.compareTo(b) != 0)

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.


问:
Pyspark JDBC connection to PostgreSQL fails due to missing connectivity between driver and database
We are using Pyspark on an EMR cluster in order to access and analyse data from a PostgreSQL database (accessible via the JDBC connector at jdbc:postgresql://psqlhost:5432/psqldatabase). Network is open between the EMR cluster and the PostgreSQL instance so that, when we access the EMR master via SSH, we can launch the following job successfully (both in client and in cluster deploy mode):

```<code>url = 'jdbc:postgresql://psqlhost:5432/psqldatabase'
table = 'mytable'

properties = {
    'user': 'user',
    'password': 'password',
    'driver': 'org.postgresql.Driver'
}

products_df = spark.read.jdbc(url=url, table=table, properties=properties)
</code>```

We would like now to change setup and execute Pyspark commands on the EMR cluster from a separate client instance with full connectivity to the EMR cluster. This has been successfully set up by copying the necessary yarn configuration files to the client machine and executing Pyspark with --master yarn.

We are however still experiencing issues in accessing the PostgreSQL database from the client instance. For security reasons, the client machine cannot access the PostgreSQL instance, which however remains accessible to the EMR cluster. the above code snippet works without problem with --deploy-mode cluster. However, when working in --deploy-mode client, the last line produces the following error:

```<code>17/03/27 11:39:21 ERROR Driver: Connection error:
org.postgresql.util.PSQLException: The connection attempt failed.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:275)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
    at org.postgresql.Driver.makeConnection(Driver.java:431)
    at org.postgresql.Driver.connect(Driver.java:247)
    at org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.connect(DriverWrapper.scala:45)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:65)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:56)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:123)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:117)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:237)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:159)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:211)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:62)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 22 more
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-2-f5f370f4d567> in <module>()
----> 1 products_df = spark.read.jdbc(url=url, table=table, properties=properties)

/opt/spark-2.0.0/python/pyspark/sql/readwriter.pyc in jdbc(self, url, table, column, lowerBound, upperBound, numPartitions, predicates, properties)
    420             jpredicates = utils.toJArray(gateway, gateway.jvm.java.lang.String, predicates)
    421             return self._df(self._jreader.jdbc(url, table, jpredicates, jprop))
--> 422         return self._df(self._jreader.jdbc(url, table, jprop))
    423
    424

/opt/spark-2.0.0/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py in __call__(self, *args)
    931         answer = self.gateway_client.send_command(command)
    932         return_value = get_return_value(
--> 933             answer, self.gateway_client, self.target_id, self.name)
    934
    935         for temp_arg in temp_args:

/opt/spark-2.0.0/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/opt/spark-2.0.0/python/lib/py4j-0.10.1-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    310                 raise Py4JJavaError(
    311                     "An error occurred while calling {0}{1}{2}.\n".
--> 312                     format(target_id, ".", name), value)
    313             else:
    314                 raise Py4JError(

Py4JJavaError: An error occurred while calling o47.jdbc.
: org.postgresql.util.PSQLException: The connection attempt failed.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:275)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
    at org.postgresql.Driver.makeConnection(Driver.java:431)
    at org.postgresql.Driver.connect(Driver.java:247)
    at org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.connect(DriverWrapper.scala:45)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:65)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:56)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:123)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:117)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:237)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:159)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:211)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:62)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 22 more
</code>```

The failure is likely due the fact that the application driver (which in --deploy-mode client lives on the client machine) tries to connect to the PostgreSQL instance, which however fails as the PostgreSQL instance is not accessible from the client. However, I do not understand why the connectivity driver-postgreSQL should be required: when actual actions will be executed on the dataframe, the actual operations will be executed by the machines on the cluster (and not by the driver on the client machine), and the results will be sent back to the driver via the cluster master. Hence, the missing connectivity driver-postgreSQL should not prevent from executing dataframe operations as long as the postgreSQL instance is reachable from the cluster.

Questions:

Is it correct that the driver must be able to connect to the database in order to execute operations?

Is there any good reason why this connectivity must be in place that I'm missing?

If that is not the case, is there any way we can bypass this connection check?

答:
As pointed out by Samson Scharfrichter, the driver needs to be able to access the database in order to fetch the schema.

Unfortunately our client does not have direct access to the database. However, as the EMR cluster can access the database and the client has SSH access to the cluster, we can use the following workaround based on SSH tunneling:

```<code>from sshtunnel import SSHTunnelForwarder

url = 'jdbc:postgresql://localhost:5432,psqlhost:5432/psqldatabase'
table = 'mytable'

properties = {
    'user': 'user',
    'password': 'password',
    'driver': 'org.postgresql.Driver'
}

with SSHTunnelForwarder(
    ('emrhost', 22),
    remote_bind_address=('psqlhost', 5432),
    local_bind_address=('localhost', 5432)
    ):
    products_df = spark.read.jdbc(url=url, table=table, properties=properties)
</code>```

After this step, the dataframe products_df can be manipulated even if the tunnel is closed. With this workaround, the client machine can query the database even in client deploy mode.

Body:
We are using Pyspark on an EMR cluster in order to access and analyse data from a PostgreSQL database (accessible via the JDBC connector at jdbc:postgresql://psqlhost:5432/psqldatabase). Network is open between the EMR cluster and the PostgreSQL instance so that, when we access the EMR master via SSH, we can launch the following job successfully (both in client and in cluster deploy mode):

url = 'jdbc:postgresql://psqlhost:5432/psqldatabase'
table = 'mytable'

properties = {
    'user': 'user',
    'password': 'password',
    'driver': 'org.postgresql.Driver'
}

products_df = spark.read.jdbc(url=url, table=table, properties=properties)

We would like now to change setup and execute Pyspark commands on the EMR cluster from a separate client instance with full connectivity to the EMR cluster. This has been successfully set up by copying the necessary yarn configuration files to the client machine and executing Pyspark with --master yarn.

We are however still experiencing issues in accessing the PostgreSQL database from the client instance. For security reasons, the client machine cannot access the PostgreSQL instance, which however remains accessible to the EMR cluster. the above code snippet works without problem with --deploy-mode cluster. However, when working in --deploy-mode client, the last line produces the following error:

17/03/27 11:39:21 ERROR Driver: Connection error:
org.postgresql.util.PSQLException: The connection attempt failed.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:275)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
    at org.postgresql.Driver.makeConnection(Driver.java:431)
    at org.postgresql.Driver.connect(Driver.java:247)
    at org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.connect(DriverWrapper.scala:45)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:65)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:56)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:123)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:117)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:237)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:159)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:211)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:62)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 22 more
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-2-f5f370f4d567> in <module>()
----> 1 products_df = spark.read.jdbc(url=url, table=table, properties=properties)

/opt/spark-2.0.0/python/pyspark/sql/readwriter.pyc in jdbc(self, url, table, column, lowerBound, upperBound, numPartitions, predicates, properties)
    420             jpredicates = utils.toJArray(gateway, gateway.jvm.java.lang.String, predicates)
    421             return self._df(self._jreader.jdbc(url, table, jpredicates, jprop))
--> 422         return self._df(self._jreader.jdbc(url, table, jprop))
    423
    424

/opt/spark-2.0.0/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py in __call__(self, *args)
    931         answer = self.gateway_client.send_command(command)
    932         return_value = get_return_value(
--> 933             answer, self.gateway_client, self.target_id, self.name)
    934
    935         for temp_arg in temp_args:

/opt/spark-2.0.0/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/opt/spark-2.0.0/python/lib/py4j-0.10.1-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    310                 raise Py4JJavaError(
    311                     "An error occurred while calling {0}{1}{2}.\n".
--> 312                     format(target_id, ".", name), value)
    313             else:
    314                 raise Py4JError(

Py4JJavaError: An error occurred while calling o47.jdbc.
: org.postgresql.util.PSQLException: The connection attempt failed.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:275)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
    at org.postgresql.Driver.makeConnection(Driver.java:431)
    at org.postgresql.Driver.connect(Driver.java:247)
    at org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.connect(DriverWrapper.scala:45)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:65)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:56)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:123)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:117)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:237)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:159)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:211)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:62)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 22 more

The failure is likely due the fact that the application driver (which in --deploy-mode client lives on the client machine) tries to connect to the PostgreSQL instance, which however fails as the PostgreSQL instance is not accessible from the client. However, I do not understand why the connectivity driver-postgreSQL should be required: when actual actions will be executed on the dataframe, the actual operations will be executed by the machines on the cluster (and not by the driver on the client machine), and the results will be sent back to the driver via the cluster master. Hence, the missing connectivity driver-postgreSQL should not prevent from executing dataframe operations as long as the postgreSQL instance is reachable from the cluster.

Questions:

Is it correct that the driver must be able to connect to the database in order to execute operations?

Is there any good reason why this connectivity must be in place that I'm missing?

If that is not the case, is there any way we can bypass this connection check?

Body:
As pointed out by Samson Scharfrichter, the driver needs to be able to access the database in order to fetch the schema.

Unfortunately our client does not have direct access to the database. However, as the EMR cluster can access the database and the client has SSH access to the cluster, we can use the following workaround based on SSH tunneling:

from sshtunnel import SSHTunnelForwarder

url = 'jdbc:postgresql://localhost:5432,psqlhost:5432/psqldatabase'
table = 'mytable'

properties = {
    'user': 'user',
    'password': 'password',
    'driver': 'org.postgresql.Driver'
}

with SSHTunnelForwarder(
    ('emrhost', 22),
    remote_bind_address=('psqlhost', 5432),
    local_bind_address=('localhost', 5432)
    ):
    products_df = spark.read.jdbc(url=url, table=table, properties=properties)

After this step, the dataframe products_df can be manipulated even if the tunnel is closed. With this workaround, the client machine can query the database even in client deploy mode.


问:
Android Studio continues to get a Unsupported major.minor version 52.0
After merging my project with some changes from other developers I continue to get the following:

```<code>Error:Cause: com/android/build/gradle/internal/model/DefaultAndroidProject : Unsupported major.minor version 52.0
</code>```

I've tried installing Java 8, and setting my project to use Java 8.  If I change my JAVA_HOME to 1.8 on the command line and compile with gradle it works.  If I try to use JAVA_HOME set to 1.7 and gradle it fails with the same error.

However, in Android Studio, no matter the JDK version, it continues to print that error.

Other developers are saying they are using Java 7 without issue.  Other things I've tried:

```<code>gradle clean build
gradlew clean build
Reinstalling Android Studio
</code>```

Another interesting symptom is that other projects in Android Studio are perfectly happy.  It's just this project that has this problem.

Here are my environment settings:

```<code>OS: Mac OS X 10.9.5
Android Studio: 2.1.1
Android Studio JVM: 1.6
Project JVM: 1.7.0_75
Android SDK (Build Tools): 23.0.2
Gradle: 2.13
JAVA_HOME: /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home
ANDROID_HOME: /Users/me/Library/Android/sdk
</code>```

I suspect it has something to do with the gradle wrapper, but I can't figure out how to get graddle wrapper to reinitialize itself using 1.7.

答:
If you're seeing this error you need to update your JDK in "Project Structure" options.

This is found under File > Project Structure > SDK. Or from the welcome screen in Configure > Project Defaults > Project Structure.

Select the Use the embedded JDK (recommended) option instead of using your own JDK.

Body:
After merging my project with some changes from other developers I continue to get the following:

Error:Cause: com/android/build/gradle/internal/model/DefaultAndroidProject : Unsupported major.minor version 52.0

I've tried installing Java 8, and setting my project to use Java 8.  If I change my JAVA_HOME to 1.8 on the command line and compile with gradle it works.  If I try to use JAVA_HOME set to 1.7 and gradle it fails with the same error.

However, in Android Studio, no matter the JDK version, it continues to print that error.

Other developers are saying they are using Java 7 without issue.  Other things I've tried:

gradle clean build
gradlew clean build
Reinstalling Android Studio

Another interesting symptom is that other projects in Android Studio are perfectly happy.  It's just this project that has this problem.

Here are my environment settings:

OS: Mac OS X 10.9.5
Android Studio: 2.1.1
Android Studio JVM: 1.6
Project JVM: 1.7.0_75
Android SDK (Build Tools): 23.0.2
Gradle: 2.13
JAVA_HOME: /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home
ANDROID_HOME: /Users/me/Library/Android/sdk

I suspect it has something to do with the gradle wrapper, but I can't figure out how to get graddle wrapper to reinitialize itself using 1.7.


问:
Populate a user object in the Firebase database when a new user signs up?
Currently, I'm working with a firebase application that only uses the Google auth provider. There is a single sign-in flow for new and returning users that calls
firebase.auth().signInWithPopup() to authenticate the user.

I want to populate an object on the firebase database that stores each new user's UUID and information about them. Ideally, I'd like to generate this information server side and not allow write access to the object from the client.

How can I best tell when a new user has signed up? I am passing the user's token to the server as a cookie to be authenticated with each request to make sure they're signed in and authorized. I could check the UUID of each request to see if it's already in the users object, but this seems hugely wasteful as the majority of requests will not be from new users.

答:
modify rule of real time database:</p>

```<code> "rules": {
    "Users":{
      "$uid":{
          ".read": "auth.uid == $uid",
           ".write": "auth.uid == $uid"
}
}
}
</code>```

Body:
modify rule of real time database:

 "rules": {
    "Users":{
      "$uid":{
          ".read": "auth.uid == $uid",
           ".write": "auth.uid == $uid"
}
}
}


问:
How can we communicate between a TCPEventBus and SockJSEventBus in vertx
I have written two verticle one runs a TCPEventBusBridge and another SockJSEventBus. I want to communicate between both. How can I do it in a vertx environment.

android client is talking to the TCPEventBus server and a web client is listening to a SockJSEvent bus server.

答:
If the eventbuses are connected then this shouldn't be a problem. The eventbus has one namespace. That means, if you send a message (m) to an address (a) from your webclient and this address (a) is registered in the component (c), which is connected over the TCPEventBusBridge. The message (m) should reach the component (c).

Here is and example with SockJS and 2 clustered vert.x Instances (2 separate JVM). The part of the TCPEventBusBridge is missing, but it can give you an idea how it can work.

https://github.com/floriankammermann/vertx-examples/blob/master/eventbus-chat (Run the Example on two JVM clustered eventbus)


答:
Join them?</p>

```<code>select * from table1
  join table2 j1 on table2.id = table1.old_category
  join table2 j2 on table2.id = table1.new_category
</code>```

Title: Query to get name from a table with 2 ID columns

Body:
Join them?

select * from table1
  join table2 j1 on table2.id = table1.old_category
  join table2 j2 on table2.id = table1.new_category


问:
React / Redux components rerendering
Hi I have been using React / Redux for may App. I have to render multiple input fields dynamically. The problem which I am facing right now is...

So suppose, the form already have 2 input fields, and I want 5 input fields total, I will simply render these with the help of a loop with 5 repetitions. the problem is react renders 3 new fields and keeps 2 old at top. But I need fresh 5 fields. Is there a way to force react to remove old fields first and then render 5 new fields.

答:
The problem is in the key attribute. If you give the components new keys each render, then the fields will be recreated

A small example is below. I used Math.and() to generate unique keys. Of course, better to use shortid or similar

https://www.npmjs.com/browse/keyword/shortid

```<code>class InputRenderer extends Component {

  constructor() {
    super()
    this.state = {
      inputsCount: 3
    }
  }

  handleInputsCountChange = (newCount) => {
    this.setState({
      inputsCount: newCount
    })
  }

  renderInputs = () => {
    const inputs = []
    for (let i = 0; i < this.state.inputsCount; i++) {
      inputs.push(<input key={i + Math.random()} />)
    }
    return inputs
  }

  render = () =>
    <div>
      <button onClick={() => this.handleInputsCountChange(3)}>3</button>
      <button onClick={() => this.handleInputsCountChange(5)}>5</button>
      {this.renderInputs()}
    </div>
}
</code>```

Title: React / Redux components rerendering

Body:
The problem is in the key attribute. If you give the components new keys each render, then the fields will be recreated

A small example is below. I used Math.and() to generate unique keys. Of course, better to use shortid or similar

https://www.npmjs.com/browse/keyword/shortid

class InputRenderer extends Component {

  constructor() {
    super()
    this.state = {
      inputsCount: 3
    }
  }

  handleInputsCountChange = (newCount) => {
    this.setState({
      inputsCount: newCount
    })
  }

  renderInputs = () => {
    const inputs = []
    for (let i = 0; i < this.state.inputsCount; i++) {
      inputs.push(<input key={i + Math.random()} />)
    }
    return inputs
  }

  render = () =>
    <div>
      <button onClick={() => this.handleInputsCountChange(3)}>3</button>
      <button onClick={() => this.handleInputsCountChange(5)}>5</button>
      {this.renderInputs()}
    </div>
}


问:
Elements move on hover because border is added, padding, as suggested elsewhere doesn't seem to work
When I hover over an area on my testing website, I made it so a border is added. But because that happens, other elements move. I've looked up other posts, and they recommended adding padding, but that doesn't seem to work because it goes over other stuff.

This is where I add the border:

```<code>#logo:hover {
  border: 2px solid cyan;
}
</code>```

This is what it was added to:

```<code>#logo {
    width: 200px;
    height: 200px;
    position: relative;
    top: 80px;
    line-height: 12em;
    border-radius: 200px;
    margin: 0 10px 0 10px;
    overflow: hidden;
}
</code>```

Does anyone know how to help me? Also about the way I asked my question.

#logo {
    background-color: black;
    width: 200px;
    height: 200px;
    position: relative;
    top: 80px;
    line-height: 12em;
    border-radius: 200px;
    margin: 0 10px 0 10px;
    overflow: hidden;
}

#logo:hover {
  border: 2px solid cyan;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id=logo></div></code>```

Greetings,
TheWombatGuru

答:
You also can use box shadow:</p>

```<code> #logo{
    box-shadow: inset 0 0 0 1px cyan;
 }

 #logo:hover {
    box-shadow: inset 0 0 0 2px cyan;
 }
</code>```

Body:
When I hover over an area on my testing website, I made it so a border is added. But because that happens, other elements move. I've looked up other posts, and they recommended adding padding, but that doesn't seem to work because it goes over other stuff.

This is where I add the border:

#logo:hover {
  border: 2px solid cyan;
}

This is what it was added to:

#logo {
    width: 200px;
    height: 200px;
    position: relative;
    top: 80px;
    line-height: 12em;
    border-radius: 200px;
    margin: 0 10px 0 10px;
    overflow: hidden;
}

Does anyone know how to help me? Also about the way I asked my question.

#logo {
    background-color: black;
    width: 200px;
    height: 200px;
    position: relative;
    top: 80px;
    line-height: 12em;
    border-radius: 200px;
    margin: 0 10px 0 10px;
    overflow: hidden;
}

#logo:hover {
  border: 2px solid cyan;
}

Greetings,
TheWombatGuru

Body:
You also can use box shadow:

 #logo{
    box-shadow: inset 0 0 0 1px cyan;
 }

 #logo:hover {
    box-shadow: inset 0 0 0 2px cyan;
 }


问:
Trying to filter out matching records from 2 array as 1 array have different structure
Below is my sample records :

```<code>var array1 = [
    {
      "testId": 15,
      "child": [
        {
          "variantId": 100,
          "name": "A1",
        },
        {
          "variantId": 200,
          "name": "A2",
        },
        {
          "variantId": 300,
          "name": "A3",
        },
        {
          "variantId": 400,
          "name": "A4",
        },
        {
          "variantId": 500,
          "name": "A5",
        }
      ]
    }
]

var array2=
[
    {
      "variantId": 100,
      "tests": [
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 200,
      "tests": [
        {
          "testId": 15,
          "flag" : false
        }
      ]
    },
    {
      "variantId": 400,
      "tests": [
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 500,
      "tests": [
        {
          "testId": 15,
          "flag" : true
        }
      ]
    }
  ]
</code>```

At first I will fetch selected testId record from Array1. Now I would like to select only those variantId from array2 whose flag is true. For example, from inputs ,VariantIds will be 100,400 and 500.

Now with this selected variantsIds from array2 I want fetch only matching variantIds, so from Array2 I want to search 100,400 and 500 in Array1 and select only matching records from Array1.

Expected output :

```<code>"child": [
        {
          "variantId": 100,
          "name": "A1",
        },
        {
          "variantId": 400,
          "name": "A4",
        },
        {
          "variantId": 500,
          "name": "A5",
        }
      ]
</code>```

So far I am successful in getting specific TestId record from array1 but now I am not getting how to filter out variantIds from array1 as structure of array2 is little complex.

var array1 = [
    {
      "testId": 15,
      "child": [
        {
          "variantId": 100,
          "name": "A1",
        },
        {
          "variantId": 200,
          "name": "A2",
        },
        {
          "variantId": 300,
          "name": "A3",
        },
        {
          "variantId": 400,
          "name": "A4",
        },
        {
          "variantId": 500,
          "name": "A5",
        }
      ]
    }
]

var array2=
[
    {
      "variantId": 100,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 200,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : false
        }
      ]
    },
    {
      "variantId": 400,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 500,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : true
        }
      ]
    }
  ]

var testId = 15;

var testObj ={};
 for (var i = 0; i < array1.length; i++) {
            if (array1[i].testId == testId) {
                testObj = array1[i];
                break;
            }
        }
        console.log(testObj);```

答:
You could use a hash table and get first all true flags, the filter the child array.

function getChildren(data, flags, testId) {
    var hash = Object.create(null),
        result;

    flags.forEach(function (a) {
        a.tests.forEach(function (b) {
            b.testId === testId && b.flag && (hash[a.variantId] = true);
        });
    });

    data.forEach(function (a) {
        if (a.testId === testId) {
            result = {
                child: a.child.filter(function (b) {
                    return hash[b.variantId];
                })
            };
        }
    });
    return result;
}

var array1 = [{ testId: 15, child: [{ variantId: 100, name: "A1", }, { variantId: 200, name: "A2", }, { variantId: 300, name: "A3", }, { variantId: 400, name: "A4", }, { variantId: 500, name: "A5", }] }],
    array2 = [{ variantId: 100, tests: [{ testId: 15, flag: true }] }, { variantId: 200, tests: [{ testId: 15, flag: false }] }, { variantId: 400, tests: [{ testId: 15, flag: true }] }, { variantId: 500, tests: [{ testId: 15, flag: true }] }],
    array3 = [{ testId: 15, child: [{ variantId: 100, name: "A1", }, { variantId: 200, name: "A2", }, { variantId: 300, name: "A3", }, { variantId: 400, name: "A4", }, { variantId: 500, name: "A5", }] }],
    array4 = [{ variantId: 100, tests: [{ testId: 14, flag: true }, { testId: 15, flag: true }] }, { variantId: 200, tests: [{ testId: 14, flag: true }, { testId: 15, flag: false }] }, { variantId: 400, tests: [{ testId: 14, flag: true }, { testId: 15, flag: true }] }, { variantId: 500, tests: [{ testId: 14, flag: true }, { testId: 15, flag: true }] }],
    testId = 15;

console.log(getChildren(array1, array2, testId));
console.log(getChildren(array3, array4, testId));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Below is my sample records :

var array1 = [
    {
      "testId": 15,
      "child": [
        {
          "variantId": 100,
          "name": "A1",
        },
        {
          "variantId": 200,
          "name": "A2",
        },
        {
          "variantId": 300,
          "name": "A3",
        },
        {
          "variantId": 400,
          "name": "A4",
        },
        {
          "variantId": 500,
          "name": "A5",
        }
      ]
    }
]

var array2=
[
    {
      "variantId": 100,
      "tests": [
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 200,
      "tests": [
        {
          "testId": 15,
          "flag" : false
        }
      ]
    },
    {
      "variantId": 400,
      "tests": [
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 500,
      "tests": [
        {
          "testId": 15,
          "flag" : true
        }
      ]
    }
  ]

At first I will fetch selected testId record from Array1. Now I would like to select only those variantId from array2 whose flag is true. For example, from inputs ,VariantIds will be 100,400 and 500.

Now with this selected variantsIds from array2 I want fetch only matching variantIds, so from Array2 I want to search 100,400 and 500 in Array1 and select only matching records from Array1.

Expected output :

"child": [
        {
          "variantId": 100,
          "name": "A1",
        },
        {
          "variantId": 400,
          "name": "A4",
        },
        {
          "variantId": 500,
          "name": "A5",
        }
      ]

So far I am successful in getting specific TestId record from array1 but now I am not getting how to filter out variantIds from array1 as structure of array2 is little complex.

var array1 = [
    {
      "testId": 15,
      "child": [
        {
          "variantId": 100,
          "name": "A1",
        },
        {
          "variantId": 200,
          "name": "A2",
        },
        {
          "variantId": 300,
          "name": "A3",
        },
        {
          "variantId": 400,
          "name": "A4",
        },
        {
          "variantId": 500,
          "name": "A5",
        }
      ]
    }
]

var array2=
[
    {
      "variantId": 100,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 200,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : false
        }
      ]
    },
    {
      "variantId": 400,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : true
        }
      ]
    },
    {
      "variantId": 500,
      "tests": [
        {
          "testId": 14,
          "flag" : true
        },
        {
          "testId": 15,
          "flag" : true
        }
      ]
    }
  ]

var testId = 15;

var testObj ={};
 for (var i = 0; i < array1.length; i++) {
            if (array1[i].testId == testId) {
                testObj = array1[i];
                break;
            }
        }
        console.log(testObj);

Body:
You could use a hash table and get first all true flags, the filter the child array.

function getChildren(data, flags, testId) {
    var hash = Object.create(null),
        result;

    flags.forEach(function (a) {
        a.tests.forEach(function (b) {
            b.testId === testId && b.flag && (hash[a.variantId] = true);
        });
    });

    data.forEach(function (a) {
        if (a.testId === testId) {
            result = {
                child: a.child.filter(function (b) {
                    return hash[b.variantId];
                })
            };
        }
    });
    return result;
}

var array1 = [{ testId: 15, child: [{ variantId: 100, name: "A1", }, { variantId: 200, name: "A2", }, { variantId: 300, name: "A3", }, { variantId: 400, name: "A4", }, { variantId: 500, name: "A5", }] }],
    array2 = [{ variantId: 100, tests: [{ testId: 15, flag: true }] }, { variantId: 200, tests: [{ testId: 15, flag: false }] }, { variantId: 400, tests: [{ testId: 15, flag: true }] }, { variantId: 500, tests: [{ testId: 15, flag: true }] }],
    array3 = [{ testId: 15, child: [{ variantId: 100, name: "A1", }, { variantId: 200, name: "A2", }, { variantId: 300, name: "A3", }, { variantId: 400, name: "A4", }, { variantId: 500, name: "A5", }] }],
    array4 = [{ variantId: 100, tests: [{ testId: 14, flag: true }, { testId: 15, flag: true }] }, { variantId: 200, tests: [{ testId: 14, flag: true }, { testId: 15, flag: false }] }, { variantId: 400, tests: [{ testId: 14, flag: true }, { testId: 15, flag: true }] }, { variantId: 500, tests: [{ testId: 14, flag: true }, { testId: 15, flag: true }] }],
    testId = 15;

console.log(getChildren(array1, array2, testId));
console.log(getChildren(array3, array4, testId));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Difference in time between records
I have a table that has (among others) a timestamp column (named timestamp; it's a standard Oracle DATE datatype).  The records are about 4-11 minutes apart, about 7 or 8 records every hour, and I'm trying to determine if there is any pattern to them.

Is there an easy way to see each record, and the number of minutes that record occurred after the previous record?

Thanks,
AndyDan

答:
This is Oracle 9i+, using the LAG function to get the previous timestamp value without needing to self join:

```<code>SELECT t.timestamp - LAG(t.timestamp) OVER (ORDER BY t.timestamp) AS diff
  FROM YOUR_TABLE t
</code>```

...but because whole numbers represent the number of days in the result, a difference of less than 24 hours will be a fraction.  Also, the LAG will return NULL if there's no earlier value -- same as if having used an OUTER JOIN.

To see minutes, use the ROUND function:

```<code>SELECT ROUND((t.timestamp - LAG(t.timestamp) OVER (ORDER BY t.timestamp)) *1440) AS diff_in_minutes
  FROM YOUR_TABLE t
</code>```

Title: Difference in time between records

Body:
This is Oracle 9i+, using the LAG function to get the previous timestamp value without needing to self join:

SELECT t.timestamp - LAG(t.timestamp) OVER (ORDER BY t.timestamp) AS diff
  FROM YOUR_TABLE t

...but because whole numbers represent the number of days in the result, a difference of less than 24 hours will be a fraction.  Also, the LAG will return NULL if there's no earlier value -- same as if having used an OUTER JOIN.

To see minutes, use the ROUND function:

SELECT ROUND((t.timestamp - LAG(t.timestamp) OVER (ORDER BY t.timestamp)) *1440) AS diff_in_minutes
  FROM YOUR_TABLE t


问:
Sensu check for jvm heap not working
I am facing issues with sensu-plugins-java. I have installed plugin in our server and I need to use check-java-heap-pcnt.rb to monitor the heap size in our server, but it is not showing proper output when I try to run the check locally.
Here's how I tried to run the check locally: </p>

```<code># ./check-java-heap-pcnt.rb -n java -w 70 -c 85 -j /usr/java/defaults/bin/ -p
</code>```

<p>Here's the output it generated: </p>

```<code>    invalid argument count
Usage: jstat -help|-options
       jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]

Definitions:
  <option>      An option reported by the -options option
  <vmid>        Virtual Machine Identifier. A vmid takes the following form:
                     <lvmid>[@<hostname>[:<port>]]
                Where <lvmid> is the local vm identifier for the target
                Java virtual machine, typically a process id; <hostname>is
                the name of the host running the target Java virtual machine;
                and <port> is the port number for the rmiregistry on the
                target host. See the jvmstat documentation for a more complete
                description of the Virtual Machine Identifier.
  <lines>       Number of samples between header lines.
  <interval>    Sampling interval. The following forms are allowed:
                    <n>["ms"|"s"]
                Where <n> is an integer and the suffix specifies the units as
                milliseconds("ms") or seconds("s"). The default units are "ms".
  <count>       Number of samples to take before terminating.
  -J<flag>      Pass <flag> directly to the runtime system.
(standard_in) 1: syntax error
MEM UNKNOWN -
</code>```

答:
Download the nagios plugins from
https://kb.op5.com/display/HOWTOs/Jboss+Monitoring+with+check_jmx

and use with sensu.

Name:- check_jmx

For thread cound command:-

./check_jmx -U service:jmx:rmi:///jndi/rmi://'servername':'port'/jmxrmi -O java.lang:type=Threading -A ThreadCount  -K 9200 -w 250 -c 300

For Heap Memory:-

./check_jmx -U service:jmx:rmi:///jndi/rmi://'servername':'port'/jmxrmi -O java.lang:type=Memory -A HeapMemoryUsage -K used -I HeapMemoryUsage -J used -vvvv -w 102400 -c 81290

Title: Sensu check for jvm heap not working

Body:
I am facing issues with sensu-plugins-java. I have installed plugin in our server and I need to use check-java-heap-pcnt.rb to monitor the heap size in our server, but it is not showing proper output when I try to run the check locally.
Here's how I tried to run the check locally:

# ./check-java-heap-pcnt.rb -n java -w 70 -c 85 -j /usr/java/defaults/bin/ -p

Here's the output it generated:

    invalid argument count
Usage: jstat -help|-options
       jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]

Definitions:
  <option>      An option reported by the -options option
  <vmid>        Virtual Machine Identifier. A vmid takes the following form:
                     <lvmid>[@<hostname>[:<port>]]
                Where <lvmid> is the local vm identifier for the target
                Java virtual machine, typically a process id; <hostname>is
                the name of the host running the target Java virtual machine;
                and <port> is the port number for the rmiregistry on the
                target host. See the jvmstat documentation for a more complete
                description of the Virtual Machine Identifier.
  <lines>       Number of samples between header lines.
  <interval>    Sampling interval. The following forms are allowed:
                    <n>["ms"|"s"]
                Where <n> is an integer and the suffix specifies the units as
                milliseconds("ms") or seconds("s"). The default units are "ms".
  <count>       Number of samples to take before terminating.
  -J<flag>      Pass <flag> directly to the runtime system.
(standard_in) 1: syntax error
MEM UNKNOWN -


问:
DomElement from ContextMenuHandler
Is there away to get the DOMElement with my ContextMenuHandler when user right clicks on page?  I need to retrieve attribute information stored on element that I click on.</p>

答:
You can use the Browser.getNodeAtPoint(int x, int y) method to find DOMNode at the given location on the loaded document. The x and y you can get from ContextMenuParams. For example:

```<code>DOMNodeAtPoint nodeAtPoint = params.getBrowser().getNodeAtPoint(params.getLocation());
DOMNode node = nodeAtPoint.getNode();
</code>```

Title: DomElement from ContextMenuHandler

Body:
You can use the Browser.getNodeAtPoint(int x, int y) method to find DOMNode at the given location on the loaded document. The x and y you can get from ContextMenuParams. For example:

DOMNodeAtPoint nodeAtPoint = params.getBrowser().getNodeAtPoint(params.getLocation());
DOMNode node = nodeAtPoint.getNode();


问:
Different width and height from DisplayMetrics and $(window).width() in WebView
Inside an Android app, I tried using the following way to obtain the screen width and height:

```<code>DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final int screenWidth = metrics.widthPixels;
        final int screenHeight = metrics.heightPixels;
</code>```

This reports 1080 and 1920 respectively for my phone, which matches the specs.

However, inside a webview, when I used:

```<code>var screenWidth = $(window).width();
</code>```

This reports only 360.

From this what I understand, both are using pixel as unit, so why are the values different?

答:
Notice width is same in both cases but units are different.

E.g.

This is in Pixels
metrics.widthPixels;

This one is in Dps
360 OR $(window).width();

Convert 360Dps to pixels

On xxhdpi device, 360dps = 1080px

Dp to pixels & vice versa

Body:
Inside an Android app, I tried using the following way to obtain the screen width and height:

DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final int screenWidth = metrics.widthPixels;
        final int screenHeight = metrics.heightPixels;

This reports 1080 and 1920 respectively for my phone, which matches the specs.

However, inside a webview, when I used:

var screenWidth = $(window).width();

This reports only 360.

From this what I understand, both are using pixel as unit, so why are the values different?


问:
Move a view up only when the keyboard covers an input field
I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom.
When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen.
I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}
</code>```

答:
Awesome answers are already given but this is a different way to deal with this situation (using Swift 3x):

First of all call the following method in viewWillAppear()

```<code>func registerForKeyboardNotifications() {

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}
</code>```

Now take one IBOutlet of UIView's top constraints of your UIViewcontroller like this: (here the UIView is the subview of UIScrollView that means you should have a UIScrollView for all your subViews)

```<code>@IBOutlet weak var loginViewTopConstraint: NSLayoutConstraint!
</code>```

And an another variable like following and add a delegate i.e. UITextFieldDelegate:

```<code>var activeTextField = UITextField() //This is to keep the reference of UITextField currently active
</code>```

After that here is the magical part just paste this below snippet:

```<code>func keyboardWasShown(_ notification: Notification) {

let keyboardInfo  = notification.userInfo as NSDictionary?

//print(keyboardInfo!)

let keyboardFrameEnd: NSValue? = (keyboardInfo?.value(forKey: UIKeyboardFrameEndUserInfoKey) as? NSValue)

let keyboardFrameEndRect: CGRect? = keyboardFrameEnd?.cgRectValue

if activeTextField.frame.origin.y + activeTextField.frame.size.height + 10 > (keyboardFrameEndRect?.origin.y)! {

    UIView.animate(withDuration: 0.3, delay: 0, options: .transitionFlipFromTop, animations: {() -> Void in

        //code with animation

        //Print some stuff to know what is actually happening
        //print(self.activeTextField.frame.origin.y)
        //print(self.activeTextField.frame.size.height)
        //print(self.activeTextField.frame.size.height)

        self.loginViewTopConstraint.constant = -(self.activeTextField.frame.origin.y + self.activeTextField.frame.size.height - (keyboardFrameEndRect?.origin.y)!) - 30.0

        self.view.layoutIfNeeded()

    }, completion: {(_ finished: Bool) -> Void in
        //code for completion

    })
}
}

func keyboardWillBeHidden(_ notification: Notification) {

UIView.animate(withDuration: 0.3, animations: {() -> Void in

    self.loginViewTopConstraint.constant = self.view.frame.origin.y
    self.view.layoutIfNeeded()

})
}

//MARK: textfield delegates
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    activeTextField = textField
    return true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

           switch textField {
    case YOUR_TEXTFIELD_ONE:
        YOUR_TEXTFIELD_TWO.becomeFirstResponder()
        break
    case YOUR_TEXTFIELD_TWO:
        YOUR_TEXTFIELD_THREE.becomeFirstResponder()
        break
    default:
        textField.resignFirstResponder()
        break
    }
    return true
}
</code>```

Now the last snippet:

```<code>//Remove Keyboard Observers
override func viewWillDisappear(_ animated: Bool) {

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
</code>```

Don't forget to assign delegates to all your UITextFields  in UIStoryboard

Good luck!

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom.
When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen.
I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}

Body:
Awesome answers are already given but this is a different way to deal with this situation (using Swift 3x):

First of all call the following method in viewWillAppear()

func registerForKeyboardNotifications() {

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

Now take one IBOutlet of UIView's top constraints of your UIViewcontroller like this: (here the UIView is the subview of UIScrollView that means you should have a UIScrollView for all your subViews)

@IBOutlet weak var loginViewTopConstraint: NSLayoutConstraint!

And an another variable like following and add a delegate i.e. UITextFieldDelegate:

var activeTextField = UITextField() //This is to keep the reference of UITextField currently active

After that here is the magical part just paste this below snippet:

func keyboardWasShown(_ notification: Notification) {

let keyboardInfo  = notification.userInfo as NSDictionary?

//print(keyboardInfo!)

let keyboardFrameEnd: NSValue? = (keyboardInfo?.value(forKey: UIKeyboardFrameEndUserInfoKey) as? NSValue)

let keyboardFrameEndRect: CGRect? = keyboardFrameEnd?.cgRectValue

if activeTextField.frame.origin.y + activeTextField.frame.size.height + 10 > (keyboardFrameEndRect?.origin.y)! {

    UIView.animate(withDuration: 0.3, delay: 0, options: .transitionFlipFromTop, animations: {() -> Void in

        //code with animation

        //Print some stuff to know what is actually happening
        //print(self.activeTextField.frame.origin.y)
        //print(self.activeTextField.frame.size.height)
        //print(self.activeTextField.frame.size.height)

        self.loginViewTopConstraint.constant = -(self.activeTextField.frame.origin.y + self.activeTextField.frame.size.height - (keyboardFrameEndRect?.origin.y)!) - 30.0

        self.view.layoutIfNeeded()

    }, completion: {(_ finished: Bool) -> Void in
        //code for completion

    })
}
}

func keyboardWillBeHidden(_ notification: Notification) {

UIView.animate(withDuration: 0.3, animations: {() -> Void in

    self.loginViewTopConstraint.constant = self.view.frame.origin.y
    self.view.layoutIfNeeded()

})
}

//MARK: textfield delegates
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    activeTextField = textField
    return true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

           switch textField {
    case YOUR_TEXTFIELD_ONE:
        YOUR_TEXTFIELD_TWO.becomeFirstResponder()
        break
    case YOUR_TEXTFIELD_TWO:
        YOUR_TEXTFIELD_THREE.becomeFirstResponder()
        break
    default:
        textField.resignFirstResponder()
        break
    }
    return true
}

Now the last snippet:

//Remove Keyboard Observers
override func viewWillDisappear(_ animated: Bool) {

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

Don't forget to assign delegates to all your UITextFields  in UIStoryboard

Good luck!


问:
How to grep word from file
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

```<code>open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);
</code>```

My file1.txt is something like this:

```<code>i am a dog
i am a cat
we are the fish
he is a boy
she is a girl
</code>```

My file2.txt is like this:

```<code>is
am
</code>```

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

答:
You can already do this with egrep :</p>

```<code>egrep -f file2.txt file1.txt
</code>```

Title: How to grep word from file

Body:
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);

My file1.txt is something like this:

i am a dog
i am a cat
we are the fish
he is a boy
she is a girl

My file2.txt is like this:

is
am

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

Body:
You can already do this with egrep :

egrep -f file2.txt file1.txt


问:
Unexplained number in front of json array from php json_encode
I try to create a JSON Array of objects in php with json_encode.
The source of the Jobs Array is Doctrine but I think that is unimportant.

```<code>$jobsAsArray = array();
foreach ($jobs as $job) {
    $jobsAsArray[] = array('jobId' => $job->getId(),
                    'jobName' => $job->getName(),
                    'jobType' => $job->getJobType());
}
echo json_encode($jobsAsArray);
</code>```

I get this result:

```<code>1[{"jobid":1,"jobName":"Name1","jobType":"type1"},{"jobid":2,"jobName":"CoolName","jobType":"type2"},{"jobid":3,"jobName":"noName","jobType":"noType"}]
</code>```

If I understood correctly, I get an JSON Array with three objects. But I don't understand why there is a '1' in front if the Array.

thank you in advance

答: Where you show the json array, are you sure you didn't put this number accidentally before the result? if not, can you post the rest of the code like html and the rest of php? it's weird x)</p>

Body:
I try to create a JSON Array of objects in php with json_encode.
The source of the Jobs Array is Doctrine but I think that is unimportant.

$jobsAsArray = array();
foreach ($jobs as $job) {
    $jobsAsArray[] = array('jobId' => $job->getId(),
                    'jobName' => $job->getName(),
                    'jobType' => $job->getJobType());
}
echo json_encode($jobsAsArray);

I get this result:

1[{"jobid":1,"jobName":"Name1","jobType":"type1"},{"jobid":2,"jobName":"CoolName","jobType":"type2"},{"jobid":3,"jobName":"noName","jobType":"noType"}]

If I understood correctly, I get an JSON Array with three objects. But I don't understand why there is a '1' in front if the Array.

thank you in advance


问:
Change the size of a JTextField inside a JBorderLayout
When I use the code below it doesn't alter the size at all, it still fills the area in the grid.</p>

```<code>JPanel displayPanel = new JPanel(new GridLayout(4, 2));

JTextField titleText = new JTextField("title");

displayPanel.add(titleText);

titleText.setSize(200, 24);
</code>```

答: With a BorderLayout you need to use setPreferredSize instead of setSize

Body:
When I use the code below it doesn't alter the size at all, it still fills the area in the grid.

JPanel displayPanel = new JPanel(new GridLayout(4, 2));

JTextField titleText = new JTextField("title");

displayPanel.add(titleText);

titleText.setSize(200, 24);


问:
Custom code snippet for WebStorm and PhpStorm
I use custom code snippet for Sublime Text like custom comments, function, reusable block code, CDN and more.. but I could not do that in WebStorm and PhpStorm IDE.

Here is my building block code snippet (comments) for Sublime Text:

```<code> /*============================
            comments
   ============================*/
</code>```

and this code blocks for HTML5 comments

```<code> <!-----------------------
           comments
   ----------------------->
</code>```

Moreover I'm new user for JetBrains software. Can I use custom code snippet above in JetBrains software ?

答:
I don't think you can do this, however you can add custom tags in Settings > Editor > TODO.

//TODO & //FIXME are already implemented.

But this custom tags are not working for HTML.

Maybe you can find an extension to do that in Settings > Plugins.

Body:
I use custom code snippet for Sublime Text like custom comments, function, reusable block code, CDN and more.. but I could not do that in WebStorm and PhpStorm IDE.

Here is my building block code snippet (comments) for Sublime Text:

 /*============================
            comments
   ============================*/

and this code blocks for HTML5 comments

Moreover I'm new user for JetBrains software. Can I use custom code snippet above in JetBrains software ?


问:
angularjs How to escape “${variable}” in html?
I want to show a string like ${date} to the div element:

```<code><div>please use the ${date} as the substitute tag to the name</div>
</code>```

the content will be display like:

```<code>please use the ${date} as the substitute tag to the name.
</code>```

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

答:
Thanks for all the answers, I have resolve the problem in an elegant way.

I replace the string ${date} with {{"\${date}"}} and it works. It means that the browser regards the "\${date}" as a angularjs expression which is referenced to the constant string value.

By the way, $ is a special character in string, we should add an escape character \ before it.

Body:
I want to show a string like ${date} to the div element:

please use the ${date} as the substitute tag to the name

the content will be display like:

please use the ${date} as the substitute tag to the name.

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?


答:
Problem is solved in Comments! There was another echo in my script.

`you have another echo or print in your script. – Amani'

thx!

Title: Unexplained number in front of json array from php json_encode


问:
Can I use an if statement with multiple conditions? PHP
I bet I can, but would it work like this?

```<code>function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }
</code>```

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

答:
Try this:

Use elseif conditions

```<code>if ($month == '01') {
    $dutchmonth = 'Januari';
} elseif ($month == '02') {
    $dutchmonth = 'Februari';
} elseif ($month == '03') {
   $dutchmonth = '...';
}
</code>```

Body:
I bet I can, but would it work like this?

function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

Body:
Try this:

Use elseif conditions

if ($month == '01') {
    $dutchmonth = 'Januari';
} elseif ($month == '02') {
    $dutchmonth = 'Februari';
} elseif ($month == '03') {
   $dutchmonth = '...';
}


问:
How to select earliest date according to current sg
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.</p>

```<code>empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31
</code>```

答:
If I understand you correctly, you can do that both with an inner query

```<code>select  min(date_from)
from    yourTable
where   sg = (
            select  sg
            from    yourTable
            where   date_to = '1900-01-01'
        )
</code>```

or with a join

```<code>select  min(t1.date_from)
from    yourTable t1
join    yourTable t2
on      t1.sg = t2.sg
where   t2.date_to = '1900-01-01'
</code>```

Edit

To get the minimum date for each position, the easiest way is tweaking the second query into this:

```<code>select  t1.position, min(t1.date_from)
from    yourTable t1
join    yourTable t2
on      t1.sg = t2.sg and
        t1.position = t2.position
where   t2.date_to = '1900-01-01'
group by t1.position
</code>```

Edit 2

Since the requirement is to get the minimum date for each value in the the empno column, what you need to do is this

```<code>select  t1.empno, min(t1.date_from)
from    yourTable t1
join    yourTable t2
on      t1.sg = t2.sg and
        t1.empno = t2.empno
where   t2.date_to = '1900-01-01'
group by t1.empno
</code>```

You can see it at work here

Body:
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.

empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31

Body:
If I understand you correctly, you can do that both with an inner query

select  min(date_from)
from    yourTable
where   sg = (
            select  sg
            from    yourTable
            where   date_to = '1900-01-01'
        )

or with a join

select  min(t1.date_from)
from    yourTable t1
join    yourTable t2
on      t1.sg = t2.sg
where   t2.date_to = '1900-01-01'

Edit

To get the minimum date for each position, the easiest way is tweaking the second query into this:

select  t1.position, min(t1.date_from)
from    yourTable t1
join    yourTable t2
on      t1.sg = t2.sg and
        t1.position = t2.position
where   t2.date_to = '1900-01-01'
group by t1.position

Edit 2

Since the requirement is to get the minimum date for each value in the the empno column, what you need to do is this

select  t1.empno, min(t1.date_from)
from    yourTable t1
join    yourTable t2
on      t1.sg = t2.sg and
        t1.empno = t2.empno
where   t2.date_to = '1900-01-01'
group by t1.empno

You can see it at work here