问:
Internet Check in dialog
I have created a project in which it checks for continuous Internet Connection using Broadcast receiver.
Now if internet is available it shows nothing but as soon as i turn my internet connection off by scrolling from notification,it shows my alert box with error that no internet connection.but when i turn my internet turn on again from scrolling notifaction my alert box remains on Screen how to dismiss alert box.

I have tried to globally delcare my Alertd

//Code

```<code> private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if(currentNetworkInfo.isConnected()){

               // alertDialog.dismiss(); not working showing Error
//Attempt to invoke virtual method 'void androidx.appcompat.app.AlertDialog.dismiss()' on a null object reference
                // Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();

            }
               else{
 alerDialogbuilder = new AlertDialog.Builder(Registration.this);
            alerDialogbuilder.setTitle("Internet / Wifi Connection Error ! ");
            alerDialogbuilder.setMessage("Turn on Wifi/Internet ");

            alerDialogbuilder.setCancelable(false);
            alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivityForResult(new Intent(Settings.ACTION_WIFI_SETTINGS), 0);

                }
            });
            alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent iteer = new Intent(Registration.this, MainActivity.class);
                    startActivity(iteer);
                    overridePendingTransition(R.anim.from_left, R.anim.slide_to_right);
                    finish();
                }
            });

            alertDialog = alerDialogbuilder.create();
                alertDialog.show();
            }
        }
    };
</code>```

//Calling on Resume

```<code>@Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
</code>```

//inside on create

```<code> this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
</code>```

答:
do this

initiate alert dialog in onCreate() like this , with your existing code you were creating new instances of alert dialog again and again and that is why dismiss() was not working

```<code>onCreate(){
 alerDialogbuilder = new AlertDialog.Builder(Registration.this);
            alerDialogbuilder.setTitle("Internet / Wifi Connection Error ! ");
            alerDialogbuilder.setMessage("Turn on Wifi/Internet ");

            alerDialogbuilder.setCancelable(false);
            alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivityForResult(new Intent(Settings.ACTION_WIFI_SETTINGS), 0);

                }
            });
            alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent iteer = new Intent(Registration.this, MainActivity.class);
                    startActivity(iteer);
                    overridePendingTransition(R.anim.from_left, R.anim.slide_to_right);
                    finish();
                }
            });

            alertDialog = alerDialogbuilder.create();

}
</code>```

and your broadcast receiver looks like this

```<code>private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if(currentNetworkInfo.isConnected()){

              //dismiss dialog here
                alertDialog.dismiss();

            }
               else{
 //show dialog here
                alertDialog.show();
            }
        }
    };
//unregister broadtcast here
@Override
protected void onDestroy() {
    super.onDestroy();
    if (this.mConnReceiver != null) {
        unregisterReceiver(this.mConnReceiver);
    }

}
</code>```

IMPORTANT NOTICE:-

unregister broadcast receiver in onStop() else there will be
  exception and crash

DO NO REGISTER RECEIVER AGAIN IN ONRESUME()

Title: Internet Check in dialog

Body:
I have created a project in which it checks for continuous Internet Connection using Broadcast receiver.
Now if internet is available it shows nothing but as soon as i turn my internet connection off by scrolling from notification,it shows my alert box with error that no internet connection.but when i turn my internet turn on again from scrolling notifaction my alert box remains on Screen how to dismiss alert box.

I have tried to globally delcare my Alertd

//Code

 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if(currentNetworkInfo.isConnected()){

               // alertDialog.dismiss(); not working showing Error
//Attempt to invoke virtual method 'void androidx.appcompat.app.AlertDialog.dismiss()' on a null object reference
                // Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();

            }
               else{
 alerDialogbuilder = new AlertDialog.Builder(Registration.this);
            alerDialogbuilder.setTitle("Internet / Wifi Connection Error ! ");
            alerDialogbuilder.setMessage("Turn on Wifi/Internet ");

            alerDialogbuilder.setCancelable(false);
            alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivityForResult(new Intent(Settings.ACTION_WIFI_SETTINGS), 0);

                }
            });
            alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent iteer = new Intent(Registration.this, MainActivity.class);
                    startActivity(iteer);
                    overridePendingTransition(R.anim.from_left, R.anim.slide_to_right);
                    finish();
                }
            });

            alertDialog = alerDialogbuilder.create();
                alertDialog.show();
            }
        }
    };

//Calling on Resume

@Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

//inside on create

 this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

Body:
do this

initiate alert dialog in onCreate() like this , with your existing code you were creating new instances of alert dialog again and again and that is why dismiss() was not working

onCreate(){
 alerDialogbuilder = new AlertDialog.Builder(Registration.this);
            alerDialogbuilder.setTitle("Internet / Wifi Connection Error ! ");
            alerDialogbuilder.setMessage("Turn on Wifi/Internet ");

            alerDialogbuilder.setCancelable(false);
            alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivityForResult(new Intent(Settings.ACTION_WIFI_SETTINGS), 0);

                }
            });
            alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent iteer = new Intent(Registration.this, MainActivity.class);
                    startActivity(iteer);
                    overridePendingTransition(R.anim.from_left, R.anim.slide_to_right);
                    finish();
                }
            });

            alertDialog = alerDialogbuilder.create();

}

and your broadcast receiver looks like this

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if(currentNetworkInfo.isConnected()){

              //dismiss dialog here
                alertDialog.dismiss();

            }
               else{
 //show dialog here
                alertDialog.show();
            }
        }
    };
//unregister broadtcast here
@Override
protected void onDestroy() {
    super.onDestroy();
    if (this.mConnReceiver != null) {
        unregisterReceiver(this.mConnReceiver);
    }

}

IMPORTANT NOTICE:-

unregister broadcast receiver in onStop() else there will be
  exception and crash

DO NO REGISTER RECEIVER AGAIN IN ONRESUME()


来源: stackexchange

问:
Getting existing git branches to track remote branches
My usual workflow when working with git, is something like this:

create a local repository

do some work in that repository, add/change files etc.

decide that I want a central remote location for the repository, and create one

push all the commits from my local repository to this new remote repository

Now, however, I want to be able to push and pull from this remote repository without having to specify where I'm pushing to or pulling from; I want my local master to track the remote master.

The proper way to do this isn't clear to me, and I've been unable to determine it from the documentation, even though it shouldn't really be more than one command.

Because it's something that's only ever done once per repository, I've generally employed one of two simple, but hacky, solutions:

used git clone to make a new local repository, and deleted the old one. After git cloning, the new repository is setup to track the origin.

manually edited .git/config to make master track origin.

I think I should be able to run a command, probably some form of git remote to setup an existing repository to have master track a remote master. Can anyone tell me what that command is?

答:
Use this command:

git clone [<options>] [--] <repo> [<dir>]
```

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
How to execute mongodb find query in a loop in nodejs
I am trying to execute mongodb find query in a loop.
I have an object with some properties. The value of each property will be checked in the mongodb to get its
updated value. Once all the property values are updated, i want to perform some other actions.

But before getting the updated object(updatedVehObj), the next line of code (function updatedVehicleData )
is getting executed and its throwing some error,since i dont have the updated values.

Thanks in advance for any help to solve this issue or any better methods for achieving this result.

```<code>const processVehData = async (vehData) => {
  const vehObj = {
    make: 'AUD',
    model: 'A12',
    type: 'S',
  }
  const updatedVehObj = await getDBMapping(vehObj)
  // Do some preocessing with the updated vehicle obj
  const processedDataRes = updatedVehicleData(updatedVehObj)
  return processedDataRe;
}

const getDBMapping = async (vehObj) => {
  let updatedVeh = {}
  MongoClient.connect(connectionStr, mongoOptions, async (err, client) => {
    if (err) {
      console.log('Error in connecting to DB')
    }
    const dbo = client.db('VehicleDataBase')
    for (const key of Object.keys(vehObj)) {
      // Iterating every element in the object
      await dbo
        .collection(key)  // key name will be the collection name in mongodb
        .find({
          code: vehObj[key],
        })
        .toArray()
        .then(result => {
          updatedVeh[key] = result[0] // Framing new object with updated values
        })
        .catch(err => {
          console.log(' Error in getting mapping', err)
        })
    }
    return updatedVeh;
    /*** Expected result
      updatedVeh = {
        "make": "AUDI",
        "model" : "A3 Auto",
        "type" : "Sedan"
      }
    ****/
  })
}

const updatedVehicleData = vehData => {
  // Do something
}

</code>```

答:
As per your problem "But before getting the updated object(updatedVehObj), the next line of code (function updatedVehicleData ) is getting executed and its throwing some error,since i dont have the updated values."

You have to write same async and await before this function,

```<code>const processedDataRes = await updatedVehicleData(updatedVehObj)

const updatedVehicleData = async vehData => {
  // Do something
}
</code>```

Body:
I am trying to execute mongodb find query in a loop.
I have an object with some properties. The value of each property will be checked in the mongodb to get its
updated value. Once all the property values are updated, i want to perform some other actions.

But before getting the updated object(updatedVehObj), the next line of code (function updatedVehicleData )
is getting executed and its throwing some error,since i dont have the updated values.

Thanks in advance for any help to solve this issue or any better methods for achieving this result.

const processVehData = async (vehData) => {
  const vehObj = {
    make: 'AUD',
    model: 'A12',
    type: 'S',
  }
  const updatedVehObj = await getDBMapping(vehObj)
  // Do some preocessing with the updated vehicle obj
  const processedDataRes = updatedVehicleData(updatedVehObj)
  return processedDataRe;
}

const getDBMapping = async (vehObj) => {
  let updatedVeh = {}
  MongoClient.connect(connectionStr, mongoOptions, async (err, client) => {
    if (err) {
      console.log('Error in connecting to DB')
    }
    const dbo = client.db('VehicleDataBase')
    for (const key of Object.keys(vehObj)) {
      // Iterating every element in the object
      await dbo
        .collection(key)  // key name will be the collection name in mongodb
        .find({
          code: vehObj[key],
        })
        .toArray()
        .then(result => {
          updatedVeh[key] = result[0] // Framing new object with updated values
        })
        .catch(err => {
          console.log(' Error in getting mapping', err)
        })
    }
    return updatedVeh;
    /*** Expected result
      updatedVeh = {
        "make": "AUDI",
        "model" : "A3 Auto",
        "type" : "Sedan"
      }
    ****/
  })
}

const updatedVehicleData = vehData => {
  // Do something
}

Body:
As per your problem "But before getting the updated object(updatedVehObj), the next line of code (function updatedVehicleData ) is getting executed and its throwing some error,since i dont have the updated values."

You have to write same async and await before this function,

const processedDataRes = await updatedVehicleData(updatedVehObj)

const updatedVehicleData = async vehData => {
  // Do something
}


问:
Uncaught ReferenceError: getSelectedOption is not defined at HTMLButtonElement.document.getElementById.onclick
I am a super beginner in javascript and html and doing an experiment to build an webapp.
I ran npm install http-server -g and http-server '' -o and it opened up a browser tab. But in the console, I get this error and cannot identify what is causing the problem.

```<code>Uncaught ReferenceError: getSelectedOption is not defined
at HTMLButtonElement.document.getElementById.onclick (app.js:5)
document.getElementById.onclick @ app.js:5
</code>```

In the browser I see a pull down menu and  Refresh button. So why is getSelectedOption not defined?? I'm not sure if it's related to this problem, but even though I click the button, console.log("clicked!") doesn't print anything.

Here is my index.html

```<code><head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"> </script>
    <script type="text/javascript" src="app.js" defer></script>
</head>
<body>
    <form>
    <div class="form-group">
        <label>Store ID</label>
        <select class="form-control" id="company">
          <option selected>All</option>
          <option>Air France</option>
          <option>Lufthansa</option>
        </select>
        <button  class="btn btn-primary" type='button' id="button">Refresh</button>
      </div>
    </form>
</body>
</code>```

Here is my app.js

```<code>console.log("button", document.getElementById("button"))

document.getElementById('button').onclick = function(){
    console.log("clicked!")
    let company = getSelectedOption('company');
    let headers = new Headers()
    let init = {
        method : 'GET',
        headers : headers
    }
    let params = {
        'company':company
    }

    $.get( "/getmethod/<params>" );

    $.get("/getpythondata", function(data) {
        console.log($.parseJSON(data))
    })
</code>```

答:
You need to use document.getElementById('company').value to get value of select box.i.e :

console.log("button", document.getElementById("button"))

document.getElementById('button').onclick = function() {
    console.log("clicked!")
    let company = document.getElementById('company').value;//get value of select box
    console.log(company)
    let headers = new Headers()
    let init = {
      method: 'GET',
      headers: headers
    }
    let params = {
      'company': company
    }

    $.get("/getmethod/<params>");

    $.get("/getpythondata", function(data) {
      console.log($.parseJSON(data))
    })

    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class="form-group">
    <label>Store ID</label>
    <select class="form-control" id="company">
      <option selected>All</option>
      <option>Air France</option>
      <option>Lufthansa</option>
    </select>
    <button class="btn btn-primary" type='button' id="button">Refresh</button>
  </div>
</form></code>```

Body:
I am a super beginner in javascript and html and doing an experiment to build an webapp.
I ran npm install http-server -g and http-server '' -o and it opened up a browser tab. But in the console, I get this error and cannot identify what is causing the problem.

Uncaught ReferenceError: getSelectedOption is not defined
at HTMLButtonElement.document.getElementById.onclick (app.js:5)
document.getElementById.onclick @ app.js:5

In the browser I see a pull down menu and  Refresh button. So why is getSelectedOption not defined?? I'm not sure if it's related to this problem, but even though I click the button, console.log("clicked!") doesn't print anything.

Here is my index.html

    <form>

        Store ID
        <select class="form-control" id="company">
          <option selected>All</option>
          <option>Air France</option>
          <option>Lufthansa</option>
        </select>
        <button  class="btn btn-primary" type='button' id="button">Refresh</button>

    </form>

Here is my app.js

console.log("button", document.getElementById("button"))

document.getElementById('button').onclick = function(){
    console.log("clicked!")
    let company = getSelectedOption('company');
    let headers = new Headers()
    let init = {
        method : 'GET',
        headers : headers
    }
    let params = {
        'company':company
    }

    $.get( "/getmethod/<params>" );

    $.get("/getpythondata", function(data) {
        console.log($.parseJSON(data))
    })

Body:
You need to use document.getElementById('company').value to get value of select box.i.e :

console.log("button", document.getElementById("button"))

document.getElementById('button').onclick = function() {
    console.log("clicked!")
    let company = document.getElementById('company').value;//get value of select box
    console.log(company)
    let headers = new Headers()
    let init = {
      method: 'GET',
      headers: headers
    }
    let params = {
      'company': company
    }

    $.get("/getmethod/<params>");

    $.get("/getpythondata", function(data) {
      console.log($.parseJSON(data))
    })

    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class="form-group">
    <label>Store ID</label>
    <select class="form-control" id="company">
      <option selected>All</option>
      <option>Air France</option>
      <option>Lufthansa</option>
    </select>
    <button class="btn btn-primary" type='button' id="button">Refresh</button>
  </div>
</form>


问:
How to get short month name from full month name?
I need to get the short month name for the full month name.

For example,

```<code>DateTime.Now.ToString("MMMM", CultureInfo.CurrentCulture);
this returns - "agosto"

DateTime.Now.ToString("MMM", CultureInfo.CurrentCulture);
this returns - "ago."
</code>```

This two codes works only to get the current month. I need to get the short month name for all the months.

If I give "agosto", it should return "ago.". How could I achieve this?

答:
This is what you need:</p>

```<code>var dateUtil = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture);
return dateUtil.AbbreviatedMonthNames[DateTime.Now.Month -1];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to get the short month name for the full month name.

For example,

DateTime.Now.ToString("MMMM", CultureInfo.CurrentCulture);
this returns - "agosto"

DateTime.Now.ToString("MMM", CultureInfo.CurrentCulture);
this returns - "ago."

This two codes works only to get the current month. I need to get the short month name for all the months.

If I give "agosto", it should return "ago.". How could I achieve this?

Body:
This is what you need:

var dateUtil = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture);
return dateUtil.AbbreviatedMonthNames[DateTime.Now.Month -1];


问:
ValueError: invalid literal for int() with base 10 - TextInput value
I have recently started learning Kivy and have encountered a weird error when handling text / numbers entered in a TextInput box.

The Kivy Code looks like this:

```<code>BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'horizontal'
            Label:
                text: 'No. of buttons:'
                markup: True
                color: 0, 0, 0, 1
            CustomTextInput:
                id: textinput_num
                max_characters: 2
                multiline: False
                input_filter: 'int'
</code>```

The relevant Python code looks like this:

```<code>class DropDownScreen(Screen):
    def add_dd_values(self):
        dd_input = App.get_running_app().root.get_screen('dd_screen').ids.textinput_num.text
        print("TextInputBox: ", dd_input, "\n")
        print("Length: ",len(dd_input))
        print(int(dd_input)+1)
</code>```

I have referenced the value of the text input box as follows:

```<code>dd_input = App.get_running_app().root.get_screen('dd_screen').ids.textinput_num.text
</code>```

Here, textinput_num is the id of the relevant text input box. I am able to print the value of the text input box and also check the length of the string. Note: I have used the input_filter: 'int' statement to allow only numbers in the text input box. I understand that dd_input shall receive a string value. So, I tried to convert it into an integer value and perform a numerical operation.

However, I get the following error: ValueError: invalid literal for int() with base 10:

I looked up in Google and it seems that this is an issue with the data type being handled.

Can you please help me understand what is going wrong here? What is the right way to access and read numerical values from a text input box?

The weirdest part is that this error is intermittent in nature for the same piece of code. Sometimes it returns the error and some times it does not.

答:
You mentioned that the error is "intermittent in nature". I may be wrong but I think this is what is happening. You are getting an exception/error when the textinput field is blank/empty. Essentially, this means the value of dd_input is null or it points to an empty string, which cannot be converted to an integer. Hence, the error.

Add a condition to handle the exception and see what happens:

```<code>if dd_input == '':
            dd_input="0"
</code>```

Body:
I have recently started learning Kivy and have encountered a weird error when handling text / numbers entered in a TextInput box.

The Kivy Code looks like this:

BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'horizontal'
            Label:
                text: 'No. of buttons:'
                markup: True
                color: 0, 0, 0, 1
            CustomTextInput:
                id: textinput_num
                max_characters: 2
                multiline: False
                input_filter: 'int'

The relevant Python code looks like this:

class DropDownScreen(Screen):
    def add_dd_values(self):
        dd_input = App.get_running_app().root.get_screen('dd_screen').ids.textinput_num.text
        print("TextInputBox: ", dd_input, "\n")
        print("Length: ",len(dd_input))
        print(int(dd_input)+1)

I have referenced the value of the text input box as follows:

dd_input = App.get_running_app().root.get_screen('dd_screen').ids.textinput_num.text

Here, textinput_num is the id of the relevant text input box. I am able to print the value of the text input box and also check the length of the string. Note: I have used the input_filter: 'int' statement to allow only numbers in the text input box. I understand that dd_input shall receive a string value. So, I tried to convert it into an integer value and perform a numerical operation.

However, I get the following error: ValueError: invalid literal for int() with base 10:

I looked up in Google and it seems that this is an issue with the data type being handled.

Can you please help me understand what is going wrong here? What is the right way to access and read numerical values from a text input box?

The weirdest part is that this error is intermittent in nature for the same piece of code. Sometimes it returns the error and some times it does not.

Body:
You mentioned that the error is "intermittent in nature". I may be wrong but I think this is what is happening. You are getting an exception/error when the textinput field is blank/empty. Essentially, this means the value of dd_input is null or it points to an empty string, which cannot be converted to an integer. Hence, the error.

Add a condition to handle the exception and see what happens:

if dd_input == '':
            dd_input="0"


问:
Spotipy Oauth2 Flow Storing Tokens
I am trying to implement oauth2 for a spotify app I am making with spotipy. I may have a bad understanding of how the flask session works, but I am trying to generate a Spotify API access token using SpotiPY with the Authorization Code Flow, and store it in Flask's session storage.

The program doesn't seem to be able to store it, and therefore later runs in to an error when trying to call it. Here is a visual explanation with images and captions: https://imgur.com/a/KiYZFiQ

```<code>from flask import Flask, render_template, redirect, request, session, make_response,session,redirect
import spotipy
import spotipy.util as util
from credentz import *
import time
import json
app = Flask(__name__)

app.secret_key = SSK

API_BASE = 'https://accounts.spotify.com'

# Make sure you add this to Redirect URIs in the setting of the application dashboard
REDIRECT_URI = "http://localhost:8080"

SCOPE = 'playlist-modify-private,playlist-modify-public,user-top-read'

# Set this to True for testing but you probaly want it set to False in production.
SHOW_DIALOG = True

# authorization-code-flow Step 1. Have your application request authorization;
# the user logs in and authorizes access
@app.route("/")
def verify():
    # Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
    auth_url = sp_oauth.get_authorize_url()
    print(auth_url)
    return redirect(auth_url)

@app.route("/index")
def index():
    return render_template("index.html")

# authorization-code-flow Step 2.
# Have your application request refresh and access tokens;
# Spotify returns access and refresh tokens
@app.route("/api_callback")
def api_callback():
    # Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
    session.clear()
    code = request.args.get('code')
    token_info = sp_oauth.get_access_token(code)

    # Saving the access token along with all other token related info
    session["token_info"] = token_info

    return redirect("index")

# authorization-code-flow Step 3.
# Use the access token to access the Spotify Web API;
# Spotify returns requested data
@app.route("/go", methods=['POST'])
def go():
    session['token_info'], authorized = get_token(session)
    session.modified = True
    if not authorized:
        return redirect('/')
    data = request.form
    sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))
    response = sp.current_user_top_tracks(limit=data['num_tracks'], time_range=data['time_range'])

    # print(json.dumps(response))

    return render_template("results.html", data=data)

# Checks to see if token is valid and gets a new token if not
def get_token(session):
    token_valid = False
    token_info = session.get("token_info", {})

    # Checking if the session already has a token stored
    if not (session.get('token_info', False)):
        token_valid = False
        return token_info, token_valid

    # Checking if token has expired
    now = int(time.time())
    is_token_expired = session.get('token_info').get('expires_at') - now < 60

    # Refreshing token if it has expired
    if (is_token_expired):
        # Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
        sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
        token_info = sp_oauth.refresh_access_token(session.get('token_info').get('refresh_token'))

    token_valid = True
    return token_info, token_valid

if __name__ == "__main__":
    app.run(debug=True)

</code>```

I found this code elsewhere on the site. However, it appears that the module "credentz" doesn't exist. Anyone have an idea of how to store Tokens for multiple spotify accounts in spotipy?

答: An example flask API app has been added in the spotipy repo https://github.com/plamere/spotipy/blob/master/examples/app.py</p>

Title: Spotipy Oauth2 Flow Storing Tokens

Body:
I am trying to implement oauth2 for a spotify app I am making with spotipy. I may have a bad understanding of how the flask session works, but I am trying to generate a Spotify API access token using SpotiPY with the Authorization Code Flow, and store it in Flask's session storage.

The program doesn't seem to be able to store it, and therefore later runs in to an error when trying to call it. Here is a visual explanation with images and captions: https://imgur.com/a/KiYZFiQ

from flask import Flask, render_template, redirect, request, session, make_response,session,redirect
import spotipy
import spotipy.util as util
from credentz import *
import time
import json
app = Flask(__name__)

app.secret_key = SSK

API_BASE = 'https://accounts.spotify.com'

# Make sure you add this to Redirect URIs in the setting of the application dashboard
REDIRECT_URI = "http://localhost:8080"

SCOPE = 'playlist-modify-private,playlist-modify-public,user-top-read'

# Set this to True for testing but you probaly want it set to False in production.
SHOW_DIALOG = True

# authorization-code-flow Step 1. Have your application request authorization;
# the user logs in and authorizes access
@app.route("/")
def verify():
    # Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
    auth_url = sp_oauth.get_authorize_url()
    print(auth_url)
    return redirect(auth_url)

@app.route("/index")
def index():
    return render_template("index.html")

# authorization-code-flow Step 2.
# Have your application request refresh and access tokens;
# Spotify returns access and refresh tokens
@app.route("/api_callback")
def api_callback():
    # Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
    session.clear()
    code = request.args.get('code')
    token_info = sp_oauth.get_access_token(code)

    # Saving the access token along with all other token related info
    session["token_info"] = token_info

    return redirect("index")

# authorization-code-flow Step 3.
# Use the access token to access the Spotify Web API;
# Spotify returns requested data
@app.route("/go", methods=['POST'])
def go():
    session['token_info'], authorized = get_token(session)
    session.modified = True
    if not authorized:
        return redirect('/')
    data = request.form
    sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))
    response = sp.current_user_top_tracks(limit=data['num_tracks'], time_range=data['time_range'])

    # print(json.dumps(response))

    return render_template("results.html", data=data)

# Checks to see if token is valid and gets a new token if not
def get_token(session):
    token_valid = False
    token_info = session.get("token_info", {})

    # Checking if the session already has a token stored
    if not (session.get('token_info', False)):
        token_valid = False
        return token_info, token_valid

    # Checking if token has expired
    now = int(time.time())
    is_token_expired = session.get('token_info').get('expires_at') - now < 60

    # Refreshing token if it has expired
    if (is_token_expired):
        # Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
        sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
        token_info = sp_oauth.refresh_access_token(session.get('token_info').get('refresh_token'))

    token_valid = True
    return token_info, token_valid

if __name__ == "__main__":
    app.run(debug=True)

I found this code elsewhere on the site. However, it appears that the module "credentz" doesn't exist. Anyone have an idea of how to store Tokens for multiple spotify accounts in spotipy?


问:
Nuxt EventBus - usage for many events
in my Nuxt app I have a Canvas that listens for mouse events. Now I want to send those mouse events to the DOM, everything is working fine. But I'm concerned that there are too many events for Vue, because there is like thousands of them. When I switch to the Vue dev tools, my Computer already begins to stutter. I feel like Vue is only made for simple click events, but I'm using it for a ton. Is there a better way to handle that? </p>

```<code>init(){
    document.addEventListener("mousemove", this.mouseMove.bind(this));
}
mouseMove(e){
    EventBus.$emit("MOUSEMOVE", e);
}
</code>```

答:
How about using debouncer for a short time limit.

I'm guessing that your DOM is not updating on every event and it takes some to self update. So slow down the event bus emit like in every 50/100 ms there will be an event fire. You can emit to event bus on every 50 MiliSecond or as per as your need. That would be helpful even if you solve the problem in other way.

Title: Nuxt EventBus - usage for many events

Body:
in my Nuxt app I have a Canvas that listens for mouse events. Now I want to send those mouse events to the DOM, everything is working fine. But I'm concerned that there are too many events for Vue, because there is like thousands of them. When I switch to the Vue dev tools, my Computer already begins to stutter. I feel like Vue is only made for simple click events, but I'm using it for a ton. Is there a better way to handle that?

init(){
    document.addEventListener("mousemove", this.mouseMove.bind(this));
}
mouseMove(e){
    EventBus.$emit("MOUSEMOVE", e);
}


问:
python random choice choosing nothing
I have a method to generate random string that always starts with a character and has length of at minimum 1.

```<code>class Util:
    @staticmethod
    def get_random_name():
        N = r.randint(0, 5)
        return "".join(
            r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
            )
        ).join(
            r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
                + string.digits
            )
            for _ in range(N)
        )
</code>```

Now when I do this:

```<code>for i in range(0,50):
    logging.debug(str(i)+" -- "+Util().get_random_name())
</code>```

Some of them gives me empty string or sometimes it starts with number.

What am I missing ?

Check the log:

答:
The problem is you are using the join function, which is for joining together multiple strings with some symbol. But what you really want is to concatenate strings which in Python is done using the + sign.

Let's look at the join function:

```<code>>>> '|'.join('abc')
'a|b|c'
</code>```

Let's look at this output:

```<code>aHCHRH1H0
</code>```

What happened here is that you generate the first letter H and then the string aCR10, which is correct. But then instead of + a join occurs:

```<code>>>> 'H'.join('aCR10')
'aHCHRH1H0'
</code>```

Fixed version:

```<code>class Util:
    @staticmethod
    def get_random_name():
        N = r.randint(0, 5)
        return r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
        ) + ''.join(
            r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
                + string.digits
            )
            for _ in range(N)
        )
</code>```

Title: python random choice choosing nothing

Body:
I have a method to generate random string that always starts with a character and has length of at minimum 1.

class Util:
    @staticmethod
    def get_random_name():
        N = r.randint(0, 5)
        return "".join(
            r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
            )
        ).join(
            r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
                + string.digits
            )
            for _ in range(N)
        )

Now when I do this:

for i in range(0,50):
    logging.debug(str(i)+" -- "+Util().get_random_name())

Some of them gives me empty string or sometimes it starts with number.

What am I missing ?

Check the log:

Body:
The problem is you are using the join function, which is for joining together multiple strings with some symbol. But what you really want is to concatenate strings which in Python is done using the + sign.

Let's look at the join function:

>>> '|'.join('abc')
'a|b|c'

Let's look at this output:

aHCHRH1H0

What happened here is that you generate the first letter H and then the string aCR10, which is correct. But then instead of + a join occurs:

>>> 'H'.join('aCR10')
'aHCHRH1H0'

Fixed version:

class Util:
    @staticmethod
    def get_random_name():
        N = r.randint(0, 5)
        return r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
        ) + ''.join(
            r.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
                + string.digits
            )
            for _ in range(N)
        )


问:
Wordpress Lightbox shows the first image only
I tried 3 different plugins for images Lightbox, but all of them (the first was Elementor's lightbox) are showing only the first image. I'm using Infinitifree hosting, so it can be the problem? I also unchecked the "lazy loading" for images.

Now I'm using SimpLy Gallery Block plugin.

答: Most likely the problem might not be the hosting company but the plugin setting. Which theme are you using?</p>


问:
get array values in python
I have the values arr1  as 25,26 and arr2 values as A,B

Its always that the number of values in arr1 and arr2 are equal

My question is that

```<code>          for i in arr1.split(","):
                print i //prints 25 and 26
</code>```

is it not possible to get the values of arr2 in the same loop or should  another loop be written only for this purpose.Basically the idea is that map the values of arr1 and arr2

答: I don't think it can be as elegant as you hope.  You have to split both, then loop over the size of one array (assuming the other has the same size).</p>

Title: get array values in python

Body:
I have the values arr1  as 25,26 and arr2 values as A,B

Its always that the number of values in arr1 and arr2 are equal

My question is that

          for i in arr1.split(","):
                print i //prints 25 and 26

is it not possible to get the values of arr2 in the same loop or should  another loop be written only for this purpose.Basically the idea is that map the values of arr1 and arr2


问:
Why do I keep getting a 500(Internal Server Error) GET http://localhost:3000/favicon.ico 500 (Internal Server Error)?
When I began this project I didn't keep anything from the CRA files that are generated, so why do I still get this error, where is it comming from?

```<code>GET http://localhost:3000/favicon.ico 500 (Internal Server Error)
</code>```

As I said, I have created my own ./public/index.html in which I am not specifying a favicon.
What is the source of this error and how can I get rid of it?

答:
As I said, I have created my own ./public/index.html in which I am not specifying a favicon. What is the source of this error and how can I get rid of it?

Browsers automatically request the favicon. If no favicon is specified in the html file an automatic request is make to <protocol>://<domain>/favicon.ico

I added an empty link for favicon and i doesn't work. <link rel="shortcut icon" href="">

The browser still sees an empty href as a favicon that has not been specified in the html file.

You can set your own favicon url via the href in the <link rel="shortcut icon"> and serve a .ico file or just ignore the requests.
At this time I'm not aware of a way to disable the favicon requests entirely.

Body:
When I began this project I didn't keep anything from the CRA files that are generated, so why do I still get this error, where is it comming from?

GET http://localhost:3000/favicon.ico 500 (Internal Server Error)

As I said, I have created my own ./public/index.html in which I am not specifying a favicon.
What is the source of this error and how can I get rid of it?


问:
js-cookie samesite and httpOnly
I'm using js-cookie 2.2.0 and I would like to add the samesite flag but i don't find anything about.

Here my actual code.

```<code>Cookies.set('traffweb' + cookieName, cookieStr, {
  expires: 7,
  path: window.location.href,
  secure: true
})
</code>```

how can I add a samesite flag?

答:
I added a "sameSite" attribute and the warning went away</p>

```<code>Cookies.set('name', 'value', { sameSite:'strict' });
</code>```

Title: js-cookie samesite and httpOnly

Body:
I'm using js-cookie 2.2.0 and I would like to add the samesite flag but i don't find anything about.

Here my actual code.

Cookies.set('traffweb' + cookieName, cookieStr, {
  expires: 7,
  path: window.location.href,
  secure: true
})

how can I add a samesite flag?

Body:
I added a "sameSite" attribute and the warning went away

Cookies.set('name', 'value', { sameSite:'strict' });


问:
Spotipy Refreshing Access Token Oauth2
I am trying to make a program that will remove songs from spotify playlists. Currently I am unable to refresh the auth tokens despite having them saved on my hard drive and specifying the cache paths when making oauth objects.

```<code>from bottle import route, run, request
import spotipy
from spotipy import oauth2
import time

PORT_NUMBER = 8080
SPOTIPY_CLIENT_ID = 'e1bb48ed8b594aeb9faf74f7e8915de7'
SPOTIPY_CLIENT_SECRET = 'dd6de8b7a0324d6ebf1fc0591e8e3220'
SPOTIPY_REDIRECT_URI = 'http://localhost:8080'
SCOPE = 'playlist-modify-public'
tracks = ['6DCZcSspjsKoFjzjrWoCdn']

def remove(sp_oauth):

    access_token = ""

    token_info = sp_oauth.get_cached_token()

    if token_info:
        if sp_oauth.is_token_expired:
            token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
            access_token = token_info['access_token']
        else:
            print ("Found cached token!")
            access_token = token_info['access_token']

    if access_token:
        print ("Access token available! Trying to get user information...")
        sp = spotipy.Spotify(access_token)
        results = sp.current_user_playlists()
        userinfo = sp.current_user()
        userid = userinfo['id']
        for items in results['items']:
            if userid == items['owner']['id']:
                sp.user_playlist_remove_all_occurrences_of_tracks(items['owner']['id'],items['id'],tracks)
                print("removed from " + items['owner']['display_name'] + " s list  " + items['name'])

example =oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE,cache_path=r'C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\Caches\example')

remove(example)
</code>```

The error I get is

```<code>Traceback (most recent call last):
  File "C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\unfollowLists.py", line 212, in <module>
    remove(blake)
  File "C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\unfollowLists.py", line 63, in remove
    if sp_oauth.is_token_expired:
AttributeError: 'SpotifyOAuth' object has no attribute 'is_token_expired'
</code>```

The version of spotipy I have is 2.4.4

答:
Update your version of spotipy and the token should be refreshed automatically</p>

```<code>pip3 install spotipy --upgrade
</code>```

Title: Spotipy Refreshing Access Token Oauth2

Body:
I am trying to make a program that will remove songs from spotify playlists. Currently I am unable to refresh the auth tokens despite having them saved on my hard drive and specifying the cache paths when making oauth objects.

from bottle import route, run, request
import spotipy
from spotipy import oauth2
import time

PORT_NUMBER = 8080
SPOTIPY_CLIENT_ID = 'e1bb48ed8b594aeb9faf74f7e8915de7'
SPOTIPY_CLIENT_SECRET = 'dd6de8b7a0324d6ebf1fc0591e8e3220'
SPOTIPY_REDIRECT_URI = 'http://localhost:8080'
SCOPE = 'playlist-modify-public'
tracks = ['6DCZcSspjsKoFjzjrWoCdn']

def remove(sp_oauth):

    access_token = ""

    token_info = sp_oauth.get_cached_token()

    if token_info:
        if sp_oauth.is_token_expired:
            token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
            access_token = token_info['access_token']
        else:
            print ("Found cached token!")
            access_token = token_info['access_token']

    if access_token:
        print ("Access token available! Trying to get user information...")
        sp = spotipy.Spotify(access_token)
        results = sp.current_user_playlists()
        userinfo = sp.current_user()
        userid = userinfo['id']
        for items in results['items']:
            if userid == items['owner']['id']:
                sp.user_playlist_remove_all_occurrences_of_tracks(items['owner']['id'],items['id'],tracks)
                print("removed from " + items['owner']['display_name'] + " s list  " + items['name'])

example =oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE,cache_path=r'C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\Caches\example')

remove(example)

The error I get is

Traceback (most recent call last):
  File "C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\unfollowLists.py", line 212, in <module>
    remove(blake)
  File "C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\unfollowLists.py", line 63, in remove
    if sp_oauth.is_token_expired:
AttributeError: 'SpotifyOAuth' object has no attribute 'is_token_expired'

The version of spotipy I have is 2.4.4

Body:
Update your version of spotipy and the token should be refreshed automatically

pip3 install spotipy --upgrade


问:
Last item not removed from cart in Woocommerce
I can’t remove the last item from cart. I add several products to the cart - remove all items, but the last are not. Ajax works, shows a message that the product has been removed from cart, but visually - it has not gone away. After refreshing the page, the cart is empty.</p>

答:
I had the same issue on one of our websites.  I have been following the javascript in /woocommerce/assets/js/frontend/cart.js and I noticed that there is the following line of code $( '.woocommerce-cart-form__contents' ).closest( '.woocommerce' ).replaceWith( $cart_html ); which replaces all the cart content from the cart page.

Most probably you have overridden the default woocommerce cart template and have removed the class .woocommerce-cart-form__contents from your custom template, therefore the html cannot be replaced by javascript.

You have 2 options to solve this:

Option 1:
Try to include the .woocommerce-cart-form__contents in your cart.php template

Option 2:
In case you prefer not to add that class, woocommerce triggers the javascript event wc_cart_emptied when the cart has been emptied. Therefore you can use the below code in your theme's javascript to make sure that you empty the DOM elements from the cart page when this is triggered:

```<code>    /**
     * When Cart has been emptied we need to make sure that cart form and cart collaterals in /cart page are removed.
     *
     * @param {Event} e
     */
    function cartEmptied(e) {
        //The below 2 elements can be changed according to the classes you use in your custom cart template
        var cartForm = $('.woocommerce-cart-form');
        var cartCollaterals = $('.cart-collaterals');

        if (cartForm.length > 0) {
            cartForm.remove();
        }

        if (cartCollaterals.length > 0) {
            cartCollaterals.remove();
        }
    }
    $(document.body).on('wc_cart_emptied', cartEmptied);
</code>```

Body:
I had the same issue on one of our websites.  I have been following the javascript in /woocommerce/assets/js/frontend/cart.js and I noticed that there is the following line of code $( '.woocommerce-cart-form__contents' ).closest( '.woocommerce' ).replaceWith( $cart_html ); which replaces all the cart content from the cart page.

Most probably you have overridden the default woocommerce cart template and have removed the class .woocommerce-cart-form__contents from your custom template, therefore the html cannot be replaced by javascript.

You have 2 options to solve this:

Option 1:
Try to include the .woocommerce-cart-form__contents in your cart.php template

Option 2:
In case you prefer not to add that class, woocommerce triggers the javascript event wc_cart_emptied when the cart has been emptied. Therefore you can use the below code in your theme's javascript to make sure that you empty the DOM elements from the cart page when this is triggered:

    /**
     * When Cart has been emptied we need to make sure that cart form and cart collaterals in /cart page are removed.
     *
     * @param {Event} e
     */
    function cartEmptied(e) {
        //The below 2 elements can be changed according to the classes you use in your custom cart template
        var cartForm = $('.woocommerce-cart-form');
        var cartCollaterals = $('.cart-collaterals');

        if (cartForm.length > 0) {
            cartForm.remove();
        }

        if (cartCollaterals.length > 0) {
            cartCollaterals.remove();
        }
    }
    $(document.body).on('wc_cart_emptied', cartEmptied);


问:
Google Maps Api v3 - set map position in runtime
How can I change position of the map, from where it is pointing now, to ie. 45.00,19.00, but in a runtime, now when map is initialized?

my application have to "jump" from some coordinates to other, so that's why I need this ability.

答:
Define the place where to position

Pass that to map.setCenter()

var map;

function initMap() {

    var container = document.getElementById('map');
    var options = {
        zoom: 18,
        gestureHandling: 'cooperative',
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(container, options);

    var myPlace = { lat: 23.7266, lng: 90.4216 };
    map.setCenter(myPlace);
}
```


问:
How do you add CSS with Javascript?
How do you add CSS rules (eg strong { color: red }) by use of Javascript?

答:
The solution by Ben Blank wouldn't work in IE8 for me.

However this did work in IE8

```<code>function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}
</code>```

OwnerDisplayName: nickf

Title: How do you add CSS with Javascript?

LastEditorDisplayName: nickf

Body:
The solution by Ben Blank wouldn't work in IE8 for me.

However this did work in IE8

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}


问:
loss(y, y) != 0 (same labels and predictions, non-zero loss)

import numpy as np
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.models import Model  # TF 2.2.0

#%%#######################################################
ipt = Input(batch_shape=(128, 28, 28, 1))
x   = Flatten()(ipt)
out = Dense(10, activation='softmax')(x)
model = Model(ipt, out)
model.compile('adam', 'categorical_crossentropy')

#%%#######################################################
x = np.random.uniform(0, 1, model.input_shape)

pred = model(x, training=True)  # =False also works
loss = model.compiled_loss(pred, pred)
print(loss)
```

<p>Output:</p>

<pre class="lang-py prettyprint-override"><code>tf.Tensor(1.9904033, shape=(), dtype=float32)
</code>```

What's the deal?

答:
That's just because of how the categorical_crossentropy loss works. If you try with [0,0,0,1,0,0,0,0,0,0], it is zero. If you change categorical_crossentropy to mse in your original code, you also get zero.

```<code>import numpy as np
import tensorflow as tf  # TF 2.2.0
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.models import Model

ipt = Input(shape=(28, 28, 1))
x   = Flatten()(ipt)
out = Dense(10, activation='softmax')(x)
model = Model(ipt, out)
model.compile('adam', 'categorical_crossentropy')

label = tf.one_hot([5,3,2], depth=10)
# tf.Tensor(
# [[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
#  [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]], shape=(3, 10), dtype=float32)
loss = model.compiled_loss(label, label)
print(loss) # tf.Tensor(1.1920929e-07, shape=(), dtype=float32)
</code>```

EDIT:

a numpy implementation of the categorical crossentropy loss would be:

```<code>import numpy as np
def cce(y_label,y_pred):
    return np.sum(-y_label*np.log(y_pred))
x = np.random.uniform(0, 1, (10,))
print(cce(x,x)) # which yields values like 1.9904033
</code>```

This shows why it is not zero, because you take the log of the prediction and multiply it by the label and take the negative. So the question to what's the deal is: this is working as intended.

Body:
import numpy as np
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.models import Model  # TF 2.2.0

#%%#######################################################
ipt = Input(batch_shape=(128, 28, 28, 1))
x   = Flatten()(ipt)
out = Dense(10, activation='softmax')(x)
model = Model(ipt, out)
model.compile('adam', 'categorical_crossentropy')

#%%#######################################################
x = np.random.uniform(0, 1, model.input_shape)

pred = model(x, training=True)  # =False also works
loss = model.compiled_loss(pred, pred)
print(loss)

Output:

tf.Tensor(1.9904033, shape=(), dtype=float32)

What's the deal?

Body:
That's just because of how the categorical_crossentropy loss works. If you try with [0,0,0,1,0,0,0,0,0,0], it is zero. If you change categorical_crossentropy to mse in your original code, you also get zero.

import numpy as np
import tensorflow as tf  # TF 2.2.0
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.models import Model

ipt = Input(shape=(28, 28, 1))
x   = Flatten()(ipt)
out = Dense(10, activation='softmax')(x)
model = Model(ipt, out)
model.compile('adam', 'categorical_crossentropy')

label = tf.one_hot([5,3,2], depth=10)
# tf.Tensor(
# [[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
#  [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]], shape=(3, 10), dtype=float32)
loss = model.compiled_loss(label, label)
print(loss) # tf.Tensor(1.1920929e-07, shape=(), dtype=float32)

EDIT:

a numpy implementation of the categorical crossentropy loss would be:

import numpy as np
def cce(y_label,y_pred):
    return np.sum(-y_label*np.log(y_pred))
x = np.random.uniform(0, 1, (10,))
print(cce(x,x)) # which yields values like 1.9904033

This shows why it is not zero, because you take the log of the prediction and multiply it by the label and take the negative. So the question to what's the deal is: this is working as intended.


问:
Should I store data as a variable in javascript or in a text file?
I am creating a webpage, and I want it to display a random text. Suppose I have around 1000 sentences (for example), and I want to select a random sentence from the list.

Which would be a better way: to store all these sentences in a javascript array or to store them in a text file, and then use javascript to read a line from the file?

Essentially, how does this impact the performance? And the 1000 lines are just for example, I want to know how the general approach should be for increasing variable size.

The desired result is that the webpage should load fast, and should not be computationally heavy on the client side.

Note that the page is static and the sentences are immutable and won't change over the course of time.

答:
If you're concerned about performance, storing them in an array is always going to be a huge boost in performance than storing them in a file and reading them which comes with additional cost.

Just imagine doing this for getting your variables.(I'm assuming it's kept in your local machine and there's no network call involved) vs keeping the variables in-memory

```<code>  var myFile = new XMLHttpRequest();
    myFile.open("GET", file, false);
    myFile.onreadystatechange = function ()
    {
        if(myFile.readyState === 4)
        {
            if(myFile.status === 200 || myFile.status == 0)
            {
                var allText = myFile.responseText;
                //Finally You get it Here. Phew!!!
            }
        }
    }
</code>```

You can also consider storing in localstorage as the variable size grows significantly. That'd perform better than the text file. However, you need to keep in mind, you can not directly store, objects and array in localstorage. You'll need to strigify and and store it and again while retrieving them, you'll need to parse them, which is at additional cost.

Body:
If you're concerned about performance, storing them in an array is always going to be a huge boost in performance than storing them in a file and reading them which comes with additional cost.

Just imagine doing this for getting your variables.(I'm assuming it's kept in your local machine and there's no network call involved) vs keeping the variables in-memory

  var myFile = new XMLHttpRequest();
    myFile.open("GET", file, false);
    myFile.onreadystatechange = function ()
    {
        if(myFile.readyState === 4)
        {
            if(myFile.status === 200 || myFile.status == 0)
            {
                var allText = myFile.responseText;
                //Finally You get it Here. Phew!!!
            }
        }
    }

You can also consider storing in localstorage as the variable size grows significantly. That'd perform better than the text file. However, you need to keep in mind, you can not directly store, objects and array in localstorage. You'll need to strigify and and store it and again while retrieving them, you'll need to parse them, which is at additional cost.


问:
Problems with install build of google cloud storage cpp library on Linux
I am trying to build and install google-cloud-cpp on a Rehat 7 system. I am using the cmake install option using instructions found on https://github.com/googleapis/google-cloud-cpp-common/blob/master/INSTALL.md.

I have installed all of the prerequisites.

The last 2 steps, according to the instructions are:

cmake -H. -Bcmake-out
cmake --build cmake-out --target install

When I run the second command command, I get link errors which appear to be from google test:

```<code>[ 22%] Built target google_cloud_cpp_common
[ 22%] Built target google_cloud_cpp_testing_grpc
[ 22%] Built target google_cloud_cpp_grpc_utils
[ 23%] Built target google_cloud_cpp_testing
[ 23%] Linking CXX executable internal_background_threads_impl_test
bin/ld: CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/internal/background_threads_impl_test.cc.o: in function `testing::AssertionResult::AppendMessage(testing::Message const&)':
background_threads_impl_test.cc:(.text._ZN7testing15AssertionResult13AppendMessageERKNS_7MessageE[_ZN7testing15AssertionResult13AppendMessageERKNS_7MessageE]+0x77): undefined reference to `testing::Message::GetString[abi:cxx11]() const'
bin/ld: CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/internal/background_threads_impl_test.cc.o: in function `testing::AssertionResult testing::internal::CmpHelperEQFailure<std::future_status, std::future_status>(char const*, char const*, std::future_status const&, std::future_status const&)':
background_threads_impl_test.cc:(.text._ZN7testing8internal18CmpHelperEQFailureISt13future_statusS2_EENS_15AssertionResultEPKcS5_RKT_RKT0_[_ZN7testing8internal18CmpHelperEQFailureISt13future_statusS2_EENS_15AssertionResultEPKcS5_RKT_RKT0_]+0x6c): undefined reference to `testing::internal::EqFailure(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
bin/ld: CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/internal/background_threads_impl_test.cc.o: in function `testing::AssertionResult testing::internal::CmpHelperEQFailure<std::thread::id, std::thread::id>(char const*, char const*, std::thread::id const&, std::thread::id const&)':
background_threads_impl_test.cc:(.text._ZN7testing8internal18CmpHelperEQFailureINSt6thread2idES3_EENS_15AssertionResultEPKcS6_RKT_RKT0_[_ZN7testing8internal18CmpHelperEQFailureINSt6thread2idES3_EENS_15AssertionResultEPKcS6_RKT_RKT0_]+0x6c): undefined reference to `testing::internal::EqFailure(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
collect2: error: ld returned 1 exit status
gmake[2]: *** [google/cloud/CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/build.make:167: google/cloud/internal_background_threads_impl_test] Error 1
gmake[1]: *** [CMakeFiles/Makefile2:2245: google/cloud/CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/all] Error 2
gmake: *** [Makefile:141: all] Error 2
</code>```

This library has been installed.

Can anyone help me with this?

Thanks for any information,

John

答: There appears to be a setup mechanism in google-cloud-cpp/doc/setup-cmake-environment.md which differs from directions in INSTALL.md. The instructions in this file describe how to setup your workstation to build the Google Cloud C++ client libraries using CMake, which is what I was attempting. Using these instructions result in a good build.</p>

Body:
I am trying to build and install google-cloud-cpp on a Rehat 7 system. I am using the cmake install option using instructions found on https://github.com/googleapis/google-cloud-cpp-common/blob/master/INSTALL.md.

I have installed all of the prerequisites.

The last 2 steps, according to the instructions are:

cmake -H. -Bcmake-out
cmake --build cmake-out --target install

When I run the second command command, I get link errors which appear to be from google test:

[ 22%] Built target google_cloud_cpp_common
[ 22%] Built target google_cloud_cpp_testing_grpc
[ 22%] Built target google_cloud_cpp_grpc_utils
[ 23%] Built target google_cloud_cpp_testing
[ 23%] Linking CXX executable internal_background_threads_impl_test
bin/ld: CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/internal/background_threads_impl_test.cc.o: in function `testing::AssertionResult::AppendMessage(testing::Message const&)':
background_threads_impl_test.cc:(.text._ZN7testing15AssertionResult13AppendMessageERKNS_7MessageE[_ZN7testing15AssertionResult13AppendMessageERKNS_7MessageE]+0x77): undefined reference to `testing::Message::GetString[abi:cxx11]() const'
bin/ld: CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/internal/background_threads_impl_test.cc.o: in function `testing::AssertionResult testing::internal::CmpHelperEQFailure<std::future_status, std::future_status>(char const*, char const*, std::future_status const&, std::future_status const&)':
background_threads_impl_test.cc:(.text._ZN7testing8internal18CmpHelperEQFailureISt13future_statusS2_EENS_15AssertionResultEPKcS5_RKT_RKT0_[_ZN7testing8internal18CmpHelperEQFailureISt13future_statusS2_EENS_15AssertionResultEPKcS5_RKT_RKT0_]+0x6c): undefined reference to `testing::internal::EqFailure(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
bin/ld: CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/internal/background_threads_impl_test.cc.o: in function `testing::AssertionResult testing::internal::CmpHelperEQFailure<std::thread::id, std::thread::id>(char const*, char const*, std::thread::id const&, std::thread::id const&)':
background_threads_impl_test.cc:(.text._ZN7testing8internal18CmpHelperEQFailureINSt6thread2idES3_EENS_15AssertionResultEPKcS6_RKT_RKT0_[_ZN7testing8internal18CmpHelperEQFailureINSt6thread2idES3_EENS_15AssertionResultEPKcS6_RKT_RKT0_]+0x6c): undefined reference to `testing::internal::EqFailure(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
collect2: error: ld returned 1 exit status
gmake[2]: *** [google/cloud/CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/build.make:167: google/cloud/internal_background_threads_impl_test] Error 1
gmake[1]: *** [CMakeFiles/Makefile2:2245: google/cloud/CMakeFiles/common_grpc_utils_internal_background_threads_impl_test.dir/all] Error 2
gmake: *** [Makefile:141: all] Error 2

This library has been installed.

Can anyone help me with this?

Thanks for any information,

John


问:
How to remove null rows from sql query result?
I have a SQL query in which I am getting some records.
Query is:

```<code>    select c.Id, c.FirstName, dbo.GetClientStaffContacts(c.Id, '27,31') as Staff from Client c order by c.Id
</code>```

Result is:

I want only those rows that are not having null values in column Staff.

Any help would be appreciated.
Thank you.

答:
```<code>select
  c.Id, c.FirstName, dbo.GetClientStaffContacts(c.Id, '27,31') as Staff
from
  Client c
where
  dbo.GetClientStaffContacts(c.Id, '27,31') is not null
order
  by c.Id
</code>```

Body:
I have a SQL query in which I am getting some records.
Query is:

    select c.Id, c.FirstName, dbo.GetClientStaffContacts(c.Id, '27,31') as Staff from Client c order by c.Id

Result is:

I want only those rows that are not having null values in column Staff.

Any help would be appreciated.
Thank you.


问:
gcc shared library "undefined reference" on nested dependencies
g++ 5.4.0

Ubuntu 16.04

i have several shared libraries and here is the abstraction of them:

libtest0.so: definition of `void foo()`
libtest1.so: `extern void foo()`, and not depends on libtest0.so
libtest2.so: use libtest1.so and depends on libtest1.so
```

<p>and now i have a binary:</p>

<pre class="lang-sh prettyprint-override"><code>a.out: use libtest2.so
</code>```

of course a.out has undefined symbol of foo(). To resolve it, i tried:

g++ main.cc -L. -ltest2 -ltest0
```

<p>since libtest0.so has definition of <code>foo()</code>.</p>

<p>However, it does not work:</p>

<pre class="lang-sh prettyprint-override"><code>$g++ -g main.cc -L. -ltest2 -ltest0
libtest1.so: undefined reference to `foo'
collect2: error: ld returned 1 exit status
</code>```

My questions are:

why does this "undefined reference" happen?

any solution to tell the linker that libtest0.so has definition of foo()?

thanks.

Update1:

if i link libtest0 when compile libtest2, then compile:

g++ -g main.cc -L. -ltest2
```

<p>everything is fine now. However, in the real world problem, i cannot change the linkage of libtest2.so</p>

<p><strong>Update2</strong></p>

<p>clang++ works with this cmd: (and the linker is ld, not lld)</p>

<pre class="lang-sh prettyprint-override"><code># clang version 11.0.0
clang++ -g main.cc -L. -ltest2 -ltest0
</code>```

Update3

an example is: https://gist.github.com/xgwang/da93edcc06542264157f600eb64bc082

just bash it on linux. Tested on Ubuntu 16.

答:
First, a quote from here (emphasis is mine):

Failure in final linking, undefined symbols

This is the most common error that happens while using --as-needed. It happens during the final linking stage of an executable (libraries don't create problems, because they are allowed to have undefined symbols). The executable linking stage dies because of an undefined symbol that is present in one of the libraries fed to the command line. However, the library is not used by the executable itself, thus it gets removed by --as-needed. This usually means that a library was not linked to another library, but was using it, and then relying on the final executable to link them together. This behavior is also an extra encumbrance on developers using that library because they have to check for the requirements.

As a workaround, instead of

g++ main.cc -L. -ltest2 -ltest0
```

<p>try</p>

<pre class="lang-none prettyprint-override"><code>g++ main.cc -L. -ltest2 -Wl,--no-as-needed -ltest0
</code>```

to disable --as-needed behaviour.

The minimal complete example that works for me:

#!/bin/bash

export LD_LIBRARY_PATH=.

g++ -fPIC -shared test0.cc -o libtest0.so
g++ -fPIC -shared test1.cc -o libtest1.so
g++ -fPIC -shared test2.cc -o libtest2.so -L. -ltest1

g++ main.cc -L. -ltest2 -Wl,--no-as-needed -ltest0
```

Body:
g++ 5.4.0

Ubuntu 16.04

i have several shared libraries and here is the abstraction of them:

libtest0.so: definition of `void foo()`
libtest1.so: `extern void foo()`, and not depends on libtest0.so
libtest2.so: use libtest1.so and depends on libtest1.so

and now i have a binary:

a.out: use libtest2.so

of course a.out has undefined symbol of foo(). To resolve it, i tried:

g++ main.cc -L. -ltest2 -ltest0

since libtest0.so has definition of foo().

However, it does not work:

$g++ -g main.cc -L. -ltest2 -ltest0
libtest1.so: undefined reference to `foo'
collect2: error: ld returned 1 exit status

My questions are:

why does this "undefined reference" happen?

any solution to tell the linker that libtest0.so has definition of foo()?

thanks.

Update1:

if i link libtest0 when compile libtest2, then compile:

g++ -g main.cc -L. -ltest2

everything is fine now. However, in the real world problem, i cannot change the linkage of libtest2.so

Update2

clang++ works with this cmd: (and the linker is ld, not lld)

# clang version 11.0.0
clang++ -g main.cc -L. -ltest2 -ltest0

Update3

an example is: https://gist.github.com/xgwang/da93edcc06542264157f600eb64bc082

just bash it on linux. Tested on Ubuntu 16.

Body:
First, a quote from here (emphasis is mine):

Failure in final linking, undefined symbols

This is the most common error that happens while using --as-needed. It happens during the final linking stage of an executable (libraries don't create problems, because they are allowed to have undefined symbols). The executable linking stage dies because of an undefined symbol that is present in one of the libraries fed to the command line. However, the library is not used by the executable itself, thus it gets removed by --as-needed. This usually means that a library was not linked to another library, but was using it, and then relying on the final executable to link them together. This behavior is also an extra encumbrance on developers using that library because they have to check for the requirements.

As a workaround, instead of

g++ main.cc -L. -ltest2 -ltest0

try

g++ main.cc -L. -ltest2 -Wl,--no-as-needed -ltest0

to disable --as-needed behaviour.

The minimal complete example that works for me:

#!/bin/bash

export LD_LIBRARY_PATH=.

g++ -fPIC -shared test0.cc -o libtest0.so
g++ -fPIC -shared test1.cc -o libtest1.so
g++ -fPIC -shared test2.cc -o libtest2.so -L. -ltest1

g++ main.cc -L. -ltest2 -Wl,--no-as-needed -ltest0


问:
Print SubArray of Maximum Contiguous product in Array
Maximum Product Subarray
Given an array that contains both positive and negative integers, find the subarray of the maximum product .
Examples:

Input: arr[] = {6, -3, -10, 0, 2}
Output:  The subarray is {6, -3, -10}

Input: arr[] = {-1, -3, -10, 0, 60}
Output:  The subarray is {60}

Input: arr[] = {-2, -3, 0, -2, -40}
Output:  The subarray is {-2, -40}

Note: Finding the Max Product is done as using the kadane algo where i tried to reuse it for finding sub array but not able to break the part of finding the start index, finding end index is easy. end index is where res  < max.

```<code>public int maxProductSubArray(int arr[], int len) {

        int res = arr[0];

        int max = arr[0];
        int min = arr[0];

        for (int i = 1; i < len; i++) {

            int temp = max;

            max = Math.max(Math.max(max * arr[i], min * arr[i]), arr[i]);
            min = Math.min(Math.min(temp * arr[i], min * arr[i]), arr[i]);

            res = Math.max(res, max);
        }

        return res;

    }
</code>```

but not able to break the problem to find the SubArray.

答:
There are several possible ways to solve this problem:

Brute-Force

Divide-and-Conquer

Backtracking

I will only show you the Brute-Force-Solution. It is not the fastest solution, but in my opinion the most clear and easily understandable solution:

```<code>public class SubArray {

    public static int findMax(int[] num) {

        int max = num[0];
        int start = 0;
        int end = 0;
        for(int i = 0; i < num.length; i++) {   //Iterating over every possible starting position
            for(int j = i; j < num.length; j++) { //Iterating over every possible end position
                int multiply = 1;
                for(int k = i; k <= j; k++) {   //Multiply from start to end
                    multiply *= num[k];
                }
                if(max < multiply) {    //Did we find a new maximum?
                    max = multiply;
                    start = i;
                    end = j;
                }
            }
        }

        System.out.print("The subarray is {");  //Print subarray with highest product
        for(int i = start; i <= end; i++) {
            System.out.print(num[i]);
            if(i < end) {
                System.out.print(", ");
            }
        }
        System.out.println("}");

        return max;
    }

    public static void main(String[] args) {
        int[] array = {6, -3, -10, 0, 2} ;
        int max = findMax(array);
        System.out.println("Maximal product is: " + max);
    }
}
</code>```

Body:
Maximum Product Subarray
Given an array that contains both positive and negative integers, find the subarray of the maximum product .
Examples:

Input: arr[] = {6, -3, -10, 0, 2}
Output:  The subarray is {6, -3, -10}

Input: arr[] = {-1, -3, -10, 0, 60}
Output:  The subarray is {60}

Input: arr[] = {-2, -3, 0, -2, -40}
Output:  The subarray is {-2, -40}

Note: Finding the Max Product is done as using the kadane algo where i tried to reuse it for finding sub array but not able to break the part of finding the start index, finding end index is easy. end index is where res  < max.

public int maxProductSubArray(int arr[], int len) {

        int res = arr[0];

        int max = arr[0];
        int min = arr[0];

        for (int i = 1; i < len; i++) {

            int temp = max;

            max = Math.max(Math.max(max * arr[i], min * arr[i]), arr[i]);
            min = Math.min(Math.min(temp * arr[i], min * arr[i]), arr[i]);

            res = Math.max(res, max);
        }

        return res;

    }

but not able to break the problem to find the SubArray.

Body:
There are several possible ways to solve this problem:

Brute-Force

Divide-and-Conquer

Backtracking

I will only show you the Brute-Force-Solution. It is not the fastest solution, but in my opinion the most clear and easily understandable solution:

public class SubArray {

    public static int findMax(int[] num) {

        int max = num[0];
        int start = 0;
        int end = 0;
        for(int i = 0; i < num.length; i++) {   //Iterating over every possible starting position
            for(int j = i; j < num.length; j++) { //Iterating over every possible end position
                int multiply = 1;
                for(int k = i; k <= j; k++) {   //Multiply from start to end
                    multiply *= num[k];
                }
                if(max < multiply) {    //Did we find a new maximum?
                    max = multiply;
                    start = i;
                    end = j;
                }
            }
        }

        System.out.print("The subarray is {");  //Print subarray with highest product
        for(int i = start; i <= end; i++) {
            System.out.print(num[i]);
            if(i < end) {
                System.out.print(", ");
            }
        }
        System.out.println("}");

        return max;
    }

    public static void main(String[] args) {
        int[] array = {6, -3, -10, 0, 2} ;
        int max = findMax(array);
        System.out.println("Maximal product is: " + max);
    }
}


答:
There can be one approach to this:

You can use JS arrays to store all sentences in the browser's local storage, instead of storing it a file and repeatedly reading it.

Have a look to this on how to use local storage

Title: Should I store data as a variable in javascript or in a text file?

Body:
I am creating a webpage, and I want it to display a random text. Suppose I have around 1000 sentences (for example), and I want to select a random sentence from the list.

Which would be a better way: to store all these sentences in a javascript array or to store them in a text file, and then use javascript to read a line from the file?

Essentially, how does this impact the performance? And the 1000 lines are just for example, I want to know how the general approach should be for increasing variable size.

The desired result is that the webpage should load fast, and should not be computationally heavy on the client side.

Note that the page is static and the sentences are immutable and won't change over the course of time.


问:
How to filter by elements in array field in JSON format?
I have data set with one of the field containing array as below:

```<code>{ "name" : "James", "subjects" : [ "english", "french", "botany" ] },
{ "name" : "neo", "subjects" : [ "english", "physics" ] },
{ "name" : "john", "subjects" : [ "spanish", "mathematics" ] }
</code>```

Now i want to filter using Dataset.filter function by passing Column object. I tried isin function of Column and array_contains function of functions but did not work.

Is there a way to create Column object that will filter the dataset where an array field contains one of the values?

答:
As per my understanding, you are trying to find the records within DataFrame based on the array column which contains a particular string. For example, in this case, you are trying to find the records which contain the particular subject say "english".

Let first create a sample DataFrame

```<code>import org.apache.spark.sql.functions._

val json_data = """[{ "name" : "James", "subjects" : [ "english", "french", "botany" ] },
{ "name" : "neo", "subjects" : [ "english", "physics" ] },
{ "name" : "john", "subjects" : [ "spanish", "mathematics" ] }]"""
val df = spark.read.json(Seq(json_data).toDS).toDF
</code>```

Now let's try to find the records which contain the subject say "english". Here we can use the higher-order function "array_contains" which is available from spark 2.4.0.

```<code>df.filter(array_contains($"subjects", "english")).show(truncate=false)
</code>```

// Output

```<code>+-----+-------------------------+------------+
|name |subjects                 |contains_eng|
+-----+-------------------------+------------+
|James|[english, french, botany]|true        |
|neo  |[english, physics]       |true        |
+-----+-------------------------+------------+
</code>```

You can find more details about the functions here (scala and python).

I hope this helps.

Body:
I have data set with one of the field containing array as below:

{ "name" : "James", "subjects" : [ "english", "french", "botany" ] },
{ "name" : "neo", "subjects" : [ "english", "physics" ] },
{ "name" : "john", "subjects" : [ "spanish", "mathematics" ] }

Now i want to filter using Dataset.filter function by passing Column object. I tried isin function of Column and array_contains function of functions but did not work.

Is there a way to create Column object that will filter the dataset where an array field contains one of the values?

Body:
As per my understanding, you are trying to find the records within DataFrame based on the array column which contains a particular string. For example, in this case, you are trying to find the records which contain the particular subject say "english".

Let first create a sample DataFrame

import org.apache.spark.sql.functions._

val json_data = """[{ "name" : "James", "subjects" : [ "english", "french", "botany" ] },
{ "name" : "neo", "subjects" : [ "english", "physics" ] },
{ "name" : "john", "subjects" : [ "spanish", "mathematics" ] }]"""
val df = spark.read.json(Seq(json_data).toDS).toDF

Now let's try to find the records which contain the subject say "english". Here we can use the higher-order function "array_contains" which is available from spark 2.4.0.

df.filter(array_contains($"subjects", "english")).show(truncate=false)

// Output

+-----+-------------------------+------------+
|name |subjects                 |contains_eng|
+-----+-------------------------+------------+
|James|[english, french, botany]|true        |
|neo  |[english, physics]       |true        |
+-----+-------------------------+------------+

You can find more details about the functions here (scala and python).

I hope this helps.


问:
Strange side effect from a copy constructor
This simple code:

```<code>#include <iostream>
#include <vector>

struct my_struct
{
    int m_a;

    my_struct(int a) : m_a(a) { std::cout << "normal const " << m_a << std::endl; }

    my_struct(const my_struct&& other) : m_a(other.m_a) { std::cout << "copy move " << other.m_a << std::endl; }

    my_struct(const my_struct &other) : m_a(other.m_a) { std::cout << "copy const " << other.m_a << std::endl; }
};

class my_class
{
public:
    my_class() {}

    void append(my_struct &&m) { m_vec.push_back(m); }

private:
    std::vector<my_struct> m_vec;
};

int main()
{
    my_class m;

    m.append(my_struct(5));
    m.append(std::move(my_struct(6)));
}
</code>```

produces this output:

```<code>normal const 5
copy const 5
normal const 6
copy const 6
copy const 5
</code>```

The first call to append creates the object, and push_back creates a copy. Likewise, the second call to append creates the object, and push_back creates a copy. Now, a copy constructor of the first object is mysteriously called. Could someone explain me what happens? It looks like a strange side effect...

答:
Now, a copy constructor of the first object is mysteriously called. Could someone explain me what happens? It looks like a strange side effect...

When you call push_back on std::vector, vector may need to grow it's size as stated in the cppreference:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

You can use reserve before pushing anything to your vector. Try this:

```<code>class my_class
{
public:
    my_class()
    {
        m_vec.reserve(10); // Use any number that you want.
    }

    void append(my_struct &&m) { m_vec.push_back(m); }

private:
    std::vector<my_struct> m_vec;
};
</code>```

Few other issues with your program:

You need to fix signature of your move constructor as move constructor requires rvalue reference (more specifically, xvalue or prvalue). It should like this:

```<code>my_struct(my_struct&& other) noexcept : m_a(other.m_a)
{
    std::cout << "copy move " << other.m_a << std::endl;
}
</code>```

noexcept is required as we need to inform C++ (specifically std::vector) that move constructor and destructor does not throw, using noexcept. Then the move constructor will be called when the vector grows. See this.

The method append should be:

```<code>void append(my_struct &&m)
{
    m_vec.push_back(std::move(m));
}
</code>```

To know why we need to use std::move on rvalue reference, see this Is an Rvalue Reference an Rvalue?. It says:

Things that are declared as rvalue reference can be lvalues or rvalues. The distinguishing criterion is: if it has a name, then it is an lvalue. Otherwise, it is an rvalue.

If you don't use std::move, then copy constructor would be called.

Body:
This simple code:

#include <iostream>
#include <vector>

struct my_struct
{
    int m_a;

    my_struct(int a) : m_a(a) { std::cout << "normal const " << m_a << std::endl; }

    my_struct(const my_struct&& other) : m_a(other.m_a) { std::cout << "copy move " << other.m_a << std::endl; }

    my_struct(const my_struct &other) : m_a(other.m_a) { std::cout << "copy const " << other.m_a << std::endl; }
};

class my_class
{
public:
    my_class() {}

    void append(my_struct &&m) { m_vec.push_back(m); }

private:
    std::vector<my_struct> m_vec;
};

int main()
{
    my_class m;

    m.append(my_struct(5));
    m.append(std::move(my_struct(6)));
}

produces this output:

normal const 5
copy const 5
normal const 6
copy const 6
copy const 5

The first call to append creates the object, and push_back creates a copy. Likewise, the second call to append creates the object, and push_back creates a copy. Now, a copy constructor of the first object is mysteriously called. Could someone explain me what happens? It looks like a strange side effect...

Body:
Now, a copy constructor of the first object is mysteriously called. Could someone explain me what happens? It looks like a strange side effect...

When you call push_back on std::vector, vector may need to grow it's size as stated in the cppreference:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

You can use reserve before pushing anything to your vector. Try this:

class my_class
{
public:
    my_class()
    {
        m_vec.reserve(10); // Use any number that you want.
    }

    void append(my_struct &&m) { m_vec.push_back(m); }

private:
    std::vector<my_struct> m_vec;
};

Few other issues with your program:

You need to fix signature of your move constructor as move constructor requires rvalue reference (more specifically, xvalue or prvalue). It should like this:

my_struct(my_struct&& other) noexcept : m_a(other.m_a)
{
    std::cout << "copy move " << other.m_a << std::endl;
}

noexcept is required as we need to inform C++ (specifically std::vector) that move constructor and destructor does not throw, using noexcept. Then the move constructor will be called when the vector grows. See this.

The method append should be:

void append(my_struct &&m)
{
    m_vec.push_back(std::move(m));
}

To know why we need to use std::move on rvalue reference, see this Is an Rvalue Reference an Rvalue?. It says:

Things that are declared as rvalue reference can be lvalues or rvalues. The distinguishing criterion is: if it has a name, then it is an lvalue. Otherwise, it is an rvalue.

If you don't use std::move, then copy constructor would be called.


问:
msdeploy (Web Deploy) failing with 401 auth issues
I'm trying to get msdeploy installed and set up. I've installed the remote service on the web server, but all my tests are giving me a 401 unauthorised error. The server is Windows 2008 R2.

I'm testing a very simple msdeploy command:

```<code>msdeploy -verb:dump -source:contentPath=c:\inetpub\wwwroot\MyApp,computerName=<IP HERE>,userName=Domain\msdeploy,password=MyPassword
</code>```

And the error:

```<code>Error: Object of type 'contentPath' and path 'c:\inetpub\wwwroot\MonApp' cannot be created.
Error: Remote agent (URL http://<IP HERE>/MSDEPLOYAGENTSERVICE) could not be contacted.  Make sure the remote agent service is installed and started on the target computer.
Error: An unsupported response was received. The response header 'MSDeploy.Response' was '' but 'v1' was expected.
Error: The remote server returned an error: (401) Unauthorized.
Error count: 1.
</code>```

I created a user called msdeploy and I added it to the local admins group on the server.

I've checked:

That the service installed properly and I started it

Various combinations of not using the domain part of the username, and adding authType=Basic

Given full permissions to that folder to everyone

In IIS allow remote connections

Added Management Service Delegation rules for my "msdeploy" user for contentPath and iisApp (loosely based on reading this)

Tried with a different admin account I use for RDC to the server...

Tried with different contentPaths and different msdeploy commands

Created a specific account, and added that account to the IIS_Users. Added that user to my web site "IIS Manager Permissions", and setup "Management Service Delegation" for all providers.

答:
In the end I never did suss out what permissions I was missing with my deploy user account - but found that if I used the machine admin account, that the deployment would succeed. For now I'm using the admin account to do the deployment.

Kudos to Kev for the fantastic and informative summary of setting up ms deploy 2 :)

Body:
I'm trying to get msdeploy installed and set up. I've installed the remote service on the web server, but all my tests are giving me a 401 unauthorised error. The server is Windows 2008 R2.

I'm testing a very simple msdeploy command:

msdeploy -verb:dump -source:contentPath=c:\inetpub\wwwroot\MyApp,computerName=<IP HERE>,userName=Domain\msdeploy,password=MyPassword

And the error:

Error: Object of type 'contentPath' and path 'c:\inetpub\wwwroot\MonApp' cannot be created.
Error: Remote agent (URL http://<IP HERE>/MSDEPLOYAGENTSERVICE) could not be contacted.  Make sure the remote agent service is installed and started on the target computer.
Error: An unsupported response was received. The response header 'MSDeploy.Response' was '' but 'v1' was expected.
Error: The remote server returned an error: (401) Unauthorized.
Error count: 1.

I created a user called msdeploy and I added it to the local admins group on the server.

I've checked:

That the service installed properly and I started it

Various combinations of not using the domain part of the username, and adding authType=Basic

Given full permissions to that folder to everyone

In IIS allow remote connections

Added Management Service Delegation rules for my "msdeploy" user for contentPath and iisApp (loosely based on reading this)

Tried with a different admin account I use for RDC to the server...

Tried with different contentPaths and different msdeploy commands

Created a specific account, and added that account to the IIS_Users. Added that user to my web site "IIS Manager Permissions", and setup "Management Service Delegation" for all providers.