问:
Java: ModelMapper does not compile nested objects that contain collection List
I am using ModelMapper v0.7.7
My classes look like below:

```<code>public class ParentClassOne {

    protected String someValue1;
    protected String someValue2;

    protected ChildClassOne itemOne;

    public ChildClassOne getItemOne() {
        return itemOne;
    }

    public void setItemOne(ChildClassOne itemOne) {
        this.itemOne = itemOne;
    }

    ...setter and getter methods for the rest of fields...
}

public class ParentClassOne {
    ...this class contains the same elements like the first one...
}
</code>```

My ModelMapper configuration looks like this below:

```<code>ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
modelMapper.getConfiguration().setMethodAccessLevel(AccessLevel.PUBLIC);
modelMapper.getConfiguration().setFieldAccessLevel(AccessLevel.PROTECTED);
</code>```

When I want to convert the one object to another one I am using following source code:

```<code>info.p2.ParentClassOne result = modelMapper.map(data, info.p2.ParentClassOne.class);
</code>```

Of course it implies that data is object that was created by the first class from package info.p1  .

When I execute this source code only these "String" variables (someValue1 and someValue2) will be filled but variable "itemOne" will be null even if I pass full object that has all attributes filled.

Indication: The both classes are generated via maven with org.apache.cxf -> wsdl2java package so both of them contain special "javax.xml" annotations.

Edit1:
Class ChildClassOne exists in both packages. When ModelMapper tries to convert this, it recognizes that this variable in both classes have totally different type due to different packages and ModelMapper will not map this variable.

It is the same thing with string variables (someValue1, someValue2) but String type is the same in both classes and this type exists in a same package then ModelMapper will map them.

Of course I can add some manual steps to solve this simple example but in real situation I have much more complicated object that contains many nested objects.

Edit2:
The problem that I noticed, I did know when I asked the questions, are collections Lists in my ChildClassOne. ModelMapper can not map any object that contains any type of collection. In my classes list looks like below:

```<code>public ChildClassOne {
    protected List<ChildAnyClass> children;

    ...getter method...
    Notice: ...there is no setter method for the list....
}
</code>```

If there is no collection in nested objects ModelMapper will map all of them but in my case I have collection in each of my nested objects.

答:
I was searching and found following solution that can be used:

```<code>ModelMapper modelMapper = new ModelMapper();

Converter<ObjectOne, ObjectTwo> converter = new Converter<ObjectOne, ObjectTwo>() {
    public ObjectTwo convert(MappingContext<ObjectOne, ObjectTwo> context) {

        ObjectTwo dest = new ObjectTwo();
        if (context.getSource() != null) {

            // Converts list from source object into the list of destination object
            Type listType = new TypeToken<List<ObjectTwo>>() {}.getType();
            List<ObjectTwo> items = modelMapper.map(context.getSource().getList(), listType);

            dest.getList().addAll(items);
            return dest;

        } else {
            return dest;
        }
    }
};
</code>```

Now it is just necessary to add your convertor into ModelMapper with following source code:

```<code>modelMapper.addConverter(converter);
</code>```

This is a good solution if you have one or two nested collection but in case where you have multiple of them then you have to write for each of them convertor.

If someone knows how to solve this issue with multiple of nested collection please share with us.

Body:
I am using ModelMapper v0.7.7
My classes look like below:

public class ParentClassOne {

    protected String someValue1;
    protected String someValue2;

    protected ChildClassOne itemOne;

    public ChildClassOne getItemOne() {
        return itemOne;
    }

    public void setItemOne(ChildClassOne itemOne) {
        this.itemOne = itemOne;
    }

    ...setter and getter methods for the rest of fields...
}

public class ParentClassOne {
    ...this class contains the same elements like the first one...
}

My ModelMapper configuration looks like this below:

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
modelMapper.getConfiguration().setMethodAccessLevel(AccessLevel.PUBLIC);
modelMapper.getConfiguration().setFieldAccessLevel(AccessLevel.PROTECTED);

When I want to convert the one object to another one I am using following source code:

info.p2.ParentClassOne result = modelMapper.map(data, info.p2.ParentClassOne.class);

Of course it implies that data is object that was created by the first class from package info.p1  .

When I execute this source code only these "String" variables (someValue1 and someValue2) will be filled but variable "itemOne" will be null even if I pass full object that has all attributes filled.

Indication: The both classes are generated via maven with org.apache.cxf -> wsdl2java package so both of them contain special "javax.xml" annotations.

Edit1:
Class ChildClassOne exists in both packages. When ModelMapper tries to convert this, it recognizes that this variable in both classes have totally different type due to different packages and ModelMapper will not map this variable.

It is the same thing with string variables (someValue1, someValue2) but String type is the same in both classes and this type exists in a same package then ModelMapper will map them.

Of course I can add some manual steps to solve this simple example but in real situation I have much more complicated object that contains many nested objects.

Edit2:
The problem that I noticed, I did know when I asked the questions, are collections Lists in my ChildClassOne. ModelMapper can not map any object that contains any type of collection. In my classes list looks like below:

public ChildClassOne {
    protected List<ChildAnyClass> children;

    ...getter method...
    Notice: ...there is no setter method for the list....
}

If there is no collection in nested objects ModelMapper will map all of them but in my case I have collection in each of my nested objects.

Body:
I was searching and found following solution that can be used:

ModelMapper modelMapper = new ModelMapper();

Converter<ObjectOne, ObjectTwo> converter = new Converter<ObjectOne, ObjectTwo>() {
    public ObjectTwo convert(MappingContext<ObjectOne, ObjectTwo> context) {

        ObjectTwo dest = new ObjectTwo();
        if (context.getSource() != null) {

            // Converts list from source object into the list of destination object
            Type listType = new TypeToken<List<ObjectTwo>>() {}.getType();
            List<ObjectTwo> items = modelMapper.map(context.getSource().getList(), listType);

            dest.getList().addAll(items);
            return dest;

        } else {
            return dest;
        }
    }
};

Now it is just necessary to add your convertor into ModelMapper with following source code:

modelMapper.addConverter(converter);

This is a good solution if you have one or two nested collection but in case where you have multiple of them then you have to write for each of them convertor.

If someone knows how to solve this issue with multiple of nested collection please share with us.


来源: stackexchange

问:
Failed to load ressource (Node js)
I'm working on a project with Node js (Express...). I'll try to explain my problem as clear as I can

I work on localhost, and the home page of my index.html allows us to click on buttons which redirect us to other pages.
I found a little game which I would like to put in my project. So I created a button which is supposed to redirect us to the game's html file. (pong.html). And in pong.html, i have a HTML tag  :

```<code><script type="text/javascript" src="pong.js"></script>
</code>```

which is supposed to load the script pong.js and execute it on my page. But I have an error :

"Failed to load resource: the server responded with a status of 404 (Not Found)"

pong.html is in a "public" folder ; and pong.js is at the root of my project. I don't know if the error comes from a bad redirection in the script tag or in the use of one Nodejs function...
If it can help : the first thing my "pong.js" does after variable declarations is :

```<code>app.use(express.static(path.join(__dirname,"public")));
</code>```

Thanks by advance!

答:
pong.js is at the root of my project.

It should be near your pong.html file

ContentLicense: CC BY-SA 3.0

Title: Failed to load ressource (Node js)

Body:
I'm working on a project with Node js (Express...). I'll try to explain my problem as clear as I can

I work on localhost, and the home page of my index.html allows us to click on buttons which redirect us to other pages.
I found a little game which I would like to put in my project. So I created a button which is supposed to redirect us to the game's html file. (pong.html). And in pong.html, i have a HTML tag  :

which is supposed to load the script pong.js and execute it on my page. But I have an error :

"Failed to load resource: the server responded with a status of 404 (Not Found)"

pong.html is in a "public" folder ; and pong.js is at the root of my project. I don't know if the error comes from a bad redirection in the script tag or in the use of one Nodejs function...
If it can help : the first thing my "pong.js" does after variable declarations is :

app.use(express.static(path.join(__dirname,"public")));

Thanks by advance!


问:
How to show an app helper in the login items in macOS?
I have created a helper app that will launch the main app on macOS login. To do that I have follow this tutorial. All work fine but unfortunately, the helper app is not shown in the Login Items of preferences.

How can I have the helper app to appear in the user's Login Items like iTunesHelper and Dropbox?

答:
In the Apple documentation there is this information:

Adding Login Items

There are two ways to add a login item: using the Service Management
framework, and using a shared file list

Login items installed using the Service Management framework are not
visible in System Preferences and can only be removed by the
application that installed them.

Login items installed using a shared file list are visible in System
Preferences; users have direct control over them. If you use this API,
your login item can be disabled by the user, so any other application
that communicates with it it should have reasonable fallback behavior
in case the login item is disabled.

https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLoginItems.html

There is a tutorial by Richard Hult here, it's based on shared file list. The tutorial is 2012 (five years ago) so I don't know if it is still suitable. Moreover it's for Objective-C.


问:
Override PHP docblock/annotation of method without overloading (PhpStorm autocompletion)
This is a question about the autocompletion behavior in PhpStorm (and possibly other IDEs) in conjunction with PHP docblocks.

I have to groups of classes in my application. First there are individual classes for various products (CarProduct, FoodProduct etc.), all inheriting from BaseProduct, and the counterpart for individual contracts (CarContract, FoodContract etc.), all inheriting from BaseContract.

```<code><?php

class BaseContract
{
    /** @var BaseProduct */
    private $product;

    /**
     * @return BaseProduct
     */
    public function getProduct()
    {
        return $this->product;
    }
}
</code>```

Now I have an instance of CarContract, and I wanna get some CarProduct specific information:

```<code><?php

/* PhpStorm thinks, this is BaseProduct */
$product = $carContract->getProduct();

/* hence, getSpeed() is not available for PhpStorm */
$product->getSpeed();
</code>```

The autocompletion is not working as I like. There are two workarounds for this, but both are not nice:

Overload getProduct() in the subclass, just with updated @return docblocks

Add /** @var CarProduct $product */ everywhere, where I access the product of a CarContract

Is there a "usual" way to solve something like this, or are my workarounds the only solutions?

答:
PhpStorm does not really allow/does not support doing something like: have the same named class defined elsewhere and just use it as a reference for overriding definitions of real class. You can do that .. but IDE will warn with "multiple definitions of the same class" and it may introduce some weird behaviour/unexpected warnings...

Here is a ticket that ask for such feature: https://youtrack.jetbrains.com/issue/WI-851 -- watch it (star/vote/comment) to get notified on any progress.

Your options are: you can provide correct type hint locally (to local variable) using @var -- you already know it and that's first that you would think of:

```<code><?php

/** @var \CarProduct $product */
$product = $carContract->getProduct();

$product->getSpeed();
</code>```

Another possible way: instead of overriding actual method .. you can try doing the same but with @method PHPDoc -- will work with your code:

```<code><?php
/**
 * My Car Product class
 *
 * @method \CarProduct getProduct() Bla-bla optional description
 */
class CarContract extends BaseContract ...
</code>```

Body:
This is a question about the autocompletion behavior in PhpStorm (and possibly other IDEs) in conjunction with PHP docblocks.

I have to groups of classes in my application. First there are individual classes for various products (CarProduct, FoodProduct etc.), all inheriting from BaseProduct, and the counterpart for individual contracts (CarContract, FoodContract etc.), all inheriting from BaseContract.

<?php

class BaseContract
{
    /** @var BaseProduct */
    private $product;

    /**
     * @return BaseProduct
     */
    public function getProduct()
    {
        return $this->product;
    }
}

Now I have an instance of CarContract, and I wanna get some CarProduct specific information:

<?php

/* PhpStorm thinks, this is BaseProduct */
$product = $carContract->getProduct();

/* hence, getSpeed() is not available for PhpStorm */
$product->getSpeed();

The autocompletion is not working as I like. There are two workarounds for this, but both are not nice:

Overload getProduct() in the subclass, just with updated @return docblocks

Add /** @var CarProduct $product */ everywhere, where I access the product of a CarContract

Is there a "usual" way to solve something like this, or are my workarounds the only solutions?

Body:
PhpStorm does not really allow/does not support doing something like: have the same named class defined elsewhere and just use it as a reference for overriding definitions of real class. You can do that .. but IDE will warn with "multiple definitions of the same class" and it may introduce some weird behaviour/unexpected warnings...

Here is a ticket that ask for such feature: https://youtrack.jetbrains.com/issue/WI-851 -- watch it (star/vote/comment) to get notified on any progress.

Your options are: you can provide correct type hint locally (to local variable) using @var -- you already know it and that's first that you would think of:

<?php

/** @var \CarProduct $product */
$product = $carContract->getProduct();

$product->getSpeed();

Another possible way: instead of overriding actual method .. you can try doing the same but with @method PHPDoc -- will work with your code:

<?php
/**
 * My Car Product class
 *
 * @method \CarProduct getProduct() Bla-bla optional description
 */
class CarContract extends BaseContract ...


问:
I am trying to call on a text input with javascript
I am trying to check to make sure a form is complete, here is a piece of my code
checking the password

function checkpass()
{

    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');

    var message = document.getElementById('confirmMessage');

    var goodColor = "#66cc66";
    var badColor = "#ff6666";

    if(pass1.value == pass2.value){

        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords Match!"
    }else{

        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords Do Not Match!"
    }
}  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label >Password:</label>
            <input type="password" name="pass1" id="pass1">
      <p></p>

        <label >Verify Password:</label>
        <input type="password" name="pass2" id="pass2" onBlur="checkpass()">
<span id="confirmMessage" class="confirmMessage"></span></code>```

this works, but when I try to do something similar with the name input it does not work

```<code> <input type="text" name="name1" id="name1" onblur="checkname">
 <label>First Name</label>
function checkname(){var name1 = document.getElementById('name1');if (name1 == null) {alert('entername');}}
</code>```

If you have can tell me a simple error I have made that makes me look like a idiot that would be great, or if you could tell me a better way to do the whole thing that would also be great.
Any help you can offer will be much appreciated.

答:
You need to check for an empty name and not for a null name try with :

```<code>var name1 = document.getElementById('name1').value;
if(name1.trim() == "")
</code>```

also you need to call checkname() function on onblur in place of checkname

function checkname(){
var name1 = document.getElementById('name1').value;
if (name1.trim() == "")
{
alert('entername');
}
}
function checkpass()
{

    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');

    var message = document.getElementById('confirmMessage');

    var goodColor = "#66cc66";
    var badColor = "#ff6666";

    if(pass1.value == pass2.value){

        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords Match!"
    }else{

        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords Do Not Match!"
    }
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<label >Password:</label>
            <input type="password" name="pass1" id="pass1">
<br/>

        <label >Verify Password:</label>
        <input type="password" name="pass2" id="pass2" onBlur="checkpass()">
        <br/>
<span id="confirmMessage" class="confirmMessage"></span>
<br/>

 <input type="text" name="name1" id="name1" onblur="checkname();">
 <label>First Name</label>
 <br/>
 <input type="text" name="name2" id="name2">
 <label>Last Name</label> </code>```

Body:
I am trying to check to make sure a form is complete, here is a piece of my code
checking the password

function checkpass()
{

    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');

    var message = document.getElementById('confirmMessage');

    var goodColor = "#66cc66";
    var badColor = "#ff6666";

    if(pass1.value == pass2.value){

        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords Match!"
    }else{

        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords Do Not Match!"
    }
}

Password:
            <input type="password" name="pass1" id="pass1">

        Verify Password:
        <input type="password" name="pass2" id="pass2" onBlur="checkpass()">

this works, but when I try to do something similar with the name input it does not work

 <input type="text" name="name1" id="name1" onblur="checkname">
 First Name
function checkname(){var name1 = document.getElementById('name1');if (name1 == null) {alert('entername');}}

If you have can tell me a simple error I have made that makes me look like a idiot that would be great, or if you could tell me a better way to do the whole thing that would also be great.
Any help you can offer will be much appreciated.

Body:
You need to check for an empty name and not for a null name try with :

var name1 = document.getElementById('name1').value;
if(name1.trim() == "")

also you need to call checkname() function on onblur in place of checkname

function checkname(){
var name1 = document.getElementById('name1').value;
if (name1.trim() == "")
{
alert('entername');
}
}
function checkpass()
{

    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');

    var message = document.getElementById('confirmMessage');

    var goodColor = "#66cc66";
    var badColor = "#ff6666";

    if(pass1.value == pass2.value){

        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords Match!"
    }else{

        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords Do Not Match!"
    }
}

<label >Password:</label>
            <input type="password" name="pass1" id="pass1">
<br/>

        <label >Verify Password:</label>
        <input type="password" name="pass2" id="pass2" onBlur="checkpass()">
        <br/>
<span id="confirmMessage" class="confirmMessage"></span>
<br/>

 <input type="text" name="name1" id="name1" onblur="checkname();">
 <label>First Name</label>
 <br/>
 <input type="text" name="name2" id="name2">
 <label>Last Name</label>


问:
How to get the subdomain value from a url?
how can I get the subdomain value in rails, is there a built-in way to do this?

e.g.

```<code>test123.example.com
</code>```

I want the test123 part of the url.

答: account_location is also a good plugin. After using it, you can find the account based on different subdomains. And you can find out subdomain from url just by writing ```<code>request.subdomains(0).first</code>``` in your code.</p>

ContentLicense: CC BY-SA 2.5

Body:
how can I get the subdomain value in rails, is there a built-in way to do this?

e.g.

test123.example.com

I want the test123 part of the url.

Body:
account_location is also a good plugin. After using it, you can find the account based on different subdomains. And you can find out subdomain from url just by writing
request.subdomains(0).first
 in your code.


问:
add default option to ember power select
in ember power select how to include default options for drop-down like "All" in  below

my service does't return "All" option.I think it not good to include it in the store.

答: As you said, it is not good to include additional options to store. Hence, you can just make use of a computed property. Please take a look at the following twiddle. I created a computed property name computedOptions within my-component.js and inserted your custom option "All" as the first option to a new array copied from original options and just passed this computedOptions as options attribute of power-select.


问:
Prevent border clipping my image
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slideshow">
    <table>
      <tr>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Images:

No-Clipping

Clipping

Winrar logo

答:
Placing the images inside a div and giving the divs the 'icon_circle' class fixed it. Had to add a few extra properties. Here's the working code for anyone who encounters same problem. =D

    #boxes .box img{
  height: 90px;
}
  .slideshow {
  display: none;
  margin-top: -50px;
  font-size: 25px;
}

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  display: table;
  margin: 0 auto;
  display: block;
  width: 90px;
  padding: 25px;
  border-radius: 250px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="slideshow">
    <table>
      <tr>
        <td><div class="icon_circle" ><img src="https://i.stack.imgur.com/N2SF1.png" alt=""></div></td>
        <td><div class="icon_circle" ><img src="https://i.stack.imgur.com/N2SF1.png" alt=""></div></td>
        <td><div class="icon_circle" ><img src="https://i.stack.imgur.com/N2SF1.png" alt=""></div></td>

      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Title: Prevent border clipping my image

Body:
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}

Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.

Images:

No-Clipping

Clipping

Winrar logo

Body:
Placing the images inside a div and giving the divs the 'icon_circle' class fixed it. Had to add a few extra properties. Here's the working code for anyone who encounters same problem. =D

    #boxes .box img{
  height: 90px;
}
  .slideshow {
  display: none;
  margin-top: -50px;
  font-size: 25px;
}

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  display: table;
  margin: 0 auto;
  display: block;
  width: 90px;
  padding: 25px;
  border-radius: 250px;
  border: #000 5px solid;
}

    <div class="slideshow">
    <table>
      <tr>
        <td><div class="icon_circle" ><img src="https://i.stack.imgur.com/N2SF1.png" alt=""></div></td>
        <td><div class="icon_circle" ><img src="https://i.stack.imgur.com/N2SF1.png" alt=""></div></td>
        <td><div class="icon_circle" ><img src="https://i.stack.imgur.com/N2SF1.png" alt=""></div></td>

      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div>


问:
JIRA - Is it possible to use multiple issues within the same workflow?
I am wondering whether I can use multiple issues in a workflow or not? So the workflow in my head will be as follows: Some people in an inspection group will create an issue. They will enter some data to the JIRA system and also they will grant some authorizations to other people. Afterwards, the people who have been granted authorizations will proceed within the work flow by creating another issue? So, to sum up, can I break a workflow into different aparts such that every apart will run with different issues? Thanks in advance. </p>

答: A parent issue can have multiple child task. You can get more information about the same through this link</p>


问:
How to fix adding JSON data to the ArrayList and updating to the ArrayAdapter
This code is to simply query the Google Books API and to return the data in JSON. Then, the JSON data is parsed and the Book Name, Authors and the Publication Date are stored in an ArrayList of type 'Book'. There is a problem when tryiing to parse the Array of JSON data. It's not coming out of the loop at Line 70 in MainActivity.java class. What might be the possible solution?

The repository is https://github.com/PRAVEENT26/GoogleBooksAPI

I'll list the files here too.

MainActivity.java

package com.praveent.googlebooksapi;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.in;

public class MainActivity extends AppCompatActivity {

  EditText query;
  Button submit;
  String dataJSON;
  TextView test;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    query = (EditText) findViewById(R.id.query);
    submit = (Button) findViewById(R.id.submit);
    final String baseURL = "https://www.googleapis.com/books/v1/volumes";
    final String queryParameter = "q";

    submit.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String searchQuery = query.getText().toString();

        Uri tempUri = Uri.parse(baseURL).buildUpon().appendQueryParameter(queryParameter, searchQuery).build();
        URL url;
        try {
          url = new URL(tempUri.toString());
          new fetchDataAsync().execute(url);
        } catch (IOException e) {
          e.printStackTrace();
        }

      }
    });
  }

  public void jsonParsing() throws JSONException {
    JSONObject response = new JSONObject(dataJSON);
    int total = response.getInt("totalItems");
    TextView test = (TextView) findViewById(R.id.test);
    int flag = 0;
    JSONArray bookArray = response.getJSONArray("items");
    //test.setText(Integer.toString(bookArray.length()));
    ArrayList < Book > bookList = new ArrayList < > ();
    ListView listView = (ListView) findViewById(R.id.commonView);
    for (int i = 0; i < total; i++) {

      flag++;
      JSONObject volume = bookArray.getJSONObject(i);
      if (volume.has("volumeInfo")) {
        JSONObject tempObject = volume.getJSONObject("volumeInfo");
        String bookName = tempObject.getString("title");
        String authorName = null;
        if (tempObject.has("authors")) {
          JSONArray authorsArray = tempObject.getJSONArray("authors");
          for (int j = 0; j < authorsArray.length(); j++) {
            authorName += authorsArray.getString(j);
            if (j < authorsArray.length() - 1) {
              authorName += ", ";
            }
          }
        }
        String publicationDate = tempObject.getString("publishedDate");
        bookList.add(new Book(bookName, authorName, publicationDate));
      }
    }
    test.setText(Integer.toString(flag));
    BookAdapter bookAdapter = new BookAdapter(this, bookList);
    listView.setAdapter(bookAdapter);
  }

  public class fetchDataAsync extends AsyncTask < URL, Void, String > {

    @Override
    protected String doInBackground(URL...url) {
      URL searchURL = url[0];
      try {
        dataJSON = fetchData(searchURL);

      } catch (IOException e) {
        e.printStackTrace();
      }
      return dataJSON;
    }

    @Override
    protected void onPostExecute(String s) {
      try {
        jsonParsing();
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  public static String fetchData(URL url) throws IOException {
    HttpURLConnection newConnection = (HttpURLConnection) url.openConnection();
    try {
      InputStream newStream = newConnection.getInputStream();
      Scanner scanner = new Scanner(newStream);
      scanner.useDelimiter("\\A");
      boolean hasInput = scanner.hasNext();
      if (hasInput) {
        return scanner.next();
      } else
        return null;
    } finally {
      newConnection.disconnect();
    }
  }
}```
</div>
</div>
</p>

<p>BookAdapter.java</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package com.praveent.googlebooksapi;

    import android.app.Activity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;

    import java.util.ArrayList;

    public class BookAdapter extends ArrayAdapter<Book>{

    public BookAdapter(Activity context, ArrayList<Book> bookArrayListAdapter) {
        super(context, 0, bookArrayListAdapter);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View tempView = convertView;
        if (tempView == null){
            tempView = LayoutInflater.from(getContext()).inflate(R.layout.book_details,parent,false);
        }
        Book temp = getItem(position);
        ImageView imageView = (ImageView) tempView.findViewById(R.id.image);
        TextView nameView = (TextView) tempView.findViewById(R.id.bookName);
        TextView authorView = (TextView) tempView.findViewById(R.id.authorName);
        TextView dateView = (TextView) tempView.findViewById(R.id.publishDate);

        imageView.setImageResource(R.drawable.google);
        nameView.setText(temp.getbookName());
        authorView.setText(temp.getAuthorName());
        dateView.setText(temp.getPublishedDate());

        return tempView;
    }
    }</code>```

Book.java //Custom Object

package com.praveent.googlebooksapi;

    public class Book {

    String bookName;
    String authorName;
    String publishedDate;
    public Book(String name, String authors, String date){
        bookName = name;
        authorName = authors;
        publishedDate = date;
    }

    public String getbookName() {
        return bookName;
    }
    public String getAuthorName() {
        return authorName;
    }
    public String getPublishedDate() {
        return publishedDate;
    }

    }```
</div>
</div>
</p>

<p>XML Layouts:</p>

<p>book_details.xml:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp">
    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:padding="8dp"
        android:id="@+id/image"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/bookName"
            android:textSize="16dp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/authorName"
            android:textSize="16dp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/publishDate"
            android:textSize="16dp" />
    </LinearLayout>

</LinearLayout></code>```

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.praveent.googlebooksapi.MainActivity">

    <EditText
        android:id="@+id/query"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Enter the Book Query" />

    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SUBMIT QUERY" />
    <TextView
        android:id="@+id/test"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/commonView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"/>

</LinearLayout>```
</div>
</div>
</p>

<p>ANDROID MANIFEST FILE:</p>

<p>AndroidManifest.xml:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.praveent.googlebooksapi">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest></code>```

SAMPLE JSON DATA: Query Results in JSON. Click this to view the JSON structure.

Please help me run without any problems. Thanks in advance!

答:
Try this,</p>

```<code>try
{
    JSONObject result = new JSONObject(resultResponse);
    String kind = result.getString("kind");

    JSONArray items_arr=result.getJSONArray("items");
    for(int i=0;i<items_arr.length();i++)
    {
        JSONObject obj=items_arr.getJSONObject(i);
        JSONObject volumeInfo_obj=obj.getJSONObject("volumeInfo");
        String bookName=volumeInfo_obj.getString("title");
        JSONArray volumeInfo_arr=volumeInfo_obj.getJSONArray("authors");
        String authorName=volumeInfo_arr.getString(0);

        String publicationDate=volumeInfo_obj.getString("publishedDate");

        bookList.add(new Book(bookName, authorName, publicationDate));
    }
    BookAdapter bookAdapter = new BookAdapter(this, bookList);
    listView.setAdapter(bookAdapter);

} catch (JSONException e) {
    Constants.dismiss_progress_dialog();
    e.printStackTrace();
}
</code>```

Body:
This code is to simply query the Google Books API and to return the data in JSON. Then, the JSON data is parsed and the Book Name, Authors and the Publication Date are stored in an ArrayList of type 'Book'. There is a problem when tryiing to parse the Array of JSON data. It's not coming out of the loop at Line 70 in MainActivity.java class. What might be the possible solution?

The repository is https://github.com/PRAVEENT26/GoogleBooksAPI

I'll list the files here too.

MainActivity.java

package com.praveent.googlebooksapi;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.in;

public class MainActivity extends AppCompatActivity {

  EditText query;
  Button submit;
  String dataJSON;
  TextView test;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    query = (EditText) findViewById(R.id.query);
    submit = (Button) findViewById(R.id.submit);
    final String baseURL = "https://www.googleapis.com/books/v1/volumes";
    final String queryParameter = "q";

    submit.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String searchQuery = query.getText().toString();

        Uri tempUri = Uri.parse(baseURL).buildUpon().appendQueryParameter(queryParameter, searchQuery).build();
        URL url;
        try {
          url = new URL(tempUri.toString());
          new fetchDataAsync().execute(url);
        } catch (IOException e) {
          e.printStackTrace();
        }

      }
    });
  }

  public void jsonParsing() throws JSONException {
    JSONObject response = new JSONObject(dataJSON);
    int total = response.getInt("totalItems");
    TextView test = (TextView) findViewById(R.id.test);
    int flag = 0;
    JSONArray bookArray = response.getJSONArray("items");
    //test.setText(Integer.toString(bookArray.length()));
    ArrayList < Book > bookList = new ArrayList < > ();
    ListView listView = (ListView) findViewById(R.id.commonView);
    for (int i = 0; i < total; i++) {

      flag++;
      JSONObject volume = bookArray.getJSONObject(i);
      if (volume.has("volumeInfo")) {
        JSONObject tempObject = volume.getJSONObject("volumeInfo");
        String bookName = tempObject.getString("title");
        String authorName = null;
        if (tempObject.has("authors")) {
          JSONArray authorsArray = tempObject.getJSONArray("authors");
          for (int j = 0; j < authorsArray.length(); j++) {
            authorName += authorsArray.getString(j);
            if (j < authorsArray.length() - 1) {
              authorName += ", ";
            }
          }
        }
        String publicationDate = tempObject.getString("publishedDate");
        bookList.add(new Book(bookName, authorName, publicationDate));
      }
    }
    test.setText(Integer.toString(flag));
    BookAdapter bookAdapter = new BookAdapter(this, bookList);
    listView.setAdapter(bookAdapter);
  }

  public class fetchDataAsync extends AsyncTask < URL, Void, String > {

    @Override
    protected String doInBackground(URL...url) {
      URL searchURL = url[0];
      try {
        dataJSON = fetchData(searchURL);

      } catch (IOException e) {
        e.printStackTrace();
      }
      return dataJSON;
    }

    @Override
    protected void onPostExecute(String s) {
      try {
        jsonParsing();
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  public static String fetchData(URL url) throws IOException {
    HttpURLConnection newConnection = (HttpURLConnection) url.openConnection();
    try {
      InputStream newStream = newConnection.getInputStream();
      Scanner scanner = new Scanner(newStream);
      scanner.useDelimiter("\\A");
      boolean hasInput = scanner.hasNext();
      if (hasInput) {
        return scanner.next();
      } else
        return null;
    } finally {
      newConnection.disconnect();
    }
  }
}

BookAdapter.java

package com.praveent.googlebooksapi;

    import android.app.Activity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;

    import java.util.ArrayList;

    public class BookAdapter extends ArrayAdapter<Book>{

    public BookAdapter(Activity context, ArrayList<Book> bookArrayListAdapter) {
        super(context, 0, bookArrayListAdapter);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View tempView = convertView;
        if (tempView == null){
            tempView = LayoutInflater.from(getContext()).inflate(R.layout.book_details,parent,false);
        }
        Book temp = getItem(position);
        ImageView imageView = (ImageView) tempView.findViewById(R.id.image);
        TextView nameView = (TextView) tempView.findViewById(R.id.bookName);
        TextView authorView = (TextView) tempView.findViewById(R.id.authorName);
        TextView dateView = (TextView) tempView.findViewById(R.id.publishDate);

        imageView.setImageResource(R.drawable.google);
        nameView.setText(temp.getbookName());
        authorView.setText(temp.getAuthorName());
        dateView.setText(temp.getPublishedDate());

        return tempView;
    }
    }

Book.java //Custom Object

package com.praveent.googlebooksapi;

    public class Book {

    String bookName;
    String authorName;
    String publishedDate;
    public Book(String name, String authors, String date){
        bookName = name;
        authorName = authors;
        publishedDate = date;
    }

    public String getbookName() {
        return bookName;
    }
    public String getAuthorName() {
        return authorName;
    }
    public String getPublishedDate() {
        return publishedDate;
    }

    }

XML Layouts:

book_details.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp">
    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:padding="8dp"
        android:id="@+id/image"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/bookName"
            android:textSize="16dp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/authorName"
            android:textSize="16dp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/publishDate"
            android:textSize="16dp" />
    </LinearLayout>

</LinearLayout>

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.praveent.googlebooksapi.MainActivity">

    <EditText
        android:id="@+id/query"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Enter the Book Query" />

    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SUBMIT QUERY" />
    <TextView
        android:id="@+id/test"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/commonView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"/>

</LinearLayout>

ANDROID MANIFEST FILE:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.praveent.googlebooksapi">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

SAMPLE JSON DATA: Query Results in JSON. Click this to view the JSON structure.

Please help me run without any problems. Thanks in advance!

Body:
Try this,

try
{
    JSONObject result = new JSONObject(resultResponse);
    String kind = result.getString("kind");

    JSONArray items_arr=result.getJSONArray("items");
    for(int i=0;i<items_arr.length();i++)
    {
        JSONObject obj=items_arr.getJSONObject(i);
        JSONObject volumeInfo_obj=obj.getJSONObject("volumeInfo");
        String bookName=volumeInfo_obj.getString("title");
        JSONArray volumeInfo_arr=volumeInfo_obj.getJSONArray("authors");
        String authorName=volumeInfo_arr.getString(0);

        String publicationDate=volumeInfo_obj.getString("publishedDate");

        bookList.add(new Book(bookName, authorName, publicationDate));
    }
    BookAdapter bookAdapter = new BookAdapter(this, bookList);
    listView.setAdapter(bookAdapter);

} catch (JSONException e) {
    Constants.dismiss_progress_dialog();
    e.printStackTrace();
}


问:
Create structures in loop without naming them
Let's say I want to create structures in a loop. I don't want to change the values of the structure variables in each loop, I want to create new ones. However, from what I've learnt until know I have to name every new structure I make. Is there a way to do it without naming the structures?

And more specifically, can I have a pointer in each structure that will point to the next one?

What I wanna make is a BST and my struct is for every new node I add to the tree.That's how I've seen people do it, with struct. How can I add nodes if I don't name them? I definitely have some blanks there.

答:
Rules for an Identifier

An Indetifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ).

The first character of an identifier can only contain alphabet( a-z , A-Z ) or underscore ( _ ).

Identifiers are also case sensitive in C. For example name and Name are two different identifier in C.

Keywords are not allowed to be used as Identifiers.

No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to be used in or as Identifier.

So, to answer your question you cannot create new structs without identifying them, and even if you were able to, what would you reference it by?
If there is nothing pointing to a it, it is simply garbage taking space on the memory


问:
Organizing stick axis labels on Flot chart
I'm using a Flot chart and when I have many labels in the xaxis so the information is truncated.

I need to change the labels angle to show the information correctly, like this:

How can I do this? I read something about labelAngle: 45 property for xaxis, but that does not work. When I use this property nothing changes in the graph.

```<code>xaxis: {
        show: true,
        mode: "time",
        ticks: xaxisLabel,
        //timeformat:"%d/%m/%y %H:%M",
        timeformat: ( ($('#periodo').val() == "0") || ($('#periodo').val() == "1"))?"%H:%M":"%d/%m/%y",
        timezone: "browser",
        tickSize: [4, 'hour']
      }
</code>```

答: Flot does not support rotated labels by default. You need to define some custom CSS (like in this answer) or use a plugin, for example tickrotor (which uses the xaxis.rotateTicks property instead of labelAngle).

Body:
I'm using a Flot chart and when I have many labels in the xaxis so the information is truncated.

I need to change the labels angle to show the information correctly, like this:

How can I do this? I read something about labelAngle: 45 property for xaxis, but that does not work. When I use this property nothing changes in the graph.

xaxis: {
        show: true,
        mode: "time",
        ticks: xaxisLabel,
        //timeformat:"%d/%m/%y %H:%M",
        timeformat: ( ($('#periodo').val() == "0") || ($('#periodo').val() == "1"))?"%H:%M":"%d/%m/%y",
        timezone: "browser",
        tickSize: [4, 'hour']
      }


问:
How to get all css properties and events of a html element with jquery or other libraries?
see these pictures :

How to get all corresponding css properties of a specific html element with their current values and events ?

答:
Use getComputedStyle()

var body = $('body')[0];
var style = window.getComputedStyle(body, null);
var events = $._data(body, "events");

console.log(style)
console.log(events);```
<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></code>```

Body:
Use getComputedStyle()

var body = $('body')[0];
var style = window.getComputedStyle(body, null);
var events = $._data(body, "events");

console.log(style)
console.log(events);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
How to trigger a function from dropdown in angular 2
I have a drop down with the following code,

```<code><select class="form-control">
     <option value="">Select Draft</option>
     <option (change)="getDetails(event.name)" *ngFor="let event of eventasdraft">{{ event.name }}
     </option>
</select>
</code>```

When I execute the above code,it is not triggering the function.Can anyone please help me.Thanks.

答:
The <option> doesn't emit a change event, only the select

<select class="form-control" (change)="getEventDetails($event.target.value)">
```

<p>or</p>

<pre class="lang-ts prettyprint-override"><code><select ngModel (ngModelChange)="getDetails($event)" class="form-control">
     <option value="">Select Draft</option>
     <option *ngFor="let event of eventasdraft" [value]="event.name">{{ event.name }}
     </option>
</select>
</code>```

Body:
I have a drop down with the following code,

<select class="form-control">
     <option value="">Select Draft</option>
     <option (change)="getDetails(event.name)" *ngFor="let event of eventasdraft">{{ event.name }}
     </option>
</select>

When I execute the above code,it is not triggering the function.Can anyone please help me.Thanks.

Body:
The <option> doesn't emit a change event, only the select

<select class="form-control" (change)="getEventDetails($event.target.value)">

or

<select ngModel (ngModelChange)="getDetails($event)" class="form-control">
     <option value="">Select Draft</option>
     <option *ngFor="let event of eventasdraft" [value]="event.name">{{ event.name }}
     </option>
</select>


问:
hive: filter by "max(partitioned_col)" without performing full table scan
I have a large Hive table partitioned by date, and I'm trying to setup an Oozie workflow that runs a process on the most recent partition. Each time the ETL job runs a new folder is created. The directory structure looks like this:

```<code>/user/hive/warehouse/my_transactions/date=20150424
[...]
/user/hive/warehouse/my_transactions/date=20150811
/user/hive/warehouse/my_transactions/date=20150812
/user/hive/warehouse/my_transactions/date=20150813
</code>```

On my home/lab cluster, running Hive 1.1.0-cdh5.4.4, I'm able to use the max aggregate function in a subquery to filter for the most recent days data:

```<code>select
  [...]
from my_transactions
inner join (select max(date) as max_date from my_transactions) max_date
on date = max_date
</code>```

The results are returned pretty quickly.

In our work environment, running Hive 0.13.0-mapr-1501 on a much larger dataset with beefier hardware, the same query attempts to execute in multiple stages and eventually throws a java.lang.OutOfMemoryError: Java heap space.

If I replace the subquery with a literal, i.e. WHERE date = '20150813' instead of the aggregation and the inner join, it executes really quickly. With the aggregation/subquery it seems like, instead of using the partitions to reduce the amount of IO, it's attempting to scan all the partitions.

Is there a better way to write this query (e.g. possibly query the Hive metadata to get the max(date) of the partitioned column)?

答:
This query gives the max(partitioned column) without scanning the entire table.</p>

```<code>hive -e "set hive.cli.print.header=false;show partitions table_name;" | tail -1 | cut -d'=' -f2
</code>```

Body:
I have a large Hive table partitioned by date, and I'm trying to setup an Oozie workflow that runs a process on the most recent partition. Each time the ETL job runs a new folder is created. The directory structure looks like this:

/user/hive/warehouse/my_transactions/date=20150424
[...]
/user/hive/warehouse/my_transactions/date=20150811
/user/hive/warehouse/my_transactions/date=20150812
/user/hive/warehouse/my_transactions/date=20150813

On my home/lab cluster, running Hive 1.1.0-cdh5.4.4, I'm able to use the max aggregate function in a subquery to filter for the most recent days data:

select
  [...]
from my_transactions
inner join (select max(date) as max_date from my_transactions) max_date
on date = max_date

The results are returned pretty quickly.

In our work environment, running Hive 0.13.0-mapr-1501 on a much larger dataset with beefier hardware, the same query attempts to execute in multiple stages and eventually throws a java.lang.OutOfMemoryError: Java heap space.

If I replace the subquery with a literal, i.e. WHERE date = '20150813' instead of the aggregation and the inner join, it executes really quickly. With the aggregation/subquery it seems like, instead of using the partitions to reduce the amount of IO, it's attempting to scan all the partitions.

Is there a better way to write this query (e.g. possibly query the Hive metadata to get the max(date) of the partitioned column)?

Body:
This query gives the max(partitioned column) without scanning the entire table.

hive -e "set hive.cli.print.header=false;show partitions table_name;" | tail -1 | cut -d'=' -f2


问:
How to get a list of files with errors in PhpStorm
In PhpStorm I get a read mark on the upper right side of the code window if there's a PHP bug in the file. That's great. What I like to have is a list of all files which have this read mark.

Any ideas?

答: Slightly off-topic, but may be helpful. If you need to jump through all the errors in a file (for example, CSS file), open up the file and and hit the F2 button on the keyboard. Repeat it to cycle through all the errors. To navigate back to the previous error, hit Shift + F2


问:
Implementing isset() in a setter method
Is there any way to implement isset() in a setter method? That is, have the setter method check if the variable exists? From what I can tell no, but hopefully someone can confirm that for me. In a nutshell, I'm looking to avoid having to do

```<code>if (isset($arr[0])) $foo->setId($arr[0])
</code>```

and simply just do

```<code>$foo->setId($arr[0])
</code>```

and somehow implement the isset() logic in the setter method. Thanks!

答:
First, read @alex's answer. (Edit: Read @deceze's answer, too)

In order to mimic what you want you can pass the array and the index separately:

```<code>$foo->setId($arr, 0);
</code>```

And change the setId() method's signature (or add a safeSetId()):

```<code>function safeSetId($array, $index) {
    if (isset($array[$index])) {
        $this->setId($array[$index]);
    }
}
</code>```

This is not very pretty, though :)

Title: Implementing isset() in a setter method

Body:
Is there any way to implement isset() in a setter method? That is, have the setter method check if the variable exists? From what I can tell no, but hopefully someone can confirm that for me. In a nutshell, I'm looking to avoid having to do

if (isset($arr[0])) $foo->setId($arr[0])

and simply just do

$foo->setId($arr[0])

and somehow implement the isset() logic in the setter method. Thanks!

Body:
First, read @alex's answer. (Edit: Read @deceze's answer, too)

In order to mimic what you want you can pass the array and the index separately:

$foo->setId($arr, 0);

And change the setId() method's signature (or add a safeSetId()):

function safeSetId($array, $index) {
    if (isset($array[$index])) {
        $this->setId($array[$index]);
    }
}

This is not very pretty, though :)


问:
Publish from VS works, xcopy of dotnet publish does not
We have a dotnet core app, full framework referencing a ef6 lib. Running publish to IIS from VS2017 works fine.

When running the following from TFS2017 it does not work (ef6 strange errors)

nuget restore ***.sln

dotnet restore src/CoolApp/CoolApp.csproj

dotnet publish src/CoolApp/CoolApp.csproj --configuration release --output $(drop)

(when releasing) Copy everything from $(drop) to IIS website

Comparing content the exe is of course different, and exe.config also.

Any ideas what we've missed?

答:
Are you using TFS 2017 Update1. If you are using TFS 2017 Update1, please don't use the .netCore(preview) step first. Try to use the tasks in this document about build your ASP.NET Core app to see if it works. Steps are:

Command Line(Dotnet restore).

Visual Studio Build. Cause your project is created in VS2017, select VS 2017 in this step to build.

Command Line(Dot restore). publish --configuration release --output $(drop)

Publish build artifacts.
When in release, copy the artifacts from $(drop).


问:
How to access value of __nssingleobjectarrayi in the following code
I parsed a json and got a JSON Dictionary.

```<code>{
data =     (
            {
        bio = "<null>";
        bookmarked = 35;
        id = 22;
        "last_seen" =             {
            date = "2017-03-30 14:00:01";
            timezone = "Asia/Kolkata";
            "timezone_type" = 3;
        };
        name = "Alex";
        username = "Alex";
    }
);}
</code>```

I am trying to access username and date.
I tried it doing

```<code>let name = userData.value(forKeyPath: "data.username")
print(username)
</code>```

By printing this, I am getting a __NSSingleObjectArrayI with the username.

```<code>Optional(<__NSSingleObjectArrayI 0x6080000120b0>(
Alex
)
)
</code>```

How do I access that and display at other places? Basically extract the "Alex" from that as a String?

答:
value(forKeyPath applied to an array containing dictionaries returns an array – as revealed in the output. You need to get the first item of the array

```<code>let names = userData.value(forKeyPath: "data.username")
if !names.isEmpty { print(names[0]) }
</code>```

However the usual way to get the name is

```<code>if let data = userDatavalue["data") as? [[String:Any]], !data.isEmpty,
   let username = data[0]["username"] as? String {
      print(username)
}
</code>```

Body:
I parsed a json and got a JSON Dictionary.

{
data =     (
            {
        bio = "<null>";
        bookmarked = 35;
        id = 22;
        "last_seen" =             {
            date = "2017-03-30 14:00:01";
            timezone = "Asia/Kolkata";
            "timezone_type" = 3;
        };
        name = "Alex";
        username = "Alex";
    }
);}

I am trying to access username and date.
I tried it doing

let name = userData.value(forKeyPath: "data.username")
print(username)

By printing this, I am getting a __NSSingleObjectArrayI with the username.

Optional(<__NSSingleObjectArrayI 0x6080000120b0>(
Alex
)
)

How do I access that and display at other places? Basically extract the "Alex" from that as a String?

Body:
value(forKeyPath applied to an array containing dictionaries returns an array – as revealed in the output. You need to get the first item of the array

let names = userData.value(forKeyPath: "data.username")
if !names.isEmpty { print(names[0]) }

However the usual way to get the name is

if let data = userDatavalue["data") as? [[String:Any]], !data.isEmpty,
   let username = data[0]["username"] as? String {
      print(username)
}


问:
How to use and pass value to Alias Column of aggregate Function of Date
I am using this query to get year from adventureworksLT2008:

```<code>"select DATEPART(YYYY,SellStartDate) as Year from SalesLT.Product group by DATEPART(YYYY,SellStartDate)"
</code>```

Now I want to just pass year like 1998 and get all the record of 1998

```<code>"select DATEPART(YYYY,SellStartDate) as 'Years' from SalesLT.Product where Years = '1998'"
</code>```

but I'm getting this error

Invalid Column Years. SellStartDate datatype is datetime.

答:
Years is not defined when the WHERE is executed. Have a look at the execution order of a query.

Use it like this:

```<code>SELECT DATEPART(YYYY, SellStartDate) AS Years
FROM SalesLT.Product
WHERE DATEPART(YYYY, SellStartDate) = 1998
</code>```

Btw the DATEPART function returns int.

Body:
I am using this query to get year from adventureworksLT2008:

"select DATEPART(YYYY,SellStartDate) as Year from SalesLT.Product group by DATEPART(YYYY,SellStartDate)"

Now I want to just pass year like 1998 and get all the record of 1998

"select DATEPART(YYYY,SellStartDate) as 'Years' from SalesLT.Product where Years = '1998'"

but I'm getting this error

Invalid Column Years. SellStartDate datatype is datetime.

Body:
Years is not defined when the WHERE is executed. Have a look at the execution order of a query.

Use it like this:

SELECT DATEPART(YYYY, SellStartDate) AS Years
FROM SalesLT.Product
WHERE DATEPART(YYYY, SellStartDate) = 1998

Btw the DATEPART function returns int.


答:
Isset is not a function: it's a language construct. Language constructs are allowed to do magic; user-defined functions cant.

There is no way to reimplement the isset logic without isset itself (without modifications to PHP's source code, at least). If you try to implement it inside a function, the argument you receive will be null if the variable doesn't exist and a E_NOTICE error will be raised before your function is even called.

Title: Implementing isset() in a setter method


问:
Autofilter excel using java poi
I am trying to filter an excel sheet using POI class and to set the filter when i used this :

CTAutoFilter sheetFilter = my_sheet.getCTWorksheet().getAutoFilter();

CTFilterColumn myFilterColumn = sheetFilter.insertNewFilterColumn(0);

got below mentioned error on "CTFilterColumn".
Multiple markers at this line
    - The method insertNewFilterColumn(int) from the type CTAutoFilter refers to the
     missing type CTFilterColumn
    - The type org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFilterColumn
     cannot be resolved. It is indirectly referenced from required .class files
    - CTFilterColumn cannot be resolved to a type

Entire code :

```<code>import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.ss.usermodel.ComparisonOperator;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTAutoFilter;

public class Test1 {

    public static void main(String[] args) {
        try {
            //To read values and enable auto filter
            FileInputStream fileIn = new FileInputStream("./XMLs/Test001.xlsx");

            XSSFWorkbook my_workbook = new XSSFWorkbook(fileIn);

            XSSFSheet my_sheet = my_workbook.getSheet("Sheet1");
            CTAutoFilter sheetFilter = my_sheet.getCTWorksheet().getAutoFilter();

            CTFilterColumn myFilterColumn = sheetFilter.insertNewFilterColumn(0);
</code>```

Instead of this "import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTAutoFilter;" i tried import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;

But CTFilterColumn is not even listed in suggestions. Please help.

Is it because of some missing jar files, please help.

答:
Promoting a comment to an answer

This is covered in this Apache POI FAQ Entry -  I'm using the poi-ooxml-schemas jar, but my code is failing with "java.lang.NoClassDefFoundError: org/openxmlformats/schemas/something". The key section is:

There are two jar files available, as described in the components overview section. The full jar of all of the schemas is ooxml-schemas-1.3.jar, and it is currently around 15mb. The smaller poi-ooxml-schemas jar is only about 4mb. This latter jar file only contains the typically used parts though.

Many users choose to use the smaller poi-ooxml-schemas jar to save space. However, the poi-ooxml-schemas jar only contains the XSDs and classes that are typically used, as identified by the unit tests. Every so often, you may try to use part of the file format which isn't included in the minimal poi-ooxml-schemas jar. In this case, you should switch to the full ooxml-schemas-1.3.jar. Longer term, you may also wish to submit a new unit test which uses the extra parts of the XSDs, so that a future poi-ooxml-schemas jar will include them.

So, short term you need to swap out your small poi-ooxml-schemas jar for the full ooxml-schemas-1.3 jar. Longer term, if you submit a unit test to Apache POI which uses these extra classes, it'll be included in a future small schema jar.

Maven artifact details for the full schema are covered here on the Apache POI site

Title: Autofilter excel using java poi

Body:
I am trying to filter an excel sheet using POI class and to set the filter when i used this :

CTAutoFilter sheetFilter = my_sheet.getCTWorksheet().getAutoFilter();

CTFilterColumn myFilterColumn = sheetFilter.insertNewFilterColumn(0);

got below mentioned error on "CTFilterColumn".
Multiple markers at this line
    - The method insertNewFilterColumn(int) from the type CTAutoFilter refers to the
     missing type CTFilterColumn
    - The type org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFilterColumn
     cannot be resolved. It is indirectly referenced from required .class files
    - CTFilterColumn cannot be resolved to a type

Entire code :

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.ss.usermodel.ComparisonOperator;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTAutoFilter;

public class Test1 {

    public static void main(String[] args) {
        try {
            //To read values and enable auto filter
            FileInputStream fileIn = new FileInputStream("./XMLs/Test001.xlsx");

            XSSFWorkbook my_workbook = new XSSFWorkbook(fileIn);

            XSSFSheet my_sheet = my_workbook.getSheet("Sheet1");
            CTAutoFilter sheetFilter = my_sheet.getCTWorksheet().getAutoFilter();

            CTFilterColumn myFilterColumn = sheetFilter.insertNewFilterColumn(0);

Instead of this "import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTAutoFilter;" i tried import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;

But CTFilterColumn is not even listed in suggestions. Please help.

Is it because of some missing jar files, please help.


问:
I am trying to call on a text input with javascript
I am trying to check to make sure a form is complete, here is a piece of my code
checking the password

function checkpass()
{

    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');

    var message = document.getElementById('confirmMessage');

    var goodColor = "#66cc66";
    var badColor = "#ff6666";

    if(pass1.value == pass2.value){

        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords Match!"
    }else{

        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords Do Not Match!"
    }
}  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label >Password:</label>
            <input type="password" name="pass1" id="pass1">
      <p></p>

        <label >Verify Password:</label>
        <input type="password" name="pass2" id="pass2" onBlur="checkpass()">
<span id="confirmMessage" class="confirmMessage"></span></code>```

this works, but when I try to do something similar with the name input it does not work

```<code> <input type="text" name="name1" id="name1" onblur="checkname">
 <label>First Name</label>
function checkname(){var name1 = document.getElementById('name1');if (name1 == null) {alert('entername');}}
</code>```

If you have can tell me a simple error I have made that makes me look like a idiot that would be great, or if you could tell me a better way to do the whole thing that would also be great.
Any help you can offer will be much appreciated.

答:
```<code>var name1 = document.getElementById('name1')
</code>```

You forgot the .value at the end

```<code>var name1 = document.getElementById('name1').value
</code>```

Body:
I am trying to check to make sure a form is complete, here is a piece of my code
checking the password

function checkpass()
{

    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');

    var message = document.getElementById('confirmMessage');

    var goodColor = "#66cc66";
    var badColor = "#ff6666";

    if(pass1.value == pass2.value){

        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords Match!"
    }else{

        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords Do Not Match!"
    }
}

Password:
            <input type="password" name="pass1" id="pass1">

        Verify Password:
        <input type="password" name="pass2" id="pass2" onBlur="checkpass()">

this works, but when I try to do something similar with the name input it does not work

 <input type="text" name="name1" id="name1" onblur="checkname">
 First Name
function checkname(){var name1 = document.getElementById('name1');if (name1 == null) {alert('entername');}}

If you have can tell me a simple error I have made that makes me look like a idiot that would be great, or if you could tell me a better way to do the whole thing that would also be great.
Any help you can offer will be much appreciated.

Body:
var name1 = document.getElementById('name1')

You forgot the .value at the end

var name1 = document.getElementById('name1').value


问:
On-premise AD sync with azure active directory using Azure connect DirSync
If we do on-premise AD sync with azure active directory using Azure connect DirSync and do not select password synchronization then

how the user will login in office 365?

what will be the credential for user?

答:
If you don't use Password Synchronization, Azure AD cannot authenticate the user by itself.

In this scenario, you would have an Active Directory Federation Services server that does the final authentication.

Users will go to the login page and enter their username. They will then be redirected to your ADFS login page. After successful authentication, they will be redirected back to Azure AD, which will redirect them to the app they were signing in to (O365 for example).

The users will use the username that they get in Azure AD, which should be the same as the on-prem one.

Documentation: Azure AD Connect and federation

Another option would be to use Pass-through Authentication: https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-pass-through-authentication.

This would have the users login with their credentials on the Azure AD login page, and Azure AD would check the credentials with your on-prem AD in the background, without redirecting the user to ADFS.


问:
Increment html input number element
I have an input element

```<code><input type="number" min=0.083 step=0.5>
</code>```

I want to increment it with 0.5 when the up and down arrows are pressed in the input element and on the keyboard.

min needs to be at 0.083. But of course this can be checked in a input/changed event for the input field.

I want

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.8

2 + step = 2.5

0.5 - step = 0.083

But what I get is

0 + step = 0.083

0.083 + step = 0.583

1.3 + step = 1.583

2 + step = 2.083

0.5 - step = 0.083

With min = 0

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.5 //which is not what I want. I need it to be 1.8

https://jsfiddle.net/6eL64umx/1/

Any help is appreciated :)

答: <input type="number" class="cn" min=0 step=0.5>```

Title: Increment html input number element

Body:
I have an input element

<input type="number" min=0.083 step=0.5>

I want to increment it with 0.5 when the up and down arrows are pressed in the input element and on the keyboard.

min needs to be at 0.083. But of course this can be checked in a input/changed event for the input field.

I want

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.8

2 + step = 2.5

0.5 - step = 0.083

But what I get is

0 + step = 0.083

0.083 + step = 0.583

1.3 + step = 1.583

2 + step = 2.083

0.5 - step = 0.083

With min = 0

0 + step = 0.5

0.5 + step = 1

1.3 + step = 1.5 //which is not what I want. I need it to be 1.8

https://jsfiddle.net/6eL64umx/1/

Any help is appreciated :)


问:
Best practice boolean logic multiple not equal to
When writing a boolean statement with multiple 'not equal to' clauses I believe there are two potential syntaxes for achieving this, both of which are functionally equivalent. c# example:

1.

```<code>x != 1 && y != 1
</code>```

2.

```<code>!(x == 1 || y == 1)
</code>```

For the sake of being consistent and deciding on a best practice, are there any clear advantages/disadvantages to either?

Thanks

答:
Logically, these two forms are completely equal according to De Morgan's laws.

You should just decide what makes more sense according to your problem's nature, and what will be easier for other programmers to understand.

Body:
When writing a boolean statement with multiple 'not equal to' clauses I believe there are two potential syntaxes for achieving this, both of which are functionally equivalent. c# example:

1.

x != 1 && y != 1

2.

!(x == 1 || y == 1)

For the sake of being consistent and deciding on a best practice, are there any clear advantages/disadvantages to either?

Thanks


答:
Just try like this

```<code><input type="text" name="name1" id="name1" onblur="checkname">
<label>First Name</label>

function checkname()
{
     var name1 = document.getElementById('name1').value;
     if (name1 == null || name1 == "")
     {
        alert('entername');
     }
}
</code>```

You have miss the value when you selecting the attribute using id

Title: I am trying to call on a text input with javascript

Body:
Just try like this

<input type="text" name="name1" id="name1" onblur="checkname">
<label>First Name</label>

function checkname()
{
     var name1 = document.getElementById('name1').value;
     if (name1 == null || name1 == "")
     {
        alert('entername');
     }
}

You have miss the value when you selecting the attribute using id


问:
How to write C program without 'main'?
How to write C program without using Main...!
When I'm learning how to write ASM file by for a simple C file [of length 3 lines], I got this doubt.
I assembly file I used preamble and post ambles, at function. </p>

答:
Here is your answer:-></p>

```<code>#include <stdio.h>

extern void _exit(register int);

int _start(){

printf(“Hello World\n”);

_exit(0);

}
</code>```

Title: How to write C program without 'main'?

Body:
Here is your answer:->

#include <stdio.h>

extern void _exit(register int);

int _start(){

printf(“Hello World\n”);

_exit(0);

}


问:
select grandparent in css
i have an html code like this

```<code><div class="main-container">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar"> </div>
        </div>
     </div>
   </div>
</div>
</code>```

i've tried to change the main-container background if it has toolbar descendant, ive tried like this :

```<code> .main-container > .main .col-main .category-products .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

.main-container >  .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}
</code>```

but nothing works

答:
First of all you can't traverse backwards with css. So you have to resort to javascript or find some other way.

IF however .main-container didn't have any children (or any other content) you could style it like this:

.main-container {
  height: 200px;
  background: tomato;
  margin-bottom: 1rem;
}

.main-container:not(:empty){
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-container" data-toolbaar="yes">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar"> HELLO</div>
        </div>
     </div>
   </div>
</div>

<!-- EMPTY -->
<div class="main-container" data-toolbaar="yes"></div></code>```

Title: select grandparent in css

Body:
i have an html code like this

i've tried to change the main-container background if it has toolbar descendant, ive tried like this :

 .main-container > .main .col-main .category-products .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

.main-container >  .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

but nothing works

Body:
First of all you can't traverse backwards with css. So you have to resort to javascript or find some other way.

IF however .main-container didn't have any children (or any other content) you could style it like this:

.main-container {
  height: 200px;
  background: tomato;
  margin-bottom: 1rem;
}

.main-container:not(:empty){
  background: blue;
}

<div class="main-container" data-toolbaar="yes">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar"> HELLO</div>
        </div>
     </div>
   </div>
</div>

<!-- EMPTY -->
<div class="main-container" data-toolbaar="yes"></div>


问:
How to list all tables in database using Spark SQL?
I have a SparkSQL connection to an external database:

```<code>from pyspark.sql import SparkSession

spark = SparkSession \
  .builder \
  .appName("Python Spark SQL basic example") \
  .getOrCreate()
</code>```

If I know the name of a table, it's easy to query.

```<code>users_df = spark \
  .read.format("jdbc") \
  .options(dbtable="users", **db_config) \
  .load()
</code>```

But is there a good way to list/discover tables?

I want the equivalent of SHOW TABLES in mysql, or \dt in postgres.

I'm using pyspark v2.1, in case that makes any difference.

答:
The answer to this question isn't actually spark specific. You'll just need to load the information_schema.tables.

The information schema consists of a set of views that contain information about the objects defined in the current database. The information schema is defined in the SQL standard and can therefore be expected to be portable and remain stable — unlike the system catalogs, which are specific to RDBMS and are modelled after implementation concerns.

I'll be using MySQL for my code snippet which contains a enwiki database on which I want to list tables :

# read the information schema table
spark.read.format('jdbc'). \
     options(
         url='jdbc:mysql://localhost:3306/', # database url (local, remote)
         dbtable='information_schema.tables',
         user='root',
         password='root',
         driver='com.mysql.jdbc.Driver'). \
     load(). \
     filter("table_schema = 'enwiki'"). \ # filter on specific database.
     show()
# +-------------+------------+----------+----------+------+-------+----------+----------+--------------+-----------+---------------+------------+----------+--------------+--------------------+-----------+----------+---------------+--------+--------------+-------------+
# |TABLE_CATALOG|TABLE_SCHEMA|TABLE_NAME|TABLE_TYPE|ENGINE|VERSION|ROW_FORMAT|TABLE_ROWS|AVG_ROW_LENGTH|DATA_LENGTH|MAX_DATA_LENGTH|INDEX_LENGTH| DATA_FREE|AUTO_INCREMENT|         CREATE_TIME|UPDATE_TIME|CHECK_TIME|TABLE_COLLATION|CHECKSUM|CREATE_OPTIONS|TABLE_COMMENT|
# +-------------+------------+----------+----------+------+-------+----------+----------+--------------+-----------+---------------+------------+----------+--------------+--------------------+-----------+----------+---------------+--------+--------------+-------------+
# |          def|      enwiki|      page|BASE TABLE|InnoDB|     10|   Compact|   7155190|           115|  828375040|              0|   975601664|1965031424|      11359093|2017-01-23 08:42:...|       null|      null|         binary|    null|              |             |
# +-------------+------------+----------+----------+------+-------+----------+----------+--------------+-----------+---------------+------------+----------+--------------+--------------------+-----------+----------+---------------+--------+--------------+-------------+
```

Note: This solution can be applied to the scala and java with respectful languages constraints.

Body:
I have a SparkSQL connection to an external database:

from pyspark.sql import SparkSession

spark = SparkSession \
  .builder \
  .appName("Python Spark SQL basic example") \
  .getOrCreate()

If I know the name of a table, it's easy to query.

users_df = spark \
  .read.format("jdbc") \
  .options(dbtable="users", **db_config) \
  .load()

But is there a good way to list/discover tables?

I want the equivalent of SHOW TABLES in mysql, or \dt in postgres.

I'm using pyspark v2.1, in case that makes any difference.

Body:
The answer to this question isn't actually spark specific. You'll just need to load the information_schema.tables.

The information schema consists of a set of views that contain information about the objects defined in the current database. The information schema is defined in the SQL standard and can therefore be expected to be portable and remain stable — unlike the system catalogs, which are specific to RDBMS and are modelled after implementation concerns.

I'll be using MySQL for my code snippet which contains a enwiki database on which I want to list tables :

# read the information schema table
spark.read.format('jdbc'). \
     options(
         url='jdbc:mysql://localhost:3306/', # database url (local, remote)
         dbtable='information_schema.tables',
         user='root',
         password='root',
         driver='com.mysql.jdbc.Driver'). \
     load(). \
     filter("table_schema = 'enwiki'"). \ # filter on specific database.
     show()
# +-------------+------------+----------+----------+------+-------+----------+----------+--------------+-----------+---------------+------------+----------+--------------+--------------------+-----------+----------+---------------+--------+--------------+-------------+
# |TABLE_CATALOG|TABLE_SCHEMA|TABLE_NAME|TABLE_TYPE|ENGINE|VERSION|ROW_FORMAT|TABLE_ROWS|AVG_ROW_LENGTH|DATA_LENGTH|MAX_DATA_LENGTH|INDEX_LENGTH| DATA_FREE|AUTO_INCREMENT|         CREATE_TIME|UPDATE_TIME|CHECK_TIME|TABLE_COLLATION|CHECKSUM|CREATE_OPTIONS|TABLE_COMMENT|
# +-------------+------------+----------+----------+------+-------+----------+----------+--------------+-----------+---------------+------------+----------+--------------+--------------------+-----------+----------+---------------+--------+--------------+-------------+
# |          def|      enwiki|      page|BASE TABLE|InnoDB|     10|   Compact|   7155190|           115|  828375040|              0|   975601664|1965031424|      11359093|2017-01-23 08:42:...|       null|      null|         binary|    null|              |             |
# +-------------+------------+----------+----------+------+-------+----------+----------+--------------+-----------+---------------+------------+----------+--------------+--------------------+-----------+----------+---------------+--------+--------------+-------------+

Note: This solution can be applied to the scala and java with respectful languages constraints.

ContentLicense: CC BY-SA 4.0


问:
How do I see the remote device connected to my PC?
I have an MT2070 scanner, and when I connect it to my PC using a USB cable, I can see all the files and folders on the scanner (I have ActiveScan installed). However, unlike when I connect a CD ROM drive, there is no letter association (its not the D drive or E drive, etc).

My goal here is to write a simple BAT file that copies a file from the PC to the device. But from a DOS prompt, I cannot manually copy a file to this device because I don't know what to call it. I don't know the proper syntax. It's not like a network drive either, because it doesn't have any IP address. When I open Windows Explorer, it is simply called "Mobile Device". Please advise, what is the simplest way to write a script to copy a file to this device?

答:
normally USB devices implement multiple functionalities (USB device classes) by multiple descriptors. A smartphone with tethering function i.e. implements USB mass storage class and USB CDC class (RNDIS device,...)  . normally you can switch between the interfaces using some commands on the device (on an android phone switch on the tethering).

In the User Guide on page 262 ff ( https://www.zebra.com/content/dam/zebra_new_ia/en-us/manuals/barcode-scanners/mt2000-mt2070-mt2090-user-guide-a-us.pdf ) are listed the USB device classes that the MT2070 implements, this includes USB CDC ACM (Virtual COM port) and HID class (Human Interface Device). The virtual COM port is also a possible interface to the internal file system of the scanner. How USB interface switching works for the MT2070 is in the User Guide on page 265 ff

The USB interface of the scanner has to be configured, see User Guide page 146 ff on this.

The recommended way to access the internal file system of the  MT2070 over USB is to use ActiveSync (first the USB interface has to be configured). When the connection is established the VB programs like the ScanItem or ScanInventory can be modified , this is in the UserGuide Quick Startup Exercise on pages 473 - 478

complete explanation of the connecting process is on http://www.jmmsoftware.com/Documentation/MT2070/MT2070_Manual_rev_2011-11-02.pdf (includes Mobile Device Center)

https://msdn.microsoft.com/en-us/library/windows/hardware/ff538820(v=vs.85).aspx

If your device shows up as 'Mobile Device' in Windows Explorer it is connected via MTP or a similar protocol ( https://en.wikipedia.org/wiki/Media_Transfer_Protocol ). To copy files over MTP (or a similar protocol like i.e. PTP) by code you have to use the Windows Portable Devices API


问:
Linux system to manage configurations of servers?
I need a software to manage configurations of linux servers in one central location. It should be able to push changes to servers automaticly. Version control would be an advantage...</p>

答: I've heard good things about Puppet (as matli suggested) and Cfengine, which are both listed at http://en.wikipedia.org/wiki/Comparison_of_open_source_configuration_management_software</p>

OwnerDisplayName: Philip Durbin