问:
Flexbox layout with two equal height children, one containing nested flexbox with scrolling content
I have an  with a panel to its right containing a controls header and a long list of items. So I have a nested flexbox situation:

```<code>.container (flex)
 -> .child img
 -> .child controls panel (flex)
  -> .controls
  -> .content-wrapper scrolling list
</code>```

At a very basic level, the two side by side panels are easy, being a simple flex with align-items: stretch .. https://codepen.io/neekfenwick/pen/MOxYxz

At that basic level it's a duplicate question to How do I keep two divs that are side by side the same height?.

Once the panel on the right becomes more complex with a vertically scrolling list, I cannot see how to make the height of its parent, the second .child, match the height of the first .child.  https://codepen.io/neekfenwick/pen/XzGJGw

```<code>+-------------+---------------+
|             |  Controls     |
| Left child  |               |
|             +---------------+
|             |              A|
|             | Vertically   |+
|             | scrolling    ||
|             | items        ||
|             |              |+
|             |              V|
+-------------+---------------+
</code>```

I have read Flexbox item with scrollable content but that solves a horizontal scrolling problem, not a vertical layout like this.  Also Nested flexbox with scrolling area deals with vertically stacked nested flexboxes, I think this combination of row and column directions confuses my situation.

As a code snippet:

.container {
  display: flex;
  align-items: stretch;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  flex: 1 1 auto;
  width: 400px;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">
    <p>In real life I am an inline img.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I want my sibling to equal my height.</p>
  </div>
  <div class="child controls-panel">
    <div class="controls">
      <p>Small controls area. Panel below should scroll vertically.</p>
    </div>
    <div class="content-wrapper">
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
    </div>
  </div>
</div></code>```

I do not want to fix the height of any elements here.  As it happens, I know the height of the img, and so I could use CSS to force the height of the elements on the right, but I wondered if there is a 'true' flexbox way of solving this problem.

答:
In general, for overflow: scroll (or auto and hidden) to work, a height constraint is needed in one way or the other, or else element's normally grow as much as needed to fit their content.

There is mainly 3 ways, where either an actual height is set, as in this first sample, where I added it to the container.

Stack snippet 1

.container {
  display: flex;
  height: 100vh;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  flex: 1 1 auto;
  width: 400px;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">
    <p>In real life I am an inline img.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I want my sibling to equal my height.</p>
  </div>
  <div class="child controls-panel">
    <div class="controls">
      <p>Small controls area. Panel below should scroll vertically.</p>
    </div>
    <div class="content-wrapper">
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
    </div>
  </div>
</div></code>```

Or to use absolute positioning to create that height constraint, which an absolute element does.

It is simply accomplished with an extra wrapper, content-scroll, and will keep the rest of the structure fully dynamic.

Stack snippet 2

.container {
  display: flex;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  position: relative;
  flex: 1 1 auto;
  width: 400px;
}
.content-scroll {
  position: absolute;
  top: 0; left: 0;
  right: 0; bottom: 0;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">
    <p>In real life I am an inline img.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I want my sibling to equal my height.</p>
  </div>
  <div class="child controls-panel">
    <div class="controls">
      <p>Small controls area. Panel below should scroll vertically.</p>
    </div>
    <div class="content-wrapper">
      <div class="content-scroll">
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
      </div>
    </div>
  </div>
</div></code>```

Use Flexbox alone, thought it might not work fully cross browsers, especially with older versions, that still support it but is a lot buggier.

The simple fix in your original code is to change the flex: 1 1 auto; in .content-wrapper to flex: 1 1 0px; (0px were needed for my IE version, for Chrome/Firefox/Edge one can use 0)

Stack snippet 3

.container {
  display: flex;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  flex: 1 1 0px;
  width: 400px;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">
    <p>In real life I am an inline img.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I want my sibling to equal my height.</p>
  </div>
  <div class="child controls-panel">
    <div class="controls">
      <p>Small controls area. Panel below should scroll vertically.</p>
    </div>
    <div class="content-wrapper">
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
    </div>
  </div>
</div></code>```

Snippet 2 and 3 also answers your question

...with a vertically scrolling list, I cannot see how to make the
  height of its parent, the second .child, match the height of the
  first .child.

Note, if the top element in the right column can grow bigger than the left column, a minimum height will be needed on the bottom element, to prevent it from collapse into 0, e.g.

```<code>.content-wrapper {
  ...
  min-height: 200px;           /*  e.g. like this  */
}
</code>```

Body:
I have an  with a panel to its right containing a controls header and a long list of items. So I have a nested flexbox situation:

.container (flex)
 -> .child img
 -> .child controls panel (flex)
  -> .controls
  -> .content-wrapper scrolling list

At a very basic level, the two side by side panels are easy, being a simple flex with align-items: stretch .. https://codepen.io/neekfenwick/pen/MOxYxz

At that basic level it's a duplicate question to How do I keep two divs that are side by side the same height?.

Once the panel on the right becomes more complex with a vertically scrolling list, I cannot see how to make the height of its parent, the second .child, match the height of the first .child.  https://codepen.io/neekfenwick/pen/XzGJGw

+-------------+---------------+
|             |  Controls     |
| Left child  |               |
|             +---------------+
|             |              A|
|             | Vertically   |+
|             | scrolling    ||
|             | items        ||
|             |              |+
|             |              V|
+-------------+---------------+

I have read Flexbox item with scrollable content but that solves a horizontal scrolling problem, not a vertical layout like this.  Also Nested flexbox with scrolling area deals with vertically stacked nested flexboxes, I think this combination of row and column directions confuses my situation.

As a code snippet:

.container {
  display: flex;
  align-items: stretch;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  flex: 1 1 auto;
  width: 400px;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}

In real life I am an inline img.

I am some content whoop de doo.

I am some content whoop de doo.

I am some content whoop de doo.

I want my sibling to equal my height.

Small controls area. Panel below should scroll vertically.

I do not want to fix the height of any elements here.  As it happens, I know the height of the img, and so I could use CSS to force the height of the elements on the right, but I wondered if there is a 'true' flexbox way of solving this problem.

Body:
In general, for overflow: scroll (or auto and hidden) to work, a height constraint is needed in one way or the other, or else element's normally grow as much as needed to fit their content.

There is mainly 3 ways, where either an actual height is set, as in this first sample, where I added it to the container.

Stack snippet 1

.container {
  display: flex;
  height: 100vh;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  flex: 1 1 auto;
  width: 400px;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}

<div class="container">
  <div class="child">
    <p>In real life I am an inline img.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I want my sibling to equal my height.</p>
  </div>
  <div class="child controls-panel">
    <div class="controls">
      <p>Small controls area. Panel below should scroll vertically.</p>
    </div>
    <div class="content-wrapper">
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
      <div class="content-item"></div>
    </div>
  </div>
</div>

Or to use absolute positioning to create that height constraint, which an absolute element does.

It is simply accomplished with an extra wrapper, content-scroll, and will keep the rest of the structure fully dynamic.

Stack snippet 2

.container {
  display: flex;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  position: relative;
  flex: 1 1 auto;
  width: 400px;
}
.content-scroll {
  position: absolute;
  top: 0; left: 0;
  right: 0; bottom: 0;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}

<div class="container">
  <div class="child">
    <p>In real life I am an inline img.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I want my sibling to equal my height.</p>
  </div>
  <div class="child controls-panel">
    <div class="controls">
      <p>Small controls area. Panel below should scroll vertically.</p>
    </div>
    <div class="content-wrapper">
      <div class="content-scroll">
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
      </div>
    </div>
  </div>
</div>

Use Flexbox alone, thought it might not work fully cross browsers, especially with older versions, that still support it but is a lot buggier.

The simple fix in your original code is to change the flex: 1 1 auto; in .content-wrapper to flex: 1 1 0px; (0px were needed for my IE version, for Chrome/Firefox/Edge one can use 0)

Stack snippet 3

.container {
  display: flex;
}

.child {
  border: 1px solid grey;
  background-color: lightgrey;
  flex: 1 1 auto;
}

.controls-panel {
  display: flex;
  flex-direction: column;
}

.controls {
  flex: 0 0 auto;
}

.content-wrapper {
  flex: 1 1 0px;
  width: 400px;
  overflow-y: auto;
}
.content-item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: red;
}

<div class="container">
  <div class="child">
    <p>In real life I am an inline img.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I am some content whoop de doo.</p>
    <p>I want my sibling to equal my height.</p>
  </div>
  <div class="child controls-panel">
    <div class="controls">
      <p>Small controls area. Panel below should scroll vertically.</p>
    </div>
    <div class="content-wrapper">
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
    </div>
  </div>
</div>

Snippet 2 and 3 also answers your question

...with a vertically scrolling list, I cannot see how to make the
  height of its parent, the second .child, match the height of the
  first .child.

Note, if the top element in the right column can grow bigger than the left column, a minimum height will be needed on the bottom element, to prevent it from collapse into 0, e.g.

.content-wrapper {
  ...
  min-height: 200px;           /*  e.g. like this  */
}


来源: stackexchange

问:
Tizen wearable: Can you get sensors data in ambient mode?
Sorry. I'm new to tizen. Can't find answer at official tizen forum.
Wan't to develop specific watchface for tizen watches.

Can you get sensors data in ambient mode?

答:
Yes, You can Get/fetch the Sensor Data while in ambient mode. The Issue is in Showing sensor data in ambient mode.

If you are Using GearWatchDesigner:

You are only able to use the features that are being offered by the designer tool.

# You may add 'Text' Component like 'step %','heart rate', on your watchface. It would be shown on both Ambient mode & Active mode.

# You may add 'Complication' Component like 'heart rate','steps' on your watchface. But you can't show the 'Complication' component in ambient/always-on mode. It's only available in Active mode.

If you are Using Tizen-Studio IDE :

You are free to develop your watchface in ambient mode using Tizen API.
Use Tizen sensor API to get Sensor data, and add UI components to present them. But then, It's your responsibility to meet the 'less than 15% of the pixels' limit. Guide

Check out Samsung developers:Gear for details

ContentLicense: CC BY-SA 3.0


问:
https PHP/MySql webservice with ios instagram login
I'm trying to wrap my mind around something. I want to create a web service that accesses a database from an ios/ android app. Now I want the user to be able to log into the app through the Instagram API.

I'm a bit confused as in how they tie together. Obviously step one is to login with Instagram. What do I do then? I would like to save this user information I receive (let's say at least the username/ID) to the database with some other info that don't come from Instagram, like the location. All that in a secure way. can i use the instagram token for this? I'm a bit stuck on this process...

答:
To do what you're looking for, the easiest way is to do a Rest WebService.

Using this WebService, both your iOS and Android apps will be able to connect and send/get data.

Your WebService should be responsible for managing all the data, saving or getting info from a Database. And can be also be responsible for user authentication.

To talk to your WebService, your app can use JSON. So you should learn how to send and parse JSON.

Good Luck!

Useful links:

Instagram's API

Instagram Integration in Android Application Tutorial

UPDATE

To correlate the instagram user with your database you can use the provided user id:

```<code>{
    "access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
    "user": {
        "id": "1574083",
        "username": "snoopdogg",
        "full_name": "Snoop Dogg",
        "profile_picture": "..."
    }
}
</code>```

See: Instagram Authentication

Body:
To do what you're looking for, the easiest way is to do a Rest WebService.

Using this WebService, both your iOS and Android apps will be able to connect and send/get data.

Your WebService should be responsible for managing all the data, saving or getting info from a Database. And can be also be responsible for user authentication.

To talk to your WebService, your app can use JSON. So you should learn how to send and parse JSON.

Good Luck!

Useful links:

Instagram's API

Instagram Integration in Android Application Tutorial

UPDATE

To correlate the instagram user with your database you can use the provided user id:

{
    "access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
    "user": {
        "id": "1574083",
        "username": "snoopdogg",
        "full_name": "Snoop Dogg",
        "profile_picture": "..."
    }
}

See: Instagram Authentication


问:
Find Whole Months from date range java
I have two dates:

```<code>Start Date: 2017-01-15
End Date: 2017-05-27
</code>```

Now I want to find the whole month between these two dates. So the result should be:

```<code>Feb-2017
Mar-2017
Apr-2017
</code>```

January is not included in the result because start date starts from the middle of the month and May is not included because end date does not cover whole May month.

How can I achieve this with Java?

I have tried doing something like:

```<code>String date1 = "2015-01-15";
String date2 = "2015-05-27";

DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();

try {
    startCalendar.setTime(formater.parse(date1));
    endCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
    e.printStackTrace();
}

System.out.println("startDate:" + startCalendar.getTime());
System.out.println("endCalendar:" + endCalendar.getTime());

while (startCalendar.before(endCalendar)) {
    // add one month to date per loop
    String date = formater1.format(startCalendar.getTime()).toUpperCase();
    System.out.println(date);
    startCalendar.add(Calendar.MONTH, 1);
}
</code>```

But I don't know how to exclude Jan and May from the result. Currently, I am getting this result:

```<code>JAN-2015
FEB-2015
MAR-2015
APR-2015
MAY-2015
</code>```

答:
I was able to solve this by the following code:</p>

```<code>public static void main(String... strings) throws ParseException {
    String date1 = "2017-01-01";
    String date2 = "2017-05-27";

    DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
    DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

    Calendar startCalendar = Calendar.getInstance();
    Calendar endCalendar = Calendar.getInstance();

    try {
        startCalendar.setTime(formater.parse(date1));
        endCalendar.setTime(formater.parse(date2));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    while (startCalendar.before(endCalendar)) {
        if (isFirstDayofMonth(startCalendar) && !(startCalendar.get(Calendar.MONTH) == endCalendar.get(Calendar.MONTH) && startCalendar.get(Calendar.YEAR) == endCalendar.get(Calendar.YEAR))) {
            String date = formater1.format(startCalendar.getTime()).toUpperCase();
            System.out.println(date);
        }
        startCalendar.set(Calendar.DATE, 1);
        startCalendar.add(Calendar.MONTH, 1);
    }
    if (isLastDayofMonth(endCalendar)) {
        String date = formater1.format(endCalendar.getTime()).toUpperCase();
        System.out.println(date);
    }

}

private static boolean isFirstDayofMonth(Calendar calendar) {
    if (calendar == null) {
        return false;
    }

    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
    return (dayOfMonth == 1);
}

private static boolean isLastDayofMonth(Calendar calendar) {
    if (calendar == null) {
        return false;
    }

    boolean isLastDay = calendar.get(Calendar.DATE) == calendar.getActualMaximum(Calendar.DATE);
    return isLastDay;
}
</code>```

Title: Find Whole Months from date range java

Body:
I have two dates:

Start Date: 2017-01-15
End Date: 2017-05-27

Now I want to find the whole month between these two dates. So the result should be:

Feb-2017
Mar-2017
Apr-2017

January is not included in the result because start date starts from the middle of the month and May is not included because end date does not cover whole May month.

How can I achieve this with Java?

I have tried doing something like:

String date1 = "2015-01-15";
String date2 = "2015-05-27";

DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();

try {
    startCalendar.setTime(formater.parse(date1));
    endCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
    e.printStackTrace();
}

System.out.println("startDate:" + startCalendar.getTime());
System.out.println("endCalendar:" + endCalendar.getTime());

while (startCalendar.before(endCalendar)) {
    // add one month to date per loop
    String date = formater1.format(startCalendar.getTime()).toUpperCase();
    System.out.println(date);
    startCalendar.add(Calendar.MONTH, 1);
}

But I don't know how to exclude Jan and May from the result. Currently, I am getting this result:

JAN-2015
FEB-2015
MAR-2015
APR-2015
MAY-2015

Body:
I was able to solve this by the following code:

public static void main(String... strings) throws ParseException {
    String date1 = "2017-01-01";
    String date2 = "2017-05-27";

    DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
    DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

    Calendar startCalendar = Calendar.getInstance();
    Calendar endCalendar = Calendar.getInstance();

    try {
        startCalendar.setTime(formater.parse(date1));
        endCalendar.setTime(formater.parse(date2));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    while (startCalendar.before(endCalendar)) {
        if (isFirstDayofMonth(startCalendar) && !(startCalendar.get(Calendar.MONTH) == endCalendar.get(Calendar.MONTH) && startCalendar.get(Calendar.YEAR) == endCalendar.get(Calendar.YEAR))) {
            String date = formater1.format(startCalendar.getTime()).toUpperCase();
            System.out.println(date);
        }
        startCalendar.set(Calendar.DATE, 1);
        startCalendar.add(Calendar.MONTH, 1);
    }
    if (isLastDayofMonth(endCalendar)) {
        String date = formater1.format(endCalendar.getTime()).toUpperCase();
        System.out.println(date);
    }

}

private static boolean isFirstDayofMonth(Calendar calendar) {
    if (calendar == null) {
        return false;
    }

    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
    return (dayOfMonth == 1);
}

private static boolean isLastDayofMonth(Calendar calendar) {
    if (calendar == null) {
        return false;
    }

    boolean isLastDay = calendar.get(Calendar.DATE) == calendar.getActualMaximum(Calendar.DATE);
    return isLastDay;
}


问:
Why is Android Geocoder throwing a "Service not Available" exception?
The app uses the Geocoder object. It works fine on my stock Froyo Nexus One. But then I run the exact same app on a different device (an Advent Vega 10" tablet also running Froyo) and I get this exception: Service not Available. The method I'm using is getFromLocationName(), I'm building against the Android 1.6 Google API.

I'm aware of an issue where this exception is thrown on the emulator, but I suspect this is different. Why would it be thrown on one device running Froyo but not another?

The app is a location app, and as the tablet has no GPS or mobile network, in a scenario where the Wi-Fi connection doesn't provide a location, the user must manually specify it, so not being able to use the Geocoder object is bad news.

I could add a way for the user to select the location on a map, but it's not ideal. Possibly I could use the Google Maps API directly, but I'm keen to understand the nature of the issue first as would be nice to have an easier solution.

Hopefully in a future release Android will include an OS-level "default location" for non-Geocoder devices, so location-aware apps work out of the box on devices like Google TV.

答:
I asked Google's Reto Meier to confirm my theory was correct and he said "Correct. The Geocoder is part of the Google API add-on that isn't part of the AOSP."

So any device that doesn't come with the Play Store, GMail apps etc… will also be missing the Geocoder back-end.


问:
"Error: Could not find or load main class" error when using "storm jar"
I checked that Java Version, CLASSPATH, Java Build Path And Properties > Run/Debug Settings

But I can't resolve this error Could not find or load main class
What information do I need to solve this problem?

This is error and my computer information

```<code>#storm jar tims-0.0.1-SNAPSHOT.jar com.clunix.tims.TIMSTopology TIMSTopology
Running: /usr/local/jdk1.8.0_151/bin/java -client -Ddaemon.name= -Dstorm.options= -Dstorm.home=/storm/storm -Dstorm.log.dir=/storm/storm/logs -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dstorm.conf.file= -cp /storm/storm/lib/storm-core-1.1.1.jar:/storm/storm/lib/kryo-3.0.3.jar:/storm/storm/lib/reflectasm-1.10.1.jar:/storm/storm/lib/asm-5.0.3.jar:/storm/storm/lib/minlog-1.3.0.jar:/storm/storm/lib/objenesis-2.1.jar:/storm/storm/lib/clojure-1.7.0.jar:/storm/storm/lib/ring-cors-0.1.5.jar:/storm/storm/lib/disruptor-3.3.2.jar:/storm/storm/lib/log4j-api-2.8.2.jar:/storm/storm/lib/log4j-core-2.8.2.jar:/storm/storm/lib/log4j-slf4j-impl-2.8.2.jar:/storm/storm/lib/slf4j-api-1.7.21.jar:/storm/storm/lib/log4j-over-slf4j-1.6.6.jar:/storm/storm/lib/servlet-api-2.5.jar:/storm/storm/lib/storm-rename-hack-1.1.1.jar:tims-0.0.1-SNAPSHOT.jar:/storm/storm/conf:/storm/storm/bin -Dstorm.jar=tims-0.0.1-SNAPSHOT.jar -Dstorm.dependency.jars= -Dstorm.dependency.artifacts={} com.clunix.tims.TIMSTopology TIMSTopology
Error: Could not find or load main class com.clunix.tims.TIMSTopology

# java -version
java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

#echo $CLASSPATH
/usr/local/jdk1.8.0_151/lib/tools.jar:.
</code>```

I think that I Should modify it... It's right?
pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.clunix</groupId>
        <artifactId>tims</artifactId>
        <version>0.0.1-SNAPSHOT</version>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.storm</groupId>
                <artifactId>storm-core</artifactId>
                <version>1.1.0</version>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.2.1</version>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <mainClass>com.clunix.tims.TIMSTopology</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                    <executions>
                        <execution>
                            <id>make-assembly</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </project>
</code>```

Thanks in advance for your response.

答:
I think you can add this plugin inside you pom.xml and retry it.</p>

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>you spring boot version</version>
    <configuration>
      <mainClass>your main class</mainClass>
    </configuration>
</plugin>
</code>```

Body:
I checked that Java Version, CLASSPATH, Java Build Path And Properties > Run/Debug Settings

But I can't resolve this error Could not find or load main class
What information do I need to solve this problem?

This is error and my computer information

#storm jar tims-0.0.1-SNAPSHOT.jar com.clunix.tims.TIMSTopology TIMSTopology
Running: /usr/local/jdk1.8.0_151/bin/java -client -Ddaemon.name= -Dstorm.options= -Dstorm.home=/storm/storm -Dstorm.log.dir=/storm/storm/logs -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dstorm.conf.file= -cp /storm/storm/lib/storm-core-1.1.1.jar:/storm/storm/lib/kryo-3.0.3.jar:/storm/storm/lib/reflectasm-1.10.1.jar:/storm/storm/lib/asm-5.0.3.jar:/storm/storm/lib/minlog-1.3.0.jar:/storm/storm/lib/objenesis-2.1.jar:/storm/storm/lib/clojure-1.7.0.jar:/storm/storm/lib/ring-cors-0.1.5.jar:/storm/storm/lib/disruptor-3.3.2.jar:/storm/storm/lib/log4j-api-2.8.2.jar:/storm/storm/lib/log4j-core-2.8.2.jar:/storm/storm/lib/log4j-slf4j-impl-2.8.2.jar:/storm/storm/lib/slf4j-api-1.7.21.jar:/storm/storm/lib/log4j-over-slf4j-1.6.6.jar:/storm/storm/lib/servlet-api-2.5.jar:/storm/storm/lib/storm-rename-hack-1.1.1.jar:tims-0.0.1-SNAPSHOT.jar:/storm/storm/conf:/storm/storm/bin -Dstorm.jar=tims-0.0.1-SNAPSHOT.jar -Dstorm.dependency.jars= -Dstorm.dependency.artifacts={} com.clunix.tims.TIMSTopology TIMSTopology
Error: Could not find or load main class com.clunix.tims.TIMSTopology

# java -version
java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

#echo $CLASSPATH
/usr/local/jdk1.8.0_151/lib/tools.jar:.

I think that I Should modify it... It's right?
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.clunix</groupId>
        <artifactId>tims</artifactId>
        <version>0.0.1-SNAPSHOT</version>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.storm</groupId>
                <artifactId>storm-core</artifactId>
                <version>1.1.0</version>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.2.1</version>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <mainClass>com.clunix.tims.TIMSTopology</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                    <executions>
                        <execution>
                            <id>make-assembly</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </project>

Thanks in advance for your response.

Body:
I think you can add this plugin inside you pom.xml and retry it.

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>you spring boot version</version>
    <configuration>
      <mainClass>your main class</mainClass>
    </configuration>
</plugin>


问:
Check if an array contains duplicate values
I wanted to write a javascript function which checks if array contains duplicate values or not.

I have written the following code but its giving answer as "true" always.

Can anybody please tell me what am I missing.

```<code>function checkIfArrayIsUnique(myArray)
    {
        for (var i = 0; i < myArray.length; i++)
        {
            for (var j = 0; j < myArray.length; j++)
            {
                if (i != j)
                {
                    if (myArray[i] == myArray[j])
                    {
                        return true; // means there are duplicate values
                    }
                }
            }
        }
        return false; // means there are no duplicate values.
    }
</code>```

答:
Returns the duplicate item in array and creates a new array with no duplicates:</p>

```<code> var a = ["hello", "hi", "hi", "juice", "juice", "test"];
    var b = ["ding", "dong", "hi", "juice", "juice", "test"];
    var c = a.concat(b);
    var dupClearArr = [];

    function dupArray(arr) {

        for (i = 0; i < arr.length; i++) {
            if (arr.indexOf(arr[i]) != i && arr.indexOf(arr[i]) != -1) {
                console.log('duplicate item ' + arr[i]);
            } else {
                dupClearArr.push(arr[i])
            }

        }
        console.log('actual array \n' + arr + ' \nno duplicate items array \n' + dupClearArr)
    }

    dupArray(c);
</code>```

Body:
I wanted to write a javascript function which checks if array contains duplicate values or not.

I have written the following code but its giving answer as "true" always.

Can anybody please tell me what am I missing.

function checkIfArrayIsUnique(myArray)
    {
        for (var i = 0; i < myArray.length; i++)
        {
            for (var j = 0; j < myArray.length; j++)
            {
                if (i != j)
                {
                    if (myArray[i] == myArray[j])
                    {
                        return true; // means there are duplicate values
                    }
                }
            }
        }
        return false; // means there are no duplicate values.
    }

Body:
Returns the duplicate item in array and creates a new array with no duplicates:

 var a = ["hello", "hi", "hi", "juice", "juice", "test"];
    var b = ["ding", "dong", "hi", "juice", "juice", "test"];
    var c = a.concat(b);
    var dupClearArr = [];

    function dupArray(arr) {

        for (i = 0; i < arr.length; i++) {
            if (arr.indexOf(arr[i]) != i && arr.indexOf(arr[i]) != -1) {
                console.log('duplicate item ' + arr[i]);
            } else {
                dupClearArr.push(arr[i])
            }

        }
        console.log('actual array \n' + arr + ' \nno duplicate items array \n' + dupClearArr)
    }

    dupArray(c);


问:
Substring assignment
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

```<code><head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

<script type="text/javascript">

var text= test.length;

for (i=0;i< test.length;i++)

function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}

    </script>

</head>

<body>
<h1>Assignment 14</h1>
    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

</body>
</code>```

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.

答:
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:

```<code>const substrings = string =>
  Array.from(string).map((_, i) => string.slice(0, i + 1))
</code>```

And here's a working codepen

Title: Substring assignment

Body:
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

Assignment 14

    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.

Body:
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:

const substrings = string =>
  Array.from(string).map((_, i) => string.slice(0, i + 1))

And here's a working codepen


问:
How to import external css file in nextjs app
I am working on react based nextjs app. Some npm packages are using external css import.
I am getting error like

```<code>Module parse failed, you may need an appropriate loader to handle this file type.
</code>```

How can I support css import from external packages in my nextjs app. I have checked somewhere by making change in next.config.js, it works. But I am unable to find the proper one.It would be great if someone can help me around this.

答:
import your external css file into the component. For example, react-select requires you to add their stylesheet in order to make its styles work. You can import their stylesheets using

```<code>import rsStyles from 'react-select/dist/react-select.css'
</code>```

Inject style in your component using dangerouslySetInnerHTML at render method

```<code>render() {
  return (
    <div>
      <style dangerouslySetInnerHTML={{ __html: rsStyles }} />
      // rest of your component code
      // where you can use the injected styles
    </div>
  );
}
</code>```

Body:
I am working on react based nextjs app. Some npm packages are using external css import.
I am getting error like

Module parse failed, you may need an appropriate loader to handle this file type.

How can I support css import from external packages in my nextjs app. I have checked somewhere by making change in next.config.js, it works. But I am unable to find the proper one.It would be great if someone can help me around this.

Body:
import your external css file into the component. For example, react-select requires you to add their stylesheet in order to make its styles work. You can import their stylesheets using

import rsStyles from 'react-select/dist/react-select.css'

Inject style in your component using dangerouslySetInnerHTML at render method

render() {
  return (
    <div>
      <style dangerouslySetInnerHTML={{ __html: rsStyles }} />
      // rest of your component code
      // where you can use the injected styles
    </div>
  );
}


问:
getting the output of a grep command in a loop
I have a shell script that includes this search:

```<code>find . -type f -exec grep -iPho "barh(li|mar|ag)" {}  \;
</code>```

I want to capture each string the grep command finds and send it a function I will create named "parser"

```<code>parser(){
# do stuff with each single grep result found
}
</code>```

how can that be done?
is this right?

```<code>find . -type f -exec grep -iPho "barh(li|mar|ag)" {parser $1}  \;
</code>```

I do not want to output the entire find command result to the function

答:
i suggest you to use sed ,this is more powerful tool to do text processing.
for example i want to add string "myparse" after the line that end as "ha",i can do this like

```<code># echo "haha" > text1
# echo "hehe" > text2
# echo "heha" > text3
# find . -type f -exec sed '/ha$/s/ha$/ha myparse/' {} \;
haha myparse
heha myparse
hehe
</code>```

if you really want to replace the file ,not just print to stdout,you can do this like

```<code># find . -type f -exec sed -i '/ha$/s/ha$/ha myparse/' {} \;
</code>```

Body:
I have a shell script that includes this search:

find . -type f -exec grep -iPho "barh(li|mar|ag)" {}  \;

I want to capture each string the grep command finds and send it a function I will create named "parser"

parser(){
# do stuff with each single grep result found
}

how can that be done?
is this right?

find . -type f -exec grep -iPho "barh(li|mar|ag)" {parser $1}  \;

I do not want to output the entire find command result to the function

Body:
i suggest you to use sed ,this is more powerful tool to do text processing.
for example i want to add string "myparse" after the line that end as "ha",i can do this like

# echo "haha" > text1
# echo "hehe" > text2
# echo "heha" > text3
# find . -type f -exec sed '/ha$/s/ha$/ha myparse/' {} \;
haha myparse
heha myparse
hehe

if you really want to replace the file ,not just print to stdout,you can do this like

# find . -type f -exec sed -i '/ha$/s/ha$/ha myparse/' {} \;


问:
How to delete a row from a table in SQL Server using PowerShell script?
```<code>$uncServer = "\\10.243.174.102\e$"
$uncFullPath = "$uncServer\New folder\Demo.txt"
$username = "XYZ"
$password = "xyz"

net use $uncServer $password /USER:$username

$SQLServer = "AP-PUN-SRSTEP29\MSSQLSERVER12" #use Server\Instance for named SQL instances!
$SQLDBName = "SystemDB"
$SqlQuery = "Delete * from V_Solution WHERE Notes ='9.4.4'";

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
#$SqlConnection.open()

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
</code>```

I have SQL Server 2012 installed on a remote server and I want to delete a row from a particular table in a specific database, from a local machine using a PowerShell script. Is is possible to do that?

答:
Change your code like this :</p>

```<code>$uncServer = "\\10.243.174.102\e$"
$uncFullPath = "$uncServer\New folder\Demo.txt"
$username = "XYZ"
$password = "xyz"

net use $uncServer $password /USER:$username

$SQLServer = "AP-PUN-SRSTEP29\MSSQLSERVER12" #use Server\Instance for named SQL instances!
$SQLDBName = "SystemDB"
$SqlQuery = "Delete from V_Solution WHERE Notes ='9.4.4'";

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlConnection.open()

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

$SqlCmd.ExecuteNonQuery
$SqlConnection.Close()
</code>```

Body:
$uncServer = "\\10.243.174.102\e$"
$uncFullPath = "$uncServer\New folder\Demo.txt"
$username = "XYZ"
$password = "xyz"

net use $uncServer $password /USER:$username

$SQLServer = "AP-PUN-SRSTEP29\MSSQLSERVER12" #use Server\Instance for named SQL instances!
$SQLDBName = "SystemDB"
$SqlQuery = "Delete * from V_Solution WHERE Notes ='9.4.4'";

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
#$SqlConnection.open()

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd

I have SQL Server 2012 installed on a remote server and I want to delete a row from a particular table in a specific database, from a local machine using a PowerShell script. Is is possible to do that?

Body:
Change your code like this :

$uncServer = "\\10.243.174.102\e$"
$uncFullPath = "$uncServer\New folder\Demo.txt"
$username = "XYZ"
$password = "xyz"

net use $uncServer $password /USER:$username

$SQLServer = "AP-PUN-SRSTEP29\MSSQLSERVER12" #use Server\Instance for named SQL instances!
$SQLDBName = "SystemDB"
$SqlQuery = "Delete from V_Solution WHERE Notes ='9.4.4'";

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlConnection.open()

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

$SqlCmd.ExecuteNonQuery
$SqlConnection.Close()


问:
Creating module on prestashop
i need to create a module on prestashop on product page , im new in prestashop idk how to do that .
This module should be on bottom of page ,it contains product technical description
Can someone tell me how to do that
Ps : i know nothing about prestashop Hooks ....
Thanks in advance!</p>

答:
There is one hook that may fit you.

displayProductFooter

First you have to add the hook registration in your module install function

```<code>public function install()
{
   ...
   $this->registerHook('displayProductFooter');
}
</code>```

Then create a function to display the content in the hook

Save the content you want to display and use the return to send a string with all the HTML you want to print in the product footer.

In the params you will also find some useful variables like the product ID.

```<code>public function hookDisplayProductFooter($params)
{
    // Your content here
    return $output;
}
</code>```

The same procedure should work with any other hook (as long as it's a display hook)

Title: Creating module on prestashop

Body:
There is one hook that may fit you.

displayProductFooter

First you have to add the hook registration in your module install function

public function install()
{
   ...
   $this->registerHook('displayProductFooter');
}

Then create a function to display the content in the hook

Save the content you want to display and use the return to send a string with all the HTML you want to print in the product footer.

In the params you will also find some useful variables like the product ID.

public function hookDisplayProductFooter($params)
{
    // Your content here
    return $output;
}

The same procedure should work with any other hook (as long as it's a display hook)


问:
Selenium IE driver returns tab count as 1 while using getWindowHandles method on multiple tabs of same window
I'm automating a portal using selenium web driver + Internet Explorer, was able to open a multiple new tabs on existing window but was not able to pass URL to newly opened tab, IE isn't recognizing new tabs and getWindowHandles() returns count as 1, the same code works fine with Chrome.

Sample Code 1 :

```<code>String baseUrl = "www.facebook.com";
driver.get(baseUrl);
driver.findElement(By.xpath("//*[@id='userName']")).sendKeys("xyz");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("****");
driver.findElement(By.xpath("//*[@id='loginButton']")).click();

driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL +"t");
driver.getWindowHandles();
ArrayList<String> tabs =  new ArrayList<String>(driver.getWindowHandles());

driver.switchTo().window(tabs.get(1)); //switches to new tab
driver.get("www.google.com");
</code>```

Sample Code 2 :

```<code>String baseUrl = "www.facebook.com";
driver.get(baseUrl);
driver.findElement(By.xpath("//*[@id='userName']")).sendKeys("xyz");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("****");
driver.findElement(By.xpath("//*[@id='loginButton']")).click();

String parent = driver.getWindowHandle();
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL +"t");
Thread.sleep(3000);
for(String winHandle : driver.getWindowHandles()){
    if(!winHandle.equals(parent)){
        driver.switchTo().window(winHandle);
        driver.get("www.google.com");
    }
}
</code>```

Also tried several other ways changing IE configuration like changing protected modes/Overriding automatic cookie handling but nothing worked.

Is there a way to open new tab in IE via code and get the accurate tab count using any method in Selenium?

Configuration:

IE :11,
Selenium-java : 2.47/3.7
IEDriver : 3.3.0/2.53,
Windows 7

答:
I had a similar problem with IE8 and I solved using driver.switchTo().defaultContent() before call the driver.getWindowHandles(). Something like this:</p>

```<code>// Save the parent
parent = driver.getWindowHandle();
driver.switchTo().defaultContent();
for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
        if (!winHandle.equals(parent)) {
        // Do something
        }
}
driver.close();
driver.switchTo().window(parent);
</code>```

Body:
I'm automating a portal using selenium web driver + Internet Explorer, was able to open a multiple new tabs on existing window but was not able to pass URL to newly opened tab, IE isn't recognizing new tabs and getWindowHandles() returns count as 1, the same code works fine with Chrome.

Sample Code 1 :

String baseUrl = "www.facebook.com";
driver.get(baseUrl);
driver.findElement(By.xpath("//*[@id='userName']")).sendKeys("xyz");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("****");
driver.findElement(By.xpath("//*[@id='loginButton']")).click();

driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL +"t");
driver.getWindowHandles();
ArrayList<String> tabs =  new ArrayList<String>(driver.getWindowHandles());

driver.switchTo().window(tabs.get(1)); //switches to new tab
driver.get("www.google.com");

Sample Code 2 :

String baseUrl = "www.facebook.com";
driver.get(baseUrl);
driver.findElement(By.xpath("//*[@id='userName']")).sendKeys("xyz");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("****");
driver.findElement(By.xpath("//*[@id='loginButton']")).click();

String parent = driver.getWindowHandle();
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL +"t");
Thread.sleep(3000);
for(String winHandle : driver.getWindowHandles()){
    if(!winHandle.equals(parent)){
        driver.switchTo().window(winHandle);
        driver.get("www.google.com");
    }
}

Also tried several other ways changing IE configuration like changing protected modes/Overriding automatic cookie handling but nothing worked.

Is there a way to open new tab in IE via code and get the accurate tab count using any method in Selenium?

Configuration:

IE :11,
Selenium-java : 2.47/3.7
IEDriver : 3.3.0/2.53,
Windows 7

Body:
I had a similar problem with IE8 and I solved using driver.switchTo().defaultContent() before call the driver.getWindowHandles(). Something like this:

// Save the parent
parent = driver.getWindowHandle();
driver.switchTo().defaultContent();
for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
        if (!winHandle.equals(parent)) {
        // Do something
        }
}
driver.close();
driver.switchTo().window(parent);


问:
checkboxes in recyclerview get changed automatically by scrolling in android
```<code>ArrayList<HashMap<String, String>> hashMapArrayList;

public void onBindViewHolder(final EChallanRecyclerCardViewAdapter.ViewHolder holder, int position) {

 holder.cbSelectedchallans.setChecked(false);

        holder.cbSelectedchallans.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    String cvTotChallanPayAmount= holder.tvChallanPayAmount.getText().toString().replace("₹","");
                    int TotChallanPayAmount=Integer.parseInt(cvTotChallanPayAmount);
                    TotaltoPay=TotaltoPay+TotChallanPayAmount;
                    Bundle bundle=new Bundle();
                    bundle.putInt("TotaltoPay",TotaltoPay);
                    Intent intent = new Intent("Add_Send_TotaltoPay");
                    intent.putExtras(bundle);
                    LocalBroadcastManager.getInstance(cntx).sendBroadcast(intent);

                } else {
                    if(TotaltoPay!=0) {
                        String cvTotChallanPayAmount = holder.tvChallanPayAmount.getText().toString().replace("₹", "");
                        int TotChallanPayAmount = Integer.parseInt(cvTotChallanPayAmount);
                        TotaltoPay = TotaltoPay - TotChallanPayAmount;
                        Bundle bundle=new Bundle();
                        bundle.putInt("TotaltoPay",TotaltoPay);
                        Intent intent = new Intent("Remove_Send_TotaltoPay");
                        intent.putExtras(bundle);
                        LocalBroadcastManager.getInstance(cntx).sendBroadcast(intent);

                    }
                }
            }
        });
}
</code>```

答:
In Adapter class add dataObjectHolder.setIsRecyclable(false); in DataObjectHolder

Example code

```<code>@Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.content_my_leaves, parent, false);

    DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
    dataObjectHolder.setIsRecyclable(false); // this line you should add
    return dataObjectHolder;
}
</code>```

Body:
In Adapter class add dataObjectHolder.setIsRecyclable(false); in DataObjectHolder

Example code

@Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.content_my_leaves, parent, false);

    DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
    dataObjectHolder.setIsRecyclable(false); // this line you should add
    return dataObjectHolder;
}


问:
Django join multiple models using django ORM
I googled and read many articles but got confused in multiple table join.
My models looks like-

```<code>class ProductCategory(models.Model):
    category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    category_image = models.ImageField(upload_to='category', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.category_name)

class ProductSubCategory(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    sub_category_image = models.ImageField(upload_to='subcategory', null=True, blank=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.sub_category_name)

class Product(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category = models.ForeignKey(ProductSubCategory)
    product_name = models.CharField(max_length=200,blank=True, null=True)
    product_price = models.FloatField(default=0)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    # is_discountable = models.CharField(max_length=3, default='Yes', choices=option)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.product_name)

class ProductColor(models.Model):
    product = models.ForeignKey(Product)
    product_color = models.ForeignKey(Color, related_name='product_color_id', blank=True, null=True)
    product_size = models.ForeignKey(Size, related_name='product_size_id', blank=True, null=True)

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)
    product_image = models.ImageField(upload_to='images', null=True, blank=True)
</code>```

Now in views, I want to get the product filters according to category and sub-category having all the images and colors. Query is something like-

```<code>SELECT product.*, productcolor.*, productimage.* FROM product
LEFT JOIN productcolor ON productcolor.product_id = product.id
LEFT JOIN productcolor.product_id = product.id
LEFT JOIN productimage ON productimage.product_id = product.id
WHERE product.category_id=1 and product.sub_category_id=1
</code>```

答:
Accordingly to your SQL, this will do.

```<code>Product.objects.filter(category=<category>, sub_category=<sub_category>) \
    .prefetch_related('productcolor_set', 'productimages_set')
</code>```

This query will prefetch all (with .prefetch_related()) ProductColor and ProductImages related to Product that have your <category> and <sub_category>, they would be stored in productcolor_set and productimages_set respectively.

Also i would suggest to rename your ProductImages model to ProductImage because it represents only one product image.

Body:
I googled and read many articles but got confused in multiple table join.
My models looks like-

class ProductCategory(models.Model):
    category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    category_image = models.ImageField(upload_to='category', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.category_name)

class ProductSubCategory(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    sub_category_image = models.ImageField(upload_to='subcategory', null=True, blank=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.sub_category_name)

class Product(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category = models.ForeignKey(ProductSubCategory)
    product_name = models.CharField(max_length=200,blank=True, null=True)
    product_price = models.FloatField(default=0)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    # is_discountable = models.CharField(max_length=3, default='Yes', choices=option)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.product_name)

class ProductColor(models.Model):
    product = models.ForeignKey(Product)
    product_color = models.ForeignKey(Color, related_name='product_color_id', blank=True, null=True)
    product_size = models.ForeignKey(Size, related_name='product_size_id', blank=True, null=True)

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)
    product_image = models.ImageField(upload_to='images', null=True, blank=True)

Now in views, I want to get the product filters according to category and sub-category having all the images and colors. Query is something like-

SELECT product.*, productcolor.*, productimage.* FROM product
LEFT JOIN productcolor ON productcolor.product_id = product.id
LEFT JOIN productcolor.product_id = product.id
LEFT JOIN productimage ON productimage.product_id = product.id
WHERE product.category_id=1 and product.sub_category_id=1

Body:
Accordingly to your SQL, this will do.

Product.objects.filter(category=<category>, sub_category=<sub_category>) \
    .prefetch_related('productcolor_set', 'productimages_set')

This query will prefetch all (with .prefetch_related()) ProductColor and ProductImages related to Product that have your <category> and <sub_category>, they would be stored in productcolor_set and productimages_set respectively.

Also i would suggest to rename your ProductImages model to ProductImage because it represents only one product image.


问:
How to manage repetition in decorated ApiControllers?
I'm currently working on a project where every api controller needs to log activity. A rough example might be:

```<code>[Route(...)]
public IHttpActionResult Foo(...)
{
    using(var logger = ...)
    {
        // use the logger
        return _service.Bar(...);
    }
}
</code>```

In my view, this has at least three issues.

Coupling the logging cross-cutting concern with the request handling violating the Single Responsibility Principle.

Coupling the logger implementation to the controller with new violating Dependency Inversion Principle.

Repetition of the using in each endpoint in each controller violating DRY.

I think I can fix (1) by decorating the controller, (2) with basic DI, and (3), I believe, will work itself out as a result. However, I incur another repetition issue by decorating controllers which have endpoints with Route attributes. Decorating the controller shouldn't make me dependent on a specific implementation to handle the routes so I need them in each decoration (more are likely) or find a way to inherit or reuse them.

```<code>// I can fluently handle logging with a LoggingController
// but I still need the route attribute
[Route(...)]
public IHttpActionResult Foo(...)
{
    return LogActivity(...).Foo(...);
}

private IController LogActivity(...)
{
    // do logging
    return _controller;
}
</code>```

So far, I think I have two viable solutions:

Raise the level abstraction to an abstract class where I can inherit the attributes.

Provide a proxy decoration which simply delegates to whatever might be the outermost actual decoration.

(1) couples me to some base implementation and (2) couples me to a proxy/wrapper for each controller type. (2) seems like the better approach but it's questionable enough to wonder if there's some DI or AOP patterns that are meant to handle this.

```<code>// (2) with a decorator with no additional
// behavior or functionality delegates to
// the given implementation.
[Route(...)]
public IHttpActionResult Foo(...)
{
    return _controller.Foo(...);
}
</code>```

答:
You can use HTTP message handler for ASP.NET (a middleware for ASP.NET Core), which you can plug into request pipeline, transparently to the rest of the code. In this way you achieve the orthogonality of cross-cutting concerns handling, and avoid repeating yourself.

Example of HTTP message handler with ASP.NET 4.5+:

```<code>public class RequestLoggingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        // --> log begin of request
        // for example, you can include time measurement
        Stopwatch requestTime = Stopwatch.StartNew();

        try
        {
            var response = await base.SendAsync(request, cancellationToken);
            // --> log successful completion
            return response;
        }
        catch (Exception e)
        {
            // --> log failure
            throw;
        }
    }
}
</code>```

This is how you plug it in:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new RequestLoggingHandler());

        //... the rest of the setup...
    }
}
</code>```

In ASP.NET Core, there is also a new approach named Middleware. More details on it here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x#writing-middleware

Body:
I'm currently working on a project where every api controller needs to log activity. A rough example might be:

[Route(...)]
public IHttpActionResult Foo(...)
{
    using(var logger = ...)
    {
        // use the logger
        return _service.Bar(...);
    }
}

In my view, this has at least three issues.

Coupling the logging cross-cutting concern with the request handling violating the Single Responsibility Principle.

Coupling the logger implementation to the controller with new violating Dependency Inversion Principle.

Repetition of the using in each endpoint in each controller violating DRY.

I think I can fix (1) by decorating the controller, (2) with basic DI, and (3), I believe, will work itself out as a result. However, I incur another repetition issue by decorating controllers which have endpoints with Route attributes. Decorating the controller shouldn't make me dependent on a specific implementation to handle the routes so I need them in each decoration (more are likely) or find a way to inherit or reuse them.

// I can fluently handle logging with a LoggingController
// but I still need the route attribute
[Route(...)]
public IHttpActionResult Foo(...)
{
    return LogActivity(...).Foo(...);
}

private IController LogActivity(...)
{
    // do logging
    return _controller;
}

So far, I think I have two viable solutions:

Raise the level abstraction to an abstract class where I can inherit the attributes.

Provide a proxy decoration which simply delegates to whatever might be the outermost actual decoration.

(1) couples me to some base implementation and (2) couples me to a proxy/wrapper for each controller type. (2) seems like the better approach but it's questionable enough to wonder if there's some DI or AOP patterns that are meant to handle this.

// (2) with a decorator with no additional
// behavior or functionality delegates to
// the given implementation.
[Route(...)]
public IHttpActionResult Foo(...)
{
    return _controller.Foo(...);
}

Body:
You can use HTTP message handler for ASP.NET (a middleware for ASP.NET Core), which you can plug into request pipeline, transparently to the rest of the code. In this way you achieve the orthogonality of cross-cutting concerns handling, and avoid repeating yourself.

Example of HTTP message handler with ASP.NET 4.5+:

public class RequestLoggingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        // --> log begin of request
        // for example, you can include time measurement
        Stopwatch requestTime = Stopwatch.StartNew();

        try
        {
            var response = await base.SendAsync(request, cancellationToken);
            // --> log successful completion
            return response;
        }
        catch (Exception e)
        {
            // --> log failure
            throw;
        }
    }
}

This is how you plug it in:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new RequestLoggingHandler());

        //... the rest of the setup...
    }
}

In ASP.NET Core, there is also a new approach named Middleware. More details on it here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x#writing-middleware


问:
How to dynamically hide some options from a drop-down list using jQuery

I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">
            <div id="state1">
               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>
            </div>
            <div id="state2">
               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>
            </div>
        </select>
  <input name="submit" type="submit" value="Submit" />
</form></code>```

答:
you can't handle options with style
How to remove/hide select options from select-list

$(document).ready(function($) {

  var states = {
            "state1":["City1a","City1b", "City1c"]
            ,
            "state2":["City2a" , "City2b", "City2c"]
            };
  var state_option = (state) => states[state].map( (s,n)=> '<option value="'+n+'">'+s+'</option>' ).join();
  $("#city").html( state_option("state1") );
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").html( state_option(selected_state) );
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
        <select name="city" id="city">
        </select>
  <input name="submit" type="submit" value="Submit" />
</form></code>```

Body:
I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});

<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>

               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>

        </select>
  <input name="submit" type="submit" value="Submit" />
</form>

Body:
you can't handle options with style
How to remove/hide select options from select-list

$(document).ready(function($) {

  var states = {
            "state1":["City1a","City1b", "City1c"]
            ,
            "state2":["City2a" , "City2b", "City2c"]
            };
  var state_option = (state) => states[state].map( (s,n)=> '<option value="'+n+'">'+s+'</option>' ).join();
  $("#city").html( state_option("state1") );
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").html( state_option(selected_state) );
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
        <select name="city" id="city">
        </select>
  <input name="submit" type="submit" value="Submit" />
</form>


问:
How can i shift the light gallery thumbnails at the bottom to top?
I am using light gallery.

http://sachinchoolur.github.io/lightGallery/demos/

I want to the position of thumbnails to be at the top instead of bottom. Anyone encountered such an issue? Please help me.

答:
its easy with css (ofc you can do with js/jquery or even editing source file).

add this line of css in your stylesheet or the plugin style sheet in very last line:

.lg-outer .lg-thumb-outer {top:0 !important;bottom: auto !important;}


问:
How to get how many posts on a category and display it on wordpress theme
I'm developing a "real estate sale campaign", you can check it here. I've created a loop for each apartment/house on WordPress, I've made a page theme. On the page, you can check that I have a "neighborhood" section, where I want to display how many apartments I have in each "category", like Bela Vista, Boa Vista and others.

The problem is that I don't know how to do that. Here is the code I use to loop the apartments when the fields are filled:

```<code><?php
$newsArgs = array(
    'post_type' => 'property',
    'posts_per_page' => 200,
    "orderby" => 'meta_value_num',
    "meta_key" => 'numerooff',
    "order" => 'DESC',
    'tax_query' => array(
         array(
            'taxonomy' => 'property-status',
            'field'    => 'slug',
            'terms'    => 'oneoff',
         )
    )
);

$newsLoop = new WP_Query( $newsArgs );
while ( $newsLoop->have_posts() ) : $newsLoop->the_post();?>
</code>```

Maybe I should copy something of this code, to display the numbers? I don't know really. Here is where I create the slug I'm trying to use. On the snippet above, you can see where I want to place it:

```<code><!--  |-----------BELA VISTA-------------|   -->
<div class="col-sm-3 col-xs-12 portfolio-item">
    <a href="http://www.onecia.com.br/oneoff-belavista" target="_blank" class="">
    <div class="view efffect">
        <div class="portfolio-image">

            <img src="<?php bloginfo('template_directory');?>/acoes/oneoff/bairro/belavista.jpg" alt=""></div>
            <div class="mask text-center">
                <h3 style="font-family: 'Novecento Wide Light'; color: #fff;">Bela Vista</h3>
                <h4 style="color: #fff;">I WANT TO DISPLAY IT HERE</h4>
            </div>
        </div>
    </div></a>
</code>```

What should I do?

答: After $newsLoop = new WP_Query( $newsArgs ); use $count=$newsLoop->found_posts; echo $count;

Body:
I'm developing a "real estate sale campaign", you can check it here. I've created a loop for each apartment/house on WordPress, I've made a page theme. On the page, you can check that I have a "neighborhood" section, where I want to display how many apartments I have in each "category", like Bela Vista, Boa Vista and others.

The problem is that I don't know how to do that. Here is the code I use to loop the apartments when the fields are filled:

<?php
$newsArgs = array(
    'post_type' => 'property',
    'posts_per_page' => 200,
    "orderby" => 'meta_value_num',
    "meta_key" => 'numerooff',
    "order" => 'DESC',
    'tax_query' => array(
         array(
            'taxonomy' => 'property-status',
            'field'    => 'slug',
            'terms'    => 'oneoff',
         )
    )
);

$newsLoop = new WP_Query( $newsArgs );
while ( $newsLoop->have_posts() ) : $newsLoop->the_post();?>

Maybe I should copy something of this code, to display the numbers? I don't know really. Here is where I create the slug I'm trying to use. On the snippet above, you can see where I want to place it:

            <img src="<?php bloginfo('template_directory');?>/acoes/oneoff/bairro/belavista.jpg" alt="">

Bela Vista

I WANT TO DISPLAY IT HERE

What should I do?


问:
XSLT: Need Conditional based data using xslt
I am trying to use xslt in one of my product and i am stuck up on below issue.

As a response I am getting an XML which has some fields, More likely there are two main List Node Header and Details, Details is main data return by processing and Header has coded and other data related to output, In case error code is 70, which means, this is error, other error codes are treated as successful.

XML Response Example:

```<code><?xml version="1.0"?>
<root>
    <subroot>
        <data>
            <Header>
                <SCode>1</SCode>
                <StatusCode>0</StatusCode>
                <ErrorCode>00000000</ErrorCode>
                <ErrorDesc>This is OK</ErrorDesc>
            </Header>
            <Details>
                <accountNumber>1111X</accountNumber>
                <accountType>D</accountType>
                <Total>10000</Total>
                <Interest>10</Interest>
                <NewFlag>N</NewFlag>
            </Details>
        </data>
        <data>
            <Header>
                <SCode>1</SCode>
                <StatusCode>12</StatusCode>
                <ErrorCode>70</ErrorCode>
                <ErrorDesc>This is ERROR</ErrorDesc>
            </Header>
            <Details>
                <accountNumber>2222</accountNumber>
                <accountType>D</accountType>
                <Total>1000</Total>
                <Interest>12</Interest>
                <NewFlag>Y</NewFlag>
            </Details>
        </data>
    </subroot>
</root>
</code>```

Now Output should be

```<code><?xml version="1.0"?>
<root>
    <subroot>
        <data>
            <Details>
                <accountNumber>1111X</accountNumber>
                <accountType>D</accountType>
                <Total>10000</Total>
                <Interest>10</Interest>
                <NewFlag>N</NewFlag>
            </Details>
        </data>
        <data>
            <Details>
                <ErrorCode>70</ErrorCode>
                <ErrorDesc>This is ERROR</ErrorDesc>
                <accountNumber>2222</accountNumber>
                <accountType>D</accountType>
            </Details>
        </data>
    </subroot>
</root>
</code>```

Thanks!!

答:
Based on the sample input XML and the desired output shared, you can do the following to achieve the results.

Start with an identity transform template that will copy the structure as-is to the output.

```<code><xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
</xsl:template>
</code>```

Using <xsl:for-each> on the  node and using the node's position() as a reference, appropriate account information can be captured in the output. Below is the XSLT for reference with the output.

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*" />

    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="data">
        <xsl:copy>
            <xsl:for-each select="Header">
                <xsl:variable name="pos" select="position()" />
                <xsl:choose>
                    <xsl:when test="ErrorCode = '70'">
                        <Details>
                            <xsl:apply-templates select="ErrorCode" />
                            <xsl:apply-templates select="ErrorDesc" />
                            <xsl:apply-templates select="../Details[$pos]/accountNumber" />
                            <xsl:apply-templates select="../Details[$pos]/accountType" />
                        </Details>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:copy-of select="../Details[$pos]" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output

```<code><root>
    <subroot>
        <data>
            <Details>
                <accountNumber>1111X</accountNumber>
                <accountType>D</accountType>
                <Total>10000</Total>
                <Interest>10</Interest>
                <NewFlag>N</NewFlag>
            </Details>
        </data>
        <data>
            <Details>
                <ErrorCode>70</ErrorCode>
                <ErrorDesc>This is ERROR</ErrorDesc>
                <accountNumber>2222</accountNumber>
                <accountType>D</accountType>
            </Details>
        </data>
    </subroot>
</root>
</code>```

Body:
I am trying to use xslt in one of my product and i am stuck up on below issue.

As a response I am getting an XML which has some fields, More likely there are two main List Node Header and Details, Details is main data return by processing and Header has coded and other data related to output, In case error code is 70, which means, this is error, other error codes are treated as successful.

XML Response Example:

<?xml version="1.0"?>
<root>
    <subroot>
        <data>

                <SCode>1</SCode>
                <StatusCode>0</StatusCode>
                <ErrorCode>00000000</ErrorCode>
                <ErrorDesc>This is OK</ErrorDesc>

                <accountNumber>1111X</accountNumber>
                <accountType>D</accountType>
                <Total>10000</Total>
                <Interest>10</Interest>
                <NewFlag>N</NewFlag>

        </data>
        <data>

                <SCode>1</SCode>
                <StatusCode>12</StatusCode>
                <ErrorCode>70</ErrorCode>
                <ErrorDesc>This is ERROR</ErrorDesc>

                <accountNumber>2222</accountNumber>
                <accountType>D</accountType>
                <Total>1000</Total>
                <Interest>12</Interest>
                <NewFlag>Y</NewFlag>

        </data>
    </subroot>
</root>

Now Output should be

<?xml version="1.0"?>
<root>
    <subroot>
        <data>

                <accountNumber>1111X</accountNumber>
                <accountType>D</accountType>
                <Total>10000</Total>
                <Interest>10</Interest>
                <NewFlag>N</NewFlag>

        </data>
        <data>

                <ErrorCode>70</ErrorCode>
                <ErrorDesc>This is ERROR</ErrorDesc>
                <accountNumber>2222</accountNumber>
                <accountType>D</accountType>

        </data>
    </subroot>
</root>

Thanks!!

Body:
Based on the sample input XML and the desired output shared, you can do the following to achieve the results.

Start with an identity transform template that will copy the structure as-is to the output.

<xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
</xsl:template>

Using <xsl:for-each> on the <Header> node and using the node's position() as a reference, appropriate account information can be captured in the output. Below is the XSLT for reference with the output.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*" />

    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="data">
        <xsl:copy>
            <xsl:for-each select="Header">
                <xsl:variable name="pos" select="position()" />
                <xsl:choose>
                    <xsl:when test="ErrorCode = '70'">
                        <Details>
                            <xsl:apply-templates select="ErrorCode" />
                            <xsl:apply-templates select="ErrorDesc" />
                            <xsl:apply-templates select="../Details[$pos]/accountNumber" />
                            <xsl:apply-templates select="../Details[$pos]/accountType" />
                        </Details>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:copy-of select="../Details[$pos]" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output

<root>
    <subroot>
        <data>
            <Details>
                <accountNumber>1111X</accountNumber>
                <accountType>D</accountType>
                <Total>10000</Total>
                <Interest>10</Interest>
                <NewFlag>N</NewFlag>
            </Details>
        </data>
        <data>
            <Details>
                <ErrorCode>70</ErrorCode>
                <ErrorDesc>This is ERROR</ErrorDesc>
                <accountNumber>2222</accountNumber>
                <accountType>D</accountType>
            </Details>
        </data>
    </subroot>
</root>


问:
npm ERR! tarball.destroy is not a function
Hi I'm having issue while installing react-dom module.

I'm able install other modules like react express modules, on windows 10. 64 bit machine

```<code>npm install react-dom
npm WARN package.json -panel-client@1.0.0 No description
npm WARN package.json -panel-client@1.0.0 No repository field.
npm WARN package.json -panel-client@1.0.0 No README data
npm WARN package.json -panel-client@1.0.0 No license field.
npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz.2090210803' -> 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz'
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "react-dom"
npm ERR! node v4.4.3
npm ERR! npm  v2.15.1

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz.2000813013' -> 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz'
</code>```

答: uninstall  or stop ByteFence and it will run</p>

Body:
Hi I'm having issue while installing react-dom module.

I'm able install other modules like react express modules, on windows 10. 64 bit machine

npm install react-dom
npm WARN package.json -panel-client@1.0.0 No description
npm WARN package.json -panel-client@1.0.0 No repository field.
npm WARN package.json -panel-client@1.0.0 No README data
npm WARN package.json -panel-client@1.0.0 No license field.
npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz.2090210803' -> 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz'
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "react-dom"
npm ERR! node v4.4.3
npm ERR! npm  v2.15.1

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz.2000813013' -> 'C:\Users\NOI-DE~1\AppData\Local\Temp\npm-3064-f12f714d\registry.npmjs.org\react-dom\-\react-dom-0.14.8.tgz'