问:
How to put calculated data into INSERT query in a Spark.Sql code
I was trying to insert 4 data into a table:
 and for insertion I'm using below code-

```<code>spark.sql("INSERT INTO countDirectorySize VALUES (`" +str(root) + "`, `" +str(dirSize) + "`, `" +str(today1) + "`, `" +str(today2)+ "`)")
</code>```

Let me put the entire code here for better understanding-

```<code>import os
from datetime import date
size=0
root = "/dbfs/mnt/datalake/.../"
today1 = date.today()
dirSize = size/(1024*1024)
today2 = date.today()

spark.sql("INSERT INTO countDirectorySize VALUES (`" +str(root) + "`, `" +str(dirSize) + "`, `" +str(today1) + "`, `" +str(today2)+ "`)")
</code>```

And this code gives error while inserting. What am I doing wrong.

Error:

```<code>cannot resolve '`/dbfs/mnt/datalake/.../`' given input columns: []; line 1 pos 39;\n'InsertIntoTable 'UnresolvedRelation `countDirectorySize`, false, false\n+- 'UnresolvedInlineTable [col1, col2, col3, col4], [List('/dbfs/mnt/datalake/.../, '`9.256933212280273`, '2020-06-01, '2020-06-01)]\n"
</code>```

答:
Instead of using plain insert statement, I would recommended to build a dataframe and register it as a table.

Here is what I did with your code:

```<code>import os
from datetime import date
data = []
size=0
root = "/Users/hbohra/Desktop/"
today1 = date.today()
for path, subdirs, files in os.walk(root):
    for name in files:
        size += os.path.getsize(os.path.join(path, name))
        dirSize = size/(1024*1024)
today2 = date.today()
data.append((root, dirSize, today1, today2))
df = spark.createDataFrame(data, schema=['dir_name', 'dir_size', 'created_date', 'modified_date'])
df.registerTempTable('countDirectorySize')

#spark.sql("INSERT INTO countDirectorySize VALUES (`" +str(root) + "`, `" +str(dirSize) + "`, `" +str(today1) + "`, `" +str(today2)+ "`)")

df2 = spark.sql('select * from countDirectorySize')
</code>```

Output:

```<code>>>> df2.show()
+--------------------+-----------------+------------+-------------+
|            dir_name|         dir_size|created_date|modified_date|
+--------------------+-----------------+------------+-------------+
|/Users/hbohra/Des...|428.3244695663452|  2020-06-01|   2020-06-01|
+--------------------+-----------------+------------+-------------+

>>>
</code>```

Let me know if this helps.

Body:
I was trying to insert 4 data into a table:
 and for insertion I'm using below code-

spark.sql("INSERT INTO countDirectorySize VALUES (`" +str(root) + "`, `" +str(dirSize) + "`, `" +str(today1) + "`, `" +str(today2)+ "`)")

Let me put the entire code here for better understanding-

import os
from datetime import date
size=0
root = "/dbfs/mnt/datalake/.../"
today1 = date.today()
dirSize = size/(1024*1024)
today2 = date.today()

spark.sql("INSERT INTO countDirectorySize VALUES (`" +str(root) + "`, `" +str(dirSize) + "`, `" +str(today1) + "`, `" +str(today2)+ "`)")

And this code gives error while inserting. What am I doing wrong.

Error:

cannot resolve '`/dbfs/mnt/datalake/.../`' given input columns: []; line 1 pos 39;\n'InsertIntoTable 'UnresolvedRelation `countDirectorySize`, false, false\n+- 'UnresolvedInlineTable [col1, col2, col3, col4], [List('/dbfs/mnt/datalake/.../, '`9.256933212280273`, '2020-06-01, '2020-06-01)]\n"

Body:
Instead of using plain insert statement, I would recommended to build a dataframe and register it as a table.

Here is what I did with your code:

import os
from datetime import date
data = []
size=0
root = "/Users/hbohra/Desktop/"
today1 = date.today()
for path, subdirs, files in os.walk(root):
    for name in files:
        size += os.path.getsize(os.path.join(path, name))
        dirSize = size/(1024*1024)
today2 = date.today()
data.append((root, dirSize, today1, today2))
df = spark.createDataFrame(data, schema=['dir_name', 'dir_size', 'created_date', 'modified_date'])
df.registerTempTable('countDirectorySize')

#spark.sql("INSERT INTO countDirectorySize VALUES (`" +str(root) + "`, `" +str(dirSize) + "`, `" +str(today1) + "`, `" +str(today2)+ "`)")

df2 = spark.sql('select * from countDirectorySize')

Output:

>>> df2.show()
+--------------------+-----------------+------------+-------------+
|            dir_name|         dir_size|created_date|modified_date|
+--------------------+-----------------+------------+-------------+
|/Users/hbohra/Des...|428.3244695663452|  2020-06-01|   2020-06-01|
+--------------------+-----------------+------------+-------------+

>>>

Let me know if this helps.


来源: stackexchange

问:
Change web-page color based on user's input from previous page
I have a form made in the previous page. In the form, I have a checklist with the options: red, green, blue.

If the user selects red, the next page's background color should be red. If green is selected, then the background color will be green. I am using PHP to do this.

Previous page

```<code><form action="next_page.php method="POST>
  <input type="radio" name="color" value="red">
  <input type="radio" name="color" value="green">
  <input type="radio" name="color" value="blue">
</form>
</code>```

Next Page

```<code><?PHP
   $radioVal = $_POST["color"]
 ?>

 <style>
   .body{
     //what goes here
  }
 </style>
</code>```

答:
Try this: </p>

```<code><?PHP
$radioVal = $_POST["color"];

echo "
 <style>
   .body{
     background-color:" . htmlspecialchars($radioVal) . "
  }
 </style>";
 ?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a form made in the previous page. In the form, I have a checklist with the options: red, green, blue.

If the user selects red, the next page's background color should be red. If green is selected, then the background color will be green. I am using PHP to do this.

Previous page

<form action="next_page.php method="POST>
  <input type="radio" name="color" value="red">
  <input type="radio" name="color" value="green">
  <input type="radio" name="color" value="blue">
</form>

Next Page

<?PHP
   $radioVal = $_POST["color"]
 ?>

Body:
Try this:

<?PHP
$radioVal = $_POST["color"];

echo "
 <style>
   .body{
     background-color:" . htmlspecialchars($radioVal) . "
  }
 </style>";
 ?>


问:
How can I validate email addresses flawlessly?
I need help validating proper email addresses. I've managed to solve empty fields, but I also need to solve not proper email address. I mean that, if I input a something that's not an email address, it gives me a message saying "Please enter a proper email address". How can I find the empty value that I can use for this validations?

This:

if (x == "what goes here?")
   {
    document.getElementById("demo").innerHTML = "Please enter a proper email address";
    document.getElementById("demo").style.display = "block";
    return false;
  }```
</div>
</div>
</p>

<p>The "what goes here?" is a placeholder for you to replace with the answer.</p>

<p>And, without much more speaking, here's the code for the site:</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><!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
<style>
body {
  font-family: 'PT Sans', sans-serif;
}
p#demo {
  padding: 5px;
  background: rgba(255,0,0,0.2);
  border: red solid 1px;
  color: red;
  display: none;
  max-width: 140px;
  text-align: left;
  font-size: 12px;
  margin-left: 2px;
  font-family: 'PT Sans', sans-serif;
}
input[type="submit"] {
  background-color: red;
  border: none;
  font-family: 'PT Sans', sans-serif;
  font-size: 15px;
  font-weight: 700;
  text-transform: uppercase;
}
input[type="email"] {
  padding: 4px;
  }
input[type="email"]:focus {
  outline: none;
}
</style>
<script>
function validateForm() {
  var x = document.forms["myForm"]["EMAIL"].value;
  if (x == "") {
    document.getElementById("demo").innerHTML = "Email address is required.";
    document.getElementById("demo").style.display = "block";
    return false;
  }
   if (x == "what goes here?")
   {
    document.getElementById("demo").innerHTML = "Please enter a proper email address";
    document.getElementById("demo").style.display = "block";
    return false;
  }
}
</script>
</head>
<body>

<form name="myForm" action="https://gmail.us19.list-manage.com/subscribe/post?u=f206f10b38a504434c650c6bf&id=5ce815006b" onsubmit="return validateForm()" method="post" >
  <p id="demo"></p>
  <input type="email" name="EMAIL">
  <input type="submit" value="Sign up!">

</form>

</body>
</html></code>```

答:
As I was just recently creating a form with email address validation, I used a Regular Expression:

```<code>^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\]?)$
</code>```

What I am thinking you can do with this, is the following:

function validateEmail() {
  document.getElementById("demo").innerHTML = "Please enter a proper email address";
  document.getElementById("demo").style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="">
  <input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0- 9\-]+\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\]?)$" placeholder="Email Address" oninvalid="validateEmail()" />
  <div id="demo"></div>
  <input type="submit" />
</form></code>```

But, that will also create a HTML5 default validation bubble to come. So, if you don't want that add this to your JavaScript (Note: This will affect your whole form):

```<code>document.addEventListener('invalid', (function(){
    return function(e) {
      //prevent the browser from showing default error bubble / hint
      e.preventDefault();
      // optionally fire off some custom validation handler
      // myValidation();
    };
})(), true);
</code>```

This will disable the default validation, but will keep your validation. I hope this helps you!

EDIT: I know a regular expression (RegEx) is not the BEST way, but this one has never failed me in all my forms.

Body:
I need help validating proper email addresses. I've managed to solve empty fields, but I also need to solve not proper email address. I mean that, if I input a something that's not an email address, it gives me a message saying "Please enter a proper email address". How can I find the empty value that I can use for this validations?

This:

if (x == "what goes here?")
   {
    document.getElementById("demo").innerHTML = "Please enter a proper email address";
    document.getElementById("demo").style.display = "block";
    return false;
  }

The "what goes here?" is a placeholder for you to replace with the answer.

And, without much more speaking, here's the code for the site:

<!DOCTYPE html>

<link href="https://fonts.googleapis.com/css2?family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">

<form name="myForm" action="https://gmail.us19.list-manage.com/subscribe/post?u=f206f10b38a504434c650c6bf&id=5ce815006b" onsubmit="return validateForm()" method="post" >

  <input type="email" name="EMAIL">
  <input type="submit" value="Sign up!">

</form>

Body:
As I was just recently creating a form with email address validation, I used a Regular Expression:

^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\]?)$

What I am thinking you can do with this, is the following:

function validateEmail() {
  document.getElementById("demo").innerHTML = "Please enter a proper email address";
  document.getElementById("demo").style.display = "block";
}

<form action="">
  <input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0- 9\-]+\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\]?)$" placeholder="Email Address" oninvalid="validateEmail()" />
  <div id="demo"></div>
  <input type="submit" />
</form>

But, that will also create a HTML5 default validation bubble to come. So, if you don't want that add this to your JavaScript (Note: This will affect your whole form):

document.addEventListener('invalid', (function(){
    return function(e) {
      //prevent the browser from showing default error bubble / hint
      e.preventDefault();
      // optionally fire off some custom validation handler
      // myValidation();
    };
})(), true);

This will disable the default validation, but will keep your validation. I hope this helps you!

EDIT: I know a regular expression (RegEx) is not the BEST way, but this one has never failed me in all my forms.


问:
How to make SSH remote port forward that listens 0.0.0.0
I need to do remote port forwarding that will listen 0.0.0.0 instead of 127.0.0.1 on the remote machine so that I can connect from outside internet to IP_OF_BBB:SOME_PORT in order to connect to SSH port of AAA.

I managed to make this happen by the following:

AAA:~$ ssh -R 22:localhost:2222 user@BBB

BBB:~$ ssh -L 2222:*:2223 user@localhost

Now I can connect to AAA with this command:

ssh user@BBB -p 2223

The local port forwarding is a workaround, of course. Is there any clearer way to do this?

答: As addition to the existing answer you can use ssh -o GatewayPorts=true -L 2222:0.0.0.0:2223 user@localhost


问:
Create a feature in pandas based on another column
I have the following dataset:

```<code>data = {'ROC_9':  [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)
</code>```

It is an indicator about a stock price, namely rate of change.

I want to write a code that creates a new feature (column) on the pandas data frame when a current feature on the pandas data frame goes from positive to negative, or vice versa.

It is easier explained through an example: lets use the feature ROC9.

I create a new variable called ROC9_signal and set it equal to 0:

```<code>`price_data['ROC9_signal'] = 0`
</code>```

When ROC_9 goes from negative to positive, I want to change the ROC9_signal from 0 to 1.

When ROC_9 goes from positive to negative, I want to change the ROC9_signal from 0 to -1.

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.16 (positive) to -0.006 (negative).

Looking at the data, I would like ROC_9 signal to change from 0 to 1, since the value has gone from -0.11 (negative) to 0.05 (positive).

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.20 (positive) to -0.008 (negative).

It is only the row where the change happens that I want to change from 0 to 1 or 0 to -1, the other rows must remain at 0.

I will then apply this same logic to create a momentum10_signal column and a chalkin_money_flow_signal column. Therefore I want a solution that can be applied to different columns and not manually.

Thanks in advance for the help.

This is what the full data looks like:

Full Data

答:
Data

```<code>data = {'ROC_9':  [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)
price_data['ROC9_signal'] = 0
price_data
</code>```

Use Boolean selection to find the two different crossings:

```<code> ZeroCrossing1=price_data.ROC_9.ge(0)&price_data.ROC_9.shift(1).le(0)#from 0 to 1
 ZeroCrossing2=price_data.ROC_9.ge(0)&price_data.ROC_9.shift(-1).le(0)# from 0 to -1.
</code>```

Put the Zerocrossing likely outcomes into a list

```<code> ZeroCrossingOutcomes=[1,-1]
</code>```

Conditionally calculate price_data['ROC9_signal'] using np.where

```<code>price_data['ROC9_signal']=np.select([ZeroCrossing1,ZeroCrossing2],ZeroCrossingOutcomes,0)
print(price_data)
</code>```

Alternatively use nested np.where(if condition, ye, else no)

```<code>price_data['ROC9_signal']=np.where(ZeroCrossing1,1,np.where(ZeroCrossing2,-1,0)))
</code>```

Body:
I have the following dataset:

data = {'ROC_9':  [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)

It is an indicator about a stock price, namely rate of change.

I want to write a code that creates a new feature (column) on the pandas data frame when a current feature on the pandas data frame goes from positive to negative, or vice versa.

It is easier explained through an example: lets use the feature ROC9.

I create a new variable called ROC9_signal and set it equal to 0:

`price_data['ROC9_signal'] = 0`

When ROC_9 goes from negative to positive, I want to change the ROC9_signal from 0 to 1.

When ROC_9 goes from positive to negative, I want to change the ROC9_signal from 0 to -1.

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.16 (positive) to -0.006 (negative).

Looking at the data, I would like ROC_9 signal to change from 0 to 1, since the value has gone from -0.11 (negative) to 0.05 (positive).

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.20 (positive) to -0.008 (negative).

It is only the row where the change happens that I want to change from 0 to 1 or 0 to -1, the other rows must remain at 0.

I will then apply this same logic to create a momentum10_signal column and a chalkin_money_flow_signal column. Therefore I want a solution that can be applied to different columns and not manually.

Thanks in advance for the help.

This is what the full data looks like:

Full Data

Body:
Data

data = {'ROC_9':  [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)
price_data['ROC9_signal'] = 0
price_data

Use Boolean selection to find the two different crossings:

 ZeroCrossing1=price_data.ROC_9.ge(0)&price_data.ROC_9.shift(1).le(0)#from 0 to 1
 ZeroCrossing2=price_data.ROC_9.ge(0)&price_data.ROC_9.shift(-1).le(0)# from 0 to -1.

Put the Zerocrossing likely outcomes into a list

 ZeroCrossingOutcomes=[1,-1]

Conditionally calculate price_data['ROC9_signal'] using np.where

price_data['ROC9_signal']=np.select([ZeroCrossing1,ZeroCrossing2],ZeroCrossingOutcomes,0)
print(price_data)

Alternatively use nested np.where(if condition, ye, else no)

price_data['ROC9_signal']=np.where(ZeroCrossing1,1,np.where(ZeroCrossing2,-1,0)))


问:
How can I write files in Deno?
I was trying to write to a file using Deno.writeFile

```<code>await Deno.writeFile('./file.txt', 'some content')
</code>```

But got the following cryptic error:

```<code>error: Uncaught TypeError: arr.subarray is not a function
    at Object.writeAll ($deno$/buffer.ts:212:35)
    at Object.writeFile ($deno$/write_file.ts:70:9)
</code>```

What's the right way to write files in Deno?

答:
You can use ensureDir to safely write files to possibly non-existent directories:

```<code>import { ensureDir } from "https://deno.land/std@0.54.0/fs/ensure_dir.ts";

ensureDir("./my/dir")
  .then(() => Deno.writeTextFile("./my/dir/file.txt", "some content"));
</code>```

The containing file directory can be derived via dirname:

```<code>import { dirname } from "https://deno.land/std@0.54.0/path/mod.ts";

const file = "./my/dir/file.txt";
ensureDir(dirname(file)).then(() => Deno.writeTextFile(file, "some content"));
</code>```

An alternative is ensureFile to assert file existence:

```<code>import { ensureFile } from "https:deno.land/std/fs/ensure_file.ts";

ensureFile(file).then(/* your file write method */)
</code>```

This variant is slightly less verbose, with the cost of one additional write operation (file creation, if not exists).

Title: How can I write files in Deno?

Body:
I was trying to write to a file using Deno.writeFile

await Deno.writeFile('./file.txt', 'some content')

But got the following cryptic error:

error: Uncaught TypeError: arr.subarray is not a function
    at Object.writeAll ($deno$/buffer.ts:212:35)
    at Object.writeFile ($deno$/write_file.ts:70:9)

What's the right way to write files in Deno?

Body:
You can use ensureDir to safely write files to possibly non-existent directories:

import { ensureDir } from "https://deno.land/std@0.54.0/fs/ensure_dir.ts";

ensureDir("./my/dir")
  .then(() => Deno.writeTextFile("./my/dir/file.txt", "some content"));

The containing file directory can be derived via dirname:

import { dirname } from "https://deno.land/std@0.54.0/path/mod.ts";

const file = "./my/dir/file.txt";
ensureDir(dirname(file)).then(() => Deno.writeTextFile(file, "some content"));

An alternative is ensureFile to assert file existence:

import { ensureFile } from "https:deno.land/std/fs/ensure_file.ts";

ensureFile(file).then(/* your file write method */)

This variant is slightly less verbose, with the cost of one additional write operation (file creation, if not exists).


问:
How can select an element generated by jQuery?
I am trying to activate a slideDown() onclick with an element that has been generated by js.

I downloaded a script from ryanfait.com which allows you to customise the look of radio buttons. This works fine but when I try and apply an action to the generated element (in this case a span) it doesn't work. How can I work around this?

Here is my HTML:

```<code><div class="radiocont">
                                <label>Yes</label>
                                <input type="radio" class="styled" value="yes" name="watertank" />
                            </div>
                            <div class="radiocont">
                                <label>No</label>
                                <input type="radio" class="styled" value="no" name="watertank" />
                            </div>
</code>```

When the DOM loads the inputs are replaced by spans that look like this:

When you click on one of the spans I want to activate slideDown(). Here is my js:$('[title="yes"]').click(function() {
  $(this).nextAll('.secondq:first').slideDown('slow');
});

Can anyone assist?

答:
Use .live or .delegate to "Attach a handler to the event for all elements which match the current selector, now and in the future."

```<code>// .live()
$('[title="yes"]').live("click", function() {
    $(this).nextAll('.secondq:first').slideDown('slow');
});

// .delegate() (not entirely sure of your structure, the below may need
// to be modified accordingly
$('.radiocont').delegate("span[title='yes']", "click", function() {
    $(this).nextAll('.secondq:first').slideDown('slow');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to activate a slideDown() onclick with an element that has been generated by js.

I downloaded a script from ryanfait.com which allows you to customise the look of radio buttons. This works fine but when I try and apply an action to the generated element (in this case a span) it doesn't work. How can I work around this?

Here is my HTML:

                                Yes
                                <input type="radio" class="styled" value="yes" name="watertank" />

                                No
                                <input type="radio" class="styled" value="no" name="watertank" />

When the DOM loads the inputs are replaced by spans that look like this:

When you click on one of the spans I want to activate slideDown(). Here is my js:$('[title="yes"]').click(function() {
  $(this).nextAll('.secondq:first').slideDown('slow');
});

Can anyone assist?

Body:
Use .live or .delegate to "Attach a handler to the event for all elements which match the current selector, now and in the future."

// .live()
$('[title="yes"]').live("click", function() {
    $(this).nextAll('.secondq:first').slideDown('slow');
});

// .delegate() (not entirely sure of your structure, the below may need
// to be modified accordingly
$('.radiocont').delegate("span[title='yes']", "click", function() {
    $(this).nextAll('.secondq:first').slideDown('slow');
});


问:
In converting List<T> to DataTable add select properties from class
I am trying to convert a List to a DataTable. I have the basic outline done, but am stuck on one part. I am trying to only get a few of the properties form the class.

```<code>public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();

    table.Columns.Add("type", typeof(string));
    table.Columns.Add("id", typeof(Int32));
    table.Columns.Add("name", typeof(string));
    table.Columns.Add("city", typeof(string));

    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
        {
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        }
        table.Rows.Add(row);
    }
    return table;
}
</code>```

The problem is when it gets to the second property it throws an error saying column 'unincludedCol' does not belong to table.

How do I get around this?

答:
I believe using a an attribute is attribute will be more generic. Also Lets you assign property name aliases.

Attribute

```<code>[AttributeUsage(AttributeTargets.Property)]
public class UseAsTableColumn : Attribute
{
    public string Alias { get; private set; }
    public UseAsTableColumn(string columnAlias = null)
    {
        this.Alias = columnAlias;
    }
}
</code>```

A helper - Altered your method (Using Property name as the Column Name)

```<code>public static class Helper
{
    public static string GetDisplayName(PropertyInfo pi)
    {
        var uatAttrib = pi.GetCustomAttribute(typeof(UseAsTableColumn), true) as UseAsTableColumn;
        return uatAttrib.Alias == null ? pi.Name : uatAttrib.Alias;
    }
    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        var mappableAttrirbs = typeof(T).GetProperties().Where(x => x.GetCustomAttributes(typeof(UseAsTableColumn), true).FirstOrDefault() != null);
        DataTable table = new DataTable();

        foreach (var property in mappableAttrirbs)
        {
            table.Columns.Add(GetDisplayName(property), property.PropertyType);
        }

        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (var property in mappableAttrirbs)
            {
                row[GetDisplayName(property)] = property.GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(row);
        }
        return table;
    }
}
</code>```

Data Model (Mark Properties you want to serialize)

```<code>public class DataModel
{
    [UseAsTableColumn]
    public string Type { get; set; }

    [UseAsTableColumn]
    public int Id { get; set; }

    [UseAsTableColumn("name")]
    public string Name { get; set; }

    [UseAsTableColumn]
    public string City { get; set; }

    public string _InternalValue { get; private set; }
}
</code>```

Runner

```<code>public class Program
{
    static void Main(string[] args)
    {
        List<DataModel> data = new List<DataModel>()
        {
            new DataModel() { Type="Magic", Id= 1, Name = "foo", City = "bar" },
            new DataModel() { Type="Magic", Id= 2, Name = "foo1", City = "bar1" }
        };

        Helper.ToDataTable(data);
        Console.ReadKey();
    }
}
</code>```

Body:
I am trying to convert a List to a DataTable. I have the basic outline done, but am stuck on one part. I am trying to only get a few of the properties form the class.

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();

    table.Columns.Add("type", typeof(string));
    table.Columns.Add("id", typeof(Int32));
    table.Columns.Add("name", typeof(string));
    table.Columns.Add("city", typeof(string));

    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
        {
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        }
        table.Rows.Add(row);
    }
    return table;
}

The problem is when it gets to the second property it throws an error saying column 'unincludedCol' does not belong to table.

How do I get around this?

Body:
I believe using a an attribute is attribute will be more generic. Also Lets you assign property name aliases.

Attribute

[AttributeUsage(AttributeTargets.Property)]
public class UseAsTableColumn : Attribute
{
    public string Alias { get; private set; }
    public UseAsTableColumn(string columnAlias = null)
    {
        this.Alias = columnAlias;
    }
}

A helper - Altered your method (Using Property name as the Column Name)

public static class Helper
{
    public static string GetDisplayName(PropertyInfo pi)
    {
        var uatAttrib = pi.GetCustomAttribute(typeof(UseAsTableColumn), true) as UseAsTableColumn;
        return uatAttrib.Alias == null ? pi.Name : uatAttrib.Alias;
    }
    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        var mappableAttrirbs = typeof(T).GetProperties().Where(x => x.GetCustomAttributes(typeof(UseAsTableColumn), true).FirstOrDefault() != null);
        DataTable table = new DataTable();

        foreach (var property in mappableAttrirbs)
        {
            table.Columns.Add(GetDisplayName(property), property.PropertyType);
        }

        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (var property in mappableAttrirbs)
            {
                row[GetDisplayName(property)] = property.GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(row);
        }
        return table;
    }
}

Data Model (Mark Properties you want to serialize)

public class DataModel
{
    [UseAsTableColumn]
    public string Type { get; set; }

    [UseAsTableColumn]
    public int Id { get; set; }

    [UseAsTableColumn("name")]
    public string Name { get; set; }

    [UseAsTableColumn]
    public string City { get; set; }

    public string _InternalValue { get; private set; }
}

Runner

public class Program
{
    static void Main(string[] args)
    {
        List<DataModel> data = new List<DataModel>()
        {
            new DataModel() { Type="Magic", Id= 1, Name = "foo", City = "bar" },
            new DataModel() { Type="Magic", Id= 2, Name = "foo1", City = "bar1" }
        };

        Helper.ToDataTable(data);
        Console.ReadKey();
    }
}


问:
disable angular ng-select window
We are using ng-select in a project and I'm facing the problem that I can't disable the ng-select window. Is it possible to disable it with native code or do I need to find some custom solution?</p>
```<code>  <ng-select
    #changeowner
    class="custom-owner"
    [placeholder]="leagueOwner.full_name"
    [clearSearchOnAdd]="true"
    (change)="changeLeagueOwner($event)"
    [clearable]="false"
    [virtualScroll]="true"
    [items]="adminLeagueMembers"
    (scrollToEnd)="onAdminLoadScrollEnd()"
    bindLabel="full_name">
</ng-select>
</code>```

答:
If you are using reactForms, the correct way to disable inputs is to use:</p>

```<code> formGroup.get('controlName').disable()
</code>```

Title: disable angular ng-select window

Body:
We are using ng-select in a project and I'm facing the problem that I can't disable the ng-select window. Is it possible to disable it with native code or do I need to find some custom solution?

  <ng-select
    #changeowner
    class="custom-owner"
    [placeholder]="leagueOwner.full_name"
    [clearSearchOnAdd]="true"
    (change)="changeLeagueOwner($event)"
    [clearable]="false"
    [virtualScroll]="true"
    [items]="adminLeagueMembers"
    (scrollToEnd)="onAdminLoadScrollEnd()"
    bindLabel="full_name">
</ng-select>

Body:
If you are using reactForms, the correct way to disable inputs is to use:

 formGroup.get('controlName').disable()


问:
Return generated HTML from controller and bind it to template
I have a table that can display different content in tds depending on some input. For instance, I could have a button, div, img, custom component, etc. Since there is a lot of different data that can be inside the td, I created a method that would generate the proper HTML and return it. However, I cannot seem to find a way to bind it to my template.

Here is my HTML generating method:

```<code>getComponentForType(type: string): any {
    return this._sanitizer.sanitize(SecurityContext.HTML,`<span> hello world</span>`);
}
</code>```

This method would return more complex HTML, but I am just testing with a simple span for the moment.

Here is my template:

```<code><table>
    <tbody>
        <tr *ngFor="let row of data; let rowIndex = index">
            <td *ngFor="let column of columns; let colIndex = index" [attr.safeHtml]="getComponentForType(columns[colIndex].type)">
            </td>
        </tr>
    </tbody>
</table>

</code>```

Now, I tried many things to set the HTML. I tried using the safeHTML, innerHTML, ng-bind-html directives and many more, yet my HTML never seems to render. This is what Chrome renders this as:

How can I manage to add a nested HTML element inside the td from my method that generates HTML?

答:
First, try to do it with javascript getElementById

```<code>document.getElementById("demo").innerHTML = "Paragraph changed!";
</code>```

Once you have done with that, please try to add this

```<code>function parseHTML(html) {
       var t = document.createElement('template');
       t.innerHTML = html;
       return t.content.cloneNode(true);
   }

   var documentFragment = parseHTML('<td>Test</td>');
</code>```

This would help you to add innerhtml in your project.

Body:
I have a table that can display different content in tds depending on some input. For instance, I could have a button, div, img, custom component, etc. Since there is a lot of different data that can be inside the td, I created a method that would generate the proper HTML and return it. However, I cannot seem to find a way to bind it to my template.

Here is my HTML generating method:

getComponentForType(type: string): any {
    return this._sanitizer.sanitize(SecurityContext.HTML,`<span> hello world</span>`);
}

This method would return more complex HTML, but I am just testing with a simple span for the moment.

Here is my template:

Now, I tried many things to set the HTML. I tried using the safeHTML, innerHTML, ng-bind-html directives and many more, yet my HTML never seems to render. This is what Chrome renders this as:

How can I manage to add a nested HTML element inside the td from my method that generates HTML?

Body:
First, try to do it with javascript getElementById

document.getElementById("demo").innerHTML = "Paragraph changed!";

Once you have done with that, please try to add this

function parseHTML(html) {
       var t = document.createElement('template');
       t.innerHTML = html;
       return t.content.cloneNode(true);
   }

   var documentFragment = parseHTML('<td>Test</td>');

This would help you to add innerhtml in your project.


问:
I Need to Call delete[] on a Dynamic Array within a Class but It Doesn't Work
I wrote code very similar to this (although not identical) for a game I'm making. This has the same issue, so I'll provide it.

```<code>#include <iostream>

using namespace std;

class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        for(int i=0; i<=9; i++) {
            arr[i] = i;
        }
    }
    ~test() {
        delete[] arr;
    }
};

int main() {

    test obj = test(10);
    for(int i=0; i<=8; i++) {
        cout << obj.arr[i] << endl;
    }
    cout << obj.arr[9];
    obj.~test();
    return 0;

}
</code>```

I know that I could rework my code and use the vector class to avoid this problem, but I want to actually understand why it's crashing. Removing the deconstructor call fixes the error, but that also introduces a memory leak, so I would prefer to just fix the deconstructor.

答: You are explicitly calling the ~test() destructor on your obj variable, and then that same destructor will be implicitly called again when obj goes out of scope afterwards.  Omitting the explicit destructor will NOT cause a memory leak.  Let the compiler call the destructor for you.  The ONLY time you can ever safely call a destructor explicitly is when the object being destructed was constructed using placement-new, which is not the case in your example.

Body:
I wrote code very similar to this (although not identical) for a game I'm making. This has the same issue, so I'll provide it.

#include <iostream>

using namespace std;

class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        for(int i=0; i<=9; i++) {
            arr[i] = i;
        }
    }
    ~test() {
        delete[] arr;
    }
};

int main() {

    test obj = test(10);
    for(int i=0; i<=8; i++) {
        cout << obj.arr[i] << endl;
    }
    cout << obj.arr[9];
    obj.~test();
    return 0;

}

I know that I could rework my code and use the vector class to avoid this problem, but I want to actually understand why it's crashing. Removing the deconstructor call fixes the error, but that also introduces a memory leak, so I would prefer to just fix the deconstructor.


问:
AWS CloudWatch Rule triggered by Log Event
I want to create CloudWatch Rule that would be triggered upon creation of Log Event. For that reason as an event pattern I selected CloudWatch Logs service but when I try to generate some Cloud Watch logs the rule is not getting triggered. I can not find any example of using aws.logs as a source for an event and hence my question if I'm doing something wrong.

答:
This is because the only events for logs available are AWS API Call via CloudTrail. CloudWatch Logs does not generate CloudWatch events on receiving new log entries.

For the Logs API call events to work, you need to setup CloudTrial trial.

However, if you want to trigger your lambda function based on log entries, I can recommend using subscription filters for lambda:

You can use subscriptions to get access to a real-time feed of log events from CloudWatch Logs and have it delivered to other services such as a Amazon Kinesis stream, Amazon Kinesis Data Firehose stream, or AWS Lambda for custom processing, analysis, or loading to other systems.


问:
How to create and fill a list of lists in a for loop
I'm trying to populate a list with a for loop. This is what I have so far:

```<code>newlist = []
for x in range(10):
    for y in range(10):
        newlist.append(y)
</code>```

and at this point I am stumped. I was hoping the loops would give me a list of 10 lists.

答:
```<code>newlist = [list(range(10))] * 10
</code>```

Body:
I'm trying to populate a list with a for loop. This is what I have so far:

newlist = []
for x in range(10):
    for y in range(10):
        newlist.append(y)

and at this point I am stumped. I was hoping the loops would give me a list of 10 lists.

Body: newlist = [list(range(10))] * 10


问:
how can i put different colors in ListView
i want to get the different colors in each row of the list view

but current only one color is shown

so how can i do this

```<code>ArrayAdapter<String> adapter=new ArrayAdapter<String(this,R.layout.latesthappenings,R.id.LH_Titles,titles);
            setListAdapter(adapter);
</code>```

i want to different color in each row

please tell how can i do

thanks

答:
You can use anonymous ArrayAdapter you have to write code inside getView()

Sudo code

```<code>ArrayAdapter<String> adapter=new ArrayAdapter<String>(
           this,R.layout.main,R.id.textview1,titles){

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
if(position ==condition){
convertView.setBackgroundResource(R.color.grey);}
else if(second condition){convertView.setBackgroundResource(R.color.something else);}

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

ANother approach is

Why donot you do for Customized ListView? You can manage view as per your requirement there.

Have a Custom ArrayAdapter

Thanks
Deepak

Body:
i want to get the different colors in each row of the list view

but current only one color is shown

so how can i do this

ArrayAdapter<String> adapter=new ArrayAdapter<String(this,R.layout.latesthappenings,R.id.LH_Titles,titles);
            setListAdapter(adapter);

i want to different color in each row

please tell how can i do

thanks

Body:
You can use anonymous ArrayAdapter you have to write code inside getView()

Sudo code

ArrayAdapter<String> adapter=new ArrayAdapter<String>(
           this,R.layout.main,R.id.textview1,titles){

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
if(position ==condition){
convertView.setBackgroundResource(R.color.grey);}
else if(second condition){convertView.setBackgroundResource(R.color.something else);}

    return view;};
   };

ANother approach is

Why donot you do for Customized ListView? You can manage view as per your requirement there.

Have a Custom ArrayAdapter

Thanks
Deepak


问:
Is it normal that when I run my flutter code the first time it is rederized 2 times? (I only use one class )
I am new to flutter. Something worries me, I don't know if it is normal. I know the code will render if the widget is of type StateFulWidget. But in this case, I have a stateLessWidget and for some reason it renders 2 times. is this normal?

this is my code:

```<code>  import 'package:flutter/material.dart';

  void main() {
    runApp(MyApp());
  }

  class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
      print("main");
      return MaterialApp(title: 'Provider Example', initialRoute: '/', routes: {
        '/': (context) => Page2(),
      });
    }
  }

  class Page2 extends StatelessWidget {
    Page2() {
      print("page2");
    }

    @override
    Widget build(BuildContext context) {
      return Container();
    }
  }
</code>```

this is the output:

```<code> Restarted application in 832ms.
 I/flutter ( 4439): main
 I/flutter ( 4439): page2    --> next two lines are the same, the widget is render again
 I/flutter ( 4439): main
 I/flutter ( 4439): page2
</code>```

答:
Flutter build method is what creates and return your rendered widget on the screen, so the build must be called everytime something change in the UI, and it need to rebuild. According to the Documentation

The build method will be called after:

After calling initState.

After calling didUpdateWidget.

After receiving a call to setState.

After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes).

After calling deactivate and then reinserting the State object into the tree at another location.

So even if you have a Stateless Widget, flutter can and will rebuild multiple times, this why you should avoid putting logic handlers inside your Widgets, specially the build, let this method as simple as possible with only what it actually needs to build the widget.

Also, during animations, transitions... Your widget will be rebuild a lot of times in order to perfom the animation. If you want to avoid unnecessary builds there's some ways you can do it, by making using of the const widgets, if you that a certain Widget won't change during runtime like a Text('Hi') this kind of Widget just need to be build once, so you can use a const keyword to it.

Body:
I am new to flutter. Something worries me, I don't know if it is normal. I know the code will render if the widget is of type StateFulWidget. But in this case, I have a stateLessWidget and for some reason it renders 2 times. is this normal?

this is my code:

  import 'package:flutter/material.dart';

  void main() {
    runApp(MyApp());
  }

  class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
      print("main");
      return MaterialApp(title: 'Provider Example', initialRoute: '/', routes: {
        '/': (context) => Page2(),
      });
    }
  }

  class Page2 extends StatelessWidget {
    Page2() {
      print("page2");
    }

    @override
    Widget build(BuildContext context) {
      return Container();
    }
  }

this is the output:

 Restarted application in 832ms.
 I/flutter ( 4439): main
 I/flutter ( 4439): page2    --> next two lines are the same, the widget is render again
 I/flutter ( 4439): main
 I/flutter ( 4439): page2


答:
In no particular order:

Use AJAX to get the data you need from the server.

Echo the data into the page somewhere, and use JavaScript to get the
information from the DOM.

Echo the data directly to JavaScript.

Check out this comment

Title: Change web-page color based on user's input from previous page

Body:
I have a form made in the previous page. In the form, I have a checklist with the options: red, green, blue.

If the user selects red, the next page's background color should be red. If green is selected, then the background color will be green. I am using PHP to do this.

Previous page

<form action="next_page.php method="POST>
  <input type="radio" name="color" value="red">
  <input type="radio" name="color" value="green">
  <input type="radio" name="color" value="blue">
</form>

Next Page

<?PHP
   $radioVal = $_POST["color"]
 ?>


问:
React when pass data to child throw props data duplicate
I'm create Activities function component  and call child function  component called Categories  when i send categories list to Categories function  component and log "props" data send twice first one is empty and second has data as follow

Activies

```<code>function Activities() {
 const [category, setCategory] = useState([]);

  function handelChange({ target }) {
    setCategory({
      ...category,
      [target.name]: target.value,
    });
  }

  useEffect(() => {
    getCategories().then((_categories) => setCategory(_categories));
  }, []);

 return (<Categories category={category} onChange={handelChange} />)

}
</code>```

and categories component

```<code>function Categories(props) {
 console.log(props);

return (<div></div>)
}
</code>```

i'm trying to log props in useEffect but problem still exist

答:
I think you handleChange function should update item in a array of object not change the state object completely

  function handelChange({ target: {name, value} }) {
    setCategory(categories => {
      const categoryIndex = categories.findIndex(pr => pr.id === id);
      const category = categories[categoryIndex];

      return [
        ...categories.slice(0, categoryIndex)),
        {
          ...category,
          [name]: value,
        },
      ...categories.slice(categoryIndex + 1))
    ]);
  }
```

Body:
I'm create Activities function component  and call child function  component called Categories  when i send categories list to Categories function  component and log "props" data send twice first one is empty and second has data as follow

Activies

function Activities() {
 const [category, setCategory] = useState([]);

  function handelChange({ target }) {
    setCategory({
      ...category,
      [target.name]: target.value,
    });
  }

  useEffect(() => {
    getCategories().then((_categories) => setCategory(_categories));
  }, []);

 return (<Categories category={category} onChange={handelChange} />)

}

and categories component

function Categories(props) {
 console.log(props);

return (

)
}

i'm trying to log props in useEffect but problem still exist


问:
Angular @Input() value is not changed when the value is same
When I run this program, initially I get the output as false, 5, 500 as I have initialized them in the child component like that, but when I try to click on update button, I am not able to revert to the previous values. I am expecting the output to be true, 10, 1000, but I am getting it as false, 5, 1000. Only the number which was different got changed.

How can I solve this issue so that I can get the values whatever I set in the parent component?

Link to stackblitz.

app-component.html

```<code><span (click)="clickme()">Update data</span>
</code>```

app-component.ts

```<code>export class AppComponent  {
  public parentBool: boolean;
  public parentNum: number;
  public p2: number;

  public ngOnInit(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 100;
  }

  public clickme(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 1000;
  }
}
</code>```

hello.component.ts

```<code>@Component({
  selector: 'hello-comp',
  template: `
    <div>
     Boolean value is - {{boolChild}} <br/>
     Number value is - {{numChild}} <br />
     Second number is - {{numChild2}}
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  @Input() boolChild: boolean;
  @Input() numChild: number;
  @Input() numChild2: number;

  public ngOnInit(): void {
    this.boolChild = false;
    this.numChild = 5;
    this.numChild2 = 500;
  }
  constructor(private _cd: ChangeDetectorRef){}

    public ngOnChanges(changes: {}): void {
      // this._cd.detectChanges();
      console.log(changes);
    }
}
</code>```

答:
This is how the input variables in the child component is initialized at the moment.

Initialize AppComponent, trigger ngOnInit and render the template.

Initialize MyComponent, trigger ngOnChanges. This will show in the console log as follows

```<code>{
  "boolChild": {
    "currentValue": true,
    "firstChange": true
  },
  "numChild": {
    "currentValue": 10,
    "firstChange": true
  },
  "numChild2": {
    "currentValue": 100,
    "firstChange": true
  }
}
</code>```

Trigger ngOnInit (note: this is triggered after ngOnChanges) in MyComponent assign values false, 5 and 500. This is the reason why these values are shown in the template and not the one sent initially from the AppComponent.

Click Update data button in the AppComponent which will push values true, 10 and 1000. It will show the following output

```<code>{
  "numChild2": {
    "previousValue": 100,
    "currentValue": 1000,
    "firstChange": false
  }
}
</code>```

Explanation

According to ngOnChanges in the MyComponent, the previous values were true, 10 and 100 (from the ngOnInit of the AppComponent). The values false, 5 and 500 were not registered by the ngOnChanges because they weren't changes through the Input(). And so changes shows the only object that has been changed from it's previous state, which is numChild2. The other 2 values stay the same and they aren't reflected in the ngOnChanges.

One solution would be to avoid assigning values in the ngOnInit() hook in the child and assigning the values during definition.

_boolChild: boolean = false;
_numChild: number = 5;
_numChild2: number = 500;
```

Even with these changes, you will still observe only numChild2 object in the changes variable when you click the button because that is how SimpleChanges works. It will only show the value that has been changed from it's previous state, it won't reflect the values that stay the same.

Here is the hook calling order for reference

OnChanges

OnInit

DoCheck

AfterContentInit

AfterContentChecked

AfterViewInit

AfterViewChecked

OnDestroy

Body:
When I run this program, initially I get the output as false, 5, 500 as I have initialized them in the child component like that, but when I try to click on update button, I am not able to revert to the previous values. I am expecting the output to be true, 10, 1000, but I am getting it as false, 5, 1000. Only the number which was different got changed.

How can I solve this issue so that I can get the values whatever I set in the parent component?

Link to stackblitz.

app-component.html

Update data

app-component.ts

export class AppComponent  {
  public parentBool: boolean;
  public parentNum: number;
  public p2: number;

  public ngOnInit(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 100;
  }

  public clickme(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 1000;
  }
}

hello.component.ts

@Component({
  selector: 'hello-comp',
  template: `

     Boolean value is - {{boolChild}}

     Number value is - {{numChild}}

     Second number is - {{numChild2}}

  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  @Input() boolChild: boolean;
  @Input() numChild: number;
  @Input() numChild2: number;

  public ngOnInit(): void {
    this.boolChild = false;
    this.numChild = 5;
    this.numChild2 = 500;
  }
  constructor(private _cd: ChangeDetectorRef){}

    public ngOnChanges(changes: {}): void {
      // this._cd.detectChanges();
      console.log(changes);
    }
}

Body:
This is how the input variables in the child component is initialized at the moment.

Initialize AppComponent, trigger ngOnInit and render the template.

Initialize MyComponent, trigger ngOnChanges. This will show in the console log as follows

{
  "boolChild": {
    "currentValue": true,
    "firstChange": true
  },
  "numChild": {
    "currentValue": 10,
    "firstChange": true
  },
  "numChild2": {
    "currentValue": 100,
    "firstChange": true
  }
}

Trigger ngOnInit (note: this is triggered after ngOnChanges) in MyComponent assign values false, 5 and 500. This is the reason why these values are shown in the template and not the one sent initially from the AppComponent.

Click Update data button in the AppComponent which will push values true, 10 and 1000. It will show the following output

{
  "numChild2": {
    "previousValue": 100,
    "currentValue": 1000,
    "firstChange": false
  }
}

Explanation

According to ngOnChanges in the MyComponent, the previous values were true, 10 and 100 (from the ngOnInit of the AppComponent). The values false, 5 and 500 were not registered by the ngOnChanges because they weren't changes through the Input(). And so changes shows the only object that has been changed from it's previous state, which is numChild2. The other 2 values stay the same and they aren't reflected in the ngOnChanges.

One solution would be to avoid assigning values in the ngOnInit() hook in the child and assigning the values during definition.

_boolChild: boolean = false;
_numChild: number = 5;
_numChild2: number = 500;

Even with these changes, you will still observe only numChild2 object in the changes variable when you click the button because that is how SimpleChanges works. It will only show the value that has been changed from it's previous state, it won't reflect the values that stay the same.

Here is the hook calling order for reference

OnChanges

OnInit

DoCheck

AfterContentInit

AfterContentChecked

AfterViewInit

AfterViewChecked

OnDestroy


问:
RaycastHit2D stops working when another Coroutine is active. Unity2D Platformer, WebGL
I'm working on an Unity project, it is a classic Mario style 2D Platformer.
The occuring problems are with an enemy, the known Snail, which can be kicked away when it is stunned.

There are two functions, both work on their own, but doesn't work together. The project Build has been exportet as WebGL, to be playable in the browser.

1. ChangeDirection:

ChangeDirection() is a Coroutine and is called in the Start-Function. It flips the sprite and moving direction of the snail, when it reaches the end of a platform.

2. CheckCollision:

CheckCollision is called in the Update-Function and detects Collisions on 4 GameObjects, which are attached to the snail.

Problem Description:

When I outcomment "StartCoroutine(ChangeDirection());" inside the Start-Function, CheckCollision works fine. I can stun the snail and kick it away, after it has been stunned.

When I put the ChangeDirection()-Coroutine back, the snail changes its direction perfectly. Also the top_Collision can be detected. I can stun the snail and it changes the animation and stops moving, but the left and right Collision seems to stop working, so that I can not kick the snail away, after it has been stunned.

Assumption:

The ChangeDirection() Coroutine doesn't prevent CheckCollision() completely from working, because the detection of the top collision still works. topHit is a Collider2D, but leftHit and rightHit are RaycastHit2D. Somehow the RaycastHit2D doesn't work with ChangeDirection() Coroutine activated at the same time.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SnailScript : MonoBehaviour
{

    public float moveSpeed = 1f;
    private Rigidbody2D myBody;
    private Animator anim;

    public LayerMask playerLayer;

    private bool moveLeft;

    private bool canMove;
    private bool stunned;

    public Transform left_Collision, right_Collision, top_Collision, down_Collision;
    private Vector3 left_Collision_Pos, right_Collision_Pos;

    void Awake()
    {
        myBody = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();

        left_Collision_Pos = left_Collision.position;
        right_Collision_Pos = right_Collision.position;
    }

    void Start()
    {
        moveLeft = true;
        canMove = true;
        StartCoroutine(ChangeDirection());
    }

    void Update()
    {
        if (canMove)
        {
            if (moveLeft)
            {
                myBody.velocity = new Vector2(-moveSpeed, myBody.velocity.y);
            }
            else
            {
                myBody.velocity = new Vector2(moveSpeed, myBody.velocity.y);
            }
        }

        CheckCollision();

    }

    void CheckCollision()
    {
        //ATACHED GAMEOBJECTS FOR COLLISION DETECTION
        RaycastHit2D leftHit = Physics2D.Raycast(left_Collision.position, Vector2.left, 0.1f, playerLayer);
        RaycastHit2D rightHit = Physics2D.Raycast(right_Collision.position, Vector2.right, 0.1f, playerLayer);

        Collider2D topHit = Physics2D.OverlapCircle(top_Collision.position, 0.2f, playerLayer);

        if (topHit != null)
        {
            if (topHit.gameObject.CompareTag(MyTags.PLAYER_TAG))
            {
                if (!stunned)
                {
                    //Player does a little rebounce after jumping on the snail
                    topHit.gameObject.GetComponent<Rigidbody2D>().velocity =
                        new Vector2(topHit.gameObject.GetComponent<Rigidbody2D>().velocity.x, 7f);

                    canMove = false;
                    myBody.velocity = new Vector2(0, 0);

                    anim.Play("Stunned");
                    stunned = true;
                }
            }
        }

        if (leftHit)
        {
            if (leftHit.collider.gameObject.CompareTag(MyTags.PLAYER_TAG))
            {
                if (stunned)
                {
                    //SNAIL KICKED TO THE RIGHT
                    myBody.velocity = new Vector2(15f, myBody.velocity.y);
                }
            }
        }

        if (rightHit)
        {
            if (rightHit.collider.gameObject.CompareTag(MyTags.PLAYER_TAG))
            {
                if (stunned)
                {
                    //SNAIL KICKED TO THE LEFT
                    myBody.velocity = new Vector2(-15f, myBody.velocity.y);
                }
            }
        }
    }

    IEnumerator ChangeDirection()
    {
        if (!Physics2D.Raycast(down_Collision.position, Vector2.down, 0.1f))
        {
            moveLeft = !moveLeft;

            Vector3 tempScale = transform.localScale;

            if (moveLeft)
            {
                //SNAIL LOOKS TO THE LEFT
                tempScale.x = Mathf.Abs(tempScale.x);

                //Changing position of the attached GameObjects for collision detection
                left_Collision.position = left_Collision_Pos;
                right_Collision.position = right_Collision_Pos;

            }
            else
            {
                tempScale.x = -Mathf.Abs(tempScale.x);

                left_Collision.position = right_Collision_Pos;
                right_Collision.position = left_Collision_Pos;
            }

            //new sprite-orientation
            transform.localScale = tempScale;
        }

        yield return new WaitForSeconds(0.5f);

        StartCoroutine(ChangeDirection());
    }
}
</code>```

答:
As I finally found out, RaycastHit2D doesn't work very well, when you export your build as WebGL. I assume the older code should have worked without WebGL.

I found a way to replace the RaycastHit2D with a simple OnCollisionEnter2D, where I additional checked the position of the player relatively to the snail, to determine if it is a left or right collision. Now it works fine.

```<code>    //SNAIL GETS KICKED AWAY
private void OnCollisionEnter2D(Collision2D collision)
{
    if ((collision.gameObject.tag == "Player") && (stunned))
    {
                            //                 Player    -    Snail
        if( ((collision.gameObject.transform.position.x) - (gameObject.transform.position.x)) <= 0f)
        {
            //Player stands left to snail, Snail must be kicked to the right!
            myBody.velocity = new Vector2(15f, myBody.velocity.y);
        }
        else
        {
            myBody.velocity = new Vector2(-15f, myBody.velocity.y);
        }

        if (((collision.gameObject.transform.position.y) - (gameObject.transform.position.y)) >= 0.2f)
        {
            //Player does a little Rebounce, when higher than the snail
            collision.gameObject.GetComponent<Rigidbody2D>().velocity =
                    new Vector2(collision.gameObject.GetComponent<Rigidbody2D>().velocity.x, 7f);
        }

        StartCoroutine(Dead(3f));
    }
}
</code>```

Body:
I'm working on an Unity project, it is a classic Mario style 2D Platformer.
The occuring problems are with an enemy, the known Snail, which can be kicked away when it is stunned.

There are two functions, both work on their own, but doesn't work together. The project Build has been exportet as WebGL, to be playable in the browser.

1. ChangeDirection:

ChangeDirection() is a Coroutine and is called in the Start-Function. It flips the sprite and moving direction of the snail, when it reaches the end of a platform.

2. CheckCollision:

CheckCollision is called in the Update-Function and detects Collisions on 4 GameObjects, which are attached to the snail.

Problem Description:

When I outcomment "StartCoroutine(ChangeDirection());" inside the Start-Function, CheckCollision works fine. I can stun the snail and kick it away, after it has been stunned.

When I put the ChangeDirection()-Coroutine back, the snail changes its direction perfectly. Also the top_Collision can be detected. I can stun the snail and it changes the animation and stops moving, but the left and right Collision seems to stop working, so that I can not kick the snail away, after it has been stunned.

Assumption:

The ChangeDirection() Coroutine doesn't prevent CheckCollision() completely from working, because the detection of the top collision still works. topHit is a Collider2D, but leftHit and rightHit are RaycastHit2D. Somehow the RaycastHit2D doesn't work with ChangeDirection() Coroutine activated at the same time.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SnailScript : MonoBehaviour
{

    public float moveSpeed = 1f;
    private Rigidbody2D myBody;
    private Animator anim;

    public LayerMask playerLayer;

    private bool moveLeft;

    private bool canMove;
    private bool stunned;

    public Transform left_Collision, right_Collision, top_Collision, down_Collision;
    private Vector3 left_Collision_Pos, right_Collision_Pos;

    void Awake()
    {
        myBody = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();

        left_Collision_Pos = left_Collision.position;
        right_Collision_Pos = right_Collision.position;
    }

    void Start()
    {
        moveLeft = true;
        canMove = true;
        StartCoroutine(ChangeDirection());
    }

    void Update()
    {
        if (canMove)
        {
            if (moveLeft)
            {
                myBody.velocity = new Vector2(-moveSpeed, myBody.velocity.y);
            }
            else
            {
                myBody.velocity = new Vector2(moveSpeed, myBody.velocity.y);
            }
        }

        CheckCollision();

    }

    void CheckCollision()
    {
        //ATACHED GAMEOBJECTS FOR COLLISION DETECTION
        RaycastHit2D leftHit = Physics2D.Raycast(left_Collision.position, Vector2.left, 0.1f, playerLayer);
        RaycastHit2D rightHit = Physics2D.Raycast(right_Collision.position, Vector2.right, 0.1f, playerLayer);

        Collider2D topHit = Physics2D.OverlapCircle(top_Collision.position, 0.2f, playerLayer);

        if (topHit != null)
        {
            if (topHit.gameObject.CompareTag(MyTags.PLAYER_TAG))
            {
                if (!stunned)
                {
                    //Player does a little rebounce after jumping on the snail
                    topHit.gameObject.GetComponent<Rigidbody2D>().velocity =
                        new Vector2(topHit.gameObject.GetComponent<Rigidbody2D>().velocity.x, 7f);

                    canMove = false;
                    myBody.velocity = new Vector2(0, 0);

                    anim.Play("Stunned");
                    stunned = true;
                }
            }
        }

        if (leftHit)
        {
            if (leftHit.collider.gameObject.CompareTag(MyTags.PLAYER_TAG))
            {
                if (stunned)
                {
                    //SNAIL KICKED TO THE RIGHT
                    myBody.velocity = new Vector2(15f, myBody.velocity.y);
                }
            }
        }

        if (rightHit)
        {
            if (rightHit.collider.gameObject.CompareTag(MyTags.PLAYER_TAG))
            {
                if (stunned)
                {
                    //SNAIL KICKED TO THE LEFT
                    myBody.velocity = new Vector2(-15f, myBody.velocity.y);
                }
            }
        }
    }

    IEnumerator ChangeDirection()
    {
        if (!Physics2D.Raycast(down_Collision.position, Vector2.down, 0.1f))
        {
            moveLeft = !moveLeft;

            Vector3 tempScale = transform.localScale;

            if (moveLeft)
            {
                //SNAIL LOOKS TO THE LEFT
                tempScale.x = Mathf.Abs(tempScale.x);

                //Changing position of the attached GameObjects for collision detection
                left_Collision.position = left_Collision_Pos;
                right_Collision.position = right_Collision_Pos;

            }
            else
            {
                tempScale.x = -Mathf.Abs(tempScale.x);

                left_Collision.position = right_Collision_Pos;
                right_Collision.position = left_Collision_Pos;
            }

            //new sprite-orientation
            transform.localScale = tempScale;
        }

        yield return new WaitForSeconds(0.5f);

        StartCoroutine(ChangeDirection());
    }
}

Body:
As I finally found out, RaycastHit2D doesn't work very well, when you export your build as WebGL. I assume the older code should have worked without WebGL.

I found a way to replace the RaycastHit2D with a simple OnCollisionEnter2D, where I additional checked the position of the player relatively to the snail, to determine if it is a left or right collision. Now it works fine.

    //SNAIL GETS KICKED AWAY
private void OnCollisionEnter2D(Collision2D collision)
{
    if ((collision.gameObject.tag == "Player") && (stunned))
    {
                            //                 Player    -    Snail
        if( ((collision.gameObject.transform.position.x) - (gameObject.transform.position.x)) <= 0f)
        {
            //Player stands left to snail, Snail must be kicked to the right!
            myBody.velocity = new Vector2(15f, myBody.velocity.y);
        }
        else
        {
            myBody.velocity = new Vector2(-15f, myBody.velocity.y);
        }

        if (((collision.gameObject.transform.position.y) - (gameObject.transform.position.y)) >= 0.2f)
        {
            //Player does a little Rebounce, when higher than the snail
            collision.gameObject.GetComponent<Rigidbody2D>().velocity =
                    new Vector2(collision.gameObject.GetComponent<Rigidbody2D>().velocity.x, 7f);
        }

        StartCoroutine(Dead(3f));
    }
}


问:
how can I create Observable form property of the Redux Store State?
I have redux store and state for example :

```<code>export class CustomerState
{
 customerId: Number;
 customerInformation: any;
}
</code>```

I have access to store in my component and I would like get observable only from customerId.
In angular this can be done by select:

```<code>@select((s: CustomerState ) => s.CustomerState.customerId)
customerId$: Observable<Number>;
</code>```

but this is redux store and not angular component

Is this possible to achieve in Redux store?

答:
In Redux, the store (app state) is an immutable object, meaning it's properties are never changed. Instead, whenever the store is updated, the object is replaced entirely by the new object returned by your reducer function. So you can't actually observe a property of the Store. Instead, you subscribe to changes to the store, which is an observable, and then use a pattern like this one to determine if a property has changed:

https://redux.js.org/api/store#subscribelistener

```<code>function select(state) {
  return state.some.deep.property
}

let currentValue
function handleChange() {
  let previousValue = currentValue
  currentValue = select(store.getState())

  if (previousValue !== currentValue) {
    console.log(
      'Some deep nested property changed from',
      previousValue,
      'to',
      currentValue
    )
  }
}

const unsubscribe = store.subscribe(handleChange)
unsubscribe()
</code>```

Body:
I have redux store and state for example :

export class CustomerState
{
 customerId: Number;
 customerInformation: any;
}

I have access to store in my component and I would like get observable only from customerId.
In angular this can be done by select:

@select((s: CustomerState ) => s.CustomerState.customerId)
customerId$: Observable<Number>;

but this is redux store and not angular component

Is this possible to achieve in Redux store?

Body:
In Redux, the store (app state) is an immutable object, meaning it's properties are never changed. Instead, whenever the store is updated, the object is replaced entirely by the new object returned by your reducer function. So you can't actually observe a property of the Store. Instead, you subscribe to changes to the store, which is an observable, and then use a pattern like this one to determine if a property has changed:

https://redux.js.org/api/store#subscribelistener

function select(state) {
  return state.some.deep.property
}

let currentValue
function handleChange() {
  let previousValue = currentValue
  currentValue = select(store.getState())

  if (previousValue !== currentValue) {
    console.log(
      'Some deep nested property changed from',
      previousValue,
      'to',
      currentValue
    )
  }
}

const unsubscribe = store.subscribe(handleChange)
unsubscribe()


问:
find_all() method from BeautifulSoup returns empty list
I am new to programming and also new to pyhon.

My intension is to built an ebay webscraper.

I am trying to extract an list of links with the bs4 find_all() method, but no matter what I try, it returns always an empty list.

```<code>def get_index_data(soup):

    try:
        links = soup.find_all('a', {'class': 's-item__link'})
        print(links)
    except:
        links = []
        print(links)
</code>```

I wrote it also that way.

```<code>links = soup.find_all('a', class_= 's-item__link')
</code>```

It also returns an empty list. I absolutely don´t know what is wrong

Edit:

```<code>    import requests
from bs4 import BeautifulSoup

def get_page(url):

    response = requests.get(url)

    if not response.ok:
        print('server responded: ', response.status_code)
    else:
        soup = BeautifulSoup(response.text, 'lxml')
    return soup

def get_index_data(soup):
    links = soup.find_all('a')

    print(links)

def main():

    url = 'https://www.ebay.de/sch/i.html?_nkw=armbanduhr&_pgn=1 '
    get_index_data(get_page(url))

if __name__ == '__main__':
    main()
</code>```

Edit2

Error after I run the code with only .find_all('a')

```<code>Traceback (most recent call last):
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 29, in <module>
    main()
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 25, in main
    get_index_data(get_page(url))
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 19, in get_index_data
    print(links)
  File "C:\Users\Aleksandar\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 28776: character maps to <undefined>
</code>```

答:
BeautifulSoup has a few different types of parsers for different situations. In the past I have stuck with the "html.parser" instead of "lxml". Sometimes using "lxml" will actually return None in a situation where "html.parser" will return a result.

That could be why you get your error messages and the empty result, i'd try that. When I wrote up something similar to yours it worked. Since the a tag is used alot you're probably going to get a huge chunk of stuff to parse through but if you change from lxml to html.parser it should work!

Web scraping can be tough to get the hang of but once you do it's really fun to do. There are really great videos that talk about beautifulsoup on Youtube.

Body:
I am new to programming and also new to pyhon.

My intension is to built an ebay webscraper.

I am trying to extract an list of links with the bs4 find_all() method, but no matter what I try, it returns always an empty list.

def get_index_data(soup):

    try:
        links = soup.find_all('a', {'class': 's-item__link'})
        print(links)
    except:
        links = []
        print(links)

I wrote it also that way.

links = soup.find_all('a', class_= 's-item__link')

It also returns an empty list. I absolutely don´t know what is wrong

Edit:

    import requests
from bs4 import BeautifulSoup

def get_page(url):

    response = requests.get(url)

    if not response.ok:
        print('server responded: ', response.status_code)
    else:
        soup = BeautifulSoup(response.text, 'lxml')
    return soup

def get_index_data(soup):
    links = soup.find_all('a')

    print(links)

def main():

    url = 'https://www.ebay.de/sch/i.html?_nkw=armbanduhr&_pgn=1 '
    get_index_data(get_page(url))

if __name__ == '__main__':
    main()

Edit2

Error after I run the code with only .find_all('a')

Traceback (most recent call last):
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 29, in <module>
    main()
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 25, in main
    get_index_data(get_page(url))
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 19, in get_index_data
    print(links)
  File "C:\Users\Aleksandar\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 28776: character maps to <undefined>


问:
Fish game "NameError" . 'shark' is not defined?
I'm doing a game on pygame and i'm facing a problem and i'm trying to figure out the problem i'm facing. and i dont know the solution. I'm getting following error msg:

I'm getting following error msg:

shark = enemy(-389,410,170,71,-389, 1360)
TypeError: enemy() takes no arguments
does anyone know where is the error?
.

class enemy (object):
    walkRight= [pygame.image.load('shark\R\R1.png').convert()
    pygame.image.load('shark\R\R2.png').convert()
    pygame.image.load('shark\R\R3.png').convert()
    pygame.image.load('shark\R\R4.png').convert()
    pygame.image.load('shark\R\R5.png').convert()
    pygame.image.load('shark\R\R6.png').convert()
    pygame.image.load('shark\R\R7.png').convert()
    pygame.image.load('shark\R\R8.png').convert()
    pygame.image.load('shark\R\R9.png').convert()
    pygame.image.load('shark\R\R10.png').convert()
    pygame.image.load('shark\R\R11.png').convert()
    pygame.image.load('shark\R\R12.png').convert()
    pygame.image.load('shark\R\R13.png').convert()
    pygame.image.load('shark\R\R14.png').convert()
    pygame.image.load('shark\R\R15.png').convert()
    pygame.image.load('shark\R\R16.png').convert()
    pygame.image.load('shark\R\R17.png').convert()
    pygame.image.load('shark\R\R18.png').convert()
    pygame.image.load('shark\R\R19.png').convert()]

walkLeft = [pygame.image.load('shark\L\L1.png').convert()
pygame.image.load('shark\L\L2.png').convert()
pygame.image.load('shark\L\L3.png').convert()
pygame.image.load('shark\L\L4.png').convert()
pygame.image.load('shark\L\L5.png').convert()
pygame.image.load('shark\L\L6.png').convert()
pygame.image.load('shark\L\L7.png').convert()
pygame.image.load('shark\L\L8.png').convert()
pygame.image.load('shark\L\L9.png').convert()
pygame.image.load('shark\L\L10.png').convert()
pygame.image.load('shark\L\L11.png').convert()
pygame.image.load('shark\L\L12.png').convert()
pygame.image.load('shark\L\L13.png').convert()
pygame.image.load('shark\L\L14.png').convert()
pygame.image.load('shark\L\L15.png').convert()
pygame.image.load('shark\L\L16.png').convert()
pygame.image.load('shark\L\L17.png').convert()
pygame.image.load('shark\L\L18.png').convert()
pygame.image.load('shark\L\L19.png').convert()]

def __init__(self, x, y, width, hight, start, end):
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.start = start
    self.end = end
    self.walkCount = 0
    self.vel = 7

def draw(self, surface):
    self.move()
    if self.walkCount +1 >=57:
        self.walkCount = 0

        if self.vel > 0:
            surface.blit(pygame.transform.scale(self.walkRight[self.walkCount//3,], (self.width, self.height)),(self.x, self.y))
            self.walkCount +=1

    else:
        surface.blit(pygame.transform.scale(self.walkLeft[self.walkCount//3,], (self.width, self.height)),(self.x, self.y))
        self.walkCount += 1

def move(self):
    if self.vel > 0:
        if self.x < self.end + self.vel:
            self.x += self.vel
        else:
            self.vel = self.vel * -1
            self.x += self.vel
            self.walkCount = 0

def redrawwindow():
    global fish
    surface.blit (poisson, (0,0))
    fish.draw(surface)
    shark.draw(surface)
    shark1.draw(surface)
    shark2.draw(surface)
    shark3.draw(surface)
    global vie

if(shark.vel > 0 and fish.x < shark.x + shark.width and fish.x>=shark.x and fish.y <= shark.y + shark.height and fish.y >= shark.y):
   vie= vie-1

   fish = player(0, 0, 64, 64)

elif(shark.vel < 0 and  fish.x+fish.width > shark.x and fish.x<=shark.x and fish.y<= shark.y + shark.height and fish.y>= shark.y):
    vie= vie-1
    fish = player(0, 0, 64, 64)

if vie ==0:
    print ("Game Over")

pygame.display.update()

 #mainloop
fish = player(300,410,64,64)
shark= enemy(-389,410,170,71,-389, 1360)
shark1= enemy(900,180, 170,71 ,-120, 1360)
shark2= enemy(600,300, 170,71 ,-300, 1360)
shark3= enemy(300,550, 170,71 ,-500, 1360)`
```

I'm getting another error:

shark = enemy(-389,410,170,71,-389, 1360)
  TypeError: enemy() takes no arguments

Does anyone knows where is the error?

答:
These lines:

```<code> #mainloop
fish = player(300,410,64,64)
shark= enemy(-389,410,170,71,-389, 1360)
shark1= enemy(900,180, 170,71 ,-120, 1360)
shark2= enemy(600,300, 170,71 ,-300, 1360)
shark3= enemy(300,550, 170,71 ,-500, 1360)
</code>```

where you assign/define these various objects, are at the end of your program. That is AFTER you have tried to use them in the lines above.

You need these lines earlier, probably just before def redrawwindow(): would be fine.

Two other things though. I am not sure if it is a copy paste issue, but your indenting in the enemy class is wrong.
Also I am pretty sure that you intend all those loads to be part of a list assignment. Like this:

```<code>walkRight= [pygame.image.load('shark\R\R1.png').convert(),
    pygame.image.load('shark\R\R2.png').convert(),
    pygame.image.load('shark\R\R3.png').convert(),
    pygame.image.load('shark\R\R4.png').convert(),
    pygame.image.load('shark\R\R5.png').convert(),
    pygame.image.load('shark\R\R6.png').convert(),
    pygame.image.load('shark\R\R7.png').convert(),
    pygame.image.load('shark\R\R8.png').convert(),
    pygame.image.load('shark\R\R9.png').convert(),
    pygame.image.load('shark\R\R10.png').convert(),
    pygame.image.load('shark\R\R11.png').convert(),
    pygame.image.load('shark\R\R12.png').convert(),
    pygame.image.load('shark\R\R13.png').convert(),
    pygame.image.load('shark\R\R14.png').convert(),
    pygame.image.load('shark\R\R15.png').convert(),
    pygame.image.load('shark\R\R16.png').convert(),
    pygame.image.load('shark\R\R17.png').convert(),
    pygame.image.load('shark\R\R18.png').convert(),
    pygame.image.load('shark\R\R19.png').convert()]

walkLeft =  pygame.image.load('shark\L\L1.png').convert(),
    pygame.image.load('shark\L\L2.png').convert(),
    pygame.image.load('shark\L\L3.png').convert(),
    pygame.image.load('shark\L\L4.png').convert(),
    pygame.image.load('shark\L\L5.png').convert(),
    pygame.image.load('shark\L\L6.png').convert(),
    pygame.image.load('shark\L\L7.png').convert(),
    pygame.image.load('shark\L\L8.png').convert(),
    pygame.image.load('shark\L\L9.png').convert(),
    pygame.image.load('shark\L\L10.png').convert(),
    pygame.image.load('shark\L\L11.png').convert(),
    pygame.image.load('shark\L\L12.png').convert(),
    pygame.image.load('shark\L\L13.png').convert(),
    pygame.image.load('shark\L\L14.png').convert(),
    pygame.image.load('shark\L\L15.png').convert(),
    pygame.image.load('shark\L\L16.png').convert(),
    pygame.image.load('shark\L\L17.png').convert(),
    pygame.image.load('shark\L\L18.png').convert(),
    pygame.image.load('shark\L\L19.png').convert()]
</code>```

Not just loaded and then having the result discarded.

Body:
I'm doing a game on pygame and i'm facing a problem and i'm trying to figure out the problem i'm facing. and i dont know the solution. I'm getting following error msg:

I'm getting following error msg:

shark = enemy(-389,410,170,71,-389, 1360)
TypeError: enemy() takes no arguments
does anyone know where is the error?
.

class enemy (object):
    walkRight= [pygame.image.load('shark\R\R1.png').convert()
    pygame.image.load('shark\R\R2.png').convert()
    pygame.image.load('shark\R\R3.png').convert()
    pygame.image.load('shark\R\R4.png').convert()
    pygame.image.load('shark\R\R5.png').convert()
    pygame.image.load('shark\R\R6.png').convert()
    pygame.image.load('shark\R\R7.png').convert()
    pygame.image.load('shark\R\R8.png').convert()
    pygame.image.load('shark\R\R9.png').convert()
    pygame.image.load('shark\R\R10.png').convert()
    pygame.image.load('shark\R\R11.png').convert()
    pygame.image.load('shark\R\R12.png').convert()
    pygame.image.load('shark\R\R13.png').convert()
    pygame.image.load('shark\R\R14.png').convert()
    pygame.image.load('shark\R\R15.png').convert()
    pygame.image.load('shark\R\R16.png').convert()
    pygame.image.load('shark\R\R17.png').convert()
    pygame.image.load('shark\R\R18.png').convert()
    pygame.image.load('shark\R\R19.png').convert()]

walkLeft = [pygame.image.load('shark\L\L1.png').convert()
pygame.image.load('shark\L\L2.png').convert()
pygame.image.load('shark\L\L3.png').convert()
pygame.image.load('shark\L\L4.png').convert()
pygame.image.load('shark\L\L5.png').convert()
pygame.image.load('shark\L\L6.png').convert()
pygame.image.load('shark\L\L7.png').convert()
pygame.image.load('shark\L\L8.png').convert()
pygame.image.load('shark\L\L9.png').convert()
pygame.image.load('shark\L\L10.png').convert()
pygame.image.load('shark\L\L11.png').convert()
pygame.image.load('shark\L\L12.png').convert()
pygame.image.load('shark\L\L13.png').convert()
pygame.image.load('shark\L\L14.png').convert()
pygame.image.load('shark\L\L15.png').convert()
pygame.image.load('shark\L\L16.png').convert()
pygame.image.load('shark\L\L17.png').convert()
pygame.image.load('shark\L\L18.png').convert()
pygame.image.load('shark\L\L19.png').convert()]

def __init__(self, x, y, width, hight, start, end):
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.start = start
    self.end = end
    self.walkCount = 0
    self.vel = 7

def draw(self, surface):
    self.move()
    if self.walkCount +1 >=57:
        self.walkCount = 0

        if self.vel > 0:
            surface.blit(pygame.transform.scale(self.walkRight[self.walkCount//3,], (self.width, self.height)),(self.x, self.y))
            self.walkCount +=1

    else:
        surface.blit(pygame.transform.scale(self.walkLeft[self.walkCount//3,], (self.width, self.height)),(self.x, self.y))
        self.walkCount += 1

def move(self):
    if self.vel > 0:
        if self.x < self.end + self.vel:
            self.x += self.vel
        else:
            self.vel = self.vel * -1
            self.x += self.vel
            self.walkCount = 0

def redrawwindow():
    global fish
    surface.blit (poisson, (0,0))
    fish.draw(surface)
    shark.draw(surface)
    shark1.draw(surface)
    shark2.draw(surface)
    shark3.draw(surface)
    global vie

if(shark.vel > 0 and fish.x < shark.x + shark.width and fish.x>=shark.x and fish.y <= shark.y + shark.height and fish.y >= shark.y):
   vie= vie-1

   fish = player(0, 0, 64, 64)

elif(shark.vel < 0 and  fish.x+fish.width > shark.x and fish.x<=shark.x and fish.y<= shark.y + shark.height and fish.y>= shark.y):
    vie= vie-1
    fish = player(0, 0, 64, 64)

if vie ==0:
    print ("Game Over")

pygame.display.update()

 #mainloop
fish = player(300,410,64,64)
shark= enemy(-389,410,170,71,-389, 1360)
shark1= enemy(900,180, 170,71 ,-120, 1360)
shark2= enemy(600,300, 170,71 ,-300, 1360)
shark3= enemy(300,550, 170,71 ,-500, 1360)`

I'm getting another error:

shark = enemy(-389,410,170,71,-389, 1360)
  TypeError: enemy() takes no arguments

Does anyone knows where is the error?

Body:
These lines:

 #mainloop
fish = player(300,410,64,64)
shark= enemy(-389,410,170,71,-389, 1360)
shark1= enemy(900,180, 170,71 ,-120, 1360)
shark2= enemy(600,300, 170,71 ,-300, 1360)
shark3= enemy(300,550, 170,71 ,-500, 1360)

where you assign/define these various objects, are at the end of your program. That is AFTER you have tried to use them in the lines above.

You need these lines earlier, probably just before def redrawwindow(): would be fine.

Two other things though. I am not sure if it is a copy paste issue, but your indenting in the enemy class is wrong.
Also I am pretty sure that you intend all those loads to be part of a list assignment. Like this:

walkRight= [pygame.image.load('shark\R\R1.png').convert(),
    pygame.image.load('shark\R\R2.png').convert(),
    pygame.image.load('shark\R\R3.png').convert(),
    pygame.image.load('shark\R\R4.png').convert(),
    pygame.image.load('shark\R\R5.png').convert(),
    pygame.image.load('shark\R\R6.png').convert(),
    pygame.image.load('shark\R\R7.png').convert(),
    pygame.image.load('shark\R\R8.png').convert(),
    pygame.image.load('shark\R\R9.png').convert(),
    pygame.image.load('shark\R\R10.png').convert(),
    pygame.image.load('shark\R\R11.png').convert(),
    pygame.image.load('shark\R\R12.png').convert(),
    pygame.image.load('shark\R\R13.png').convert(),
    pygame.image.load('shark\R\R14.png').convert(),
    pygame.image.load('shark\R\R15.png').convert(),
    pygame.image.load('shark\R\R16.png').convert(),
    pygame.image.load('shark\R\R17.png').convert(),
    pygame.image.load('shark\R\R18.png').convert(),
    pygame.image.load('shark\R\R19.png').convert()]

walkLeft =  pygame.image.load('shark\L\L1.png').convert(),
    pygame.image.load('shark\L\L2.png').convert(),
    pygame.image.load('shark\L\L3.png').convert(),
    pygame.image.load('shark\L\L4.png').convert(),
    pygame.image.load('shark\L\L5.png').convert(),
    pygame.image.load('shark\L\L6.png').convert(),
    pygame.image.load('shark\L\L7.png').convert(),
    pygame.image.load('shark\L\L8.png').convert(),
    pygame.image.load('shark\L\L9.png').convert(),
    pygame.image.load('shark\L\L10.png').convert(),
    pygame.image.load('shark\L\L11.png').convert(),
    pygame.image.load('shark\L\L12.png').convert(),
    pygame.image.load('shark\L\L13.png').convert(),
    pygame.image.load('shark\L\L14.png').convert(),
    pygame.image.load('shark\L\L15.png').convert(),
    pygame.image.load('shark\L\L16.png').convert(),
    pygame.image.load('shark\L\L17.png').convert(),
    pygame.image.load('shark\L\L18.png').convert(),
    pygame.image.load('shark\L\L19.png').convert()]

Not just loaded and then having the result discarded.


答:
have you tried calling detectChanges before anything else?

```<code>  ngOnInit() {
    this._cd.detectChanges();
    ....rest of your code...
  }
</code>```

Btw, I don't understand why you are setting the same values in the ngOnInit() as on line 14 & 15. Actually you don't need to...

Title: Angular @Input() value is not changed when the value is same

Body:
have you tried calling detectChanges before anything else?

  ngOnInit() {
    this._cd.detectChanges();
    ....rest of your code...
  }

Btw, I don't understand why you are setting the same values in the ngOnInit() as on line 14 & 15. Actually you don't need to...


问:
Find out which request was used to perform an action
How can i see what request was used to perform a specific action on a website ?
For example adding a product to cart ?
I know its most likely via the chrome dev console but I am not sure would appreciate a beginner friendly response :)</p>

答:
There are a few ways, easiest one could be to just look at the network tab in Chrome dev tools, (filter by XHR), perform an action, and just see what appears as the last item in the list.

2nd:
Open the Chrome dev tools, go to sources tab, then on the right side, select XHR breaking point, you can select any, or provide a specific URL.


问:
ISODate format in mongodb version
I had restored MongoDB server version: 4.2.3 to MongoDB server version: 4.2.7 and I had an error about ISODate as below when saving data to the database again:

```<code>{ "_id" : ObjectId("5ed4b193ed6fab6d2272c5c4"), "id" : 1, "timestamp" : ISODate("2020-05-31T05:59:59Z") } #new data run after change db (it must disappear for unique)
{ "_id" : ObjectId("5ed33bef1e499012bf35e412"), "id" : 1, "timestamp" : ISODate("2020-05-31T04:59:59.999Z") } #old data
{ "_id" : ObjectId("5ed4b193ed6fab6d2272c5c3"), "id" : 1, "timestamp" : ISODate("2020-05-31T04:59:59Z") } #new data run after change db (it must disappear for unique)
{ "_id" : ObjectId("5ed32de165269b416f6c7362"), "id" : 1, "timestamp" : ISODate("2020-05-31T03:59:59.999Z") } #old data
{ "_id" : ObjectId("5ed4b193ed6fab6d2272c5c2"), "id" : 1, "timestamp" : ISODate("2020-05-31T03:59:59Z") } #new data run after change db (it must disappear for unique)
{ "_id" : ObjectId("5ed31fcff2a5076cc947bc02"), "id" : 1, "timestamp" : ISODate("2020-05-31T02:59:59.999Z") } #old data
{ "_id" : ObjectId("5ed311bfb0d88300f81e90d2"), "id" : 1, "timestamp" : ISODate("2020-05-31T01:59:59.999Z") } #old data
</code>```

I have an index id and timestamp which is unique, but because timestamp has microseconds, not exactly so. Please give me a solution to keep microseconds in an ISODate.

PS: my code did not change. I use PHP and always format dates with 'Y-m-d\TH:i:s.uP'

答: MongoDB time resolution is 1 millisecond. Values with more precision will be truncated to millisecond precision.</p>

Title: ISODate format in mongodb version

Body:
I had restored MongoDB server version: 4.2.3 to MongoDB server version: 4.2.7 and I had an error about ISODate as below when saving data to the database again:

{ "_id" : ObjectId("5ed4b193ed6fab6d2272c5c4"), "id" : 1, "timestamp" : ISODate("2020-05-31T05:59:59Z") } #new data run after change db (it must disappear for unique)
{ "_id" : ObjectId("5ed33bef1e499012bf35e412"), "id" : 1, "timestamp" : ISODate("2020-05-31T04:59:59.999Z") } #old data
{ "_id" : ObjectId("5ed4b193ed6fab6d2272c5c3"), "id" : 1, "timestamp" : ISODate("2020-05-31T04:59:59Z") } #new data run after change db (it must disappear for unique)
{ "_id" : ObjectId("5ed32de165269b416f6c7362"), "id" : 1, "timestamp" : ISODate("2020-05-31T03:59:59.999Z") } #old data
{ "_id" : ObjectId("5ed4b193ed6fab6d2272c5c2"), "id" : 1, "timestamp" : ISODate("2020-05-31T03:59:59Z") } #new data run after change db (it must disappear for unique)
{ "_id" : ObjectId("5ed31fcff2a5076cc947bc02"), "id" : 1, "timestamp" : ISODate("2020-05-31T02:59:59.999Z") } #old data
{ "_id" : ObjectId("5ed311bfb0d88300f81e90d2"), "id" : 1, "timestamp" : ISODate("2020-05-31T01:59:59.999Z") } #old data

I have an index id and timestamp which is unique, but because timestamp has microseconds, not exactly so. Please give me a solution to keep microseconds in an ISODate.

PS: my code did not change. I use PHP and always format dates with 'Y-m-d\TH:i:s.uP'


问:
How can i change the "box" height of matblolib subplot and get the height of a matplotlib table?
```<code>import matplotlib.pyplot as plt
import pandas as pd
df= pd.DataFrame({'A':['a','b'],'B':[1,2],'C':[1,2]})
fig,ax = plt.subplots()
ax.set_title("title")
ax.set_xlabel('label')
plt.xticks([])
plt.yticks([])
tab = ax.table(rowLabels=range(1,3),colLabels=['A','B','C'],cellText=df.values,loc='center',rowLoc='center')
plt.show()
##My doubt:
function_that_resize_the_box_height( function_that_get_the_table_height(tab) )
</code>```

That is what i mean by 'box:

答:
A possibility could be the opposite: set the size of the figure with fig,ax = plt.subplots(1, 1, figsize = (5, 2.5)) and then set the bbox parameter of the table so that it fills the figure:

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

df= pd.DataFrame({'A':['a','b'],'B':[1,2],'C':[1,2]})

fig,ax = plt.subplots(1, 1, figsize = (5, 2.5))
ax.set_title("title")
ax.set_xlabel('label')
plt.xticks([])
plt.yticks([])

tab = ax.table(rowLabels=range(1,3),colLabels=['A','B','C'],cellText=df.values,loc='center',rowLoc='center',
               bbox = [0, 0, 1, 1])

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

This is what I get:

Check this for more information.

Body:
import matplotlib.pyplot as plt
import pandas as pd
df= pd.DataFrame({'A':['a','b'],'B':[1,2],'C':[1,2]})
fig,ax = plt.subplots()
ax.set_title("title")
ax.set_xlabel('label')
plt.xticks([])
plt.yticks([])
tab = ax.table(rowLabels=range(1,3),colLabels=['A','B','C'],cellText=df.values,loc='center',rowLoc='center')
plt.show()
##My doubt:
function_that_resize_the_box_height( function_that_get_the_table_height(tab) )

That is what i mean by 'box:

Body:
A possibility could be the opposite: set the size of the figure with fig,ax = plt.subplots(1, 1, figsize = (5, 2.5)) and then set the bbox parameter of the table so that it fills the figure:

import matplotlib.pyplot as plt
import pandas as pd

df= pd.DataFrame({'A':['a','b'],'B':[1,2],'C':[1,2]})

fig,ax = plt.subplots(1, 1, figsize = (5, 2.5))
ax.set_title("title")
ax.set_xlabel('label')
plt.xticks([])
plt.yticks([])

tab = ax.table(rowLabels=range(1,3),colLabels=['A','B','C'],cellText=df.values,loc='center',rowLoc='center',
               bbox = [0, 0, 1, 1])

plt.show()

This is what I get:

Check this for more information.


问:
Comparing list values and select maximum from each day - Python
I am using Python 3.6. I have a below list(capturing start time through a json object) and would like to capture the most recent date/time value in the list for each day.

mytimelist =[2020-05-30T19:21:36.124Z, 2020-05-31T10:34:06.137Z, 2020-05-31T17:14:06.117Z,2020-05-31T23:06:21.131Z, 2020-06-01T19:21:36.108Z, 2020-06-01T21:55:11.137Z]

I would want the below list.

myfinallist = [2020-05-30T19:21:36.124Z, 2020-05-31T23:06:21.131Z, 2020-06-01T21:55:11.137Z]

Could anybody please help me here.

Body:
A solution could include groupby from itertools.

from itertools import groupby

mytimelist =['2020-05-30T19:21:36.124Z', '2020-05-31T10:34:06.137Z', '2020-05-31T17:14:06.117Z','2020-05-31T23:06:21.131Z', '2020-06-01T19:21:36.108Z', '2020-06-01T21:55:11.137Z']

for k, v in groupby(sorted(mytimelist), key=lambda x: x[:10]):
    print(list(v)[-1])

2020-05-30T19:21:36.124Z
2020-05-31T23:06:21.131Z
2020-06-01T21:55:11.137Z

Update: Sorted the datetime entries per a'r's note below.