问:
genfromtext reading .csv with 3 columns returns ValueError 'got 3 columns instead of 2'?
I am wanting to import a .csv file with 3 columns where column 1 is my x values, column 2 is one series, and column 3 is another. I want to plot both series on one plot but when I try to read the csv file and plot it returns a ValueError (see below).

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

dir = ""
file = "fig1data.csv"
fn = np.genfromtxt(file, delimiter=',')
x=fn[:,0]
y1=fn[:,1]
y2=fn[:,2]
plt.plot(x, y1, 'b', label=r"1913-1942 anomaly")
plt.plot(x, y2, 'r', label=r"$blah$")
plt.show()
</code>```

returns the error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-56-0d8440895d40> in <module>()
      4 dir = ""
      5 file = "fig1data.csv"
----> 6 fn = np.genfromtxt(file, delimiter=',')
      7 x=fn[:,0]
      8 y1=fn[:,1]

/usr/lib64/python3.4/site-packages/numpy/lib/npyio.py in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows)
   1767             # Raise an exception ?
   1768             if invalid_raise:
-> 1769                 raise ValueError(errmsg)
   1770             # Issue a warning ?
   1771             else:

ValueError: Some errors were detected !
    Line #2 (got 3 columns instead of 2)
    Line #3 (got 3 columns instead of 2)
    Line #4 (got 3 columns instead of 2)
    Line #5 (got 3 columns instead of 2)
    Line #6 (got 3 columns instead of 2)
</code>```

答:
Is your .csv file formatted correctly?

I was able to get your code to work with a .csv file that looked like this:

```<code>col1,col2,col3
0,0.0236852314846,10
1,0.0240463281472,20
2,0.0176584073052,30
3,0.0147662342087,40
4,0.0345340419842,50
</code>```

However, when I removed the "col3" name, I got the error that you saw. So there may be a discrepancy between the number of column names and the number of columns of data you have.

Body:
I am wanting to import a .csv file with 3 columns where column 1 is my x values, column 2 is one series, and column 3 is another. I want to plot both series on one plot but when I try to read the csv file and plot it returns a ValueError (see below).

import matplotlib.pyplot as plt
import numpy as np

dir = ""
file = "fig1data.csv"
fn = np.genfromtxt(file, delimiter=',')
x=fn[:,0]
y1=fn[:,1]
y2=fn[:,2]
plt.plot(x, y1, 'b', label=r"1913-1942 anomaly")
plt.plot(x, y2, 'r', label=r"$blah$")
plt.show()

returns the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-56-0d8440895d40> in <module>()
      4 dir = ""
      5 file = "fig1data.csv"
----> 6 fn = np.genfromtxt(file, delimiter=',')
      7 x=fn[:,0]
      8 y1=fn[:,1]

/usr/lib64/python3.4/site-packages/numpy/lib/npyio.py in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows)
   1767             # Raise an exception ?
   1768             if invalid_raise:
-> 1769                 raise ValueError(errmsg)
   1770             # Issue a warning ?
   1771             else:

ValueError: Some errors were detected !
    Line #2 (got 3 columns instead of 2)
    Line #3 (got 3 columns instead of 2)
    Line #4 (got 3 columns instead of 2)
    Line #5 (got 3 columns instead of 2)
    Line #6 (got 3 columns instead of 2)

Body:
Is your .csv file formatted correctly?

I was able to get your code to work with a .csv file that looked like this:

col1,col2,col3
0,0.0236852314846,10
1,0.0240463281472,20
2,0.0176584073052,30
3,0.0147662342087,40
4,0.0345340419842,50

However, when I removed the "col3" name, I got the error that you saw. So there may be a discrepancy between the number of column names and the number of columns of data you have.


来源: stackexchange

问:
How to combine two similar functions that convert between hiragana and katakana?
I have two functions that convert between katakana and hiragana and they look the same:

```<code>katakana_minus_hiragana = 0x30a1 - 0x3041 # KATAKANA LETTER A - HIRAGANA A

def is_hirgana(char):
    return 0x3040 < ord(char[0]) and ord(char[0]) < 0x3097

def is_katakana(char):
    return 0x30a0 < ord(char[0]) and ord(char[0]) < 0x30f7

def hiragana_to_katakana(hiragana_text):
    katakana_text = ""
    max_len = 0
    for i, char in enumerate(hiragana_text):
        if is_hirgana(char):
            katakana_text += chr(ord(char) + katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return katakana_text, max_len

def katakana_to_hiragana(katakana_text):
    hiragana_text = ""
    max_len = 0
    for i, char in enumerate(katakana_text):
        if is_katakana(char):
            hiragana_text += chr(ord(char) - katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return hiragana_text, max_len
</code>```

Is there a way to simplify hiragana_to_katakana() and katakana_to_hiragana() into a duck-type function or a super/meta function?

E.g. something like

```<code>def convert_hk_kh(text, charset_range, offset):
    charset_start, charset_end = charset_range
    output_text = ""
    max_len = 0
    for i, char in enumerate(text):
        if charset_start < ord(char[0]) and ord(char[0]) < charset_end:
            output_text += chr(ord(char) + offset)
            max_len +=1
        else:
            break
    return output_text, max_len

def katakana_to_hiragana(katakana_text):
    return convert_hk_kh(katakana_text, (0x30a0, 0x30f7), -katakana_minus_hiragana)

def hiragana_to_katakana(hiragana_text):
    return convert_hk_kh(hiragana_text, (0x3040, 0x3097), katakana_minus_hiragana)
</code>```

Are there other pythonic ways to simplify the two functions that are very similar?

EDITED

There's also https://github.com/olsgaard/Japanese_nlp_scripts which seems to do the same thing with str.translate. Is that more efficient? More pythonic?

答:
Here’s a function that would switch each kind of kana to the other.
Unlike the given functions, it does not stop when it encounters
non-kana, but simply passes those characters through without changing
them.

Note that conversion between kana types is not as simple as this; for
example, in hiragana a long “e” sound is indicated by ええ or えい
(e.g., おねえ older sister, せんせい teacher), while in katakana one
uses a chōonpu (オネー, せんせー). There are kana characters outside the
ranges you use as well.

```<code>def switch_kana_type(kana_text):
    """Replace each kind of kana with the other kind. Other characters are
    passed through unchanged."""

    output_text = ''
    for c in kana_text:
        if is_hiragana(c):   # Note typo fix of "is_hirgana"
            output_text += chr(ord(c) + katakana_minus_hiragana)
        elif is_katakana(char):
            output_text += chr(ord(c) - katakana_minus_hiragana)
        else:
            output_text += c;
    return output_text, len(output_text)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two functions that convert between katakana and hiragana and they look the same:

katakana_minus_hiragana = 0x30a1 - 0x3041 # KATAKANA LETTER A - HIRAGANA A

def is_hirgana(char):
    return 0x3040 < ord(char[0]) and ord(char[0]) < 0x3097

def is_katakana(char):
    return 0x30a0 < ord(char[0]) and ord(char[0]) < 0x30f7

def hiragana_to_katakana(hiragana_text):
    katakana_text = ""
    max_len = 0
    for i, char in enumerate(hiragana_text):
        if is_hirgana(char):
            katakana_text += chr(ord(char) + katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return katakana_text, max_len

def katakana_to_hiragana(katakana_text):
    hiragana_text = ""
    max_len = 0
    for i, char in enumerate(katakana_text):
        if is_katakana(char):
            hiragana_text += chr(ord(char) - katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return hiragana_text, max_len

Is there a way to simplify hiragana_to_katakana() and katakana_to_hiragana() into a duck-type function or a super/meta function?

E.g. something like

def convert_hk_kh(text, charset_range, offset):
    charset_start, charset_end = charset_range
    output_text = ""
    max_len = 0
    for i, char in enumerate(text):
        if charset_start < ord(char[0]) and ord(char[0]) < charset_end:
            output_text += chr(ord(char) + offset)
            max_len +=1
        else:
            break
    return output_text, max_len

def katakana_to_hiragana(katakana_text):
    return convert_hk_kh(katakana_text, (0x30a0, 0x30f7), -katakana_minus_hiragana)

def hiragana_to_katakana(hiragana_text):
    return convert_hk_kh(hiragana_text, (0x3040, 0x3097), katakana_minus_hiragana)

Are there other pythonic ways to simplify the two functions that are very similar?

EDITED

There's also https://github.com/olsgaard/Japanese_nlp_scripts which seems to do the same thing with str.translate. Is that more efficient? More pythonic?

Body:
Here’s a function that would switch each kind of kana to the other.
Unlike the given functions, it does not stop when it encounters
non-kana, but simply passes those characters through without changing
them.

Note that conversion between kana types is not as simple as this; for
example, in hiragana a long “e” sound is indicated by ええ or えい
(e.g., おねえ older sister, せんせい teacher), while in katakana one
uses a chōonpu (オネー, せんせー). There are kana characters outside the
ranges you use as well.

def switch_kana_type(kana_text):
    """Replace each kind of kana with the other kind. Other characters are
    passed through unchanged."""

    output_text = ''
    for c in kana_text:
        if is_hiragana(c):   # Note typo fix of "is_hirgana"
            output_text += chr(ord(c) + katakana_minus_hiragana)
        elif is_katakana(char):
            output_text += chr(ord(c) - katakana_minus_hiragana)
        else:
            output_text += c;
    return output_text, len(output_text)


问:
How to read system properties from .properties file
I have a JAVA web application which runs on Tomcat Server. I have a setup a property in my tomcat’s VM arguments; something like -Denvironment =“E1”.

I want to read that property inside my app.properties file, I tried mutiple options like ${environment} and {sys:environment} but could not able to read the value.

Please help, thanks in advance.

答:
You can also try this one:</p>

```<code>${sys:environment}
</code>```

Body:
You can also try this one:

${sys:environment}


问:
PHP output echoed out of order
I'm having trouble with the output order of a stored procedure (MariaDB). I've tried this several different ways and each echoed result set exhibits the same problem. (I couldn't resolve it using procedural/mysqli, so remade the project in PDO, and now the same issue has arisen.) This is epic, so thanks to everyone who reads.

I'm trying to create a form-letter report for each member in the result set, with an introduction and a table of fees attributed to that member.

So I would expect to see:

Intro for Member 1,

Table for Member 1;

Intro for Member 2,

Table for Member 2; and so on.

The problem is that I am seeing:

Intro for Member 1,

Intro for Member 2,

Table for Member 1,

Intro for Member 3,

Table for Member 2,

Intro for Member 4,

Table for Member 3; and so on.

Called stored procedure:

```<code>SELECT * FROM `View_Accounts_report`  WHERE `Date` >= parameter_start_date  AND `Date` <= parameter_end_dated
</code>```

Call to the output function within html:

```<code>if(isset($_REQUEST['submit'])) {
        Accounts_by_date($_REQUEST['start_date'], $_REQUEST['end_date']);
    }
</code>```

php function Accounts_by_date method 1:

```<code>function Accounts_by_date($start_date, $end_date) {
        require '../lib/pdo.php';

$prev = NULL;

$sql = "CALL accounts_report_dates (:start_date, :end_date)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':start_date', $start_date);
$stmt->bindValue(':end_date', $end_date);
$stmt->execute();

$results = $stmt->fetchALL(PDO::FETCH_ASSOC);

var_dump($results);

$arrlength = count($results);

for ($row = 0; $row < $arrlength; $row++) {

    $person = $results[$row]['Member_ID'];    // tracking each row

    if ($person != $prev) {    // if the current member is different from the previous member, print header and row

// table headers

        echo "<br><br>Member: " . $results[$row]['Member_name'] . "<br>";
        echo "Dear " . $results[$row]['First_name'] . ",<br>";
        echo "Please find your Belmont Pottery Group fees for the period " . $start_date . " to " . $end_date . " below. <br>";
        echo "<br><table><tr><th>Total</th><th>Member_ID</th><th>Date</th><th>Transaction</th><th>Amount</th>";
        echo "<th>First name</th><th>Email</th><th>Member name</th></tr>";

// table rows

        echo "<tr><td>" . $results[$row]['Total'] . "</td>";
        echo "<td>" . $results[$row]['Member_ID'] . "</td>";
        echo "<td>" . $results[$row]['Date'] . "</td>";
        echo "<td>" . $results[$row]['Transaction'] . "</td>";
        echo "<td>$" . $results[$row]['Amount'] . "</td>";
        echo "<td>" . $results[$row]['First_name'] . "</td>";
        echo "<td>" . $results[$row]['Email'] . "</td>";
        echo "<td>" . $results[$row]['Member_name'] . "</td></tr>";

        $prev = $person;

    }else{

        echo "<tr><td>" . $results[$row]['Total'] . "</td>";
        echo "<td>" . $results[$row]['Member_ID'] . "</td>";
        echo "<td>" . $results[$row]['Date'] . "</td>";
        echo "<td>" . $results[$row]['Transaction'] . "</td>";
        echo "<td>$" . $results[$row]['Amount'] . "</td>";
        echo "<td>" . $results[$row]['First_name'] . "</td>";
        echo "<td>" . $results[$row]['Email'] . "</td>";
        echo "<td>" . $results[$row]['Member_name'] . "</td></tr>";

        $prev = $person;

    }
}
</code>```

}

Excerpt of var_dump from php function method 1:

array(15) { [0]=> array(8) { ["Total"]=> string(5) "36.00" ["Member_ID"]=> int(31) ["Date"]=> string(10) "2017-11-06" ["Transaction"]=> string(4) "Clay" ["Amount"]=> string(5) "18.00" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(12) "Dummy Nine " } [1]=> array(8) { ["Total"]=> string(5) "36.00" ["Member_ID"]=> int(31) ["Date"]=> string(10) "2017-11-13" ["Transaction"]=> string(4) "Clay" ["Amount"]=> string(5) "18.00" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(12) "Dummy Nine " } [2]=> array(8) { ["Total"]=> string(5) "40.20" ["Member_ID"]=> int(29) ["Date"]=> string(10) "2017-11-05" ["Transaction"]=> string(6) "Firing" ["Amount"]=> string(4) "3.70" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(13) "Dummy Seven " } [3]=> array(8) { ["Total"]=> string(5) "40.20" ["Member_ID"]=> int(29) ["Date"]=> string(10) "2017-11-05" ["Transaction"]=> string(10) "Attendance" ["Amount"]=> string(4) "4.00" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(13) "Dummy Seven " }

php function Accounts_by_date method 2:

```<code>function Accounts_by_date($start_date, $end_date) {
        require '../lib/pdo.php';

$prev = NULL;

$sql = "CALL accounts_report_dates (:start_date, :end_date)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':start_date', $start_date);
$stmt->bindValue(':end_date', $end_date);
$stmt->execute();
$stmt->bindColumn('Total', $total);
$stmt->bindColumn('Member_ID', $id);
$stmt->bindColumn('Date', $date);
$stmt->bindColumn('Transaction', $transaction);
$stmt->bindColumn('Amount', $amount);
$stmt->bindColumn('First_name', $fname);
$stmt->bindColumn('Email', $email);
$stmt->bindColumn('Member_name', $name);

while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {

    $person = $id;

    if ($person != $prev) {    // if the current member is different from the previous member, print header and row

// table headers

        echo "<br><br>Member: " . $name . "<br>";
        echo "Dear " . $fname . ",<br>";
        echo "Please find your Belmont Pottery Group fees for the period " . $start_date . " to " . $end_date . " below. <br><br>";
        echo "The total of your invoice is: $" . $total . "<br>";
        echo "<br><table><tr><th>Total</th><th>Member_ID</th><th>Date</th><th>Transaction</th><th>Amount</th>";
        echo "<th>First name</th><th>Email</th><th>Member name</th></tr>";

// table rows

        echo "<tr><td>" . $total . "</td>";
        echo "<td>" . $id . "</td>";
        echo "<td>" . $date . "</td>";
        echo "<td>" . $transaction . "</td>";
        echo "<td>$" . $amount . "</td>";
        echo "<td>" . $fname . "</td>";
        echo "<td>" . $email . "</td>";
        echo "<td>" . $name . "</td></tr>";

        $prev = $person;

    }else{

        echo "<tr><td>" . $total . "</td>";
        echo "<td>" . $id . "</td>";
        echo "<td>" . $date . "</td>";
        echo "<td>" . $transaction . "</td>";
        echo "<td>$" . $amount . "</td>";
        echo "<td>" . $fname . "</td>";
        echo "<td>" . $email . "</td>";
        echo "<td>" . $name . "</td></tr>";

        $prev = $person;

    }
}
</code>```

}

var_dump of php function method 2 returns true.

Output (both methods):

Member: Dummy Nine
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Member: Dummy Seven
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Total   Member_ID   Date    Transaction Amount  First name  Email   Member name
36.00   31  2017-11-06  Clay    $18.00  Dummy   dummy@dummy.com Dummy Nine
36.00   31  2017-11-13  Clay    $18.00  Dummy   dummy@dummy.com Dummy Nine

Member: Dummy Six
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Total   Member_ID   Date    Transaction Amount  First name  Email   Member name
40.20   29  2017-11-05  Firing  $3.70   Dummy   dummy@dummy.com Dummy Seven
40.20   29  2017-11-05  Attendance  $4.00   Dummy   dummy@dummy.com Dummy Seven
40.20   29  2017-11-19  Firing  $11.60  Dummy   dummy@dummy.com Dummy Seven

Member: Dummy Three
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Total   Member_ID   Date    Transaction Amount  First name  Email   Member name
26.60   28  2017-11-02  Attendance  $4.00   Dummy   dummy@dummy.com Dummy Six
26.60   28  2017-11-06  Attendance  $4.00   Dummy   dummy@dummy.com Dummy Six
26.60   28  2017-11-03  Firing  $17.00  Dummy   dummy@dummy.com Dummy Six
26.60   28  2017-11-06  Firing  $1.60   Dummy   dummy@dummy.com Dummy Six

答:
I would start by making sure you are closing your tables, you can add the code below:

```<code>if ($person != $prev) {
    if ($row > 0) echo "</table>"; /*added line of code*/
</code>```

That should fix some issues with multiple table header cells in the same table. The multiple 's in one table are pushing your intro's up to the top.

Don't forget to add a

```<code></table>
</code>```

to the end of your code as well after the while loop is done for proper html

Title: PHP output echoed out of order

Body:
I'm having trouble with the output order of a stored procedure (MariaDB). I've tried this several different ways and each echoed result set exhibits the same problem. (I couldn't resolve it using procedural/mysqli, so remade the project in PDO, and now the same issue has arisen.) This is epic, so thanks to everyone who reads.

I'm trying to create a form-letter report for each member in the result set, with an introduction and a table of fees attributed to that member.

So I would expect to see:

Intro for Member 1,

Table for Member 1;

Intro for Member 2,

Table for Member 2; and so on.

The problem is that I am seeing:

Intro for Member 1,

Intro for Member 2,

Table for Member 1,

Intro for Member 3,

Table for Member 2,

Intro for Member 4,

Table for Member 3; and so on.

Called stored procedure:

SELECT * FROM `View_Accounts_report`  WHERE `Date` >= parameter_start_date  AND `Date` <= parameter_end_dated

Call to the output function within html:

if(isset($_REQUEST['submit'])) {
        Accounts_by_date($_REQUEST['start_date'], $_REQUEST['end_date']);
    }

php function Accounts_by_date method 1:

function Accounts_by_date($start_date, $end_date) {
        require '../lib/pdo.php';

$prev = NULL;

$sql = "CALL accounts_report_dates (:start_date, :end_date)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':start_date', $start_date);
$stmt->bindValue(':end_date', $end_date);
$stmt->execute();

$results = $stmt->fetchALL(PDO::FETCH_ASSOC);

var_dump($results);

$arrlength = count($results);

for ($row = 0; $row < $arrlength; $row++) {

    $person = $results[$row]['Member_ID'];    // tracking each row

    if ($person != $prev) {    // if the current member is different from the previous member, print header and row

// table headers

        echo "

Member: " . $results[$row]['Member_name'] . "
";
        echo "Dear " . $results[$row]['First_name'] . ",
";
        echo "Please find your Belmont Pottery Group fees for the period " . $start_date . " to " . $end_date . " below.
";
        echo "

Total	Member_ID	Date	Transaction	Amount	";
        echo "First name	Email	Member name
";

// table rows

        echo "
" . $results[$row]['Total'] . "	";
        echo "" . $results[$row]['Member_ID'] . "	";
        echo "" . $results[$row]['Date'] . "	";
        echo "" . $results[$row]['Transaction'] . "	";
        echo "$" . $results[$row]['Amount'] . "	";
        echo "" . $results[$row]['First_name'] . "	";
        echo "" . $results[$row]['Email'] . "	";
        echo "" . $results[$row]['Member_name'] . "
";

        $prev = $person;

    }else{

        echo "
" . $results[$row]['Total'] . "	";
        echo "" . $results[$row]['Member_ID'] . "	";
        echo "" . $results[$row]['Date'] . "	";
        echo "" . $results[$row]['Transaction'] . "	";
        echo "$" . $results[$row]['Amount'] . "	";
        echo "" . $results[$row]['First_name'] . "	";
        echo "" . $results[$row]['Email'] . "	";
        echo "" . $results[$row]['Member_name'] . "
";

        $prev = $person;

    }
}

}

Excerpt of var_dump from php function method 1:

array(15) { [0]=> array(8) { ["Total"]=> string(5) "36.00" ["Member_ID"]=> int(31) ["Date"]=> string(10) "2017-11-06" ["Transaction"]=> string(4) "Clay" ["Amount"]=> string(5) "18.00" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(12) "Dummy Nine " } [1]=> array(8) { ["Total"]=> string(5) "36.00" ["Member_ID"]=> int(31) ["Date"]=> string(10) "2017-11-13" ["Transaction"]=> string(4) "Clay" ["Amount"]=> string(5) "18.00" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(12) "Dummy Nine " } [2]=> array(8) { ["Total"]=> string(5) "40.20" ["Member_ID"]=> int(29) ["Date"]=> string(10) "2017-11-05" ["Transaction"]=> string(6) "Firing" ["Amount"]=> string(4) "3.70" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(13) "Dummy Seven " } [3]=> array(8) { ["Total"]=> string(5) "40.20" ["Member_ID"]=> int(29) ["Date"]=> string(10) "2017-11-05" ["Transaction"]=> string(10) "Attendance" ["Amount"]=> string(4) "4.00" ["First_name"]=> string(6) "Dummy " ["Email"]=> string(25) "dummy@dummy.com" ["Member_name"]=> string(13) "Dummy Seven " }

php function Accounts_by_date method 2:

function Accounts_by_date($start_date, $end_date) {
        require '../lib/pdo.php';

$prev = NULL;

$sql = "CALL accounts_report_dates (:start_date, :end_date)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':start_date', $start_date);
$stmt->bindValue(':end_date', $end_date);
$stmt->execute();
$stmt->bindColumn('Total', $total);
$stmt->bindColumn('Member_ID', $id);
$stmt->bindColumn('Date', $date);
$stmt->bindColumn('Transaction', $transaction);
$stmt->bindColumn('Amount', $amount);
$stmt->bindColumn('First_name', $fname);
$stmt->bindColumn('Email', $email);
$stmt->bindColumn('Member_name', $name);

while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {

    $person = $id;

    if ($person != $prev) {    // if the current member is different from the previous member, print header and row

// table headers

        echo "

Member: " . $name . "
";
        echo "Dear " . $fname . ",
";
        echo "Please find your Belmont Pottery Group fees for the period " . $start_date . " to " . $end_date . " below.

";
        echo "The total of your invoice is: $" . $total . "
";
        echo "

Total	Member_ID	Date	Transaction	Amount	";
        echo "First name	Email	Member name
";

// table rows

        echo "
" . $total . "	";
        echo "" . $id . "	";
        echo "" . $date . "	";
        echo "" . $transaction . "	";
        echo "$" . $amount . "	";
        echo "" . $fname . "	";
        echo "" . $email . "	";
        echo "" . $name . "
";

        $prev = $person;

    }else{

        echo "
" . $total . "	";
        echo "" . $id . "	";
        echo "" . $date . "	";
        echo "" . $transaction . "	";
        echo "$" . $amount . "	";
        echo "" . $fname . "	";
        echo "" . $email . "	";
        echo "" . $name . "
";

        $prev = $person;

    }
}

}

var_dump of php function method 2 returns true.

Output (both methods):

Member: Dummy Nine
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Member: Dummy Seven
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Total   Member_ID   Date    Transaction Amount  First name  Email   Member name
36.00   31  2017-11-06  Clay    $18.00  Dummy   dummy@dummy.com Dummy Nine
36.00   31  2017-11-13  Clay    $18.00  Dummy   dummy@dummy.com Dummy Nine

Member: Dummy Six
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Total   Member_ID   Date    Transaction Amount  First name  Email   Member name
40.20   29  2017-11-05  Firing  $3.70   Dummy   dummy@dummy.com Dummy Seven
40.20   29  2017-11-05  Attendance  $4.00   Dummy   dummy@dummy.com Dummy Seven
40.20   29  2017-11-19  Firing  $11.60  Dummy   dummy@dummy.com Dummy Seven

Member: Dummy Three
Dear Dummy ,
Please find your BPG fees for the period 2017-11-01 to 2017-11-30 below.

Total   Member_ID   Date    Transaction Amount  First name  Email   Member name
26.60   28  2017-11-02  Attendance  $4.00   Dummy   dummy@dummy.com Dummy Six
26.60   28  2017-11-06  Attendance  $4.00   Dummy   dummy@dummy.com Dummy Six
26.60   28  2017-11-03  Firing  $17.00  Dummy   dummy@dummy.com Dummy Six
26.60   28  2017-11-06  Firing  $1.60   Dummy   dummy@dummy.com Dummy Six

Body:
I would start by making sure you are closing your tables, you can add the code below:

if ($person != $prev) {
    if ($row > 0) echo "</table>"; /*added line of code*/

That should fix some issues with multiple table header cells in the same table. The multiple 's in one table are pushing your intro's up to the top.

Don't forget to add a

</table>

to the end of your code as well after the while loop is done for proper html


问:
How to get Result from Select statement rows to columns from multiple views in SQL Server
I have 2 different views:

View #1: Get_MTD_Booking

```<code>SELECT
    CAST(tbm.booking_datetime AS DATE) AS [Date],
    COUNT(tbm.booking_id) AS [TotalShipments],
    SUM(tbd.qty) AS [TotalPcs],
    SUM(tbd.weight) AS [TotalWeight],
    SUM(tbm.amount_wr) AS [Amount],
    'Booking' AS [Status],
    tbm.source_terminal_id, tbm.source_ccp_id
FROM
    tbl_booking_master tbm
INNER JOIN
    tbl_booking_detail tbd ON tbm.booking_id = tbd.booking_id
GROUP BY
    CAST(tbm.booking_datetime AS DATE),
    tbm.source_terminal_id, tbm.source_ccp_id
</code>```

View #2: Get_MTD_Delivery:

```<code>SELECT
    CAST(tdm.delivery_datetime AS DATE) AS [Date],
    COUNT(tdd.BarCode) AS [TotalShipments],
    SUM(tbd.qty) AS [TotalPcs],
    SUM(tbd.weight) AS [TotalWeight],
    0 AS [Amount],
    'Delivery' AS [Mode],
    tbm.destination_terminal_id,
    tbm.destination_ccp_id
FROM
    tbl_delivery_master tdm
INNER JOIN
    tbl_delivery_detail tdd ON tdm.delivery_id = tdd.delivery_id
                            AND tdm.booking_id = tdd.booking_id
INNER JOIN
    tbl_booking_master tbm ON tdm.booking_id = tbm.booking_id
INNER JOIN
    tbl_booking_detail tbd ON tbm.booking_id = tbd.booking_id
GROUP BY
    CAST(tdm.delivery_datetime AS DATE),
    tbm.destination_terminal_id, tbm.destination_ccp_id
</code>```

Each view returns the same number of columns:

1: Date

2: TotalShipments

3: TotalPcs

4: TotalWeight

5: Amount

6: Mode

7: DestinationTerminalId

8: DestinationCCPID

What I actually want is to display all of these results in this format:

```<code>|Date | DestinationId | DestinationCCP | TotalShipments_Booked | TotalPcs_Booked | TotalWeight_Booked |TotalShipments_Delivered | TotalPcs_Delivered | TotalWeight_Delivered |
</code>```

I want the result to be grouped by date and destinationid as well.

I have tried to write a subquery for this, but it didn't helped. Can anyone help me to sort this?

答:
You could just try joining both of your views.  There is of course a risk that a given shipment does not match to any actual delivery, in which case there would be a few NULL fields for such a record.  But this should work reasonably well under the assumption that every delivery originated at some point with an actual shipment.

```<code>SELECT
    t1.[DATE],
    t1.[TotalShipments] AS TotalShipmentsBooked,
    t2.[TotalShipments] AS TotalShipmentsDelivered,
    t1.[TotalPcs] AS TotalPcsBooked,
    t2.[TotalPcs] AS TotalPcsDelivered,
    t1.[TotalWeight] AS TotalWeightBooked,
    t2.[TotalWeight] AS TotalWeightDelivered,
    t1.[TotalAmount] AS TotalAmountBooked,
    t2.[TotalAmount] AS TotalAmountDelivered,
    t1.[source_terminal_id] AS TerminalId,
    t1.[source_ccp_id] AS CCPID
FROM Get_MTD_Booking t1
LEFT JOIN Get_MTD_Delivery t2
    ON t1.[DATE] = t2.[DATE] AND
       t1.source_terminal_id = t2.destination_terminal_id AND
       t1.source_ccp_id = t2.destination_ccp_id;
</code>```

Body:
I have 2 different views:

View #1: Get_MTD_Booking

SELECT
    CAST(tbm.booking_datetime AS DATE) AS [Date],
    COUNT(tbm.booking_id) AS [TotalShipments],
    SUM(tbd.qty) AS [TotalPcs],
    SUM(tbd.weight) AS [TotalWeight],
    SUM(tbm.amount_wr) AS [Amount],
    'Booking' AS [Status],
    tbm.source_terminal_id, tbm.source_ccp_id
FROM
    tbl_booking_master tbm
INNER JOIN
    tbl_booking_detail tbd ON tbm.booking_id = tbd.booking_id
GROUP BY
    CAST(tbm.booking_datetime AS DATE),
    tbm.source_terminal_id, tbm.source_ccp_id

View #2: Get_MTD_Delivery:

SELECT
    CAST(tdm.delivery_datetime AS DATE) AS [Date],
    COUNT(tdd.BarCode) AS [TotalShipments],
    SUM(tbd.qty) AS [TotalPcs],
    SUM(tbd.weight) AS [TotalWeight],
    0 AS [Amount],
    'Delivery' AS [Mode],
    tbm.destination_terminal_id,
    tbm.destination_ccp_id
FROM
    tbl_delivery_master tdm
INNER JOIN
    tbl_delivery_detail tdd ON tdm.delivery_id = tdd.delivery_id
                            AND tdm.booking_id = tdd.booking_id
INNER JOIN
    tbl_booking_master tbm ON tdm.booking_id = tbm.booking_id
INNER JOIN
    tbl_booking_detail tbd ON tbm.booking_id = tbd.booking_id
GROUP BY
    CAST(tdm.delivery_datetime AS DATE),
    tbm.destination_terminal_id, tbm.destination_ccp_id

Each view returns the same number of columns:

1: Date

2: TotalShipments

3: TotalPcs

4: TotalWeight

5: Amount

6: Mode

7: DestinationTerminalId

8: DestinationCCPID

What I actually want is to display all of these results in this format:

|Date | DestinationId | DestinationCCP | TotalShipments_Booked | TotalPcs_Booked | TotalWeight_Booked |TotalShipments_Delivered | TotalPcs_Delivered | TotalWeight_Delivered |

I want the result to be grouped by date and destinationid as well.

I have tried to write a subquery for this, but it didn't helped. Can anyone help me to sort this?

Body:
You could just try joining both of your views.  There is of course a risk that a given shipment does not match to any actual delivery, in which case there would be a few NULL fields for such a record.  But this should work reasonably well under the assumption that every delivery originated at some point with an actual shipment.

SELECT
    t1.[DATE],
    t1.[TotalShipments] AS TotalShipmentsBooked,
    t2.[TotalShipments] AS TotalShipmentsDelivered,
    t1.[TotalPcs] AS TotalPcsBooked,
    t2.[TotalPcs] AS TotalPcsDelivered,
    t1.[TotalWeight] AS TotalWeightBooked,
    t2.[TotalWeight] AS TotalWeightDelivered,
    t1.[TotalAmount] AS TotalAmountBooked,
    t2.[TotalAmount] AS TotalAmountDelivered,
    t1.[source_terminal_id] AS TerminalId,
    t1.[source_ccp_id] AS CCPID
FROM Get_MTD_Booking t1
LEFT JOIN Get_MTD_Delivery t2
    ON t1.[DATE] = t2.[DATE] AND
       t1.source_terminal_id = t2.destination_terminal_id AND
       t1.source_ccp_id = t2.destination_ccp_id;


问:
How would you tidy up this controller logic?
I've got some logic in a controller that sets a status of an object if certain conditions are met:

```<code>if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end
</code>```

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

答:
You can make your code less dependent on both conditions and make it a lot more flexible.

```<code>waiting_on = []
waiting_on << 'Compliance' unless params[:concept][:consulted_marketing]
waiting_on << 'Legal' unless params[:concept][:consulted_legal]
status = waiting_on.empty? ? "Awaiting #{waiting_on.join(' & ')} Approval" : 'Pending Approval'
@concept.attributes = {:status => status}
</code>```

Version for both create and update without filter:

```<code>def create
  set_concept_status_attribute
  ...
end

def update
  set_concept_status_attribute
  ...
end

private
  def set_concept_status_attribute
    waiting_on = []
    waiting_on << 'Compliance' unless params[:concept][:consulted_marketing]
    waiting_on << 'Legal' unless params[:concept][:consulted_legal]
    status = waiting_on.empty? ? "Awaiting #{waiting_on.join(' & ')} Approval" : 'Pending Approval'
    @concept.attributes = {:status => status}
  end
</code>```

Or with a before_filter:

```<code>before_filter :set_concept_status_attribute, :only => [:create, :update]

def create
  ...
end

def update
  ...
end
</code>```

If you can move it to you view, it looks even better:

```<code>module ConceptHelper
  def get_concept_status
    ...
  end
end

<%= get_concept_status %>
</code>```

OwnerDisplayName: The Pied Pipes

ContentLicense: CC BY-SA 2.5

Body:
I've got some logic in a controller that sets a status of an object if certain conditions are met:

if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

Body:
You can make your code less dependent on both conditions and make it a lot more flexible.

waiting_on = []
waiting_on << 'Compliance' unless params[:concept][:consulted_marketing]
waiting_on << 'Legal' unless params[:concept][:consulted_legal]
status = waiting_on.empty? ? "Awaiting #{waiting_on.join(' & ')} Approval" : 'Pending Approval'
@concept.attributes = {:status => status}

Version for both create and update without filter:

def create
  set_concept_status_attribute
  ...
end

def update
  set_concept_status_attribute
  ...
end

private
  def set_concept_status_attribute
    waiting_on = []
    waiting_on << 'Compliance' unless params[:concept][:consulted_marketing]
    waiting_on << 'Legal' unless params[:concept][:consulted_legal]
    status = waiting_on.empty? ? "Awaiting #{waiting_on.join(' & ')} Approval" : 'Pending Approval'
    @concept.attributes = {:status => status}
  end

Or with a before_filter:

before_filter :set_concept_status_attribute, :only => [:create, :update]

def create
  ...
end

def update
  ...
end

If you can move it to you view, it looks even better:

module ConceptHelper
  def get_concept_status
    ...
  end
end

<%= get_concept_status %>

OwnerDisplayName: Samuel

LastEditorDisplayName: Samuel


问:
Why are my buttons going out of screen in my Ionic app?
I have created a simple chat form in Ionic.

Problem: Buttons are going out of screen.

It looks like this this -

My chat.html

```<code><ion-header>

  <ion-navbar>
    <ion-title>communicationgiven</ion-title>
    <button ion-button (click)="close()" style="margin-left: 90%;margin-top: -3%">Close</button>
  </ion-navbar>

</ion-header>

<ion-content padding>

  <ion-list>
  <div>

  <p *ngFor="let list of list; let i = index;">
    <ion-item>
        <!-- <p style="color: #1bb0f4;font-size: 20px;">Tagto {{list.TAG_TO}}</p> -->
        <p style="color: #1bb0f4;"> {{list.TAG_FROM}}</p>
        <p style="color: #d2dce1;"> {{list.TAG}}</p>
    </ion-item>
  </p>
  </div>
    </ion-list>
</ion-content>

<ion-footer class="footer">
  <form #com="ngForm" (submit)="onsubmit(com.value)">
    <ion-input placeholder="TAG" type="text" name="TAG" ngModel ></ion-input>
    <button ion-button type="submit" style="margin-left: 90%;margin-top: -5%;">Submit</button>
  </form>

</ion-footer>
</code>```

I want to know why my buttons are going out of the page; how can I make sure they stay inside the screen, irrespective of the screen size?

What is the best practice here? I am fairly new in CSS.

答: you had given  style="margin-left: 90% that is margin from left side is 90% so obviously it will go out of screen, try to decrease the value.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have created a simple chat form in Ionic.

Problem: Buttons are going out of screen.

It looks like this this -

My chat.html

<ion-header>

  <ion-navbar>
    <ion-title>communicationgiven</ion-title>
    <button ion-button (click)="close()" style="margin-left: 90%;margin-top: -3%">Close</button>
  </ion-navbar>

</ion-header>

<ion-content padding>

  <ion-list>

    <ion-item>

 {{list.TAG_FROM}}

 {{list.TAG}}

    </ion-item>

    </ion-list>
</ion-content>

<ion-footer class="footer">
  <form #com="ngForm" (submit)="onsubmit(com.value)">
    <ion-input placeholder="TAG" type="text" name="TAG" ngModel ></ion-input>
    <button ion-button type="submit" style="margin-left: 90%;margin-top: -5%;">Submit</button>
  </form>

</ion-footer>

I want to know why my buttons are going out of the page; how can I make sure they stay inside the screen, irrespective of the screen size?

What is the best practice here? I am fairly new in CSS.


问:
Parameter passed in GLSL function not recognized as a constant
I'm doing an exercise in Shader School in which I implement a function that returns the nth power of a matrix.  Even when I pass constant parameter n into the following function:

```<code>mat2 matrixPower(highp mat2 m, const int n) {
    if(n==0) {
        return mat2(1.0);
    } else {
        mat2 result = m;
        for(int i=1; i < n; ++i) {
            result = result * m;
        }
        return result;
    }
}
</code>```

I get the following error:

```<code>Loop index cannot be compared with non-constant expression
</code>```

How is this possible?

答:
The keyword const indicates that n is not writable, but it is still a variable and not a constant!

n varies with the actual parameter to the formal parameter when the function was called.

Note in Appandix A of The OpenGL ES Shading Language 1.0 are listed possible limitations for OpenGL ES 2.0:

for loops are supported but with the following restrictions:

condition has the form
loop_index relational_operator constant_expression

where relational_operator is one of: > >= < <= == or !=

In Chapter 5.10 Constant Expressions of The OpenGL ES Shading Language 1.0 is clearly said, that a const function  parameter is not a constant expression:

A constant expression is one of

a literal value (e.g., 5 or true)

a global or local variable qualified as const excluding function parameters

an expression formed by an operator on operands that are constant expressions, including getting
an element of a constant vector or a constant matrix, or a field of a constant structure

a constructor whose arguments are all constant expressions

a built-in function call whose arguments are all constant expressions, with the exception of the texture lookup functions.

A workaround would be to create a loop which is limited by a constant expression and to break out off the loop with a condition:

for (int i = 1; i < 10; ++i)
{
    if ( i >= n )
        break;
    result = result * m;
}
```

Body:
I'm doing an exercise in Shader School in which I implement a function that returns the nth power of a matrix.  Even when I pass constant parameter n into the following function:

mat2 matrixPower(highp mat2 m, const int n) {
    if(n==0) {
        return mat2(1.0);
    } else {
        mat2 result = m;
        for(int i=1; i < n; ++i) {
            result = result * m;
        }
        return result;
    }
}

I get the following error:

Loop index cannot be compared with non-constant expression

How is this possible?


问:
What is the key feature in MNIST Dataset that is used to classify images
I was recently learning about neural networks and came across MNIST data set. i understood that a sigmoid cost function is used to reduce the loss. Also, weights and biases gets adjusted and an optimum weights and biases are found after the training. the thing i did not understand is, on what basis the images are classified. For example, to classify whether a patient has cancer or not, data like age, location, etc., becomes features. in MNIST dataset, i did not find any of that. Am i missing something here. Please help me with this

答:
First of all the Network pipeline consists of 3 main parts:

Input Manipulation:

Parameters that effect the finding of minimum:

Parameters like your descission function in your interpretation
layer (often fully connected layer)

In contrast to your regular machine learning pipeline where you have to extract features manually a CNN uses filters. (Filters like in edge detection or viola and jones).

If a filter runs across the images and is convolved with pixels it Produces an output.

This output is then interpreted by a neuron. If the output is above a threshold it is considered as valid (Step function counts 1 if valid or in case of Sigmoid it has a value on the sigmoid function).

The next steps are the same as before.

This is progressed until the interpretation layer (often softmax). This layer interprets your computation (if the filters are good adapted to your problem you will get a good predicted label) which means you have a low difference between (y_guess - y_true_label).

Now you can see that for the guess of y we have multiplied the input x with many weights w and also used functions on it. This can be seen like a chain rule in analysis.

To get better results the effect of a single weight on the input must be known. Therefore, you use Backpropagation which is a derivative of the Error with respect to all w. The Trick is that you can reuse derivatives which is more or less Backpropagation and it becomes easier since you can use Matrix vector notation.

If you have your gradient, you can use the normal concept of minimization where you walk along the steepest descent. (There are also many other gradient methods like adagrad or adam etc).

The steps will repeat until convergence or until you reach the maximum epochs.

So the  answer is: THE COMPUTED WEIGHTS (FILTERS) ARE THE KEY TO DETECT NUMBERS AND DIGITS :)


问:
How to read the state of current permission status?
In my app, I need GPS to locate the user. I wish my app provide following kinds of result.

```<code>1.The current location.(Success)
2.Failed to get current location because of device error or something else. (Failed)
3.The user refused the permission. (Permission denied)
</code>```

I use LocationManager to do the job.

```<code>locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
</code>```

If the permission is denied, the location will be null.

But I don't know what the location will be if the function failed. And I 'm not sure whether that location is null and user refuse to open GPS are equal.

With the following code, I might know whether the permission is added in the AndroidManifest.xml. But I can't get the information I need.

```<code>boolean getLocationOn = (PackageManager.PERMISSION_GRANTED ==
           pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "my_package"));
</code>```

答:
Use below code to check and request permission

```<code>private void checkAndRequestPermissions() {
    int camera = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
    int storage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int loc = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
    int loc2 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
    int logs = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_LOGS);
    int networkstate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_NETWORK_STATE);
    int internet = ContextCompat.checkSelfPermission(this, android.Manifest.permission.INTERNET);
    int wifistate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_WIFI_STATE);
    int externalstorage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
    int phonestate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE);
    int wakelock = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WAKE_LOCK);
    int alarm = ContextCompat.checkSelfPermission(this, android.Manifest.permission.SET_ALARM);
    int audio = ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO);
    int accounts = ContextCompat.checkSelfPermission(this, android.Manifest.permission.GET_ACCOUNTS);
    int contacts = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS);
    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camera != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
    }
    if (storage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (loc2 != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (loc != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    if (logs != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_LOGS);
    }
    if (networkstate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_NETWORK_STATE);
    }
    if (internet != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.INTERNET);
    }
    if (wifistate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_WIFI_STATE);
    }
    if (externalstorage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
    }
    if (phonestate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_PHONE_STATE);
    }
    if (wakelock != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.WAKE_LOCK);
    }
    if (alarm != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.SET_ALARM);
    }
    if (audio != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.RECORD_AUDIO);
    }
    if (accounts != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.GET_ACCOUNTS);
    }
    if (contacts != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_CONTACTS);
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
    }
}
</code>```

Call checkAndRequestPermissions() to check and request for permission.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    checkAndRequestPermissions();
}
</code>```

Body:
In my app, I need GPS to locate the user. I wish my app provide following kinds of result.

1.The current location.(Success)
2.Failed to get current location because of device error or something else. (Failed)
3.The user refused the permission. (Permission denied)

I use LocationManager to do the job.

locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

If the permission is denied, the location will be null.

But I don't know what the location will be if the function failed. And I 'm not sure whether that location is null and user refuse to open GPS are equal.

With the following code, I might know whether the permission is added in the AndroidManifest.xml. But I can't get the information I need.

boolean getLocationOn = (PackageManager.PERMISSION_GRANTED ==
           pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "my_package"));

Body:
Use below code to check and request permission

private void checkAndRequestPermissions() {
    int camera = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
    int storage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int loc = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
    int loc2 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
    int logs = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_LOGS);
    int networkstate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_NETWORK_STATE);
    int internet = ContextCompat.checkSelfPermission(this, android.Manifest.permission.INTERNET);
    int wifistate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_WIFI_STATE);
    int externalstorage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
    int phonestate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE);
    int wakelock = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WAKE_LOCK);
    int alarm = ContextCompat.checkSelfPermission(this, android.Manifest.permission.SET_ALARM);
    int audio = ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO);
    int accounts = ContextCompat.checkSelfPermission(this, android.Manifest.permission.GET_ACCOUNTS);
    int contacts = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS);
    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camera != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
    }
    if (storage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (loc2 != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (loc != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    if (logs != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_LOGS);
    }
    if (networkstate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_NETWORK_STATE);
    }
    if (internet != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.INTERNET);
    }
    if (wifistate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_WIFI_STATE);
    }
    if (externalstorage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
    }
    if (phonestate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_PHONE_STATE);
    }
    if (wakelock != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.WAKE_LOCK);
    }
    if (alarm != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.SET_ALARM);
    }
    if (audio != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.RECORD_AUDIO);
    }
    if (accounts != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.GET_ACCOUNTS);
    }
    if (contacts != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_CONTACTS);
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
    }
}

Call checkAndRequestPermissions() to check and request for permission.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    checkAndRequestPermissions();
}


问:
Undo an accidental hg strip?
I have accidentally run hg strip, and deleted a stack of commits. I have not done anything in the repo since. Is there a way for me to bring back this stack of commits, to undo the hg strip I just ran?</p>

答: As long as you didn't run the strip with the --no-backup option, the stripped changesets can be found in the repository under .hg\strip-backup.  If you sort the directory content by date the latest one is likely the one you need to restore.  Restore it with hg unbundle <filename>.

Title: Undo an accidental hg strip?


问:
How to do a LIKE in Entity Framework CORE (not full .net)
There are Q+A's for Entity Framework LIKE's in the Full .net framework:

How to do SQL Like % in Linq?

Like Operator in Entity Framework?

eg:

```<code>from c in dc.Organization
where SqlMethods.Like(c.Boss, "%Jeremy%")
</code>```

This doesn't work in EF Core:

The name SqlMethods does not exist in the current context.

So how do you do a LIKE using Entity Framework CORE?

答:
Instead of Like function you can use Contains

```<code>from c in dc.Organization
where c.Boss.Contains("Jeremy")
</code>```

Body:
There are Q+A's for Entity Framework LIKE's in the Full .net framework:

How to do SQL Like % in Linq?

Like Operator in Entity Framework?

eg:

from c in dc.Organization
where SqlMethods.Like(c.Boss, "%Jeremy%")

This doesn't work in EF Core:

The name SqlMethods does not exist in the current context.

So how do you do a LIKE using Entity Framework CORE?

Body:
Instead of Like function you can use Contains

from c in dc.Organization
where c.Boss.Contains("Jeremy")


问:
Need to Merge Avro Files using java application
I am having multiple avro files under a directory which reside on hadoop environment, I need to merge all these files and make it as a single avro file.

example

```<code>/abc->
        x.avro
        y.avro   } => a.avro
        z.avro
</code>```

The file a.avro will contain contents of all x,y,z files, where x,y,z files having same schema. I need to create a java application. Any help appreciated.

Thanks.

答:
There are few tools provided by the apache avro in order to deal with the avro file operations here. These tools include Merging/Concat tool which merge same schema avro file with non-reserved metadata, catTool to extract samples from an Avro data file, conversion tool which Converts an input file from Avro binary into JSON, recoveryTool which Recovers data from a corrupt Avro Data file etc(Find more on the github url mentioned).

I have extract the code from the same tools mentioned on github, here is the java application that does solve your purpose.

```<code>Path inPath  = new Path("C:\\Users\\vaijnathp\\IdeaProjects\\MSExcel\\vaj");
Path outPath = new Path("getDestinationPath") ;
FileSystem fs = FileSystem.get(new Configuration());
FileStatus [] contents contents = fs.listStatus(inPath, new OutputLogFilter());
DataFileWriter<GenericRecord> writer = new DataFileWriter<>(new GenericDatumWriter<>());
Schema schema = null;
String inputCodec = null;
Map<String, byte[]> metadata = new TreeMap<>();
BufferedOutputStream output = new BufferedOutputStream(new BufferedOutputStream(fs.create(outPath)));
for (int i = 0; i < contents.length; i++) {
        FileStatus folderContent = contents[i];
        if (folderContent.isFile() && folderContent.getPath().getName().endsWith(".avro")) {
            InputStream input = new BufferedInputStream(fs.open(folderContent.getPath()));
            DataFileStream<GenericRecord> reader = new DataFileStream<>(input, new GenericDatumReader<GenericRecord>());
            if (schema == null) {
                schema = reader.getSchema();
               //extract metadata for further check.
                extractAvroFileMetadata(writer, metadata, reader);
                inputCodec = reader.getMetaString(DataFileConstants.CODEC);
                if (inputCodec == null) inputCodec = DataFileConstants.NULL_CODEC;
                writer.setCodec(CodecFactory.fromString(inputCodec));
                writer.create(schema, output);
            } else {
                if (!schema.equals(reader.getSchema())) reader.close();
                //compare FileMetadata with previously extracted one
                CompareAvroFileMetadata(metadata, reader, folderContent.getPath().getName());
                String thisCodec = reader.getMetaString(DataFileConstants.CODEC);
                if (thisCodec == null) thisCodec = DataFileConstants.NULL_CODEC;
                if (!inputCodec.equals(thisCodec)) reader.close();
            }
            writer.appendAllFrom(reader, false);
            reader.close();
        }
    }
 writer.close();
}catch (Exception e){
    e.printStackTrace();
}
</code>```

I hope this code snippet will help you create your java application. Thanks.

Body:
I am having multiple avro files under a directory which reside on hadoop environment, I need to merge all these files and make it as a single avro file.

example

/abc->
        x.avro
        y.avro   } => a.avro
        z.avro

The file a.avro will contain contents of all x,y,z files, where x,y,z files having same schema. I need to create a java application. Any help appreciated.

Thanks.

Body:
There are few tools provided by the apache avro in order to deal with the avro file operations here. These tools include Merging/Concat tool which merge same schema avro file with non-reserved metadata, catTool to extract samples from an Avro data file, conversion tool which Converts an input file from Avro binary into JSON, recoveryTool which Recovers data from a corrupt Avro Data file etc(Find more on the github url mentioned).

I have extract the code from the same tools mentioned on github, here is the java application that does solve your purpose.

Path inPath  = new Path("C:\\Users\\vaijnathp\\IdeaProjects\\MSExcel\\vaj");
Path outPath = new Path("getDestinationPath") ;
FileSystem fs = FileSystem.get(new Configuration());
FileStatus [] contents contents = fs.listStatus(inPath, new OutputLogFilter());
DataFileWriter<GenericRecord> writer = new DataFileWriter<>(new GenericDatumWriter<>());
Schema schema = null;
String inputCodec = null;
Map<String, byte[]> metadata = new TreeMap<>();
BufferedOutputStream output = new BufferedOutputStream(new BufferedOutputStream(fs.create(outPath)));
for (int i = 0; i < contents.length; i++) {
        FileStatus folderContent = contents[i];
        if (folderContent.isFile() && folderContent.getPath().getName().endsWith(".avro")) {
            InputStream input = new BufferedInputStream(fs.open(folderContent.getPath()));
            DataFileStream<GenericRecord> reader = new DataFileStream<>(input, new GenericDatumReader<GenericRecord>());
            if (schema == null) {
                schema = reader.getSchema();
               //extract metadata for further check.
                extractAvroFileMetadata(writer, metadata, reader);
                inputCodec = reader.getMetaString(DataFileConstants.CODEC);
                if (inputCodec == null) inputCodec = DataFileConstants.NULL_CODEC;
                writer.setCodec(CodecFactory.fromString(inputCodec));
                writer.create(schema, output);
            } else {
                if (!schema.equals(reader.getSchema())) reader.close();
                //compare FileMetadata with previously extracted one
                CompareAvroFileMetadata(metadata, reader, folderContent.getPath().getName());
                String thisCodec = reader.getMetaString(DataFileConstants.CODEC);
                if (thisCodec == null) thisCodec = DataFileConstants.NULL_CODEC;
                if (!inputCodec.equals(thisCodec)) reader.close();
            }
            writer.appendAllFrom(reader, false);
            reader.close();
        }
    }
 writer.close();
}catch (Exception e){
    e.printStackTrace();
}

I hope this code snippet will help you create your java application. Thanks.


问:
mysql select to return blanks for all but first row of repeating column
Is it possible to create a mysql select (directly or using a stored procedure) that will return blanks for repeating columns.  For example, a select that would normally return these 7 records with 2 columns:

```<code>Bob   123
Bob   557
Bob   888
Joe   887
Joe   223
Tom   899
Tom   999
</code>```

I would prefer to see this directly from the sql select:

```<code>Bob   123
      557
      888
Joe   887
      223
Tom   899
      999
</code>```

I realize I can just post process the records in my program, but I'd like to replace the duplicates with blanks within the sql call.

答:
For future readers, here is a select query that will return blanks for repeating column values.</p>

```<code>SELECT IF(name=@previous, "", @previous:=name) as name_, value
FROM (SELECT @previous:= '') AS temp, tableName
ORDER BY name
</code>```

Body:
Is it possible to create a mysql select (directly or using a stored procedure) that will return blanks for repeating columns.  For example, a select that would normally return these 7 records with 2 columns:

Bob   123
Bob   557
Bob   888
Joe   887
Joe   223
Tom   899
Tom   999

I would prefer to see this directly from the sql select:

Bob   123
      557
      888
Joe   887
      223
Tom   899
      999

I realize I can just post process the records in my program, but I'd like to replace the duplicates with blanks within the sql call.

Body:
For future readers, here is a select query that will return blanks for repeating column values.

SELECT IF(name=@previous, "", @previous:=name) as name_, value
FROM (SELECT @previous:= '') AS temp, tableName
ORDER BY name


问:
PushNotification banner not showing in ios 10.3
I have integrated Push notification on to my project and for some reason the banner appears on when I'm in the background mood and not when I'm in the foreground. I'm sure I've missed something, my code as bellow. Any help would much appreciate.

```<code>import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self //not sure this is appropriate
        registerForPushNotifications()
}
func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in

            guard granted else { return }
            self.getNotificationSettings()
        }
    }
    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async(execute: {
            UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }

        let token = tokenParts.joined()
        if let valueInDB = UserDefaults.standard.value(forKey: "Permission_Granted") {

        UserDefaults.standard.setValue(token, forKey: "PUSH_TOKEN")
        UserDefaults.standard.synchronize()
        print("Device Push Token: \(token)")

    }
</code>```

This gets called every time I gets a notification despite if its running on foreground or background. Thus the batch icon gets updated.

```<code>func application(_ application: UIApplication,
                         didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
        {

            print("Recived: \(userInfo)")

            completionHandler(.newData)

            self.onPushRecieved = MP3ViewController().catchPushNotifications
            let notification = JSON(userInfo)
            print(notification)

            let mediaId = (notification["media_id"]).stringValue
            print(mediaId)
            var badgeCount = 0
            var pushAvailable = false

            if let pushCount = UserDefaults.standard.value(forKey: "PUSH_COUNT"){
                badgeCount = pushCount as! Int
                print(badgeCount)
                badgeCount = badgeCount + 1
                UIApplication.shared.applicationIconBadgeNumber = badgeCount
            }

            print(badgeCount)
            UserDefaults.standard.setValue(badgeCount, forKey: "PUSH_COUNT")
            UserDefaults.standard.synchronize()

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            print(isOnBackGround)
            if isOnBackGround {
                if mediaId != nil{
                    DispatchQueue.main.async {
                        let mP3ViewController = storyboard.instantiateViewController(withIdentifier:"MP3ViewController") as! MP3ViewController
                        mP3ViewController.media_ID = mediaId
                        self.navigationController?.pushViewController(mP3ViewController, animated:true)
                        self.isOnBackGround = false

                    }

                }
            }else{
                print("Running on foreground")

            }

        }
    }
</code>```

答:
You may want to implement the following function, eg:

```<code>public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {
    completionHandler([.badge, .alert, .sound])
}
</code>```

of this delegate: UNUserNotificationCenterDelegate

Body:
I have integrated Push notification on to my project and for some reason the banner appears on when I'm in the background mood and not when I'm in the foreground. I'm sure I've missed something, my code as bellow. Any help would much appreciate.

import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self //not sure this is appropriate
        registerForPushNotifications()
}
func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in

            guard granted else { return }
            self.getNotificationSettings()
        }
    }
    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async(execute: {
            UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }

        let token = tokenParts.joined()
        if let valueInDB = UserDefaults.standard.value(forKey: "Permission_Granted") {

        UserDefaults.standard.setValue(token, forKey: "PUSH_TOKEN")
        UserDefaults.standard.synchronize()
        print("Device Push Token: \(token)")

    }

This gets called every time I gets a notification despite if its running on foreground or background. Thus the batch icon gets updated.

func application(_ application: UIApplication,
                         didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
        {

            print("Recived: \(userInfo)")

            completionHandler(.newData)

            self.onPushRecieved = MP3ViewController().catchPushNotifications
            let notification = JSON(userInfo)
            print(notification)

            let mediaId = (notification["media_id"]).stringValue
            print(mediaId)
            var badgeCount = 0
            var pushAvailable = false

            if let pushCount = UserDefaults.standard.value(forKey: "PUSH_COUNT"){
                badgeCount = pushCount as! Int
                print(badgeCount)
                badgeCount = badgeCount + 1
                UIApplication.shared.applicationIconBadgeNumber = badgeCount
            }

            print(badgeCount)
            UserDefaults.standard.setValue(badgeCount, forKey: "PUSH_COUNT")
            UserDefaults.standard.synchronize()

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            print(isOnBackGround)
            if isOnBackGround {
                if mediaId != nil{
                    DispatchQueue.main.async {
                        let mP3ViewController = storyboard.instantiateViewController(withIdentifier:"MP3ViewController") as! MP3ViewController
                        mP3ViewController.media_ID = mediaId
                        self.navigationController?.pushViewController(mP3ViewController, animated:true)
                        self.isOnBackGround = false

                    }

                }
            }else{
                print("Running on foreground")

            }

        }
    }

Body:
You may want to implement the following function, eg:

public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {
    completionHandler([.badge, .alert, .sound])
}

of this delegate: UNUserNotificationCenterDelegate


答:
You have to use below code for left button

```<code><ion-header>

    <ion-navbar>
        <button ion-button icon-only menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>

        <ion-title>
            Page Title
        </ion-title>

        <ion-buttons end>
            <button ion-button icon-only (click)="openModal()">
                <ion-icon name="options"></ion-icon>
            </button>
        </ion-buttons>
    </ion-navbar>

</ion-header>
</code>```

For footer you can use ion-grid

```<code><ion-footer class="footer">
  <form #com="ngForm" (submit)="onsubmit(com.value)">
    <ion-grid>
        <ion-row>
            <ion-col col-9>
                <ion-input placeholder="TAG" type="text" name="TAG" ngModel ></ion-input>
            </ion-col>
            <ion-col col-3>
                <button ion-button type="submit">Submit</button>
            </ion-col>
        </ion-row>
    </ion-grid>
  </form>
</ion-footer>
</code>```

For more info please refer this

https://ionicframework.com/docs/api/components/toolbar/Navbar/

Title: Why are my buttons going out of screen in my Ionic app?

Body:
You have to use below code for left button

<ion-header>

    <ion-navbar>
        <button ion-button icon-only menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>

        <ion-title>
            Page Title
        </ion-title>

        <ion-buttons end>
            <button ion-button icon-only (click)="openModal()">
                <ion-icon name="options"></ion-icon>
            </button>
        </ion-buttons>
    </ion-navbar>

</ion-header>

For footer you can use ion-grid

<ion-footer class="footer">
  <form #com="ngForm" (submit)="onsubmit(com.value)">
    <ion-grid>
        <ion-row>
            <ion-col col-9>
                <ion-input placeholder="TAG" type="text" name="TAG" ngModel ></ion-input>
            </ion-col>
            <ion-col col-3>
                <button ion-button type="submit">Submit</button>
            </ion-col>
        </ion-row>
    </ion-grid>
  </form>
</ion-footer>

For more info please refer this

https://ionicframework.com/docs/api/components/toolbar/Navbar/


问:
Use ActiveRecord to count rows where id is matched and another column matches one of two values
I need to create a query in CodeIgniter as follows:

```<code>SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE (
       LOWER(ResponseStatus) = 'submitted'
       OR LOWER(ResponseStatus) = 'inqueue'
      )
      AND `SMSUsageID` = '1'
</code>```

so I created a function in my model as:

```<code>function submittedSMSCount($smsUsageID) {
    $this->db->where('lower(ResponseStatus)', 'submitted');
    $this->db->or_where('lower(ResponseStatus)', 'inqueue');
    $this->db->where('SMSUsageID', $smsUsageID);
    return $this->db->count_all_results('smslog_tbl');
}
</code>```

but this function generates a query like:

```<code>SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE LOWER(ResponseStatus) = 'submitted'
      OR LOWER(ResponseStatus) = 'inqueue'
      AND `SMSUsageID` = '1'
</code>```

These two queries generate different results because of the conditions. I need to group the OR conditions to get the correct result. How can I do this with CodeIgniter's Active Record query building methods?

答:
use group with query builder

```<code>function submittedSMSCount($smsUsageID) {
    $this->db->select('COUNT(*) AS numrows')
    ->group_start()
    ->where('lower(ResponseStatus)', 'submitted')
    ->or_where('lower(ResponseStatus)','inqueue')
    ->group_end()
    ->where('SMSUsageID', $smsUsageID);
    return $this->db->get('smslog_tbl');
}
</code>```

output

SELECT COUNT(*) AS numrows FROM smslog_tbl WHERE ( lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue' ) AND SMSUsageID = '1'

Body:
I need to create a query in CodeIgniter as follows:

SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE (
       LOWER(ResponseStatus) = 'submitted'
       OR LOWER(ResponseStatus) = 'inqueue'
      )
      AND `SMSUsageID` = '1'

so I created a function in my model as:

function submittedSMSCount($smsUsageID) {
    $this->db->where('lower(ResponseStatus)', 'submitted');
    $this->db->or_where('lower(ResponseStatus)', 'inqueue');
    $this->db->where('SMSUsageID', $smsUsageID);
    return $this->db->count_all_results('smslog_tbl');
}

but this function generates a query like:

SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE LOWER(ResponseStatus) = 'submitted'
      OR LOWER(ResponseStatus) = 'inqueue'
      AND `SMSUsageID` = '1'

These two queries generate different results because of the conditions. I need to group the OR conditions to get the correct result. How can I do this with CodeIgniter's Active Record query building methods?

Body:
use group with query builder

function submittedSMSCount($smsUsageID) {
    $this->db->select('COUNT(*) AS numrows')
    ->group_start()
    ->where('lower(ResponseStatus)', 'submitted')
    ->or_where('lower(ResponseStatus)','inqueue')
    ->group_end()
    ->where('SMSUsageID', $smsUsageID);
    return $this->db->get('smslog_tbl');
}

output

SELECT COUNT(*) AS numrows FROM smslog_tbl WHERE ( lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue' ) AND SMSUsageID = '1'


问:
Disable automatic (preview) window (buffer) with a function signature
Every time I click dot, the function signature appears in a separate buffer.

```<code>import sys

sys.argv   # in this moment I have a separate buffer opened with sys.argv signature
</code>```

Then this buffer exists until manually closed.

I'd like to have it only when I press ctrl-K. Or at least it disappears when I exit insert mode...

答:
Finally I found the solution:

add

I added youCompleteMe plugin:

Plugin 'Valloric/YouCompleteMe'

and

let g:ycm_autoclose_preview_window_after_completion=1

Body:
Every time I click dot, the function signature appears in a separate buffer.

import sys

sys.argv   # in this moment I have a separate buffer opened with sys.argv signature

Then this buffer exists until manually closed.

I'd like to have it only when I press ctrl-K. Or at least it disappears when I exit insert mode...


问:
Combine two arrays in specific order
I need to combine these two arrays:

```<code>A = ["Dog", "Cat", "Bird"]
B = ["John", "Doe", "Foo"]
</code>```

I must take the first element of the first array and then the first element of the second array, then the second element of the first array and the second element of the second array and so on. It has to be in this exact order:

```<code>["Dog", "John", "Cat", "Doe", "Bird", "Foo"]
</code>```

Title: Combine two arrays in specific order

Body:
I need to combine these two arrays:

A = ["Dog", "Cat", "Bird"]
B = ["John", "Doe", "Foo"]

I must take the first element of the first array and then the first element of the second array, then the second element of the first array and the second element of the second array and so on. It has to be in this exact order:

["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

Body:
Array.new(2*A.size) { |i| i.even? ? A[i/2] : B[i/2] }
  #=> ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]


问:
Intellij-idea cannot see generated sources directory
I have a maven project in IntelliJ I have marked the generated sources directory as the source by doing Files>Project Structure and marking as source. I've also done it the other way by right clicking on the folder and marking as generated-sources.

I'm still getting errors saying the IntelliJ cannot find things in these folders Cannot resolve symbol 'name_of_folder' when I'm creating a SOAP implementation

Does anyone know how I can fix this issue? From what I can see I have done everything correctly to mark that folder and IntelliJ Should be able to read from there

答: uncheck "Create Separate module per source set" in Preferences > Build, Execution, Deployment > Gradle and then rebuild / gradle refresh</p>


问:
Smooth edges of non-rectangular form in .NET
I've created a form with rounded corners using Form.Region. It works, but unfortunately the rounding appears rough. Are there any tricks for smoothing such shaped form corners? I know many applications support this, just not sure how to make it in .NET.

Thanks guys.

答:
From what I've read online most people end up overriding the forms onpaint event and drawing the region there.  This allows them to use GDI+ with antialiasing and make it look much cleaner.

The examples I found:

http://netcode.ru/dotnet/?lang=&katID=30&skatID=283&artID=7833
http://www.xtremevbtalk.com/showthread.php?t=288178


问:
Async functions on Angular2
I want to make functions on this service asynchronous, the last function should wait to a response of the one above it and so on. I am getting 'property subscribe does not exist on type void' on the second line of createPlaylist() and I don't know why.

Imports:

```<code>import { Injectable } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
</code>```

Code:

```<code>getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  this.http.get(url, {headers : headers}).map((res: Response) => res.json())
  .subscribe(result => {
    this.currentUser = result.id;
    console.log(this.currentUser);
    return Observable.of(result);
  });
}

createPlaylist(token:string = localStorage.getItem('myToken')) {
  this.getUserId().subscribe(user => {
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {
    'name': 'searchDDD playlist'
  };
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.json().name);
    console.log(result.status);
    this.playlistID = result.json().id;
  });
  });
}

addSongs(token:string = localStorage.getItem('myToken')) {
  this.createPlaylist();
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists/${this.playlistID}/tracks`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {'uris': ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
  'spotify:track:1301WleyT98MSxVHPZCA6M']};
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.status);
  });
}
</code>```

答:
Return from the getUserId function and remove the subscribe part. You can just one time subscribe to a Observable and put the logic inside the single subscribe or just write an intermediate logic via do function.

```<code>getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  return this.http.get(url, {headers : headers})
                  .map((res: Response) => res.json())
                  .do(result => this.currentUser = result.id);
}
</code>```

Title: Async functions on Angular2

Body:
I want to make functions on this service asynchronous, the last function should wait to a response of the one above it and so on. I am getting 'property subscribe does not exist on type void' on the second line of createPlaylist() and I don't know why.

Imports:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

Code:

getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  this.http.get(url, {headers : headers}).map((res: Response) => res.json())
  .subscribe(result => {
    this.currentUser = result.id;
    console.log(this.currentUser);
    return Observable.of(result);
  });
}

createPlaylist(token:string = localStorage.getItem('myToken')) {
  this.getUserId().subscribe(user => {
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {
    'name': 'searchDDD playlist'
  };
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.json().name);
    console.log(result.status);
    this.playlistID = result.json().id;
  });
  });
}

addSongs(token:string = localStorage.getItem('myToken')) {
  this.createPlaylist();
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists/${this.playlistID}/tracks`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {'uris': ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
  'spotify:track:1301WleyT98MSxVHPZCA6M']};
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.status);
  });
}

Body:
Return from the getUserId function and remove the subscribe part. You can just one time subscribe to a Observable and put the logic inside the single subscribe or just write an intermediate logic via do function.

getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  return this.http.get(url, {headers : headers})
                  .map((res: Response) => res.json())
                  .do(result => this.currentUser = result.id);
}


问:
Python - Double backslash is not passed to command
I need to pass the following user login to a bash subprocess command, however when its passed through it returns as "domain\test" rather than a single backslash. But when i print it, it will return as a single.

```<code>usr = "domain\\"
u = "test"
usrLogin = ''.join([usr,u])
</code>```

I have tried the following variations of assigning usr:

```<code>usr = "domain\\"
usr = 'domain\\'
usr = r'domain\'
usr = r"domain\\"
usr = str(r('domain\\'))
</code>```

The string is passed to the following command:
    subprocess.call(["chown", "-R", usrLogin, usrLocation])

The output i need is:

```<code>domain\test
</code>```

however at the moment, when it is being passed to the subprocess call it is showing as:

```<code>domain\\usr
</code>```

However when i call print it will only show with 1 backslash:

```<code>print('usrLogin)
domain\test
</code>```

Edit: Sorry for the confusion, i have added more detail that hopefully helps.

答:
usr = "domain\\"

\ is escape character, so you've to use four slashes to get two.

Body:
I need to pass the following user login to a bash subprocess command, however when its passed through it returns as "domain\test" rather than a single backslash. But when i print it, it will return as a single.

usr = "domain\\"
u = "test"
usrLogin = ''.join([usr,u])

I have tried the following variations of assigning usr:

usr = "domain\\"
usr = 'domain\\'
usr = r'domain\'
usr = r"domain\\"
usr = str(r('domain\\'))

The string is passed to the following command:
    subprocess.call(["chown", "-R", usrLogin, usrLocation])

The output i need is:

domain\test

however at the moment, when it is being passed to the subprocess call it is showing as:

domain\\usr

However when i call print it will only show with 1 backslash:

print('usrLogin)
domain\test

Edit: Sorry for the confusion, i have added more detail that hopefully helps.


问:
Why does scanf skip getting string input?
I am trying to get multiple words input and multiple lines into one array. But somewhere the code skips getting the input and skips to end the program. I have tried adding space before and after the ' %s' (or '%s ') but it won't work (maybe because it's inside a loop?). Would really appreciate anyone's help! It also starts to act weird if I enter more than two-three words :(
My goal is to find how many times a specific letter has occurred throughout all those words and lines.</p>

```<code>#include <stdio.h> //include standard library

int main(){
  int lineCount, occuranceCount;
  printf("How many lines are you going to enter?");
  scanf("%d", &lineCount);

  char input[lineCount][100], searchChar;

  for(int i=0; i<lineCount; i++){
    printf("Please enter line #%d (100 characters of less):",i+1);
    scanf("%s", &input[i]);
  }

  printf("What letter do you want to check the frequence in those lines? ");
  scanf("%c", &searchChar);

  for(int j=0; j<lineCount; j++){
    for(int k=0; k<100; k++){
      if(input[j][k] != '\0'){
        if(input[j][k]==searchChar)
          occuranceCount++;
      }
    }
  }

  printf("The letter occurs for %d time", occuranceCount);

  return 0;
}
</code>```

答:
scanf using the %s always read until a ' '(whitespace) or '\n'(new line) is encountered, so you always can read only one word with scanf("%s", s1)...

if you want to read the spaces or new line characters you must use gets, or fgets(more secure than gets)

Body:
I am trying to get multiple words input and multiple lines into one array. But somewhere the code skips getting the input and skips to end the program. I have tried adding space before and after the ' %s' (or '%s ') but it won't work (maybe because it's inside a loop?). Would really appreciate anyone's help! It also starts to act weird if I enter more than two-three words :(
My goal is to find how many times a specific letter has occurred throughout all those words and lines.

#include <stdio.h> //include standard library

int main(){
  int lineCount, occuranceCount;
  printf("How many lines are you going to enter?");
  scanf("%d", &lineCount);

  char input[lineCount][100], searchChar;

  for(int i=0; i<lineCount; i++){
    printf("Please enter line #%d (100 characters of less):",i+1);
    scanf("%s", &input[i]);
  }

  printf("What letter do you want to check the frequence in those lines? ");
  scanf("%c", &searchChar);

  for(int j=0; j<lineCount; j++){
    for(int k=0; k<100; k++){
      if(input[j][k] != '\0'){
        if(input[j][k]==searchChar)
          occuranceCount++;
      }
    }
  }

  printf("The letter occurs for %d time", occuranceCount);

  return 0;
}


问:
Write data to Google Spreadsheet using API Key (C#)
I have an app that allow me to read the data from Google Spreadsheet using API Key. I just make HTTP GET to this address and get a response with data.

```<code>https://sheets.googleapis.com/v4/spreadsheets/18soCZy9H4ZGuu**********BeHlNY1lD8at-Pbjmf8c/values/Sheet1!A1?key=AIzaSyAYJ***********pB-4iKZjYf4y0vhXP8OM
</code>```

But when I try to do same to write data using HTTP PUT to address

```<code>https://sheets.googleapis.com/v4/spreadsheets/18soCZy9H4ZGuu**********BeHlNY1lD8at-Pbjmf8c/values/Sheet1!A4?valueInputOption=RAW?key=AIzaSyAYJ***********pB-4iKZjYf4y0vhXP8OM
</code>```

its gives me 401 error.
Code to make PUT request:

```<code> using (WebClient wc = new WebClient())
 {
     byte[] res = wc.UploadData(link, "PUT", Encoding.ASCII.GetBytes(textBox1.Text));
     MessageBox.Show(Encoding.Default.GetString(res));
 }
</code>```

Also spreadsheet is fully public with permission to read and write by anyone without auth. My guess is that I can't use API Key to write data to spreadsheet, and only way to do this is using OAuth.

UPDATE:
So i've just tryed Google.Apis.Sheets.v4 to write values, and now i'm almost 100% sure that API Key can't be used to write data to Google Spreadsheet. Well, then I'll use OAuth 2.0.

答:
For anyone still hoping for a simple answer, it seems there won't be one - any writing to a sheet, irrespective of the sheets permissions, will require OAuth2:

'This is intentional behavior. While public sheets are anonymously readable, anonymous edits aren't currently supported for a variety of reasons.

In this context, "anyone" == anyone with a google account.' HERE

Body:
I have an app that allow me to read the data from Google Spreadsheet using API Key. I just make HTTP GET to this address and get a response with data.

https://sheets.googleapis.com/v4/spreadsheets/18soCZy9H4ZGuu**********BeHlNY1lD8at-Pbjmf8c/values/Sheet1!A1?key=AIzaSyAYJ***********pB-4iKZjYf4y0vhXP8OM

But when I try to do same to write data using HTTP PUT to address

https://sheets.googleapis.com/v4/spreadsheets/18soCZy9H4ZGuu**********BeHlNY1lD8at-Pbjmf8c/values/Sheet1!A4?valueInputOption=RAW?key=AIzaSyAYJ***********pB-4iKZjYf4y0vhXP8OM

its gives me 401 error.
Code to make PUT request:

 using (WebClient wc = new WebClient())
 {
     byte[] res = wc.UploadData(link, "PUT", Encoding.ASCII.GetBytes(textBox1.Text));
     MessageBox.Show(Encoding.Default.GetString(res));
 }

Also spreadsheet is fully public with permission to read and write by anyone without auth. My guess is that I can't use API Key to write data to spreadsheet, and only way to do this is using OAuth.

UPDATE:
So i've just tryed Google.Apis.Sheets.v4 to write values, and now i'm almost 100% sure that API Key can't be used to write data to Google Spreadsheet. Well, then I'll use OAuth 2.0.


问:
Spring Boot integration tests doesn't read properties files
I would like to create integration test in which Spring Boot will read a value from .properties file using @Value annotation.

But every time I'm running test my assertion fails because Spring is unable to read the value:

```<code>org.junit.ComparisonFailure:
Expected :works!
Actual   :${test}
</code>```

My test:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
    @Configuration
    @ActiveProfiles("test")
    static class ConfigurationClass {}

    @Component
    static class ClassToTest{
        @Value("${test}")
        private String test;
    }

    @Autowired
    private ClassToTest config;

    @Test
    public void testTransferService() {
        Assert.assertEquals(config.test, "works!");
    }
}
</code>```

application-test.properties under src/main/resource package contains:

```<code>test=works!
</code>```

What can be the reason of that behavior and how can I fix it?

Any help highly appreciated.

答:
Besides the above marked correct answer, there is another nature way to load application-test.properties: Set your test run "profile" to "test".

Mark your test cases with:

```<code>@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
</code>```

application-xxxx.properties is a naming convention for properties of different "profile".

This file application-xxxx.properties should be placed in src/main/resources folder.

"Profile" is also useful in bean configuration.

Body:
I would like to create integration test in which Spring Boot will read a value from .properties file using @Value annotation.

But every time I'm running test my assertion fails because Spring is unable to read the value:

org.junit.ComparisonFailure:
Expected :works!
Actual   :${test}

My test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
    @Configuration
    @ActiveProfiles("test")
    static class ConfigurationClass {}

    @Component
    static class ClassToTest{
        @Value("${test}")
        private String test;
    }

    @Autowired
    private ClassToTest config;

    @Test
    public void testTransferService() {
        Assert.assertEquals(config.test, "works!");
    }
}

application-test.properties under src/main/resource package contains:

test=works!

What can be the reason of that behavior and how can I fix it?

Any help highly appreciated.

Body:
Besides the above marked correct answer, there is another nature way to load application-test.properties: Set your test run "profile" to "test".

Mark your test cases with:

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)

application-xxxx.properties is a naming convention for properties of different "profile".

This file application-xxxx.properties should be placed in src/main/resources folder.

"Profile" is also useful in bean configuration.