问:
Comma is causing unwanted string split
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:

```<code>public List getAnswerStringEdit() {
        return answer_edit;
    }
</code>```

I save it as so:

```<code>editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
</code>```

Then retrieve it here:

```<code>String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
        answerString = answerString.substring(1, answerString.length() - 1).trim();
        String[] array = answerString.split(",");
</code>```

Finally, I access the array as so:

```<code>et_answer1_edit.append(array[0]);
</code>```

My problem is this - Say I add a questions which has a comma in the middle of it, like -

Question 1- "Why is this broke, I don't know?"

Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:

"Why is this broke, I don't know?"

However, instead I am getting in position 0:

Why is this broke - then position 1 as: I don't know

I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.

The retrieved JSON is as follows:

```<code>{
    "result": "success",
    "message": "Answer Has Been Selected",
    "answer": {
        "answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
    }
}
</code>```

Any help/advice that can help me to understand what is causing this, would be really appreciated.

答:
After reading all the suggest answers, figured out a simple solution:

First I stored my answers sent from my external database as so -

```<code>final String jsonAnswers = gson.toJson (resp.getAnswer().getAnswerStringEdit());
</code>```

Then saved in shared pref -

```<code>editor.putString(Constants.ANSWER_EDIT,jsonAnswers);
</code>```

Next to read the answer back out:

```<code>String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
final String[] array = gson.fromJson (answerString, String[].class);
</code>```

Finally, I could set my Edittext with data from the array:

```<code>et_answer1_edit.append(array[0].trim());

et_answer2_edit.append(array[1].trim());
</code>```

Title: Comma is causing unwanted string split

Body:
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:

public List getAnswerStringEdit() {
        return answer_edit;
    }

I save it as so:

editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());

Then retrieve it here:

String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
        answerString = answerString.substring(1, answerString.length() - 1).trim();
        String[] array = answerString.split(",");

Finally, I access the array as so:

et_answer1_edit.append(array[0]);

My problem is this - Say I add a questions which has a comma in the middle of it, like -

Question 1- "Why is this broke, I don't know?"

Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:

"Why is this broke, I don't know?"

However, instead I am getting in position 0:

Why is this broke - then position 1 as: I don't know

I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.

The retrieved JSON is as follows:

{
    "result": "success",
    "message": "Answer Has Been Selected",
    "answer": {
        "answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
    }
}

Any help/advice that can help me to understand what is causing this, would be really appreciated.

Body:
After reading all the suggest answers, figured out a simple solution:

First I stored my answers sent from my external database as so -

final String jsonAnswers = gson.toJson (resp.getAnswer().getAnswerStringEdit());

Then saved in shared pref -

editor.putString(Constants.ANSWER_EDIT,jsonAnswers);

Next to read the answer back out:

String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
final String[] array = gson.fromJson (answerString, String[].class);

Finally, I could set my Edittext with data from the array:

et_answer1_edit.append(array[0].trim());

et_answer2_edit.append(array[1].trim());


来源: stackexchange

问:
If statements to check two conditions
Trying to remove/filter away observations if two if one variable is NA but then not filter them if the variable Male is == 2

```<code>Ex <- readRDS("Session07//More data//ex.Rda")

Ex01 <- Ex %>%
  if(is.na(Ex$Idnumber02)=="TRUE"){
    if(Ex$Male==1){
      filter(!is.na(Idnumber02))
    }
  }
</code>```

but it keeps returning this error:

```<code>Error in if (.) is.na(Exam$Idnumber02) == "TRUE" else { :
  argument is not interpretable as logical
In addition: Warning message:
In if (.) is.na(Exam$Idnumber02) == "TRUE" else { :
  the condition has length > 1 and only the first element will be used
</code>```

Does anyone(i am sure most of you do) know where im wrong ?

答:
Alternative:</p>

```<code>Ex = Ex %>% filter(!is.na(Idnumber02) | Male == '2')
</code>```

ContentLicense: CC BY-SA 3.0

Title: If statements to check two conditions

Body:
Trying to remove/filter away observations if two if one variable is NA but then not filter them if the variable Male is == 2

Ex <- readRDS("Session07//More data//ex.Rda")

Ex01 <- Ex %>%
  if(is.na(Ex$Idnumber02)=="TRUE"){
    if(Ex$Male==1){
      filter(!is.na(Idnumber02))
    }
  }

but it keeps returning this error:

Error in if (.) is.na(Exam$Idnumber02) == "TRUE" else { :
  argument is not interpretable as logical
In addition: Warning message:
In if (.) is.na(Exam$Idnumber02) == "TRUE" else { :
  the condition has length > 1 and only the first element will be used

Does anyone(i am sure most of you do) know where im wrong ?

Body:
Alternative:

Ex = Ex %>% filter(!is.na(Idnumber02) | Male == '2')


问:
Scriptcraft location & events
Hello i'm trying to add events and location to an function so whenever a block is placed on an certain block it gives you a message and adds +1 to the score it doesn't have any errors but it doesn't work I have never programmed in javascript before so.

var score = 0
events.blockPlace( function (event, location) {
if (location.x == -239.538 && location.y == 71.000 &&
location.z ==314.407 ) {
 echo(event.player, 'You have just placed an block');
 var scored = score =+ 1

}
});```

答:
Code piece below should work with Spigot and Scriptcraft.

The block position is stored in event.block. The location variable you provided is a method to cancel this event.

The positions provided by the block are integers not floats.

```<code>var score = 0;
var block_place_event = events.blockPlace(function(event){
    if ((event.block.x == -239) && (event.block.y == 71) && (event.block.z == 314)){
        echo(event.player, 'You have just place an block');
        score = score + 1;
    }
});
</code>```

Title: Scriptcraft location & events

Body:
Code piece below should work with Spigot and Scriptcraft.

The block position is stored in event.block. The location variable you provided is a method to cancel this event.

The positions provided by the block are integers not floats.

var score = 0;
var block_place_event = events.blockPlace(function(event){
    if ((event.block.x == -239) && (event.block.y == 71) && (event.block.z == 314)){
        echo(event.player, 'You have just place an block');
        score = score + 1;
    }
});


问:
PHP 7.2 Warning: "Cannot change session name when session is active"
Since PHP on our server was upgraded to 7.2 from 7.0. I am getting the following warning (which leads to error) if a new deployment is done. The reason is probably, that old sessions get invalid after deployment.

Warning: session_name(): Cannot change session name when session is
  active in /var/www/html/model/login/lib/Session.class.php on line 137

Warning: session_set_cookie_params(): Cannot change session cookie
  parameters when session is active in
  /var/www/html/model/login/lib/Session.class.php on line 138

Warning: Cannot modify header information - headers already sent by
  (output started at
  /var/www/html/model/login/lib/Session.class.php:137) in
  /var/www/html/model/login/lib/Session.class.php on line 142

It seems like PHP 7.2 got more strict in the context of session sin a certain context. The server seems to recognize the invalid sessions and tries to destroy those. This is part of the Session class:

```<code>/**
 * Secure instant destruction of session. Must be called after session_start !
 */
public static function destroyAbsolute() {

    self::checkInit(); // unimportant

    session_name(self::$name); // this is line 137
    session_set_cookie_params(0, COOKIEPATH, null, self::$force_ssl_cookie, true);

    if(session_id()) {
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), "", time() - 42000, COOKIEPATH);
        }
        unset($_COOKIE[session_name()]);
        session_destroy();
    }
}
</code>```

What has changed in PHP regarding sessions?

Why is it not allowed to set a session name if another session is active (according to the docs with session_name I could change sessions and start multiple sessions)?

And how may I destroy the running session appropriately?

Doing further research I also have found the following discussion on GitHub (https://github.com/Icinga/icingaweb2/issues/3185). They confirm that this error was introduced with PHP 7.2. Unfortunatly there is also no answer :-/

答:
I have done a bug report at php.net and they explained that this is not a bug. Yes in PHP 7.2 a warning is generated now. However this never worked as intended, it just failed silently.

For creating multiple sessions it is required to use session_id(). Have a look at this related question: PHP How can I create multiple sessions?

session_name() as well as session_set_cookie_params() are always nonesense if the session is already running.

For the original answer have a look here: https://bugs.php.net/bug.php?id=75650&thanks=2

Body:
Since PHP on our server was upgraded to 7.2 from 7.0. I am getting the following warning (which leads to error) if a new deployment is done. The reason is probably, that old sessions get invalid after deployment.

Warning: session_name(): Cannot change session name when session is
  active in /var/www/html/model/login/lib/Session.class.php on line 137

Warning: session_set_cookie_params(): Cannot change session cookie
  parameters when session is active in
  /var/www/html/model/login/lib/Session.class.php on line 138

Warning: Cannot modify header information - headers already sent by
  (output started at
  /var/www/html/model/login/lib/Session.class.php:137) in
  /var/www/html/model/login/lib/Session.class.php on line 142

It seems like PHP 7.2 got more strict in the context of session sin a certain context. The server seems to recognize the invalid sessions and tries to destroy those. This is part of the Session class:

/**
 * Secure instant destruction of session. Must be called after session_start !
 */
public static function destroyAbsolute() {

    self::checkInit(); // unimportant

    session_name(self::$name); // this is line 137
    session_set_cookie_params(0, COOKIEPATH, null, self::$force_ssl_cookie, true);

    if(session_id()) {
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), "", time() - 42000, COOKIEPATH);
        }
        unset($_COOKIE[session_name()]);
        session_destroy();
    }
}

What has changed in PHP regarding sessions?

Why is it not allowed to set a session name if another session is active (according to the docs with session_name I could change sessions and start multiple sessions)?

And how may I destroy the running session appropriately?

Doing further research I also have found the following discussion on GitHub (https://github.com/Icinga/icingaweb2/issues/3185). They confirm that this error was introduced with PHP 7.2. Unfortunatly there is also no answer :-/


问:
"Spell check" and return the corrected term in Python
I recently extracted text data from a directory of pdf files. When reading pdfs, sometimes the text returned is a little messy.

For example, I can be looking at a string that says:

"T he administrati on is doing bad things, and not fulfilling what it
  prom ised"

I want the result to be:

"The administration is doing bad things, and not fulfilling what it
  promised"

I tested code (using pyenchant and wx) I found on stackoverflow here and it did not return what I wanted. My modifications were as follows:

```<code>a = "T he administrati on is doing bad things, and not fulfilling what it prom ised"
chkr = enchant.checker.SpellChecker("en_US")
chkr.set_text(a)
for err in chkr:
    sug = err.suggest()[0]
    err.replace(sug)

c = chkr.get_text()#returns corrected text
print(c)
</code>```

This code returns:

"T he administrate on is doing bad things, and not fulfilling what it
  prom side"

I'm using Python 3.5.x on a Windows 7 Enterprise, 64-bit. I would appreciate any suggestions!

答:
I have taken Generic Human’s answer, slightly modified it to solve your problem.

You need to copy these 125k words, sorted by frequency into a text file, name the file words-by-frequency.txt.

```<code>from math import log

# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
with open("words-by-frequency.txt") as f:
    words = [line.strip() for line in f.readlines()]
    wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
    maxword = max(len(x) for x in words)

def infer_spaces(s):
    """Uses dynamic programming to infer the location of spaces in a string
    without spaces."""

    # Find the best match for the i first characters, assuming cost has
    # been built for the i-1 first characters.
    # Returns a pair (match_cost, match_length).
    def best_match(i):
        candidates = enumerate(reversed(cost[max(0, i-maxword):i]))
        return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates)

    # Build the cost array.
    cost = [0]
    for i in range(1,len(s)+1):
        c,k = best_match(i)
        cost.append(c)

    # Backtrack to recover the minimal-cost string.
    out = []
    i = len(s)
    while i>0:
        c,k = best_match(i)
        assert c == cost[i]
        out.append(s[i-k:i])
        i -= k

    return " ".join(reversed(out))
</code>```

Running the function with the input:

```<code>messy_txt = "T he administrati on is doing bad things, and not fulfilling what it prom ised"

print(infer_spaces(messy_txt.lower().replace(' ', '').replace(',', '')).capitalize())

The administration is doing bad things and not fulfilling what it promised
>>>
</code>```

Edit: The code below doesn't require the text file and works just for your input i.e., "T he administrati on is doing bad things, and not fulfilling what it prom ised"

```<code>from math import log

# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
words = ["the", "administration", "is", "doing", "bad",
         "things", "and", "not", "fulfilling", "what",
         "it", "promised"]
wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
maxword = max(len(x) for x in words)

def infer_spaces(s):
    """Uses dynamic programming to infer the location of spaces in a string
    without spaces."""

    # Find the best match for the i first characters, assuming cost has
    # been built for the i-1 first characters.
    # Returns a pair (match_cost, match_length).
    def best_match(i):
        candidates = enumerate(reversed(cost[max(0, i-maxword):i]))
        return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates)

    # Build the cost array.
    cost = [0]
    for i in range(1,len(s)+1):
        c,k = best_match(i)
        cost.append(c)

    # Backtrack to recover the minimal-cost string.
    out = []
    i = len(s)
    while i>0:
        c,k = best_match(i)
        assert c == cost[i]
        out.append(s[i-k:i])
        i -= k

    return " ".join(reversed(out))

messy_txt = "T he administrati on is doing bad things, and not fulfilling what it prom ised"

print(infer_spaces(messy_txt.lower().replace(' ', '').replace(',', '')).capitalize())

The administration is doing bad things and not fulfilling what it promised
>>>
</code>```

I have just tried the above edit at repl.it and it printed the output as shown.

Body:
I recently extracted text data from a directory of pdf files. When reading pdfs, sometimes the text returned is a little messy.

For example, I can be looking at a string that says:

"T he administrati on is doing bad things, and not fulfilling what it
  prom ised"

I want the result to be:

"The administration is doing bad things, and not fulfilling what it
  promised"

I tested code (using pyenchant and wx) I found on stackoverflow here and it did not return what I wanted. My modifications were as follows:

a = "T he administrati on is doing bad things, and not fulfilling what it prom ised"
chkr = enchant.checker.SpellChecker("en_US")
chkr.set_text(a)
for err in chkr:
    sug = err.suggest()[0]
    err.replace(sug)

c = chkr.get_text()#returns corrected text
print(c)

This code returns:

"T he administrate on is doing bad things, and not fulfilling what it
  prom side"

I'm using Python 3.5.x on a Windows 7 Enterprise, 64-bit. I would appreciate any suggestions!

Body:
I have taken Generic Human’s answer, slightly modified it to solve your problem.

You need to copy these 125k words, sorted by frequency into a text file, name the file words-by-frequency.txt.

from math import log

# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
with open("words-by-frequency.txt") as f:
    words = [line.strip() for line in f.readlines()]
    wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
    maxword = max(len(x) for x in words)

def infer_spaces(s):
    """Uses dynamic programming to infer the location of spaces in a string
    without spaces."""

    # Find the best match for the i first characters, assuming cost has
    # been built for the i-1 first characters.
    # Returns a pair (match_cost, match_length).
    def best_match(i):
        candidates = enumerate(reversed(cost[max(0, i-maxword):i]))
        return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates)

    # Build the cost array.
    cost = [0]
    for i in range(1,len(s)+1):
        c,k = best_match(i)
        cost.append(c)

    # Backtrack to recover the minimal-cost string.
    out = []
    i = len(s)
    while i>0:
        c,k = best_match(i)
        assert c == cost[i]
        out.append(s[i-k:i])
        i -= k

    return " ".join(reversed(out))

Running the function with the input:

messy_txt = "T he administrati on is doing bad things, and not fulfilling what it prom ised"

print(infer_spaces(messy_txt.lower().replace(' ', '').replace(',', '')).capitalize())

The administration is doing bad things and not fulfilling what it promised
>>>

Edit: The code below doesn't require the text file and works just for your input i.e., "T he administrati on is doing bad things, and not fulfilling what it prom ised"

from math import log

# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
words = ["the", "administration", "is", "doing", "bad",
         "things", "and", "not", "fulfilling", "what",
         "it", "promised"]
wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
maxword = max(len(x) for x in words)

def infer_spaces(s):
    """Uses dynamic programming to infer the location of spaces in a string
    without spaces."""

    # Find the best match for the i first characters, assuming cost has
    # been built for the i-1 first characters.
    # Returns a pair (match_cost, match_length).
    def best_match(i):
        candidates = enumerate(reversed(cost[max(0, i-maxword):i]))
        return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates)

    # Build the cost array.
    cost = [0]
    for i in range(1,len(s)+1):
        c,k = best_match(i)
        cost.append(c)

    # Backtrack to recover the minimal-cost string.
    out = []
    i = len(s)
    while i>0:
        c,k = best_match(i)
        assert c == cost[i]
        out.append(s[i-k:i])
        i -= k

    return " ".join(reversed(out))

messy_txt = "T he administrati on is doing bad things, and not fulfilling what it prom ised"

print(infer_spaces(messy_txt.lower().replace(' ', '').replace(',', '')).capitalize())

The administration is doing bad things and not fulfilling what it promised
>>>

I have just tried the above edit at repl.it and it printed the output as shown.


问:
MailGun Api Example
I'm doing a test with mailgun, and I copy the example and put my domain and password, but it's not going, and I do not get the mail either

I have put my : Domain Name and API Key.

```<code>import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public static JsonNode sendSimpleMessage() throws UnirestException {

    HttpResponse<JsonNode> request = Unirest
            .post("https://api.mailgun.net/v3/" + "sandbox21801cd223b94bbc92dbd011424xxxxx.mailgun.org"
                    + "/messages")
            .basicAuth("api", "xxx8013e6a2e75889370b0d2e670b2e")
            .queryString("from", "Excited User <notifications-noreply@miempresa.com>")
            .queryString("to", "joseluis.garcia@miempresa.com").queryString("subject", "hello")
            .queryString("text", "testing").asJson();

    return request.getBody();
}
</code>```

Error:

```<code>Exception in thread "main" com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at com.abalia.crm482.sms_mail.mailSendInfobip.sendSimpleMessage(mailSendInfobip.java:22)
at com.abalia.crm482.sms_mail.mailSendInfobip.main(mailSendInfobip.java:11)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:106)
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:139)
... 3 more

Caused by: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:51)
at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:95)
... 4 more
Caused by: org.json.JSONException: A JSONArray text must start with '[' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONArray.<init>(JSONArray.java:113)
at org.json.JSONArray.<init>(JSONArray.java:157)
at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:48)
... 5 more
</code>```

答:
I had the same issue when I passed in a wrong key. By replacing public key with private key (which you can find from mailgun console), I fixed this problem.

Basically what happened when you pass in a wrong key is like this:
If you debug inside into com.mashape.unirest.http.HttpResponse<T>, inside the constructor, you will find how the JsonNode was build. And rawBody, which suppose to be a json string, become a simple String: Forbidden if you failed the key authentication. And trying to build a JsonArray from such a string throws such exception.

Hope it helps~

Title: MailGun Api Example

Body:
I'm doing a test with mailgun, and I copy the example and put my domain and password, but it's not going, and I do not get the mail either

I have put my : Domain Name and API Key.

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public static JsonNode sendSimpleMessage() throws UnirestException {

    HttpResponse<JsonNode> request = Unirest
            .post("https://api.mailgun.net/v3/" + "sandbox21801cd223b94bbc92dbd011424xxxxx.mailgun.org"
                    + "/messages")
            .basicAuth("api", "xxx8013e6a2e75889370b0d2e670b2e")
            .queryString("from", "Excited User <notifications-noreply@miempresa.com>")
            .queryString("to", "joseluis.garcia@miempresa.com").queryString("subject", "hello")
            .queryString("text", "testing").asJson();

    return request.getBody();
}

Error:

Exception in thread "main" com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at com.abalia.crm482.sms_mail.mailSendInfobip.sendSimpleMessage(mailSendInfobip.java:22)
at com.abalia.crm482.sms_mail.mailSendInfobip.main(mailSendInfobip.java:11)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:106)
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:139)
... 3 more

Caused by: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at character 1
at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:51)
at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:95)
... 4 more
Caused by: org.json.JSONException: A JSONArray text must start with '[' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONArray.<init>(JSONArray.java:113)
at org.json.JSONArray.<init>(JSONArray.java:157)
at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:48)
... 5 more


问:
how to use yocto sdcard image
I am very new to yocto world, I am following below instructions to compile yocto.

http://doc.qt.io/QtForDeviceCreation/qtee-custom-embedded-linux-image.html

When I compiled yocto(boot2qt) from qt repository I got sdcard image. When I flashed sdcard to memory card I observed that there is no files in /boot/ directory kernel and dtb files are present in another partition mmc1p1. My u-boot configuration is as below

```<code>setenv bootargs 'console=ttymxc1,115200 root=/dev/mmcblk0p2 rootwait fixrtc rw'
setenv bootcmd 'mmc dev 1; ext2load mmc 1:2 10800000 /boot/zImage;ext2load mmc 1:2 0x12000000 /boot/imx6q-sabrelitesd.dtb; bootz 0x10800000 - 0x12000000'
saveenv
</code>```

And its not booting because there is no files in /boot/ directory. Then I changed my uboot configuration as below

```<code>setenv bootcmd 'mmc dev 1; ext2load mmc 1:2 10800000 /zImage;ext2load mmc 1:2 0x12000000 /imx6q-sabrelitesd.dtb; bootz 0x10800000 - 0x12000000'
</code>```

and I am getting file not found error, so its clear that I have mentioned
root=/dev/mmcblk0p2 and I am trying to load kernel from mmc0p1

How to fix this issue? Should I have to do something on yocto configuration and make kernel and dtb files to be available in /boot/ directory or I have to change u-boot configuration to load kernel from different partition and rootfs from different partition?

答:
The problem here is you are still trying to load kernel and dtb from partition 2, you have to update bootcmd. And as per my knowledge with yocto  partition1 will be in FAT file system so you have to use fatload.</p>

```<code>setenv bootcmd 'mmc dev 1; fatload mmc 1:1 10800000 /zImage; fatload mmc 1:1 0x12000000 /imx6q-sabrelitesd.dtb; bootz 0x10800000 - 0x12000000'
</code>```

Title: how to use yocto sdcard image

Body:
I am very new to yocto world, I am following below instructions to compile yocto.

http://doc.qt.io/QtForDeviceCreation/qtee-custom-embedded-linux-image.html

When I compiled yocto(boot2qt) from qt repository I got sdcard image. When I flashed sdcard to memory card I observed that there is no files in /boot/ directory kernel and dtb files are present in another partition mmc1p1. My u-boot configuration is as below

setenv bootargs 'console=ttymxc1,115200 root=/dev/mmcblk0p2 rootwait fixrtc rw'
setenv bootcmd 'mmc dev 1; ext2load mmc 1:2 10800000 /boot/zImage;ext2load mmc 1:2 0x12000000 /boot/imx6q-sabrelitesd.dtb; bootz 0x10800000 - 0x12000000'
saveenv

And its not booting because there is no files in /boot/ directory. Then I changed my uboot configuration as below

setenv bootcmd 'mmc dev 1; ext2load mmc 1:2 10800000 /zImage;ext2load mmc 1:2 0x12000000 /imx6q-sabrelitesd.dtb; bootz 0x10800000 - 0x12000000'

and I am getting file not found error, so its clear that I have mentioned
root=/dev/mmcblk0p2 and I am trying to load kernel from mmc0p1

How to fix this issue? Should I have to do something on yocto configuration and make kernel and dtb files to be available in /boot/ directory or I have to change u-boot configuration to load kernel from different partition and rootfs from different partition?

Body:
The problem here is you are still trying to load kernel and dtb from partition 2, you have to update bootcmd. And as per my knowledge with yocto  partition1 will be in FAT file system so you have to use fatload.

setenv bootcmd 'mmc dev 1; fatload mmc 1:1 10800000 /zImage; fatload mmc 1:1 0x12000000 /imx6q-sabrelitesd.dtb; bootz 0x10800000 - 0x12000000'


问:
string: replace "(" with "\("
i have to send a string to the bash, which contains an escape sequence. For example, i have to replace special characters like "(" with "(", because the bash else throws errors. I trtied like

```<code>public class escape {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("(", "\\(");
        System.out.println(s);
    }
}
</code>```

with no luck. Please help!!

thanks

答:
This is happening because the ( is a special character according to the regexp syntax (which is used by replaceAll).

You should take Skeet's advice and use "replace" instead in this case, but to give you an idea of how the regexp version works, here's a fixed example:

```<code>public class test {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("\\(", "\\\\(");
        System.out.println(s);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: string: replace "(" with "\("

Body:
i have to send a string to the bash, which contains an escape sequence. For example, i have to replace special characters like "(" with "(", because the bash else throws errors. I trtied like

public class escape {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("(", "\\(");
        System.out.println(s);
    }
}

with no luck. Please help!!

thanks

Body:
This is happening because the ( is a special character according to the regexp syntax (which is used by replaceAll).

You should take Skeet's advice and use "replace" instead in this case, but to give you an idea of how the regexp version works, here's a fixed example:

public class test {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("\\(", "\\\\(");
        System.out.println(s);
    }
}


问:
Hibernate Spring MVC
I am trying to get Products by categoryId, categoryName and so I was writing in some custom queries but nothing seems to work. I am new to hibernate.

// this is my product class

```<code>    package springmvc.java.domain;
    @Entity
    @Table(name = "product")
    public class Product {

        @Id
        @Column(name = "productId" , nullable = false)
        private Long productId;

        @Column(name = "productName", nullable = false)
        private String productName;

        @Column(name = "productCost", nullable = false)
        private double productCost;

        @Column(name = "productDescription")
        private String productDescription;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "categoryId", nullable = false)
        private Category category;

        public Long getProductId() {
            return productId;
        }

        public void setProductId(Long productId) {
            this.productId = productId;
        }

        public String getProductName() {
            return productName;
        }

        public void setProductName(String productName) {
            this.productName = productName;
        }

        public double getProductCost() {
            return productCost;
        }

        public void setProductCost(double productCost) {
            this.productCost = productCost;
        }

        public String getProductDescription() {
            return productDescription;
        }

        public void setProductDescription(String productDescription) {
            this.productDescription = productDescription;
        }

    }
</code>```

// ********************************************************

//category class

```<code>    package springmvc.java.domain;
    @Entity
    @Table(name = "category")
    public class Category {

        @Id
        @Column(name = "categoryId", nullable = false)
        private Long categoryId;

        @Column(name = "categoryName", nullable = false)
        private String categoryName;

        @Column(name = "categoryDescription")
        private String categoryDescription;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "category", fetch = FetchType.EAGER)
        private List<Product> products;

        public Long getCategoryId() {
            return categoryId;
        }

        public void setCategoryId(Long categoryId) {
            this.categoryId = categoryId;
        }

        public String getCategoryName() {
            return categoryName;
        }

        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }

        public String getCategoryDescription() {
            return categoryDescription;
        }

        public void setCategoryDescription(String categoryDescription) {
            this.categoryDescription = categoryDescription;
        }

        public List<Product> getProducts() {
            return products;
        }

        public void setProducts(List<Product> products) {
            this.products = products;
        }

    }
</code>```

// ********************************************************
//My product DAO

which extends JPA Repository
 I am trying to write custom methods with the help of @Query Annotation

```<code>    package springmvc.java.dao;
    import springmvc.java.domain.Product;
    public interface ProductDAO extends JpaRepository<Product,Long> {

        @Query("select p from Product p where p.categoryId = :categoryId")
        public List<Product> findProductsByCategoryId(@Param("categoryId") Long categoryId);`enter code here`
    }
</code>```

// ********************************************************

//Stack Trace

```<code>Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List springmvc.java.dao.ProductDAO.findProductsByCategoryId(java.lang.Long)!
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:62)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:72)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:53)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:136)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:204)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:73)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:416)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:206)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:251)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:237)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    ... 47 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
    at com.sun.proxy.$Proxy36.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
    ... 60 more
Caused by: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
    at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1968)
    at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:313)
    at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:494)
    at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:598)
    at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:266)
    at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:213)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:118)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:114)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:881)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1264)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4426)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3898)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2076)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:794)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:595)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)
    ... 67 more
</code>```

答:
Correct query - select p from Product p where p.category = :categoryId"

Please note that, property name defined in Product entity is 'category' and not 'catagoryid'.
Hope correcting query above resolves exception.

Title: Hibernate Spring MVC

Body:
I am trying to get Products by categoryId, categoryName and so I was writing in some custom queries but nothing seems to work. I am new to hibernate.

// this is my product class

    package springmvc.java.domain;
    @Entity
    @Table(name = "product")
    public class Product {

        @Id
        @Column(name = "productId" , nullable = false)
        private Long productId;

        @Column(name = "productName", nullable = false)
        private String productName;

        @Column(name = "productCost", nullable = false)
        private double productCost;

        @Column(name = "productDescription")
        private String productDescription;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "categoryId", nullable = false)
        private Category category;

        public Long getProductId() {
            return productId;
        }

        public void setProductId(Long productId) {
            this.productId = productId;
        }

        public String getProductName() {
            return productName;
        }

        public void setProductName(String productName) {
            this.productName = productName;
        }

        public double getProductCost() {
            return productCost;
        }

        public void setProductCost(double productCost) {
            this.productCost = productCost;
        }

        public String getProductDescription() {
            return productDescription;
        }

        public void setProductDescription(String productDescription) {
            this.productDescription = productDescription;
        }

    }

// ********************************************************

//category class

    package springmvc.java.domain;
    @Entity
    @Table(name = "category")
    public class Category {

        @Id
        @Column(name = "categoryId", nullable = false)
        private Long categoryId;

        @Column(name = "categoryName", nullable = false)
        private String categoryName;

        @Column(name = "categoryDescription")
        private String categoryDescription;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "category", fetch = FetchType.EAGER)
        private List<Product> products;

        public Long getCategoryId() {
            return categoryId;
        }

        public void setCategoryId(Long categoryId) {
            this.categoryId = categoryId;
        }

        public String getCategoryName() {
            return categoryName;
        }

        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }

        public String getCategoryDescription() {
            return categoryDescription;
        }

        public void setCategoryDescription(String categoryDescription) {
            this.categoryDescription = categoryDescription;
        }

        public List<Product> getProducts() {
            return products;
        }

        public void setProducts(List<Product> products) {
            this.products = products;
        }

    }

// ********************************************************
//My product DAO

which extends JPA Repository
 I am trying to write custom methods with the help of @Query Annotation

    package springmvc.java.dao;
    import springmvc.java.domain.Product;
    public interface ProductDAO extends JpaRepository<Product,Long> {

        @Query("select p from Product p where p.categoryId = :categoryId")
        public List<Product> findProductsByCategoryId(@Param("categoryId") Long categoryId);`enter code here`
    }

// ********************************************************

//Stack Trace

Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List springmvc.java.dao.ProductDAO.findProductsByCategoryId(java.lang.Long)!
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:62)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:72)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:53)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:136)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:204)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:73)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:416)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:206)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:251)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:237)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    ... 47 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
    at com.sun.proxy.$Proxy36.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
    ... 60 more
Caused by: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
    at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1968)
    at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:313)
    at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:494)
    at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:598)
    at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:266)
    at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:213)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:118)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:114)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:881)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1264)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4426)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3898)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2076)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:794)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:595)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)
    ... 67 more


问:
Is not matching a template<typename...> to template<typename> a defect?
While exploring this answer I discovered that a template that takes a parameter pack will not be accepted by a template that expects template that has a specific number of parameters.

This seems to me that it is a defect since if a template can take any number of parameters, it should be able to map to a specific number.  Is there a language lawyer that could explain why this is not allowed?

Here is a simple example:

```<code>template <typename...Ts>
using pack = void;

template <template <typename> class>
using accept_template = int;

accept_template<pack> value = 0;
</code>```

I wouldn't use it in this exact scenario of course.  It would be used to pass a template to another template which would use the passed template in some manner.  In my answer that I linked, I have stated a workaround, but I still feel that this is a defect.

答:
This restriction was loosened as a result of P0522, which introduces new rules to handle how template template-arguments match template template-parameters. As a result, from the paper:

```<code>template<class T, class U = T> class B { /* ... */ };
template <class ... Types> class C { /* ... */ };
template<template<class> class P> class X { /* ... */ };

X<B> xb; // OK, was ill-formed:
         // default arguments for the parameters of a template argument are ignored

X<C> xc; // OK, was ill-formed:
         // a template parameter pack does not match a template parameter
</code>```

Your example fails to compile in C++14, but will compile in C++17.

Body:
While exploring this answer I discovered that a template that takes a parameter pack will not be accepted by a template that expects template that has a specific number of parameters.

This seems to me that it is a defect since if a template can take any number of parameters, it should be able to map to a specific number.  Is there a language lawyer that could explain why this is not allowed?

Here is a simple example:

template <typename...Ts>
using pack = void;

template <template <typename> class>
using accept_template = int;

accept_template<pack> value = 0;

I wouldn't use it in this exact scenario of course.  It would be used to pass a template to another template which would use the passed template in some manner.  In my answer that I linked, I have stated a workaround, but I still feel that this is a defect.

Body:
This restriction was loosened as a result of P0522, which introduces new rules to handle how template template-arguments match template template-parameters. As a result, from the paper:

template<class T, class U = T> class B { /* ... */ };
template <class ... Types> class C { /* ... */ };
template<template<class> class P> class X { /* ... */ };

X<B> xb; // OK, was ill-formed:
         // default arguments for the parameters of a template argument are ignored

X<C> xc; // OK, was ill-formed:
         // a template parameter pack does not match a template parameter

Your example fails to compile in C++14, but will compile in C++17.


问:
ValueError: Cannot run multiple SparkContexts at once in spark with pyspark
i am new in using spark , i try to run this code on pyspark

```<code>from pyspark import SparkConf, SparkContext
import collections

conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
sc = SparkContext(conf = conf)
</code>```

but he till me this erore message

```<code>Using Python version 3.5.2 (default, Jul  5 2016 11:41:13)
SparkSession available as 'spark'.
>>> from pyspark import SparkConf, SparkContext
>>> import collections
>>> conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
>>> sc = SparkContext(conf = conf)

   Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\spark\python\pyspark\context.py", line 115, in __init__
        SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
      File "C:\spark\python\pyspark\context.py", line 275, in _ensure_initialized
        callsite.function, callsite.file, callsite.linenum))
    ValueError: Cannot run multiple SparkContexts at once; existing SparkContext(app=PySparkShell, master=local[*]) created by getOrCreate at C:\spark\bin\..\python\pyspark\shell.py:43
    >>>
</code>```

i have version spark 2.1.1 and python 3.5.2 , i search and found it is problem in sc ,he could not read it but no when till why , any one have help here

答:
You can try out this

sc = SparkContext.getOrCreate();

Body:
i am new in using spark , i try to run this code on pyspark

from pyspark import SparkConf, SparkContext
import collections

conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
sc = SparkContext(conf = conf)

but he till me this erore message

Using Python version 3.5.2 (default, Jul  5 2016 11:41:13)
SparkSession available as 'spark'.
>>> from pyspark import SparkConf, SparkContext
>>> import collections
>>> conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
>>> sc = SparkContext(conf = conf)

   Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\spark\python\pyspark\context.py", line 115, in __init__
        SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
      File "C:\spark\python\pyspark\context.py", line 275, in _ensure_initialized
        callsite.function, callsite.file, callsite.linenum))
    ValueError: Cannot run multiple SparkContexts at once; existing SparkContext(app=PySparkShell, master=local[*]) created by getOrCreate at C:\spark\bin\..\python\pyspark\shell.py:43
    >>>

i have version spark 2.1.1 and python 3.5.2 , i search and found it is problem in sc ,he could not read it but no when till why , any one have help here


问:
The Git command "git reset --hard" is not working as expected
As I understand it calling "git reset --hard" should undo any changes on my computer. However after running it, I have 1,459 files on my system Git says I need to add or merge to the branch I am working on.

How can I have it throw away all changes on my computer (I do want to keep the changes I have pushed up already)?

If it's relevant, this occurred because Visual Studio ran out of memory half way through switching to another branch. So I think it left files from the one branch on my system but marked itself as on the switched to branch.

答:
TL;DR

Try removing the index (remove the file .git/index), then running git reset --hard origin/support-15.2.  This isn't a normal thing to do, but your situation is not normal either.

Description

It sure sounds like Visual Studio goofed up the "disk full" error-handling.

As another recent Q&A noted, when we work in Git (without some IDE in the way), we have three main parts of interest:

The repository itself, usually hidden inside a directory named .git (but not when using a --bare repository).

The repository stores objects (it's a sort of key/value database), plus some ancillary data, most significantly a mapping from names—which Git normally presents as "branch B" or "tag T", but the general format is reference names—to object hash IDs, such as the big ugly commit hashes.  Since the hashes appear random, Git (and we) need a way to turn a consistent, sensible name like master into the hash ID of the commit to treat as the most recent commit on a branch.  (This mapping changes over time, as we add more and more commits.)

Objects inside the repository are stored in a special Git-only format.  They are also read-only, once created: an object is either there, containing the same value it had when it was saved into the key/value store initially and forever; or it's not there at all.  If one runs out of disk space, this database must maintain this same property (objects must still be all-or-nothing).

The name-to-object-ID mappings are read/write, since they do change.  Running out of disk space could cause you to lose some mappings, which is significant since it's these mappings themselves that make objects reachable.

The work-tree (or working-tree, or working directory, or various additional names, all for "the place where you do your work").

Files in the work-tree have their normal everyday form, and are read/write, like normal everyday files.

The index, also called the staging area and the cache.

The index is, in a sense, entirely unnecessary, but it's how Git gets much of its speed.  It also enables a bunch of tricky items like git add -p.  The actual implementation of the index is as a file, .git/index, but the format and contents of that file are nontrivial (and now there's something called a split index where the index is in more than one file; and when you use git worktree add, you get one index per work-tree, so you should not assume .git/index anyway).

The index, like the work-tree, is necessarily read/write.  It has several roles: it not only lets you stage items for commit (via git add <file>), it also caches information about all the work-tree files.  This is why it has the names staging area and cache.  The cached information lets git status go very fast—but assumes that the index has been correctly adjusted based on the contents of the work-tree, and vice versa.

A normal git checkout and series of git adds keeps this cache data up to date, so that the index and work-tree match each other.  I suspect that after running out of space, VS and/or the underlying Git code got the two out of sync.  If they got them sufficiently badly de-synchronized, it's possible that even an ordinary git reset --hard is not getting them back in sync.

In this case, as long as you have no staged modifications, no in-progress merges, and the like, it's safe enough to remove the index entirely.  This loses all the cached information about the current commit and about the current work-tree contents, which forces Git to rebuild it all from scratch.  A subsequent git reset with either --mixed or --hard will do this rebuilding.  With --mixed, Git will make index entries for files in the target commit of the git reset,1 looking at what's in the work-tree, without touching the work-tree.  With --hard, Git will make these index entries and at the same time re-set the work-tree files to match the target commit.  If some work-tree files are left over from a half-conversion from some other commit hash ID, making them all match the hash ID to which origin/support-15.2 resolves is probably the right thing to do.

(As always, if you're not quite sure, you can save the work-tree contents somewhere out of the reach of Git itself, then use whatever tools you like to compare the saved tree with what Git extracts.)

1The target is what I call the commit argument to git reset:

git reset [--type] target (where type is one of soft, mixed, or hard)

The Git documentation calls this a <commit>, but there are lots of commits.  If you specify a raw hash ID, this must be the hash ID of a commit, and Git will change the current branch name—whatever branch name that is—so that it names that specific hash ID as its current commit.  If you specify a name, such as origin/support-15.2, Git just resolves that name to a commit hash ID, and then proceeds as if you'd given it a commit hash ID.

With --soft, Git changes the current branch to point to the target commit, and stops.  With --mixed, Git goes on to modify the index as well, and then stops.  With --hard, Git updates the work-tree while modifying the index.


问:
Change matplotlib.bar Order in python 2.7
In this example:

```<code>import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(colors, rates)
</code>```

the bars in the plot are ordered by the alphabetic order.

How do I make them to show in the same order as they are in the code (from highest to lowest rate)?

答:
Use values 0,1,2,3,4,... as x and assign colors with tick_label=

```<code>import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(range(len(colors)), rates, tick_label=colors)

plt.show()
</code>```

Body:
In this example:

import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(colors, rates)

the bars in the plot are ordered by the alphabetic order.

How do I make them to show in the same order as they are in the code (from highest to lowest rate)?

Body:
Use values 0,1,2,3,4,... as x and assign colors with tick_label=

import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(range(len(colors)), rates, tick_label=colors)

plt.show()


问:
Can a local variable exist before a combined declaration/assignment?
I'm currently trying to debug a small C program whose general structure looks like this:

```<code>int some_function(...) {
    ...
    size_t buf_len = some_other_function(...)
    ...
}

main() {
    ...
    int foo = some_function(...)
    ...
}
</code>```

I've set a breakpoint at some_function() (using lldb). However, if I inspect the stack frame at this breakpoint it shows the variable buf_len already existing with the local scope and even having an arbitrary(?) value. How is this possible if the variable is not declared anywhere before this function?

答:
According to §6.2.4/6 of the C11 Draft Standard:

For such an object that does not have a variable length array type,
  its lifetime extends from entry into the block with which it is
  associated until execution of that block ends in any way.

So it should come as no surprise that buf_len is visible in the debugger the moment execution enters some_function().

Body:
I'm currently trying to debug a small C program whose general structure looks like this:

int some_function(...) {
    ...
    size_t buf_len = some_other_function(...)
    ...
}

main() {
    ...
    int foo = some_function(...)
    ...
}

I've set a breakpoint at some_function() (using lldb). However, if I inspect the stack frame at this breakpoint it shows the variable buf_len already existing with the local scope and even having an arbitrary(?) value. How is this possible if the variable is not declared anywhere before this function?


问:
Create Parent-Child tree JSON
I have a JSON data containing moduleId and parentId, I want a new JSON with a map structure of module's parent-child.

**parentId can be null which means that module has no parent.

Current JSON-

```<code>[{
    "moduleId": 1,
    "parentId": null
 },
 {
    "moduleId": 2,
    "parentId": 1
 },
 {
    "moduleId": 3,
    "parentId": 1
 },
 {
    "moduleId": 4,
    "parentId": null
 },
 {
    "moduleId": 5,
    "parentId": null
 },
 {
    "moduleId": 6,
    "parentId": 3
 }
]
</code>```

Required JSON-

```<code>[{
    "moduleId": 1,
    "child": [{
                "moduleId": 2,
                "child": []
              },
              {
                "moduleId": 3,
                "child":[{
                            "moduleId": 6,
                            "child": []
                        }]
              }]
 },
 {
    "moduleId": 4,
    "child": []
 },
 {
    "moduleId": 5,
    "child": []
 }
]
</code>```

Current Code

Problem - children inside children are not getting mapped

```<code>function tree($list)
{
    $map = new stdClass();
    $roots = [];$node = [];

    for($i=0; $i<sizeof($list); $i++)
    {
        $c=$list[$i]["moduleId"];
        $map->$c = $i;

        $list[$i]["children"] = []; // initialize the children
    }

    for($i=0; $i<sizeof($list); $i++)
    {
        $node = $list[$i];
        if( $node["parentId"] !== "" )
        {
            $m = $node["parentId"];
            $val = $map->$m;

            $child = new StdClass;
            $child->moduleId = $node["moduleId"];
            $child->parentId = $node["parentId"];
            $child->children = [];

            array_push($list[$val]["children"],$node);

        }
    }

for($i = 0;$i<sizeof($list);$i++)
    {
        if($list[$i]["parentId"] == "")
        {
            array_push($roots, $list[$i]);
        }
    }
    return json_encode($roots);
}
</code>```

I cant figure it out. All the answers here give different kinds of result.
Can use any language(java,C,php,js,python,etc). Thankyou.

答:
```<code>var arry = [{
    "parentId": null,
    "moduleId": 1

 },
 {
    "parentId": 1,
    "moduleId": 2

 },
 {
    "parentId": 1,

    "moduleId": 3

 },
 {
    "parentId": null,
    "moduleId": 4

 },
 {
    "parentId": null,
    "moduleId": 5
 },
 {

    "parentId": 3,
    "moduleId": 6
 }
];

function convert(array){
    var map = {};
    for(var i = 0; i < array.length; i++){
        var obj = array[i];
        obj.children= [];

        map[obj.moduleId] = obj;

        var parent = obj.parentId || '-';
        if(!map[parent]){
            map[parent] = {
                children: []
            };
        }
        map[parent].children.push(obj);
    }
    return map['-'].children;
}

var r = convert(arry)
console.log('array', r);
console.log('result', JSON.stringify(r))
</code>```

Title: Create Parent-Child tree JSON

Body:
I have a JSON data containing moduleId and parentId, I want a new JSON with a map structure of module's parent-child.

**parentId can be null which means that module has no parent.

Current JSON-

[{
    "moduleId": 1,
    "parentId": null
 },
 {
    "moduleId": 2,
    "parentId": 1
 },
 {
    "moduleId": 3,
    "parentId": 1
 },
 {
    "moduleId": 4,
    "parentId": null
 },
 {
    "moduleId": 5,
    "parentId": null
 },
 {
    "moduleId": 6,
    "parentId": 3
 }
]

Required JSON-

[{
    "moduleId": 1,
    "child": [{
                "moduleId": 2,
                "child": []
              },
              {
                "moduleId": 3,
                "child":[{
                            "moduleId": 6,
                            "child": []
                        }]
              }]
 },
 {
    "moduleId": 4,
    "child": []
 },
 {
    "moduleId": 5,
    "child": []
 }
]

Current Code

Problem - children inside children are not getting mapped

function tree($list)
{
    $map = new stdClass();
    $roots = [];$node = [];

    for($i=0; $i<sizeof($list); $i++)
    {
        $c=$list[$i]["moduleId"];
        $map->$c = $i;

        $list[$i]["children"] = []; // initialize the children
    }

    for($i=0; $i<sizeof($list); $i++)
    {
        $node = $list[$i];
        if( $node["parentId"] !== "" )
        {
            $m = $node["parentId"];
            $val = $map->$m;

            $child = new StdClass;
            $child->moduleId = $node["moduleId"];
            $child->parentId = $node["parentId"];
            $child->children = [];

            array_push($list[$val]["children"],$node);

        }
    }

for($i = 0;$i<sizeof($list);$i++)
    {
        if($list[$i]["parentId"] == "")
        {
            array_push($roots, $list[$i]);
        }
    }
    return json_encode($roots);
}

I cant figure it out. All the answers here give different kinds of result.
Can use any language(java,C,php,js,python,etc). Thankyou.


问:
Python3 - using pandas to group rows, where two colums contain values in forward or reverse order: v1,v2 or v2,v1
I'm fairly new to python and pandas, but I've written code that reads an excel workbook, and groups rows based on the values contained in two columns.

So where Col_1=A and Col_2=B, or Col_1=B and Col_2=A, both would be assigned a GroupID=1.

sample spreadsheet data, with rows color coded for ease of visibility
I've manged to get this working, but I wanted to know if there's a more simpler/efficient/cleaner/less-clunky way to do this.

```<code>import pandas as pd
df = pd.read_excel('test.xlsx')

# get column values into a list
col_group = df.groupby(['Header_2','Header_3'])
original_list = list(col_group.groups)

# parse list to remove 'reverse-duplicates'
new_list = []
for a,b in original_list:
    if (b,a) not in new_list:
        new_list.append((a,b))

# iterate through each row in the DataFrame
# check to see if values in the new_list[] exist, in forward or reverse
for index, row in df.iterrows():
    for a,b in new_list:
        # if the values exist in forward direction
        if (a in df.loc[index, "Header_2"]) and (b in df.loc[index,"Header_3"]):
            # GroupID value given, where value is index in the new_list[]
            df.loc[index,"GroupID"] = new_list.index((a,b))+1
        # else check if value exists in the reverse direction
        if (b in df.loc[index, "Header_2"]) and (a in df.loc[index,"Header_3"]):
            df.loc[index,"GroupID"] = new_list.index((a,b))+1

# Finally write the DataFrame to a new spreadsheet
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer, 'Sheet1')
</code>```

I know of the pandas.groupby([columnA, columnB]) option, but I couldn't figure a way to create groups that contained both (v1, v2) and (v2,v1).

答:
A boolean mask should do the trick:

```<code>import pandas as pd
df = pd.read_excel('test.xlsx')
mask = ((df['Header_2'] == 'A') & (df['Header_3'] == 'B') |
        (df['Header_2'] == 'B') & (df['Header_3'] == 'A'))

# Label each row in the original DataFrame with
# 1 if it matches the specified criteria, and
# 0 if it does not.
# This column can now be used in groupby operations.
df.loc[:, 'match_flag'] = mask.astype(int)

# Get rows that match the criteria
df[mask]
# Get rows that do not match the criteria
df[~mask]
</code>```

EDIT: updated answer to address the groupby requirement.

Body:
I'm fairly new to python and pandas, but I've written code that reads an excel workbook, and groups rows based on the values contained in two columns.

So where Col_1=A and Col_2=B, or Col_1=B and Col_2=A, both would be assigned a GroupID=1.

sample spreadsheet data, with rows color coded for ease of visibility
I've manged to get this working, but I wanted to know if there's a more simpler/efficient/cleaner/less-clunky way to do this.

import pandas as pd
df = pd.read_excel('test.xlsx')

# get column values into a list
col_group = df.groupby(['Header_2','Header_3'])
original_list = list(col_group.groups)

# parse list to remove 'reverse-duplicates'
new_list = []
for a,b in original_list:
    if (b,a) not in new_list:
        new_list.append((a,b))

# iterate through each row in the DataFrame
# check to see if values in the new_list[] exist, in forward or reverse
for index, row in df.iterrows():
    for a,b in new_list:
        # if the values exist in forward direction
        if (a in df.loc[index, "Header_2"]) and (b in df.loc[index,"Header_3"]):
            # GroupID value given, where value is index in the new_list[]
            df.loc[index,"GroupID"] = new_list.index((a,b))+1
        # else check if value exists in the reverse direction
        if (b in df.loc[index, "Header_2"]) and (a in df.loc[index,"Header_3"]):
            df.loc[index,"GroupID"] = new_list.index((a,b))+1

# Finally write the DataFrame to a new spreadsheet
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer, 'Sheet1')

I know of the pandas.groupby([columnA, columnB]) option, but I couldn't figure a way to create groups that contained both (v1, v2) and (v2,v1).

Body:
A boolean mask should do the trick:

import pandas as pd
df = pd.read_excel('test.xlsx')
mask = ((df['Header_2'] == 'A') & (df['Header_3'] == 'B') |
        (df['Header_2'] == 'B') & (df['Header_3'] == 'A'))

# Label each row in the original DataFrame with
# 1 if it matches the specified criteria, and
# 0 if it does not.
# This column can now be used in groupby operations.
df.loc[:, 'match_flag'] = mask.astype(int)

# Get rows that match the criteria
df[mask]
# Get rows that do not match the criteria
df[~mask]

EDIT: updated answer to address the groupby requirement.


问:
Entity framework core One to One
The databse

(Project,Contest,LocalJob)-> Each one of them has 1 WorkDetails and 1 WorkDetails has one of them

Hello this is my database and I would like to ask you the following question:

Should I add a foreign key column in WorkDetails for project,contest or LocalJobs.

And if I have to how to implement navigational property?

答:
In code-first you could use owned types for this:</p>

```<code>using Microsoft.EntityFrameworkCore;
using System.Linq;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;

namespace efCoreTest
{

    class Project
    {
        public int Id { get; set; }
        public WorkDetail WorkDetail { get; set; }

    }
    class Contest
    {
        public int Id { get; set; }
        public WorkDetail WorkDetail { get; set; }
    }
    class LocalJob
    {
        public int Id { get; set; }
        public WorkDetail WorkDetail { get; set; }
    }
    class WorkDetail
    {
        public int Id { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }
    class Db : DbContext
    {
        public DbSet<Project> Projects { get; set; }
        public DbSet<Contest> Contests { get; set; }
        public DbSet<LocalJob> LocalJobs { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=.;Database=efCoreTest;Integrated Security=true");
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Project>().OwnsOne(p => p.WorkDetail);
            modelBuilder.Entity<Contest>().OwnsOne(p => p.WorkDetail);
            modelBuilder.Entity<LocalJob>().OwnsOne(p => p.WorkDetail);

            base.OnModelCreating(modelBuilder);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new Db())
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

            }

        }
    }
}
</code>```

Title: Entity framework core One to One

Body:
In code-first you could use owned types for this:

using Microsoft.EntityFrameworkCore;
using System.Linq;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;

namespace efCoreTest
{

    class Project
    {
        public int Id { get; set; }
        public WorkDetail WorkDetail { get; set; }

    }
    class Contest
    {
        public int Id { get; set; }
        public WorkDetail WorkDetail { get; set; }
    }
    class LocalJob
    {
        public int Id { get; set; }
        public WorkDetail WorkDetail { get; set; }
    }
    class WorkDetail
    {
        public int Id { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }
    class Db : DbContext
    {
        public DbSet<Project> Projects { get; set; }
        public DbSet<Contest> Contests { get; set; }
        public DbSet<LocalJob> LocalJobs { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=.;Database=efCoreTest;Integrated Security=true");
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Project>().OwnsOne(p => p.WorkDetail);
            modelBuilder.Entity<Contest>().OwnsOne(p => p.WorkDetail);
            modelBuilder.Entity<LocalJob>().OwnsOne(p => p.WorkDetail);

            base.OnModelCreating(modelBuilder);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new Db())
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

            }

        }
    }
}


答:
During compilation each variable is added to the symbol table.
For this reason any reference to a variable will resolve only if it was already declared, and inserted in the symbol table. If you reference a variable before its declaration you'll get an error of undefined reference.

But the space for all the automatic variables is allocated all-in-one in the stack during the function prolog (i.e. in IA32-64 architecture the space required by all automatic variables is obtained subtracting that space to the stack pointer register in the stack frame). The required space is computed by the compiler by summing the memory space required for all automatic variables present in the symbol table for that function.

Practically when stack frame is created on function entry all automatic variables are there, even if used after.

In some cases the variables are not allocated if the compiler optimize them out, the compiler optimizing the code choose a different way to use the variable suppressing it (i.e. using a register or simplifying the flow and removing intermediate storage).

Title: Can a local variable exist before a combined declaration/assignment?


问:
Collection View not returning cells (Swift 3)
Ok so I've added a UICollectionView inside a UIView and added an item, but I can't seem to figure out why the item is not showing in the collection view. Here's what I have so far:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView!.delegate = self
    self.collectionView!.dataSource = self
    self.collectionView.backgroundColor = UIColor.green
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
    cell.itemImage.image = UIImage(named: "banana.png")
    cell.itemName.text = "banana testing"
    return cell
}
</code>```

I can get the collection view background to change colours but for some reason it doesn't populate the items inside the collection view. Any tip would be appreciated. I've even called the reload function but still no difference:

```<code>DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
</code>```

答:
Ok so I found the answer a while ago and I thought it's best if I posted the answer. There was nothing wrong with my code or any of my connections in the storyboard. All I had to do was to go in the attributes inspector and under Collection View, change layout from Custom to Flow.

I think the older versions of Xcode automatically set the layout to Flow, but it seems that the default is Custom now. I just had to pay a bit more attention to the details.

Body:
Ok so I've added a UICollectionView inside a UIView and added an item, but I can't seem to figure out why the item is not showing in the collection view. Here's what I have so far:

override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView!.delegate = self
    self.collectionView!.dataSource = self
    self.collectionView.backgroundColor = UIColor.green
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
    cell.itemImage.image = UIImage(named: "banana.png")
    cell.itemName.text = "banana testing"
    return cell
}

I can get the collection view background to change colours but for some reason it doesn't populate the items inside the collection view. Any tip would be appreciated. I've even called the reload function but still no difference:

DispatchQueue.main.async {
            self.collectionView.reloadData()
        }


问:
make search query in adonisjs lucid
i have model called Apps with this tables
id    developer_id    title   body    price   size    version category created_at updated_at

so i want a search query by title to find the searched %string% in title

```<code>const apps = await Apps.query()
.where(‘title’, params.title)
.fetch()
</code>```

the problem is this code does not search for similar string and only looks for exact mach

答:
Remember that Lucid uses knex.js for query builder, you can use method whereRaw.
So, if you use this code may work.</p>

```<code>const apps = await Apps.query().whereRaw('title like %?%', [params.title]).fetch()
</code>```

Title: make search query in adonisjs lucid

Body:
i have model called Apps with this tables
id    developer_id    title   body    price   size    version category created_at updated_at

so i want a search query by title to find the searched %string% in title

const apps = await Apps.query()
.where(‘title’, params.title)
.fetch()

the problem is this code does not search for similar string and only looks for exact mach

Body:
Remember that Lucid uses knex.js for query builder, you can use method whereRaw.
So, if you use this code may work.

const apps = await Apps.query().whereRaw('title like %?%', [params.title]).fetch()


问:
Android database (SQLite) returns a non-empty cursor from an empty table
I verified using SQLite Database Browser that the table contains no rows. I stepped through the query builder code to get the generated query and ran the query in SQLite Database Broswer. The query returned zero rows. But still, the cursor returned by Android's SQLiteQueryBuilder.query method returns true on cursor.moveToFirst() call and returns null values.

Anyone seen something like this before?

答:
moveToFirst is actually implemented as moveToPosition(0). moveToPosition is a final method defined in AbstractCursor. Looking at the code, you can see that the result is partially depentandt on getCount. and it seems that in your case getCount returns a non-zero value.

See what's the value of the '_id' column, and try to delete it. Alternatively, try to call that code after re-creating the database (calling 'drop table' and then 'create table').


问:
Regular Expression matching in Python to extract all hashtags and its adjacent punctuations?
I want to extract all the hashtags adjacent to other hashtags/punctuations so that I can get the bigrams from them. For the following variable c I want to extract the output of ['! #helloworld #goodday #winter #christmastime !']

```<code>c = 'Hello!! This is a good day! #helloworld #goodday #winter #christmastime!'
re.findall(r'(?:#[a-zA-Z]+ #[a-zA-Z]+)|(?:[\!"#\$%&\'\(\)*+,-./\:;<=>\?\@\[\\]\^_`{|}~]+ #[a-zA-Z]+)',b)
</code>```

Actual Output:
['#helloworld #goodday', '#winter #christmastime']

Expected Output:
['! #helloworld #goodday #winter #christmastime !']

Which regular expression should be used for extracting the expected output from the string?

答:
You may use

```<code>[^\w\s](?:\s*#[a-zA-Z]+)+(?:\s*[^\w\s])?
</code>```

See the regex demo. If there are always at least 1 whitespace, replace \s* with \s+.

Details

[^\w\s] - a punctuation symbol (any 1 char other than word and whitespace char)

(?:\s*#[a-zA-Z]+)+  - a non-capturing group matching 1 or more sequences of:

\s* - 0+ whitespaces

# - a # symbol

[a-zA-Z]+ - 1+ ASCII letters

(?:\s*[^\w\s])? - an optional sequence of:

\s* - 0+ whitespaces

[^\w\s] - a punctuation symbol (any 1 char other than word and whitespace char)

Python demo:

```<code>import re
c = 'Hello!! This is a good day! #helloworld #goodday #winter #christmastime!'
print(re.findall(r'[^\w\s](?:\s*#[a-zA-Z]+)+(?:\s*[^\w\s])?',c))
# => ['! #helloworld #goodday #winter #christmastime!']
</code>```

Body:
I want to extract all the hashtags adjacent to other hashtags/punctuations so that I can get the bigrams from them. For the following variable c I want to extract the output of ['! #helloworld #goodday #winter #christmastime !']

c = 'Hello!! This is a good day! #helloworld #goodday #winter #christmastime!'
re.findall(r'(?:#[a-zA-Z]+ #[a-zA-Z]+)|(?:[\!"#\$%&\'\(\)*+,-./\:;<=>\?\@\[\\]\^_`{|}~]+ #[a-zA-Z]+)',b)

Actual Output:
['#helloworld #goodday', '#winter #christmastime']

Expected Output:
['! #helloworld #goodday #winter #christmastime !']

Which regular expression should be used for extracting the expected output from the string?

Body:
You may use

[^\w\s](?:\s*#[a-zA-Z]+)+(?:\s*[^\w\s])?

See the regex demo. If there are always at least 1 whitespace, replace \s* with \s+.

Details

[^\w\s] - a punctuation symbol (any 1 char other than word and whitespace char)

(?:\s*#[a-zA-Z]+)+  - a non-capturing group matching 1 or more sequences of:

\s* - 0+ whitespaces

# - a # symbol

[a-zA-Z]+ - 1+ ASCII letters

(?:\s*[^\w\s])? - an optional sequence of:

\s* - 0+ whitespaces

[^\w\s] - a punctuation symbol (any 1 char other than word and whitespace char)

Python demo:

import re
c = 'Hello!! This is a good day! #helloworld #goodday #winter #christmastime!'
print(re.findall(r'[^\w\s](?:\s*#[a-zA-Z]+)+(?:\s*[^\w\s])?',c))
# => ['! #helloworld #goodday #winter #christmastime!']


问:
Where can I find the llvm -stats information
I am running the command line

```<code>opt test.bc -loop-vectorize -o test2.bc -stats
</code>```

to check the statistics collected by the LLVM loop vectorize pass. However, after running the command, I only get the test2.bc without getting any stats printed. May I know where should I look for these stats?

Thanks in advance,
T

答:
They should be printed on your terminal after the command has finished executing. However, your LLVM needs to be built with assertions enabled, documented here:

Note that in order to use the ‘-stats‘ option, LLVM must be compiled
  with assertions enabled.

This corresponds to this cmake flag, if you are building LLVM from source:

```<code>-DLLVM_ENABLE_ASSERTIONS=On
</code>```

Moreover, you can query a specific LLVM installation for its assertion mode using:

```<code>llvm-config --assertion-mode
</code>```

If assertions are enabled, then it should return ON.

For code introspection of this feature, the corresponding preprocessor definition is

```<code>LLVM_ENABLE_STATS
</code>```

or when NDEBUG is not defined, as seen in the include/llvm/Support/Statistic.h header file.

Body:
I am running the command line

opt test.bc -loop-vectorize -o test2.bc -stats

to check the statistics collected by the LLVM loop vectorize pass. However, after running the command, I only get the test2.bc without getting any stats printed. May I know where should I look for these stats?

Thanks in advance,
T

Body:
They should be printed on your terminal after the command has finished executing. However, your LLVM needs to be built with assertions enabled, documented here:

Note that in order to use the ‘-stats‘ option, LLVM must be compiled
  with assertions enabled.

This corresponds to this cmake flag, if you are building LLVM from source:

-DLLVM_ENABLE_ASSERTIONS=On

Moreover, you can query a specific LLVM installation for its assertion mode using:

llvm-config --assertion-mode

If assertions are enabled, then it should return ON.

For code introspection of this feature, the corresponding preprocessor definition is

LLVM_ENABLE_STATS

or when NDEBUG is not defined, as seen in the include/llvm/Support/Statistic.h header file.


问:
Retrieving Android contact using contentResolver on HTC 10 returns no result
My app creates a contact in the Android contact book with a special SYNC4 key, so we can look up our special contact (seperate from other Android contacts). However, we're unable to read the contact on a HTC 10 device. I've read about some differences between HTC devices and other Android devices concerning handling contacts, but unfortunately didn't find a good explanation or solution to this problem.

The creation of the contact works like this:

```<code>private static final String SPECIAL_CONTACT_KEY = "_MY_SPECIAL_CONTACT_KEY_";

// Create an operation with the special SYN4 key
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
        builder.withValue(RawContacts.ACCOUNT_TYPE, null);
        builder.withValue(RawContacts.ACCOUNT_NAME, null);
        builder.withValue(RawContacts.SYNC4, SPECIAL_CONTACT_KEY);
        ops.add(builder.build());

// Add a 'given name' to the list of operations
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
        builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        builder.withValue(StructuredName.GIVEN_NAME, "givenName");
        ops.add(builder.build());

// Add a 'phone number with type work' to the list of operations
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
        builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        builder.withValue(Phone.TYPE, Phone.TYPE_WORK);
        builder.withValue(Phone.NUMBER, "phoneNumber");
        ops.add(builder.build());

// Add a 'note' to the list of operations (to be able to visually discern the contact from other contacts)
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
        builder.withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE);
        builder.withValue(Note.NOTE, "note");
        ops.add(builder.build());

ContentProviderResult[] result = App.getContext().getContentResolver().applyBatch(AUTHORITY, ops);
</code>```

The contact(s) can be retrieved like this:

```<code>// Retrieve our own contacts using the special SYNC4 key
Uri uri = Phone.CONTENT_URI;
String[] projection = {Phone.NUMBER};
String mySpecialSelection = RawContacts.SYNC4 + "='" + SPECIAL_CONTACT_KEY + "'";
Cursor cursor = App.getContext().getContentResolver().query(uri, projection, mySpecialSelection, null, null);
</code>```

The cursor is filled with the correct contact data on all device, but on the HTC the cursor is empty.

答:
You can't/shouldn't create a contact with null ACCOUNT_NAME and ACCOUNT_TYPE, these are called zombie contacts, and there isn't a guarantee they'll remain on the device (not only on HTC devices).

If you must create new contacts, you need to create a custom account for you app, and create new contacts/raw-contacts under that account.

See this and this.
BTW, you don't have to have a SyncAdapter, but it makes things like updating your contact's data easier and plays nicely with the Android ecosystem.

You can then find your own RawContacts by querying for ACCOUNT_TYPE = <your custom type> in your query.

Body:
My app creates a contact in the Android contact book with a special SYNC4 key, so we can look up our special contact (seperate from other Android contacts). However, we're unable to read the contact on a HTC 10 device. I've read about some differences between HTC devices and other Android devices concerning handling contacts, but unfortunately didn't find a good explanation or solution to this problem.

The creation of the contact works like this:

private static final String SPECIAL_CONTACT_KEY = "_MY_SPECIAL_CONTACT_KEY_";

// Create an operation with the special SYN4 key
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
        builder.withValue(RawContacts.ACCOUNT_TYPE, null);
        builder.withValue(RawContacts.ACCOUNT_NAME, null);
        builder.withValue(RawContacts.SYNC4, SPECIAL_CONTACT_KEY);
        ops.add(builder.build());

// Add a 'given name' to the list of operations
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
        builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        builder.withValue(StructuredName.GIVEN_NAME, "givenName");
        ops.add(builder.build());

// Add a 'phone number with type work' to the list of operations
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
        builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        builder.withValue(Phone.TYPE, Phone.TYPE_WORK);
        builder.withValue(Phone.NUMBER, "phoneNumber");
        ops.add(builder.build());

// Add a 'note' to the list of operations (to be able to visually discern the contact from other contacts)
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
        builder.withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE);
        builder.withValue(Note.NOTE, "note");
        ops.add(builder.build());

ContentProviderResult[] result = App.getContext().getContentResolver().applyBatch(AUTHORITY, ops);

The contact(s) can be retrieved like this:

// Retrieve our own contacts using the special SYNC4 key
Uri uri = Phone.CONTENT_URI;
String[] projection = {Phone.NUMBER};
String mySpecialSelection = RawContacts.SYNC4 + "='" + SPECIAL_CONTACT_KEY + "'";
Cursor cursor = App.getContext().getContentResolver().query(uri, projection, mySpecialSelection, null, null);

The cursor is filled with the correct contact data on all device, but on the HTC the cursor is empty.


问:
hidden field vs viewstate
What is the difference when using

Hidden field vs View state?

When to use each one ?

Which one more secure?

Which is better in performance?

what are the alternatives?

答:
A hidden field can be viewed in a pages HTML source whereas ViewState is, to say the least, obfuscated and depending on your .net version, can be encrypted to varying degrees.

asp.net viewstate encryption

Hidden field will be better in performance but provides no security and if the post data can be manipulated, be a lot easier to change the ViewState.

Session variables are a good alternative to these.

Title: hidden field vs viewstate