问:
What is the appropriate syntax to separate multiple values in a LDAP multi-valued attribute?
This question is related to Convert a Base64 LDIF file to plaintext (for import) .

A LDAP I'm using has some attributes containing multiple values. E.g. foobarStatus has the following value:

```<code>market = "US"
mgmt.account.mode = "X12"
foo.field = "Something"
bar.field = "Something else"
</code>```

(When this attribute is added or modified via a LDIF file, this value is imported encoded in Base64.)

Using Ldapadmin (a LDAP GUI client) to examine the entry shows the value of this attribute as such:

```<code>market = "US"mgmt.account.mode = "X12"foo.field = "Something"bar.field = "Something else"
</code>```

which made me think about the question in the title: What is the appropriate syntax to separate multiple values in a LDAP multi-valued attribute?

答:
IF I understand what you are trying to perform.

You do not use a separator to implement multiple values within LDAP/LDIF.
Each attribute is a container for value(s).

So IF I understand what you are trying to perform a LDIF something like this should work:

```<code>dn: cn=johndoe,ou=clients,ou=management,dc=example,dc=com
changetype: modify
delete: foobarStatus
-
add:foobarStatus
foobarStatus: market = "US"
foobarStatus: mgmt.account.mode = "X12"
foobarStatus: foo.field = "Something"
foobarStatus: bar.field = "Something else"
</code>```

Also keep in mind:

there are some characters that either need escaped within LDIF operations

there can NOT be any spaces at the end of a value

or the values will be base64 encoded.

Body:
This question is related to Convert a Base64 LDIF file to plaintext (for import) .

A LDAP I'm using has some attributes containing multiple values. E.g. foobarStatus has the following value:

market = "US"
mgmt.account.mode = "X12"
foo.field = "Something"
bar.field = "Something else"

(When this attribute is added or modified via a LDIF file, this value is imported encoded in Base64.)

Using Ldapadmin (a LDAP GUI client) to examine the entry shows the value of this attribute as such:

market = "US"mgmt.account.mode = "X12"foo.field = "Something"bar.field = "Something else"

which made me think about the question in the title: What is the appropriate syntax to separate multiple values in a LDAP multi-valued attribute?

Body:
IF I understand what you are trying to perform.

You do not use a separator to implement multiple values within LDAP/LDIF.
Each attribute is a container for value(s).

So IF I understand what you are trying to perform a LDIF something like this should work:

dn: cn=johndoe,ou=clients,ou=management,dc=example,dc=com
changetype: modify
delete: foobarStatus
-
add:foobarStatus
foobarStatus: market = "US"
foobarStatus: mgmt.account.mode = "X12"
foobarStatus: foo.field = "Something"
foobarStatus: bar.field = "Something else"

Also keep in mind:

there are some characters that either need escaped within LDIF operations

there can NOT be any spaces at the end of a value

or the values will be base64 encoded.


来源: stackexchange

问:
python3 error when passing variable into os.chdir
I am trying to find a specific pathname and pass this into os.chdir so I can run a command in that directory. I won't know the exact pathname hence why I have to run the find command. I have tried several ways to do this and each comes with a new error. The code below is one of the ways I have tried, can anyone suggest the best way to do this? Or how to fix this error?

Source Code:

```<code>import os
import subprocess

os.system('find ~ -path "*MyDir" > MyDir.txt')

output = subprocess.check_output("cat MyDir.txt", shell=True)

os.chdir(output)

os.system("file * > MyDir/File.txt")
</code>```

The error:

```<code>Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'
</code>```

I know that directory exists and presume it has something to do with the b' and \n'. I just don't know what the problem is.

答:
Get rid of the \n with strip:

```<code>output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find a specific pathname and pass this into os.chdir so I can run a command in that directory. I won't know the exact pathname hence why I have to run the find command. I have tried several ways to do this and each comes with a new error. The code below is one of the ways I have tried, can anyone suggest the best way to do this? Or how to fix this error?

Source Code:

import os
import subprocess

os.system('find ~ -path "*MyDir" > MyDir.txt')

output = subprocess.check_output("cat MyDir.txt", shell=True)

os.chdir(output)

os.system("file * > MyDir/File.txt")

The error:

Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'

I know that directory exists and presume it has something to do with the b' and \n'. I just don't know what the problem is.

Body:
Get rid of the \n with strip:

output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)


问:
how to select all booleancheckbox using jsf primefaces?
ok guys, i know theres another related question like mine, but i ve tried that solution but still not work at all. heres my jsf

```<code><h:form id="store-news-check">
                    <ul style="list-style: none;padding:5px;margin-top:0px">
                        <ui:repeat value="#{dashboardBean.storeNewsList}" var="item" varStatus="status">
                            <li style="display:inline-flex;width: 100%;margin-bottom: 5px">
                                <p:selectBooleanCheckbox value="#{item.cmsCheck}" style="margin-bottom:0px" />
                                <a href="#" style="color:#333"><span class="task-name">#{item.storeId.name} - ${fn:substring(item.title,0, 10)} ....</span></a>
                            </li>
                        </ui:repeat>
                    </ul>

                    <p:commandButton actionListener="#{dashboardBean.selectAllNews()}" value="Select All" update="@form" icon="ui-icon-send" style="border-radius:3px 0px 0px 3px"/>
                    <p:commandButton value="Save" icon="ui-icon-send" style="border-radius:0px 3px 3px 0px"/>
                </h:form>
</code>```

and heres my backing bean

```<code>@PostConstruct
    public void init() {
        storeNewsList = storeNewsFacade.findStoreNewsDashbroad();

    }

private List<StoreNews> storeNewsList;

    public List<StoreNews> getStoreNewsList() {

            return storeNewsList;

        }

    public void selectAllNews(){
            for(StoreNews sn:storeNewsList){
                sn.setCmsCheck(true);
            }

            infoMessage("check all store news");
        }
</code>```

hope you guys can help me, thanks !

答:
I'd say you just need to update the checkboxes. For example with

```<code><p:commandButton actionListener="#{dashboardBean.selectAllNews()}" update="@form" ... />
</code>```

Also type="button" on the save-button seems not right.

Body:
ok guys, i know theres another related question like mine, but i ve tried that solution but still not work at all. heres my jsf

<h:form id="store-news-check">

                        <ui:repeat value="#{dashboardBean.storeNewsList}" var="item" varStatus="status">

                                #{item.storeId.name} - ${fn:substring(item.title,0, 10)} ....

                        </ui:repeat>

                </h:form>

and heres my backing bean

@PostConstruct
    public void init() {
        storeNewsList = storeNewsFacade.findStoreNewsDashbroad();

    }

private List<StoreNews> storeNewsList;

    public List<StoreNews> getStoreNewsList() {

            return storeNewsList;

        }

    public void selectAllNews(){
            for(StoreNews sn:storeNewsList){
                sn.setCmsCheck(true);
            }

            infoMessage("check all store news");
        }

hope you guys can help me, thanks !

Body:
I'd say you just need to update the checkboxes. For example with

<p:commandButton actionListener="#{dashboardBean.selectAllNews()}" update="@form" ... />

Also type="button" on the save-button seems not right.


问:
overflow auto on child div
I have a structure that is similar to modal windows and it looks like this:

.pos_container {
  display:block;
  vertical-align:top;
  width:70%;
  height:auto;
  margin:auto;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  border:1px solid #ddd;
  position:relative;
  top:5%;
  max-height:90%;
  overflow:hidden;
 }
 .pos_header {
  display:block;
  vertical-align:top;
  padding:15px 20px;
  background:#f7f7f7;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom:1px solid #ddd;

 }
 .pos_body {
  display:block;
  vertical-align:top;
  padding:10px 20px;
  background:#fff;
  overflow-y:auto;
  height:100%;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="pos_container">
  <div class="pos_header">
   // SOME CONTENT HERE, ALWAYS HAS FIXED HEIGHT
  </div>
  <div class="pos_body">
   // CONTENT IN HERE CAN BE VARIOUS HEIGHT, NEED AUTO-SCROLL
  </div>
 </div></code>```

I've searched the internet and always there is a rule to set the height of .pos_body to fixed height, but I need it to fit the visible part of .pos_container and in case content of .pos_body is overlapping the .pos_container then scroll will appear

答:
try with a flex container

.pos_container {
  vertical-align:top;
  width:70%;
  height:auto;
  margin:auto;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  border:1px solid #ddd;
  position:relative;
  top:5%;
  max-height:100px;
  overflow:hidden;
    display: flex;
    flex-direction: column;
 }
 .pos_header {
  display:block;
  vertical-align:top;
  padding:15px 20px;
  background:#f7f7f7;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom:1px solid #ddd;

 }
 .pos_body {
  vertical-align:top;
  padding:10px 20px;
  background:#fff;
  overflow-y:auto;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pos_container">
  <div class="pos_header">
   // SOME CONTENT HERE, ALWAYS HAS FIXED HEIGHT
  </div>
  <div class="pos_body">
   // CONTENT IN HERE CAN BE VARIOUS HEIGHT,
      fewfew few<br>
      fe<br>
      fwef<br>
      fwefeweNEED AUTO-SCROLL
  </div>
 </div></code>```

Title: overflow auto on child div

Body:
I have a structure that is similar to modal windows and it looks like this:

.pos_container {
  display:block;
  vertical-align:top;
  width:70%;
  height:auto;
  margin:auto;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  border:1px solid #ddd;
  position:relative;
  top:5%;
  max-height:90%;
  overflow:hidden;
 }
 .pos_header {
  display:block;
  vertical-align:top;
  padding:15px 20px;
  background:#f7f7f7;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom:1px solid #ddd;

 }
 .pos_body {
  display:block;
  vertical-align:top;
  padding:10px 20px;
  background:#fff;
  overflow-y:auto;
  height:100%;
 }

   // SOME CONTENT HERE, ALWAYS HAS FIXED HEIGHT

   // CONTENT IN HERE CAN BE VARIOUS HEIGHT, NEED AUTO-SCROLL

I've searched the internet and always there is a rule to set the height of .pos_body to fixed height, but I need it to fit the visible part of .pos_container and in case content of .pos_body is overlapping the .pos_container then scroll will appear

Body:
try with a flex container

.pos_container {
  vertical-align:top;
  width:70%;
  height:auto;
  margin:auto;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  border:1px solid #ddd;
  position:relative;
  top:5%;
  max-height:100px;
  overflow:hidden;
    display: flex;
    flex-direction: column;
 }
 .pos_header {
  display:block;
  vertical-align:top;
  padding:15px 20px;
  background:#f7f7f7;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom:1px solid #ddd;

 }
 .pos_body {
  vertical-align:top;
  padding:10px 20px;
  background:#fff;
  overflow-y:auto;
 }

<div class="pos_container">
  <div class="pos_header">
   // SOME CONTENT HERE, ALWAYS HAS FIXED HEIGHT
  </div>
  <div class="pos_body">
   // CONTENT IN HERE CAN BE VARIOUS HEIGHT,
      fewfew few<br>
      fe<br>
      fwef<br>
      fwefeweNEED AUTO-SCROLL
  </div>
 </div>


问:
WWF or WPF for flowcharts?
I want to be able to present my data using a flowchart. I can use wpf to do this, but I dont want to have to code all the arrows, connectors etc - I would like to use a library if possible..

Also could I use windows workflow foundation to do this in any way? Would this help? I get the impression although WWF is workflow, its more to do with the process as opposed to presenting data.

It appears that I might have to obtain a third party control to do this....any recommendations - the component should be able to draw a flowchart at the minimum!

Thanks

答: If your not creating a work flow then stick with WPF and take a look at http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part4.aspx this code project article should give you a healthy starting point for what you want to do.</p>

ContentLicense: CC BY-SA 2.5

Title: WWF or WPF for flowcharts?


问:
How to encrypt admin password?
In my java web app, admin account will create user account, where the password will be encrypted, using StandardPasswordEncoder class, that's easy. But how to encrypt the admin password, which i already stored in MySQL database?

答:
how to encrypt the admin password, which i already stored in mysql
  database?

You can edit your password :

```<code>UPDATE table_name SET pass = MD5(pass);
-- --------------------------^^^-------
-- This can be any Standard encryption algorithm, you can check the link above
</code>```

You can take a look about Encryption and Compression Functions

how if i only want to encrypt only the admin password? the other users
  password will be encrypted by admin in java controller class.

You can mark your password like a master admin for example you can add a column in your table that make difference between the admin and the ordinary users, consider you have a big enterprise in this case one admin account is not enough, you need many admin accounts, and in base of this column you can encrypt the admin account with an algorithm and the others with another algorithm.

Encrypt password using SHA-256

I managed to encrypt the admin password, but i can't log in to my web
  app coz the StandardPasswordEncoder class in the web app is using
  SHA-256 hashing algorithm

SHA-256 != MD5, this is clear so you have to use the same algothm in the both side code and database, in your case you are using SHA-256 i assume you are using a function like this :

CODE

```<code>public static String sha256(String base) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}
</code>```

This will encrypt admin like this :

```<code>admin = 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918
</code>```

DATABASE

So in your database you have to encrypt your password like this :

```<code>SELECT SHA2('admin', 256);
</code>```

The update query should look like this :

```<code>UPDATE table_name SET pass = SHA2(pass, 256) WHERE admin_master = true;
-- -------------Field to check if it is admin or not ---^
</code>```

So when you try to log in you have to check if it is admin or not, if admin encrypt your password with SHA-256 and check if the user exist or not, else if the user is ordanary user, check with your previouse algorithm.

Hope this can give you an idea.

Title: How to encrypt admin password?

Body:
how to encrypt the admin password, which i already stored in mysql
  database?

You can edit your password :

UPDATE table_name SET pass = MD5(pass);
-- --------------------------^^^-------
-- This can be any Standard encryption algorithm, you can check the link above

You can take a look about Encryption and Compression Functions

how if i only want to encrypt only the admin password? the other users
  password will be encrypted by admin in java controller class.

You can mark your password like a master admin for example you can add a column in your table that make difference between the admin and the ordinary users, consider you have a big enterprise in this case one admin account is not enough, you need many admin accounts, and in base of this column you can encrypt the admin account with an algorithm and the others with another algorithm.

Encrypt password using SHA-256

I managed to encrypt the admin password, but i can't log in to my web
  app coz the StandardPasswordEncoder class in the web app is using
  SHA-256 hashing algorithm

SHA-256 != MD5, this is clear so you have to use the same algothm in the both side code and database, in your case you are using SHA-256 i assume you are using a function like this :

CODE

public static String sha256(String base) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

This will encrypt admin like this :

admin = 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

DATABASE

So in your database you have to encrypt your password like this :

SELECT SHA2('admin', 256);

The update query should look like this :

UPDATE table_name SET pass = SHA2(pass, 256) WHERE admin_master = true;
-- -------------Field to check if it is admin or not ---^

So when you try to log in you have to check if it is admin or not, if admin encrypt your password with SHA-256 and check if the user exist or not, else if the user is ordanary user, check with your previouse algorithm.

Hope this can give you an idea.


问:
How do I go from one html page to another using onclick attribute in an html form
This is the code below and I would like to know what to type in the onclick attribute in the HTML form, so that I can go from one page to another.

```<code><form class="login-container" action="/var/www/html/upload.php" method="post" enctype="multipart/form-data">
    <p>
    Select Image<input type="file" onchange="previewFile()" class="imageupload" name="image" id="image" placeholder="Select Image"/>
    <br/>
    <img src="" height="200" alt="Image preview..."/>
    <br/>
    <input type="number" min="1" name="quantity" placeholder="Quantity"/>
    <br/>
    <textarea rows="5" cols="40"placeholder="describe how you want the picture to be done"></textarea>
    <br/>
    <input type="submit" value="Next" onclick=" "/></p>
</form>
</code>```

答:
When you click on submit button all will be post on upload.php here you insert your data into database table.
After successfully insertion of data write below code to redirect to another page which page you want to open on button click.

header('location:page2.php');

Body:
This is the code below and I would like to know what to type in the onclick attribute in the HTML form, so that I can go from one page to another.

<form class="login-container" action="/var/www/html/upload.php" method="post" enctype="multipart/form-data">

    Select Image<input type="file" onchange="previewFile()" class="imageupload" name="image" id="image" placeholder="Select Image"/>

    <input type="number" min="1" name="quantity" placeholder="Quantity"/>

    <textarea rows="5" cols="40"placeholder="describe how you want the picture to be done"></textarea>

    <input type="submit" value="Next" onclick=" "/>

</form>


问:
understanding some concepts in java generics
So I came across this code while studying linkedlists. The code here uses generics and I am having problem understanding some of the things here.

```<code>public static class Node<E>
{
     E element;
     Node <E> next;
    public Node(E e,Node <E> n)
    {
        element=e;
        next=n;System.out.println(next);
    }
    public E getelement() {return element;}
    public Node<E> getnext(){ return next;}
    public void setnext(Node <E> n)
    {
        next=n;
    }
}
</code>```

So what does class Node <E> mean?
I think E element; means  element is of type E. Am I right?
Node <E> next; what does this mean?

答:
You can easily find official docs and many other resources for such a big topic in Java, I'll try to explain it by "the process of re-creating generics".

Say you're going to implement the class Node given in the question, it's a basic building unit for LinkedList, so you define it as:

```<code>class Node {
    private Node next;

    public Node getNext() {
        return next;
    }

    public void setNext(Node n) {
        next = n;
    }
}
</code>```

but you need to store some data in each Node, don't you, otherwise this class is useless. Obviously one more field is necessary and the type you want to store is MyData, then it'll be:

```<code>class Node {
    private MyData element;
    private Node next;

    public Node getNext() {
        return next;
    }

    public MyData getElement() {
        return element;
    }

    public void setElement(MyData element) {
        this.element = element;
    }

    public void setNext(Node n) {
        next = n;
    }
}
</code>```

One day you want to make your implementation a common library so it can be used by anyone, but one serious problem comes up which is people will not happy with that they can only store data of type MyData in your Node, they want to store whatever type they want, so you made a little change - declare the type of element to Object so that it can handle any type:

```<code>class Node {
    private Object element;
    private Node next;

    public Node getNext() {
        return next;
    }

    public Object getElement() {
        return element;
    }

    public void setElement(Object element) {
        this.element = element;
    }

    public void setNext(Node n) {
        next = n;
    }
}
</code>```

Everything's good now, but some time later you receive some feedbacks from some picky users:

User A: everywhere I call Node.getElement() in my code, I get an Object type stuff and I need to do a type cast, which is inconvenient, it would be better if what I get from getElement is the type I want

User B: I want to only store type A but there's no way to prevent me put a type B into Node, I can't find this bug till exception happens during runtime, it would be better that compiler can help me to find the bug

So you feel that it'll be great if you can leave the decision of what type of data is allowed to put in Node to users, rather than hardcoded in implementation, which means what you'll put at the underscore of the statement private ___ element; is uncertain, you need it be a variable and specified by the user at the moment they use it, so a variable to the class, that's good, but you need a place to declare the variable before you can use it, finally you decide to put the declaration of the variable right after the class name, inside <>(a new syntax), then the code will be:

```<code>class Node<E> {
    private E element;
    private Node next;

    public E getElement() {
        return element;
    }

    public void setElement(E element) {
        this.element = element;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node n) {
        next = n;
    }
}
</code>```

almost done but wait: you're using Node by yourself - the field next, you need to follow the rule you just made: pass type info of element to Node at the time when you use it, so finally you got the code following:

```<code>class Node<E> {
    private E element;
    private Node<E> next;

    public E getElement() {
        return element;
    }

    public void setElement(E element) {
        this.element = element;
    }

    public Node<E> getNext() {
        return next;
    }

    public void setNext(Node<E> n) {
        next = n;
    }
}
</code>```

Em....Sorry I didn't expect this to be so long...But hope it could be a little helpful to you.

Body:
So I came across this code while studying linkedlists. The code here uses generics and I am having problem understanding some of the things here.

public static class Node<E>
{
     E element;
     Node <E> next;
    public Node(E e,Node <E> n)
    {
        element=e;
        next=n;System.out.println(next);
    }
    public E getelement() {return element;}
    public Node<E> getnext(){ return next;}
    public void setnext(Node <E> n)
    {
        next=n;
    }
}

So what does class Node <E> mean?
I think E element; means  element is of type E. Am I right?
Node <E> next; what does this mean?

Body:
You can easily find official docs and many other resources for such a big topic in Java, I'll try to explain it by "the process of re-creating generics".

Say you're going to implement the class Node given in the question, it's a basic building unit for LinkedList, so you define it as:

class Node {
    private Node next;

    public Node getNext() {
        return next;
    }

    public void setNext(Node n) {
        next = n;
    }
}

but you need to store some data in each Node, don't you, otherwise this class is useless. Obviously one more field is necessary and the type you want to store is MyData, then it'll be:

class Node {
    private MyData element;
    private Node next;

    public Node getNext() {
        return next;
    }

    public MyData getElement() {
        return element;
    }

    public void setElement(MyData element) {
        this.element = element;
    }

    public void setNext(Node n) {
        next = n;
    }
}

One day you want to make your implementation a common library so it can be used by anyone, but one serious problem comes up which is people will not happy with that they can only store data of type MyData in your Node, they want to store whatever type they want, so you made a little change - declare the type of element to Object so that it can handle any type:

class Node {
    private Object element;
    private Node next;

    public Node getNext() {
        return next;
    }

    public Object getElement() {
        return element;
    }

    public void setElement(Object element) {
        this.element = element;
    }

    public void setNext(Node n) {
        next = n;
    }
}

Everything's good now, but some time later you receive some feedbacks from some picky users:

User A: everywhere I call Node.getElement() in my code, I get an Object type stuff and I need to do a type cast, which is inconvenient, it would be better if what I get from getElement is the type I want

User B: I want to only store type A but there's no way to prevent me put a type B into Node, I can't find this bug till exception happens during runtime, it would be better that compiler can help me to find the bug

So you feel that it'll be great if you can leave the decision of what type of data is allowed to put in Node to users, rather than hardcoded in implementation, which means what you'll put at the underscore of the statement private ___ element; is uncertain, you need it be a variable and specified by the user at the moment they use it, so a variable to the class, that's good, but you need a place to declare the variable before you can use it, finally you decide to put the declaration of the variable right after the class name, inside <>(a new syntax), then the code will be:

class Node<E> {
    private E element;
    private Node next;

    public E getElement() {
        return element;
    }

    public void setElement(E element) {
        this.element = element;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node n) {
        next = n;
    }
}

almost done but wait: you're using Node by yourself - the field next, you need to follow the rule you just made: pass type info of element to Node at the time when you use it, so finally you got the code following:

class Node<E> {
    private E element;
    private Node<E> next;

    public E getElement() {
        return element;
    }

    public void setElement(E element) {
        this.element = element;
    }

    public Node<E> getNext() {
        return next;
    }

    public void setNext(Node<E> n) {
        next = n;
    }
}

Em....Sorry I didn't expect this to be so long...But hope it could be a little helpful to you.


问:
Spring Boot - How to log all requests and responses with exceptions in single place?
I'm working on REST API with spring boot. I need to log all requests with input params (with methods, eg. GET, POST, etc.), request path, query string, corresponding class method of this request, also response of this action, both success and errors. For example:

Successful request:

```<code>http://example.com/api/users/1
</code>```

Log should look something like this:

{
   HttpStatus: 200,
   path: "api/users/1",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 1
   },
   response: {
      user: {
        id: 1,
        username: "user123",
        email: "user123@example.com"
      }
   },
   exceptions: []
}
```
<p>Or <strong>request with error:</strong></p>
```http://example.com/api/users/9999
```
<p>Log should be something like this:</p>
<pre class="lang-json prettyprint-override"><code>{
   HttpStatus: 404,
   errorCode: 101,
   path: "api/users/9999",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 9999
   },
   returns: {
   },
   exceptions: [
     {
       exception: "UserNotFoundException",
       message: "User with id 9999 not found",
       exceptionId: "adhaskldjaso98d7324kjh989",
       stacktrace: ...................
   ]
}
</code>```

I want Request/Response to be a single entity, with custom information related to this entity, both in successful and error cases.

What is best practice in spring to achieve this, may be with filters? if yes, can you provide concrete example?

I've played with @ControllerAdvice and @ExceptionHandler, but as I mentioned, I need to handle all success and error requests in single place (and single log).

答:
Spring already provides a filter that does this job. Add following bean to your config

```<code>@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(true);
    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setMaxPayloadLength(64000);
    return loggingFilter;
}
</code>```

Don't forget to change log level of org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on REST API with spring boot. I need to log all requests with input params (with methods, eg. GET, POST, etc.), request path, query string, corresponding class method of this request, also response of this action, both success and errors. For example:

Successful request:

http://example.com/api/users/1

Log should look something like this:

{
   HttpStatus: 200,
   path: "api/users/1",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 1
   },
   response: {
      user: {
        id: 1,
        username: "user123",
        email: "user123@example.com"
      }
   },
   exceptions: []
}

Or request with error:

http://example.com/api/users/9999

Log should be something like this:

{
   HttpStatus: 404,
   errorCode: 101,
   path: "api/users/9999",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 9999
   },
   returns: {
   },
   exceptions: [
     {
       exception: "UserNotFoundException",
       message: "User with id 9999 not found",
       exceptionId: "adhaskldjaso98d7324kjh989",
       stacktrace: ...................
   ]
}

I want Request/Response to be a single entity, with custom information related to this entity, both in successful and error cases.

What is best practice in spring to achieve this, may be with filters? if yes, can you provide concrete example?

I've played with @ControllerAdvice and @ExceptionHandler, but as I mentioned, I need to handle all success and error requests in single place (and single log).

Body:
Spring already provides a filter that does this job. Add following bean to your config

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(true);
    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setMaxPayloadLength(64000);
    return loggingFilter;
}

Don't forget to change log level of org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG.


问:
Data binding Angular2 dynamically created components
I've found code to dynamically create child components, pass data to them, and render them accordingly.

http://plnkr.co/edit/wwHEZkbvKmNVF0Snr2ZB?p=preview

However, I'm not sure how to bind the data from the child components to its parent. In the Plunker I included above, I'd like to have 2-way data binding to showNum.. Any idea?

答:
I hope this is what you want.

LIVE DEMO : http://plnkr.co/edit/SPbo1Cw7mDadfLK3ElEC?p=preview

src/dynamic-component.ts

```<code>import 'rxjs/Rx';

export default class DynamicComponent {

myData:any;
@Input() set componentData(data: {component: any, inputs: any }) {
    ...
    this.myData=data; //assinging parent data object to myData object.
    ...
    ...
    component.instance.showNum=this.myData.inputs.showNum
    //component.instance.someNumber syntax allows you to pass varible to dynamically created component

    //here, I'm using subject from rxjs and subscribing to it as below
    component.instance.emitNumber$.subscribe(v=>{
      console.log('getting'+ v);
      console.log(this.myData);
      this.myData.inputs.showNum=v;  //assigning subscribed value back to parent object
      console.log(this.myData);
    });

}
</code>```

src/hello-world-component.ts

```<code>import {Observable,Subject} 'rxjs/Rx';

@Component({
  selector: 'hello-world',
  template: `
    ...
    <input [(ngModel)]="showNum" (keyup)="updateValue(showNum)" type="text">
  `,

   export default class HelloWorldComponent {

    @Input() showNum:number;
    emitNumber=new Subject<number>();          //using rxjs subject
    emitNumber$=this.emitNumber.asObservable();

    updateValue(val){
      this.emitNumber.next(val);               //emitting value back to dyanmic component
    }

  }

})
</code>```

Parent

```<code><div *ngFor="let x of components">showNum of parent: {{x.inputs.showNum}}<br></div>
</code>```

same with world-hello-component.ts.

Body:
I hope this is what you want.

LIVE DEMO : http://plnkr.co/edit/SPbo1Cw7mDadfLK3ElEC?p=preview

src/dynamic-component.ts

import 'rxjs/Rx';

export default class DynamicComponent {

myData:any;
@Input() set componentData(data: {component: any, inputs: any }) {
    ...
    this.myData=data; //assinging parent data object to myData object.
    ...
    ...
    component.instance.showNum=this.myData.inputs.showNum
    //component.instance.someNumber syntax allows you to pass varible to dynamically created component

    //here, I'm using subject from rxjs and subscribing to it as below
    component.instance.emitNumber$.subscribe(v=>{
      console.log('getting'+ v);
      console.log(this.myData);
      this.myData.inputs.showNum=v;  //assigning subscribed value back to parent object
      console.log(this.myData);
    });

}

src/hello-world-component.ts

import {Observable,Subject} 'rxjs/Rx';

@Component({
  selector: 'hello-world',
  template: `
    ...
    <input [(ngModel)]="showNum" (keyup)="updateValue(showNum)" type="text">
  `,

   export default class HelloWorldComponent {

    @Input() showNum:number;
    emitNumber=new Subject<number>();          //using rxjs subject
    emitNumber$=this.emitNumber.asObservable();

    updateValue(val){
      this.emitNumber.next(val);               //emitting value back to dyanmic component
    }

  }

})

Parent

<div *ngFor="let x of components">showNum of parent: {{x.inputs.showNum}}<br></div>

same with world-hello-component.ts.


问:
How can i convert linux "date +%s" output to a more readable format in bash script
Here is the script:

```<code>
#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

</code>
```

so i want to convert $startTime into a UTC format

答:
I'd have another variable

startTimeHuman=$(date -u -R)

right next to where you set startTime.  This way you'd have both variants, one for doing math, and one for humans to understand.

Body:
Here is the script:

#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

so i want to convert $startTime into a UTC format


问:
How to set image on centre in FrameLayout
I'm doing a project in which I want to set an image in the center.I'm using TableLayout and I want set this image in FrameLayout. If u have any idea so please suggest me. Its very urgent. Thanx to all. Here is my code:</p>

```<code><TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*" >

       <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:layout_weight="1"
          android:layout_gravity="center"
          android:scaleType="center"
         >

        <com.nexbits.digitechi.DrawCanvas
        android:id="@+id/SurfaceView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

         />

     </FrameLayout>

     <TableRow

     android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:gravity="center_horizontal">

    <ImageButton
        android:id="@+id/imageButton5"

        android:layout_weight="1"
        android:padding="20dip"
        android:layout_gravity="center_horizontal"
        android:onClick="video"
        android:src="@drawable/ic_webcamera" />

    <ImageButton
         android:id="@+id/imageButton3"
         android:layout_weight="1"
         android:layout_gravity="center_horizontal"

         android:padding="20dip"
         android:src="@drawable/ic_twitter64" />

    <ImageButton
        android:id="@+id/imageButton2"

         android:layout_weight="1"
         android:padding="20dip"
         android:layout_gravity="center_horizontal"

         android:src="@drawable/ic_brightness64" />

      <ImageButton
          android:id="@+id/imageButton4"
          android:layout_weight="1"
          android:padding="20dip"
          android:layout_gravity="center_horizontal"
          android:src="@drawable/microscope" />
         </TableRow>
         </TableLayout>
</code>```

答:
I achieved it by adding to Child (something inside frame layout)

```<code>  android:layout_gravity="center"
</code>```

Body:
I'm doing a project in which I want to set an image in the center.I'm using TableLayout and I want set this image in FrameLayout. If u have any idea so please suggest me. Its very urgent. Thanx to all. Here is my code:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*" >

       <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:layout_weight="1"
          android:layout_gravity="center"
          android:scaleType="center"
         >

        <com.nexbits.digitechi.DrawCanvas
        android:id="@+id/SurfaceView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

         />

     </FrameLayout>

     <TableRow

     android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:gravity="center_horizontal">

    <ImageButton
        android:id="@+id/imageButton5"

        android:layout_weight="1"
        android:padding="20dip"
        android:layout_gravity="center_horizontal"
        android:onClick="video"
        android:src="@drawable/ic_webcamera" />

    <ImageButton
         android:id="@+id/imageButton3"
         android:layout_weight="1"
         android:layout_gravity="center_horizontal"

         android:padding="20dip"
         android:src="@drawable/ic_twitter64" />

    <ImageButton
        android:id="@+id/imageButton2"

         android:layout_weight="1"
         android:padding="20dip"
         android:layout_gravity="center_horizontal"

         android:src="@drawable/ic_brightness64" />

      <ImageButton
          android:id="@+id/imageButton4"
          android:layout_weight="1"
          android:padding="20dip"
          android:layout_gravity="center_horizontal"
          android:src="@drawable/microscope" />
         </TableRow>
         </TableLayout>

Body:
I achieved it by adding to Child (something inside frame layout)

  android:layout_gravity="center"


问:
How to add item to listbox?
I am creating a simple GUI program to manage priorities. I am having troubles with adding items to the listbox. I tried to create an instance of Priority class by passing two attributes to the constructor and then use g.listBox.insert(END, item), but it seems it doesn't work like that. I am getting an error:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Exception in Tkinter callback Traceback (most recent call last):

  File "/usr/lib/python3.5/tkinter/init.py", line 1553, in call
      return self.func(*args)   File "/home/cali/PycharmProjects/priorities/priorities.py", line 52, in
  addItem
      item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c')) AttributeError: 'GuiPart' object has no attribute 'textBox'

Process finished with exit code 0

Here is what I have done:

```<code># priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:

    def __init__(self, subject, priority):
        self.subject = subject
        self.priority = priority

    def subject(self):
        return self.subject

    def priority(self):
        return self.priority

class GuiPart:

    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def createWidgets(self):

        Button(self.root,
               text = "Add",
               command = self.addItem).grid(row = 2, column = 0, sticky = W + E)

        Button(self.root,
               text="Remove",
               command = self.removeItem).grid(row = 2, column = 1, sticky = W + E)

        Button(self.root,
               text="Edit",
               command = self.editItem).grid(row = 2, column = 2, sticky = W + E)

        listBox = Listbox(width = 30).grid(row = 1, sticky = W + E, columnspan = 3)

        textBox = Text(height=10, width=30).grid(row = 3, columnspan = 3, sticky = W + E + N + S)

    def addItem(self):
        item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c'))

        g.listBox.insert(END, item)

    def removeItem(self):
       pass

    def editItem(self):
        pass

class Client:
    pass

if __name__ == "__main__":
    g = GuiPart()
    g.createWidgets()
    g.root.mainloop()
</code>```

I'm using Python 3.5.

答:
These Lines are causing Error :

```<code>listBox = Listbox(width = 30).grid(row = 1, sticky = W + E, columnspan = 3)
textBox = Text(height=10, width=30).grid(row = 3, columnspan = 3, sticky = W + E + N + S)
</code>```

Do it like this:

```<code>self.listBox = Listbox(self.root,width = 30)
self.listBox.grid(row = 1, sticky = W + E, columnspan = 3)
self.textBox = Text(self.root,height=10, width=30)
self.textBox.grid(row = 3, columnspan = 3, sticky = W + E + N + S)
</code>```

Actually you are not creating listBox and textBox objects instead grid is returning to listBox and textBox

Title: How to add item to listbox?

Body:
I am creating a simple GUI program to manage priorities. I am having troubles with adding items to the listbox. I tried to create an instance of Priority class by passing two attributes to the constructor and then use g.listBox.insert(END, item), but it seems it doesn't work like that. I am getting an error:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Exception in Tkinter callback Traceback (most recent call last):

  File "/usr/lib/python3.5/tkinter/init.py", line 1553, in call
      return self.func(*args)   File "/home/cali/PycharmProjects/priorities/priorities.py", line 52, in
  addItem
      item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c')) AttributeError: 'GuiPart' object has no attribute 'textBox'

Process finished with exit code 0

Here is what I have done:

# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:

    def __init__(self, subject, priority):
        self.subject = subject
        self.priority = priority

    def subject(self):
        return self.subject

    def priority(self):
        return self.priority

class GuiPart:

    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def createWidgets(self):

        Button(self.root,
               text = "Add",
               command = self.addItem).grid(row = 2, column = 0, sticky = W + E)

        Button(self.root,
               text="Remove",
               command = self.removeItem).grid(row = 2, column = 1, sticky = W + E)

        Button(self.root,
               text="Edit",
               command = self.editItem).grid(row = 2, column = 2, sticky = W + E)

        listBox = Listbox(width = 30).grid(row = 1, sticky = W + E, columnspan = 3)

        textBox = Text(height=10, width=30).grid(row = 3, columnspan = 3, sticky = W + E + N + S)

    def addItem(self):
        item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c'))

        g.listBox.insert(END, item)

    def removeItem(self):
       pass

    def editItem(self):
        pass

class Client:
    pass

if __name__ == "__main__":
    g = GuiPart()
    g.createWidgets()
    g.root.mainloop()

I'm using Python 3.5.

Body:
These Lines are causing Error :

listBox = Listbox(width = 30).grid(row = 1, sticky = W + E, columnspan = 3)
textBox = Text(height=10, width=30).grid(row = 3, columnspan = 3, sticky = W + E + N + S)

Do it like this:

self.listBox = Listbox(self.root,width = 30)
self.listBox.grid(row = 1, sticky = W + E, columnspan = 3)
self.textBox = Text(self.root,height=10, width=30)
self.textBox.grid(row = 3, columnspan = 3, sticky = W + E + N + S)

Actually you are not creating listBox and textBox objects instead grid is returning to listBox and textBox


问:
Grab SELECTED text on UITextView
How do I grab the SELECTED or HIGHLIGHTED text on a UITextView?  I already know how to do this on UIWebView using JavaScript.  Now I am trying to figure it out for the UITextView.

答:
Swift 3.0

In Swift, getting the selected text from a UITextView is done by first getting the selected text range (a UITextRange), and then using that range to get the actual text:

```<code>if let textRange = myTextView.selectedTextRange {
    let selectedText = myTextView.text(in: textRange)
}
</code>```

Title: Grab SELECTED text on UITextView

Body:
Swift 3.0

In Swift, getting the selected text from a UITextView is done by first getting the selected text range (a UITextRange), and then using that range to get the actual text:

if let textRange = myTextView.selectedTextRange {
    let selectedText = myTextView.text(in: textRange)
}


问:
Cannot find central directory error
I am trying to read data from an excel file. </p>

```<code>FileStream stream = File.Open (@"C:\Temp\F1\SMRPAC974-00024COMINVDETEXTRACT.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
string csvData = "";
int row_no = 0;
while (row_no < result.Tables[0].Rows.Count)
{
 for (int i = 0; i < result.Tables[0].Columns.Count; i++)
 {
  csvData += result.Tables[0].Rows[row_no][i].ToString() + ";";
 }
 row_no++;
 csvData += "\n";
}
</code>```

<p>The problem i'm currently tackling with is an error that "Cannot find central directory". I don't know what this means I have even tried moving the excel file to different locations but i'm still facing the same error. </p>

答:
check weather you are using .xlsx or .xls file.

If you are using .xlsx then use

```<code>     IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
</code>```

if you are using .xls then use

```<code>    IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
</code>```

Hope it helps. It worked for me.

Title: Cannot find central directory error

Body:
I am trying to read data from an excel file.

FileStream stream = File.Open (@"C:\Temp\F1\SMRPAC974-00024COMINVDETEXTRACT.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
string csvData = "";
int row_no = 0;
while (row_no < result.Tables[0].Rows.Count)
{
 for (int i = 0; i < result.Tables[0].Columns.Count; i++)
 {
  csvData += result.Tables[0].Rows[row_no][i].ToString() + ";";
 }
 row_no++;
 csvData += "\n";
}

The problem i'm currently tackling with is an error that "Cannot find central directory". I don't know what this means I have even tried moving the excel file to different locations but i'm still facing the same error.

Body:
check weather you are using .xlsx or .xls file.

If you are using .xlsx then use

     IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

if you are using .xls then use

    IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

Hope it helps. It worked for me.


问:
SQL query, primary key to multiple foreign key
I'm having a problem which i cannot manage to fix.
I've been looking at some other posts but most of them were either to complex for me to understand/use or do not deal with the same problem.

First the tables:

Person

```<code>   id   |   amt
   =============
    1   |    5
    2   |    26
    3   |    3
</code>```

Goal

```<code>   id   |    idPerson |  goals
   ===========================
    1   |    1        |  "AAA"
    2   |    1        |  "AAA"
    4   |    1        |  "DDD"
    5   |    2        |  "CCC"
    6   |    2        |  "BBB"
    7   |    3        |  "AAA"
</code>```

What I want:
I need all Person ids where the Person does not have the goal "AAA".
Currently a Person can only have between 1 and 3 goals in the Table Goal.

My Select:

```<code> SELECT Person.id, Person.amt
 FROM Person
 WHERE amt < 10
 AND Person.id IN
 (
    SELECT Goal.idPerson
    FROM Goal
    WHERE Person.id = Goal.idPerson
    AND Goal.goals != "AAA"
 )
</code>```

If possible could someone explain me why my SQL is not working and what i have to do different so it works? With an explanation i could avoid the same problem in the future. :)

Thank you.

EDIT:
I did not thought that this would make a problem but when i filter not only for 'AAA' but also for 'BBB' then it I will get results with 'AAA', 'BBB' and even some with both.
How the Where is now:

```<code> AND Person.id NOT IN
 (
    SELECT Goal.idPerson
    FROM Goal
    WHERE Person.id = Goal.idPerson
    AND Goal.goals = 'AAA'
    AND Goal.goals = 'BBB'
 )
</code>```

答:
Also change this:

```<code> AND Goal.goals != "AAA"
</code>```

to

```<code> AND Goal.goals != 'AAA'
</code>```

Body:
I'm having a problem which i cannot manage to fix.
I've been looking at some other posts but most of them were either to complex for me to understand/use or do not deal with the same problem.

First the tables:

Person

   id   |   amt
   =============
    1   |    5
    2   |    26
    3   |    3

Goal

   id   |    idPerson |  goals
   ===========================
    1   |    1        |  "AAA"
    2   |    1        |  "AAA"
    4   |    1        |  "DDD"
    5   |    2        |  "CCC"
    6   |    2        |  "BBB"
    7   |    3        |  "AAA"

What I want:
I need all Person ids where the Person does not have the goal "AAA".
Currently a Person can only have between 1 and 3 goals in the Table Goal.

My Select:

 SELECT Person.id, Person.amt
 FROM Person
 WHERE amt < 10
 AND Person.id IN
 (
    SELECT Goal.idPerson
    FROM Goal
    WHERE Person.id = Goal.idPerson
    AND Goal.goals != "AAA"
 )

If possible could someone explain me why my SQL is not working and what i have to do different so it works? With an explanation i could avoid the same problem in the future. :)

Thank you.

EDIT:
I did not thought that this would make a problem but when i filter not only for 'AAA' but also for 'BBB' then it I will get results with 'AAA', 'BBB' and even some with both.
How the Where is now:

 AND Person.id NOT IN
 (
    SELECT Goal.idPerson
    FROM Goal
    WHERE Person.id = Goal.idPerson
    AND Goal.goals = 'AAA'
    AND Goal.goals = 'BBB'
 )

Body:
Also change this:

 AND Goal.goals != "AAA"

to

 AND Goal.goals != 'AAA'


问:
ms access query to join date table to Timesheet table
My end result is a report of multiple employees that includes days worked in a date range.  In my report, I need to have all dates in the range showing on the report whether the employee worked it or not.

So I have a table with dates worked and hours for each empl.  I also created a table with dates far into the future.  I think I need a query that joins the two tables and puts all dates for the date range - that will be prompted. added to the table of employee time worked.

Does anyone have any ideas how to join these tables and get all dates for each employee in the two week range that will be prompted?

First table Dates has only 1 column with dates way into the future.

Second table has Empl Name, Date worked, and hours worked.

答:
You will need to use a nested query (aka. sub query) to create all combinations of employees and calendar days then you can do a left to your second table (timesheet table).</p>

```<code>select *
from (select distinct empl_name, cal_date from first_tbl, second_tbl
      where cal_date between [start date] and [end date]) as nested
left join second_tbl
    on  nested.empl_name = table_2.empl_name
    and nested.cal_date = table_2.work_date
</code>```

Body:
You will need to use a nested query (aka. sub query) to create all combinations of employees and calendar days then you can do a left to your second table (timesheet table).

select *
from (select distinct empl_name, cal_date from first_tbl, second_tbl
      where cal_date between [start date] and [end date]) as nested
left join second_tbl
    on  nested.empl_name = table_2.empl_name
    and nested.cal_date = table_2.work_date


问:
Populate select option on change odoo 9
How populate select option on change other field. For example:

Default value for select option is store in database tbl_car (Audi, Opel, Mercedes, VW, Bmw). In other table tbl_car_user I store car_name and user_name ('Peter','Audi'). Now I want after change user_id (Select user Peter) in car select option get all car not include Audi (User Peter already use Audi).

Maybe like this:

for car in self.env['tbl.car'].search([]):
    for car_user in self.env['car.user'].search([('user_id','=','self.user_id.id]):
    if (car.name = car_user.name):
       print("DUPLICATE")
    else:
       print("ADD TO SELECT OPTION")
```

Any simple solution?

答:
This kind of problem don't use Selection, even when you find this, if you edit the record next time the selection will not know the value that it contain because odoo will fill the selection by all value except the value that it have. you will see uknown value on the selection field.

but if you want to do this don't use selection use many2one change the selection of car name to a Model (table in database) and use domain for you many2one field.

you cannot do this logic by selection this logic can be don with selection only for wizard.

field_selection = fields.Selection(selection='generate_selection')

def generate_selection(self):
    # compute selection
    return computed_selection
```

but this works when the view is load the first time now the value of the selection cannot be edited or changed with onchange event.

Title: Populate select option on change odoo 9

Body:
How populate select option on change other field. For example:

Default value for select option is store in database tbl_car (Audi, Opel, Mercedes, VW, Bmw). In other table tbl_car_user I store car_name and user_name ('Peter','Audi'). Now I want after change user_id (Select user Peter) in car select option get all car not include Audi (User Peter already use Audi).

Maybe like this:

for car in self.env['tbl.car'].search([]):
    for car_user in self.env['car.user'].search([('user_id','=','self.user_id.id]):
    if (car.name = car_user.name):
       print("DUPLICATE")
    else:
       print("ADD TO SELECT OPTION")

Any simple solution?

Body:
This kind of problem don't use Selection, even when you find this, if you edit the record next time the selection will not know the value that it contain because odoo will fill the selection by all value except the value that it have. you will see uknown value on the selection field.

but if you want to do this don't use selection use many2one change the selection of car name to a Model (table in database) and use domain for you many2one field.

you cannot do this logic by selection this logic can be don with selection only for wizard.

field_selection = fields.Selection(selection='generate_selection')

def generate_selection(self):
    # compute selection
    return computed_selection

but this works when the view is load the first time now the value of the selection cannot be edited or changed with onchange event.


问:
How to pass item Click Position in Listview
This is My Main Listview `

```<code>lvComments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getApplicationContext(), Subcategories.class);

                intent.putExtra("position", i);

                startActivity(intent);
            }
        });
</code>```

This is code i am using for item position`This is my 2nd Listview its open when  i am clicking on main ListView But This opens in all position and i want to open this 2nd listview on 0th position of main(1ST) Listview

答:
If you want to open second listview only when you click on 0th position then use following code.</p>

```<code>    lvComments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent = new Intent(getApplicationContext(), Subcategories.class);

                  if(i == 0){
                    intent.putExtra("position", i);
                    startActivity(intent);
                  } else {
                     //do your stuff for other position.
                  }
                }
            });
</code>```

Body:
This is My Main Listview `

lvComments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getApplicationContext(), Subcategories.class);

                intent.putExtra("position", i);

                startActivity(intent);
            }
        });

This is code i am using for item position`This is my 2nd Listview its open when  i am clicking on main ListView But This opens in all position and i want to open this 2nd listview on 0th position of main(1ST) Listview

Body:
If you want to open second listview only when you click on 0th position then use following code.

    lvComments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent = new Intent(getApplicationContext(), Subcategories.class);

                  if(i == 0){
                    intent.putExtra("position", i);
                    startActivity(intent);
                  } else {
                     //do your stuff for other position.
                  }
                }
            });


问:
R and Leaflet: How to arrange label text across multiple lines
Suppose you have the following data frame:

```<code>cities = data.frame( name = c('Madrid','Barcelona','Sevilla'),
                 country = c('Spain','Spain','Spain'),
                 region = c('Comunidad de Madrid','Cataluña','Andalucia'),
                 data = c(100, 200, 300),
                 lng = c(-3.683333,2.166667,-6.083333),
                 lat = c(40.433333,41.383333,37.446667))
</code>```

My idea is to have a map of these cities and labels that could display some relevant information when hovering the corresponding city circles. I'd like to have the label text arranged in several lines. The very first approach below failed:

```<code>library( leaflet )

map = leaflet( cities ) %>%
addTiles() %>%
addCircles( lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000,
          stroke = FALSE, fillOpacity = 0.8, label = paste0( cities$name,'\n', cities$region, '\n', cities$country, '\n', cities$data ) )
</code>```

as well as other similar attempts. After googling a while, I found a possible solution by involving the htmltools package:

```<code>library( htmltools )
map2 = leaflet( cities ) %>%
addTiles() %>%
addCircles( lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000,
          stroke = FALSE, fillOpacity = 0.8,
          label = HTML( paste0( '<p>', cities$name, '<p></p>', cities$region, ', ', cities$country,'</p><p>', cities$data, '</p>' ) ) )
</code>```

In this case, the information is displayed as I'd like but, within the same label, there is an entry for each city of the dataset. How could I do to have the text of a single city arranged in multiple lines? Any help would be really appreciated

答:
First, create a character vector of html content for each city and then wrap that in a lapply call to set the HTML attribute for correct display when defining the label attribute in adCircles

```<code>labs <- lapply(seq(nrow(cities)), function(i) {
  paste0( '<p>', cities[i, "name"], '<p></p>',
          cities[i, "region"], ', ',
          cities[i, "country"],'</p><p>',
          cities[i, "data"], '</p>' )
})

map2 = leaflet( cities ) %>%
  addTiles() %>%
  addCircles(lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000,
              stroke = FALSE, fillOpacity = 0.8,
              label = lapply(labs, htmltools::HTML))

map2
</code>```

Body:
Suppose you have the following data frame:

cities = data.frame( name = c('Madrid','Barcelona','Sevilla'),
                 country = c('Spain','Spain','Spain'),
                 region = c('Comunidad de Madrid','Cataluña','Andalucia'),
                 data = c(100, 200, 300),
                 lng = c(-3.683333,2.166667,-6.083333),
                 lat = c(40.433333,41.383333,37.446667))

My idea is to have a map of these cities and labels that could display some relevant information when hovering the corresponding city circles. I'd like to have the label text arranged in several lines. The very first approach below failed:

library( leaflet )

map = leaflet( cities ) %>%
addTiles() %>%
addCircles( lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000,
          stroke = FALSE, fillOpacity = 0.8, label = paste0( cities$name,'\n', cities$region, '\n', cities$country, '\n', cities$data ) )

as well as other similar attempts. After googling a while, I found a possible solution by involving the htmltools package:

library( htmltools )
map2 = leaflet( cities ) %>%
addTiles() %>%
addCircles( lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000,
          stroke = FALSE, fillOpacity = 0.8,
          label = HTML( paste0( '
', cities$name, '

', cities$region, ', ', cities$country,'

', cities$data, '
' ) ) )

In this case, the information is displayed as I'd like but, within the same label, there is an entry for each city of the dataset. How could I do to have the text of a single city arranged in multiple lines? Any help would be really appreciated

Body:
First, create a character vector of html content for each city and then wrap that in a lapply call to set the HTML attribute for correct display when defining the label attribute in adCircles

labs <- lapply(seq(nrow(cities)), function(i) {
  paste0( '<p>', cities[i, "name"], '<p></p>',
          cities[i, "region"], ', ',
          cities[i, "country"],'</p><p>',
          cities[i, "data"], '</p>' )
})

map2 = leaflet( cities ) %>%
  addTiles() %>%
  addCircles(lng = ~lng, lat = ~lat, fillColor = 'darkBlue', radius = 10000,
              stroke = FALSE, fillOpacity = 0.8,
              label = lapply(labs, htmltools::HTML))

map2


问:
How to invoke Presenter Methods in Model file with Dagger2 and MVP pattern
I am trying to create substructure with Dagger2 and eveything works fine.

My main problem is starting when I need invoke presenter methods in my model file. Let me give more detail.

As you can seen in my Model file I request to server with retrofit and based on the result I should invoke a method from presenter. Because Model will decide which method should be worked in presenter and according to choosed method the presenter will invoke view methods. But problem is that the Presenter is using the Model by calling in Constructor but even the Presenter is a middle man, Model can not use the Presenter.

This substructure below is right for MVP.

Whos duty to request server Presenter or Model?

If my substructure is right, how should Model invoke the presenter files with Dagger2?

It is my MVP interface cluster.

```<code>public interface IRegisterMVP {

    interface View extends IGeneralViewOps{

        void showWarning( String warningMessage );

        void openMainActivity();
    }

    interface Presenter {

        void setView( View view );

        void registerTriggered( ArrayMap< String, String > userParameters );

        void registerTriggered( EditText userName, EditText mailAddress, EditText password, EditText passwordRepeat );

        void notValidated( String warningMessage );

        void validate();
    }

    interface Model {

        void validateData( ArrayMap< String, String > userParameters );

    }
</code>```

It is my Module

```<code>@Module
public class UserOperationsModule {

    @Provides
    public IRegisterMVP.Presenter provideRegisterPresenter( IRegisterMVP.Model model ){
        return new RegisterFragmentPresenter( model );

    }

    @Provides
    public IRegisterMVP.Model provideRegisterModel( Context context, IRegisterMVP.Presenter presenter ){
        return new UserBussinessModel( context );

    }

}
</code>```

It is my Presenter

```<code>public class RegisterFragmentPresenter implements IRegisterMVP.Presenter {

private IRegisterMVP.View mView;
private IRegisterMVP.Model mModel;

public RegisterFragmentPresenter( IRegisterMVP.Model mModel ) {
    this.mModel = mModel;
}

@Override
public void setView( IRegisterMVP.View view ) {
    this.mView = view;

}

@Override
public void registerTriggered( ArrayMap< String, String > userParameters ) {
    this.mModel.validateData( userParameters );

}

@Override
public void registerTriggered( EditText userName, EditText mailAddress, EditText password, EditText passwordRepeat ) {

    ArrayMap< String, String > createViewValues = new ArrayMap<>( 4 );
    createViewValues.put( UserBussinessModel.USER_NAME, userName.getText().toString() );
    createViewValues.put( UserBussinessModel.USER_MAIL_ADDRES, mailAddress.getText().toString() );
    createViewValues.put( UserBussinessModel.USER_PASS, password.getText().toString() );
    createViewValues.put( UserBussinessModel.USER_PASS_REPEAT, passwordRepeat.getText().toString() );

    this.registerTriggered( createViewValues );
}

@Override
public void notValidated( String warningMessage ) {
    this.mView.hideWaitingView();
    this.mView.showWarning( warningMessage );

}

@Override
public void validate() {
    this.mView.hideWaitingView();
    this.mView.openMainActivity();

}
</code>```

}

And it is my businessmodel file

```<code>public UserBussinessModel( Context context ) {
    this.mContext = context;

}

public UserBussinessModel( Context mContext, IRegisterMVP.Presenter mRegisterPresenter ) {
    this.mContext = mContext;
    this.mRegisterPresenter = mRegisterPresenter;
}

public UserBussinessModel( Context mContext, LoginMVP.Presenter mLoginPresenter ) {
    this.mContext = mContext;
    this.mLoginPresenter = mLoginPresenter;
}

@Override
public void validateData( ArrayMap< String, String > userParameters ) {
  Call< MainModel< Fortune > > jsonObjectCall =    this.mFortuneService.getSpesificFortuneBasedOnUser( userUUID, fortune_id );
    jsonObjectCall.enqueue( new Callback< MainModel< Fortune > >() {
        @Override
        public void onResponse( Call< MainModel< Fortune > > call, Response< MainModel< Fortune > > response ) {
        // HOW SHOULD MODEL INVOKE THE PRESENTER METHOD IN ORDER TO ARRANGE VIEW FILES?
        }

        @Override
        public void onFailure( Call< MainModel< Fortune > > call, Throwable t ) {
         // HOW SHOULD MODEL INVOKE THE PRESENTER METHOD IN ORDER TO ARRANGE VIEW FILES?
        }
    } );
}
</code>```

答:
If you are interested in implementing MVP in Android, please refer to the Google Android Architecture Blueprints.

With respect to your question:

Because Model will decide which method should be worked in presenter and according to choosed method the presenter will invoke view methods.

This isn't the usual way of doing MVP. In MVP, the model is passive and the presenter is the agent.

(Diagram from MVP Wikipedia page)

As per the diagram above, the presenter manipulates the model, and the model doesn't know or care about the presenter. When it is necessary for the model to notify the presenter of state change events it is done through the presenter registering for callbacks from the model. This is also clear in the Blueprint example:

```<code>@Inject
TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
    mTasksRepository = tasksRepository;
    mTasksView = tasksView;
}
</code>```

The presenter takes a dependency on the model (the tasks repository) but the tasks repository doesn't know or care about who is consuming it. While the linked example doesn't show a state-change event propagating from the model layer to the presenter, if there was one it probably be done through registering a callback inside the presenter layer. Something like the following:

```<code>mTasksRepository.registerStateChangeEvent(this);
</code>```

Likewise, the example also shows loading similar to yours and correctly places this inside the presenter:

```<code>private void loadStatistics() {
    mStatisticsView.setProgressIndicator(true);

    // The network request might be handled in a different thread so make sure Espresso knows
    // that the app is busy until the response is handled.
    EspressoIdlingResource.increment(); // App is busy until further notice

    mTasksRepository.getTasks(new TasksDataSource.LoadTasksCallback() {
    //snip
</code>```

Because mTasksRepository doesn't take any dependencies that relate to the view or presenter and is manipulated as a patient by the presenter, we still maintain separation of concerns.

Body:
I am trying to create substructure with Dagger2 and eveything works fine.

My main problem is starting when I need invoke presenter methods in my model file. Let me give more detail.

As you can seen in my Model file I request to server with retrofit and based on the result I should invoke a method from presenter. Because Model will decide which method should be worked in presenter and according to choosed method the presenter will invoke view methods. But problem is that the Presenter is using the Model by calling in Constructor but even the Presenter is a middle man, Model can not use the Presenter.

This substructure below is right for MVP.

Whos duty to request server Presenter or Model?

If my substructure is right, how should Model invoke the presenter files with Dagger2?

It is my MVP interface cluster.

public interface IRegisterMVP {

    interface View extends IGeneralViewOps{

        void showWarning( String warningMessage );

        void openMainActivity();
    }

    interface Presenter {

        void setView( View view );

        void registerTriggered( ArrayMap< String, String > userParameters );

        void registerTriggered( EditText userName, EditText mailAddress, EditText password, EditText passwordRepeat );

        void notValidated( String warningMessage );

        void validate();
    }

    interface Model {

        void validateData( ArrayMap< String, String > userParameters );

    }

It is my Module

@Module
public class UserOperationsModule {

    @Provides
    public IRegisterMVP.Presenter provideRegisterPresenter( IRegisterMVP.Model model ){
        return new RegisterFragmentPresenter( model );

    }

    @Provides
    public IRegisterMVP.Model provideRegisterModel( Context context, IRegisterMVP.Presenter presenter ){
        return new UserBussinessModel( context );

    }

}

It is my Presenter

public class RegisterFragmentPresenter implements IRegisterMVP.Presenter {

private IRegisterMVP.View mView;
private IRegisterMVP.Model mModel;

public RegisterFragmentPresenter( IRegisterMVP.Model mModel ) {
    this.mModel = mModel;
}

@Override
public void setView( IRegisterMVP.View view ) {
    this.mView = view;

}

@Override
public void registerTriggered( ArrayMap< String, String > userParameters ) {
    this.mModel.validateData( userParameters );

}

@Override
public void registerTriggered( EditText userName, EditText mailAddress, EditText password, EditText passwordRepeat ) {

    ArrayMap< String, String > createViewValues = new ArrayMap<>( 4 );
    createViewValues.put( UserBussinessModel.USER_NAME, userName.getText().toString() );
    createViewValues.put( UserBussinessModel.USER_MAIL_ADDRES, mailAddress.getText().toString() );
    createViewValues.put( UserBussinessModel.USER_PASS, password.getText().toString() );
    createViewValues.put( UserBussinessModel.USER_PASS_REPEAT, passwordRepeat.getText().toString() );

    this.registerTriggered( createViewValues );
}

@Override
public void notValidated( String warningMessage ) {
    this.mView.hideWaitingView();
    this.mView.showWarning( warningMessage );

}

@Override
public void validate() {
    this.mView.hideWaitingView();
    this.mView.openMainActivity();

}

}

And it is my businessmodel file

public UserBussinessModel( Context context ) {
    this.mContext = context;

}

public UserBussinessModel( Context mContext, IRegisterMVP.Presenter mRegisterPresenter ) {
    this.mContext = mContext;
    this.mRegisterPresenter = mRegisterPresenter;
}

public UserBussinessModel( Context mContext, LoginMVP.Presenter mLoginPresenter ) {
    this.mContext = mContext;
    this.mLoginPresenter = mLoginPresenter;
}

@Override
public void validateData( ArrayMap< String, String > userParameters ) {
  Call< MainModel< Fortune > > jsonObjectCall =    this.mFortuneService.getSpesificFortuneBasedOnUser( userUUID, fortune_id );
    jsonObjectCall.enqueue( new Callback< MainModel< Fortune > >() {
        @Override
        public void onResponse( Call< MainModel< Fortune > > call, Response< MainModel< Fortune > > response ) {
        // HOW SHOULD MODEL INVOKE THE PRESENTER METHOD IN ORDER TO ARRANGE VIEW FILES?
        }

        @Override
        public void onFailure( Call< MainModel< Fortune > > call, Throwable t ) {
         // HOW SHOULD MODEL INVOKE THE PRESENTER METHOD IN ORDER TO ARRANGE VIEW FILES?
        }
    } );
}

Body:
If you are interested in implementing MVP in Android, please refer to the Google Android Architecture Blueprints.

With respect to your question:

Because Model will decide which method should be worked in presenter and according to choosed method the presenter will invoke view methods.

This isn't the usual way of doing MVP. In MVP, the model is passive and the presenter is the agent.

(Diagram from MVP Wikipedia page)

As per the diagram above, the presenter manipulates the model, and the model doesn't know or care about the presenter. When it is necessary for the model to notify the presenter of state change events it is done through the presenter registering for callbacks from the model. This is also clear in the Blueprint example:

@Inject
TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
    mTasksRepository = tasksRepository;
    mTasksView = tasksView;
}

The presenter takes a dependency on the model (the tasks repository) but the tasks repository doesn't know or care about who is consuming it. While the linked example doesn't show a state-change event propagating from the model layer to the presenter, if there was one it probably be done through registering a callback inside the presenter layer. Something like the following:

mTasksRepository.registerStateChangeEvent(this);

Likewise, the example also shows loading similar to yours and correctly places this inside the presenter:

private void loadStatistics() {
    mStatisticsView.setProgressIndicator(true);

    // The network request might be handled in a different thread so make sure Espresso knows
    // that the app is busy until the response is handled.
    EspressoIdlingResource.increment(); // App is busy until further notice

    mTasksRepository.getTasks(new TasksDataSource.LoadTasksCallback() {
    //snip

Because mTasksRepository doesn't take any dependencies that relate to the view or presenter and is manipulated as a patient by the presenter, we still maintain separation of concerns.


答:
Your subselect filters all rows that do not match "AAA". That includes "DDD". You can use </p>

```<code>SELECT * FROM Person p
WHERE NOT EXISTS (SELECT g.id FROM Goal g WHERE g.goals="AAA" AND g.idPerson=p.id)
</code>```

Title: SQL query, primary key to multiple foreign key

Body:
Your subselect filters all rows that do not match "AAA". That includes "DDD". You can use

SELECT * FROM Person p
WHERE NOT EXISTS (SELECT g.id FROM Goal g WHERE g.goals="AAA" AND g.idPerson=p.id)


问:
How to map an existing view using EntityFramework Core?
I know how to map table from tutorial

```<code>public DbSet<AccountEntity> Account { get; set; }
//..... OnModelCreating
modelBuilder.Entity<AccountEntity>().ToTable("Account");
</code>```

Let's say there is an view in database named V_Account, how can I map to this view and use it as _context.V_Account?

答:
As far as I am concerned it's not possible yet to map to a view. See the "Critical O/RM features" on the EF Core Roadmap Docs on GitHub

Critical O/RM features

The things we think we need before we say EF Core is the recommended version of EF. Until we implement these features EF Core will be a valid option for many applications, especially on platforms such as UWP and .NET Core where EF6.x does not work, but for many applications the lack of these features will make EF6.x a better option.

Modelling

Complex/value types are types that do not have a primary key and are used to represent a set of properties on an entity type.

Stored procedure mapping allows EF to use stored procedures to persist changes to the database (FromSql already provides good support for using a stored procedure to query).

View mapping allows EF to map to database views.

See the last point, which means that it's still on the roadmap. Since it's not yet in the Roadmap for EF Core 2.0 it's to be assumed that it won't come until a later version.

If you need such features you should fall back to using EF 6.x (but then unable to target .NET Core, just .NET Framework 4.x)

Body:
I know how to map table from tutorial

public DbSet<AccountEntity> Account { get; set; }
//..... OnModelCreating
modelBuilder.Entity<AccountEntity>().ToTable("Account");

Let's say there is an view in database named V_Account, how can I map to this view and use it as _context.V_Account?


答:
```<code>lvComments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getApplicationContext(), Subcategories.class);
                  if(i == 0){
                        intent.putExtra("position", i);
                        startActivity(intent);
                      }else {// do whatever your stuff
                   }
                }
            });
</code>```

In Second Activity

```<code>    int position = getIntent().getIntExtra("position", 0); // 0 will be default value if there is no value in bundle
</code>```

Title: How to pass item Click Position in Listview

Body:
lvComments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getApplicationContext(), Subcategories.class);
                  if(i == 0){
                        intent.putExtra("position", i);
                        startActivity(intent);
                      }else {// do whatever your stuff
                   }
                }
            });

In Second Activity

    int position = getIntent().getIntExtra("position", 0); // 0 will be default value if there is no value in bundle


问:
How do I shutdown my linux based computer remotely?
I have absolutely basic knowledge regarding networking. And I know about ssh tunneling or connections but I have no clue how to apply it or use it. I'm designing an application for security and I need help getting past this hurdle. </p>

答:
Create a tcp server on one machine and tcp client on another machine.

Send the string "shutdown" from the client to the server.

Write the tcp server in such a way that it shuts down the machine when it gets the string "shutdown".


答:
You don't need it to be correlated and you want to use NOT IN instead:

```<code>select Person.id,
    Person.amt
from Person
where amt < 10
    and id not in (
        select idPerson
        from Goal
        where goals = 'AAA'
        )
</code>```

Body:
You don't need it to be correlated and you want to use NOT IN instead:

select Person.id,
    Person.amt
from Person
where amt < 10
    and id not in (
        select idPerson
        from Goal
        where goals = 'AAA'
        )


问:
How to make the third party library twisted of python automatically complete in sublime?
I have installed package 'Anaconda' in sublime. But it doesn't work for third library like twisted and so on...How can I make it automatically complete? Thanks in advance.</p>

答:
By default, anaconda uses the python interpreter that is in your PATH
  environment variable, the most important configuration option is the
  python_interpreter option that allow the user to use a different
  python interpreter, for example, one that resides in a virtual
  environment:

So check your sublime3 configuration, and make sure the python interpreter is right:

e.g.

```<code>{
    "font_face": "Monaco",
    "font_size": 11,
    "python_interpreter": "/Users/**/venv/bin/python"
}
</code>```

See more details from anaconda settings.

Body:
By default, anaconda uses the python interpreter that is in your PATH
  environment variable, the most important configuration option is the
  python_interpreter option that allow the user to use a different
  python interpreter, for example, one that resides in a virtual
  environment:

So check your sublime3 configuration, and make sure the python interpreter is right:

e.g.

{
    "font_face": "Monaco",
    "font_size": 11,
    "python_interpreter": "/Users/**/venv/bin/python"
}

See more details from anaconda settings.


问:
CSS padding-bottom does not seem to work
I need to put space between the fixed footer and the bottom of the page. I've tried setting a padding for #main-content, but it's not working. Is there a problem here that I failed to see?

CSS

```<code>#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

footer {
    background-color: #00496b;
    width: 100%;
    bottom: 0;
    position: fixed;
}
</code>```

Instead of getting the desired result, the main contents disappear behind the footer, instead. I want the #main-content to go a little further up. Hope I have explained the problem enough.

答: Try margin-bottom instead of padding-bottom

Body:
I need to put space between the fixed footer and the bottom of the page. I've tried setting a padding for #main-content, but it's not working. Is there a problem here that I failed to see?

CSS

#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

footer {
    background-color: #00496b;
    width: 100%;
    bottom: 0;
    position: fixed;
}

Instead of getting the desired result, the main contents disappear behind the footer, instead. I want the #main-content to go a little further up. Hope I have explained the problem enough.


问:
Having description and contact at Mercurial web page
Currently, I am in the progress of migrating CVS to Mercurial.

http://jstock.hg.sourceforge.net/hgweb/jstock/

I would like to have contact and description information in the mercurial page.

I look at https://www.mercurial-scm.org/wiki/PublishingRepositories#Putting_useful_information_in_the_index_page

But, it seems that, modification on C:\Projects\jstock\.hg\hgrc doesn't have any effect at all. push will not update anything in sourceforge server.

So, does this mean the only way is to remote access to sourceforge mercurial server and modify the hgrc file manually?

I try to ssh to the remote machine.

```<code>[yccheok@shell-22003 .hg]$ pwd
/home/scm_hg/j/js/jstock/jstock-cloud/.hg
[yccheok@shell-22003 .hg]$ ls -al
total 56
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 .
drwxrwsr-x 3 yccheok jstock   80 Nov 30 15:13 ..
-rw-rw-r-- 1 yccheok jstock   57 Nov 30 15:13 00changelog.i
-rw-rw-r-- 1 yccheok jstock   93 Nov 30 15:29 branchheads.cache
-rw-rw-r-- 1 yccheok jstock   23 Nov 30 15:13 requires
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 store
-rw-rw-r-- 1 yccheok jstock  317 Nov 30 15:29 tags.cache
-rw-rw-r-- 1 yccheok jstock    7 Nov 30 15:29 undo.branch
-rw-rw-r-- 1 yccheok jstock    0 Nov 30 15:29 undo.dirstate
[yccheok@shell-22003 .hg]$
</code>```

But not able to find hgrc file.

答:
The .hg/hgrc file contains local settings and is not itself a versioned file. These settings do not travel from one repository to the other by hg clone, hg push or hg pull commands.

If you want to edit the hgrc file of your source forge repository, you have to use Sourceforge's interactive shell service.

Body:
Currently, I am in the progress of migrating CVS to Mercurial.

http://jstock.hg.sourceforge.net/hgweb/jstock/

I would like to have contact and description information in the mercurial page.

I look at https://www.mercurial-scm.org/wiki/PublishingRepositories#Putting_useful_information_in_the_index_page

But, it seems that, modification on C:\Projects\jstock\.hg\hgrc doesn't have any effect at all. push will not update anything in sourceforge server.

So, does this mean the only way is to remote access to sourceforge mercurial server and modify the hgrc file manually?

I try to ssh to the remote machine.

[yccheok@shell-22003 .hg]$ pwd
/home/scm_hg/j/js/jstock/jstock-cloud/.hg
[yccheok@shell-22003 .hg]$ ls -al
total 56
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 .
drwxrwsr-x 3 yccheok jstock   80 Nov 30 15:13 ..
-rw-rw-r-- 1 yccheok jstock   57 Nov 30 15:13 00changelog.i
-rw-rw-r-- 1 yccheok jstock   93 Nov 30 15:29 branchheads.cache
-rw-rw-r-- 1 yccheok jstock   23 Nov 30 15:13 requires
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 store
-rw-rw-r-- 1 yccheok jstock  317 Nov 30 15:29 tags.cache
-rw-rw-r-- 1 yccheok jstock    7 Nov 30 15:29 undo.branch
-rw-rw-r-- 1 yccheok jstock    0 Nov 30 15:29 undo.dirstate
[yccheok@shell-22003 .hg]$

But not able to find hgrc file.


答:
You probably looking for NOT EXISTS instead like

```<code> SELECT Person.id, Person.amt
 FROM Person
 WHERE amt < 10
 AND NOT EXISTS
 (
    SELECT 1
    FROM Goal
    WHERE idperson = person.id AND goals = "AAA"
 )
</code>```

Body:
I'm having a problem which i cannot manage to fix.
I've been looking at some other posts but most of them were either to complex for me to understand/use or do not deal with the same problem.

First the tables:

Person

   id   |   amt
   =============
    1   |    5
    2   |    26
    3   |    3

Goal

   id   |    idPerson |  goals
   ===========================
    1   |    1        |  "AAA"
    2   |    1        |  "AAA"
    4   |    1        |  "DDD"
    5   |    2        |  "CCC"
    6   |    2        |  "BBB"
    7   |    3        |  "AAA"

What I want:
I need all Person ids where the Person does not have the goal "AAA".
Currently a Person can only have between 1 and 3 goals in the Table Goal.

My Select:

 SELECT Person.id, Person.amt
 FROM Person
 WHERE amt < 10
 AND Person.id IN
 (
    SELECT Goal.idPerson
    FROM Goal
    WHERE Person.id = Goal.idPerson
    AND Goal.goals != "AAA"
 )

If possible could someone explain me why my SQL is not working and what i have to do different so it works? With an explanation i could avoid the same problem in the future. :)

Thank you.

EDIT:
I did not thought that this would make a problem but when i filter not only for 'AAA' but also for 'BBB' then it I will get results with 'AAA', 'BBB' and even some with both.
How the Where is now:

 AND Person.id NOT IN
 (
    SELECT Goal.idPerson
    FROM Goal
    WHERE Person.id = Goal.idPerson
    AND Goal.goals = 'AAA'
    AND Goal.goals = 'BBB'
 )

Body:
You probably looking for NOT EXISTS instead like

 SELECT Person.id, Person.amt
 FROM Person
 WHERE amt < 10
 AND NOT EXISTS
 (
    SELECT 1
    FROM Goal
    WHERE idperson = person.id AND goals = "AAA"
 )


答:
You need to use NOT IN rather than IN, e.g.:

```<code>SELECT *
FROM Person
WHERE amt < 10
 AND Person.id NOT IN (
        SELECT idPerson FROM Goal WHERE goals = 'AAA'
  );
</code>```

Body:
You need to use NOT IN rather than IN, e.g.:

SELECT *
FROM Person
WHERE amt < 10
 AND Person.id NOT IN (
        SELECT idPerson FROM Goal WHERE goals = 'AAA'
  );


问:
When is preferable to use if 'key' in dict: instead of if dict.get('key') is not None:?
I've been using the following syntax in my code for checking the existence of a key:

```<code>if dict.get("key") is not None:
    print "key found"
</code>```

However, I have seen in other people's code the following syntax:

```<code>if 'key' in dict:
   print "key found"
</code>```

I was just wondering which way is best to express a dictionary key null check and if there is an advantage (if any) to using one over the other.

I saw the existing question addressing the similar question of what are the alternatives to using .get() but just want to know if there is any advantage between the two examples I provided.

答:
If there is a key entry with the value None the two expressions will return different results:

```<code>>>> d = {'key': None}
>>> d.get("key") is not None
False
>>> 'key' in d
True
</code>```

If you want to check whether the key exists in the dictionary, the in operator should be used; it also makes your intention clearer. Additionally, it also works for other sequence types (eg. list, tuple, etc.)

BTW, don't use dict as a variable name; it shadows the builtin function/type dict.

Body:
I've been using the following syntax in my code for checking the existence of a key:

if dict.get("key") is not None:
    print "key found"

However, I have seen in other people's code the following syntax:

if 'key' in dict:
   print "key found"

I was just wondering which way is best to express a dictionary key null check and if there is an advantage (if any) to using one over the other.

I saw the existing question addressing the similar question of what are the alternatives to using .get() but just want to know if there is any advantage between the two examples I provided.

Body:
If there is a key entry with the value None the two expressions will return different results:

>>> d = {'key': None}
>>> d.get("key") is not None
False
>>> 'key' in d
True

If you want to check whether the key exists in the dictionary, the in operator should be used; it also makes your intention clearer. Additionally, it also works for other sequence types (eg. list, tuple, etc.)

BTW, don't use dict as a variable name; it shadows the builtin function/type dict.


答:
This is better.

```<code>if 'key' in dict:
   print "key found"
</code>```

Also, as @falsetrue noted, if you have a None value in your dict, if d.get('key') is not None becomes False which may not be the intended behaviour.

dict.get is useful when you use the value in an expression and want a default value to be used when the key is not in the dict.

```<code>d['key'] = 4
a = 5 + d.get('key', 0) # returns 0 if `key` is not in `d`
</code>```

Title: When is preferable to use if 'key' in dict: instead of if dict.get('key') is not None:?

Body:
This is better.

if 'key' in dict:
   print "key found"

Also, as @falsetrue noted, if you have a None value in your dict, if d.get('key') is not None becomes False which may not be the intended behaviour.

dict.get is useful when you use the value in an expression and want a default value to be used when the key is not in the dict.

d['key'] = 4
a = 5 + d.get('key', 0) # returns 0 if `key` is not in `d`


问:
Loading A CSS File From Django Template
I have looked through several answers for loading CSS pages. http://docs.djangoproject.com/en/dev/howto/static-files/

Basically, I believe my question should be how do I get staticfiles installed?

I am confused about the settings in settings.py, and I get this error when trying to run collectstatic.

```<code>./manage.py collectstatic
Unknown command: 'collectstatic'
</code>```

In settings.py, I've added

```<code>'django.contrib.staticfiles',
</code>```

to INSTALLED_APS

and

```<code>STATICFILES_DIRS = (
 "/home/amr/django/static_media",
)

STATIC_ROOT = "/home/amr/django/static_media"
</code>```

The error I'm getting is there is no module staticfiles.

答: That documentation is for the development version of Django. If you're running a stable version then you should examine the appropriate docs by clicking on the version number at the top of the article.</p>

Title: Loading A CSS File From Django Template

Body:
I have looked through several answers for loading CSS pages. http://docs.djangoproject.com/en/dev/howto/static-files/

Basically, I believe my question should be how do I get staticfiles installed?

I am confused about the settings in settings.py, and I get this error when trying to run collectstatic.

./manage.py collectstatic
Unknown command: 'collectstatic'

In settings.py, I've added

'django.contrib.staticfiles',

to INSTALLED_APS

and

STATICFILES_DIRS = (
 "/home/amr/django/static_media",
)

STATIC_ROOT = "/home/amr/django/static_media"

The error I'm getting is there is no module staticfiles.