问:
Ajax / Javascript action doesn't appear on my main page
I'm trying to create a button with a simple Ajax / Javascript command, it seems to be working however it doesnt appears on my main page (under F12) which cause some issues.

here is the code:

```<code><html>
    <head>
        <script src="js/jquery.js"></script>
    </head>
<body>
    <button class="createButton" id="create_Button" onclick='button_creation()'>Create me</button>
</body>

<script>
    function button_creation()
    {
            button_exist = document.getElementById('submit_button');
            if(button_exist == null)
            {
                    btn = document.createElement("BUTTON");
                    btn.innerHTML = "Submit";
                    btn.setAttribute("type","submit");
                    btn.setAttribute("name","submit");
                    btn.setAttribute("value","submit");
                    document.body.appendChild(btn);
            }
    }
</script>
</code>```

the script works, however when i keep pressing the button it keep creating more buttons, and the reason for that (at least to me) its because it doesnt appears on the F12 of the main page.
although when i go to the console (F12) and write "document.getElementById('submit_button')"
i get all the values i entered.

anyone knows why and how do i solve that Ajax / Javascript will appear in my F12?

Many thanks.

答:
When you hit F12, it is showing you the rendered source code in the browser's debugging tool. What you see may vary slightly between Chrome, Edge, FireFox, etc, as their tools vary slightly. This isn't the issue. Also, HTML rendered with JavaScript may not immediately appear in your F12 code. You may have to right click and choose to inspect the new button to get it to refresh (depending on which browser you're using).

Your code is checking for a button with an ID of submit_button. If it doesn't find it, it creates a new button. But, it doesn't assign that new button an ID value at all. So, when it checks again for buttons with an ID of submit_button, it will never find any, so it keeps making buttons. You should add an ID to your newly-created button:

```<code>function button_creation()
    {
            button_exist = document.getElementById('submit_button');
            if(button_exist == null)
            {
                    btn = document.createElement("BUTTON");
                    btn.innerHTML = "Submit";
                    btn.setAttribute("id","submit_button");
                    btn.setAttribute("type","submit");
                    btn.setAttribute("name","submit_button");
                    btn.setAttribute("value","submit");
                    document.body.appendChild(btn);
            }
    }
</code>```

Body:
I'm trying to create a button with a simple Ajax / Javascript command, it seems to be working however it doesnt appears on my main page (under F12) which cause some issues.

here is the code:

    <button class="createButton" id="create_Button" onclick='button_creation()'>Create me</button>

the script works, however when i keep pressing the button it keep creating more buttons, and the reason for that (at least to me) its because it doesnt appears on the F12 of the main page.
although when i go to the console (F12) and write "document.getElementById('submit_button')"
i get all the values i entered.

anyone knows why and how do i solve that Ajax / Javascript will appear in my F12?

Many thanks.

Body:
When you hit F12, it is showing you the rendered source code in the browser's debugging tool. What you see may vary slightly between Chrome, Edge, FireFox, etc, as their tools vary slightly. This isn't the issue. Also, HTML rendered with JavaScript may not immediately appear in your F12 code. You may have to right click and choose to inspect the new button to get it to refresh (depending on which browser you're using).

Your code is checking for a button with an ID of submit_button. If it doesn't find it, it creates a new button. But, it doesn't assign that new button an ID value at all. So, when it checks again for buttons with an ID of submit_button, it will never find any, so it keeps making buttons. You should add an ID to your newly-created button:

function button_creation()
    {
            button_exist = document.getElementById('submit_button');
            if(button_exist == null)
            {
                    btn = document.createElement("BUTTON");
                    btn.innerHTML = "Submit";
                    btn.setAttribute("id","submit_button");
                    btn.setAttribute("type","submit");
                    btn.setAttribute("name","submit_button");
                    btn.setAttribute("value","submit");
                    document.body.appendChild(btn);
            }
    }


来源: stackexchange

问:
C# windows form button to execute SQL Query
I'm new to programming so please bear with me as I learn. I've been looking for days for a way to make this work, trying different solutions that I have found on here and other sites. I am using user input to create my connection string, and button 1 works great to verify that a connection has been established, button 2 not so much. I am trying to create a button that once pushed will execute a SQL command and provide the results from the command.

This is what I have so far, its button 2 that I have not been able to get to work yet.

using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }

       private void Form1_Load(object sender, EventArgs e)
       {

       }

       private void textBox1_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox2_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox3_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox4_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox5_TextChanged(object sender, EventArgs e)
       {

       }

       private void button1_Click(object sender, EventArgs e)
       {
           {
               string ServerName = textBox1.Text;
               string Database = textBox2.Text;
               string Username = textBox3.Text;
               string Pass = textBox4.Text;

               string connetionString;
               SqlConnection cnn;
               connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
               cnn = new SqlConnection(connetionString);
               try
               {
                   cnn.Open();
                   MessageBox.Show("Connection Open  !");
                   cnn.Close();
               }
               catch (Exception) { MessageBox.Show("Login Failed, Information is Incorrect"); }
           }
       }

       private void button2_Click(object sender, EventArgs e)
       {
           string ServerName = textBox1.Text;
           string Database = textBox2.Text;
           string Username = textBox3.Text;
           string Pass = textBox4.Text;
           string results = textBox5.Text;

           string connetionString;
           SqlConnection cnn;
           connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
           string userInput = "";
           var process = new Process();
           var startInfo = new ProcessStartInfo();
           startInfo.WindowStyle = ProcessWindowStyle.Hidden;
           startInfo.FileName = "cmd.exe";
           startInfo.Arguments = string.Format(@"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + "; "" SELECT count(*) from participanthistory, SELECT count(*) from postransaction where communicated = 0, userInput);

           process.StartInfo = startInfo;
           process.Start();
       }

       }

   }
```

<p>I am trying to get the button to run this sql:</p>

<pre class="lang-sql prettyprint-override"><code>select count(*) from history
select count(*) from results where communicated = 0
</code>```

I can run the SQL Query in SSMS no problem its just getting it to launch from the GUI I'm creating.

Any help is greatly appreciated.

答:
Sanitize that input!

Your click event code might look something like this:

```<code>    private void button2_Click(object sender, EventArgs e)
    {
        string ServerName = textBox1.Text;
        string Database = textBox2.Text;
        string Username = textBox3.Text;
        string Pass = textBox4.Text;
        //string results = textBox5.Text;

        using (var cnn = new SqlConnection($"Data Source= \"{ServerName}\";Initial Catalog= \"{Database}\";User ID=\"{Username}\";Password= \"{Pass}\";"))
        using (var cmd = cnn.CreateCommand())
        {
            cmd.CommandText = "-- Your query here --";

            try
            {
                cnn.Open();
            }
            catch (Exception ex)
            {
                // Error connecting to db.
            }

            if (cnn.State == System.Data.ConnectionState.Open)
            {
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        // Read your data, row by row, here. ...or do something with textBox5
                    }
                }
            }
        }
    }
</code>```

And because you are just getting counts, you may also skip the reader and do this instead...

```<code>if (cnn.State == System.Data.ConnectionState.Open)
{
    var count = cmd.ExecuteScalar();
    //count is an object, cast as needed.
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to programming so please bear with me as I learn. I've been looking for days for a way to make this work, trying different solutions that I have found on here and other sites. I am using user input to create my connection string, and button 1 works great to verify that a connection has been established, button 2 not so much. I am trying to create a button that once pushed will execute a SQL command and provide the results from the command.

This is what I have so far, its button 2 that I have not been able to get to work yet.

using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }

       private void Form1_Load(object sender, EventArgs e)
       {

       }

       private void textBox1_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox2_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox3_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox4_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox5_TextChanged(object sender, EventArgs e)
       {

       }

       private void button1_Click(object sender, EventArgs e)
       {
           {
               string ServerName = textBox1.Text;
               string Database = textBox2.Text;
               string Username = textBox3.Text;
               string Pass = textBox4.Text;

               string connetionString;
               SqlConnection cnn;
               connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
               cnn = new SqlConnection(connetionString);
               try
               {
                   cnn.Open();
                   MessageBox.Show("Connection Open  !");
                   cnn.Close();
               }
               catch (Exception) { MessageBox.Show("Login Failed, Information is Incorrect"); }
           }
       }

       private void button2_Click(object sender, EventArgs e)
       {
           string ServerName = textBox1.Text;
           string Database = textBox2.Text;
           string Username = textBox3.Text;
           string Pass = textBox4.Text;
           string results = textBox5.Text;

           string connetionString;
           SqlConnection cnn;
           connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
           string userInput = "";
           var process = new Process();
           var startInfo = new ProcessStartInfo();
           startInfo.WindowStyle = ProcessWindowStyle.Hidden;
           startInfo.FileName = "cmd.exe";
           startInfo.Arguments = string.Format(@"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + "; "" SELECT count(*) from participanthistory, SELECT count(*) from postransaction where communicated = 0, userInput);

           process.StartInfo = startInfo;
           process.Start();
       }

       }

   }

I am trying to get the button to run this sql:

select count(*) from history
select count(*) from results where communicated = 0

I can run the SQL Query in SSMS no problem its just getting it to launch from the GUI I'm creating.

Any help is greatly appreciated.

Body:
Sanitize that input!

Your click event code might look something like this:

    private void button2_Click(object sender, EventArgs e)
    {
        string ServerName = textBox1.Text;
        string Database = textBox2.Text;
        string Username = textBox3.Text;
        string Pass = textBox4.Text;
        //string results = textBox5.Text;

        using (var cnn = new SqlConnection($"Data Source= \"{ServerName}\";Initial Catalog= \"{Database}\";User ID=\"{Username}\";Password= \"{Pass}\";"))
        using (var cmd = cnn.CreateCommand())
        {
            cmd.CommandText = "-- Your query here --";

            try
            {
                cnn.Open();
            }
            catch (Exception ex)
            {
                // Error connecting to db.
            }

            if (cnn.State == System.Data.ConnectionState.Open)
            {
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        // Read your data, row by row, here. ...or do something with textBox5
                    }
                }
            }
        }
    }

And because you are just getting counts, you may also skip the reader and do this instead...

if (cnn.State == System.Data.ConnectionState.Open)
{
    var count = cmd.ExecuteScalar();
    //count is an object, cast as needed.
}


问:
Time since in php dateTime object in seconds

Possible Duplicate:

  Date to timestamp (PHP)?

How do I get the current time in seconds since 1st january 1970 in php?

does the dateTime object support anything since as

```<code>$date1 = new DateTime("01/01/1970");
$return = since($date1, date.now());
</code>```

The problem I get here is I could just do something like ((minutes=hours *60)*60)

Is there a nicer way?

答:
time()

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  Date to timestamp (PHP)?

How do I get the current time in seconds since 1st january 1970 in php?

does the dateTime object support anything since as

$date1 = new DateTime("01/01/1970");
$return = since($date1, date.now());

The problem I get here is I could just do something like ((minutes=hours *60)*60)

Is there a nicer way?


问:
How to replace a key with def value using karate framework
I have a JSON file as given below:

```<code>{
    "lastname": {
        "displayName": "lastname"
    },
    "#(dynamicKey)": {
        "displayName": "#(dynamicKey)"
    }
}
</code>```

When I try to read the file, the key and values are not getting updated but when I use JSON like below, value got replaced by the def values. If I give dynamic key both key and value are not getting updated. :-(

```<code>{
    "lastname": {
        "displayName": "lastname"
     },
     "someKey": {
        "displayName": "#(dynamicKey)"
     }
}
</code>```

Could you please help me on how to replace dynamic key and value?

答:
This is how you can handle dynamic keys. The #(dynamicKey) embedded-expression approach will not work.

```<code>* def dynamicKey = 'bar'
* def test = { someKey: 'foo' }
* test[dynamicKey] = 'baz'
* match test == { someKey: 'foo', bar: 'baz' }
</code>```

Body:
I have a JSON file as given below:

{
    "lastname": {
        "displayName": "lastname"
    },
    "#(dynamicKey)": {
        "displayName": "#(dynamicKey)"
    }
}

When I try to read the file, the key and values are not getting updated but when I use JSON like below, value got replaced by the def values. If I give dynamic key both key and value are not getting updated. :-(

{
    "lastname": {
        "displayName": "lastname"
     },
     "someKey": {
        "displayName": "#(dynamicKey)"
     }
}

Could you please help me on how to replace dynamic key and value?

Body:
This is how you can handle dynamic keys. The #(dynamicKey) embedded-expression approach will not work.

* def dynamicKey = 'bar'
* def test = { someKey: 'foo' }
* test[dynamicKey] = 'baz'
* match test == { someKey: 'foo', bar: 'baz' }


问:
(Gatsby + Prismic): Content Relationship URLs
I have a Gatsby Prismic blog with two custom content types - guide, and review.

I want the URL structure to be www.mysite.com/guide_url/review_url.

What I've done so far:

I've added a content relationship field in Prismic to the parent custom type guide and linked the children (review) to it.

In my gatsby-node.js file the code looks like this:

```<code>exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators;
  return new Promise((resolve, reject) => {
    graphql(`
      {
        allPrismicGuide {
          edges {
            node {
              id
              uid
            }
          }
        }
        allPrismicReview {
          edges {
            node {
              id
              uid
            }
          }
        }
    `).then(result => {
      const categoriesSet = new Set();
      result.data.allPrismicGuide.edges.forEach(({ node }) => {
        createPage({
          path: node.uid,
          component: path.resolve(`./src/templates/GuideTemplate.js`),
          context: {
            // Data passed to context is available in page queries as GraphQL variables.
            slug: node.uid
          }
        });
      });
      result.data.allPrismicReview.edges.forEach(({ node }) => {
        createPage({
          path: node.uid,
          component: path.resolve(`./src/templates/ReviewTemplate.js`),
          context: {
            // Data passed to context is available in page queries as GraphQL variables.
            slug: node.uid,
            tags: node.tags
          }
        });
      });

</code>```

I'm pretty new to Gatsby and Prismic.

I would love to get some feedback (helpful links) and suggestions!

答:
[Update] Prismic is not longer recommending the gatsby-source-prismic-graphql plugin.

Here's an article that'll help you migrating to the other one:

How to migrate a project from 'gatsby-source-prismic' to 'gatsby-source-prismic-graphql'

Body:
I have a Gatsby Prismic blog with two custom content types - guide, and review.

I want the URL structure to be www.mysite.com/guide_url/review_url.

What I've done so far:

I've added a content relationship field in Prismic to the parent custom type guide and linked the children (review) to it.

In my gatsby-node.js file the code looks like this:

exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators;
  return new Promise((resolve, reject) => {
    graphql(`
      {
        allPrismicGuide {
          edges {
            node {
              id
              uid
            }
          }
        }
        allPrismicReview {
          edges {
            node {
              id
              uid
            }
          }
        }
    `).then(result => {
      const categoriesSet = new Set();
      result.data.allPrismicGuide.edges.forEach(({ node }) => {
        createPage({
          path: node.uid,
          component: path.resolve(`./src/templates/GuideTemplate.js`),
          context: {
            // Data passed to context is available in page queries as GraphQL variables.
            slug: node.uid
          }
        });
      });
      result.data.allPrismicReview.edges.forEach(({ node }) => {
        createPage({
          path: node.uid,
          component: path.resolve(`./src/templates/ReviewTemplate.js`),
          context: {
            // Data passed to context is available in page queries as GraphQL variables.
            slug: node.uid,
            tags: node.tags
          }
        });
      });

I'm pretty new to Gatsby and Prismic.

I would love to get some feedback (helpful links) and suggestions!


问:
React DatePicker loads with default value but then will not change when state changes
I have a component which renders x amount of DateInputs based on x number of charges. The date inputs should be rendered with the default value loaded from the server. Once the onChange is triggered it updates the state in the parent and prints out the console with the selected date using the computedProperty. To give more context here is an image of the page:

A you can see, a datepicker is rendered for each charge and the user needs the ability to modify the charge date. So in terms of data flow, the onChange in the child component triggers the method handleChargesDateChange in the parent, as the state needs to be stored in parent.

At the minute, the default charge date is rendered in the dropdown, but when onChange is executed then date input value does not change. However, the method prints out the correct date that was selected. Again, for more context, here is a screenshot of the data stored in parent when child executes onChange on the date picker.

As you can see, the date values get modified when the user selects one from each datepicker. However, the actual datepicker value stays the same. I can get it to work where it renders with an empty date for each datepicker and when the user selects a new date, it will render the datepicker with the selected date. It also stored the value in parent. But I am really struggling to render the defalt value, but when it is changed update the datepicker with the user selected value... I hope this makes sense.. Anyway here's the code. So the method which gets triggered in parent:

```<code> handleChargesDateChange = (e) => {
    const date = e.target.value;
    const momentDate = moment(date);
    const chargeId = e.target.name;
    console.log(date);
    console.log(momentDate);
    this.setState({
        updatedChargeDates: [
            ...this.state.updatedChargeDates,
            {[chargeId]: date}
        ]
    }, () => console.log(this.state.updatedChargeDates))
}
</code>```

This then gets passed down (around 3 children deep) via:

```<code>  <Grid.Row>
            <Grid.Column width={16}>
                <OrderSummary
                    order={this.state.order}
                    fuelTypes={this.state.fuelTypes}
                    vehicleClasses={this.state.vehicleClasses}
                    deviceTypes={this.state.deviceTypes}
                    chargeTypes={this.state.chargeTypes}
                    featureTypes={this.state.featureTypes}
                    itemGroups={this.state.itemGroups}
                    itemTypes={this.state.itemTypes}
                    updateChargeDates={this.handleChargesDateChange}
                    chargeDates={this.state.updatedChargeDates}
                />
            </Grid.Column>
</code>```

I will skip the various other children components that the method gets passed to and go straight to the effected component. So the method then lands at Charges:

```<code> export class Charges extends Component {

constructor(props) {
    super(props);

    this.state = {
        currentItem: 0,
        newDate: '',
        fields: {}
    }
}

render() {
 const {charges, chargeTypes, updateChargeDates, chargeDates} = this.props;

 console.log('Props method', charges);
 if (charges.length === 0) { return null; }

return <Form>
    <h3>Charges</h3>
    {charges.map(charge => {

        console.log(charge);
        const chargeType = chargeTypes.find(type => type.code === charge.type) || {};
        return <Grid>
            <Grid.Row columns={2}>
                <Grid.Column>
                    <Form.Input
                        key={charge.id}
                        label={chargeType.description || charge.type}
                        value={Number(charge.amount).toFixed(2)}
                        readOnly
                        width={6} />
                </Grid.Column>
                <Grid.Column>
                    <DateInput
                        name={charge.id}
                        selected={this.state.newDate}
                        ***onChange={updateChargeDates}***
                        ***value={chargeDates[charge.id] == null ? charge.effectiveDate : chargeDates[charge.id]}***
                    />
                </Grid.Column>
            </Grid.Row>
        </Grid>
    })}
    <Divider hidden />
    <br />
</Form>
}
</code>```

I have highlighted the culprit code with *** to make it easier to follow. I am using a ternary type operator to determine which value to display, but it doesnt seem to update when i select a value.. I thought that from the code I have, if the initial chargeDates[charge.id] is null then we display the charge.effectiveDate which is what it is doing, but soon as I change the date i would expect chargeDates[charge.id] to have a value, which in turn should display that value...

I really hope that makes sense, im sure im missing the point with this here and it will be a simple fix.. But seems as im a newbie to react, im quite confused..

I have tride to follow the following resources but it doesnt really give me what I want:

Multiple DatePickers in State

Daepicker state

If you need anymore questions or clarification please do let me know!

答:
Looking at your screenshot, updatedChargeDates (chargeDates prop) is an array of objects. The array has indexes 0, 1 and 2, but you access it in the DateInput like this chargeDates[charge.id] your trying to get the data at the index 431780 for example, which returns undefined, and so the condition chargeDates[charge.id] == null ? charge.effectiveDate : chargeDates[charge.id], will always return charge.effectiveDate.

You can fix this in handleChargesDateChange by making updatedChargeDates an object, like this :

```<code> handleChargesDateChange = (e) => {
    const date = e.target.value;
    const momentDate = moment(date);
    const chargeId = e.target.name;
    console.log(date);
    console.log(momentDate);
    this.setState({
        updatedChargeDates: {
            ...this.state.updatedChargeDates,
            [chargeId]: date
        }
    }, () => console.log(this.state.updatedChargeDates))
}
</code>```

Body:
I have a component which renders x amount of DateInputs based on x number of charges. The date inputs should be rendered with the default value loaded from the server. Once the onChange is triggered it updates the state in the parent and prints out the console with the selected date using the computedProperty. To give more context here is an image of the page:

A you can see, a datepicker is rendered for each charge and the user needs the ability to modify the charge date. So in terms of data flow, the onChange in the child component triggers the method handleChargesDateChange in the parent, as the state needs to be stored in parent.

At the minute, the default charge date is rendered in the dropdown, but when onChange is executed then date input value does not change. However, the method prints out the correct date that was selected. Again, for more context, here is a screenshot of the data stored in parent when child executes onChange on the date picker.

As you can see, the date values get modified when the user selects one from each datepicker. However, the actual datepicker value stays the same. I can get it to work where it renders with an empty date for each datepicker and when the user selects a new date, it will render the datepicker with the selected date. It also stored the value in parent. But I am really struggling to render the defalt value, but when it is changed update the datepicker with the user selected value... I hope this makes sense.. Anyway here's the code. So the method which gets triggered in parent:

 handleChargesDateChange = (e) => {
    const date = e.target.value;
    const momentDate = moment(date);
    const chargeId = e.target.name;
    console.log(date);
    console.log(momentDate);
    this.setState({
        updatedChargeDates: [
            ...this.state.updatedChargeDates,
            {[chargeId]: date}
        ]
    }, () => console.log(this.state.updatedChargeDates))
}

This then gets passed down (around 3 children deep) via:

  <Grid.Row>
            <Grid.Column width={16}>
                <OrderSummary
                    order={this.state.order}
                    fuelTypes={this.state.fuelTypes}
                    vehicleClasses={this.state.vehicleClasses}
                    deviceTypes={this.state.deviceTypes}
                    chargeTypes={this.state.chargeTypes}
                    featureTypes={this.state.featureTypes}
                    itemGroups={this.state.itemGroups}
                    itemTypes={this.state.itemTypes}
                    updateChargeDates={this.handleChargesDateChange}
                    chargeDates={this.state.updatedChargeDates}
                />
            </Grid.Column>

I will skip the various other children components that the method gets passed to and go straight to the effected component. So the method then lands at Charges:

 export class Charges extends Component {

constructor(props) {
    super(props);

    this.state = {
        currentItem: 0,
        newDate: '',
        fields: {}
    }
}

render() {
 const {charges, chargeTypes, updateChargeDates, chargeDates} = this.props;

 console.log('Props method', charges);
 if (charges.length === 0) { return null; }

return <Form>

Charges

    {charges.map(charge => {

        console.log(charge);
        const chargeType = chargeTypes.find(type => type.code === charge.type) || {};
        return <Grid>
            <Grid.Row columns={2}>
                <Grid.Column>
                    <Form.Input
                        key={charge.id}
                        label={chargeType.description || charge.type}
                        value={Number(charge.amount).toFixed(2)}
                        readOnly
                        width={6} />
                </Grid.Column>
                <Grid.Column>
                    <DateInput
                        name={charge.id}
                        selected={this.state.newDate}
                        ***onChange={updateChargeDates}***
                        ***value={chargeDates[charge.id] == null ? charge.effectiveDate : chargeDates[charge.id]}***
                    />
                </Grid.Column>
            </Grid.Row>
        </Grid>
    })}
    <Divider hidden />

</Form>
}

I have highlighted the culprit code with *** to make it easier to follow. I am using a ternary type operator to determine which value to display, but it doesnt seem to update when i select a value.. I thought that from the code I have, if the initial chargeDates[charge.id] is null then we display the charge.effectiveDate which is what it is doing, but soon as I change the date i would expect chargeDates[charge.id] to have a value, which in turn should display that value...

I really hope that makes sense, im sure im missing the point with this here and it will be a simple fix.. But seems as im a newbie to react, im quite confused..

I have tride to follow the following resources but it doesnt really give me what I want:

Multiple DatePickers in State

Daepicker state

If you need anymore questions or clarification please do let me know!

Body:
Looking at your screenshot, updatedChargeDates (chargeDates prop) is an array of objects. The array has indexes 0, 1 and 2, but you access it in the DateInput like this chargeDates[charge.id] your trying to get the data at the index 431780 for example, which returns undefined, and so the condition chargeDates[charge.id] == null ? charge.effectiveDate : chargeDates[charge.id], will always return charge.effectiveDate.

You can fix this in handleChargesDateChange by making updatedChargeDates an object, like this :

 handleChargesDateChange = (e) => {
    const date = e.target.value;
    const momentDate = moment(date);
    const chargeId = e.target.name;
    console.log(date);
    console.log(momentDate);
    this.setState({
        updatedChargeDates: {
            ...this.state.updatedChargeDates,
            [chargeId]: date
        }
    }, () => console.log(this.state.updatedChargeDates))
}


问:
How to build Customizable Apps in .Net?
We are building a LOB Thick WPF Client / WCF Server application. I need to create an architecture that allows "pluggable" workflows on the Client side, to facilitate a business selling point of per customer flexibility.

In .Net however, adding projects to a solution for every customer modification and for nearly every component that is deemed "replaceable" seems dangerous, at best.

The alternative that comes to mind is abstracting all classes to an interface and to let configuration feed through the correct implementation.

Then there is the logistical perspective: how do you best manage this in source control for instance?

What experiences can you share and what options do you know of?

PS: I'm not really aiming for extensibility. I need existing features to be "customizable". Things like changing page order in a wizard. I think Colin's suggestion of configuration will possibly be the best option. But beyond that?

答:
Take a look at the Managed Extensibility Framework:

http://mef.codeplex.com/

It allows you to create pluggable applications where assemblies that extend or add functionality to your application are loaded at runtime.

This solves the problem of assembling the components for a specific customer. However, it sounds like you want to have customer configuration on the component level, not just which components a customer has.

I would not recommend having customer specific code in your project, this will become unmanageable over time, both in terms of code volume and testability. Instead, build in configuration from day one. In other words, for each component have a number of configuration parameters that can be used to tailor it for each customer.

(I currently work on an application that is being used by ~400 white label partners, each with their own config!)

Title: How to build Customizable Apps in .Net?


问:
Visual studio code cmd error: Cannot be loaded because running scripts is disabled on this system
Inside of visual studio code, I'm trying to execute a script.bat from the command line, but I'm getting the following error:

File C:\Theses_Repo\train-cnn\environment\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system.

After reading this I tried to run the visual studio code in administrator mode, thinking that the problem was a matter of privileges. But the error is throwing anyway.

答:
Face the same issue and this works for me.
open PowerShell as Administrator and paste this.</p>

```<code>    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
</code>```

Body:
Face the same issue and this works for me.
open PowerShell as Administrator and paste this.

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser


问:
JSON / PowerShell - store ps variables in JSON and execute when converted to powershell object
Quick and dirty: I need a way to store a variable inside a JSON File. Let's show an example:

JSON File

```<code>{
   "Computername": "$env:COMPUTERNAME"
}
</code>```

PowerShell

Get-Content -Path Filename.json | ConvertFrom-Json

Expecting output:

```<code>Computername
--------------
XYZ1234
</code>```

Real Output (Problem):

```<code>Computername
--------------
$env:COMPUTERNAME
</code>```

Do I need to go with escaping? I couldnt figure it out how to solve this. Thanks for any help.

答:
Since you have a string as the value, you can use ExpandString to evaluate it.</p>

```<code>$ExecutionContext.InvokeCommand.ExpandString((Get-Content -Path Filename.json)) | ConvertFrom-Json
</code>```

Body:
Quick and dirty: I need a way to store a variable inside a JSON File. Let's show an example:

JSON File

{
   "Computername": "$env:COMPUTERNAME"
}

PowerShell

Get-Content -Path Filename.json | ConvertFrom-Json

Expecting output:

Computername
--------------
XYZ1234

Real Output (Problem):

Computername
--------------
$env:COMPUTERNAME

Do I need to go with escaping? I couldnt figure it out how to solve this. Thanks for any help.

Body:
Since you have a string as the value, you can use ExpandString to evaluate it.

$ExecutionContext.InvokeCommand.ExpandString((Get-Content -Path Filename.json)) | ConvertFrom-Json


问:
SyntaxError: Name 's' is used prior to global declaration in Python/Flask code
The goal of my code is to place it into two EC2 instances which is then connected to a load balancer to distribute requests between the two instances.

This is my code which I am first trying to test in my local before I test it in the EC2 instances and then ultimately test everything with the load balancer as well.

```<code>from flask import Flask,request,session
##global s
s = 0
app = Flask(__name__)

@app.route("/", methods=["GET","POST"])
def disp():
    if request.method == "GET":
        global s
        s = 0
        return str(s)
    if request.method == "POST":
        global s
        s = request.json["num"]
        return str(s)

if __name__ =="__main__":
    app.run()
    ##app.run('0.0.0.0', port=80)
</code>```

The error that returns when I run locally is SyntaxError: Name 's' is used prior to global declaration. I tried removing the s=0 after the import line but the error still persists.

答:
You have two global s in your disp function and the second one says something's wrong because it sees s = 0 before.

Ideally, put global definitions just after declaring the function:

```<code>from flask import Flask,request,session

s = 0
app = Flask(__name__)

@app.route("/", methods=["GET","POST"])
def disp():
    global s
    if request.method == "GET":
        s = 0
        return str(s)
    elif request.method == "POST":
        s = request.json["num"]
        return str(s)

if __name__ =="__main__":
    app.run()
    ##app.run('0.0.0.0', port=80)
</code>```

Also changed second if to elif.

Body:
The goal of my code is to place it into two EC2 instances which is then connected to a load balancer to distribute requests between the two instances.

This is my code which I am first trying to test in my local before I test it in the EC2 instances and then ultimately test everything with the load balancer as well.

from flask import Flask,request,session
##global s
s = 0
app = Flask(__name__)

@app.route("/", methods=["GET","POST"])
def disp():
    if request.method == "GET":
        global s
        s = 0
        return str(s)
    if request.method == "POST":
        global s
        s = request.json["num"]
        return str(s)

if __name__ =="__main__":
    app.run()
    ##app.run('0.0.0.0', port=80)

The error that returns when I run locally is SyntaxError: Name 's' is used prior to global declaration. I tried removing the s=0 after the import line but the error still persists.

Body:
You have two global s in your disp function and the second one says something's wrong because it sees s = 0 before.

Ideally, put global definitions just after declaring the function:

from flask import Flask,request,session

s = 0
app = Flask(__name__)

@app.route("/", methods=["GET","POST"])
def disp():
    global s
    if request.method == "GET":
        s = 0
        return str(s)
    elif request.method == "POST":
        s = request.json["num"]
        return str(s)

if __name__ =="__main__":
    app.run()
    ##app.run('0.0.0.0', port=80)

Also changed second if to elif.


问:
What is the real world accuracy of phone accelerometers when used for positioning?
I am working on an application where I would like to track the position of a mobile user inside a building where GPS is unavailable.  The user starts at a well known fixed location (accurate to within 5 centimeters), at which point the accelerometer in the phone is to be activated to track any further movements with respect to that fixed location.  My question is, in current generation smart phones (iphones, android phones, etc), how accurately can one expect to be able to track somebodies position based on the accelerometer these phones generally come equip with?

Specific examples would be good, such as "If I move 50 meters X from the starting point, 35 meters Y from the starting point and 5 meters Z from the starting point, I can expect my location to be approximated to within +/- 80 centimeters on most current smart phones", or whatever.

I have only a superficial understanding of techniques like Kalman filters to correct for drift, though if such techniques are relevant to my application and someone wants to describe the quality of the corrections I might get from such techniques, that would be a plus.

答:
If you integrate the accelerometer values twice you get position but the error is horrible. It is useless in practice.

Here is an explanation why (Google Tech Talk) at 23:20.

I answered a similar question.


问:
Path to resources inside custom module
I have a module:

Obs.: It's not the root module

```
my-module
├── components
|   └── my-component
|        └── my-component.html
└── images
    └── my-image.png
```

I am trying to set the path to "my-image.png" inside "my-component.html".

I have already tried to following ways:

```

    img src="./images/my-image.png"
    img src="../images/my-image.png"
    img src="/images/my-image.png"

```

But when i serve my app, angular resolves my paths to:

```

    localhost:4200/./images/my-image.png
    localhost:4200/../images/my-image.png
    localhost:4200/images/my-image.png

```

I want angular to resolve my path relative to the module where my html file is inside.
How can i do that?

答:
You have to add your images folder to the assets in your angular.json:

```<code>"assets": [
              "src/assets",
              "src/favicon.ico",
              {
                "glob": "*.{png,jpg,gif,svg}",
                "input": "src/app/path-to-your-module/images",
                "output": "your-module/images"
              }

            ],

</code>```

This matches all png,jpg,gif and svg files in your images directory.
And outputs them to your-module/images/. To use your images inside your module use:

```<code><img src="your-module/images/your-image.png">
</code>```

By using a object instead of a string you can specify the output directory. Otherwise you would have to use the complete path to your module in the img tag.

Title: Path to resources inside custom module

Body:
I have a module:

Obs.: It's not the root module

my-module
├── components
|   └── my-component
|        └── my-component.html
└── images
    └── my-image.png

I am trying to set the path to "my-image.png" inside "my-component.html".

I have already tried to following ways:

    img src="./images/my-image.png"
    img src="../images/my-image.png"
    img src="/images/my-image.png"

But when i serve my app, angular resolves my paths to:

    localhost:4200/./images/my-image.png
    localhost:4200/../images/my-image.png
    localhost:4200/images/my-image.png

I want angular to resolve my path relative to the module where my html file is inside.
How can i do that?

Body:
You have to add your images folder to the assets in your angular.json:

"assets": [
              "src/assets",
              "src/favicon.ico",
              {
                "glob": "*.{png,jpg,gif,svg}",
                "input": "src/app/path-to-your-module/images",
                "output": "your-module/images"
              }

            ],

This matches all png,jpg,gif and svg files in your images directory.
And outputs them to your-module/images/. To use your images inside your module use:

<img src="your-module/images/your-image.png">

By using a object instead of a string you can specify the output directory. Otherwise you would have to use the complete path to your module in the img tag.


问:
How can I use the value of one variable when i declare another
I am new to jquery but getting there. I am stuck trying to add the value from one var to when I declare another.

Here is my code -

```<code>var selected = jQuery(this).val();

var vt = jQuery('.details-tcs').find('input:radio:checked').val();
</code>```

I need to use the first var 'selected' with a value of 'AI' and add it to the second var 'vt' so it looks like -

```<code>var vt = jQuery('.details-tcs.AI').find('input:radio:checked').val();
</code>```

Any help really appreciated.

答:
I think you should first add event listener on radio buttons because empty values can cause errors.Eg.

```<code>document.querySelector("."+val) // val is null when page loads
</code>```

Attach event listener and then use string concatenation:

```<code>//var vt =""; //use global variables when using values outside of functions. Also Modify using functions
jQuery(".details-tcs input:radio").change(function(){
    var selected = jQuery(this).val();
    var vt = jQuery('.details-tcs').find('input:radio:checked').val();
    vt = jQuery('.details-tcs.'+vt).find('input:radio:checked').val(); // modify previous variable. Don't declare again
});
</code>```

Body:
I am new to jquery but getting there. I am stuck trying to add the value from one var to when I declare another.

Here is my code -

var selected = jQuery(this).val();

var vt = jQuery('.details-tcs').find('input:radio:checked').val();

I need to use the first var 'selected' with a value of 'AI' and add it to the second var 'vt' so it looks like -

var vt = jQuery('.details-tcs.AI').find('input:radio:checked').val();

Any help really appreciated.

Body:
I think you should first add event listener on radio buttons because empty values can cause errors.Eg.

document.querySelector("."+val) // val is null when page loads

Attach event listener and then use string concatenation:

//var vt =""; //use global variables when using values outside of functions. Also Modify using functions
jQuery(".details-tcs input:radio").change(function(){
    var selected = jQuery(this).val();
    var vt = jQuery('.details-tcs').find('input:radio:checked').val();
    vt = jQuery('.details-tcs.'+vt).find('input:radio:checked').val(); // modify previous variable. Don't declare again
});


问:
How to disable Rabbit health check via Configuration
I would like to disable the rabbit health check in my default RabbitMockConfiguration.
We have a Configuration that is imported via @Import. Unfortunately the Configuration does not prevent the health check from being added to the health indicator as that happens once spring-rabbit is in the classpath.

We have the workaround, that we add a properties file in every service using that Configuration, which disables the property management.health.rabbit.enabled, but for us it would be much nicer to be able to disable that heathcheck on configuration level.

I thought about the tests with @TestPropertySource(properties = ["management.health.rabbit.enabled=false"]), but I could not find an equivalent to use for the a @Configuration, as @PropertySource expects a location for a properties file and does not accept single properties.

Any idea what we can do?

Spring boot version: 2.2.4

Spring amqp version: 2.2.3

Spring Version: 5.2.3

答:
If you want to change the behaviour of the health check, I'd rather override the health check so that it states Rabbit is in mock mode.

To do so, just create a HealthIndicator bean named rabbitHealthIndicator:

```<code>@Bean
public HealthIndicator rabbitHealthIndicator() {
    return () -> Health.up().withDetail("version", "mock").build();
}
</code>```

This has the effect of switching the production one and exposes the fact the app is running with a mock.

Body:
If you want to change the behaviour of the health check, I'd rather override the health check so that it states Rabbit is in mock mode.

To do so, just create a HealthIndicator bean named rabbitHealthIndicator:

@Bean
public HealthIndicator rabbitHealthIndicator() {
    return () -> Health.up().withDetail("version", "mock").build();
}

This has the effect of switching the production one and exposes the fact the app is running with a mock.


问:
Checking if a blob exists in Azure Blob storage (php)
Simple question; how do you check if a blob exists using PHP in Azure blob storage using the file name? I can't seem to find it in the API.

Cheers

答:
I was looking for this today and this was the top search result so wanted to give my solution here which uses the prefix option to find only blobs which match the name I'm looking for.

You will need to include use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions; as well.

```<code>function blobExists($name)
{
    global $blobClient, $blobContainer;

    $listBlobsOptions = new ListBlobsOptions();
    $listBlobsOptions->setPrefix($name);
    $result = $blobClient->listBlobs($blobContainer, $listBlobsOptions);
    return count($result->getBlobs());
}
</code>```

Body:
I was looking for this today and this was the top search result so wanted to give my solution here which uses the prefix option to find only blobs which match the name I'm looking for.

You will need to include use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions; as well.

function blobExists($name)
{
    global $blobClient, $blobContainer;

    $listBlobsOptions = new ListBlobsOptions();
    $listBlobsOptions->setPrefix($name);
    $result = $blobClient->listBlobs($blobContainer, $listBlobsOptions);
    return count($result->getBlobs());
}


问:
How to retrieve one random row for each category?
I would like to retrieve one random row for each user_group. How can I do this ?

Here find 2 tables, user and user_group.

user :

```<code>id
firstname
user_group_id
</code>```

user_group :

```<code>id
label
</code>```

Data

users

```<code>1 | Thor        | 1
2 | Iron man    | 2
3 | Hulk        | 3
4 | Groot       | 3
</code>```

user_groups

```<code>1 | admin
2 | support
3 | user
</code>```

Results expected

```<code>1 | Thor        | admin
2 | Iron man    | support
4 | Groot       | user (or 3 | Hulk | user)
</code>```

答:
The answer using GROUP BY will conflict with the default SQL mode in MySQL 5.7 and later, which makes it an error to reference columns in the select-list that are neither in the GROUP BY, nor in an aggregate function.

The solution in MySQL 8.0 is to use window functions:

```<code>SELECT r.id, r.firstname, r.user_group_id, g.label
FROM (
  SELECT id, firstname, user_group_id,
    ROW_NUMBER() OVER (PARTITION BY user_group_id ORDER BY RAND()) AS rownum
  FROM users
) AS r
JOIN user_groups AS g ON (r.user_group_id = g.id)
WHERE r.rownum = 1
</code>```

Re your comment:

```<code>SELECT r.id, r.firstname, r.user_group_id, r.count, g.label
FROM (
  SELECT id, firstname, user_group_id,
    ROW_NUMBER() OVER (PARTITION BY user_group_id ORDER BY RAND()) AS rownum,
    COUNT(*) OVER (PARTITION BY user_group_id) AS count
  FROM users
) AS r
JOIN user_groups AS g ON (r.user_group_id = g.id)
WHERE r.rownum = 1
</code>```

Result:

```<code>+------+-----------+---------------+-------+---------+
| id   | firstname | user_group_id | count | label   |
+------+-----------+---------------+-------+---------+
|    1 | Thor      |             1 |     1 | admin   |
|    2 | Iron Man  |             2 |     1 | support |
|    3 | Hulk      |             3 |     2 | user    |
+------+-----------+---------------+-------+---------+
</code>```

You can use aggregate functions over windows. Read https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html for details on this.

Body:
I would like to retrieve one random row for each user_group. How can I do this ?

Here find 2 tables, user and user_group.

user :

id
firstname
user_group_id

user_group :

id
label

Data

users

1 | Thor        | 1
2 | Iron man    | 2
3 | Hulk        | 3
4 | Groot       | 3

user_groups

1 | admin
2 | support
3 | user

Results expected

1 | Thor        | admin
2 | Iron man    | support
4 | Groot       | user (or 3 | Hulk | user)

Body:
The answer using GROUP BY will conflict with the default SQL mode in MySQL 5.7 and later, which makes it an error to reference columns in the select-list that are neither in the GROUP BY, nor in an aggregate function.

The solution in MySQL 8.0 is to use window functions:

SELECT r.id, r.firstname, r.user_group_id, g.label
FROM (
  SELECT id, firstname, user_group_id,
    ROW_NUMBER() OVER (PARTITION BY user_group_id ORDER BY RAND()) AS rownum
  FROM users
) AS r
JOIN user_groups AS g ON (r.user_group_id = g.id)
WHERE r.rownum = 1

Re your comment:

SELECT r.id, r.firstname, r.user_group_id, r.count, g.label
FROM (
  SELECT id, firstname, user_group_id,
    ROW_NUMBER() OVER (PARTITION BY user_group_id ORDER BY RAND()) AS rownum,
    COUNT(*) OVER (PARTITION BY user_group_id) AS count
  FROM users
) AS r
JOIN user_groups AS g ON (r.user_group_id = g.id)
WHERE r.rownum = 1

Result:

+------+-----------+---------------+-------+---------+
| id   | firstname | user_group_id | count | label   |
+------+-----------+---------------+-------+---------+
|    1 | Thor      |             1 |     1 | admin   |
|    2 | Iron Man  |             2 |     1 | support |
|    3 | Hulk      |             3 |     2 | user    |
+------+-----------+---------------+-------+---------+

You can use aggregate functions over windows. Read https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html for details on this.


问:
How to figure out (using terminal) which version of python pip is installing to (MacOS)
Question in title. How do I figure out (using terminal) which version of python pip is installing to (Ex. Python 2.7 or Python 3.6). I am looking to use Terminal on MacOS.</p>

答:
Try the Pip --version command to verify the pip version.

```<code>$ pip --version
</code>```

if you want to know the version of any library installed, try:

```<code>$ pip list
</code>```

if you want to know the python version, just simply run in the command line:

```<code>$ python -v
</code>```

Body:
Try the Pip --version command to verify the pip version.

$ pip --version

if you want to know the version of any library installed, try:

$ pip list

if you want to know the python version, just simply run in the command line:

$ python -v


问:
How to parse form data using Azure Functions
I am trying to get form data within an Azure function.

```<code>public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
    NameValueCollection col = req.Content.ReadAsFormDataAsync().Result;
    return req.CreateResponse(HttpStatusCode.OK, "OK");
}
</code>```

I am getting the following error:

Exception while executing function: System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'multipart/form-data'.

I am trying to parse inbound emails via SendGrid as described here.
https://sendgrid.com/docs/Classroom/Basics/Inbound_Parse_Webhook/setting_up_the_inbound_parse_webhook.html

The incoming request looks correct.

--xYzZY
Content-Disposition: form-data; name="attachments"

0
--xYzZY
Content-Disposition: form-data; name="text"

Hello world
--xYzZY
Content-Disposition: form-data; name="subject"

Subject
--xYzZY
Content-Disposition: form-data; name="to"

答:
Since there doesn't appear to be a good way to convert an IFormCollection to a custom model / viewmodel type, I wrote an extension method for this.

It's a shame that Azure Functions v2/v3 doesn't support this out of the box yet.

public static class FormCollectionExtensions
{
    ///
    /// Attempts to bind a form collection to a model of type <typeparamref name="T" />.
    ///
    /// <typeparam name="T">The model type. Must have a public parameterless constructor.</typeparam>
    /// <param name="form">The form data to bind.</param>
    /// <returns>A new instance of type <typeparamref name="T" /> containing the form data.</returns>
    public static T BindToModel<T>(this IFormCollection form) where T : new()
    {
        var props = typeof(T).GetProperties();
        var instance = Activator.CreateInstance<T>();
        var formKeyMap = form.Keys.ToDictionary(k => k.ToUpper(), k => k);

        foreach (var p in props)
        {
            if (p.CanWrite && formKeyMap.ContainsKey(p.Name.ToUpper()))
            {
                p.SetValue(instance, form[formKeyMap[p.Name.ToUpper()]].FirstOrDefault());
            }
        }

        return instance;
    }
}
```

<p>This will attempt to bind an <code>IFormCollection</code> to whatever model type you pass in. Property names are case insensitive (i.e. you can map <code>firstname=Bob</code> to <code>public string FirstName { get; set; }</code>.</p>

<p>Usage:</p>

<pre class="lang-cs prettyprint-override"><code>var myModel = (await httpReq.ReadFormAsync()).BindToModel<MyModel>();
</code>```

Body:
I am trying to get form data within an Azure function.

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
    NameValueCollection col = req.Content.ReadAsFormDataAsync().Result;
    return req.CreateResponse(HttpStatusCode.OK, "OK");
}

I am getting the following error:

Exception while executing function: System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'multipart/form-data'.

I am trying to parse inbound emails via SendGrid as described here.
https://sendgrid.com/docs/Classroom/Basics/Inbound_Parse_Webhook/setting_up_the_inbound_parse_webhook.html

The incoming request looks correct.

--xYzZY
Content-Disposition: form-data; name="attachments"

0
--xYzZY
Content-Disposition: form-data; name="text"

Hello world
--xYzZY
Content-Disposition: form-data; name="subject"

Subject
--xYzZY
Content-Disposition: form-data; name="to"

Body:
Since there doesn't appear to be a good way to convert an IFormCollection to a custom model / viewmodel type, I wrote an extension method for this.

It's a shame that Azure Functions v2/v3 doesn't support this out of the box yet.

public static class FormCollectionExtensions
{
    /// <summary>
    /// Attempts to bind a form collection to a model of type <typeparamref name="T" />.
    /// </summary>
    /// <typeparam name="T">The model type. Must have a public parameterless constructor.</typeparam>
    /// <param name="form">The form data to bind.</param>
    /// <returns>A new instance of type <typeparamref name="T" /> containing the form data.</returns>
    public static T BindToModel<T>(this IFormCollection form) where T : new()
    {
        var props = typeof(T).GetProperties();
        var instance = Activator.CreateInstance<T>();
        var formKeyMap = form.Keys.ToDictionary(k => k.ToUpper(), k => k);

        foreach (var p in props)
        {
            if (p.CanWrite && formKeyMap.ContainsKey(p.Name.ToUpper()))
            {
                p.SetValue(instance, form[formKeyMap[p.Name.ToUpper()]].FirstOrDefault());
            }
        }

        return instance;
    }
}

This will attempt to bind an IFormCollection to whatever model type you pass in. Property names are case insensitive (i.e. you can map firstname=Bob to public string FirstName { get; set; }.

Usage:

var myModel = (await httpReq.ReadFormAsync()).BindToModel<MyModel>();


问:
How can I initiate a new function, immediately after a function is successful in react native
I want to run a function, just after a function is completed, and also pass some data into the second function.
I have tested the two functions individually, they both work. But I want to initiate the second one immediately after the first is complete

This is my code below but the second function didn't run properly.

```<code>const ChargeCard = (dispatch) => ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => {

    try {
        RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
            .then(response => {

                if (response) {
                    setBasic({ id }) //the function to run if this is successful
                }
            })

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};
</code>```

This function I want to run immediately that is successful;

```<code>const setBasic = () => async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}
</code>```

答:
Change the second function to this:

```<code>const setBasic = async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}
</code>```

You've defined it as:

```<code>const setBasic = () => async ({ id }) => {
</code>```

but you are calling it with:

```<code> setBasic({ id })
</code>```

Body:
I want to run a function, just after a function is completed, and also pass some data into the second function.
I have tested the two functions individually, they both work. But I want to initiate the second one immediately after the first is complete

This is my code below but the second function didn't run properly.

const ChargeCard = (dispatch) => ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => {

    try {
        RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
            .then(response => {

                if (response) {
                    setBasic({ id }) //the function to run if this is successful
                }
            })

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};

This function I want to run immediately that is successful;

const setBasic = () => async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}

Body:
Change the second function to this:

const setBasic = async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}

You've defined it as:

const setBasic = () => async ({ id }) => {

but you are calling it with:

 setBasic({ id })


问:
Pass value from iframe to parent of different domain or port
I want to Pass value from iframe to parent of different domain and port , can  i do that if yes than how? </p>

答:
see if this post helps

Yet Another cross-domain iframe resize Q&A


问:
Save Frames from Video OpenCV-python
I want to save frames from a video. My problem is that saved frames keep overwriting and only last frame saved at the end.
Here is my code</p>

```<code>import cv2

vc = cv2.VideoCapture('111.mp4')
c = 1
if vc.isOpened():
    rval, frame = vc.read()
else:
    rval = False
timeF = 30
while rval:
    rval, frame = vc.read()
    if not rval: break
    if (c % timeF == 0):
        cv2.imwrite('/home/benson/Image/imagename.jpg', frame)
    c = c + 1
    cv2.waitKey(1)
vc.release()
</code>```

答:
You already have a counter available, why aren't you using it?

```<code>cv2.imwrite('/home/benson/Image/imagename_{:04d}.jpg'.format(c), frame)
</code>```

Good luck

Andreas

Title: Save Frames from Video OpenCV-python

Body:
I want to save frames from a video. My problem is that saved frames keep overwriting and only last frame saved at the end.
Here is my code

import cv2

vc = cv2.VideoCapture('111.mp4')
c = 1
if vc.isOpened():
    rval, frame = vc.read()
else:
    rval = False
timeF = 30
while rval:
    rval, frame = vc.read()
    if not rval: break
    if (c % timeF == 0):
        cv2.imwrite('/home/benson/Image/imagename.jpg', frame)
    c = c + 1
    cv2.waitKey(1)
vc.release()

Body:
You already have a counter available, why aren't you using it?

cv2.imwrite('/home/benson/Image/imagename_{:04d}.jpg'.format(c), frame)

Good luck

Andreas


问:
HTML and or CSS to automatically produce simple search filter images / options
I have a requirement to display a list of search filters on an HTML page for many permutations of a product's configuration

there are a number of tray slot options:

4 tray slots

5 tray slots

6 tray slots

7 tray slots

8 tray slots

9 tray slots

10 tray slots

11 tray slots

and for each tray slot option there are a number of configurations available... a basket takes up 2 tray slots, and a tray takes one tray slot, so for the 6 tray option the permutations are:

2 baskets, 2 trays

1 basket, 4 trays

0 baskets, 6 trays

3 baskets, 0 trays

i need images for each combination to make the search filters easier to understand by the user...

e.g for the 11 tray option, the search filter image would look something like:

and for one of the 11 tray slot combinations, the 9 tray and 1 basket option would look like:

Can I use css or some dynamic image / icon creator to automatically create the image / css display feature to create these permutations dynamically? Otherwise maintaining and creating these images could be tiresome

答:
I've gone with this for the moment. Any comments welcome on how to improve the css / html

 ```

Body:
I've gone with this for the moment. Any comments welcome on how to improve the css / html

<html>
 <head>
  <style>
     .trapezoid {
     border-bottom: 1.2vw solid grey;
     border-left: 0.8vw solid transparent;
     border-right: 0.8vw solid transparent;
     height: 0;
     transform: rotate(180deg);
     margin: 0.5vw;
     }
     .rectangle {
     height: 0.4vw;
     background-color: grey;
     margin:0.2vw;
     }
     .option-wrapper {
     float: left;
     margin: 0.5vw;
     width: 5.0vw;
     border: 0.1vw solid grey;
     }
  </style>
 </head>
 <body>
  <span class="option-wrapper">
   <a href="">
    <div class="trapezoid"></div>
    <div class="trapezoid"></div>
    <div class="trapezoid"></div>
   </a>
  </span>
  <span class="option-wrapper">
   <a href="">
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="trapezoid"></div>
    <div class="trapezoid"></div>
   </a>
  </span>
  <span class="option-wrapper">
   <a href="">
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="trapezoid"></div>
   </a>
  </span>
  <span class="option-wrapper">
   <a href="">
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="rectangle"></div>
    <div class="rectangle"></div>
   </a>
  </span>
 </body>
 <html>


问:
Kubernetes kubectl apply command does not work, gives connection refused error
When I am trying to setup pod network using the following
kubectl apply -f ./deployment.yaml

I get this error, please help:

error: unable to recognize "./deployment.yaml": Get http://localhost:8080/api?timeout=32s: dial tcp [::1]:8080: connect: connection refused

Here is the output of the minikube logs command:

  command runner: getting ssh client for bootstrapper: Error dialing tcp via ssh client: dial tcp 192.168.64.2:22: connect: operation timed out
  minikube is exiting due to an error. If the above message is not useful, open an issue:
  https://github.com/kubernetes/minikube/issues/new/choose

答:
If You are experiencing issues with minikube You can do the following:

As @RohanMehto suggested, check logs with minikube logs.

If You see an error which looks starts like this:

```<code>error: unable to recognize
</code>```

It is usually related to kubectl miss-configuration.

As @emeric mentioned in comments, make sure that Your kubectl version supports the version of minikube.

Upgrading kubectl version to the latest fixed this issue.

Use minikube status to check if minikube is properly configured. If there are any errors, this command will provide how to resolve the issues.

Body:
If You are experiencing issues with minikube You can do the following:

As @RohanMehto suggested, check logs with minikube logs.

If You see an error which looks starts like this:

error: unable to recognize

It is usually related to kubectl miss-configuration.

As @emeric mentioned in comments, make sure that Your kubectl version supports the version of minikube.

Upgrading kubectl version to the latest fixed this issue.

Use minikube status to check if minikube is properly configured. If there are any errors, this command will provide how to resolve the issues.


问:
Django does not store password in database
When i print my password from view it shows non in my command prompt
i am using only password1 in forms.py
i put pass2=none

Models.py:-

```<code>class Profile(models.Model):
            user = models.OneToOneField(User, on_delete=models.CASCADE)
            bio = models.TextField(max_length=500, blank=True)
            location = models.CharField(max_length=30, blank=True)
            birth_date = models.DateField(null=True, blank=True)
            gender = models.CharField(max_length=10,blank=True)

            def __str__(self):
                return self.fullname
</code>```

Forms.py:-

```<code>class UserForm(forms.ModelForm):
            username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'}))
            password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'}))
            email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'}))
    password2=None

            class Meta:
                model=User
                fields=['username','password1','email']

        class ProfileForm(forms.ModelForm):
            fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'}))
            class Meta:
                model=Profile
                fields=['fullname']
</code>```

views.py:-

```<code>def register(request):
        if request.method =='POST':
            form = UserForm(request.POST)
            profile_form = ProfileForm(request.POST)
            if form.is_valid() and profile_form.is_valid():
                user=form.save()
                profile=profile_form.save(commit=False)
                profile.user=user
                profile.save()
                username= form.cleaned_data.get('username')
                password= form.cleaned_data.get('password')
                print(username)
                print(password)
                messages.success(request,f'account created for {{ username }}')
                return redirect('home')
        else:
            form = UserForm()
            profile_form = ProfileForm()
        context={'form':form , 'profile_form':profile_form}
        return render(request, 'users/register.html',context)
</code>```

**When i print my password in viws it shows None.also i am using only password1 **

答:
You are using the user module that comes with django.

```<code>from django.contrib.auth import authenticate, login, get_user_model
from django.contrib.auth.models import User
</code>```

Django for storing data in db.sqlite file in an encrypted format. You need a secret key to access while decoding which is present in settings.py file.you can decode all the data with it but not password

The passwords will be hashed in sha256 algorithm for 16 iterations so you cant get the password and this is done by default
If you want to reset the password use put call to reset it

Body:
When i print my password from view it shows non in my command prompt
i am using only password1 in forms.py
i put pass2=none

Models.py:-

class Profile(models.Model):
            user = models.OneToOneField(User, on_delete=models.CASCADE)
            bio = models.TextField(max_length=500, blank=True)
            location = models.CharField(max_length=30, blank=True)
            birth_date = models.DateField(null=True, blank=True)
            gender = models.CharField(max_length=10,blank=True)

            def __str__(self):
                return self.fullname

Forms.py:-

class UserForm(forms.ModelForm):
            username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'}))
            password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'}))
            email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'}))
    password2=None

            class Meta:
                model=User
                fields=['username','password1','email']

        class ProfileForm(forms.ModelForm):
            fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'}))
            class Meta:
                model=Profile
                fields=['fullname']

views.py:-

def register(request):
        if request.method =='POST':
            form = UserForm(request.POST)
            profile_form = ProfileForm(request.POST)
            if form.is_valid() and profile_form.is_valid():
                user=form.save()
                profile=profile_form.save(commit=False)
                profile.user=user
                profile.save()
                username= form.cleaned_data.get('username')
                password= form.cleaned_data.get('password')
                print(username)
                print(password)
                messages.success(request,f'account created for {{ username }}')
                return redirect('home')
        else:
            form = UserForm()
            profile_form = ProfileForm()
        context={'form':form , 'profile_form':profile_form}
        return render(request, 'users/register.html',context)

**When i print my password in viws it shows None.also i am using only password1 **

Body:
You are using the user module that comes with django.

from django.contrib.auth import authenticate, login, get_user_model
from django.contrib.auth.models import User

Django for storing data in db.sqlite file in an encrypted format. You need a secret key to access while decoding which is present in settings.py file.you can decode all the data with it but not password

The passwords will be hashed in sha256 algorithm for 16 iterations so you cant get the password and this is done by default
If you want to reset the password use put call to reset it


问:
Tied root for Alpha Beta Pruning Algorithm
I am having trouble understanding why the alpha-beta pruning algorithm should not prune C here?

Here is my terminal output:

```<code>eval A
min 2 min1 -9223372036854775807 10.0
eval B
min 2 min2 10.0 10.0
*** FAIL: test_cases/q3/6-tied-root.test
***     Incorrect generated nodes for depth=3
***         Student generated nodes: A B max min1 min2
***         Correct generated nodes: A B C max min1 min2
***     Tree:
***         max
***        /   \
***     min1    min2
***      |      /  \
***      A      B   C
***     10     10   0
</code>```

My understanding was that once B is evaluated, min2 will see that max will not pick anything lower than 10, therefore, even if a smaller value is found (x<=10) it would not make a difference. In this case, min2 would only be incentivized to look at C if B was greater than 10.

Thanks in advance

答:
My understanding was that once B is evaluated, min2 will see that max will not pick anything lower than 10, therefore, even if a smaller value is found (x<=10) it would not make a difference.

It's correct and can be verified with an online simulator (e.g. http://homepage.ufp.pt/jtorres/ensino/ia/alfabeta.html or https://raphsilva.github.io/utilities/minimax_simulator/):

0,0,2,1,-1000,393.75,30,-1000,1000,-1,-1,undefined,1,1,1,3,1000,225,295,undefined,undefined,0,-1,undefined,2,1,2,4,1000,562.5,295,undefined,undefined,0,-1,undefined,3,2,0,-1,10,225,560,undefined,undefined,1,undefined,undefined,4,2,0,-1,10,450,560,undefined,undefined,2,undefined,undefined,5,2,0,-1,0,675,560,undefined,undefined,2,undefined,undefined,<">

min2 would only be incentivized to look at C if B was greater than 10.

Equally correct:

0,0,2,1,-1000,393.75,30,-1000,1000,-1,-1,undefined,1,1,1,3,1000,225,295,undefined,undefined,0,-1,undefined,2,1,2,4,1000,562.5,295,undefined,undefined,0,-1,undefined,3,2,0,-1,10,225,560,undefined,undefined,1,undefined,undefined,4,2,0,-1,12,450,560,undefined,undefined,2,undefined,undefined,5,2,0,-1,0,675,560,undefined,undefined,2,undefined,undefined,<">

min2 must check C also if A is less than 10.

Could it be a wrong test case?

Body:
I am having trouble understanding why the alpha-beta pruning algorithm should not prune C here?

Here is my terminal output:

eval A
min 2 min1 -9223372036854775807 10.0
eval B
min 2 min2 10.0 10.0
*** FAIL: test_cases/q3/6-tied-root.test
***     Incorrect generated nodes for depth=3
***         Student generated nodes: A B max min1 min2
***         Correct generated nodes: A B C max min1 min2
***     Tree:
***         max
***        /   \
***     min1    min2
***      |      /  \
***      A      B   C
***     10     10   0

My understanding was that once B is evaluated, min2 will see that max will not pick anything lower than 10, therefore, even if a smaller value is found (x<=10) it would not make a difference. In this case, min2 would only be incentivized to look at C if B was greater than 10.

Thanks in advance

Body:
My understanding was that once B is evaluated, min2 will see that max will not pick anything lower than 10, therefore, even if a smaller value is found (x<=10) it would not make a difference.

It's correct and can be verified with an online simulator (e.g. http://homepage.ufp.pt/jtorres/ensino/ia/alfabeta.html or https://raphsilva.github.io/utilities/minimax_simulator/):

min2 would only be incentivized to look at C if B was greater than 10.

Equally correct:

min2 must check C also if A is less than 10.

Could it be a wrong test case?


问:
browser specific css attributes
Where can I find a complete "browser specific css attributes" reference?

I mean some attributes such as -moz-border-radius that is just for Firefox or -webkit-min-device-pixel-ratio. These examples work just in a specified web browser. I want a complete reference for these attributes.

答:
Each vendor should maintain a list of custom CSS extensions.  The ones I've found are linked below.

Mozilla (Firefox)

Opera

Safari (merged with standard CSS properties)

Internet Explorer (outdated)

Ones I can't find ...

Chrome (same engine as Safari, some slight differences in vendor extensions supported)

Title: browser specific css attributes


问:
how to change menu item gravity to right in NavigationView
I need to put a menu item icon at right of text (by default it's on the left side) so how to change menu item gravity to right in NavigationView ?

because we can not custom NavigationView Items,I think it's impossible. can any one help me.

my menu xml file is:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/menu_group_2">
        <item
            android:id="@+id/menu_settings"
            android:title="Settings" />
        <item
            android:id="@+id/menu_about"
            android:title="About" />
    </group>
</menu>
</code>```

and my navigationview in layout is

```<code><android.support.design.widget.NavigationView
    android:id="@+id/vNavigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    android:background="#ffffff"
    app:headerLayout="@layout/view_global_menu_header"
    app:itemIconTint="#8b8b8b"
    app:itemTextColor="#666666"
    android:gravity="right"
    app:menu="@menu/drawer_menu" />
</code>```

答:
You can use app:actionLayout attribute to customize the item the way you want.

Here is an example:

menu_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/nav_favorite"
        android:title=""
        app:actionLayout="@layout/action_layout_favorite" />

</menu>

```

<p><code>action_layout_favorite.xml</code></p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="center|end"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:src="@drawable/ic_heart_solid"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="@string/favorite"
        android:textColor="@color/Black"
        app:layout_constraintBottom_toBottomOf="@+id/imageView"
        app:layout_constraintEnd_toStartOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

here is the result shown at the first item

I got this solution from this website: https://stablekernel.com/using-custom-views-as-menu-items/

Body:
I need to put a menu item icon at right of text (by default it's on the left side) so how to change menu item gravity to right in NavigationView ?

because we can not custom NavigationView Items,I think it's impossible. can any one help me.

my menu xml file is:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/menu_group_2">
        <item
            android:id="@+id/menu_settings"
            android:title="Settings" />
        <item
            android:id="@+id/menu_about"
            android:title="About" />
    </group>
</menu>

and my navigationview in layout is

<android.support.design.widget.NavigationView
    android:id="@+id/vNavigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    android:background="#ffffff"
    app:headerLayout="@layout/view_global_menu_header"
    app:itemIconTint="#8b8b8b"
    app:itemTextColor="#666666"
    android:gravity="right"
    app:menu="@menu/drawer_menu" />

Body:
You can use app:actionLayout attribute to customize the item the way you want.

Here is an example:

menu_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/nav_favorite"
        android:title=""
        app:actionLayout="@layout/action_layout_favorite" />

    <!--Some more items-->

</menu>

action_layout_favorite.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="center|end"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:src="@drawable/ic_heart_solid"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="@string/favorite"
        android:textColor="@color/Black"
        app:layout_constraintBottom_toBottomOf="@+id/imageView"
        app:layout_constraintEnd_toStartOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>

here is the result shown at the first item

I got this solution from this website: https://stablekernel.com/using-custom-views-as-menu-items/


问:
postgres Like query performance for single word columns
DB-Type: PostgreSQL
DB-Version: 11
We have a column which has a single word as a value always. The maxlength is 10 chars.

We always have unique value for this column in the table.

We do not have any updates to this column, only new rows are inserted with this column.

We would like to enable like queries for this column.

Should we consider the PostgreSQL TRGM extension and using a GIN index? or will a normal index suffice in this case?

The queries will be like this:

select * from my_table where my_column like '%abc%';
```

The question arrives from the fact that TRGM is quite powerful when full text search is required for a long text with many words, but wanted to know if it will be better than a normal index for the single word scenario also.

答:
A trigram index is the only index that could help with a LIKE query with a leading wildcard. For short search strings like the one you show, it may still be slow if the trigram occurs in many words. But that's the best you can get.

For a LIKE condition without a wildcard in the beginning, a b-tree index might well be faster.

Body:
DB-Type: PostgreSQL
DB-Version: 11
We have a column which has a single word as a value always. The maxlength is 10 chars.

We always have unique value for this column in the table.

We do not have any updates to this column, only new rows are inserted with this column.

We would like to enable like queries for this column.

Should we consider the PostgreSQL TRGM extension and using a GIN index? or will a normal index suffice in this case?

The queries will be like this:

select * from my_table where my_column like '%abc%';

The question arrives from the fact that TRGM is quite powerful when full text search is required for a long text with many words, but wanted to know if it will be better than a normal index for the single word scenario also.


问:
Can't play the rest of the code when using winsound
I am writing a simple game but when I try to use the winsound command to play some music, it will play it but everything after it doesn't work. I tried to put it in the end but then the music starts when I quit the game.</p>

答: That's because, from what I understand, you are doing it synchronously, so the code execution will recover after the sound has been reproduced. Now, since I think you are referring the winsound python library, you should be able to run a thread where you play the sound using the Python Threading library. This way the sound is reproduced asynchronously while the rest of your code run


问:
How to copy multiple directories into a single directory and preserve directory structure
I would like to copy multiple directories (with contents) to a single directory in my container while maintaining the original directory structure of my project. For example, the relevant line in my Dockerfile looks like this:

```<code>COPY bin env project ./projects/
</code>```

The command above only copies files into my projects directory and also removes all of the original directory structure of bin, env, and project.

How can I copy several directories (with contents) such that the original directory structures are preserved? I did find this reference, but as the first commenter points out, directory structure is lost with this method.

答:
you need to create the directory structure since COPY will only add files not the directory itself.
one approach will be aading them one by one.

```<code>RUN mkdir -p projects/{bin,env,project}
COPY bin projects/
COPY env projects/
COPY project projects/
</code>```

or maybe using ADD will be a better approach since Add will decompress archives download files and more.
so you will need to archive directories first, then use add like below

```<code>ADD archive.tgz projects/
</code>```

Body:
I would like to copy multiple directories (with contents) to a single directory in my container while maintaining the original directory structure of my project. For example, the relevant line in my Dockerfile looks like this:

COPY bin env project ./projects/

The command above only copies files into my projects directory and also removes all of the original directory structure of bin, env, and project.

How can I copy several directories (with contents) such that the original directory structures are preserved? I did find this reference, but as the first commenter points out, directory structure is lost with this method.

Body:
you need to create the directory structure since COPY will only add files not the directory itself.
one approach will be aading them one by one.

RUN mkdir -p projects/{bin,env,project}
COPY bin projects/
COPY env projects/
COPY project projects/

or maybe using ADD will be a better approach since Add will decompress archives download files and more.
so you will need to archive directories first, then use add like below

ADD archive.tgz projects/


问:
How to apply distinct on google datastore using objectify?
I am trying to fetch some entities with distinct values on a property. Say, I have an entity called messages. And it has some properties say personId, typeId, convId, createdTime, etc. I want fetch messages of personId p1 with distinct convIds. How can I do that.

I already referred to
Executing DISTINCT query with objectify for app engine
and some others. And tried something like this.

```<code>ofy().load().type(messages.class).limit( 10 ).filter("personId ==", "p1").order("-createdTime").project("convId").distinct(true).list();

</code>```

I am sure that there are some entities with this combination. But it is fetching no entities.
Please help me with this.

答:
Unfortunately, your query isn't valid.  For projection queries you need distinct to be on the values that you are sorting by (i.e. -createdTime).  To use distinct you'll need to order by convId.

https://cloud.google.com/datastore/docs/concepts/queries#restrictions_on_queries has more details.

Body:
I am trying to fetch some entities with distinct values on a property. Say, I have an entity called messages. And it has some properties say personId, typeId, convId, createdTime, etc. I want fetch messages of personId p1 with distinct convIds. How can I do that.

I already referred to
Executing DISTINCT query with objectify for app engine
and some others. And tried something like this.

ofy().load().type(messages.class).limit( 10 ).filter("personId ==", "p1").order("-createdTime").project("convId").distinct(true).list();

I am sure that there are some entities with this combination. But it is fetching no entities.
Please help me with this.


问:
grep extract specific pattern from a large file of 190GB
I need to extract the email addresses from a large 190GB flat file (only error log) that I cut into a 5mb files. (with 152,353,216 lines)

The grep command works well, but the memory quickly becomes saturated and I end up getting errors.

The content of the files is not formatted, so I have to use regexp.

```<code>grep -r -E -h -o "\b(pattern)\b" /dir/* > outs.txt
</code>```

How to process files one by one?

答:
Depending on your data, your disk performance and your CPU, you may get on better with GNU Parallel. If you use the --pipepart option it will also split your 190GB file up for you without creating temporary files.

So, I created a 5GB file with 100000000 lines using Perl like this:

```<code>perl -E 'for($i=0;$i<100000000;$i++){say "Line $i,field2,field3,junk,junk,junk",int rand 1000000}' > BigBoy.txt
</code>```

The first 3 lines look like this:

```<code>Line 0,field2,field3,junk,junk,junk514649
Line 1,field2,field3,junk,junk,junk257773
Line 2,field2,field3,junk,junk,junk203414
</code>```

I then timed a grep at 58 seconds on that file that produced 88 lines of output:

```<code>time grep "junk426888$" BigBoy.txt
</code>```

I then timed GNU Parallel at 11 seconds for the same output:

```<code>time parallel -a BigBoy.txt --pipepart --block -1 grep "junk426888$"
</code>```

Body:
I need to extract the email addresses from a large 190GB flat file (only error log) that I cut into a 5mb files. (with 152,353,216 lines)

The grep command works well, but the memory quickly becomes saturated and I end up getting errors.

The content of the files is not formatted, so I have to use regexp.

grep -r -E -h -o "\b(pattern)\b" /dir/* > outs.txt

How to process files one by one?

Body:
Depending on your data, your disk performance and your CPU, you may get on better with GNU Parallel. If you use the --pipepart option it will also split your 190GB file up for you without creating temporary files.

So, I created a 5GB file with 100000000 lines using Perl like this:

perl -E 'for($i=0;$i<100000000;$i++){say "Line $i,field2,field3,junk,junk,junk",int rand 1000000}' > BigBoy.txt

The first 3 lines look like this:

Line 0,field2,field3,junk,junk,junk514649
Line 1,field2,field3,junk,junk,junk257773
Line 2,field2,field3,junk,junk,junk203414

I then timed a grep at 58 seconds on that file that produced 88 lines of output:

time grep "junk426888$" BigBoy.txt

I then timed GNU Parallel at 11 seconds for the same output:

time parallel -a BigBoy.txt --pipepart --block -1 grep "junk426888$"