问:
Validation with html form only gives if statement
No matter how many characters I enter, it only gives the if statement and not the else.
is there a typo I entered somewhere I am not seeing, or does the function not work if there are two inputs?

function valid_Function(){
    var x, text;

    x = document.getElementById("name").value;

    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }
    document.getElementById("valid").innerHTML = text;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form input {
    display: block;
    margin-top: 10px;
}
form [type="submit"] {
    padding: 5px;
    border-radius: 5px;
    border: none;
    background: skyblue;
    transition: .5s ease;
}
form [type="submit"]:hover {
    box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}</code>```

<form action="#">
        <input for="fname" id="name" placeholder="First Name" type="text">
        <input for="lname" id="name" placeholder="Last Name" type="text">
        <input onclick="valid_Function()" type="submit" value="Submit">
    </form>

```

答:
The couple issues noted in the comments are causing your code to break.

IDs in HTML need to be unique, so having 2 elements with id="name" will cause problems in JavaScript

Assuming you meant to check the length of first/last names rather than comparing the values to the integers 1 and 10, the code should be checking the .length property in your conditionals.

Assuming you want to run this check separately for each name input, here is the adjusted code to validate first and last name separately. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event for more information about handling form submission events.

document.getElementById('form').addEventListener('submit', function(event) {
  event.preventDefault(); // this prevents the form from submitting right away so the rest of the validation can run

  var firstName = document.getElementById("first_name").value.trim();
  var lastName = document.getElementById("last_name").value.trim();
  var text;

  if (firstName.length < 1 || firstName.length > 10) {
    text = "First name is not valid";
  } else if (lastName.length < 1 || lastName.length > 10) {
    text = "Last name is not valid";
  } else {
    text = "Input OK";
  }
  document.getElementById("valid").innerHTML = text;

  return false; // this stops the form from continuing to submit, you may or may not want this line here
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form input {
  display: block;
  margin-top: 10px;
}

form [type="submit"] {
  padding: 5px;
  border-radius: 5px;
  border: none;
  background: skyblue;
  transition: .5s ease;
}

form [type="submit"]:hover {
  box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}</code>```

<form id="form">
  <input for="fname" id="first_name" placeholder="First Name" type="text">
  <input for="lname" id="last_name" placeholder="Last Name" type="text">
  <input type="submit" value="Submit">
</form>

```

Body:
No matter how many characters I enter, it only gives the if statement and not the else.
is there a typo I entered somewhere I am not seeing, or does the function not work if there are two inputs?

function valid_Function(){
    var x, text;

    x = document.getElementById("name").value;

    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }
    document.getElementById("valid").innerHTML = text;
}

form input {
    display: block;
    margin-top: 10px;
}
form [type="submit"] {
    padding: 5px;
    border-radius: 5px;
    border: none;
    background: skyblue;
    transition: .5s ease;
}
form [type="submit"]:hover {
    box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}

<form action="#">
        <input for="fname" id="name" placeholder="First Name" type="text">
        <input for="lname" id="name" placeholder="Last Name" type="text">
        <input onclick="valid_Function()" type="submit" value="Submit">
    </form>

Body:
The couple issues noted in the comments are causing your code to break.

IDs in HTML need to be unique, so having 2 elements with id="name" will cause problems in JavaScript

Assuming you meant to check the length of first/last names rather than comparing the values to the integers 1 and 10, the code should be checking the .length property in your conditionals.

Assuming you want to run this check separately for each name input, here is the adjusted code to validate first and last name separately. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event for more information about handling form submission events.

document.getElementById('form').addEventListener('submit', function(event) {
  event.preventDefault(); // this prevents the form from submitting right away so the rest of the validation can run

  var firstName = document.getElementById("first_name").value.trim();
  var lastName = document.getElementById("last_name").value.trim();
  var text;

  if (firstName.length < 1 || firstName.length > 10) {
    text = "First name is not valid";
  } else if (lastName.length < 1 || lastName.length > 10) {
    text = "Last name is not valid";
  } else {
    text = "Input OK";
  }
  document.getElementById("valid").innerHTML = text;

  return false; // this stops the form from continuing to submit, you may or may not want this line here
});

form input {
  display: block;
  margin-top: 10px;
}

form [type="submit"] {
  padding: 5px;
  border-radius: 5px;
  border: none;
  background: skyblue;
  transition: .5s ease;
}

form [type="submit"]:hover {
  box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}

<form id="form">
  <input for="fname" id="first_name" placeholder="First Name" type="text">
  <input for="lname" id="last_name" placeholder="Last Name" type="text">
  <input type="submit" value="Submit">
</form>
<p id="valid"></p>


来源: stackexchange

问:
How do you delete or change the display on the last print on perl?
What I'm trying to do it print out a string and then after a few background checks, change the previously said string?

So here is what it will initially look like:

```<code>#
Loading design modules....please wait.
</code>```

Then after a few background checks it will remove "Loading design modules....please wait." then change it to something like this without clearing the whole CLI Screen:

```<code>#
Design module loaded!
</code>```

This is my code so far:

```<code>#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

use feature 'say';
use feature 'switch';

use IO::Socket;
use Scalar::Util qw(looks_like_number);
use Term::ANSIScreen qw/:cursor :screen/;

$| = 1;
print "Loading design modules....please wait";
sleep(5);
say "Design module loaded!";
</code>```

答:
If you only need to rewrite that one line, then the \r character escape is enough

```<code>use warnings;
use strict;
use feature 'say';

$| = 1;

my $msg_init = "Loading design modules....please wait";

print $msg_init;

sleep 5;

say "\rDesign module loaded", ' ' x length $msg_init;
</code>```

where I print spaces after the final message to make sure that the original one is overwritten.

The carriage return \r puts the cursor back at the beginning of the line, so this only works for the current line.  It is commonly used to track progress of waiting, something like in this one-liner

```<code>perl -wE'$| = 1; for (1..5) { print "\rWorking ... $_ "; sleep 1 }; say "\ndone"'
</code>```

(in which case the original message is left on the screen).

See this post for some ways to animate the cursor while waiting.

ContentLicense: CC BY-SA 4.0

Body:
What I'm trying to do it print out a string and then after a few background checks, change the previously said string?

So here is what it will initially look like:

#
Loading design modules....please wait.

Then after a few background checks it will remove "Loading design modules....please wait." then change it to something like this without clearing the whole CLI Screen:

#
Design module loaded!

This is my code so far:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

use feature 'say';
use feature 'switch';

use IO::Socket;
use Scalar::Util qw(looks_like_number);
use Term::ANSIScreen qw/:cursor :screen/;

$| = 1;
print "Loading design modules....please wait";
sleep(5);
say "Design module loaded!";

Body:
If you only need to rewrite that one line, then the \r character escape is enough

use warnings;
use strict;
use feature 'say';

$| = 1;

my $msg_init = "Loading design modules....please wait";

print $msg_init;

sleep 5;

say "\rDesign module loaded", ' ' x length $msg_init;

where I print spaces after the final message to make sure that the original one is overwritten.

The carriage return \r puts the cursor back at the beginning of the line, so this only works for the current line.  It is commonly used to track progress of waiting, something like in this one-liner

perl -wE'$| = 1; for (1..5) { print "\rWorking ... $_ "; sleep 1 }; say "\ndone"'

(in which case the original message is left on the screen).

See this post for some ways to animate the cursor while waiting.


问:
Update to MySQL 5.7 and high disk space consumption
Using: MySQL 5.6 on Debian 9, total DB size is around 450Gb

Updated to 5.7, ran mysql_upgrade, noticed that around 150 GB has been taken up. 2 tables are really large and they stayed in 'copying to tmp table' for a couple of  hours

Noticed innodb_file_per_table was on and created large ibd files that weren't there previously.

Restored from a snapshot, disabled the file_per_table, ran mysql_upgrade again. 100GB gone, which is almost 1/4 of my total DB.

In the first case, it pulled the data from ibdata and put it into a separate file but ibdata never shrinks so taken space almost doubled.

What happens in the second case? Does the temp table get created within the ibdata file that never shrinks so even when table is not used anymore - space is still gone?

Another thing I noticed is that space consumption doesn't start until query has been in copying to tmp table status for like an hour or so.

1) Is there any way to avoid/minimize space increase?

Would running update with file_per_table on, then disabling it and running alter table engine innodb free up the space?

2) Any way to predict how much space will be occupied? At least per table

3) How does max_tmp_table_size play into this?

答:
The only(?) way to switch to file_per_table without the disk bloat is

Dump the data.

Get a fresh install (or otherwise get rid of ibdata1).

Reload (with file_per_table on).


问:
fontawesome onclick icon change angular using material table
I want to fill favorite icon when it's empty. While click on the favorite icon i have to display solid favorite icon.

I tried like below code

```<code>    <span class="icon iconVisibile" (click)="isClicked()">
            <i class="fa-star"[ngClass]="isSelectedFav ? 'fas' : 'far'"></i>
    </span>
</code>```

ts

```<code>   public isSelected:boolean = false;
   isClicked(){
     this.isSelected = true;
     console.log(this.isSelected);
   }
</code>```

with above code that is not working please let me know what I am doing wrong here

答:
Demo Your problem seems that font awesome return i element tag to svg. That is why you can't change it. you should close autoReplaceSvg property in font awesome

put below ones in index.html

```<code><script type="text/javascript">
   window.FontAwesomeConfig = { autoReplaceSvg: false }
</script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />
</code>```

component.ts

```<code>public isSelected:boolean = false;
isClicked(){
   this.isSelected = true;
}
</code>```

html

```<code><span class="icon iconVisibile" (click)="isClicked()">
     <i class="fa-star"[ngClass]="isSelected ? 'fas' : 'far'"></i>
</span>
</code>```

Body:
I want to fill favorite icon when it's empty. While click on the favorite icon i have to display solid favorite icon.

I tried like below code

ts

   public isSelected:boolean = false;
   isClicked(){
     this.isSelected = true;
     console.log(this.isSelected);
   }

with above code that is not working please let me know what I am doing wrong here

Body:
Demo Your problem seems that font awesome return i element tag to svg. That is why you can't change it. you should close autoReplaceSvg property in font awesome

put below ones in index.html

<script type="text/javascript">
   window.FontAwesomeConfig = { autoReplaceSvg: false }
</script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

component.ts

public isSelected:boolean = false;
isClicked(){
   this.isSelected = true;
}

html

<span class="icon iconVisibile" (click)="isClicked()">
     <i class="fa-star"[ngClass]="isSelected ? 'fas' : 'far'"></i>
</span>


问:
How to supply additional audit data to ProgressTracker at runtime
We have requirement where we would like to supply some additional audit data to progress tracker at runtime. Currently progress tracker shows the static label text when the flow is tracked. I do see that Corda provided some provision in the ProgressTracker.Step class with attribute called extraAuditData. But I don't have an example how to make a use of it.</p>

答:
Progress tracker is a good tool see the process inside the node shell, however, it is not the case that you will always run all of your flows in the node shell.

In a real production environment, you would probably run the flows via some client server, That said, I suggest you use the logger to log any additional information to the log (for debugging).

See example syntax:

```<code>        log.info("Tracking new Payment Request")
</code>```

Full code: https://github.com/corda/samples-kotlin/blob/master/Features/cordaService-autopayroll/workflows-kotlin/src/main/kotlin/net/corda/examples/autopayroll/flows/AutoPaymentService.kt#L26

Body:
Progress tracker is a good tool see the process inside the node shell, however, it is not the case that you will always run all of your flows in the node shell.

In a real production environment, you would probably run the flows via some client server, That said, I suggest you use the logger to log any additional information to the log (for debugging).

See example syntax:

        log.info("Tracking new Payment Request")

Full code: https://github.com/corda/samples-kotlin/blob/master/Features/cordaService-autopayroll/workflows-kotlin/src/main/kotlin/net/corda/examples/autopayroll/flows/AutoPaymentService.kt#L26


问:
C - Convert an uppercase letter to lowercase
A really simple program. I just want to turn an 'A' into an 'a', but output is giving me 'A'. </p>

```<code>#include <stdio.h>

int main(void) {
    putchar(lower('A'));

}

lower(a)
int a;
{
    if ((a >= 65) && (a >= 90))
        a = a + 32;
    return a;
}
</code>```

答:
In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.</p>

```<code>int lower(int a)
{
    return a | ' ';
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A really simple program. I just want to turn an 'A' into an 'a', but output is giving me 'A'.

#include <stdio.h>

int main(void) {
    putchar(lower('A'));

}

lower(a)
int a;
{
    if ((a >= 65) && (a >= 90))
        a = a + 32;
    return a;
}

Body:
In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.

int lower(int a)
{
    return a | ' ';
}


问:
Encrypt with JAVA (jasypt) and Decrypt with PHP
Encrypt with JAVA (jasypt) and Decrypt with PHP - Whats the less vulnerable Algorithm?

Im working on a legacy system that has the following tasks:

1) The Java Application saves some encrypted data on a mysql database. This happens very rarely. The data is saved once and rarely updated.

2) A PHP page loads that encrypted data from the mysql database and uses it for internal logic. This php page must be able to decrypt it internally, but not to encrypt it.

3) The java Application also loads the encrypted data from the mysql database and decrypts it for internal purposes.

In another words, I have a Java application that encrypts and decrypts data. And I have a php single page that must be able to decrypt the data.

Currently, I must re-do this with new crypto algorithms. I researched at stackoverflow and many are saying to stay away from MD5 and DES. As far as I understood, I must go with AES, So Ive came up with the following java CODE below. However:

a) Im unsure how to decrypt with php, I normally use openSSL but I dont know the equivalent algo name in php.

```<code><?php

ini_set('display_errors', 1);

$salt = 'nXdHqFg74g22g4Vq';
$key = $salt; // ? not sure

$data = 'uVJ+m3FGkzFTCQXpZJysmo53rWh5+5L9dWzyyD8xues=';
$method = "AES-256-CFB"; //not sure which

//openssl_decrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string $tag = "" [, string $aad = "" ]]]] ) : string
echo openssl_decrypt($data, "AES-256-CFB", $key);

?>
</code>```

b) Is this safe enough for general purposes? I dont need anything awesomely secure just enough since this data mostly travel through https.

```<code>import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.iv.IvGenerator;
import org.jasypt.iv.StringFixedIvGenerator;

public class MyCryptoTest {

    //private static final byte[] key = "nXdHqFg74g22g4Vq".getBytes();
    private static final byte[] key = {110, 88, 100, 72, 113, 70, 103, 55, 52, 103, 50, 50, 103, 52, 86, 113};

    private static PooledPBEStringEncryptor textCryptor = new PooledPBEStringEncryptor();

    public static void main(String args[]) throws Exception {

        //System.out.println(Arrays.toString(key));
        //System.out.println(Arrays.toString("nXdHqFg74g22g4Vq".getBytes(Charset.forName("UTF-8"))));
        String input = "stackoverflow";
        String x = encrypt(input);
        String y = decrypt(x);

        System.out.println(x);
        System.out.println(y);

        System.out.println("Test Result: " + input.equals(y));

    }

    static {
        IvGenerator ivGenerator = new StringFixedIvGenerator("some_random_word?");
        textCryptor.setPoolSize(2);
        textCryptor.setPassword(new String(key));
        textCryptor.setAlgorithm("PBEWithHMACSHA512AndAES_256");
        textCryptor.setIvGenerator(ivGenerator);
    }

    public static String encrypt(String strClearText) throws Exception {
        String strData = "";

        try {
            strData = textCryptor.encrypt(strClearText);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception(ex);
        }
        return strData;
    }

    public static String decrypt(String strEncrypted) throws Exception {
        String strData = "";

        try {
            //System.out.println(strEncrypted);
            strData = textCryptor.decrypt(strEncrypted);

        } catch (Exception ex) {
            throw new Exception(ex);
        }
        return strData;
    }

}
</code>```

Important Quotes from the references:

Ideally you should move away from DES and since this padding is going
  to be a problem in PHP, why not see if you can change the encryption
  algorithm to something less troublesome and more secure?

To help you can show this page: http://www.ietf.org/rfc/rfc4772.txt,
  where it is succinctly expressed that DES is susceptible to brute
  force attacks, so has been deprecated and replaced with AES.

Community♦ 111 silver badge answered Dec 17 '13 at 17:15

James Black

Both MD5 and DES have known vulnerabilities and should not be used. –
  SLaks Apr 24 '12 at 14:45

MD5 is actually fine for key derivation, single DES is only fine for
  real time, short lived encryption purposes (which is basically never).
  Both should be avoided of course, especially if you don't know what
  you are doing. – Maarten Bodewes Apr 25 '12 at 20:06

References:

Decrypt ( with PHP ) a Java encryption ( PBEWithMD5AndDES )

Replacing JAVA with PHP for PKCS5 encryption

How can I list the available Cipher algorithms?

答:
Concerning the Jasypt code the following has to be considered:

PBEWithHMACSHA512AndAES_256 uses PBKDF2, i.e. by means of digest, password, salt and iteration count the encryption / decryption key is derived, i.e. these parameters are also needed for decryption. Algorithm and digest can be derived directly: AES-256 and SHA-512. As mode of operation CBC is applied.

The posted code generates a different ciphertext each time due to a randomly generated salt. A user defined salt can be passed to the PooledPBEStringEncryptor instance textCryptor analogous to the IV with:

```<code>textCryptor.setSaltGenerator(new StringFixedSaltGenerator(<YourSalt>));
</code>```

Jasypt uses the blocksize (16 bytes for AES) as salt size. Smaller salts cause an exception, larger salts are simply truncated.

The processing of the IV is analogous to the salt: Smaller IVs cause an exception, larger IVs are truncated.

If the iteration count isn't set explicitly with PooledPBEStringEncryptor#setKeyObtentionIterations(<iteration count>), 1000 is used by default.

Jasypt expects an ASCII-string as password (just for completeness, as this is true for the posted code).

With the Salt A16bytesSalt_012 the Jasypt code provides the following ciphertext: Lg01eeYnujbof0Wy9rs3XQ==. This ciphertext can be decrypted with PHP using hash_pbkdf2 as follows:

```<code><?php
$salt = 'A16bytesSalt_012'; // First 16 bytes of the salt used in Jasypt code
$iv = 'some_random_word';   // First 16 bytes of the IV used in Jasypt code
$iterations = 1000;         // Jasypt default
$password = array(110, 88, 100, 72, 113, 70, 103, 55, 52, 103, 50, 50, 103, 52, 86, 113); // Password used in Jasypt code
$password = implode(array_map("chr", $password));
$key = hash_pbkdf2("sha512", $password, $salt, $iterations, 32, TRUE);

$data = 'Lg01eeYnujbof0Wy9rs3XQ=='; // Ciphertext from Jasypt code
$method = "aes-256-cbc";            // Algorithm and mode used in Jasypt code
echo openssl_decrypt($data, $method, $key, 0, $iv);
?>
</code>```

Body:
Encrypt with JAVA (jasypt) and Decrypt with PHP - Whats the less vulnerable Algorithm?

Im working on a legacy system that has the following tasks:

1) The Java Application saves some encrypted data on a mysql database. This happens very rarely. The data is saved once and rarely updated.

2) A PHP page loads that encrypted data from the mysql database and uses it for internal logic. This php page must be able to decrypt it internally, but not to encrypt it.

3) The java Application also loads the encrypted data from the mysql database and decrypts it for internal purposes.

In another words, I have a Java application that encrypts and decrypts data. And I have a php single page that must be able to decrypt the data.

Currently, I must re-do this with new crypto algorithms. I researched at stackoverflow and many are saying to stay away from MD5 and DES. As far as I understood, I must go with AES, So Ive came up with the following java CODE below. However:

a) Im unsure how to decrypt with php, I normally use openSSL but I dont know the equivalent algo name in php.

<?php

ini_set('display_errors', 1);

$salt = 'nXdHqFg74g22g4Vq';
$key = $salt; // ? not sure

$data = 'uVJ+m3FGkzFTCQXpZJysmo53rWh5+5L9dWzyyD8xues=';
$method = "AES-256-CFB"; //not sure which

//openssl_decrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string $tag = "" [, string $aad = "" ]]]] ) : string
echo openssl_decrypt($data, "AES-256-CFB", $key);

?>

b) Is this safe enough for general purposes? I dont need anything awesomely secure just enough since this data mostly travel through https.

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.iv.IvGenerator;
import org.jasypt.iv.StringFixedIvGenerator;

public class MyCryptoTest {

    //private static final byte[] key = "nXdHqFg74g22g4Vq".getBytes();
    private static final byte[] key = {110, 88, 100, 72, 113, 70, 103, 55, 52, 103, 50, 50, 103, 52, 86, 113};

    private static PooledPBEStringEncryptor textCryptor = new PooledPBEStringEncryptor();

    public static void main(String args[]) throws Exception {

        //System.out.println(Arrays.toString(key));
        //System.out.println(Arrays.toString("nXdHqFg74g22g4Vq".getBytes(Charset.forName("UTF-8"))));
        String input = "stackoverflow";
        String x = encrypt(input);
        String y = decrypt(x);

        System.out.println(x);
        System.out.println(y);

        System.out.println("Test Result: " + input.equals(y));

    }

    static {
        IvGenerator ivGenerator = new StringFixedIvGenerator("some_random_word?");
        textCryptor.setPoolSize(2);
        textCryptor.setPassword(new String(key));
        textCryptor.setAlgorithm("PBEWithHMACSHA512AndAES_256");
        textCryptor.setIvGenerator(ivGenerator);
    }

    public static String encrypt(String strClearText) throws Exception {
        String strData = "";

        try {
            strData = textCryptor.encrypt(strClearText);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception(ex);
        }
        return strData;
    }

    public static String decrypt(String strEncrypted) throws Exception {
        String strData = "";

        try {
            //System.out.println(strEncrypted);
            strData = textCryptor.decrypt(strEncrypted);

        } catch (Exception ex) {
            throw new Exception(ex);
        }
        return strData;
    }

}

Important Quotes from the references:

Ideally you should move away from DES and since this padding is going
  to be a problem in PHP, why not see if you can change the encryption
  algorithm to something less troublesome and more secure?

To help you can show this page: http://www.ietf.org/rfc/rfc4772.txt,
  where it is succinctly expressed that DES is susceptible to brute
  force attacks, so has been deprecated and replaced with AES.

Community♦ 111 silver badge answered Dec 17 '13 at 17:15

James Black

Both MD5 and DES have known vulnerabilities and should not be used. –
  SLaks Apr 24 '12 at 14:45

MD5 is actually fine for key derivation, single DES is only fine for
  real time, short lived encryption purposes (which is basically never).
  Both should be avoided of course, especially if you don't know what
  you are doing. – Maarten Bodewes Apr 25 '12 at 20:06

References:

Decrypt ( with PHP ) a Java encryption ( PBEWithMD5AndDES )

Replacing JAVA with PHP for PKCS5 encryption

How can I list the available Cipher algorithms?

Body:
Concerning the Jasypt code the following has to be considered:

PBEWithHMACSHA512AndAES_256 uses PBKDF2, i.e. by means of digest, password, salt and iteration count the encryption / decryption key is derived, i.e. these parameters are also needed for decryption. Algorithm and digest can be derived directly: AES-256 and SHA-512. As mode of operation CBC is applied.

The posted code generates a different ciphertext each time due to a randomly generated salt. A user defined salt can be passed to the PooledPBEStringEncryptor instance textCryptor analogous to the IV with:

textCryptor.setSaltGenerator(new StringFixedSaltGenerator(<YourSalt>));

Jasypt uses the blocksize (16 bytes for AES) as salt size. Smaller salts cause an exception, larger salts are simply truncated.

The processing of the IV is analogous to the salt: Smaller IVs cause an exception, larger IVs are truncated.

If the iteration count isn't set explicitly with PooledPBEStringEncryptor#setKeyObtentionIterations(<iteration count>), 1000 is used by default.

Jasypt expects an ASCII-string as password (just for completeness, as this is true for the posted code).

With the Salt A16bytesSalt_012 the Jasypt code provides the following ciphertext: Lg01eeYnujbof0Wy9rs3XQ==. This ciphertext can be decrypted with PHP using hash_pbkdf2 as follows:

<?php
$salt = 'A16bytesSalt_012'; // First 16 bytes of the salt used in Jasypt code
$iv = 'some_random_word';   // First 16 bytes of the IV used in Jasypt code
$iterations = 1000;         // Jasypt default
$password = array(110, 88, 100, 72, 113, 70, 103, 55, 52, 103, 50, 50, 103, 52, 86, 113); // Password used in Jasypt code
$password = implode(array_map("chr", $password));
$key = hash_pbkdf2("sha512", $password, $salt, $iterations, 32, TRUE);

$data = 'Lg01eeYnujbof0Wy9rs3XQ=='; // Ciphertext from Jasypt code
$method = "aes-256-cbc";            // Algorithm and mode used in Jasypt code
echo openssl_decrypt($data, $method, $key, 0, $iv);
?>


问:
How do I set Firebase's 'Realtime Database' rules?
Simple question: Is there any problem with setting the 'read' and 'write' rule on my Realtime Database (Firebase) to 'true' (no authentication) if the user is just reading data from the database and not writing anything to it and there's no secret data stored in this database, that the user isn't supposed to see?

答: If the user isn't writing anything at all, then I don't know why you would allow write access.  Just allow read access.  If you allow unconditional write access, then anyone with an internet connection will be able to write (and delete) that data.  If that's not what you want, then don't allow it.</p>


问:
The ordered and unordered sequence
I would like to write a program that reads a sequence of integer numbers and outputs true if the sequence is ordered (in asc or desc order), otherwise, false.

The sequence ends with 0. Do not consider this number as a part of the sequence. The sequence always has at least one number (excluding 0).

my code:

```<code>import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int a;
        int b;
        boolean asc = true;
        boolean dsc = true;
        a = read.nextInt();
        while (a == 0) {
            a = read.nextInt();
        }
        while (true) {
            b = read.nextInt();
            if (b == 0) {
                break;
            }
            dsc = dsc && a >= b;
            asc = asc && a <= b;
            if (asc || dsc == false) {
                break;
            }
            a = b;
        }
        System.out.println(asc || dsc);
    }
}
</code>```

Test input: 1 2 5 5 2 3 0

Correct output: false

My code output: true

What is wrong with my code?

答:
I think the problem is in your if statement if (asc || dsc == false) which most likely should be if (!asc && !dsc).

Result would be this:

```<code>import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int a;
        int b;
        boolean asc = true;
        boolean dsc = true;
        a = read.nextInt();
        while (a == 0) {
            a = read.nextInt();
        }
        while (true) {
            b = read.nextInt();
            if (b == 0) {
                break;
            }
            dsc = dsc && a >= b;
            asc = asc && a <= b;
            if (!asc && !dsc) {
                break;
            }
            a = b;
        }
        System.out.println(asc || dsc);
    }
}

</code>```

Title: The ordered and unordered sequence

Body:
I would like to write a program that reads a sequence of integer numbers and outputs true if the sequence is ordered (in asc or desc order), otherwise, false.

The sequence ends with 0. Do not consider this number as a part of the sequence. The sequence always has at least one number (excluding 0).

my code:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int a;
        int b;
        boolean asc = true;
        boolean dsc = true;
        a = read.nextInt();
        while (a == 0) {
            a = read.nextInt();
        }
        while (true) {
            b = read.nextInt();
            if (b == 0) {
                break;
            }
            dsc = dsc && a >= b;
            asc = asc && a <= b;
            if (asc || dsc == false) {
                break;
            }
            a = b;
        }
        System.out.println(asc || dsc);
    }
}

Test input: 1 2 5 5 2 3 0

Correct output: false

My code output: true

What is wrong with my code?

Body:
I think the problem is in your if statement if (asc || dsc == false) which most likely should be if (!asc && !dsc).

Result would be this:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int a;
        int b;
        boolean asc = true;
        boolean dsc = true;
        a = read.nextInt();
        while (a == 0) {
            a = read.nextInt();
        }
        while (true) {
            b = read.nextInt();
            if (b == 0) {
                break;
            }
            dsc = dsc && a >= b;
            asc = asc && a <= b;
            if (!asc && !dsc) {
                break;
            }
            a = b;
        }
        System.out.println(asc || dsc);
    }
}


问:
Python prime list
```<code>integer = int(input("Enter an integer: "))
if integer >= 2:
    print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
        else: # is prime
            print(i)
</code>```

input:

7
```

<p>output:</p>

<pre class="lang-none prettyprint-override"><code>2
3
5
5
5
7
7
7
7
7
</code>```

output I want:

2
3
5
7
```

adding more detail to get past error:

It looks like your post is mostly code; please add some more details.

答:
Put the print(i) in the outer for loop with a flag that keeps track of the result.

for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    isPrime = True
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0:
            isPrime = False
            break
    if isPrime:
        print(i)
```

Title: Python prime list

Body:
integer = int(input("Enter an integer: "))
if integer >= 2:
    print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    for j in range(2, i): # we are going to try dividing by these
        if i % j == 0: # not prime
            break
        else: # is prime
            print(i)

input:

7

output:

2
3
5
5
5
7
7
7
7
7

output I want:

2
3
5
7

adding more detail to get past error:

It looks like your post is mostly code; please add some more details.


问:
How can I provide customised authentication for Appsync?
In appsync, there are 4 authorization mode, API Key, IAM, Cognito, OPEN ID. How can I make a customised one, like a lambda? Or how can I remove authorization at all which means it is open to public and I will do authorization in business layer?

答:
AppSync doesn't currently support custom Lambda authorizer, you can +1 the issue. https://github.com/aws/aws-appsync-community/issues/2

Regarding your second question, you can't remove authentication altogether, the closest you can get to it is use API_KEY (no authentication essentially as any client or person with your API_KEY can access your API.


问:
ASP.NET CORE and BLAZOR : Reset Password
Hy,

I'm new to blazor and .net and was wondering how i can implement a password reset the best way possible.
Currently i'm using this example to login etc : Blazor Authentication Sample.
This example excludes an example for reseting the password.So i was searching for a solution myself.

This is what is have, it's a Razor Component

```<code>@page "/ResetPassword"

@inject UserManager<IdentityUser> userManager
@inject NavigationManager navigationManager
@inject IDataProtectionProvider dataProtectionProvider

@if (IsResetSend)
{
    <h3>Reset Password</h3>
    <div>
        A mail has been send with a password reset link, please click this link to set a new password.
    </div>
    <br />
    <a href="/">Back</a>
}
else
{
    <h3>Reset Password</h3>
    <EditForm Model="resetPassword" OnValidSubmit="@SendResetPassword">
        <div class="field">
            <label class="label">E-mail</label>
            <div class="control">
                <InputText id="email" class="input" type="email" @bind-Value="@resetPassword.Email"></InputText>
            </div>
        </div>
        <div class="field">
            <div class="control">
                <button type="submit" class="button is-primary">Sign in</button>
            </div>
        </div>
    </EditForm>
}

@code {

    ResetPassword resetPassword = new ResetPassword();

    bool IsResetSend = false;

    public async void SendResetPassword()
    {
        List<string> mailTo = new List<string>();

        string passwordResetToken;

        var user = await userManager.FindByEmailAsync(resetPassword.Email);

        if (user != null)
        {
            mailTo.Add(resetPassword.Email);

            passwordResetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            //Send mail with the relevant token
            Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
            emailObject.Email_To = mailTo;
            emailObject.Email_Subject = "Password Reset Webco !";
            emailObject.Email_Message = "Hy There, <br> Please click this link to reset your password : <br> https://localhost:44384/" + passwordResetToken;
            emailObject.SendEmail(emailObject);

            IsResetSend = true;
        }
    }

    public class ResetPassword
    {
        [Required]
        public string Email { get; set; }

    }
</code>```

As you can see, this is a staightforward approach, currently the one thing i can't seem to find is a way to store the password reset token, and capture it when it is being clicked in the mail.

Before i would;

Create a random token, store it in the database in the field ;
UserResetToken of the current user

When the user then click's the link, the token would be offered to the webpage [Parameter].

A stored procedure would then find the token and clear it, to alter the password afterwards on another user form.

I don't think this is best practice there it is based on a custom stored procedure. Could anybody guide me in this ?

Regards,

答:
Blazor has all required examples already included. Create a new project and choose as authentication In-App Storage. Click with the right mouse button on your project and choose Add->New Scaffolding element and choose Identity on the right. Visual Studio will ask you which files you want to override and creates a full example which you can use to build it in your main app.

This pages are possible:

Body:
Hy,

I'm new to blazor and .net and was wondering how i can implement a password reset the best way possible.
Currently i'm using this example to login etc : Blazor Authentication Sample.
This example excludes an example for reseting the password.So i was searching for a solution myself.

This is what is have, it's a Razor Component

@page "/ResetPassword"

@inject UserManager<IdentityUser> userManager
@inject NavigationManager navigationManager
@inject IDataProtectionProvider dataProtectionProvider

@if (IsResetSend)
{

Reset Password

        A mail has been send with a password reset link, please click this link to set a new password.

    Back
}
else
{

Reset Password

    <EditForm Model="resetPassword" OnValidSubmit="@SendResetPassword">

            E-mail

                <InputText id="email" class="input" type="email" @bind-Value="@resetPassword.Email"></InputText>

                <button type="submit" class="button is-primary">Sign in</button>

    </EditForm>
}

@code {

    ResetPassword resetPassword = new ResetPassword();

    bool IsResetSend = false;

    public async void SendResetPassword()
    {
        List<string> mailTo = new List<string>();

        string passwordResetToken;

        var user = await userManager.FindByEmailAsync(resetPassword.Email);

        if (user != null)
        {
            mailTo.Add(resetPassword.Email);

            passwordResetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            //Send mail with the relevant token
            Webco.Email.Entities.EmailObject emailObject = new Webco.Email.Entities.EmailObject();
            emailObject.Email_To = mailTo;
            emailObject.Email_Subject = "Password Reset Webco !";
            emailObject.Email_Message = "Hy There,
 Please click this link to reset your password :
 https://localhost:44384/" + passwordResetToken;
            emailObject.SendEmail(emailObject);

            IsResetSend = true;
        }
    }

    public class ResetPassword
    {
        [Required]
        public string Email { get; set; }

    }

As you can see, this is a staightforward approach, currently the one thing i can't seem to find is a way to store the password reset token, and capture it when it is being clicked in the mail.

Before i would;

Create a random token, store it in the database in the field ;
UserResetToken of the current user

When the user then click's the link, the token would be offered to the webpage [Parameter].

A stored procedure would then find the token and clear it, to alter the password afterwards on another user form.

I don't think this is best practice there it is based on a custom stored procedure. Could anybody guide me in this ?

Regards,


问:
How to make service registration dependent on configuration?
I would like to wire the services in the configuration file, something like

```<code>builder.Services.AddTransient<MyService>(s => s.GetServiceFromSetting<MyAppSetting>("MyServiceA"));
</code>```

I could instead use reflection to get the type (although I am not sure if the configuration is available in Startup already, at least with Azure functions there is an issue: https://github.com/Azure/azure-webjobs-sdk/issues/2406).

I was wondering, if there is a better way to get this done.

答:
I was struggling with this the other day, and couldn't find a reference.  But it turned out it's just because it's actually incredibly simple.

You just use the Services.AddXXX method that takes a Func<IServiceProvider,TTargetService> which will run whenever the service is resolved.  EG

```<code>services.AddScoped<ISomeService>(sp =>
{
    var config = sp.GetService<IConfiguration>();
    var serviceType = config.GetValue<string>("SomeServiceType");

    if (serviceType=="typeA")
    {
        return sp.GetService<SomeTypeAService>();
    }
    else if (serviceType=="typeB")
    {
        return sp.GetService<SomeTypeAService>();
    }
    else
    {
        throw new InvalidOperationException($"SomeServiceType {serviceType} unknown.");
    }

});
</code>```

Body:
I would like to wire the services in the configuration file, something like

builder.Services.AddTransient<MyService>(s => s.GetServiceFromSetting<MyAppSetting>("MyServiceA"));

I could instead use reflection to get the type (although I am not sure if the configuration is available in Startup already, at least with Azure functions there is an issue: https://github.com/Azure/azure-webjobs-sdk/issues/2406).

I was wondering, if there is a better way to get this done.

Body:
I was struggling with this the other day, and couldn't find a reference.  But it turned out it's just because it's actually incredibly simple.

You just use the Services.AddXXX method that takes a Func<IServiceProvider,TTargetService> which will run whenever the service is resolved.  EG

services.AddScoped<ISomeService>(sp =>
{
    var config = sp.GetService<IConfiguration>();
    var serviceType = config.GetValue<string>("SomeServiceType");

    if (serviceType=="typeA")
    {
        return sp.GetService<SomeTypeAService>();
    }
    else if (serviceType=="typeB")
    {
        return sp.GetService<SomeTypeAService>();
    }
    else
    {
        throw new InvalidOperationException($"SomeServiceType {serviceType} unknown.");
    }

});


问:
How do you solve a Heroku app showing an error that no module named "My project name"
I am trying to upload my first Django project to Heroku and when I run my app its says this:

```<code> 2020-06-01T13:39:36.641010+00:00 app[web.1]: ModuleNotFoundError: No module named 'Personal_Website'
    2020-06-01T13:39:36.641135+00:00 app[web.1]: [2020-06-01 13:39:36 +0000] [10] [INFO] Worker exiting (pid: 10)
    2020-06-01T13:39:36.747848+00:00 app[web.1]: [2020-06-01 13:39:36 +0000] [4] [INFO] Shutting down: Master
    2020-06-01T13:39:36.747950+00:00 app[web.1]: [2020-06-01 13:39:36 +0000] [4] [INFO] Reason: Worker failed to boot.
</code>```

The Personal_Website is my project name

答:
Try deploying using Heroku CLI
Just install it on your desktop</p>

Body:
I am trying to upload my first Django project to Heroku and when I run my app its says this:

 2020-06-01T13:39:36.641010+00:00 app[web.1]: ModuleNotFoundError: No module named 'Personal_Website'
    2020-06-01T13:39:36.641135+00:00 app[web.1]: [2020-06-01 13:39:36 +0000] [10] [INFO] Worker exiting (pid: 10)
    2020-06-01T13:39:36.747848+00:00 app[web.1]: [2020-06-01 13:39:36 +0000] [4] [INFO] Shutting down: Master
    2020-06-01T13:39:36.747950+00:00 app[web.1]: [2020-06-01 13:39:36 +0000] [4] [INFO] Reason: Worker failed to boot.

The Personal_Website is my project name


问:
Difference between HTMLCollection, NodeLists, and arrays of objects
I've always been confused between HTMLCollections, objects, and arrays when it comes to DOM.  For instance...

What is the difference between document.getElementsByTagName("td") and $("td")?

$("#myTable") and $("td") are objects (jQuery objects).  Why is console.log also showing the array of DOM elements beside them, and are they not objects and not an array?

What is the elusive "NodeLists" all about, and how do I select one?

Please also provide any interpretation of the below script.

[123,"abc",321,"cba"]=[123,"abc",321,"cba"]
{123:123,abc:"abc",321:321,cba:"cba"}=Object { 123=123, abc="abc", 321=321, more...}
Node= Node { ELEMENT_NODE=1, ATTRIBUTE_NODE=2, TEXT_NODE=3, more...}
document.links= HTMLCollection[a #, a #]
document.getElementById("myTable")=

document.getElementsByClassName("myRow")= HTMLCollection[tr.myRow, tr.myRow]
document.getElementsByTagName("td")= HTMLCollection[td, td, td, td]
$("#myTable")= Object[table#myTable]
$("td")= Object[td, td, td, td]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
        <title>Collections?</title>

        Link1
        Link2

td11	td12

td21	td22

```

答:
So much has been told already, but thought a more summarised version of answer with an example to explain the differences between HTMLCollection and NodeList would help.

Types of Nodes in DOM

There are 12 different node types, which may have children of various node types:

We can use the following three properties to inspect and inquire about nodes in DOM:

nodeType Property

nodeName Property

nodeValue Property

The nodeType property returns the node type, as a number, of the specified node.

If the node is an element node, the nodeType property will return 1.

If the node is an attribute node, the nodeType property will return 2.

If the node is a text node, the nodeType property will return 3.

If the node is a comment node, the nodeType property will return 8.

This property is read-only.

HTMLCollection vs NodeList

We can understand the differences between HTMLCollection and NodeList more clearly with the following example. Please, try to check the outputs in your own browser console to have a better understanding.

foo

bar

bar

```

<pre class="lang-js prettyprint-override"><code>// retrieve element using querySelectorAll
const listItems_querySelector = document.querySelectorAll('li');
console.log('querySelector', listItems_querySelector);

// retrieve element using childNodes
const list  = document.querySelector('ul')
const listItems_childNodes = list.childNodes;
console.log('childNodes', listItems_childNodes);
const listItems_children = list.children;
console.log('children', listItems_children);

const listItems_getElementsByTagName = document.getElementsByTagName('li');
console.log('getElementsByTagName', listItems_getElementsByTagName);

console.log('*************************');
console.log('add one list item');
console.log('*************************');
list.appendChild(document.createElement('li'));

console.log('querySelector', listItems_querySelector);
console.log('childNodes', listItems_childNodes);
console.log('children', listItems_children);
console.log('getElementsByTagName', listItems_getElementsByTagName);

console.log('*************************');
console.log('add one more list item');
console.log('*************************');
listItems_getElementsByTagName[0].parentNode.appendChild(document.createElement('li'));

console.log('querySelector', listItems_querySelector);
console.log('childNodes', listItems_childNodes);
console.log('children', listItems_children);
console.log('getElementsByTagName', listItems_getElementsByTagName);
</code>```

Body:
So much has been told already, but thought a more summarised version of answer with an example to explain the differences between HTMLCollection and NodeList would help.

Types of Nodes in DOM

There are 12 different node types, which may have children of various node types:

We can use the following three properties to inspect and inquire about nodes in DOM:

nodeType Property

nodeName Property

nodeValue Property

The nodeType property returns the node type, as a number, of the specified node.

If the node is an element node, the nodeType property will return 1.

If the node is an attribute node, the nodeType property will return 2.

If the node is a text node, the nodeType property will return 3.

If the node is a comment node, the nodeType property will return 8.

This property is read-only.

HTMLCollection vs NodeList

We can understand the differences between HTMLCollection and NodeList more clearly with the following example. Please, try to check the outputs in your own browser console to have a better understanding.

<ul>
  <li>foo</li>
  <li>bar</li>
  <li>bar</li>
</ul>

// retrieve element using querySelectorAll
const listItems_querySelector = document.querySelectorAll('li');
console.log('querySelector', listItems_querySelector);

// retrieve element using childNodes
const list  = document.querySelector('ul')
const listItems_childNodes = list.childNodes;
console.log('childNodes', listItems_childNodes);
const listItems_children = list.children;
console.log('children', listItems_children);

const listItems_getElementsByTagName = document.getElementsByTagName('li');
console.log('getElementsByTagName', listItems_getElementsByTagName);

console.log('*************************');
console.log('add one list item');
console.log('*************************');
list.appendChild(document.createElement('li'));

console.log('querySelector', listItems_querySelector);
console.log('childNodes', listItems_childNodes);
console.log('children', listItems_children);
console.log('getElementsByTagName', listItems_getElementsByTagName);

console.log('*************************');
console.log('add one more list item');
console.log('*************************');
listItems_getElementsByTagName[0].parentNode.appendChild(document.createElement('li'));

console.log('querySelector', listItems_querySelector);
console.log('childNodes', listItems_childNodes);
console.log('children', listItems_children);
console.log('getElementsByTagName', listItems_getElementsByTagName);


问:
Gradient is none in pytorch when it shouldn't
I am trying to get/trace the gradient of a variable using pytorch, where I have that variable, pass it to a first function that looks for some minimum value of some other variable, then the output of the first function is inputted to a second function, and the whole thing repeats multiple times.

Here is my code:

```<code>import torch

def myFirstFunction(parameter_current_here):
    optimalValue = 100000000000000
    Optimal = 100000000000000
    for j in range(2, 10):
        i = torch.ones(1, requires_grad=True)*j
        with torch.enable_grad():
            optimalValueNow = i*parameter_current_here.sum()
        if (optimalValueNow < optimalValue):
            optimalValue = optimalValueNow
            Optimal = i
    return optimalValue, Optimal

def mySecondFunction(Current):
    with torch.enable_grad():
        y = (20*Current)/2 + (Current**2)/10
    return y

counter = 0
while counter < 5:
    parameter_current = torch.randn(2, 2, requires_grad=True)

    outputMyFirstFunction = myFirstFunction(parameter_current)
    outputmySecondFunction = mySecondFunction(outputMyFirstFunction[1])
    outputmySecondFunction.backward()

    print("outputMyFirstFunction after backward:",
               outputMyFirstFunction)
    print("outputmySecondFunction after backward:",
               outputmySecondFunction)
    print("parameter_current Gradient after backward:",
               parameter_current.grad)

    counter = counter + 1
</code>```

The parameter_current.grad is none for all iterations when it obviously shouldn't be none. What am I doing wrong? And how can I fix it?

Your help on this would be highly appreciated. Thanks a lot!

Aly

答:
I have a similar experience with this. Reference: https://pytorch.org/docs/stable/tensors.html

For Tensors that have requires_grad which is True, they will be leaf Tensors if they were created by the user. This means that they are not the result of an operation and so grad_fn is None.

Only leaf Tensors will have their grad populated during a call to backward(). To get grad populated for non-leaf Tensors, you can use retain_grad().
Example:

```<code>    >>> a = torch.tensor([[1,1],[2,2]], dtype=torch.float, requires_grad=True)
    >>> a.is_leaf
    True
    >>> b = a * a
    >>> b.is_leaf
    False
    >>> c = b.mean()
    >>> c.backward()
    >>> print(c.grad)
    None
    >>> print(b.grad)
    None
    >>> print(a.grad)
    tensor([[0.5000, 0.5000],
            [1.0000, 1.0000]])
    >>> b = a * a
    >>> c = b.mean()
    >>> b.retain_grad()
    >>> c.retain_grad()
    >>> c.backward()
    >>> print(a.grad)
    tensor([[1., 1.],
            [2., 2.]])
    >>> print(b.grad)
    tensor([[0.2500, 0.2500],
            [0.2500, 0.2500]])
    >>> print(c.grad)
    tensor(1.)
</code>```

Body:
I am trying to get/trace the gradient of a variable using pytorch, where I have that variable, pass it to a first function that looks for some minimum value of some other variable, then the output of the first function is inputted to a second function, and the whole thing repeats multiple times.

Here is my code:

import torch

def myFirstFunction(parameter_current_here):
    optimalValue = 100000000000000
    Optimal = 100000000000000
    for j in range(2, 10):
        i = torch.ones(1, requires_grad=True)*j
        with torch.enable_grad():
            optimalValueNow = i*parameter_current_here.sum()
        if (optimalValueNow < optimalValue):
            optimalValue = optimalValueNow
            Optimal = i
    return optimalValue, Optimal

def mySecondFunction(Current):
    with torch.enable_grad():
        y = (20*Current)/2 + (Current**2)/10
    return y

counter = 0
while counter < 5:
    parameter_current = torch.randn(2, 2, requires_grad=True)

    outputMyFirstFunction = myFirstFunction(parameter_current)
    outputmySecondFunction = mySecondFunction(outputMyFirstFunction[1])
    outputmySecondFunction.backward()

    print("outputMyFirstFunction after backward:",
               outputMyFirstFunction)
    print("outputmySecondFunction after backward:",
               outputmySecondFunction)
    print("parameter_current Gradient after backward:",
               parameter_current.grad)

    counter = counter + 1

The parameter_current.grad is none for all iterations when it obviously shouldn't be none. What am I doing wrong? And how can I fix it?

Your help on this would be highly appreciated. Thanks a lot!

Aly

Body:
I have a similar experience with this. Reference: https://pytorch.org/docs/stable/tensors.html

For Tensors that have requires_grad which is True, they will be leaf Tensors if they were created by the user. This means that they are not the result of an operation and so grad_fn is None.

Only leaf Tensors will have their grad populated during a call to backward(). To get grad populated for non-leaf Tensors, you can use retain_grad().
Example:

    >>> a = torch.tensor([[1,1],[2,2]], dtype=torch.float, requires_grad=True)
    >>> a.is_leaf
    True
    >>> b = a * a
    >>> b.is_leaf
    False
    >>> c = b.mean()
    >>> c.backward()
    >>> print(c.grad)
    None
    >>> print(b.grad)
    None
    >>> print(a.grad)
    tensor([[0.5000, 0.5000],
            [1.0000, 1.0000]])
    >>> b = a * a
    >>> c = b.mean()
    >>> b.retain_grad()
    >>> c.retain_grad()
    >>> c.backward()
    >>> print(a.grad)
    tensor([[1., 1.],
            [2., 2.]])
    >>> print(b.grad)
    tensor([[0.2500, 0.2500],
            [0.2500, 0.2500]])
    >>> print(c.grad)
    tensor(1.)


问:
I can’t build in the apk file it gives an error
I can’t build in the apk file, it gives an error, help fix it.

I will show you the error and screenshots

Error building Player: CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
  C:/Program Files (x86)/Java/jdk-14.0.1\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/Sanchek19/AppData/Local/Android/Sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar"

stderr[

      Error:Invalid command android

  ]

  stdout[

  ]

  exit code: 64

enter image description here

答:
This sounds like exactly the same issue described here: https://answers.unity.com/questions/1343613/need-help-asap-building-apk-file-error-commandinvo.html

I was also able to encounter this error in the past - using older Android Build Tools should help, just like the described 25.2.5. Google deprecated the android command in meantime, so that it returnes 64 result code.

Out of curiosity, what is your Unity version?


问:
Multiplication of two variables for linear problems in glpk (gusek)
I'm trying to implemenet an assignment problem. I have the following problem when trying to multiply two variables in linear programming (using glpk gusek) in my goal function:

```<code>minimize PATH_COST: sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z]; #y is a binary variable; Koszty_Suma is total cost for ordez z and car type k
</code>```

The following error is arising: "model.mod:47: multiplication of linear forms not allowed".

Code (.dat file):

```<code>data;

set numery_Zlecen := 1, 2, 3; #order numbers

set Miasta := '*some data: *' #cities.

#order numer (from city to city)
set Zlecenie[1] := Warszawa Paris;
set Zlecenie[2] := Berlin Praha;
set Zlecenie[3] := Praha Amsterdam;

#number of packages for transport for a particular order
param Ilosc_Wyrobow :=
1 10
2 50
3 110;

param Godziny_Pracy := 9; #number of working hours during the day
param Pojemnosc_Samochodu := 35; #capacity of the car (how many packages it can take)
param Srednia_Predkosc := 80; #average car speed
param Spalenie_Paliwa := 0.25; #fuel combustion
param Wynagrodzenie_za_Godzine := 20; #salary for one working hour
param Cena_Noclegu := 100; #price of accommodation

param Dystans: '*some data: *' #km between cities.
param Koszt_Paliwa : '*some data: *' #fuel consumption depends on country.
end;
</code>```

Code (.mod file):

```<code>#INDEXY
#=====================================================================
set Miasta;                 #i,j
set numery_Zlecen;              #z
set Zlecenie{numery_Zlecen} dimen 2;    #p,q
set Rodzaj_Transportu;          #k

#PARAMETRY
#=====================================================================
param Dystans {Miasta,Miasta};
param Ilosc_Wyrobow{numery_Zlecen};
param Godziny_Pracy >= 0;
param Pojemnosc_Samochodu {Rodzaj_Transportu}>= 0;
param Srednia_Predkosc >=0;
param Spalenie_Paliwa >=0;
param Koszt_Paliwa {Miasta,Miasta};
param Wynagrodzenie_za_Godzine >= 0;
param Cena_Noclegu >= 0;

#ZMIENE
#=====================================================================
var x{Miasta,Miasta,numery_Zlecen} <= 1, >= 0; #variable x equal 1 when we're going the path from city A to city B; otherwise it equals 0
var y{Rodzaj_Transportu,numery_Zlecen} binary <=1, >=0; #variable that shows what types of car/s we are using for order (can be 0 or 1)
var Koszty_Suma{Rodzaj_Transportu,numery_Zlecen}; #total costs
var Koszty_Transportu{numery_Zlecen}; #transport costs
var Koszty_Odpoczynku{numery_Zlecen}; #rest costs
var Koszty_Wynagrodzenia{numery_Zlecen}; #salary costs

#FUNKCjA CELU
#=====================================================================
minimize PATH_COST: sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z];

#OGRANICZENIA (constraints)
#=====================================================================
s.t. SOURCE{z in numery_Zlecen, (p,q) in Zlecenie[z], i in Miasta: i = p && p != q}:
sum {j in Miasta} (x[i ,j ,z ]) - sum {j in Miasta}( x[j ,i ,z ]) = 1;

s.t. INTERNAL {z in numery_Zlecen, (p,q) in Zlecenie[z],i in Miasta: i != p && i != q && p != q }:
sum {j in Miasta} (x[i ,j ,z ]) - sum {j in Miasta}( x[j ,i ,z ]) = 0;

s.t. OGR_KM_DZIEN{z in numery_Zlecen,(p,q) in Zlecenie[z], j in Miasta, i in Miasta: i != q}:
if (Dystans[i,j] > (Godziny_Pracy*Srednia_Predkosc)) and i != q then x[i,j,z] = 0;

s.t. OGR_KOSZTY_SUMA{z in numery_Zlecen, k in Rodzaj_Transportu}:
Koszty_Suma[k,z] = (Koszty_Transportu[z] + Koszty_Odpoczynku[z] + Koszty_Wynagrodzenia[z])*ceil(Ilosc_Wyrobow[z]/Pojemnosc_Samochodu[k]);

s.t. OGR_KOSZTY_TRANSPORTU{z in numery_Zlecen}:
Koszty_Transportu[z] = (sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z]*Koszt_Paliwa[i,j] ) ))*Spalenie_Paliwa;

s.t. OGR_KOSZTY_ODPOCZYNKU{z in numery_Zlecen}:
Koszty_Odpoczynku[z] =
(sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z] ) ))/(Godziny_Pracy*Srednia_Predkosc) * Cena_Noclegu;

s.t. OGR_KOSZTY_WYNAGRODZENIA{z in numery_Zlecen}:
Koszty_Wynagrodzenia[z] =
((sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z] ) ))/(Srednia_Predkosc)) * Wynagrodzenie_za_Godzine;

s.t. OGR_Y_JEDEN{z in numery_Zlecen}:
sum{k in Rodzaj_Transportu}(y[k,z]) = 1;
solve;
</code>```

How is it possible to get rid of this error? Any hints how to solve this kind of problem are welcome.

答:
First I think the parentheses are incorrect (note that y[k,z] depends on z). The expression

```<code>  sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z];
</code>```

is not mathematically correct. So, I assume what you meant is:

```<code>sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z]*y[k,z]);
</code>```

Let me restate the problem a little bit. I assume we can write this as:

```<code>sum((i,j), x[i,j]*y[i,j])
</code>```

with y a binary variable and x a continuous variable.  I also assume 0 <= x[i,j] <= U[i,j]. (U is an upper bound).

Here is a way to linearize this quadratic term. We can introduce a variable z[i,j]=x[i,j]*y[i,j] using the following inequalities:

```<code> z[i,j] <= U[i,j]*y[i,j]
 z[i,j] <= x[i,j]
 z[i,j] >= x[i,j]-U[i,j]*(1-y[i,j])
 0 <= z[i,j] <= U[i,j]
</code>```

Now you just can minimize sum((i,j),z[i,j]). For a similar linearization see link.

Body:
I'm trying to implemenet an assignment problem. I have the following problem when trying to multiply two variables in linear programming (using glpk gusek) in my goal function:

minimize PATH_COST: sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z]; #y is a binary variable; Koszty_Suma is total cost for ordez z and car type k

The following error is arising: "model.mod:47: multiplication of linear forms not allowed".

Code (.dat file):

data;

set numery_Zlecen := 1, 2, 3; #order numbers

set Miasta := '*some data: *' #cities.

#order numer (from city to city)
set Zlecenie[1] := Warszawa Paris;
set Zlecenie[2] := Berlin Praha;
set Zlecenie[3] := Praha Amsterdam;

#number of packages for transport for a particular order
param Ilosc_Wyrobow :=
1 10
2 50
3 110;

param Godziny_Pracy := 9; #number of working hours during the day
param Pojemnosc_Samochodu := 35; #capacity of the car (how many packages it can take)
param Srednia_Predkosc := 80; #average car speed
param Spalenie_Paliwa := 0.25; #fuel combustion
param Wynagrodzenie_za_Godzine := 20; #salary for one working hour
param Cena_Noclegu := 100; #price of accommodation

param Dystans: '*some data: *' #km between cities.
param Koszt_Paliwa : '*some data: *' #fuel consumption depends on country.
end;

Code (.mod file):

#INDEXY
#=====================================================================
set Miasta;                 #i,j
set numery_Zlecen;              #z
set Zlecenie{numery_Zlecen} dimen 2;    #p,q
set Rodzaj_Transportu;          #k

#PARAMETRY
#=====================================================================
param Dystans {Miasta,Miasta};
param Ilosc_Wyrobow{numery_Zlecen};
param Godziny_Pracy >= 0;
param Pojemnosc_Samochodu {Rodzaj_Transportu}>= 0;
param Srednia_Predkosc >=0;
param Spalenie_Paliwa >=0;
param Koszt_Paliwa {Miasta,Miasta};
param Wynagrodzenie_za_Godzine >= 0;
param Cena_Noclegu >= 0;

#ZMIENE
#=====================================================================
var x{Miasta,Miasta,numery_Zlecen} <= 1, >= 0; #variable x equal 1 when we're going the path from city A to city B; otherwise it equals 0
var y{Rodzaj_Transportu,numery_Zlecen} binary <=1, >=0; #variable that shows what types of car/s we are using for order (can be 0 or 1)
var Koszty_Suma{Rodzaj_Transportu,numery_Zlecen}; #total costs
var Koszty_Transportu{numery_Zlecen}; #transport costs
var Koszty_Odpoczynku{numery_Zlecen}; #rest costs
var Koszty_Wynagrodzenia{numery_Zlecen}; #salary costs

#FUNKCjA CELU
#=====================================================================
minimize PATH_COST: sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z];

#OGRANICZENIA (constraints)
#=====================================================================
s.t. SOURCE{z in numery_Zlecen, (p,q) in Zlecenie[z], i in Miasta: i = p && p != q}:
sum {j in Miasta} (x[i ,j ,z ]) - sum {j in Miasta}( x[j ,i ,z ]) = 1;

s.t. INTERNAL {z in numery_Zlecen, (p,q) in Zlecenie[z],i in Miasta: i != p && i != q && p != q }:
sum {j in Miasta} (x[i ,j ,z ]) - sum {j in Miasta}( x[j ,i ,z ]) = 0;

s.t. OGR_KM_DZIEN{z in numery_Zlecen,(p,q) in Zlecenie[z], j in Miasta, i in Miasta: i != q}:
if (Dystans[i,j] > (Godziny_Pracy*Srednia_Predkosc)) and i != q then x[i,j,z] = 0;

s.t. OGR_KOSZTY_SUMA{z in numery_Zlecen, k in Rodzaj_Transportu}:
Koszty_Suma[k,z] = (Koszty_Transportu[z] + Koszty_Odpoczynku[z] + Koszty_Wynagrodzenia[z])*ceil(Ilosc_Wyrobow[z]/Pojemnosc_Samochodu[k]);

s.t. OGR_KOSZTY_TRANSPORTU{z in numery_Zlecen}:
Koszty_Transportu[z] = (sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z]*Koszt_Paliwa[i,j] ) ))*Spalenie_Paliwa;

s.t. OGR_KOSZTY_ODPOCZYNKU{z in numery_Zlecen}:
Koszty_Odpoczynku[z] =
(sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z] ) ))/(Godziny_Pracy*Srednia_Predkosc) * Cena_Noclegu;

s.t. OGR_KOSZTY_WYNAGRODZENIA{z in numery_Zlecen}:
Koszty_Wynagrodzenia[z] =
((sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z] ) ))/(Srednia_Predkosc)) * Wynagrodzenie_za_Godzine;

s.t. OGR_Y_JEDEN{z in numery_Zlecen}:
sum{k in Rodzaj_Transportu}(y[k,z]) = 1;
solve;

How is it possible to get rid of this error? Any hints how to solve this kind of problem are welcome.

Body:
First I think the parentheses are incorrect (note that y[k,z] depends on z). The expression

  sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z];

is not mathematically correct. So, I assume what you meant is:

sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z]*y[k,z]);

Let me restate the problem a little bit. I assume we can write this as:

sum((i,j), x[i,j]*y[i,j])

with y a binary variable and x a continuous variable.  I also assume 0 <= x[i,j] <= U[i,j]. (U is an upper bound).

Here is a way to linearize this quadratic term. We can introduce a variable z[i,j]=x[i,j]*y[i,j] using the following inequalities:

 z[i,j] <= U[i,j]*y[i,j]
 z[i,j] <= x[i,j]
 z[i,j] >= x[i,j]-U[i,j]*(1-y[i,j])
 0 <= z[i,j] <= U[i,j]

Now you just can minimize sum((i,j),z[i,j]). For a similar linearization see link.


问:
Django, Apache2 on Google Kubernetes Engine writing Opencensus Traces to Stackdriver Trace
I have a Django web app served from Apache2 with mod_wsgi in docker containers running on a Kubernetes cluster in Google Cloud Platform, protected by Identity-Aware Proxy. Everything is working great, but I want to send GCP Stackdriver traces for all requests without writing one for each view in my project. I found middleware to handle this, using Opencensus. I went through this documentation, and was able to manually generate traces that exported to Stackdriver Trace in my project by specifying the StackdriverExporter and passing the project_id parameter as the Google Cloud Platform Project Number for my project.

Now to make this automatic for ALL requests, I followed the instructions to set up the middleware. In settings.py, I added the module to INSTALLED_APPS, MIDDLEWARE, and set up the OPENCENSUS_TRACE dictionary of options. I also added the OPENCENSUS_TRACE_PARAMS. This works great with the default exporter 'opencensus.trace.exporters.print_exporter.PrintExporter', as I can see the Trace and Span information, including Trace ID and all details in my Apache2 web server logs. However, I want to send these to my Stackdriver Trace processor for analysis.

I tried setting the EXPORTER parameter to opencensus.trace.exporters.stackdriver_exporter.StackdriverExporter, which works when run manually from the shell, as long as you supply the project number.

When it is set up to use StackdriverExporter, the web page will not respond load, the health check starts to fail, and ultimately the web page comes back with a 502 error, stating I should try again in 30 seconds (I believe the Identity-Aware Proxy is generating this error, once it detects the failed health check), but the server generates no errors, and there are no logs in access or errors for Apache2.

There is another dictionary in settings.py named OPENCENSUS_TRACE_PARAMS, which I presume is needed to determine which project number the exporter should be using. The example has GCP_EXPORTER_PROJECT set as None, and SERVICE_NAME set as 'my_service'.

What options do I need to set to get the exporter to send back to Stackdriver instead of printing to logs? Do you have any idea about how I can set this up?

settings.py

```<code>MIDDLEWARE = (
    ...
    'opencensus.trace.ext.django.middleware.OpencensusMiddleware',
)
INSTALLED_APPS = (
    ...
    'opencensus.trace.ext.django',
)

OPENCENSUS_TRACE = {
    'SAMPLER': 'opencensus.trace.samplers.probability.ProbabilitySampler',
    'EXPORTER': 'opencensus.trace.exporters.stackdriver_exporter.StackdriverExporter',  # This one just makes the server hang with no response or error and kills the health check.
    'PROPAGATOR': 'opencensus.trace.propagation.google_cloud_format.GoogleCloudFormatPropagator',
    # 'EXPORTER': 'opencensus.trace.exporters.print_exporter.PrintExporter',  # This one works to print the Trace and Span with IDs and details in the logs.
}

OPENCENSUS_TRACE_PARAMS = {
    'BLACKLIST_PATHS': ['/health'],
    'GCP_EXPORTER_PROJECT': 'my_project_number',  # Should this be None like the example, or Project ID, or Project Number?
    'SAMPLING_RATE': 0.5,
    'SERVICE_NAME': 'my_service',  # Not sure if this is my app name or some other service name.
    'ZIPKIN_EXPORTER_HOST_NAME': 'localhost',  # Are the following even necessary, or are they causing a failure that is not detected by Apache2?
    'ZIPKIN_EXPORTER_PORT': 9411,
    'ZIPKIN_EXPORTER_PROTOCOL': 'http',
    'JAEGER_EXPORTER_HOST_NAME': None,
    'JAEGER_EXPORTER_PORT': None,
    'JAEGER_EXPORTER_AGENT_HOST_NAME': 'localhost',
    'JAEGER_EXPORTER_AGENT_PORT': 6831
}
</code>```

Here's an example (I prettified the format for readability) of the Apache2 log when it is set to use the PrintExporter:

```<code>[Fri Feb 08 09:00:32.427575 2019]
[wsgi:error]
[pid 1097:tid 139801302882048]
[client 10.48.0.1:43988]
[SpanData(
  name='services.views.my_view',
  context=SpanContext(
    trace_id=e882f23e49e34fc09df621867d753532,
    span_id=None,
    trace_options=TraceOptions(enabled=True),
    tracestate=None
  ),
  span_id='bcbe7b96906a482a',
  parent_span_id=None,
  attributes={
    'http.status_code': '200',
    'http.method': 'GET',
    'http.url': '/',
    'django.user.name': ''
  },
  start_time='2019-02-08T17:00:29.845733Z',
  end_time='2019-02-08T17:00:32.427455Z',
  child_span_count=0,
  stack_trace=None,
  time_events=[],
  links=[],
  status=None,
  same_process_as_parent_span=None,
  span_kind=1
)]
</code>```

Thanks in advance for any tips, assistance, or troubleshooting advice!

Edit 2019-02-08 6:56 PM UTC:

I found this in the middleware:

```<code># Initialize the exporter
transport = convert_to_import(settings.params.get(TRANSPORT))

if self._exporter.__name__ == 'GoogleCloudExporter':
    _project_id = settings.params.get(GCP_EXPORTER_PROJECT, None)
    self.exporter = self._exporter(
        project_id=_project_id,
        transport=transport)
elif self._exporter.__name__ == 'ZipkinExporter':
    _service_name = self._get_service_name(settings.params)
    _zipkin_host_name = settings.params.get(
        ZIPKIN_EXPORTER_HOST_NAME, 'localhost')
    _zipkin_port = settings.params.get(
        ZIPKIN_EXPORTER_PORT, 9411)
    _zipkin_protocol = settings.params.get(
        ZIPKIN_EXPORTER_PROTOCOL, 'http')
    self.exporter = self._exporter(
        service_name=_service_name,
        host_name=_zipkin_host_name,
        port=_zipkin_port,
        protocol=_zipkin_protocol,
        transport=transport)
elif self._exporter.__name__ == 'TraceExporter':
    _service_name = self._get_service_name(settings.params)
    _endpoint = settings.params.get(
        OCAGENT_TRACE_EXPORTER_ENDPOINT, None)
    self.exporter = self._exporter(
        service_name=_service_name,
        endpoint=_endpoint,
        transport=transport)
elif self._exporter.__name__ == 'JaegerExporter':
    _service_name = self._get_service_name(settings.params)
    self.exporter = self._exporter(
        service_name=_service_name,
        transport=transport)
else:
    self.exporter = self._exporter(transport=transport)
</code>```

The exporter is now named StackdriverExporter, instead of GoogleCloudExporter. I set up a class in my app named GoogleCloudExporter that inherits StackdriverExporter, and updated my settings.py to use GoogleCloudExporter, but it didn't seem to work, I wonder if there is other code referencing these old naming schemes, possibly for the transport. I'm searching the source code for clues... This at least tells me I can get rid of the ZIPKIN and JAEGER param options, as this is determined on the EXPORTER param.

Edit 2019-02-08 11:58 PM UTC:

I scrapped Apache2 to isolate the problem and just set my docker image to use Django's built in webserver CMD ["python", "/path/to/manage.py", "runserver", "0.0.0.0:80"] and it works! When I go to the site, it writes traces to Stackdriver Trace for each request, the Span name is the module and method being executed.

Somehow Apache2 is not being allowed to send these, but I can do so from the shell when running as root. I'm adding Apache2 and mod-wsgi tags to the question, because I have a funny feeling this has to do with forking child processes in Apache2 and mod-WSGI. Would it be the child process being unable to be created as apache2's child process is sandboxed, or could this be a permissions thing? It seems strange, because it is just calling python modules, no external system OS binaries, that I am aware of. Any other ideas would be greatly appreciated!

答:
I had this problem while using gunicorn with gevent as the worker class. To resolve and get cloud traces working the solution was to monkey patch grpc like so

```<code>from gevent import monkey
monkey.patch_all()

import grpc.experimental.gevent as grpc_gevent
grpc_gevent.init_gevent()
</code>```

See https://github.com/grpc/grpc/issues/4629#issuecomment-376962677

Body:
I have a Django web app served from Apache2 with mod_wsgi in docker containers running on a Kubernetes cluster in Google Cloud Platform, protected by Identity-Aware Proxy. Everything is working great, but I want to send GCP Stackdriver traces for all requests without writing one for each view in my project. I found middleware to handle this, using Opencensus. I went through this documentation, and was able to manually generate traces that exported to Stackdriver Trace in my project by specifying the StackdriverExporter and passing the project_id parameter as the Google Cloud Platform Project Number for my project.

Now to make this automatic for ALL requests, I followed the instructions to set up the middleware. In settings.py, I added the module to INSTALLED_APPS, MIDDLEWARE, and set up the OPENCENSUS_TRACE dictionary of options. I also added the OPENCENSUS_TRACE_PARAMS. This works great with the default exporter 'opencensus.trace.exporters.print_exporter.PrintExporter', as I can see the Trace and Span information, including Trace ID and all details in my Apache2 web server logs. However, I want to send these to my Stackdriver Trace processor for analysis.

I tried setting the EXPORTER parameter to opencensus.trace.exporters.stackdriver_exporter.StackdriverExporter, which works when run manually from the shell, as long as you supply the project number.

When it is set up to use StackdriverExporter, the web page will not respond load, the health check starts to fail, and ultimately the web page comes back with a 502 error, stating I should try again in 30 seconds (I believe the Identity-Aware Proxy is generating this error, once it detects the failed health check), but the server generates no errors, and there are no logs in access or errors for Apache2.

There is another dictionary in settings.py named OPENCENSUS_TRACE_PARAMS, which I presume is needed to determine which project number the exporter should be using. The example has GCP_EXPORTER_PROJECT set as None, and SERVICE_NAME set as 'my_service'.

What options do I need to set to get the exporter to send back to Stackdriver instead of printing to logs? Do you have any idea about how I can set this up?

settings.py

MIDDLEWARE = (
    ...
    'opencensus.trace.ext.django.middleware.OpencensusMiddleware',
)
INSTALLED_APPS = (
    ...
    'opencensus.trace.ext.django',
)

OPENCENSUS_TRACE = {
    'SAMPLER': 'opencensus.trace.samplers.probability.ProbabilitySampler',
    'EXPORTER': 'opencensus.trace.exporters.stackdriver_exporter.StackdriverExporter',  # This one just makes the server hang with no response or error and kills the health check.
    'PROPAGATOR': 'opencensus.trace.propagation.google_cloud_format.GoogleCloudFormatPropagator',
    # 'EXPORTER': 'opencensus.trace.exporters.print_exporter.PrintExporter',  # This one works to print the Trace and Span with IDs and details in the logs.
}

OPENCENSUS_TRACE_PARAMS = {
    'BLACKLIST_PATHS': ['/health'],
    'GCP_EXPORTER_PROJECT': 'my_project_number',  # Should this be None like the example, or Project ID, or Project Number?
    'SAMPLING_RATE': 0.5,
    'SERVICE_NAME': 'my_service',  # Not sure if this is my app name or some other service name.
    'ZIPKIN_EXPORTER_HOST_NAME': 'localhost',  # Are the following even necessary, or are they causing a failure that is not detected by Apache2?
    'ZIPKIN_EXPORTER_PORT': 9411,
    'ZIPKIN_EXPORTER_PROTOCOL': 'http',
    'JAEGER_EXPORTER_HOST_NAME': None,
    'JAEGER_EXPORTER_PORT': None,
    'JAEGER_EXPORTER_AGENT_HOST_NAME': 'localhost',
    'JAEGER_EXPORTER_AGENT_PORT': 6831
}

Here's an example (I prettified the format for readability) of the Apache2 log when it is set to use the PrintExporter:

[Fri Feb 08 09:00:32.427575 2019]
[wsgi:error]
[pid 1097:tid 139801302882048]
[client 10.48.0.1:43988]
[SpanData(
  name='services.views.my_view',
  context=SpanContext(
    trace_id=e882f23e49e34fc09df621867d753532,
    span_id=None,
    trace_options=TraceOptions(enabled=True),
    tracestate=None
  ),
  span_id='bcbe7b96906a482a',
  parent_span_id=None,
  attributes={
    'http.status_code': '200',
    'http.method': 'GET',
    'http.url': '/',
    'django.user.name': ''
  },
  start_time='2019-02-08T17:00:29.845733Z',
  end_time='2019-02-08T17:00:32.427455Z',
  child_span_count=0,
  stack_trace=None,
  time_events=[],
  links=[],
  status=None,
  same_process_as_parent_span=None,
  span_kind=1
)]

Thanks in advance for any tips, assistance, or troubleshooting advice!

Edit 2019-02-08 6:56 PM UTC:

I found this in the middleware:

# Initialize the exporter
transport = convert_to_import(settings.params.get(TRANSPORT))

if self._exporter.__name__ == 'GoogleCloudExporter':
    _project_id = settings.params.get(GCP_EXPORTER_PROJECT, None)
    self.exporter = self._exporter(
        project_id=_project_id,
        transport=transport)
elif self._exporter.__name__ == 'ZipkinExporter':
    _service_name = self._get_service_name(settings.params)
    _zipkin_host_name = settings.params.get(
        ZIPKIN_EXPORTER_HOST_NAME, 'localhost')
    _zipkin_port = settings.params.get(
        ZIPKIN_EXPORTER_PORT, 9411)
    _zipkin_protocol = settings.params.get(
        ZIPKIN_EXPORTER_PROTOCOL, 'http')
    self.exporter = self._exporter(
        service_name=_service_name,
        host_name=_zipkin_host_name,
        port=_zipkin_port,
        protocol=_zipkin_protocol,
        transport=transport)
elif self._exporter.__name__ == 'TraceExporter':
    _service_name = self._get_service_name(settings.params)
    _endpoint = settings.params.get(
        OCAGENT_TRACE_EXPORTER_ENDPOINT, None)
    self.exporter = self._exporter(
        service_name=_service_name,
        endpoint=_endpoint,
        transport=transport)
elif self._exporter.__name__ == 'JaegerExporter':
    _service_name = self._get_service_name(settings.params)
    self.exporter = self._exporter(
        service_name=_service_name,
        transport=transport)
else:
    self.exporter = self._exporter(transport=transport)

The exporter is now named StackdriverExporter, instead of GoogleCloudExporter. I set up a class in my app named GoogleCloudExporter that inherits StackdriverExporter, and updated my settings.py to use GoogleCloudExporter, but it didn't seem to work, I wonder if there is other code referencing these old naming schemes, possibly for the transport. I'm searching the source code for clues... This at least tells me I can get rid of the ZIPKIN and JAEGER param options, as this is determined on the EXPORTER param.

Edit 2019-02-08 11:58 PM UTC:

I scrapped Apache2 to isolate the problem and just set my docker image to use Django's built in webserver CMD ["python", "/path/to/manage.py", "runserver", "0.0.0.0:80"] and it works! When I go to the site, it writes traces to Stackdriver Trace for each request, the Span name is the module and method being executed.

Somehow Apache2 is not being allowed to send these, but I can do so from the shell when running as root. I'm adding Apache2 and mod-wsgi tags to the question, because I have a funny feeling this has to do with forking child processes in Apache2 and mod-WSGI. Would it be the child process being unable to be created as apache2's child process is sandboxed, or could this be a permissions thing? It seems strange, because it is just calling python modules, no external system OS binaries, that I am aware of. Any other ideas would be greatly appreciated!

Body:
I had this problem while using gunicorn with gevent as the worker class. To resolve and get cloud traces working the solution was to monkey patch grpc like so

from gevent import monkey
monkey.patch_all()

import grpc.experimental.gevent as grpc_gevent
grpc_gevent.init_gevent()

See https://github.com/grpc/grpc/issues/4629#issuecomment-376962677


问:
How to mock private method of an abstract class
```<code>public abstract class ClassA extends {

        public String getName(){
          String lastName = getLastName();
          return "Language"+lastName;
        }

        private String getLastName(){
          return "Java";
        }
}
</code>```

I am writing the test for getName . I want to mock getLastName method . How can i do it ?

答:
You can try approach from that answer.

However, if logic in private method is complex and class needs separate testing for it, it's a sure sign that you need some refactoring.

According to SOLID principles your private method should be public, and also should be placed in derived class.

public abstract class ClassA {
  private final LastNameProvider provider;

  public ClassA(LastNameProvider provider) {
    this.provider = provider;
  }

  public String getName() {
    String lastName = provider.getLastName();
    return "Language"+lastName;
  }
}

public interface LastNameProvider {
  String getLastName()
}

public class JavaLastNameProvider {
  private String getLastName(){
    return "Java";
  }
}
```

With that approach you can easily replace provider in ClassA with another one for testing, or you can mock it with Mockito and so on.

Body:
public abstract class ClassA extends {

        public String getName(){
          String lastName = getLastName();
          return "Language"+lastName;
        }

        private String getLastName(){
          return "Java";
        }
}

I am writing the test for getName . I want to mock getLastName method . How can i do it ?

Body:
You can try approach from that answer.

However, if logic in private method is complex and class needs separate testing for it, it's a sure sign that you need some refactoring.

According to SOLID principles your private method should be public, and also should be placed in derived class.

public abstract class ClassA {
  private final LastNameProvider provider;

  public ClassA(LastNameProvider provider) {
    this.provider = provider;
  }

  public String getName() {
    String lastName = provider.getLastName();
    return "Language"+lastName;
  }
}

public interface LastNameProvider {
  String getLastName()
}

public class JavaLastNameProvider {
  private String getLastName(){
    return "Java";
  }
}

With that approach you can easily replace provider in ClassA with another one for testing, or you can mock it with Mockito and so on.


问:
When to 'IN' and when not to?
Let's presume that you are writing an application for a retail store chain. So, you would design your object model such that you would define 'Store' as the core business object and lots of supporting objects. Let's say 'Store' looks like follows:

```<code>class Store implements Validatable{
int storeNo;
int storeName;
... etc....
}
</code>```

So, your client tells you that you have to import store schedule from a excel sheet into the application and you would have to run a series of validations on 'em. For instance, 'StoreIsInSameCountry';'StoreIsValid'... etc. So, you would design a Rule interface for checking all business conditions. Something like this:

```<code>interface Rule T extends Validatable> {
public Error check(T value) throws Exception;
}
</code>```

Now, here comes the question. I am uploading 2000 stores from this excel sheet. So, I would end up running each rule defined for a store that many times. If I were to have 4 rules = 8000 queries to the database, i.e, 16000 hits to the connection pool. For a simple check where I would just have to check whether the store exists or not, the query would be:

```<code> SELECT STORE_ATTRIB1, STORE_ATTRIB2... from STORE where STORE_ID = ?
</code>```

That way I would obtain get my 'Store' object. When I don't get anything from the database, then that store doesn't exist. So, for such a simple check, I would have to hit the database 2000 times for 2000 stores.

Alternatively, I could just do:

```<code>SELECT STORE_ATTRIB1, STORE_ATTRIB2... from STORE where STORE_ID in (1,2,3..... )
</code>```

This query would actually return much faster than doing the one above it 2000 times.
However, it doesn't go well with the design that a Rule can be run for a single store only.

I know using IN is not a suggested methodology. So, what do you think I should be doing? Should I go ahead and use IN here, coz it gives better performance in this scenario? Or should I change my design?

What would you do if you were in my shoes, and what is the best practice?

答:
...a Rule can be run for a single store only.

Managing business rules along with performance is a tricky task, so there is a library ("Persistence Layer") that does exactly that. You define rules, then execute a bulk of commands, then the library fetch from DB whatever the rules require in a single query (by using temp tables rather than 'IN') and then passes it to the rules.
There is an example of a validator in here.

ContentLicense: CC BY-SA 2.5

Title: When to 'IN' and when not to?

Body:
Let's presume that you are writing an application for a retail store chain. So, you would design your object model such that you would define 'Store' as the core business object and lots of supporting objects. Let's say 'Store' looks like follows:

class Store implements Validatable{
int storeNo;
int storeName;
... etc....
}

So, your client tells you that you have to import store schedule from a excel sheet into the application and you would have to run a series of validations on 'em. For instance, 'StoreIsInSameCountry';'StoreIsValid'... etc. So, you would design a Rule interface for checking all business conditions. Something like this:

interface Rule T extends Validatable> {
public Error check(T value) throws Exception;
}

Now, here comes the question. I am uploading 2000 stores from this excel sheet. So, I would end up running each rule defined for a store that many times. If I were to have 4 rules = 8000 queries to the database, i.e, 16000 hits to the connection pool. For a simple check where I would just have to check whether the store exists or not, the query would be:

 SELECT STORE_ATTRIB1, STORE_ATTRIB2... from STORE where STORE_ID = ?

That way I would obtain get my 'Store' object. When I don't get anything from the database, then that store doesn't exist. So, for such a simple check, I would have to hit the database 2000 times for 2000 stores.

Alternatively, I could just do:

SELECT STORE_ATTRIB1, STORE_ATTRIB2... from STORE where STORE_ID in (1,2,3..... )

This query would actually return much faster than doing the one above it 2000 times.
However, it doesn't go well with the design that a Rule can be run for a single store only.

I know using IN is not a suggested methodology. So, what do you think I should be doing? Should I go ahead and use IN here, coz it gives better performance in this scenario? Or should I change my design?

What would you do if you were in my shoes, and what is the best practice?


答:
Your logic is slightly wrong. I have added the correct code below with comments :

```<code>integer = int(input("Enter an integer: "))

if integer >= 2:
    print(2)

for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    prime=true                       #assume that i is prime
    for j in range(2, i):       # we are going to try dividing by these
        if i % j == 0:          # not prime
            prime=false             # we now know it is not prime
            break
    if prime==true:                # if we didn't do prime=0, then it's a prime
        print(i)
</code>```

What you were doing is printing i for every j from 2 to i that did not divide i. But instead, what had to be done is print i only once when none of the j from 2 to i divided i.

Hope you understand the mistake and this clears your doubt !

Title: Python prime list

Body:
Your logic is slightly wrong. I have added the correct code below with comments :

integer = int(input("Enter an integer: "))

if integer >= 2:
    print(2)

for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
    prime=true                       #assume that i is prime
    for j in range(2, i):       # we are going to try dividing by these
        if i % j == 0:          # not prime
            prime=false             # we now know it is not prime
            break
    if prime==true:                # if we didn't do prime=0, then it's a prime
        print(i)

What you were doing is printing i for every j from 2 to i that did not divide i. But instead, what had to be done is print i only once when none of the j from 2 to i divided i.

Hope you understand the mistake and this clears your doubt !


问:
Overlapping/crowded labels on y-axis python
I'am kind of in a rush to finish this for tomorrows presentation towards the project owner. We are a small group of economic students in germany trying to figure out machine learning with python. We set up a Random Forest Classifier and are desperate to show the estimators important features in a neat plot. By applying google search we came up with the following solution that kind of does the trick, but leaves us unsatisfied due to the overlapping of the labels on the y-axis. The code we used looks like this:

```<code>feature_importances = clf.best_estimator_.feature_importances_
feature_importances = 100 * (feature_importances / feature_importances.max())
sorted_idx = np.argsort(feature_importances)

pos = np.arange(sorted_idx.shape[0])
plt.barh(pos, feature_importances[sorted_idx], align='center', height=0.8)
plt.yticks(pos, df_year_four.columns[sorted_idx])
plt.show()
</code>```

Due to privacy let me say this: The feature names on the y-axis are overlapping (there are about 30 of them). I was looking into the documentation of matplotlib in order to get an understanding of how to do this by myself, unfortunately I couldn't find anything helpful. Seems like training and testing models is easier than understanding matplotlib and creating plots :D

Thank you so much for helping out and taking the time, I appreciate it.

答:
Got it guys!
'Geistesblitz' as we say in germany! (spiritual lightening)
See the variable feature_importances in the third top row? Add feature_importnaces[:-15]
to view only the top half of the features and loosen up the y-axis. Yes!!! This does well because there are way less important features.

Body:
I'am kind of in a rush to finish this for tomorrows presentation towards the project owner. We are a small group of economic students in germany trying to figure out machine learning with python. We set up a Random Forest Classifier and are desperate to show the estimators important features in a neat plot. By applying google search we came up with the following solution that kind of does the trick, but leaves us unsatisfied due to the overlapping of the labels on the y-axis. The code we used looks like this:

feature_importances = clf.best_estimator_.feature_importances_
feature_importances = 100 * (feature_importances / feature_importances.max())
sorted_idx = np.argsort(feature_importances)

pos = np.arange(sorted_idx.shape[0])
plt.barh(pos, feature_importances[sorted_idx], align='center', height=0.8)
plt.yticks(pos, df_year_four.columns[sorted_idx])
plt.show()

Due to privacy let me say this: The feature names on the y-axis are overlapping (there are about 30 of them). I was looking into the documentation of matplotlib in order to get an understanding of how to do this by myself, unfortunately I couldn't find anything helpful. Seems like training and testing models is easier than understanding matplotlib and creating plots :D

Thank you so much for helping out and taking the time, I appreciate it.