问:
PDO MYSQL_ATTR_USE_BUFFERED_QUERY Not taking affect
I have the following rough code (full code is 146 lines, 90 of which are string parsing, can add if needed):

```<code>ini_set('memory_limit', '7G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2020-04-25', '2020-05-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
}
</code>```

during $stmt->execute(array('2020-04-25', '2020-05-25')); my memory consumption is as .34GB (using ps aux | grep 'php ' | awk '{$5=int(100 * $5/1024/1024)/100"GB";}{ print;}' to monitor consumption during select and show full processlist SQL side to verify). Once the script enters the while it jumps to +5 GB.

Testing the setattribute

```<code>var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));
</code>```

seems like it has taken affect:

```<code>bool(true)
</code>```

but the behavior doesn't change when I switch buffered or unbuffered.

```<code>$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)
</code>```

and

```<code>$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)
</code>```

Using echo $db->getAttribute(constant('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')); also shows the setting changes.

Moving the setting to the statement rather than connection as https://www.php.net/manual/en/ref.pdo-mysql.php suggested also didn't work.

```<code>$stmt = $db->prepare('select columns from stats where timestamp between ? and ?', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
</code>```

I've also tried moving the buffer setting to the connection with no affect:

```<code>$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
</code>```

Taking out the second connection seems to allow the unbuffered query to function as intended:

```<code>ini_set('memory_limit', '1G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
//$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
//$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2019-01-25', '2019-11-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      /*
     $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
     */
}
</code>```

This usage the memory_get_usage doesn't exceed 379999.

If I uncomment the second connection and make it unbuffered as well I receive:

```<code>Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
</code>```

The second connection buffered performs as initially described, large memory consumption on execution. If ini_set('memory_limit' is high it works if low it errors. Using a large memory_limit isn't a feasible solution.

Was using (Red Hat Enterprise Linux Server release 7.3 (Maipo)):

```<code>php71u-pdo.x86_64                  7.1.19-1.ius.centos7
</code>```

Moved script to a newer machine (Amazon Linux release 2 (Karoo)):

```<code>var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));
</code>```0

and have the same behavior.

答:
You are actually making 135000000 queries instead of iterating over 135000000 objects.

Change the code to only do one query but order the elements as if they were inside your for loop.

```<code>$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$stmt = $db->prepare('SELECT * FROM stats ORDER BY id ASC');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // ...
}
</code>```

You even don't need this if, it's logic that can be faster used by the DB itself:

if(!empty($row['id'])) {

Instead:

```<code>SELECT * FROM stats WHERE id IS NOT NULL ORDER BY id ASC
</code>```

I didnt look into PDO/MySQL for some time but I was assuming unbuffered allows you to use the cursor:

```<code>$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
</code>```

Take in account there can be only a single query active per connection. You are basically using the connection's buffer.

The better option would be to load only small chunks in a map reduce kind of way.

```<code>SELECT * FROM stats LIMIT 100, 0
</code>```

use the results, then

```<code>SELECT * FROM stats LIMIT 100, 100
</code>```

and so on.

Body:
I have the following rough code (full code is 146 lines, 90 of which are string parsing, can add if needed):

ini_set('memory_limit', '7G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2020-04-25', '2020-05-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
}

during $stmt->execute(array('2020-04-25', '2020-05-25')); my memory consumption is as .34GB (using ps aux | grep 'php ' | awk '{$5=int(100 * $5/1024/1024)/100"GB";}{ print;}' to monitor consumption during select and show full processlist SQL side to verify). Once the script enters the while it jumps to +5 GB.

Testing the setattribute

var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));

seems like it has taken affect:

bool(true)

but the behavior doesn't change when I switch buffered or unbuffered.

$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)

and

$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)

Using echo $db->getAttribute(constant('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')); also shows the setting changes.

Moving the setting to the statement rather than connection as https://www.php.net/manual/en/ref.pdo-mysql.php suggested also didn't work.

$stmt = $db->prepare('select columns from stats where timestamp between ? and ?', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));

I've also tried moving the buffer setting to the connection with no affect:

$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));

Taking out the second connection seems to allow the unbuffered query to function as intended:

ini_set('memory_limit', '1G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
//$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
//$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2019-01-25', '2019-11-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      /*
     $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
     */
}

This usage the memory_get_usage doesn't exceed 379999.

If I uncomment the second connection and make it unbuffered as well I receive:

Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

The second connection buffered performs as initially described, large memory consumption on execution. If ini_set('memory_limit' is high it works if low it errors. Using a large memory_limit isn't a feasible solution.

Was using (Red Hat Enterprise Linux Server release 7.3 (Maipo)):

php71u-pdo.x86_64                  7.1.19-1.ius.centos7

Moved script to a newer machine (Amazon Linux release 2 (Karoo)):

php73-pdo.x86_64                   7.3.17-1.el7.ius

and have the same behavior.

Body:
You are actually making 135000000 queries instead of iterating over 135000000 objects.

Change the code to only do one query but order the elements as if they were inside your for loop.

$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$stmt = $db->prepare('SELECT * FROM stats ORDER BY id ASC');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // ...
}

You even don't need this if, it's logic that can be faster used by the DB itself:

if(!empty($row['id'])) {

Instead:

SELECT * FROM stats WHERE id IS NOT NULL ORDER BY id ASC

I didnt look into PDO/MySQL for some time but I was assuming unbuffered allows you to use the cursor:

$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

Take in account there can be only a single query active per connection. You are basically using the connection's buffer.

The better option would be to load only small chunks in a map reduce kind of way.

SELECT * FROM stats LIMIT 100, 0

use the results, then

SELECT * FROM stats LIMIT 100, 100

and so on.


来源: stackexchange

问:
RedirectToAction is not sending users to correct page
I want to redirect the user if the date is past 5/25/2020
otherwise they get the current view

```<code>    public ActionResult Login()
    {
        DateTime dt = DateTime.Now;
        DateTime expirationDate = new DateTime(2020, 05, 25);

        if (dt > expirationDate)
        {
            return RedirectToAction("ThankYou", "Home");
        }
        else
        {

        }
        return View();
    }
</code>```

Code from HomeController.cs

```<code>    public IActionResult Index()
    {
        var userId = User.Identity.Name;
        string userIdfromCache = SaveToCache("UserID", userId);
        return RedirectToAction("Login", "Authentication");
    }

    public IActionResult ThankYou()
    {
        return View();
    }
</code>```

The IActionResult ThankYou() is not redirecting the user. It should display a static HTML file

答: The only return in the ActionResult is the View(). Replace  RedirectToAction("ThankYou", "Home"); with  return RedirectToAction("ThankYou", "Home"); and it should work

ContentLicense: CC BY-SA 4.0

Body:
I want to redirect the user if the date is past 5/25/2020
otherwise they get the current view

    public ActionResult Login()
    {
        DateTime dt = DateTime.Now;
        DateTime expirationDate = new DateTime(2020, 05, 25);

        if (dt > expirationDate)
        {
            return RedirectToAction("ThankYou", "Home");
        }
        else
        {

        }
        return View();
    }

Code from HomeController.cs

    public IActionResult Index()
    {
        var userId = User.Identity.Name;
        string userIdfromCache = SaveToCache("UserID", userId);
        return RedirectToAction("Login", "Authentication");
    }

    public IActionResult ThankYou()
    {
        return View();
    }

The IActionResult ThankYou() is not redirecting the user. It should display a static HTML file


问:
How can a child worker send message to parent process in Deno?
From this answer, I know that a parent process can talk to a child worker, but how about the other way around?</p>

答:
From the worker you have to use Worker.postMessage

self.postMessage('hi')
```

<p>And in the main process:</p>

<pre class="lang-js prettyprint-override"><code>const worker = new Worker("./worker.js", { type: "module", deno: true });

worker.addEventListener('message', message => {
    console.log('message', message);
    // message.data === 'hi'
});
</code>```

Regarding self

The Window.self read-only property returns the window itself, as a
  WindowProxy. It can be used with dot notation on a window object (that
  is, window.self) or standalone (self). The advantage of the standalone
  notation is that a similar notation exists for non-window contexts,
  such as in Web Workers. By using self, you can refer to the global
  scope in a way that will work not only in a window context (self will
  resolve to window.self) but also in a worker context (self will then
  resolve to WorkerGlobalScope.self).

Body:
From the worker you have to use Worker.postMessage

self.postMessage('hi')

And in the main process:

const worker = new Worker("./worker.js", { type: "module", deno: true });

worker.addEventListener('message', message => {
    console.log('message', message);
    // message.data === 'hi'
});

Regarding self

The Window.self read-only property returns the window itself, as a
  WindowProxy. It can be used with dot notation on a window object (that
  is, window.self) or standalone (self). The advantage of the standalone
  notation is that a similar notation exists for non-window contexts,
  such as in Web Workers. By using self, you can refer to the global
  scope in a way that will work not only in a window context (self will
  resolve to window.self) but also in a worker context (self will then
  resolve to WorkerGlobalScope.self).


问:
path.plot in R synth package not plotting over whole time period
I have used the synth package to generate the dataprep.out and synth.out objects for plotting. However, when I use the path.plot function, the graph defaults to just the post-treatment period.

path.plot(
  synth.res = synth.out,
  dataprep.res = dataprep.out,
  Ylab = "black mortality rate (per 100000) among 80-84 yos",
  Xlab = "year",
  Legend = c("Iowa", "synthetic Iowa"),
  Legend.position = "bottomright"
  )```
</div>
</div>
</p>

<p>default plot: just post-treatment period</p>

<p>When I adjust the Z.plot parameter, only the pre-treatment period is plotted. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>path.plot(
  synth.res = synth.out,
  dataprep.res = dataprep.out,
  Ylab = "black mortality rate (per 100000) among 80-84 yos",
  Xlab = "year",
  Legend = c("Iowa", "synthetic Iowa"),
  Legend.position = "bottomright",
  Z.plot = TRUE
  )</code>```

plot specifying Z.plot parameter

I'd be extremely grateful if anyone could identify why this might be happening. Thank you!

答: I figured it out but thought I'd answer in case it is helpful for others. Be sure to specify the time.plot term in the dataprep() to be the full time period, not just the post-treatment period.</p>

Body:
I have used the synth package to generate the dataprep.out and synth.out objects for plotting. However, when I use the path.plot function, the graph defaults to just the post-treatment period.

path.plot(
  synth.res = synth.out,
  dataprep.res = dataprep.out,
  Ylab = "black mortality rate (per 100000) among 80-84 yos",
  Xlab = "year",
  Legend = c("Iowa", "synthetic Iowa"),
  Legend.position = "bottomright"
  )

default plot: just post-treatment period

When I adjust the Z.plot parameter, only the pre-treatment period is plotted.

path.plot(
  synth.res = synth.out,
  dataprep.res = dataprep.out,
  Ylab = "black mortality rate (per 100000) among 80-84 yos",
  Xlab = "year",
  Legend = c("Iowa", "synthetic Iowa"),
  Legend.position = "bottomright",
  Z.plot = TRUE
  )

plot specifying Z.plot parameter

I'd be extremely grateful if anyone could identify why this might be happening. Thank you!


问:
SQL Insert values INTO specific column where ID equals to
I would like to perform an INSERT data into a table with specific table.

The example as follows:

Table A
col1(PK), col2, col3
these three col already have value on it, lets say:

```<code>col1 col2 col3
 q    w     e
 z    x     c
</code>```

currently I am adding a new column 4 to it

```<code>ALTER TABLE A
ADD col4 int;
</code>```

Now I want to add value to Table A col4, how do I perform such action? for example I am adding 1 to row q and 2 to row z

UPDATE

As I try below for updating one row at a time, the query will be as follows:

```<code>UPDATE Table A set col4 = '1' where col1 = 'q'
</code>```

the above query shall update the table and result looks like follows:

```<code>col1 col2 col3 col4
 q    w     e    1
 z    x     c
</code>```

Or you guys can refer the answer from GordonLinoff, link here.

答:
You would use update:

```<code>update a
    set col4 = (case when col1 = 'q' then 1 else 2 end)
    where col1 in ('q', 'z');
</code>```

Body:
I would like to perform an INSERT data into a table with specific table.

The example as follows:

Table A
col1(PK), col2, col3
these three col already have value on it, lets say:

col1 col2 col3
 q    w     e
 z    x     c

currently I am adding a new column 4 to it

ALTER TABLE A
ADD col4 int;

Now I want to add value to Table A col4, how do I perform such action? for example I am adding 1 to row q and 2 to row z

UPDATE

As I try below for updating one row at a time, the query will be as follows:

UPDATE Table A set col4 = '1' where col1 = 'q'

the above query shall update the table and result looks like follows:

col1 col2 col3 col4
 q    w     e    1
 z    x     c

Or you guys can refer the answer from GordonLinoff, link here.

Body:
You would use update:

update a
    set col4 = (case when col1 = 'q' then 1 else 2 end)
    where col1 in ('q', 'z');


问:
How do I release only changes project from multiple project in one .sln?
I have 7 projects in one .sln. I am using azure devops. There is 4 api and 3 web. I have created two different pipeline for api and web. When commit then both pipeline is triggered.

What I want....

I want only changes project will trigger, build and release. If project 1 is changes then only build and release project 1. Others no.

How do I manage this?

Currently for one change all projects are building and releasing.

答:
Update your includes path in the pipeline.</p>

```<code>  paths:
    include:
    - /Project1FolderName/*
    - /Project2FolderName/*
</code>```

Body:
Update your includes path in the pipeline.

  paths:
    include:
    - /Project1FolderName/*
    - /Project2FolderName/*


问:
How do I create a column such that its values is count of the number of,1, in that row, which are appearing for the first time in their own column?
How do I do this operation using pandas?

Initial Df:

```<code>    A B C D
0   0 1 0 0
1   0 1 0 0
2   0 0 1 1
3   0 1 0 1
4   1 1 0 0
5   1 1 1 0
</code>```

Final Df:

```<code>    A B C D Param
0   0 1 0 0     1
1   0 1 0 0     0
2   0 0 1 1     2
3   0 1 0 1     0
4   1 1 0 0     1
5   1 1 1 0     0
</code>```

Basically Param is the number of the 1 in that row which is appearing for the first time in its own column.
Example:
index 0 : 1 in the column B is appearing for the first time hence Param1 = 1

index 1 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 2 : 1 in the column C and D is appearing for the first time  in their columns hence Paramm1 = 2

index 3 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 4 : 1 in the column A is appearing for the first time  in the column hence Paramm1 = 1

index 5 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

答:
I will do idxmax and value_counts

```<code>df['Param']=df.idxmax().value_counts().reindex(df.index,fill_value=0)
df
   A  B  C  D  Param
0  0  1  0  0      1
1  0  1  0  0      0
2  0  0  1  1      2
3  0  1  0  1      0
4  1  1  0  0      1
5  1  1  1  0      0
</code>```

Body:
How do I do this operation using pandas?

Initial Df:

    A B C D
0   0 1 0 0
1   0 1 0 0
2   0 0 1 1
3   0 1 0 1
4   1 1 0 0
5   1 1 1 0

Final Df:

    A B C D Param
0   0 1 0 0     1
1   0 1 0 0     0
2   0 0 1 1     2
3   0 1 0 1     0
4   1 1 0 0     1
5   1 1 1 0     0

Basically Param is the number of the 1 in that row which is appearing for the first time in its own column.
Example:
index 0 : 1 in the column B is appearing for the first time hence Param1 = 1

index 1 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 2 : 1 in the column C and D is appearing for the first time  in their columns hence Paramm1 = 2

index 3 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 4 : 1 in the column A is appearing for the first time  in the column hence Paramm1 = 1

index 5 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

Body:
I will do idxmax and value_counts

df['Param']=df.idxmax().value_counts().reindex(df.index,fill_value=0)
df
   A  B  C  D  Param
0  0  1  0  0      1
1  0  1  0  0      0
2  0  0  1  1      2
3  0  1  0  1      0
4  1  1  0  0      1
5  1  1  1  0      0


问:
Accessing multiple <select>-ed parameters with Perl CGI
I am using the Perl CGI module. If I have HTML like this

```<code><select multiple name="FILTER_SITE">
  <option>1</option>
  <option>2</option>
</select>
</code>```

and submit my form I can get something like this in the URL:
[..] FILTER_SITE=1&FILTER_SITE=2

Perl's my $FILTER_SITE   = $cgi->param('FILTER_SITE'); wil capture only the first instance.

How can I make use of both (in this case)? Hack it and parse the referrer myself and add them to an array is my first idea but it'd be a bit messy, then again I'm hardly versed in CGI.pm or Perl.

With Data::Dumper, interestingly

print "```".Dumper($cgi->param('FILTER_SITE')) . "```";

```<code>$VAR1 = '1';
$VAR2 = '2';
</code>```

答:
I know this is an old post, but looks like few things changed since this question was answered. I want to post the latest info on this, especially because the accepted answer is now considered a security vulnerability. CGI.pm documentation says

{Warning - calling param() in list context can lead to vulnerabilities if you do not sanitise user input as it is possible to inject other param keys and values into your code. This is why the multi_param() method exists, to make it clear that a list is being returned, note that param() can still be called in list context and will return a list for back compatibility.}

It is recommended to use $cgi->multi_param method instead.

ContentLicense: CC BY-SA 3.0

Body:
I am using the Perl CGI module. If I have HTML like this

<select multiple name="FILTER_SITE">
  <option>1</option>
  <option>2</option>
</select>

and submit my form I can get something like this in the URL:
[..] FILTER_SITE=1&FILTER_SITE=2

Perl's my $FILTER_SITE   = $cgi->param('FILTER_SITE'); wil capture only the first instance.

How can I make use of both (in this case)? Hack it and parse the referrer myself and add them to an array is my first idea but it'd be a bit messy, then again I'm hardly versed in CGI.pm or Perl.

With Data::Dumper, interestingly

print "
".Dumper($cgi->param('FILTER_SITE')) . "
";

$VAR1 = '1';
$VAR2 = '2';


问:
Calling inherited method in Java
I have the following java code,

```<code>class Animal {
    private String name="Animal";

    public String getName() {
        return name;
    }
}

class Cat extends Animal {
    private String name = "Cat";
}

public class Test {
    public static void main(String[] args) {
        Cat cat = new Cat();
        System.out.println(cat.getName());
    }
}
</code>```

after running that code, I got output Animal, but I think it should be Cat. And after overriding getName method in Cat like this, I got Cat.

```<code>@Override
public String getName() {
    return name;
}
</code>```

Is that because calling an inherited (not overrode) method in a subclass  instance just like  cat.getName()  equals to calling super.getName() (so I get Animal instead of Cat in the first case)? Or because the strange behavior of instance variable hiding (I'm not very sure)?

答:
The accepted answer covers some good answers, but I wanted to add a few things.

I would discourage adding an overrided getName method in the Cat Class if you are doing the exact same thing. This is to prevent code duplication in any other subclasses you may create.

You could create a constructor to initialize the name field instead and switch the name field to protected.

Eg.

```<code>class Animal {
    protected String name;

    public Animal() {
        this.name = "Animal";
    }

    public String getName() {
        return this.name;
    }
}

class Cat extends Animal {
    public Cat() {
        this.name = "Cat";
    }
}

</code>```

Alternatively, if you want to keep the name field private, you could create a setter method that's protected to allow only your subclasses to set the name.

Eg.

```<code>class Animal {
    private String name = "Animal";

    public String getName() {
        return this.name;
    }

    protected void setName(String name) {
        this.name = name;
    }
}

class Cat extends Animal {
    public Cat() {
        setName("Cat");
    }
}
</code>```

Title: Calling inherited method in Java

Body:
I have the following java code,

class Animal {
    private String name="Animal";

    public String getName() {
        return name;
    }
}

class Cat extends Animal {
    private String name = "Cat";
}

public class Test {
    public static void main(String[] args) {
        Cat cat = new Cat();
        System.out.println(cat.getName());
    }
}

after running that code, I got output Animal, but I think it should be Cat. And after overriding getName method in Cat like this, I got Cat.

@Override
public String getName() {
    return name;
}

Is that because calling an inherited (not overrode) method in a subclass  instance just like  cat.getName()  equals to calling super.getName() (so I get Animal instead of Cat in the first case)? Or because the strange behavior of instance variable hiding (I'm not very sure)?

Body:
The accepted answer covers some good answers, but I wanted to add a few things.

I would discourage adding an overrided getName method in the Cat Class if you are doing the exact same thing. This is to prevent code duplication in any other subclasses you may create.

You could create a constructor to initialize the name field instead and switch the name field to protected.

Eg.

class Animal {
    protected String name;

    public Animal() {
        this.name = "Animal";
    }

    public String getName() {
        return this.name;
    }
}

class Cat extends Animal {
    public Cat() {
        this.name = "Cat";
    }
}

Alternatively, if you want to keep the name field private, you could create a setter method that's protected to allow only your subclasses to set the name.

Eg.

class Animal {
    private String name = "Animal";

    public String getName() {
        return this.name;
    }

    protected void setName(String name) {
        this.name = name;
    }
}

class Cat extends Animal {
    public Cat() {
        setName("Cat");
    }
}


问:
Can I extend a typescript interface to put all keys under a new key?
I have an existing Typescript interface like this:

```<code>interface Person {
 name: string;
 age: number;
 pet: string;
}
</code>```

Another method (out of my control) requires the input to have each value be placed in an object {value: value} like this:

```<code>update({
   name: {value: "string"},
   age: {value: 0},
   pet: {value: "dog"}
})
</code>```

Is there some way to extend or make use of my existing Person interface to create a new type or interface to match that required format?

答:
Something like this would work:

```<code>interface Person {
 name: string;
 age: number;
 pet: string;
}

type AwkwardPerson = {
    [K in keyof Person]: { value: Person[K] }
}

let newTyped: AwkwardPerson = {
   name: {value: "string"},
   age: {value: 0},
   pet: {value: "dog"}
}
</code>```

We iterate over the keys of person and give the desired shape with the right type.

If you have a lot of those interfaces going on that you need to convert, you can make a generic converter (instead of repeating yourself) like this:

```<code>type MakeAwkward<T> = {
    [key in keyof T]: { value: T[key] }
}

type GenericAwkwardPerson = MakeAwkward<Person>

let genericTyped: GenericAwkwardPerson = {
   name: {value: "string"},
   age: {value: 0},
   pet: {value: "dog"}
}
</code>```

Any interface you give to MakeAwkward<> inside the angled brackets will be converted to a compatible type.

Body:
I have an existing Typescript interface like this:

interface Person {
 name: string;
 age: number;
 pet: string;
}

Another method (out of my control) requires the input to have each value be placed in an object {value: value} like this:

update({
   name: {value: "string"},
   age: {value: 0},
   pet: {value: "dog"}
})

Is there some way to extend or make use of my existing Person interface to create a new type or interface to match that required format?

Body:
Something like this would work:

interface Person {
 name: string;
 age: number;
 pet: string;
}

type AwkwardPerson = {
    [K in keyof Person]: { value: Person[K] }
}

let newTyped: AwkwardPerson = {
   name: {value: "string"},
   age: {value: 0},
   pet: {value: "dog"}
}

We iterate over the keys of person and give the desired shape with the right type.

If you have a lot of those interfaces going on that you need to convert, you can make a generic converter (instead of repeating yourself) like this:

type MakeAwkward<T> = {
    [key in keyof T]: { value: T[key] }
}

type GenericAwkwardPerson = MakeAwkward<Person>

let genericTyped: GenericAwkwardPerson = {
   name: {value: "string"},
   age: {value: 0},
   pet: {value: "dog"}
}

Any interface you give to MakeAwkward<> inside the angled brackets will be converted to a compatible type.


问:
Transact-SQL: How do I tokenize a string?
I want to be able to tokenize an input string from a text box to do my query.
Example: user enters "abc xyz 123" in the text box.
I want to do this:

```<code>SELECT * FROM database WHERE Name contains "abc" AND "xyz" AND "123"
-- as opposed to containing "abc xyz 123"
-- please ignore my sql syntax, I am an absolute beginner
</code>```

Thanks.

答:
You can use dynamic SQL to achieve this:

```<code>declare @InputText varchar(8000)
set @InputText = 'abc xyz 123'

declare @CommorText varchar(8000)
set @CommorText = 'SELECT * FROM table WHERE Name like ''%' + replace(@InputText, ' ', '%'' or Name like ''%') + '%''';

-- @CommorText would look like this at this point
-- SELECT * FROM table WHERE Name like '%abc%' or Name like '%xyz%' or Name like '%123%'

execute(@CommorText)
</code>```

[Edit] In response to Avitus's comment:

Not the most perfect solution. However, If somebody enters 'drop table Test1', query will be SELECT * FROM Test1 WHERE Name like '%drop%' or Name like '%table%' or Name like '%Test1%'

Body:
I want to be able to tokenize an input string from a text box to do my query.
Example: user enters "abc xyz 123" in the text box.
I want to do this:

SELECT * FROM database WHERE Name contains "abc" AND "xyz" AND "123"
-- as opposed to containing "abc xyz 123"
-- please ignore my sql syntax, I am an absolute beginner

Thanks.

Body:
You can use dynamic SQL to achieve this:

declare @InputText varchar(8000)
set @InputText = 'abc xyz 123'

declare @CommorText varchar(8000)
set @CommorText = 'SELECT * FROM table WHERE Name like ''%' + replace(@InputText, ' ', '%'' or Name like ''%') + '%''';

-- @CommorText would look like this at this point
-- SELECT * FROM table WHERE Name like '%abc%' or Name like '%xyz%' or Name like '%123%'

execute(@CommorText)

[Edit] In response to Avitus's comment:

Not the most perfect solution. However, If somebody enters 'drop table Test1', query will be SELECT * FROM Test1 WHERE Name like '%drop%' or Name like '%table%' or Name like '%Test1%'


问:
Elasticsearch: some fields appear immediately and some with delay
I have a very strange situation

After sending documents to the ES index and creating documents, some fields in a document appear immediately, and some with a delay. That is, some fields have null,[]and0 (depending on the field type) instead of the values sent to the index.

After 5-10 minutes, these fields are filled with the actual values.

This situation arises when I bulk a lot of documents (up to 500). When I sent the documents one by one, this did not occur.

The search for this problem in Google did not give anything.

What can be changed in the index or bulk settings so that documents are not displayed in the search with empty values?

Elasticsearch version: 7.6.0

Update:

For more context, I've added print screens:

1) This is how the document looks in the Kibana immediately after adding:

2) And so the document looks after 5-10 minutes:

In the index settings refresh_interval set to 1s

Adding refresh = "wait_for" to the bulk request didn't change anything

答:
Please check the refresh parameter of your index, default is 1 second but can be tweaked. Also please check when you are sending one by one you are not doing an explicit refresh or using wait_for param in the request.

According to official doc wait_for param

Wait for the changes made by the request to be made visible by a
  refresh before replying. This doesn’t force an immediate refresh,
  rather, it waits for a refresh to happen. Elasticsearch automatically
  refreshes shards that have changed every

Solution: For your bulk request, use wait_for param, using this will not return the result until refresh happens and once you get the response, values which you are sending will be available for search.

Further read https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-refresh.html#_choosing_which_setting_to_use


问:
How to set maintenance mode for Laravel 5.8 behind load balancer in EC2 instance and access from my office?
I want to use Laravel maintenance mode on EC2 instance behind the load balancer because I do not want to touch AWS console for returning maintenance content.

Moreover, I want to access my app via web browser from my office while maintenance mode.

I did following and it turns into maintenance mode.

But, I can not see my app from my office although the IP at my office in the allow list.

php artisan down --allow=127.0.0.1 --allow=myip/34

Do you have any suggestions for this?

Here is my environment information-
PHP: 5.7
Laravel: 5.8

Also, I have following source code in App/Http/Middleware/TrustProxies.php

    class TrustProxies extends Middleware
    {
        protected $proxies = '*';
        protected $headers = [
            Request::HEADER_FORWARDED => 'FORWARDED',
            Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
            Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
            Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
            Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
        ];
    }

Regards,

答:
Instead of modifying your Middleware code there, it is better to put this into your configuration file. Add config/trustedproxy.php file with the following code in it:

<?php

return [
    'proxies' => env('TRUSTED_PROXIES'),
];

```

<p>Then add the following line to your <code>.env</code> file:</p>

```TRUSTED_PROXIES="*"
```

Also a side note: it is generally not really a good idea to trust all proxies, because people can just fake the X-Forwarded-For headers. Instead, you can put the IPs for your private IP subnet, whatever it is in your EC2 VPC. It would be one of the RFC 1918 private IP networks, by default it would be one of the 172.x.x.x subnets.  You can then substitute the "*" in the code above with something like "172.16.0.0/12" or whatever your private subnet is — you can look it up in your VPC settings.

Body:
Instead of modifying your Middleware code there, it is better to put this into your configuration file. Add config/trustedproxy.php file with the following code in it:

<?php

return [
    'proxies' => env('TRUSTED_PROXIES'),
];

Then add the following line to your .env file:

TRUSTED_PROXIES="*"

Also a side note: it is generally not really a good idea to trust all proxies, because people can just fake the X-Forwarded-For headers. Instead, you can put the IPs for your private IP subnet, whatever it is in your EC2 VPC. It would be one of the RFC 1918 private IP networks, by default it would be one of the 172.x.x.x subnets.  You can then substitute the "*" in the code above with something like "172.16.0.0/12" or whatever your private subnet is — you can look it up in your VPC settings.


问:
Calculating totals for pre period excluding counts prior to lookback and after reference year
Assuming a student eats only 1 candy per day. I need to find out how many candies a student consumed before the start of school(as shown in the column "Total_candies_consumed_one_year_before_start_of_school" in red font). My data is as shown in the table with black font. I calculated the highlighted column. I have provided rationale on how to calculate the "Total_candies_consumed_one_year_before_start_of_school".

I am stuck at how to exclude counts that happened before "1_year_lookback_period" and after "school start date".

Any help is greatly appreciated.

答:
I think that you  are looking for some kind of linear regression.

The idea is to assess how many candies were consumed during the year that precedes school_start_date by computing the number of days of overlap between this period and the date range defined by the purchase_date  and consumed_date of the candies. Based on the overlap ratio, you can project the consumption during the lookback period.

This should do what you want:

```<code>select
    t.*,
    number_of_candies *
        greatest(
            least(school_start_date, consumed_date)
            - greatest(purchase_date, add_months(school_start_date, -12)),
            0
        ) / (consumed_date - purchase_date) candies_consumed_during_loopback
from mytable t
</code>```

Demo on DB Fiddle:

```
ID | PURCHASE_DATE | NUMBER_OF_CANDIES | CONSUMED_DATE | SCHOOL_START_DATE | RES
-: | :------------ | ----------------: | :------------ | :---------------- | --:
 1 | 30-DEC-09     |                15 | 14-JAN-10     | 01-JAN-11         |  13
 1 | 30-MAY-10     |                30 | 29-JUN-10     | 01-JAN-11         |  30
 2 | 01-NOV-10     |                90 | 30-JAN-11     | 01-JAN-11         |  61
 2 | 09-AUG-12     |                15 | 24-AUG-12     | 01-JAN-11         |   0
 3 | 01-DEC-14     |               900 | 19-MAY-17     | 01-JAN-16         | 365
```

Body:
I think that you  are looking for some kind of linear regression.

The idea is to assess how many candies were consumed during the year that precedes school_start_date by computing the number of days of overlap between this period and the date range defined by the purchase_date  and consumed_date of the candies. Based on the overlap ratio, you can project the consumption during the lookback period.

This should do what you want:

select
    t.*,
    number_of_candies *
        greatest(
            least(school_start_date, consumed_date)
            - greatest(purchase_date, add_months(school_start_date, -12)),
            0
        ) / (consumed_date - purchase_date) candies_consumed_during_loopback
from mytable t

Demo on DB Fiddle:

ID | PURCHASE_DATE | NUMBER_OF_CANDIES | CONSUMED_DATE | SCHOOL_START_DATE | RES
-: | :------------ | ----------------: | :------------ | :---------------- | --:
 1 | 30-DEC-09     |                15 | 14-JAN-10     | 01-JAN-11         |  13
 1 | 30-MAY-10     |                30 | 29-JUN-10     | 01-JAN-11         |  30
 2 | 01-NOV-10     |                90 | 30-JAN-11     | 01-JAN-11         |  61
 2 | 09-AUG-12     |                15 | 24-AUG-12     | 01-JAN-11         |   0
 3 | 01-DEC-14     |               900 | 19-MAY-17     | 01-JAN-16         | 365


问:
FIrestore document onUpdate: trigger only for specific fields
in my cloud function I have next unction:

export const collectionOnUpdate = functions.firestore.document('cards/{id}').onUpdate(async (change, context) => {
  await updateDocumentInAlgolia(change);
});
```

And this function is triggered each time, when any fields of document was edited. But I want to run it only when one of specific fields was changed (in this case, for example: title, category) and not when any of other.

How can I do this?

答:
firebase firstore cloud functions are works based on the basis of changes to the  documents,not based on the fields of a document.

So if you want to check whether some fields have any change,you have to check manually

```<code>exports.updateUser = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {

  // ...the new value after this update
  const newValue = change.after.data()||{};

  // ...the previous value before this update
  const previousValue = change.before.data()||{};

  // access a particular field as you would any JS property

  //The value after an update operation
  const new_name = newValue.name;

  // the value before an update operation
  const old_name = previousValue.name;

  if(new_name!==old_name){
   //There must be some changes
   // perform desired operations ...
  }else{
  //No changes to the field called `name`
  // perform desired operations ...
  }

});
</code>```

Body:
in my cloud function I have next unction:

export const collectionOnUpdate = functions.firestore.document('cards/{id}').onUpdate(async (change, context) => {
  await updateDocumentInAlgolia(change);
});

And this function is triggered each time, when any fields of document was edited. But I want to run it only when one of specific fields was changed (in this case, for example: title, category) and not when any of other.

How can I do this?

Body:
firebase firstore cloud functions are works based on the basis of changes to the  documents,not based on the fields of a document.

So if you want to check whether some fields have any change,you have to check manually

exports.updateUser = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {

  // ...the new value after this update
  const newValue = change.after.data()||{};

  // ...the previous value before this update
  const previousValue = change.before.data()||{};

  // access a particular field as you would any JS property

  //The value after an update operation
  const new_name = newValue.name;

  // the value before an update operation
  const old_name = previousValue.name;

  if(new_name!==old_name){
   //There must be some changes
   // perform desired operations ...
  }else{
  //No changes to the field called `name`
  // perform desired operations ...
  }

});


问:
how to combine two selectors?
in my example http://jsfiddle.net/radek/HnXC4/2/ I defined jQuery handler for click

on button

that have a class run

via $(":button, .run").click(function(){

how come the this button should NOT work button's clicked is fired too? It doesn't have class "run".

答:
Try:

```<code>$(":button.run").click(function(){
</code>```

$(":button, .run") will match any elements that are either buttons or have a CSS class of run.

Title: how to combine two selectors?

Body:
Try:

$(":button.run").click(function(){

$(":button, .run") will match any elements that are either buttons or have a CSS class of run.


问:
Need to pass this SQL code to spark syntax
Having a hard time passing this code to just pyspark syntax, without using spark.sql

TableD = spark.sql("SELECT Region, SUM(moneyspent)/count(distinct id) as avgspent FROM finaldatatable as Data GROUP BY Region ORDER BY avgspent desc ")
TableD.show()

Please help, really stuck here. Thanks.

答:
Check below code.</p>

```<code>>>> from pyspark.sql import functions as F

>>> df.printSchema()
root
 |-- id: integer (nullable = true)
 |-- region: string (nullable = true)
 |-- moneyspent: double (nullable = true)

>>> df
.groupBy(F.col("region"))
.agg((F.sum(F.col("moneyspent"))/F.countDistinct(F.col("id"))).alias("avgspent"))
.orderBy(F.col("avgspent"),ascending=False)
.show()

</code>```

Body:
Check below code.

>>> from pyspark.sql import functions as F

>>> df.printSchema()
root
 |-- id: integer (nullable = true)
 |-- region: string (nullable = true)
 |-- moneyspent: double (nullable = true)

>>> df
.groupBy(F.col("region"))
.agg((F.sum(F.col("moneyspent"))/F.countDistinct(F.col("id"))).alias("avgspent"))
.orderBy(F.col("avgspent"),ascending=False)
.show()


问:
How to create a calculated new column in pandas
I'm trying to do something in Python that I can do easily in Excel, but it's simply not working out. Essentially, I want to take a dataframe, look at 2 columns in the dataframe and create a third column based on conditionals.
In short, I want to look at foo, determine using a conditional what category it would fall into, and then add that result to thud for a new column with a value of conditional foo + thud.

My simplistic approach was to iterate over the dataframe, use a dictionary to store my key:values for the conditional test of foo and then create a new column with the result of the foo conditional plus thud.

My challenge is every solution I've tried, I end up with this error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

My algorithm is sound I feel but the coding execution using Pandas isn't working the way I thought it would.

How can I avoid the Value errors? Or am I completely offbase in my approach?
Thank you for your time!

答:
without your code its impossible to tell ... but based on the error you described i would expect this to solve your issue

you cannot do if dataframe

you can do if dataframe is None: if you want to test if its none

or if len(dataframe) == 0: if you want to test ifits empty

however more to the point, usually you use pandas to avoid looping

I am going to go out on a limb and assume you want something like the following

```<code>coin_values = {'Gold':100,'Silver':10,'Bronze':1}

my_coin_values = df['Thud'].map(coin_values)

total_moneys = my_coin_values * df['foo']

print(df['qux'][total_moneys > 500])
</code>```

Body:
without your code its impossible to tell ... but based on the error you described i would expect this to solve your issue

you cannot do if dataframe

you can do if dataframe is None: if you want to test if its none

or if len(dataframe) == 0: if you want to test ifits empty

however more to the point, usually you use pandas to avoid looping

I am going to go out on a limb and assume you want something like the following

coin_values = {'Gold':100,'Silver':10,'Bronze':1}

my_coin_values = df['Thud'].map(coin_values)

total_moneys = my_coin_values * df['foo']

print(df['qux'][total_moneys > 500])


问:
TAR override the contents of the directory
My understanding of tar command that it will override the content of the file if file exist. Otherwise it would keep as existing.

```<code>[root@something~]# ls -al /etc/init.d/
total XX
drwxr-xr-x.  2 root root    83 Jun 14  2018 .
drwxr-xr-x. 10 root root   127 Jun  6  2017 ..
-rwxr-xr-x.  1 root root  7293 Jan  2  2018 network
-rw-r--r--.  1 root root  1160 Feb 20  2018 README
[root@something~]# tar tvf /tmp/env_pkg_1.tar
drwxr-xr-x staff    0 2020-05-29 19:42 etc/
drwxr-xr-x user/staff    0 2020-05-29 18:04 etc/init.d/
-rw-r--r-- user/staff 3383 2020-05-29 18:04 etc/init.d/sshd
[root@something~]# cd /
[root@something /]# tar xf /tmp/env_pkg_1.tar
[root@something/]# ls -al /etc/init.d/
total 16
drwxr-xr-x   2 XXXXXX XXXXXX 18 May 29 18:04 .
drwxr-xr-x. 85 XXXXXX XXXXXX 8192 May 29 19:42 ..
-rw-r--r--   1 XXXXXX XXXXXX 3383 May 29 18:04 sshd
</code>```

I am not understand why tar is replacing the entire contents of /etc/init.d

Any inputs would be helpful ?

答:
I belive that /etc/init.d is a link to /etc/rc.d/init.d.

When you untarred that file, it overwrote the link with a directory.  All of your files are still in /etc/rc.d/init.d.

To fix your situation, remove /etc/init.d, relink it, and add a h to the tar command:

```<code>rm -rf /etc/init.d
cd /etc
ln -s ./rc.d/init.d
cd /
tar xhf /tmp/env_pkg_1.tar
</code>```

Body:
My understanding of tar command that it will override the content of the file if file exist. Otherwise it would keep as existing.

[root@something~]# ls -al /etc/init.d/
total XX
drwxr-xr-x.  2 root root    83 Jun 14  2018 .
drwxr-xr-x. 10 root root   127 Jun  6  2017 ..
-rwxr-xr-x.  1 root root  7293 Jan  2  2018 network
-rw-r--r--.  1 root root  1160 Feb 20  2018 README
[root@something~]# tar tvf /tmp/env_pkg_1.tar
drwxr-xr-x staff    0 2020-05-29 19:42 etc/
drwxr-xr-x user/staff    0 2020-05-29 18:04 etc/init.d/
-rw-r--r-- user/staff 3383 2020-05-29 18:04 etc/init.d/sshd
[root@something~]# cd /
[root@something /]# tar xf /tmp/env_pkg_1.tar
[root@something/]# ls -al /etc/init.d/
total 16
drwxr-xr-x   2 XXXXXX XXXXXX 18 May 29 18:04 .
drwxr-xr-x. 85 XXXXXX XXXXXX 8192 May 29 19:42 ..
-rw-r--r--   1 XXXXXX XXXXXX 3383 May 29 18:04 sshd

I am not understand why tar is replacing the entire contents of /etc/init.d

Any inputs would be helpful ?

Body:
I belive that /etc/init.d is a link to /etc/rc.d/init.d.

When you untarred that file, it overwrote the link with a directory.  All of your files are still in /etc/rc.d/init.d.

To fix your situation, remove /etc/init.d, relink it, and add a h to the tar command:

rm -rf /etc/init.d
cd /etc
ln -s ./rc.d/init.d
cd /
tar xhf /tmp/env_pkg_1.tar


问:
SwiftUI: changing view using "if else"
I’m trying to change a view based on a selection made with a button. I’m using Combine and SwiftUI.

I create a view router class with a @Published var:

import Foundation
import SwiftUI
import Combine

class ViewRouter: ObservableObject {

    @Published var currentView = "folder"

}
```

<p>I have my button struct:</p>

<pre class="lang-swift prettyprint-override"><code>import SwiftUI
import Combine

struct MultiButton: View {
    @ObservedObject var viewRouter = ViewRouter()
    @State var showButton = false

    var body: some View {
        GeometryReader { geometry in
            ZStack{

                // open multi button
                Button(action: {

                    withAnimation {
                        self.showButton.toggle()
                    }
                }) {
                    Image(systemName: "gear")
                        .resizable()
                        .frame(width: 40, height: 40, alignment: .center)
                }
                if self.showButton {

                    Multi()
                    .offset(CGSize(width: -30, height: -100))
                }
            }

        }
    }
}

struct MultiButton_Previews: PreviewProvider {
    static var previews: some View {
        MultiButton()
    }
}

struct Multi: View {

 @ObservedObject var viewRouter = ViewRouter()

    var body: some View {
        HStack(spacing: 10) {
            ZStack {

                Button(action: {
                    self.viewRouter.currentView = "folder"
                     debugPrint("\(self.viewRouter.currentView)")
                }) {
                    ZStack{

                    Circle()
                        .foregroundColor(Color.blue)
                        .frame(width: 70, height: 70)
                    Image(systemName: "folder")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(20)
                        .frame(width: 70, height: 70)
                        .foregroundColor(.white)
                    }.shadow(radius: 10)
                }
            }

            Button(action: {
                self.viewRouter.currentView = "setting"
                debugPrint("\(self.viewRouter.currentView)")
            }, label: {
                ZStack {
                    Circle()
                        .foregroundColor(Color.blue)
                        .frame(width: 70, height: 70)
                    Image(systemName: "gear")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(20)
                        .frame(width: 70, height: 70)
                        .foregroundColor(.white)
                }.shadow(radius: 10)
            })
        }
            .transition(.scale)
    }
}
</code>```

And the contentView:

import SwiftUI
import Combine

struct ContentView: View {
    @ObservedObject var viewRouter = ViewRouter()
    var body: some View {
        VStack{

            MultiButton()

            if viewRouter.currentView == "folder" {
                Text("folder")
            } else if viewRouter.currentView == "setting"{
                Text("setting")
            }
        }
    }
}
```

Why is my text is not changing from the folder to setting the base when the button is pressEd?

The var is @Published; it should publish the change and update the main view.

Did I miss something?

答:
You have multiple instances of ViewRouter with each view having its own instance. If you change that instance, the other instances are not going to change.

To solve this, you either have to pass one instance around manually:

```<code>struct MultiButton {
    @ObservedObject var viewRouter: ViewRouter
    ...
}

struct ContentView {
    @ObservedObject var viewRouter = ViewRouter()
    var body: some View {
        VStack {
            MultiButton(viewRouter: self.viewRouter)
            ...
        }
    }
}
</code>```

Or you can declare it as an environment object:

```<code>struct MultiButton {
    @EnvironmentObject var viewRouter: ViewRouter
    ...
}
</code>```

And then inject it for example when you create your view hierarchy in your scene delegate:

```<code>let contentView = ContentView()
    .environmentObject(ViewRouter())
</code>```

Note that when injecting the environment object in the scene delegate, it will not be available in every preview of a view that uses the ViewRouter, unless you manually inject it there as well:

```<code>static var previews: some View {
    ContentView()
    .environmentObject(ViewRouter())
}
</code>```

Title: SwiftUI: changing view using "if else"

Body:
I’m trying to change a view based on a selection made with a button. I’m using Combine and SwiftUI.

I create a view router class with a @Published var:

import Foundation
import SwiftUI
import Combine

class ViewRouter: ObservableObject {

    @Published var currentView = "folder"

}

I have my button struct:

import SwiftUI
import Combine

struct MultiButton: View {
    @ObservedObject var viewRouter = ViewRouter()
    @State var showButton = false

    var body: some View {
        GeometryReader { geometry in
            ZStack{

                // open multi button
                Button(action: {

                    withAnimation {
                        self.showButton.toggle()
                    }
                }) {
                    Image(systemName: "gear")
                        .resizable()
                        .frame(width: 40, height: 40, alignment: .center)
                }
                if self.showButton {

                    Multi()
                    .offset(CGSize(width: -30, height: -100))
                }
            }

        }
    }
}

struct MultiButton_Previews: PreviewProvider {
    static var previews: some View {
        MultiButton()
    }
}

struct Multi: View {

 @ObservedObject var viewRouter = ViewRouter()

    var body: some View {
        HStack(spacing: 10) {
            ZStack {

                Button(action: {
                    self.viewRouter.currentView = "folder"
                     debugPrint("\(self.viewRouter.currentView)")
                }) {
                    ZStack{

                    Circle()
                        .foregroundColor(Color.blue)
                        .frame(width: 70, height: 70)
                    Image(systemName: "folder")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(20)
                        .frame(width: 70, height: 70)
                        .foregroundColor(.white)
                    }.shadow(radius: 10)
                }
            }

            Button(action: {
                self.viewRouter.currentView = "setting"
                debugPrint("\(self.viewRouter.currentView)")
            }, label: {
                ZStack {
                    Circle()
                        .foregroundColor(Color.blue)
                        .frame(width: 70, height: 70)
                    Image(systemName: "gear")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(20)
                        .frame(width: 70, height: 70)
                        .foregroundColor(.white)
                }.shadow(radius: 10)
            })
        }
            .transition(.scale)
    }
}

And the contentView:

import SwiftUI
import Combine

struct ContentView: View {
    @ObservedObject var viewRouter = ViewRouter()
    var body: some View {
        VStack{

            MultiButton()

            if viewRouter.currentView == "folder" {
                Text("folder")
            } else if viewRouter.currentView == "setting"{
                Text("setting")
            }
        }
    }
}

Why is my text is not changing from the folder to setting the base when the button is pressEd?

The var is @Published; it should publish the change and update the main view.

Did I miss something?

Body:
You have multiple instances of ViewRouter with each view having its own instance. If you change that instance, the other instances are not going to change.

To solve this, you either have to pass one instance around manually:

struct MultiButton {
    @ObservedObject var viewRouter: ViewRouter
    ...
}

struct ContentView {
    @ObservedObject var viewRouter = ViewRouter()
    var body: some View {
        VStack {
            MultiButton(viewRouter: self.viewRouter)
            ...
        }
    }
}

Or you can declare it as an environment object:

struct MultiButton {
    @EnvironmentObject var viewRouter: ViewRouter
    ...
}

And then inject it for example when you create your view hierarchy in your scene delegate:

let contentView = ContentView()
    .environmentObject(ViewRouter())

Note that when injecting the environment object in the scene delegate, it will not be available in every preview of a view that uses the ViewRouter, unless you manually inject it there as well:

static var previews: some View {
    ContentView()
    .environmentObject(ViewRouter())
}


问:
Unable to Connect to Azure SQL DB from Azure App Service
We have an ASP Classic web application running successfully in an Azure App Service that currently uses SQL Server Authentication to access the Azure SQL Database. We need to change the authentication to Active Directory user. We managed to make this application work from a developer’s workstation accessing the Azure SQL Database, see what worked and did not, below.

* Does NOT work on desktop and Does NOT works in Azure
Conportail.Open "Provider=SQLOLEDB; Server=tcp:.database.windows.net,1433; Initial Catalog=; Persist Security Info=False; User ID=@leg*.com; Password=; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False;  Connection Timeout=30; Authentication=ActiveDirectoryPassword;"

* Does NOT work on desktop and Does NOT works in Azure
Conportail.Open "Provider=SQLOLEDB.1; Server=tcp:.database.windows.net,1433; Initial Catalog=; Persist Security Info=False; User ID=@leg*.com; Password=; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False;    Connection Timeout=30; Authentication=ActiveDirectoryPassword;"

* Works on desktop and Does NOT works in Azure
Conportail.Open "Provider=MSOLEDBSQL; Server=tcp:.database.windows.net,1433; Initial Catalog=; Persist Security Info=False; User ID=@leg*.com; Password=; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False;    Connection Timeout=30; Authentication=ActiveDirectoryPassword;"

What are we missing to make this work in Azure App Service?

答:
UPDATE

You can follow the offical document to set in portal. I have try it and sucessed.

Create SQL managed instances (maybe cost long time)

Configure Active Directory admin

Configure your db

When u have finished it, you can find connection string like pic. You just copy and paste it in your code. It works for me.

Connection strings like below

```<code>Server=tcp:panshubeidb.database.windows.net,1433;Initial Catalog=dbname;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication='Active Directory Password';
</code>```

PRIVIOUS

Your SQL Connectionstrings should be like Server=tcp:testdb.database.windows.net,1433;Initial Catalog=test;Persist Security Info=False;User ID=sasasa;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30; .

You can find it in portal like pic.

You also can configure your connectionstring's name in web.config.

```<code><connectionStrings>
    <add name="DefaultConnection" connectionString="You local db connnection strings or others" />
    <add name="DefaultConnection11" connectionString="Data Source =**;Initial Catalog = {your db in server not azure};User Id = {userid};Password ={password};" />
</connectionStrings>
</code>```

You can configure your Connectionstrings like the code I given. And when you want to depoly your apps. You can switch to your production database, and don't need change anything in your code. Fore more details, you can see this article .

Its priority is higher than the configuration in web.config, and it will cover the address in the code, so after setting it here, you do not need to modify your web.config file when deploying.

Body:
UPDATE

You can follow the offical document to set in portal. I have try it and sucessed.

Create SQL managed instances (maybe cost long time)

Configure Active Directory admin

Configure your db

When u have finished it, you can find connection string like pic. You just copy and paste it in your code. It works for me.

Connection strings like below

Server=tcp:panshubeidb.database.windows.net,1433;Initial Catalog=dbname;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication='Active Directory Password';

PRIVIOUS

Your SQL Connectionstrings should be like Server=tcp:testdb.database.windows.net,1433;Initial Catalog=test;Persist Security Info=False;User ID=sasasa;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30; .

You can find it in portal like pic.

You also can configure your connectionstring's name in web.config.

<connectionStrings>
    <add name="DefaultConnection" connectionString="You local db connnection strings or others" />
    <add name="DefaultConnection11" connectionString="Data Source =**;Initial Catalog = {your db in server not azure};User Id = {userid};Password ={password};" />
</connectionStrings>

You can configure your Connectionstrings like the code I given. And when you want to depoly your apps. You can switch to your production database, and don't need change anything in your code. Fore more details, you can see this article .

Its priority is higher than the configuration in web.config, and it will cover the address in the code, so after setting it here, you do not need to modify your web.config file when deploying.


问:
FAB on click start new activity based on fragment currently shown
I am trying to figure a good way to start an activity from a click on the floating action button.
My FAB is located in mainactivity.xml. My MainActivity consists of bottom navigation with fragments. I need to implement a different on click action determined by a fragment that is shown.

```<code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_add);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    fabClicked();
    }
});
</code>```

fabClicked Method

```<code>public void fabClicked() {
    Object id = getSupportFragmentManager().findFragmentById(R.id.container);

    if ((getSupportFragmentManager().findFragmentById(R.id.fragment_1)).equals(id)) {
        Intent intent1 = new Intent(MainActivity.this, Add1.class);
        startActivity(intent1);
    }

    else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_2)).equals(id)) {
        Intent intent2 = new Intent(MainActivity.this, Add2.class);
        startActivity(intent2);
    }

    else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_3)).equals(id)) {
        Intent intent3 = new Intent(MainActivity.this, Add3.class);
        startActivity(intent3);
    }
    else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_home)).equals(id)) {
        //plan to add to code to hide fab on homescreen
    }

}

</code>```

答:
One simple solution for this is :

Whenever the bottom navigation is used, just save the selected fragment id in a static variable and when the user presses the FAB, just open the activity based on the fragment stored in variable.

Body:
I am trying to figure a good way to start an activity from a click on the floating action button.
My FAB is located in mainactivity.xml. My MainActivity consists of bottom navigation with fragments. I need to implement a different on click action determined by a fragment that is shown.

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_add);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    fabClicked();
    }
});

fabClicked Method

public void fabClicked() {
    Object id = getSupportFragmentManager().findFragmentById(R.id.container);

    if ((getSupportFragmentManager().findFragmentById(R.id.fragment_1)).equals(id)) {
        Intent intent1 = new Intent(MainActivity.this, Add1.class);
        startActivity(intent1);
    }

    else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_2)).equals(id)) {
        Intent intent2 = new Intent(MainActivity.this, Add2.class);
        startActivity(intent2);
    }

    else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_3)).equals(id)) {
        Intent intent3 = new Intent(MainActivity.this, Add3.class);
        startActivity(intent3);
    }
    else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_home)).equals(id)) {
        //plan to add to code to hide fab on homescreen
    }

}


问:
Python CNN LSTM (Value Error strides should be of length 1, 1 or 3 but was 2)
I've been trying to train a convlstm model on mnist dataset to broaden my knowledge in model development. I cannot escape the error that I have included in the title. Any help or hint is appreciated!

I know the default for strides is (1,1) but am unsure how 2 is being set.

```<code>import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM, CuDNNLSTM, TimeDistributed, Reshape
from keras.utils import to_categorical
from keras.layers.convolutional import Conv2D, Conv3D
from keras.layers.pooling import MaxPooling2D, MaxPool3D
from keras.layers.core import Flatten

def prep_pixels(train, test):
    # convert from integers to floats
    train_norm = train.astype('float32')
    test_norm = test.astype('float32')
    # normalize to range 0-1
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return normalized images
    return train_norm, test_norm

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape((x_train.shape[0], 28, 28, 1))
x_test = x_test.reshape((x_test.shape[0], 28, 28, 1))

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

x_train, x_test = prep_pixels(x_train, x_test)

model = Sequential()

model.add(TimeDistributed(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))))
model.add(TimeDistributed((MaxPooling2D((2, 2)))))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(32, activation='relu', return_sequences=True))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))

opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
model.fit(x_train, y_train, epochs=1, validation_data=(x_test, y_test))
</code>```

ERROR

model.fit(x_train, y_train, epochs=1, validation_data=(x_test, y_test))

strides = _get_sequence(strides, n, channel_index, "strides")

ValueError: strides should be of length 1, 1 or 3 but was 2

答:
It seems like you haven't created a windowed dataset for your ConvLSTM. So you might want to do this before calling model.fit

d_train = tf.keras.preprocessing.sequence.TimeseriesGenerator(x_train, y_train, length=5, batch_size=64) # window size = 5
d_test = tf.keras.preprocessing.sequence.TimeseriesGenerator(x_test, y_test, length=5)
model.fit(d_train, epochs=1, validation_data=d_test)
```

<p>To be consistent with your loss function, you will need to disable return sequences (or add another layer that does not return sequences).</p>

<pre class="lang-py prettyprint-override"><code>model.add(tf.keras.layers.LSTM(32, activation='relu', return_sequences=False))
</code>```

Body:
I've been trying to train a convlstm model on mnist dataset to broaden my knowledge in model development. I cannot escape the error that I have included in the title. Any help or hint is appreciated!

I know the default for strides is (1,1) but am unsure how 2 is being set.

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM, CuDNNLSTM, TimeDistributed, Reshape
from keras.utils import to_categorical
from keras.layers.convolutional import Conv2D, Conv3D
from keras.layers.pooling import MaxPooling2D, MaxPool3D
from keras.layers.core import Flatten

def prep_pixels(train, test):
    # convert from integers to floats
    train_norm = train.astype('float32')
    test_norm = test.astype('float32')
    # normalize to range 0-1
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return normalized images
    return train_norm, test_norm

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape((x_train.shape[0], 28, 28, 1))
x_test = x_test.reshape((x_test.shape[0], 28, 28, 1))

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

x_train, x_test = prep_pixels(x_train, x_test)

model = Sequential()

model.add(TimeDistributed(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))))
model.add(TimeDistributed((MaxPooling2D((2, 2)))))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(32, activation='relu', return_sequences=True))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))

opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
model.fit(x_train, y_train, epochs=1, validation_data=(x_test, y_test))

ERROR

model.fit(x_train, y_train, epochs=1, validation_data=(x_test, y_test))

strides = _get_sequence(strides, n, channel_index, "strides")

ValueError: strides should be of length 1, 1 or 3 but was 2

Body:
It seems like you haven't created a windowed dataset for your ConvLSTM. So you might want to do this before calling model.fit

d_train = tf.keras.preprocessing.sequence.TimeseriesGenerator(x_train, y_train, length=5, batch_size=64) # window size = 5
d_test = tf.keras.preprocessing.sequence.TimeseriesGenerator(x_test, y_test, length=5)
model.fit(d_train, epochs=1, validation_data=d_test)

To be consistent with your loss function, you will need to disable return sequences (or add another layer that does not return sequences).

model.add(tf.keras.layers.LSTM(32, activation='relu', return_sequences=False))


问:
While Loop occuring once more than intended (Python)
The while loops controlled by either the x variable won't stop after its relevant variable is set to False by the code contained within the if/elif statement. Instead of stopping the while loop, when the x variable is set to False it allows the loop to occur one more time before causing the loop to stop. What is causing this?

```<code>def GameIntro():
# Declaration of outer while loop variable
    x = True
# Outer while loop that I want to keep running until the player enters the 'yes' branch of the if statement
    while x:
# Declaration of inner while loop variable
        j = True
        playerName = input("Please enter your name:")
        print("\nWelcome " + playerName)
        print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
        while j:
            beginGame = input(playerName + ", are you ready to begin? [Y] or [N]")
            beginGame = beginGame.upper()
            if beginGame == "Y" or beginGame == "YES":
# At this point I want this function to end and for it to return a True value. The     # print is purely for testing purposes.
                print("Yes Test")
                x = False
                j = False
                return True
            elif beginGame == "N" or beginGame == "NO":
# At this point, I want the inner loop to stop and for the outer loop to occur again.  # This works.
                print("No Test")
                j = False
            else:
                print("Please enter either [Y] or [N]")

GameIntro()
</code>```

Here is the output I am getting.

```<code>Please enter your name:Bob
Welcome Bob
At any time, type 'Help' to bring up the list of possible actions.
Bob, are you ready to begin? [Y] or [N]
Y
Yes Test
Please enter your name:Bob2
Welcome Bob2
At any time, type 'Help' to bring up the list of possible actions.
Bob2, are you ready to begin? [Y] or [N]
Y Yes Test
Run game
Process finished with exit code 0
</code>```

The "Run game" comes from another function that is receiving the returned True from the yes branch of the if/elif statement.

答:
I don't think you really need a separate variable, you can use the beginGame, for example as your sentinal value

I would also recommend placing a break at every point within the loops rather than rely on return unless you cannot posssible break to a safe return state

```<code>def validInput(x):
    return x in {'YES', 'Y'}

def intro():
    playerName = input("Please enter your name:")
    print("\nWelcome " + playerName)
    print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
    beginGame = 'N'
    while not validInput(beginGame):
        beginGame = input(playerName + ", are you ready to begin? [Y] or [N]").upper()
        if beginGame == "HELP":
            print('[Y] or [N]?')
        elif validInput(beginGame):
            print('Starting Game!')
    print(f'Getting {playerName} ready to play...')
    return (playerName, True)

playerName, ready_intro = intro()
if ready_intro:
    main_game(playerName)
</code>```

Body:
The while loops controlled by either the x variable won't stop after its relevant variable is set to False by the code contained within the if/elif statement. Instead of stopping the while loop, when the x variable is set to False it allows the loop to occur one more time before causing the loop to stop. What is causing this?

def GameIntro():
# Declaration of outer while loop variable
    x = True
# Outer while loop that I want to keep running until the player enters the 'yes' branch of the if statement
    while x:
# Declaration of inner while loop variable
        j = True
        playerName = input("Please enter your name:")
        print("\nWelcome " + playerName)
        print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
        while j:
            beginGame = input(playerName + ", are you ready to begin? [Y] or [N]")
            beginGame = beginGame.upper()
            if beginGame == "Y" or beginGame == "YES":
# At this point I want this function to end and for it to return a True value. The     # print is purely for testing purposes.
                print("Yes Test")
                x = False
                j = False
                return True
            elif beginGame == "N" or beginGame == "NO":
# At this point, I want the inner loop to stop and for the outer loop to occur again.  # This works.
                print("No Test")
                j = False
            else:
                print("Please enter either [Y] or [N]")

GameIntro()

Here is the output I am getting.

Please enter your name:Bob
Welcome Bob
At any time, type 'Help' to bring up the list of possible actions.
Bob, are you ready to begin? [Y] or [N]
Y
Yes Test
Please enter your name:Bob2
Welcome Bob2
At any time, type 'Help' to bring up the list of possible actions.
Bob2, are you ready to begin? [Y] or [N]
Y Yes Test
Run game
Process finished with exit code 0

The "Run game" comes from another function that is receiving the returned True from the yes branch of the if/elif statement.

Body:
I don't think you really need a separate variable, you can use the beginGame, for example as your sentinal value

I would also recommend placing a break at every point within the loops rather than rely on return unless you cannot posssible break to a safe return state

def validInput(x):
    return x in {'YES', 'Y'}

def intro():
    playerName = input("Please enter your name:")
    print("\nWelcome " + playerName)
    print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
    beginGame = 'N'
    while not validInput(beginGame):
        beginGame = input(playerName + ", are you ready to begin? [Y] or [N]").upper()
        if beginGame == "HELP":
            print('[Y] or [N]?')
        elif validInput(beginGame):
            print('Starting Game!')
    print(f'Getting {playerName} ready to play...')
    return (playerName, True)

playerName, ready_intro = intro()
if ready_intro:
    main_game(playerName)


问:
Align children flex container bottom not working
I have 3 elements (1 image, 2 texts) inside a flex container. I am not able to align them on the bottom line. I tried with margin-bottom: 0 margin-bottom: auto and it is not working.

.distance {
  display: flex;
  justify-content: space-between;
}

.flex {
  display: flex;
}

.icon {
  width: auto;
  max-height: 100px;
  margin-right: 8px;
}

.text1 {
  font-size: 15px;
}

.text2 {
  font-size: 12px;
  margin-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="distance">
  <div class="flex">
    <img src="https://r00t4bl3.com/uploads/pp-840x830-pad-1000x1000-f8f8f8-c3edd4cbfc0d7bc9d7b02b27c6f6bac5.jpg" class="icon">
    <div class="text1">
      Golang
    </div>
    <div class="text2">
      Made by Google
    </div>
  </div>
</div></code>```

答: for vertical align in a flex display use the property align-items. in your case add align-items: flex-end at flex class. css-tricks is a good reference for flexbox.

Body:
I have 3 elements (1 image, 2 texts) inside a flex container. I am not able to align them on the bottom line. I tried with margin-bottom: 0 margin-bottom: auto and it is not working.

.distance {
  display: flex;
  justify-content: space-between;
}

.flex {
  display: flex;
}

.icon {
  width: auto;
  max-height: 100px;
  margin-right: 8px;
}

.text1 {
  font-size: 15px;
}

.text2 {
  font-size: 12px;
  margin-bottom: 0px;
}

      Golang

      Made by Google


问:
Transfer Learning on MNIST: wrong labels error
So I trained a perceptron in tensorflow on the MNIST dataset but only the digits 0 through 4. Then I made a new model with all the same layers and weights but with a new output layer also with 5 output nodes. I want to train this new model to classify the digits 5 to 9.

I generated a new x_train and y_train with only the digits 5 to 9, and ran

transfer_model.fit(x_train[train_filter],y_train[train_filter], epoch=5)

where train_filter is defined as np.where(np.logical_and(x_train<=5,x_train>=9)).

At the very first step of training, I get this error:

InvalidArgumentError:  Received a label value of 9 which is outside the valid range of [0, 5).  Label values: 5 9 7 8 9 8 7 6 8 7 6 9 5 5 8 7 6 9 9 7 6 7 6 8 7 7 9 7 6 8 5 6

This makes sense because I originally trained the network to classify in the range [0,5), but now I want to do the range [5,10). Did I miss a step here? I'm not sure what I'm missing... How do I define what each output neuron corresponds to?

Here is my model summary:

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
flatten_7 (Flatten)          (None, 784)               0
_________________________________________________________________
dense_49 (Dense)             (None, 100)               78500
_________________________________________________________________
batch_normalization_10 (Batc (None, 100)               400
_________________________________________________________________
dropout_5 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_50 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_11 (Batc (None, 100)               400
_________________________________________________________________
dropout_6 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_51 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_12 (Batc (None, 100)               400
_________________________________________________________________
dropout_7 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_52 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_13 (Batc (None, 100)               400
_________________________________________________________________
dropout_8 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_53 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_14 (Batc (None, 100)               400
_________________________________________________________________
dropout_9 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_55 (Dense)             (None, 5)                 505
=================================================================
Total params: 121,405
Trainable params: 505
Non-trainable params: 120,900
_________________________________________________________________
</code>```

答:
Since you use numpy, you can try the following

import tensorflow as tf
import numpy as np

arr = np.array([5,6,7,8,9,8,7,6,5])
arr = tf.one_hot(arr,10,axis=0).numpy()
arr = arr[5:]

tf.argmax(arr).numpy() # returns array([0, 1, 2, 3, 4, 3, 2, 1, 0])
```

<p>or using <code>tf.map_fn</code></p>

<pre class="lang-py prettyprint-override"><code>arr = np.array([5,6,7,8,9,8,7,6,5])

tf.map_fn(lambda x : x-5, arr).numpy() # array([0, 1, 2, 3, 4, 3, 2, 1, 0])
</code>```

Body:
So I trained a perceptron in tensorflow on the MNIST dataset but only the digits 0 through 4. Then I made a new model with all the same layers and weights but with a new output layer also with 5 output nodes. I want to train this new model to classify the digits 5 to 9.

I generated a new x_train and y_train with only the digits 5 to 9, and ran

transfer_model.fit(x_train[train_filter],y_train[train_filter], epoch=5)

where train_filter is defined as np.where(np.logical_and(x_train<=5,x_train>=9)).

At the very first step of training, I get this error:

InvalidArgumentError:  Received a label value of 9 which is outside the valid range of [0, 5).  Label values: 5 9 7 8 9 8 7 6 8 7 6 9 5 5 8 7 6 9 9 7 6 7 6 8 7 7 9 7 6 8 5 6

This makes sense because I originally trained the network to classify in the range [0,5), but now I want to do the range [5,10). Did I miss a step here? I'm not sure what I'm missing... How do I define what each output neuron corresponds to?

Here is my model summary:

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
flatten_7 (Flatten)          (None, 784)               0
_________________________________________________________________
dense_49 (Dense)             (None, 100)               78500
_________________________________________________________________
batch_normalization_10 (Batc (None, 100)               400
_________________________________________________________________
dropout_5 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_50 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_11 (Batc (None, 100)               400
_________________________________________________________________
dropout_6 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_51 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_12 (Batc (None, 100)               400
_________________________________________________________________
dropout_7 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_52 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_13 (Batc (None, 100)               400
_________________________________________________________________
dropout_8 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_53 (Dense)             (None, 100)               10100
_________________________________________________________________
batch_normalization_14 (Batc (None, 100)               400
_________________________________________________________________
dropout_9 (Dropout)          (None, 100)               0
_________________________________________________________________
dense_55 (Dense)             (None, 5)                 505
=================================================================
Total params: 121,405
Trainable params: 505
Non-trainable params: 120,900
_________________________________________________________________

Body:
Since you use numpy, you can try the following

import tensorflow as tf
import numpy as np

arr = np.array([5,6,7,8,9,8,7,6,5])
arr = tf.one_hot(arr,10,axis=0).numpy()
arr = arr[5:]

tf.argmax(arr).numpy() # returns array([0, 1, 2, 3, 4, 3, 2, 1, 0])

or using tf.map_fn

arr = np.array([5,6,7,8,9,8,7,6,5])

tf.map_fn(lambda x : x-5, arr).numpy() # array([0, 1, 2, 3, 4, 3, 2, 1, 0])


问:
Mongoose ADDING/SUMING subdocument array value which is within another subdocument array
My document looks like this:

```<code>_id:'111'
products:[
   {
    _id:'pqr'
    nums:[
      {_id:'aaa',
      quantity:30
      },
      {_id:'bbb',
       quantity:40
      }
    ]
   }
]
</code>```

I need to get:

(i) summation of quantity field which is inside nums subdocument which again is in products subdocument.

(ii) products array to be returned as a whole (with the calculated quantity within it AND the nums subdocument as it is)

Below is how I want my output to be like:

```<code>products:[
  {
   _id: 'pqr',
   nums:[
      {_id:'aaa',
      quantity:30
      },
      {_id:'bbb',
       quantity:40
      }
   ],
   quantity: 70
  }
]
</code>```

So far, I have tried doing this

```<code>    Shop.aggregate([

         {$match: {'_id':'111'},

         {$unwind: "$products"},

         {$group:{
            _id : "$_id",
            nums:{$last:"$nums"},
            quatity: //I have no idea how to get this total quantity which corresponds to _id:'pqr'
          }
         }

    ])
</code>```

Any work around on how to do this?

答:
That is a good use case for $reduce:

```<code>Shop.aggregate([
     {$match: {'_id':'111'},
     {$unwind: "$products"},
     {$addFields:{
          "products.quantity":{
              $reduce:{
                   input: "$products.nums",
                   initialValue: 0
                   in: {$sum:["$$value","$$this.quantity"]}
              }
          }
      }}
])
</code>```

Body:
My document looks like this:

_id:'111'
products:[
   {
    _id:'pqr'
    nums:[
      {_id:'aaa',
      quantity:30
      },
      {_id:'bbb',
       quantity:40
      }
    ]
   }
]

I need to get:

(i) summation of quantity field which is inside nums subdocument which again is in products subdocument.

(ii) products array to be returned as a whole (with the calculated quantity within it AND the nums subdocument as it is)

Below is how I want my output to be like:

products:[
  {
   _id: 'pqr',
   nums:[
      {_id:'aaa',
      quantity:30
      },
      {_id:'bbb',
       quantity:40
      }
   ],
   quantity: 70
  }
]

So far, I have tried doing this

    Shop.aggregate([

         {$match: {'_id':'111'},

         {$unwind: "$products"},

         {$group:{
            _id : "$_id",
            nums:{$last:"$nums"},
            quatity: //I have no idea how to get this total quantity which corresponds to _id:'pqr'
          }
         }

    ])

Any work around on how to do this?

Body:
That is a good use case for $reduce:

Shop.aggregate([
     {$match: {'_id':'111'},
     {$unwind: "$products"},
     {$addFields:{
          "products.quantity":{
              $reduce:{
                   input: "$products.nums",
                   initialValue: 0
                   in: {$sum:["$$value","$$this.quantity"]}
              }
          }
      }}
])


问:
nodejs + express where load context configuration from database
my scenario id a nodejs + express app connected to a mysql database.

There are some context configurations, valid for all the website and all users, that I need to load from the database at every page request (not at app init because I don't want to reload the entire server when the configuration changes).

My idea was to use a simple middleware to inject the context into the request, like that:

const express = require('express');
const contextSetup = require('./contextSetup');

const app = express();
...
app.use(contextSetup.middleWare);
...
```

<p>and in <code>contextSetup.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>const DB = require('./DB');

module.exports.middleWare = (req, res, next) => {
  DB.query('select `code`, `data` from `setting` order by `sort`')
    .then((rows) => {
      const keyVals = {};
      rows.forEach((row) => {
        keyVals[row.code] = row.data;
      });
      req.appContext = keyVals;
      next();
    })
    .catch((err) => next(err));
};

</code>```

The only warning is to use the middleware after app.use(express.static()); otherwise my middleware would be called even for static files request (images, css, js, ...).

Is this approach correct?

Thank you

答: this works in my book! I might suggest that you put this on a router, so this works only for logged in users, for example. You might also further isolate your routers so that if there are any ajax routes, that these values are not requeried only to be ignored. So the code seems fine, and if performance becomes an issue, just implement a cache which, say, refreshes every half minute or ten requests. But its only one query, so that seems fine for now.</p>

Body:
my scenario id a nodejs + express app connected to a mysql database.

There are some context configurations, valid for all the website and all users, that I need to load from the database at every page request (not at app init because I don't want to reload the entire server when the configuration changes).

My idea was to use a simple middleware to inject the context into the request, like that:

const express = require('express');
const contextSetup = require('./contextSetup');

const app = express();
...
app.use(contextSetup.middleWare);
...

and in contextSetup.js:

const DB = require('./DB');

module.exports.middleWare = (req, res, next) => {
  DB.query('select `code`, `data` from `setting` order by `sort`')
    .then((rows) => {
      const keyVals = {};
      rows.forEach((row) => {
        keyVals[row.code] = row.data;
      });
      req.appContext = keyVals;
      next();
    })
    .catch((err) => next(err));
};

The only warning is to use the middleware after app.use(express.static()); otherwise my middleware would be called even for static files request (images, css, js, ...).

Is this approach correct?

Thank you


问:
Converting array of bits to array of hex in C through bitwise operations
I'm trying to convert an array of bits to an array of bytes, except my operations seem to be reading my bits in the opposite direction from what I want them to be. For example, say the array of binary bits is 10110111 11000000 00000110. I want the byte array to be {B7, C0, 06}. Instead, my code below produces an output of of {ED, 03, 60} i.e. it reads every 8 bits in the opposite direction. Could anyone provide me some suggestions as to where I am going wrong?

```<code>void find_hex_arr(uint8_t* bit_arr, int bit_len) {
  uint8_t* hex_arr = malloc(bit_len/8);
  int index = 0;
  unsigned int i = 0;
  unsigned int j = 0;
  for (i = 0; i < bit_len; i = j) {
    for (j = i; j < i + 8; ++j) {
      hex_arr[index] |= bit_arr[j] << (j - i);
    }
    index++;
  }
}
</code>```

答:
Strictly speaking, you don't need two loops, since the two arrays move in lock-step up to a factor of 8.

Your input array is as follows:

```<code>uint8_t bit_arr[] = {
    1, 0, 1, 1, 0, 1, 1, 1,
    1, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 1, 1, 0};
</code>```

The desired output is

```<code>uint8_t expected[] = {0xB7, 0xC0, 0x06}
</code>```

Notice that the most significant bit comes first in this representation. Bits 0-8 in the array are the most to least significant bits in byte 0 of the output and so on.

This plays very well with how basic looping and bit-shifting works. You can push the bits one by one into the least significant bit of the output array:

```<code>uint8_t *hex_arr = malloc(bit_len / 8);
memset(hex_arr, 0, bit_len / 8);
for(int i = 0; i < bit_len; i++) {
    hex_arr[i / 8] <<= 1;
    hex_arr[i / 8] += bit_arr[i];
}
</code>```

The moral of the story is that you must be careful as to how you define your representations and your data. Make sure that you understand where you want things to go conceptually, and you won't have a problem with either graphical or internal representations.

Body:
I'm trying to convert an array of bits to an array of bytes, except my operations seem to be reading my bits in the opposite direction from what I want them to be. For example, say the array of binary bits is 10110111 11000000 00000110. I want the byte array to be {B7, C0, 06}. Instead, my code below produces an output of of {ED, 03, 60} i.e. it reads every 8 bits in the opposite direction. Could anyone provide me some suggestions as to where I am going wrong?

void find_hex_arr(uint8_t* bit_arr, int bit_len) {
  uint8_t* hex_arr = malloc(bit_len/8);
  int index = 0;
  unsigned int i = 0;
  unsigned int j = 0;
  for (i = 0; i < bit_len; i = j) {
    for (j = i; j < i + 8; ++j) {
      hex_arr[index] |= bit_arr[j] << (j - i);
    }
    index++;
  }
}

Body:
Strictly speaking, you don't need two loops, since the two arrays move in lock-step up to a factor of 8.

Your input array is as follows:

uint8_t bit_arr[] = {
    1, 0, 1, 1, 0, 1, 1, 1,
    1, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 1, 1, 0};

The desired output is

uint8_t expected[] = {0xB7, 0xC0, 0x06}

Notice that the most significant bit comes first in this representation. Bits 0-8 in the array are the most to least significant bits in byte 0 of the output and so on.

This plays very well with how basic looping and bit-shifting works. You can push the bits one by one into the least significant bit of the output array:

uint8_t *hex_arr = malloc(bit_len / 8);
memset(hex_arr, 0, bit_len / 8);
for(int i = 0; i < bit_len; i++) {
    hex_arr[i / 8] <<= 1;
    hex_arr[i / 8] += bit_arr[i];
}

The moral of the story is that you must be careful as to how you define your representations and your data. Make sure that you understand where you want things to go conceptually, and you won't have a problem with either graphical or internal representations.