问:
Having issues in functions inside function in javascript (eventlistener)
Got those Event Listeners out of the functions. Works ok except when 2 sounds in a row are the same, the second sound isn't said, sometimes. No idea where this comes from. Other issue : if the game is reset when unfinished then I get double sounds. I don't know where to remove the EventListeners if they are the problem.  Isn't it troublesome to have the same event (click on cells) with 2 different targets ?

Here's the code :

//Pour placer les images dans le tableau (sinon enlever cette partie pour avoir les images en ligne avec fonction shuffle dans un flex)

let cards = document.getElementsByClassName('card');
let nbreCards = cards.length;
cell1.appendChild(card1);
cell2.appendChild(card2);
cell3.appendChild(card3);
cell4.appendChild(card4);
cell5.appendChild(card5);
cell6.appendChild(card6);

//Pour mélanger les images dans le tableau.
function shuffle() {
  let cardVar = [card1, card2, card3, card4, card5, card6];

  for (let cardPosition = cardVar.length - 1; cardPosition >= 1; cardPosition--) {
    let numrandom = Math.floor(Math.random() * (cardPosition + 1));
    let sauve = cardVar[cardPosition];
    cardVar[cardPosition] = cardVar[numrandom];
    cardVar[numrandom] = sauve;
  }
  //Mélange aléatoire des cartes du tableau
  cell1.appendChild(cardVar[0]);
  cell2.appendChild(cardVar[1]);
  cell3.appendChild(cardVar[2]);
  cell4.appendChild(cardVar[3]);
  cell5.appendChild(cardVar[4]);
  cell6.appendChild(cardVar[5]);
}

//Pour jouerSon aléatoire  sans doublon ... à finir...

//Récupérer array des sons et nombre de sons :

function sonsAleatoires() {
  //Arrays of win and loose
  let reussitesArray = [];
  let echecsArray = [];

  let sounds = document.getElementsByTagName('audio');
  let nbreSounds = sounds.length;
  let soundsArray = [];

  for (let i = 0; i < nbreSounds; i++) {
    sons = sounds[i];
    let x = sons.getAttributeNode('id').value;
    soundsArray.push(x);
  }

  //Duplique deux fois la liste des sons pour en avoir une vingtaine
  let soundsArray2 = soundsArray.slice();
  let soundsArray3 = soundsArray2.slice();
  let soundsArray4 = soundsArray.concat(soundsArray2, soundsArray3);

  //Randomize sounds
  for (let soundPosition = soundsArray4.length - 1; soundPosition >= 1; soundPosition--) {
    let numrandom = Math.floor(Math.random() * (soundPosition + 1));
    let sauve = soundsArray4[soundPosition];
    soundsArray4[soundPosition] = soundsArray4[numrandom];
    soundsArray4[numrandom] = sauve;
  }

  console.log(soundsArray4);

  let p = -1;
  let numsnd;

  son();

  function son() {
    p++;
    if (p >= soundsArray4.length) {
      return;
    } else {
      let sonAjouer = document.getElementById(soundsArray4[p]);
      let snd = sonAjouer.getAttributeNode('id').value;
      numsnd = Number(snd.charAt(3));
      sonAjouer.play();
    } //fin du if
  } //fin de son

  let cells = document.getElementsByTagName('td');
  let nbreCells = cells.length;
  for (var y = 0; y < nbreCells; y++) {
    cells[y].addEventListener('click', donnerResultat);
  }

  function donnerResultat() {
    let idCell = "";
    let contenuCell = "";
    let numImage = 0;
    idCell = (this.id);
    contenuCell = document.getElementById(idCell).lastElementChild.getAttributeNode('id').value;
    numImage = Number(contenuCell.charAt(4));
    if (p >= soundsArray4.length) {
      return;
    }

    //Compares id soundn and id img cliqued
    if (numsnd === numImage) {
      reussitesArray.push(1);

      document.getElementById(idCell).style.backgroundColor = "#83f500";
      setTimeout(function() {
        document.getElementById(idCell).style.backgroundColor = "";
      }, 1000);

    } else {
      echecsArray.push(contenuCell);
      document.getElementById(idCell).style.backgroundColor = "#f13022";
      setTimeout(function() {
        document.getElementById(idCell).style.backgroundColor = ""
      }, 1000);
    } //fin du if

  } //end of function donnerResultat

  //next sound
  for (var c = 0; c < nbreCells; c++) {
    cells[c].addEventListener('click', son, false);
  }

} //end of sonsAleatoires```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,
*:before,
*:after {
  margin: 0px;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  width: 100%;
}

body {
  justify-content: center;
  align-items: center;
  background-color: #ffeb3b63
}

h1 {
  font-size: 5vw;
  color: #FF5722;
}

.main {
  background-color: orange;
  width: 100%;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.card {
  position: relative;
  margin: auto;
}

.card img {
  max-height: 12vw;
  width: auto;
  position: relative;
  border-radius: 1em;
  margin: auto;
  border: 1px solid #9C27B0;
  cursor: pointer;
}

.buttons {
  width: 15%;
  position: absolute;
  top: 10vw;
}

.buttons ul {
  list-style: none;
}

#button1 {
  display: none;
}

#button,
#button1,
#button3,
#button4 {
  position: relative;
  max-height: 10vw;
  float: right;
}

table {
  margin: auto;
  width: 65%;
}

table,
td {
  border: 1px solid #9c27b0;
  //border-collapse: collapse;
  padding: 2px;
  text-align: center;
  font: 4vw bold;
  color: #FFC107;
  background-color: #d0e21b6e
}

td {
  width: 31%;
}

.cell {
  cursor: pointer;
  background-color: #795548a1
}

p {
  position: relative;
  color: blue;
  font-size: 4vw;
  left: 50px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Listen and point to</title>
  <link rel="stylesheet" href="style.css" />

 Ecoute et clique

<input type="image" id="button3" src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/buttons/bouton-son.png" alt="bouton" onclick="sonsAleatoires()" />

<input type="image" id="button4" src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/buttons/repeat.PNG" alt="bouton" onclick="replay()" />

<input type="image" id="button1" src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/buttons/read.png" alt="bouton" onclick="afficher()" />

  <audio id="son1">
      <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/broth.ogg" type="audio/ogg">
      <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/broth.mp3" type="audio/mpeg">
        </audio>
  <audio id="son2">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/sister.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/sister.ogg" type="audio/ogg">
  </audio>
  <audio id="son3">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/moth.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/moth.ogg" type="audio/ogg">
  </audio>
  <audio id="son4">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/fath.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/fath.ogg" type="audio/ogg">
  </audio>
  <audio id="son5">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdm.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdm.ogg" type="audio/ogg">
  </audio>
  <audio id="son6">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdf.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdf.ogg" type="audio/ogg">
          </audio>

  <p id="Moyenne"

```

答:
It is hard to tell from the provided code, but is it possible that you keep adding EventListeners each time you play a sound without removing them?

Maybe you can either remove them after playing a sound or only add them once (somewhere outside the son() function).

Body:
Got those Event Listeners out of the functions. Works ok except when 2 sounds in a row are the same, the second sound isn't said, sometimes. No idea where this comes from. Other issue : if the game is reset when unfinished then I get double sounds. I don't know where to remove the EventListeners if they are the problem.  Isn't it troublesome to have the same event (click on cells) with 2 different targets ?

Here's the code :

//Pour placer les images dans le tableau (sinon enlever cette partie pour avoir les images en ligne avec fonction shuffle dans un flex)

let cards = document.getElementsByClassName('card');
let nbreCards = cards.length;
cell1.appendChild(card1);
cell2.appendChild(card2);
cell3.appendChild(card3);
cell4.appendChild(card4);
cell5.appendChild(card5);
cell6.appendChild(card6);

//Pour mélanger les images dans le tableau.
function shuffle() {
  let cardVar = [card1, card2, card3, card4, card5, card6];

  for (let cardPosition = cardVar.length - 1; cardPosition >= 1; cardPosition--) {
    let numrandom = Math.floor(Math.random() * (cardPosition + 1));
    let sauve = cardVar[cardPosition];
    cardVar[cardPosition] = cardVar[numrandom];
    cardVar[numrandom] = sauve;
  }
  //Mélange aléatoire des cartes du tableau
  cell1.appendChild(cardVar[0]);
  cell2.appendChild(cardVar[1]);
  cell3.appendChild(cardVar[2]);
  cell4.appendChild(cardVar[3]);
  cell5.appendChild(cardVar[4]);
  cell6.appendChild(cardVar[5]);
}

//Pour jouerSon aléatoire  sans doublon ... à finir...

//Récupérer array des sons et nombre de sons :

function sonsAleatoires() {
  //Arrays of win and loose
  let reussitesArray = [];
  let echecsArray = [];

  let sounds = document.getElementsByTagName('audio');
  let nbreSounds = sounds.length;
  let soundsArray = [];

  for (let i = 0; i < nbreSounds; i++) {
    sons = sounds[i];
    let x = sons.getAttributeNode('id').value;
    soundsArray.push(x);
  }

  //Duplique deux fois la liste des sons pour en avoir une vingtaine
  let soundsArray2 = soundsArray.slice();
  let soundsArray3 = soundsArray2.slice();
  let soundsArray4 = soundsArray.concat(soundsArray2, soundsArray3);

  //Randomize sounds
  for (let soundPosition = soundsArray4.length - 1; soundPosition >= 1; soundPosition--) {
    let numrandom = Math.floor(Math.random() * (soundPosition + 1));
    let sauve = soundsArray4[soundPosition];
    soundsArray4[soundPosition] = soundsArray4[numrandom];
    soundsArray4[numrandom] = sauve;
  }

  console.log(soundsArray4);

  let p = -1;
  let numsnd;

  son();

  function son() {
    p++;
    if (p >= soundsArray4.length) {
      return;
    } else {
      let sonAjouer = document.getElementById(soundsArray4[p]);
      let snd = sonAjouer.getAttributeNode('id').value;
      numsnd = Number(snd.charAt(3));
      sonAjouer.play();
    } //fin du if
  } //fin de son

  let cells = document.getElementsByTagName('td');
  let nbreCells = cells.length;
  for (var y = 0; y < nbreCells; y++) {
    cells[y].addEventListener('click', donnerResultat);
  }

  function donnerResultat() {
    let idCell = "";
    let contenuCell = "";
    let numImage = 0;
    idCell = (this.id);
    contenuCell = document.getElementById(idCell).lastElementChild.getAttributeNode('id').value;
    numImage = Number(contenuCell.charAt(4));
    if (p >= soundsArray4.length) {
      return;
    }

    //Compares id soundn and id img cliqued
    if (numsnd === numImage) {
      reussitesArray.push(1);

      document.getElementById(idCell).style.backgroundColor = "#83f500";
      setTimeout(function() {
        document.getElementById(idCell).style.backgroundColor = "";
      }, 1000);

    } else {
      echecsArray.push(contenuCell);
      document.getElementById(idCell).style.backgroundColor = "#f13022";
      setTimeout(function() {
        document.getElementById(idCell).style.backgroundColor = ""
      }, 1000);
    } //fin du if

  } //end of function donnerResultat

  //next sound
  for (var c = 0; c < nbreCells; c++) {
    cells[c].addEventListener('click', son, false);
  }

} //end of sonsAleatoires

*,
*:before,
*:after {
  margin: 0px;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  width: 100%;
}

body {
  justify-content: center;
  align-items: center;
  background-color: #ffeb3b63
}

h1 {
  font-size: 5vw;
  color: #FF5722;
}

.main {
  background-color: orange;
  width: 100%;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.card {
  position: relative;
  margin: auto;
}

.card img {
  max-height: 12vw;
  width: auto;
  position: relative;
  border-radius: 1em;
  margin: auto;
  border: 1px solid #9C27B0;
  cursor: pointer;
}

.buttons {
  width: 15%;
  position: absolute;
  top: 10vw;
}

.buttons ul {
  list-style: none;
}

#button1 {
  display: none;
}

#button,
#button1,
#button3,
#button4 {
  position: relative;
  max-height: 10vw;
  float: right;
}

table {
  margin: auto;
  width: 65%;
}

table,
td {
  border: 1px solid #9c27b0;
  //border-collapse: collapse;
  padding: 2px;
  text-align: center;
  font: 4vw bold;
  color: #FFC107;
  background-color: #d0e21b6e
}

td {
  width: 31%;
}

.cell {
  cursor: pointer;
  background-color: #795548a1
}

p {
  position: relative;
  color: blue;
  font-size: 4vw;
  left: 50px;
}

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Listen and point to</title>
  <link rel="stylesheet" href="style.css" />

 Ecoute et clique

<input type="image" id="button3" src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/buttons/bouton-son.png" alt="bouton" onclick="sonsAleatoires()" />

<input type="image" id="button4" src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/buttons/repeat.PNG" alt="bouton" onclick="replay()" />

<input type="image" id="button1" src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/buttons/read.png" alt="bouton" onclick="afficher()" />

  <audio id="son1">
      <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/broth.ogg" type="audio/ogg">
      <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/broth.mp3" type="audio/mpeg">
        </audio>
  <audio id="son2">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/sister.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/sister.ogg" type="audio/ogg">
  </audio>
  <audio id="son3">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/moth.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/moth.ogg" type="audio/ogg">
  </audio>
  <audio id="son4">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/fath.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/fath.ogg" type="audio/ogg">
  </audio>
  <audio id="son5">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdm.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdm.ogg" type="audio/ogg">
  </audio>
  <audio id="son6">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdf.mp3" type="audio/mpeg">
          <source src="http://lve64.free.fr/projets_jeu_navigateur/projet_cartes_lve2/famille_mots/gdf.ogg" type="audio/ogg">
          </audio>

  <p id="Moyenne"


来源: stackexchange

问:
How to get timestamp in nanoseconds in Python 3?
```<code>import time
print(time.time())
</code>```

This gives me output:

```<code>1590683242.8507078
</code>```

Desired output is 19-digit long nanosecond Unix timestamp.

答:
time.time_ns()

Similar to time() but returns time as an integer number of nanoseconds since the epoch.

See https://docs.python.org/3.7/library/time.html#time.time_ns

ContentLicense: CC BY-SA 4.0

Body:
import time
print(time.time())

This gives me output:

1590683242.8507078

Desired output is 19-digit long nanosecond Unix timestamp.


问:
How can I have access into *argv[ ] in C?
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!</p>

```<code>int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}
</code>```

答:
Placing them in argv is the wrong approach. Much better to do something like this:

```<code>int main (int argc, char **argv)
{
    char f1[255];
    char f2[255];
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", f1);
        printf("file 2: ");
        scanf("%s ", f2);
    } else {
        strcpy(f1, argv[1]);
        strcpy(f2, argv[2]);
    }
    FILE *file1 = fopen(f1, "r");
    FILE *file2 = fopen(f2, "r");
}
</code>```

You should avoid writing to argv. That's in general a bad idea.

Body:
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!

int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}

Body:
Placing them in argv is the wrong approach. Much better to do something like this:

int main (int argc, char **argv)
{
    char f1[255];
    char f2[255];
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", f1);
        printf("file 2: ");
        scanf("%s ", f2);
    } else {
        strcpy(f1, argv[1]);
        strcpy(f2, argv[2]);
    }
    FILE *file1 = fopen(f1, "r");
    FILE *file2 = fopen(f2, "r");
}

You should avoid writing to argv. That's in general a bad idea.


问:
PHP MySQL insert values from multiple checkboxes into one column in table
I have a form that a user would fill out while creating a ticket for a bug they have found on our website.  In the form there is currently an input field where the user would enter in the designs that the bug is affecting (ex., "Design1, Design2, Design3, Design4" ...etc).  When the form is submitted the value is stored in a table column named affectedDesigns.

What i am wanting to do is create several checkboxes (one check box for each design we have) that a user would select instead of using the input field.  They would be able to select all that apply.  If possible i would still like to store all of the values into the affectedDesigns column in one record.  I'm thinking that i can gather the selected checkboxes values and create an array or some comma delimited value that contains all of the selected items and submit that to the databasein the one record in the affectedDesigns column.  How can i achieve this?

Also, how would i then pull that data and re-populate the checkboxes if they would like to go back later and edit the ticket?  Thanks for any help!

答: create an array from your $_POST values keyed on the name of each checkbox, then just serialize that array before insert.... then you can unserialize it when you load it up again</p>

ContentLicense: CC BY-SA 3.0


问:
How would I convert multiple strings to an IP address in Powershell so I can filter out IPv6
I have to pull a log file that contains a list of IP address within a windows log with some other stuff. I have figured out how to filter it down to just IP address, but I am struggling to convert it to an IP address object so I can filter out IPv6 entries.

In production I will use something like this to get the log:

```<code>$log = Get-Eventlog -Logname ABC -Source WIN-ABC -Newest 1 -ErrorAction stop
</code>```

The .txt or log file looks like this:

```<code>Compare-DomainControllers

Customer.local
192.168.1.100
192.168.1.101
192.168.1.102
2580:83:0:f2e:b25a:625f:c254:eb29
10.10.10.20
etc...
</code>```

What I have now in testing is:

$IPFullList = Get-content -path .\test.txt (Fake Log File)
$IPOnly = $IPFullList | Select-String -match "[0-9]"

This returns a list of just the IPv4 and IPv6 items, but I am hoping to take that list and convert the entries into [IPAddress] objects so I can filter out the IPv6 items.

I have tried:

ConvertFrom-String -Inputobject $IPOnly

and:

Foreach ($IP in IPOnly){
[IPaddress] | Where-Object {$_.Type -ne "AAAA"} | Write-Host
}

Non of them seem to do the trick. Any ideas or suggestions would be greatly appreciated!

答:
You can do the following:

```<code>$IPFullList = Get-content -Path .\test.txt
$IPOnly = [IPAddress[]]($IPFullList -match '(?:\d{1,3}\.){3}\d{1,3}').Trim()
</code>```

The result will be an array of IPv4 addresses stored in $IPOnly.

-match uses regex matching and will return matching strings if the input (left-hand side) is an array. If you are only passing a single string, -match will return $true or $false only.

Trim() method is used to remove white space from the beginning and end of each string.

If you want to process each IP individually, you can pipe into Foreach-Object:

```<code>$IPFullList = Get-content -Path .\test.txt
$IPOnly = ($IPFullList -match '(?:\d{1,3}\.){3}\d{1,3}').Trim() | Foreach-Object {
    [IPAddress]$_ # Returns the IPAddress object
}
</code>```

Body:
I have to pull a log file that contains a list of IP address within a windows log with some other stuff. I have figured out how to filter it down to just IP address, but I am struggling to convert it to an IP address object so I can filter out IPv6 entries.

In production I will use something like this to get the log:

$log = Get-Eventlog -Logname ABC -Source WIN-ABC -Newest 1 -ErrorAction stop

The .txt or log file looks like this:

Compare-DomainControllers

Customer.local
192.168.1.100
192.168.1.101
192.168.1.102
2580:83:0:f2e:b25a:625f:c254:eb29
10.10.10.20
etc...

What I have now in testing is:

$IPFullList = Get-content -path .\test.txt (Fake Log File)
$IPOnly = $IPFullList | Select-String -match "[0-9]"

This returns a list of just the IPv4 and IPv6 items, but I am hoping to take that list and convert the entries into [IPAddress] objects so I can filter out the IPv6 items.

I have tried:

ConvertFrom-String -Inputobject $IPOnly

and:

Foreach ($IP in IPOnly){
[IPaddress] | Where-Object {$_.Type -ne "AAAA"} | Write-Host
}

Non of them seem to do the trick. Any ideas or suggestions would be greatly appreciated!

Body:
You can do the following:

$IPFullList = Get-content -Path .\test.txt
$IPOnly = [IPAddress[]]($IPFullList -match '(?:\d{1,3}\.){3}\d{1,3}').Trim()

The result will be an array of IPv4 addresses stored in $IPOnly.

-match uses regex matching and will return matching strings if the input (left-hand side) is an array. If you are only passing a single string, -match will return $true or $false only.

Trim() method is used to remove white space from the beginning and end of each string.

If you want to process each IP individually, you can pipe into Foreach-Object:

$IPFullList = Get-content -Path .\test.txt
$IPOnly = ($IPFullList -match '(?:\d{1,3}\.){3}\d{1,3}').Trim() | Foreach-Object {
    [IPAddress]$_ # Returns the IPAddress object
}


Title: How to get timestamp in nanoseconds in Python 3?

Body:
import time
print(time.time_ns())

1590683731073953000


问:
How to use CSS calc() with an element's height
I was studying ways to make a hexagon with just CSS, and found a solution that gives me regular hexagons based on the width:

.hexagon {
  height: 100%;
  width: calc(100% * 0.57735);
  display: inline-block;
}
```

However, the code works by generating new rectangles based on the parent element's width. I was searching for a way to calculate the width based on the parent's height.

Is there a way to use an element's height property instead of width for calc()? (I'm not looking into using vh since the nearest parent won't always be the viewport). I googled around and could not find an answer.

答:
I suggest to define a css rule which depends on a css var (as proposed by Carles Alcolea) and implement a javascript code which updates the value of the css var.

Define css which uses var()

```<code>.hexagon.parent {
  /* ... */
  width: var(--hex-parent-height);
}
</code>```

Create a placeholder within the html to hold var(s) definition

```<code><style id="my-dyn-css">
/* dynamically define css vars here */
</style>
</code>```

Define a function to set and update the values of the vars (for example on window resize)

```<code>function updateDynCss() {
  var parentHeight = computeHeight();
  var style = ":root{--hex-parent-height:" + parentHeight + "px;}";
  $("#my-dyn-css").empty().html(style);
}
</code>```

Body:
I was studying ways to make a hexagon with just CSS, and found a solution that gives me regular hexagons based on the width:

.hexagon {
  height: 100%;
  width: calc(100% * 0.57735);
  display: inline-block;
}

However, the code works by generating new rectangles based on the parent element's width. I was searching for a way to calculate the width based on the parent's height.

Is there a way to use an element's height property instead of width for calc()? (I'm not looking into using vh since the nearest parent won't always be the viewport). I googled around and could not find an answer.

Body:
I suggest to define a css rule which depends on a css var (as proposed by Carles Alcolea) and implement a javascript code which updates the value of the css var.

Define css which uses var()

.hexagon.parent {
  /* ... */
  width: var(--hex-parent-height);
}

Create a placeholder within the html to hold var(s) definition

<style id="my-dyn-css">
/* dynamically define css vars here */
</style>

Define a function to set and update the values of the vars (for example on window resize)

function updateDynCss() {
  var parentHeight = computeHeight();
  var style = ":root{--hex-parent-height:" + parentHeight + "px;}";
  $("#my-dyn-css").empty().html(style);
}


问:
Boolean Search In Lucene
I have been trying to run the following boolean query in lucene but it seems to fail. Please help.

(a or b) and c -> works fine

(a AND b) or c -> gives result for a AND b OR c. So a becomes must and b and c becomes should, and the search result is wrong. Where it should work like a, b must be available or c may be available.

Another example:

If you search for "(a AND b)" it will return x results

If you search for "c" it will return y results

If you search for "(a and b) or c" the number of results cannot be less than the larger of x or y. But this is not happening. Please help how should I proceed to implement this?

答:
(a AND b) or c gets converted to (+a +b) c. What you want is this without parentheses: +a +b c.

From a logical perspective, "A and B must occur, C might occur" is equivalent to "A and B must occur." (There is no way to say "might be true" in classical logic.) So you will have difficulty saying (+a +b) c in boolean terms. One way you could do it is "(a AND b AND c) or (a AND b)".

Title: Boolean Search In Lucene


问:
How to Toggle Classname in ReactJS when button is Clicked?
I want to change the hamburger style of menu when I click the button. The toggle for opening the menu is already okay but I'm having a problem when changing the className of my hamburger menu.

This is my constructor and function

```<code>constructor(props) {
    super(props)

    this.state = { menuOpen: true }
    this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
    const {show} = this.state;
    this.setState({show : !show});
}
</code>```

I am binding my toggleMenu function in this section here:

```<code><div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
<div className="hamburger-inner"></div>
</div>
</div>
</code>```

I created a class Component called NavMenu and pass that function when user will click the hamburger menu.

```<code>class NavMenu extends Component {
    render() {
        return (
            <nav className="isMobile">
                <ul>
                    <li><a href="#about">About Us</a></li>
                    <li><a href="#bottom2">Services</a></li>
                    <li><a href="/">Clients</a></li>
                    <li><a href="/">Contact</a></li>
                    <li><a href="/">Login</a></li>
                </ul>
             </nav>
        )
    }
}
</code>```

And here is my whole class component to fully understand the process.
Class Component Source Code

```<code>import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (
<div id="nav_area">
<div className="nav_toggle_button">
<div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
    <div className="hamburger-inner"></div>
</div>
</div>
</div>
<nav className="isWeb">
<ul>
    <li><a href="#about">About Us</a></li>
    <li><a href="#bottom2">Services</a></li>
    <li><a href="/">Clients</a></li>
    <li><a href="/">Contact</a></li>
    <li><a href="/">Login</a></li>
</ul>
</nav>
{this.state.show && <NavMenu/>}
</div>
)
}
}

class NavMenu extends Component {
render() {
return (
<nav className="isMobile">
<ul>
<li><a href="#about">About Us</a></li>
<li><a href="#bottom2">Services</a></li>
<li><a href="/">Clients</a></li>
<li><a href="/">Contact</a></li>
<li><a href="/">Login</a></li>
</ul>
</nav>
)
}
}

export default nav
</code>```

What seems to be lacking in this end in order to change the className when clicked? What I'm trying to solve is when the hamburger menu is Clicked it will show the navigation items and also changed the hambuger from hamburger hamburger--emphatic-r to hamburger hamburger--emphatic-r is-Active.

答:
You have not declraed show object in state , no need menuOpen just replace it with show and in ternary use that show state

```<code>import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { show: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (
<div id="nav_area">
<div className="nav_toggle_button">
<div className={this.state.show ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
    <div className="hamburger-inner"></div>
</div>
</div>
</div>
<nav className="isWeb">
<ul>
    <li><a href="#about">About Us</a></li>
    <li><a href="#bottom2">Services</a></li>
    <li><a href="/">Clients</a></li>
    <li><a href="/">Contact</a></li>
    <li><a href="/">Login</a></li>
</ul>
</nav>
{this.state.show && <NavMenu/>}
</div>
)
}
}

class NavMenu extends Component {
render() {
return (
<nav className="isMobile">
<ul>
<li><a href="#about">About Us</a></li>
<li><a href="#bottom2">Services</a></li>
<li><a href="/">Clients</a></li>
<li><a href="/">Contact</a></li>
<li><a href="/">Login</a></li>
</ul>
</nav>
)
}
}

export default nav
</code>```

Body:
I want to change the hamburger style of menu when I click the button. The toggle for opening the menu is already okay but I'm having a problem when changing the className of my hamburger menu.

This is my constructor and function

constructor(props) {
    super(props)

    this.state = { menuOpen: true }
    this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
    const {show} = this.state;
    this.setState({show : !show});
}

I am binding my toggleMenu function in this section here:

I created a class Component called NavMenu and pass that function when user will click the hamburger menu.

class NavMenu extends Component {
    render() {
        return (

About Us

Services

Clients

Contact

Login

        )
    }
}

And here is my whole class component to fully understand the process.
Class Component Source Code

import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (

About Us

Services

Clients

Contact

Login

{this.state.show && <NavMenu/>}

)
}
}

class NavMenu extends Component {
render() {
return (

About Us

Services

Clients

Contact

Login

)
}
}

export default nav

What seems to be lacking in this end in order to change the className when clicked? What I'm trying to solve is when the hamburger menu is Clicked it will show the navigation items and also changed the hambuger from hamburger hamburger--emphatic-r to hamburger hamburger--emphatic-r is-Active.

Body:
You have not declraed show object in state , no need menuOpen just replace it with show and in ternary use that show state

import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { show: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (
<div id="nav_area">
<div className="nav_toggle_button">
<div className={this.state.show ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
    <div className="hamburger-inner"></div>
</div>
</div>
</div>
<nav className="isWeb">
<ul>
    <li><a href="#about">About Us</a></li>
    <li><a href="#bottom2">Services</a></li>
    <li><a href="/">Clients</a></li>
    <li><a href="/">Contact</a></li>
    <li><a href="/">Login</a></li>
</ul>
</nav>
{this.state.show && <NavMenu/>}
</div>
)
}
}

class NavMenu extends Component {
render() {
return (
<nav className="isMobile">
<ul>
<li><a href="#about">About Us</a></li>
<li><a href="#bottom2">Services</a></li>
<li><a href="/">Clients</a></li>
<li><a href="/">Contact</a></li>
<li><a href="/">Login</a></li>
</ul>
</nav>
)
}
}

export default nav


答:
Use

import time
print(time.time_ns())
```

Body:
Use

import time
print(time.time_ns())


问:
how do i get my viewer controller to be full screen?
I am developing an app using xcode (Swift) with out using the storyboard but i have a problem when a user logs in to the app they are transferred to the home page but the viewer controller does not reach the top of the screen and when i change to a different tab i can see the login screen in the background.

This is the code i use to get transferred to the home screen once the user logs in:

```<code>let mainTabVC = MainTabVC()
self.present(mainTabVC, animated: true,completion: nil)
</code>```

is there any way to fix this?

答:
You need to set  modalPresentationStyle of your controller Apple documentation

```<code> mainTabVC.modalPresentationStyle = .fullScreen
</code>```

The presentation style determines how a modally presented view
  controller is displayed onscreen. In a horizontally compact
  environment, modal view controllers are always presented full-screen.
  In a horizontally regular environment, there are several different
  presentation options. The default value for this property is
  UIModalPresentationStyle.automatic. For a list of possible
  presentation styles, and their compatibility with the available
  transition styles, see the UIModalPresentationStyle constant
  descriptions.

Body:
I am developing an app using xcode (Swift) with out using the storyboard but i have a problem when a user logs in to the app they are transferred to the home page but the viewer controller does not reach the top of the screen and when i change to a different tab i can see the login screen in the background.

This is the code i use to get transferred to the home screen once the user logs in:

let mainTabVC = MainTabVC()
self.present(mainTabVC, animated: true,completion: nil)

is there any way to fix this?

Body:
You need to set  modalPresentationStyle of your controller Apple documentation

 mainTabVC.modalPresentationStyle = .fullScreen

The presentation style determines how a modally presented view
  controller is displayed onscreen. In a horizontally compact
  environment, modal view controllers are always presented full-screen.
  In a horizontally regular environment, there are several different
  presentation options. The default value for this property is
  UIModalPresentationStyle.automatic. For a list of possible
  presentation styles, and their compatibility with the available
  transition styles, see the UIModalPresentationStyle constant
  descriptions.


问:
Should I use jquery or jquery mobile or iPad web pages?
I am making a web page "app" for the iPad or ios devices.  Should I use jquery mobile or just regular jquery?  After all they're only web pages aren't they?  Is jquery proper no good for me?  Do I need mobile jquery?

Thanks.

答:
Yes, use jQuery Mobile library. It was developed specifically for this purpose. The base jQuery library does not help you write mobile applications in and of itself.

Also look at Sencha Touch. It's a bit more mature.


问:
How to output a hyphen after each character with restrictions using nested for loops in java
I just have one small issue with outputting a hyphen after every character (including the three dots shown in the code below)

Sample input

```<code>  2 (option #)
  disappear (phrase)
</code>```

Expected output:

```<code> d-i-s-a-p-p-e-a-r-.-.-.
 d-i-s-a-p-p-e-a-.-.-.
 d-i-s-a-p-p-e-.-.-.
 d-i-s-a-p-p-.-.-.
 d-i-s-a-p-.-.-.
 d-i-s-a-.-.-.
 d-i-s-.-.-.
 d-i-.-.-.
 d-.-.-.
 .-.-.
 .-.
 .
</code>```

It outputs the "-" after every character excluding the last dot

I got the "-" to display after very word character but cant figure out displaying after the dots too, like it works but there has to be one less hypen:

My actual output:

```<code>d-i-s-a-p-p-e-a-r-.-.-.-
 d-i-s-a-p-p-e-a-.-.-.-
 d-i-s-a-p-p-e-.-.-.-
 d-i-s-a-p-p-.-.-.-
 d-i-s-a-p-.-.-.-
 d-i-s-a-.-.-.-
 d-i-s-.-.-.-
 d-i-.-.-.-
 d-.-.-.-
 .-.-.-
 .-.-
 .-
</code>```

I am partially done, I just need one less hyphen which would automatically also fulfill the requirement of not displaying a hyphen after the very last dot.

Code:

```<code>       else if (option == 2){
             for (int x = 0; x < phrase.length(); x++){
                for (int y = 0; y < phrase.length() - x; y++){
                    char n = phrase.charAt(y);
                    System.out.print(n+"-");
                }
                for (int a = 0; a < 3; a++){
                    System.out.print("."+"-");
                }
                System.out.println("");
            }
            for (int j = 0; j < 3; j++){
                for (int i = 0; i < 3 - j; i++){
                    System.out.print("."+"-");
                }
                System.out.println("");
            }
        }
</code>```

答:
One way you could remove the last - is to only print - when it's not the last iteration. You can check that it's not the last iteration by checking loopVariable != loopBound - 1.

So your code would be:

```<code>for (int x = 0; x < phrase.length(); x++){
    for (int y = 0; y < phrase.length() - x; y++){
        char n = phrase.charAt(y);
        System.out.print(n+"-");
    }

    // You could just print the literal "--.-." instead
    for (int a = 0; a < 3; a++){
        System.out.print(".");
        if (a != 2) { // Notice here!
            System.out.print("-");
        }
    }
    System.out.println();
}
for (int j = 0; j < 3; j++){
    for (int i = 0; i < 3 - j; i++){
        System.out.print(".");
        if (i != 2 - j) { // and here
            System.out.print("-");
        }
    }
    System.out.println();
}
</code>```

Here's how I would do it:

```<code>// pretend that the phrase is 3 characters longer than it actually is...
// because of the three dots at the end
for (int x = 0; x < phrase.length() + 3; x++){
    for (int y = 0; y < phrase.length() + 3 - x; y++){
        char n;
        // Should we print the phrase or the dots?
        if (y < phrase.length() - x) {
            n = phrase.charAt(y);
        } else {
            n = '.';
        }
        System.out.print(n);
        if (y != phrase.length() + 2 - x) { // same trick of checking if it is last iteration
            System.out.print("-");
        }
    }
    System.out.println();
}
</code>```

Body:
I just have one small issue with outputting a hyphen after every character (including the three dots shown in the code below)

Sample input

  2 (option #)
  disappear (phrase)

Expected output:

 d-i-s-a-p-p-e-a-r-.-.-.
 d-i-s-a-p-p-e-a-.-.-.
 d-i-s-a-p-p-e-.-.-.
 d-i-s-a-p-p-.-.-.
 d-i-s-a-p-.-.-.
 d-i-s-a-.-.-.
 d-i-s-.-.-.
 d-i-.-.-.
 d-.-.-.
 .-.-.
 .-.
 .

It outputs the "-" after every character excluding the last dot

I got the "-" to display after very word character but cant figure out displaying after the dots too, like it works but there has to be one less hypen:

My actual output:

d-i-s-a-p-p-e-a-r-.-.-.-
 d-i-s-a-p-p-e-a-.-.-.-
 d-i-s-a-p-p-e-.-.-.-
 d-i-s-a-p-p-.-.-.-
 d-i-s-a-p-.-.-.-
 d-i-s-a-.-.-.-
 d-i-s-.-.-.-
 d-i-.-.-.-
 d-.-.-.-
 .-.-.-
 .-.-
 .-

I am partially done, I just need one less hyphen which would automatically also fulfill the requirement of not displaying a hyphen after the very last dot.

Code:

       else if (option == 2){
             for (int x = 0; x < phrase.length(); x++){
                for (int y = 0; y < phrase.length() - x; y++){
                    char n = phrase.charAt(y);
                    System.out.print(n+"-");
                }
                for (int a = 0; a < 3; a++){
                    System.out.print("."+"-");
                }
                System.out.println("");
            }
            for (int j = 0; j < 3; j++){
                for (int i = 0; i < 3 - j; i++){
                    System.out.print("."+"-");
                }
                System.out.println("");
            }
        }

Body:
One way you could remove the last - is to only print - when it's not the last iteration. You can check that it's not the last iteration by checking loopVariable != loopBound - 1.

So your code would be:

for (int x = 0; x < phrase.length(); x++){
    for (int y = 0; y < phrase.length() - x; y++){
        char n = phrase.charAt(y);
        System.out.print(n+"-");
    }

    // You could just print the literal "--.-." instead
    for (int a = 0; a < 3; a++){
        System.out.print(".");
        if (a != 2) { // Notice here!
            System.out.print("-");
        }
    }
    System.out.println();
}
for (int j = 0; j < 3; j++){
    for (int i = 0; i < 3 - j; i++){
        System.out.print(".");
        if (i != 2 - j) { // and here
            System.out.print("-");
        }
    }
    System.out.println();
}

Here's how I would do it:

// pretend that the phrase is 3 characters longer than it actually is...
// because of the three dots at the end
for (int x = 0; x < phrase.length() + 3; x++){
    for (int y = 0; y < phrase.length() + 3 - x; y++){
        char n;
        // Should we print the phrase or the dots?
        if (y < phrase.length() - x) {
            n = phrase.charAt(y);
        } else {
            n = '.';
        }
        System.out.print(n);
        if (y != phrase.length() + 2 - x) { // same trick of checking if it is last iteration
            System.out.print("-");
        }
    }
    System.out.println();
}


问:
RegEx replace second closing tag in a String
I'm trying to replace the second closing tag > in an String Something="

Body:
You could match everything, but use capturing groups, so you can paste everything back in around the XXXX.

String something = "<!-- comm --!><tag titi=\"string1\" toto=\"string2\">";
System.out.println(something.replaceFirst("(^.+?>.+?)>(.*$)", "$1XXXX$2"));

( starts the first capturing group

^ anchors to the start of a line

.+? matches one or more of any character as few times as it has to

> matches '>' literally

) ends the first capturing group

> matches '>' literally again, this is the only thing not in a capturing group

( starts capturing group 2

.* matches 0 or more of any character

$ anchors to the end of the line

$1 refers to the first capturing group (everything before the second '>')

$2 refers to the second capturing group (everything that might come after the second '>')


问:
dplyr filter removing NA when that was not specified
Consider the following data:

```<code>library(tidyverse)
df <- tibble(col1 = c("A", "", NA),
             col2 = 5:7)
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 "A"       5
#> 2 ""        6
#> 3  NA       7
</code>```

I'm trying to filter out blanks from the data frame above with the following code

```<code>df %>% filter(col1 != "")
#> # A tibble: 1 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 A         5
</code>```

Why are NA removed in addition to blanks? I did not include df %>% filter(!is.na(col1)), nor drop_na(), nor na.exclude(), etc. in my filter call, so I wouldn't think the NA row should be filtered out of the data frame.

How do I filter out blanks, but keep the NA? An explanation would be preferred as well. Thank you.

答:
this is the default behavior: R simply does not know if NA == '' is TRUE or FALSE

```<code>NA == ""
[1] NA
</code>```

Therefore the third row is not returned.
If you want to include NA as well there are several workarrounds:

```<code>df %>% filter(coalesce(col1, "x") != "")
df %>% filter(col1 != "" | is.na(col1)
</code>```

Personally, I prefer the first way: coalesce substitutes NA with a default value (here "x") and then checks if the substituted value is equal to "".

Body:
Consider the following data:

library(tidyverse)
df <- tibble(col1 = c("A", "", NA),
             col2 = 5:7)
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 "A"       5
#> 2 ""        6
#> 3  NA       7

I'm trying to filter out blanks from the data frame above with the following code

df %>% filter(col1 != "")
#> # A tibble: 1 x 2
#>   col1   col2
#>   <chr> <int>
#> 1 A         5

Why are NA removed in addition to blanks? I did not include df %>% filter(!is.na(col1)), nor drop_na(), nor na.exclude(), etc. in my filter call, so I wouldn't think the NA row should be filtered out of the data frame.

How do I filter out blanks, but keep the NA? An explanation would be preferred as well. Thank you.

Body:
this is the default behavior: R simply does not know if NA == '' is TRUE or FALSE

NA == ""
[1] NA

Therefore the third row is not returned.
If you want to include NA as well there are several workarrounds:

df %>% filter(coalesce(col1, "x") != "")
df %>% filter(col1 != "" | is.na(col1)

Personally, I prefer the first way: coalesce substitutes NA with a default value (here "x") and then checks if the substituted value is equal to "".


问:
Qt - unresolved overload function type
I am getting the following error when trying to build my app in Qt Creator:

error (line 3): no matching function for call to ‘QGraphicsScene::QGraphicsScene()’

The source for this is simply (file name is gamscene.cpp):

```<code>#include "gamescene.h"

GameScene::GameScene() : QGraphicsScene(parent)
{

}
</code>```

I have googled around and have seen some similar issues but I don't really understand the answers given.

答:
We've derived from the QGraphicsScene class like so

```<code>class ImprintTemplateScene : public QGraphicsScene
{
    Q_OBJECT
public:
    ImprintTemplateScene(QObject *parent = 0);

...
};
</code>```

Notice the parent is a parameter passed to the constructor.  The constructor implementation looks like:

```<code>ImprintTemplateScene::ImprintTemplateScene(QObject *parent)
    :   QGraphicsScene(parent),
        sceneMode(mode_normal),
        editingTextBox(0)
{
}
</code>```

Title: Qt - unresolved overload function type

Body:
I am getting the following error when trying to build my app in Qt Creator:

error (line 3): no matching function for call to ‘QGraphicsScene::QGraphicsScene()’

The source for this is simply (file name is gamscene.cpp):

#include "gamescene.h"

GameScene::GameScene() : QGraphicsScene(parent)
{

}

I have googled around and have seen some similar issues but I don't really understand the answers given.

Body:
We've derived from the QGraphicsScene class like so

class ImprintTemplateScene : public QGraphicsScene
{
    Q_OBJECT
public:
    ImprintTemplateScene(QObject *parent = 0);

...
};

Notice the parent is a parameter passed to the constructor.  The constructor implementation looks like:

ImprintTemplateScene::ImprintTemplateScene(QObject *parent)
    :   QGraphicsScene(parent),
        sceneMode(mode_normal),
        editingTextBox(0)
{
}


问:
How do I send a strings with tab spaces to a website using post requests?
I am trying to read .py files from my machine and post it to my personal website using requests module in python.

Everything is working fine except the indentation.

How do I send tabspaces and multiple new line character with a post request?

答: Encode the entire file to base64 (using the base64 module perhaps), send it as the body of the POST request, and then decode it on the other end. This will take care of all ASCII characters (including tabs) as answered here - Can a Base64 String contain tabs?</p>


问:
Fastest way to whitelist list of words by another set keeping words order
I have list of words like words = ['a', 'spam', 'an', 'eggs', 'the', 'foo', 'and', 'bar'].

And I want to exclude some words (stop-words) defined in another list or set stop_words = ['a', 'an', 'the', 'and'].

What is the fastest way to do that and also keeping the order of original list? I tried to use set() or even SortedSet(). But it still doesn't help, words are still different from original order.

r1 = set(words) - set(stop_words)
r2 = SortedSet(words) - SortedSet(stop_words)
```

<p>Tried iterating one by one, but not sure if it will be quick enough on big lists.</p>

<pre class="lang-py prettyprint-override"><code>r3 = [w for w in words if w not in stop_words]
</code>```

答:
Providing a bit of benchmark with a longer list of words from Shakespeare (length 202651 words) and a vectorized solution:

```<code>text = requests.get('https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt').text

words_list = text.lower().split()
words_array = np.array(words_list)
stop_words = ['a', 'an', 'the', 'and']
set_stopwords = set(stop_words)

def numpy_filter():
    """Taking a Numpy array and returning a filtered array"""
    return words_array[np.isin(words_array,stop_words,invert=True)]

def numpy_list_filter():
    """Taking a Numpy array and returning a filtered list"""
    return words_array[np.isin(words_array,stop_words,invert=True)].tolist()

def list_filter():
    """Iterating over a list filtering by elements included in a list"""
    return [w for w in words_list if w not in stop_words]

def list_set_filter():
    """Iterating over a list filtering by elements included in a set"""
    return [w for w in words_list if w not in set_stopwords]
</code>```

Here are the results with my 2,5 GHz Dual-Core Intel Core i7, in the order in which the functions were defined above:

```<code>12.6 ms ± 378 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

31.6 ms ± 1.27 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

24.1 ms ± 4.98 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

11.7 ms ± 265 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

The fastest option amongst the ones tried is indeed the one suggested by @a_guest. This remains true even if you make the list 100 times larger. As you can see, transforming the stop_words into a set brings a significant performance improvement. Numpy is also pretty fast, but if you need to convert it back into a list at the end, the overhead involved makes it the slowest method amongst the ones tried.

Body:
I have list of words like words = ['a', 'spam', 'an', 'eggs', 'the', 'foo', 'and', 'bar'].

And I want to exclude some words (stop-words) defined in another list or set stop_words = ['a', 'an', 'the', 'and'].

What is the fastest way to do that and also keeping the order of original list? I tried to use set() or even SortedSet(). But it still doesn't help, words are still different from original order.

r1 = set(words) - set(stop_words)
r2 = SortedSet(words) - SortedSet(stop_words)

Tried iterating one by one, but not sure if it will be quick enough on big lists.

r3 = [w for w in words if w not in stop_words]

Body:
Providing a bit of benchmark with a longer list of words from Shakespeare (length 202651 words) and a vectorized solution:

text = requests.get('https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt').text

words_list = text.lower().split()
words_array = np.array(words_list)
stop_words = ['a', 'an', 'the', 'and']
set_stopwords = set(stop_words)

def numpy_filter():
    """Taking a Numpy array and returning a filtered array"""
    return words_array[np.isin(words_array,stop_words,invert=True)]

def numpy_list_filter():
    """Taking a Numpy array and returning a filtered list"""
    return words_array[np.isin(words_array,stop_words,invert=True)].tolist()

def list_filter():
    """Iterating over a list filtering by elements included in a list"""
    return [w for w in words_list if w not in stop_words]

def list_set_filter():
    """Iterating over a list filtering by elements included in a set"""
    return [w for w in words_list if w not in set_stopwords]

Here are the results with my 2,5 GHz Dual-Core Intel Core i7, in the order in which the functions were defined above:

12.6 ms ± 378 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

31.6 ms ± 1.27 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

24.1 ms ± 4.98 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

11.7 ms ± 265 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The fastest option amongst the ones tried is indeed the one suggested by @a_guest. This remains true even if you make the list 100 times larger. As you can see, transforming the stop_words into a set brings a significant performance improvement. Numpy is also pretty fast, but if you need to convert it back into a list at the end, the overhead involved makes it the slowest method amongst the ones tried.


问:
Handling firebase auth with react-router
I am building a React + Redux + Firebase app with webpack and am trying to figure out the best way to handle protected routes and redirects. I have tried using onEnter() with setTimeout() like many examples show, but it still ended up flashing the alternate component before redirecting.

Here is what I currently have, and I am trying to come up with a more elegant solution. This mostly works, but an example of when it fails is if I am on /profile and navigate to / in the browser. It seems that because firebase.auth() needs to initialize again, I get a flash of the HomePage component before it switches to Profile.

Firebase is initialized in firebaseClientConfig and I am passing firebase.auth() in to routes.

```<code>import { auth } from './firebaseClientConfig';

...

export default (
<Route path="/" component={App}>
 <IndexRoute
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (!user) {
        return require.ensure([], require => {
          cb(null, require('./components/HomePage').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      }
    });
  }}
/>
<Route
  path="/profile"
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Login/Login').default);
        });
      }
    });
  }}
/>
</Route>
);
</code>```

Does anyone have a better way of doing this?

答:
I know is kind of late, but this might help others: You can find a slightly different approach here (still with a private route so kind of similar to vhflat but I find it a little more clear and easy to implement).

Basically, in your private route you just

```<code>import { useSelector } from "react-redux";
</code>```

and

```<code>import { isLoaded } from 'react-redux-firebase'
</code>```

After that you get the auth like this

```<code>const auth = useSelector( state => state.firebase.auth );
</code>```

Then if the isLoaded( auth ) is not true (so the auth state is not loaded) you can redirect to a loading page or just return a <React.Fragment></React.Fragment> if you don't want.

In the end if on your return, you can check if !isEmpty( auth ), and if that is true return the children component, otherwise Redirect to the login page or any other page you prefer.

Body:
I am building a React + Redux + Firebase app with webpack and am trying to figure out the best way to handle protected routes and redirects. I have tried using onEnter() with setTimeout() like many examples show, but it still ended up flashing the alternate component before redirecting.

Here is what I currently have, and I am trying to come up with a more elegant solution. This mostly works, but an example of when it fails is if I am on /profile and navigate to / in the browser. It seems that because firebase.auth() needs to initialize again, I get a flash of the HomePage component before it switches to Profile.

Firebase is initialized in firebaseClientConfig and I am passing firebase.auth() in to routes.

import { auth } from './firebaseClientConfig';

...

export default (
<Route path="/" component={App}>
 <IndexRoute
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (!user) {
        return require.ensure([], require => {
          cb(null, require('./components/HomePage').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      }
    });
  }}
/>
<Route
  path="/profile"
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Login/Login').default);
        });
      }
    });
  }}
/>
</Route>
);

Does anyone have a better way of doing this?

Body:
I know is kind of late, but this might help others: You can find a slightly different approach here (still with a private route so kind of similar to vhflat but I find it a little more clear and easy to implement).

Basically, in your private route you just

import { useSelector } from "react-redux";

and

import { isLoaded } from 'react-redux-firebase'

After that you get the auth like this

const auth = useSelector( state => state.firebase.auth );

Then if the isLoaded( auth ) is not true (so the auth state is not loaded) you can redirect to a loading page or just return a <React.Fragment></React.Fragment> if you don't want.

In the end if on your return, you can check if !isEmpty( auth ), and if that is true return the children component, otherwise Redirect to the login page or any other page you prefer.


问:
Jmeter stop the current iteration issue
how to stop current iteration using jmeter and move to next iteration using beanshell script.
(Without using test action element)

I tried ctx.setRestartNextLoop(true) but this is not working.

JMeter version: 5.2.1

答:
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for any form of scripting

If for some reason (I fail to see any valid reason though) you still want to do this using JSR223 Sampler instead of Flow Control Action sampler - the relevant code would be:

```<code>SampleResult.setIgnore()
ctx.setTestLogicalAction(org.apache.jmeter.threads.JMeterContext.TestLogicalAction.START_NEXT_ITERATION_OF_CURRENT_LOOP)
</code>```

More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Title: Jmeter stop the current iteration issue

Body:
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for any form of scripting

If for some reason (I fail to see any valid reason though) you still want to do this using JSR223 Sampler instead of Flow Control Action sampler - the relevant code would be:

SampleResult.setIgnore()
ctx.setTestLogicalAction(org.apache.jmeter.threads.JMeterContext.TestLogicalAction.START_NEXT_ITERATION_OF_CURRENT_LOOP)

More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It


问:
Customize only the button that was clicked
I developed two columns, both with several buttons. The goal is to click on each button, change the background color and the font color of that button.

At an early stage you have all the buttons in their natural state. By clicking on a button in the left column (A, B, C) I want only that button to change the background color and the font color, the same with the buttons in the right column.

Is there also a way that whenever you click on a button in the left column, if in the right column any button has a background color (has already been clicked) it will return to its original state?

I tried to use jquery and work with ID's and class's, but it doesn't seem the most correct way.

Can someone help me?

DEMO

HTML

```<code><div class="row">
    <div class="col">
        <div *ngFor="let item of Groups">
            <button (click)="Change(0,item)" class="btnGrup">{{item.name}}</button>
        </div>
    </div>
    <div class="col">
        <div *ngFor="let item of Words">
            <button (click)="Change(1,item)" class="btn2">{{item.name}}</button>
        </div>
    </div>
</div>
</code>```

TS

```<code> Change(index, data) {
    let self = this;
    switch (index) {
      case 0:
        // $(".btnGrup").css({ "background-color": "#f7f7f9", "color": "#BCBCCB" });
        // $(".btnGrup").css({ "background-color": "rgba(73, 129, 194, 0.1)", "color": "rgba(73, 129, 194, 1)" });
        break;
      case 1:
        //      $(".btn2").css({ "background-color": "#f7f7f9", "color": "#BCBCCB" });
        // $(".btn2").css({ "background-color": "rgba(73, 129, 194, 0.1)", "color": "rgba(73, 129, 194, 1)" });
        break;
    }
  }
</code>```

答:
just add a new property to your group, e.g. called it "check"

```<code>Groups=[{
  id:1,
  name:"A",
  check:false
},
{
  id:2,
  name:"B",
  check:false
},
...
]
</code>```

Create two class

```<code>.class1
  {
     background-color: #f7f7f9;
   color: #BCBCCB
   }
.class2
{
  background-color: rgba(73, 129, 194, 0.1);
  color: rgba(73, 129, 194, 1)
}
</code>```

And use ngClass

```<code><button (click)="item.check=!item.check"
         class="btnGrup"
         [ngClass]="{'class1':item.check,'class2':!item.check}"
       >{{item.name}}</button>
</code>```

If you want only one button you needn't add a new property to your "groups", only need two variables

```<code>buttonSelect1=-1
buttonSelect2=-1
</code>```

And use

```<code><div *ngFor="let item of Groups;let i=index">
            <button (click)="buttonSelect1=i"
               class="btnGrup"
               [ngClass]="{'class1':buttonSelect1==i,'class2':buttonSelect1!=i}"
             >{{item.name}}</button>
</div>
</code>```

Body:
I developed two columns, both with several buttons. The goal is to click on each button, change the background color and the font color of that button.

At an early stage you have all the buttons in their natural state. By clicking on a button in the left column (A, B, C) I want only that button to change the background color and the font color, the same with the buttons in the right column.

Is there also a way that whenever you click on a button in the left column, if in the right column any button has a background color (has already been clicked) it will return to its original state?

I tried to use jquery and work with ID's and class's, but it doesn't seem the most correct way.

Can someone help me?

DEMO

HTML

            <button (click)="Change(0,item)" class="btnGrup">{{item.name}}</button>

            <button (click)="Change(1,item)" class="btn2">{{item.name}}</button>

TS

 Change(index, data) {
    let self = this;
    switch (index) {
      case 0:
        // $(".btnGrup").css({ "background-color": "#f7f7f9", "color": "#BCBCCB" });
        // $(".btnGrup").css({ "background-color": "rgba(73, 129, 194, 0.1)", "color": "rgba(73, 129, 194, 1)" });
        break;
      case 1:
        //      $(".btn2").css({ "background-color": "#f7f7f9", "color": "#BCBCCB" });
        // $(".btn2").css({ "background-color": "rgba(73, 129, 194, 0.1)", "color": "rgba(73, 129, 194, 1)" });
        break;
    }
  }

Body:
just add a new property to your group, e.g. called it "check"

Groups=[{
  id:1,
  name:"A",
  check:false
},
{
  id:2,
  name:"B",
  check:false
},
...
]

Create two class

.class1
  {
     background-color: #f7f7f9;
   color: #BCBCCB
   }
.class2
{
  background-color: rgba(73, 129, 194, 0.1);
  color: rgba(73, 129, 194, 1)
}

And use ngClass

<button (click)="item.check=!item.check"
         class="btnGrup"
         [ngClass]="{'class1':item.check,'class2':!item.check}"
       >{{item.name}}</button>

If you want only one button you needn't add a new property to your "groups", only need two variables

buttonSelect1=-1
buttonSelect2=-1

And use

<div *ngFor="let item of Groups;let i=index">
            <button (click)="buttonSelect1=i"
               class="btnGrup"
               [ngClass]="{'class1':buttonSelect1==i,'class2':buttonSelect1!=i}"
             >{{item.name}}</button>
</div>


问:
pytest: import file mismatch with added __init__.py files to test directories
Have project directory like:

```<code>/beta
    /task one
        __init__.py
        test_solution.py
    /task two
        __init__.py
        test_solution.py
</code>```

when try to collect tests via python3 -m pytest --collect-only i'm getting error:

```<code>import file mismatch:
imported module 'test_solution' has this __file__ attribute:
/Applications/PyCharm
CE.app/Contents/bin/https:/github.com/vmred/untitled/beta/task one/test_solution.py
which is not the same as the test file we want to collect:
/Applications/PyCharm
CE.app/Contents/bin/https:/github.com/vmred/untitled/beta/task
two/test_solution.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules
</code>```

__pycache__ cleared several times, but not hepled.

What could be the issue in ?
Also tried to add python_classes=test_solution.py to pytest.ini, but also not helped.

答:
I had the same error when my directory names contained hyphens. E.g.:

```<code>/beta
    /task-one
        __init__.py
        test_solution.py
    /task-two
        __init__.py
        test_solution.py
</code>```

Converting the hyphens to underscores solved the problem.

Body:
Have project directory like:

/beta
    /task one
        __init__.py
        test_solution.py
    /task two
        __init__.py
        test_solution.py

when try to collect tests via python3 -m pytest --collect-only i'm getting error:

import file mismatch:
imported module 'test_solution' has this __file__ attribute:
/Applications/PyCharm
CE.app/Contents/bin/https:/github.com/vmred/untitled/beta/task one/test_solution.py
which is not the same as the test file we want to collect:
/Applications/PyCharm
CE.app/Contents/bin/https:/github.com/vmred/untitled/beta/task
two/test_solution.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

__pycache__ cleared several times, but not hepled.

What could be the issue in ?
Also tried to add python_classes=test_solution.py to pytest.ini, but also not helped.

Body:
I had the same error when my directory names contained hyphens. E.g.:

/beta
    /task-one
        __init__.py
        test_solution.py
    /task-two
        __init__.py
        test_solution.py

Converting the hyphens to underscores solved the problem.


问:
mkdir() or mkdirs() not working on Android API 26
Following code is working with other APIs but 26

```<code>public static boolean cretaeDir()
{
    String dir = Environment.getExternalStoragePublicDirectory(Environment.MEDIA_SHARED).getAbsolutePath();
    java.io.File folder = new java.io.File(dir + "/SomeFolderName");
    if (!folder.exists()) {
        try{
            if(folder.mkdir()) {
                Log.e("Creating Folder", "Success");
                return true;
            } else {
                Log.e("Creating Folder", "Failed");
                return false;
            }
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }else{
        return true;
    }
}
</code>```

Before some one ask, Yeah the permissions have been granted and also uses-permission present in the Manifest file.

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package.name">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="com.android.vending.BILLING" />

<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application/>
</code>```

Test Device is Samsung S8, Running 8.0.0

答:
ok, so this worked for me.

RequestPermission Methods, when asking for permission, ask WRITE_EXTERNAL_STORAGE before anything else. Try it...

MainActivity.kt

```<code>// First permission to be asked
requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
// Then all other permissions
</code>```

This is working for all API inclusive & levels above 26.
TBH, I don't know how, but it working.

Body:
Following code is working with other APIs but 26

public static boolean cretaeDir()
{
    String dir = Environment.getExternalStoragePublicDirectory(Environment.MEDIA_SHARED).getAbsolutePath();
    java.io.File folder = new java.io.File(dir + "/SomeFolderName");
    if (!folder.exists()) {
        try{
            if(folder.mkdir()) {
                Log.e("Creating Folder", "Success");
                return true;
            } else {
                Log.e("Creating Folder", "Failed");
                return false;
            }
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }else{
        return true;
    }
}

Before some one ask, Yeah the permissions have been granted and also uses-permission present in the Manifest file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package.name">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="com.android.vending.BILLING" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application/>

Test Device is Samsung S8, Running 8.0.0

Body:
ok, so this worked for me.

RequestPermission Methods, when asking for permission, ask WRITE_EXTERNAL_STORAGE before anything else. Try it...

MainActivity.kt

// First permission to be asked
requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
// Then all other permissions

This is working for all API inclusive & levels above 26.
TBH, I don't know how, but it working.


问:
ML wrong prediction on Japan Crossword puzzle
I’m trying to study machine learning in hands-on way. I found exercise for myself to create neural network that solves “Japan crosswords” for fixed size images (128*128).

Very simple example (4*4) demonstrates the conception: black & white picture encoded by top and left matrices. Number in matrix means continues length of black line. Easy to prove left and top matrix have dimension at max (N*(N/2)) and ((N/2)*N) correspondingly.

I have a python generator that creates random b&w images and 2 reduced matrices. Top and left matrices are fed as input (left is transposed to match top) and b&w as an expected output. Input is treated as 3-dim (128 * 64 * 2) where 2 – is top and left correspondingly.
Following is my current topology that try to build function (128 * 64 * 2) -> (128, 128, 1)

Model: "model"

Layer (type)                 Output Shape              Param #

interlaced_reduce (InputLaye [(None, 128, 64, 2)]      0

small_conv (Conv2D)          (None, 128, 64, 32)       288

leaky_re_lu (LeakyReLU)      (None, 128, 64, 32)       0

medium_conv (Conv2D)         (None, 128, 64, 64)       8256

leaky_re_lu_1 (LeakyReLU)    (None, 128, 64, 64)       0

large_conv (Conv2D)          (None, 128, 64, 128)      32896

leaky_re_lu_2 (LeakyReLU)    (None, 128, 64, 128)      0

up_sampling2d (UpSampling2D) (None, 128, 128, 128)     0

dropout (Dropout)            (None, 128, 128, 128)     0

dense (Dense)                (None, 128, 128, 1)       129

Total params: 41,569
  Trainable params: 41,569
  Non-trainable params: 0

After train on 50 images I got the following statistic (please note, I tried to normalize input matrices to [0,1] without any success, current statistic demonstrate non-normalized case) :

...
  Epoch 50/50 2/2 [==============================] - 1s 687ms/step -loss: 18427.2871 - mae: 124.9277

Then prediction produces following:

You can see left – expected random image and right – result of prediction. In prediction I intentionally use grey-scaled image to understand how close my result to target. But as you can see – the prediction is far from expected and is close to source form of top/left reduce matrices.
So my questions:

1) What layers I’m missing?

2) What should be improved in existing topology?

p.s. this is cross post from Cross Validated Stackexchange, because nobody even viewed question that site

答:
So it's hard to say what model would work best without training and testing the actual model, but from the results you've gotten so far here's a few options you could try.

Try adding a fully connected hidden layer

From the model you posted, it seems that you have a few convolution layers, followed by an up-sampling and dropout layer, and finally a single dense layer for your output nodes. Potentially, adding additional dense layers (for e.g. 128 or more or less nodes) before your final output layer might help. While the multiple convolution layers help the neural net to build up a sort of hierarchical understanding of the image, the hypothesis class might not be complex enough. Adding one or more dense layers might help with this.

Try using a multilayer perceptron

Convolution layers are often used to process images because they help build up a hierarchical understanding of the image that is somewhat scale/shift/rotation invariant. However, considering the problem that you're solving, a global understanding of the input might be more beneficial than identifying shift-invariant features.

As such, one possible option would be to remove the convolution layers and to use a multilayer perceptron (MLP).

Let us think of the input as two matrices of numbers, and the output is a matrix of 1s and 0s that correspond to 'black' and 'white'. You could then try a model with the following layers:

A Flatten layer that takes in your two reduced matrices as inputs and flattens
them

A hidden dense layer, maybe with something like 128 nodes and relu activation. You should experiment with the number of layers, nodes, and activation.

An output dense layer with 16384 (128x128) nodes. You could apply a softmax activation to this layer which could help the optimiser during the training process. Then, when creating your final image, set values < 0.5 to 0 and values >= 0.5 to 1, and reshape and reformat the matrix into a square image.

Of course, no guarantees that an MLP would work well, but if often does especially when given sufficient amounts of data (perhaps in the 1000s or more number of training examples).

Try using a deterministic algorithm

Looking at the structure of this problem, it seems that it could be solved more appropriately with a deterministic algorithm, which would fall under more the branch of traditional artificial intelligence rather than deep learning. This is also another potential route to explore.


问:
Asynchronous function not terminating
I am writing an async function async_create_user, used for my firebase HTTPS function create_user of the form in index.js.

index.js

```<code>exports.create_user = functions.https.onCall(async_create_user);
</code>```

I am testing them all in a single file user.js like this, and running node user.js
The code gets the expected behaviour of creating the User documents in my database, but my intention for this function is also to terminate so that I can test it with a sequence of other functions. May I know if there is an implementation to let it terminate.

```<code>const { admin, db } = require("../util/admin");
//const db = admin.firestore();
//const admin = require('firebase-admin');
//admin.initializeApp(config);

const config = require("../util/config");
const { uuid } = require("uuidv4");

const {
  success_response,
  error_response
} = require("../util/validators");

const firebase = require("firebase");
firebase.initializeApp(config);

const {
  validateSignupData,
  validateLoginData,
  reduceUserDetails,
} = require("../util/validators");

exports.async_create_user = async function(data, context) {
  // Perform Authentication Checks
  try {
    const userRecord = await admin.auth().createUser({
      displayName: data.displayName,
      email: data.email,
      emailVerified: true,
      password: data.password,
      disabled: false
    });

    await admin.auth().setCustomUserClaims(userRecord.uid, {user_basic: true})

    //data required for the personal?
    const PrivateUser = {
      display_name: data.displayName,
      email: data.email,
      notification_ids: [],
      saved_posts: [],
      last_updated: admin.firestore.FieldValue.serverTimestamp()
    };

    const noImg = "no-img.png";

    //sets default profile image to be the empty image
    const PublicUser = {
      profile_image:
        {
          url: "some url",
          uid: userRecord.uid
        }
    }

    await db
      .collection("users_private")
      .doc(userRecord.uid)
      .set(PrivateUser);

    await db
      .collection("users_public")
      .doc(userRecord.uid)
      .set(PublicUser);

    console.log(userRecord.uid);
    return success_response();

  } catch (error) {
    console.log("Error in creation of user account", error);
    return error_response(error);
  }
}

const mockUser =     {
  displayName: "Mallory",
  email: "mallory@example.org",
  password: "123456",

  disabled: false,
  emailVerified: true
}

exports.async_create_user(mockUser);
</code>```

答:
I have written a library called rubico that removes a lot of cruft surrounding Promises. The result is simpler code; rubico handles asynchronous termination so you don't have to.

const { pipe, fork, get, tap, tryCatch } = require('rubico')

const setCustomUserClaims = uid =>
  admin.auth().setCustomUserClaims(uid, { user_basic: true })

const getServerTimestamp = () => admin.firestore.FieldValue.serverTimestamp()

const createPrivateUser = ({ uid, PrivateUser }) =>
  db.collection('users_private').doc(uid).set(PrivateUser)

const createPublicUser = ({ uid, PublicUser }) =>
  db.collection('users_public').doc(uid).set(PrivateUser)

const createUser = pipe([
  fork({
    displayName: get('displayName'), // input => input.displayName
    email: get('email'), // input => input.email
    emailVerified: () => true, // () => true
    password: get('password'), // input => input.password
    disabled: () => false, // () => false
  }), // { displayName, email, password } => { displayName, email, emailVerified, password, disabled } === userPreRecord
  admin.auth().createUser, // userPreRecord => userRecord
  tap(pipe([get('uid'), setCustomUserClaims])), // setCustomUserClaims with uid but don't care about the return
  fork({
    uid: get('uid'), // userRecord => userRecord.uid
    PrivateUser: fork({
      display_name: get('displayName'), // userRecord => userRecord.displayName
      email: get('email'), // userRecord => userRecord.email
      notification_ids: () => [],
      saved_posts: () => [],
      last_updated: getServerTimestamp,
    }),
    PublicUser: fork({
      profile_image: fork({
        url: () => 'no-img.png',
        uid: get('uid'), // userRecord => userRecord.uid
      }),
    }),
  }),
  tap(fork([ // tap: run input through the following fork of functions and discard return.
    createPrivateUser, // userRecord => createPrivateUser(userRecord)
    createPublicUser, // userRecord => createPublicUser(userRecord)
  ])),
])

exports.async_create_user = tryCatch( // try pipe([createUser, success_response]), catch with err => {...}
  pipe([createUser, success_response]),
  err => {
    console.log("Error in creation of user account", err);
    error_response(err);
  },
)
```

I've included comments in my example, but to really make sense of the code above, I recommend you read the intuition, then the docs

Title: Asynchronous function not terminating

Body:
I am writing an async function async_create_user, used for my firebase HTTPS function create_user of the form in index.js.

index.js

exports.create_user = functions.https.onCall(async_create_user);

I am testing them all in a single file user.js like this, and running node user.js
The code gets the expected behaviour of creating the User documents in my database, but my intention for this function is also to terminate so that I can test it with a sequence of other functions. May I know if there is an implementation to let it terminate.

const { admin, db } = require("../util/admin");
//const db = admin.firestore();
//const admin = require('firebase-admin');
//admin.initializeApp(config);

const config = require("../util/config");
const { uuid } = require("uuidv4");

const {
  success_response,
  error_response
} = require("../util/validators");

const firebase = require("firebase");
firebase.initializeApp(config);

const {
  validateSignupData,
  validateLoginData,
  reduceUserDetails,
} = require("../util/validators");

exports.async_create_user = async function(data, context) {
  // Perform Authentication Checks
  try {
    const userRecord = await admin.auth().createUser({
      displayName: data.displayName,
      email: data.email,
      emailVerified: true,
      password: data.password,
      disabled: false
    });

    await admin.auth().setCustomUserClaims(userRecord.uid, {user_basic: true})

    //data required for the personal?
    const PrivateUser = {
      display_name: data.displayName,
      email: data.email,
      notification_ids: [],
      saved_posts: [],
      last_updated: admin.firestore.FieldValue.serverTimestamp()
    };

    const noImg = "no-img.png";

    //sets default profile image to be the empty image
    const PublicUser = {
      profile_image:
        {
          url: "some url",
          uid: userRecord.uid
        }
    }

    await db
      .collection("users_private")
      .doc(userRecord.uid)
      .set(PrivateUser);

    await db
      .collection("users_public")
      .doc(userRecord.uid)
      .set(PublicUser);

    console.log(userRecord.uid);
    return success_response();

  } catch (error) {
    console.log("Error in creation of user account", error);
    return error_response(error);
  }
}

const mockUser =     {
  displayName: "Mallory",
  email: "mallory@example.org",
  password: "123456",

  disabled: false,
  emailVerified: true
}

exports.async_create_user(mockUser);

Body:
I have written a library called rubico that removes a lot of cruft surrounding Promises. The result is simpler code; rubico handles asynchronous termination so you don't have to.

const { pipe, fork, get, tap, tryCatch } = require('rubico')

const setCustomUserClaims = uid =>
  admin.auth().setCustomUserClaims(uid, { user_basic: true })

const getServerTimestamp = () => admin.firestore.FieldValue.serverTimestamp()

const createPrivateUser = ({ uid, PrivateUser }) =>
  db.collection('users_private').doc(uid).set(PrivateUser)

const createPublicUser = ({ uid, PublicUser }) =>
  db.collection('users_public').doc(uid).set(PrivateUser)

const createUser = pipe([
  fork({
    displayName: get('displayName'), // input => input.displayName
    email: get('email'), // input => input.email
    emailVerified: () => true, // () => true
    password: get('password'), // input => input.password
    disabled: () => false, // () => false
  }), // { displayName, email, password } => { displayName, email, emailVerified, password, disabled } === userPreRecord
  admin.auth().createUser, // userPreRecord => userRecord
  tap(pipe([get('uid'), setCustomUserClaims])), // setCustomUserClaims with uid but don't care about the return
  fork({
    uid: get('uid'), // userRecord => userRecord.uid
    PrivateUser: fork({
      display_name: get('displayName'), // userRecord => userRecord.displayName
      email: get('email'), // userRecord => userRecord.email
      notification_ids: () => [],
      saved_posts: () => [],
      last_updated: getServerTimestamp,
    }),
    PublicUser: fork({
      profile_image: fork({
        url: () => 'no-img.png',
        uid: get('uid'), // userRecord => userRecord.uid
      }),
    }),
  }),
  tap(fork([ // tap: run input through the following fork of functions and discard return.
    createPrivateUser, // userRecord => createPrivateUser(userRecord)
    createPublicUser, // userRecord => createPublicUser(userRecord)
  ])),
])

exports.async_create_user = tryCatch( // try pipe([createUser, success_response]), catch with err => {...}
  pipe([createUser, success_response]),
  err => {
    console.log("Error in creation of user account", err);
    error_response(err);
  },
)

I've included comments in my example, but to really make sense of the code above, I recommend you read the intuition, then the docs


问:
Intalling timbral_models on Raspeberry Pi 3+
I have been trying to install timbral_model on my Raspberry Pi (pip3 install timbral_models) without avail. I can't figure out the errors. The following screenshot provides a better overview.

I would be grateful to anyone for assistance.

Thank you in advance for your support.

答:
You might have to install the offending dependencies manually. From the screenshots that you have shared I see that Cython, sklearn and llvmlite are causing the issues. you can install these dependencies by running :

```<code>pip install sklearn
pip install llvmlite
pip install Cython
</code>```

As I cannot see the entire error message, I can only suggest these fixes. You might also have to manually install any other offending packages.

Body:
You might have to install the offending dependencies manually. From the screenshots that you have shared I see that Cython, sklearn and llvmlite are causing the issues. you can install these dependencies by running :

pip install sklearn
pip install llvmlite
pip install Cython

As I cannot see the entire error message, I can only suggest these fixes. You might also have to manually install any other offending packages.


问:
CS50 Speller.c Issue
I have some issues with the CS50 speller task in problem set 5. For those who are not familiar with this problem, basically my program works as a spell checker (you insert a dictionary and a text file and the program returns all misspelled words). Our task was to write five functions (check, hash, load, size, unload). The check function checks if a word is in set dictionary. Hash basically returns a numerical index of the hash table I used to organise the words in based on the input of a word from the text. The load function basically loads all the words from the dictionary file into the hash table. The size function returns the size of the dictionary and finally the unload functions frees all memory allocated to my program.
However, when I test my program with check50 there is apparently a fault with the freeing of memory. However, I don't know where this issue could be?

Thanks in advance!

```<code> // Implements a dictionary's functionality

 #include <stdbool.h>
 #include <stdio.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
 #include <stdlib.h>

 #include "dictionary.h"

 // Represents a node in a hash table
 typedef struct node
 {
char word[LENGTH + 1];
struct node *next;
 }
 node;

 // Number of buckets in hash table
 const unsigned int N = 26;

 // Hash table
 node *table[N];

 // Returns true if word is in dictionary else false
bool check(const char *word)
{
int x = hash(word);
for (node *temp = table[x]; temp != NULL; temp = temp->next)
{
    if (strcasecmp(word, temp->word) == 0)
    {
        return true;
    }
}
return false;

}

// Hashes word to a number
unsigned int hash(const char *word)
{
char s = word[0];

if(word[0] < 97)
{
    s = tolower(word[0]);
}
int index = s - 97;

return index;

}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// TODO
FILE *file = fopen(dictionary, "r");

if (file == NULL)
{
    printf("Could not open dictionary.\n");
    return false;
}

char theword[45];

while (fscanf(file, "%s", theword) != EOF)
{
    node *n = malloc(sizeof(node));

    if (n == NULL)
    {
        return false;
    }

    int wordlength = strlen(theword);

    int x = hash(theword);

    char tempword[45];

    if (table[x] == NULL)
    {
        for (int j = 0; j < wordlength; j++)
        {
            n->word[j] = theword[j];
        }

        n->next = NULL;

        table[x] = n;
    }

    for (node *temp = table[x]; temp != NULL; temp = temp->next)
    {
        node *temp2 = temp->next;

        if (temp2 == NULL)
        {
            for (int k = 0; k < strlen(theword); k++)
            {
                n->word[k] = theword[k];
            }
            temp->next = n;

            n->next = NULL;
        }
    }
}
return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
int count = 0;

for (int i = 0; i < N; i++)
{
    for (node *temp = table[i]; temp != NULL; temp = temp->next)
    {
        count++;
    }
}
return count;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for (int i = 0; i < N; i++)
{
    node *temp = table[i];

    while (temp != NULL)
    {
        node *temp2 = temp->next;
        free(temp);
        temp = temp2;
    }
}
return true;
}
</code>```

答:
The memory leak is caused by not closing a FILE pointer, but your code has another issue that writes to the outside of a memory space. The following is the error message. Here is the [link] to debug and reproduce this error. </p>

```<code>  Memory access warning: memory spaces are not freed; continue execution.
  # 1 memory space is allocated at
  #    file:/musl-1.1.10/src/stdio/__fdopen.c::20, 10
  # total 1164 bytes
  #

  Memory access error: writing to the outside of a memory space; abort execution.
  # Writing 1 bytes to 0xffefc609 will clobber other memory-spaces.
  #
  # The memory-space-to-be-written (start:0xffefc5dc, size:45 bytes) is bound to 'theword' at
  #    file:/dictionary.c::57, 8
  #
  #  0xffefc5dc               0xffefc608
  #  +------------------------------+
  #  |the memory-space-to-be-written|......
  #  +------------------------------+
  #                                  ^~~~~~~~~~
  #        the write starts at 0xffefc609 that is right after the memory-space end.
  #
  # Stack trace (most recent call first) of the write.
  # [0]  file:/musl-1.1.10/src/stdio/vfscanf.c::271, 12
  # [1]  file:/musl-1.1.10/src/stdio/fscanf.c::28, 8
  # [2]  file:/dictionary.c::59, 10
  # [3]  file:/speller.c::40, 19
  # [4]  [libc-start-main]
Segmentation fault
</code>```

Title: CS50 Speller.c Issue

Body:
I have some issues with the CS50 speller task in problem set 5. For those who are not familiar with this problem, basically my program works as a spell checker (you insert a dictionary and a text file and the program returns all misspelled words). Our task was to write five functions (check, hash, load, size, unload). The check function checks if a word is in set dictionary. Hash basically returns a numerical index of the hash table I used to organise the words in based on the input of a word from the text. The load function basically loads all the words from the dictionary file into the hash table. The size function returns the size of the dictionary and finally the unload functions frees all memory allocated to my program.
However, when I test my program with check50 there is apparently a fault with the freeing of memory. However, I don't know where this issue could be?

Thanks in advance!

 // Implements a dictionary's functionality

 #include <stdbool.h>
 #include <stdio.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
 #include <stdlib.h>

 #include "dictionary.h"

 // Represents a node in a hash table
 typedef struct node
 {
char word[LENGTH + 1];
struct node *next;
 }
 node;

 // Number of buckets in hash table
 const unsigned int N = 26;

 // Hash table
 node *table[N];

 // Returns true if word is in dictionary else false
bool check(const char *word)
{
int x = hash(word);
for (node *temp = table[x]; temp != NULL; temp = temp->next)
{
    if (strcasecmp(word, temp->word) == 0)
    {
        return true;
    }
}
return false;

}

// Hashes word to a number
unsigned int hash(const char *word)
{
char s = word[0];

if(word[0] < 97)
{
    s = tolower(word[0]);
}
int index = s - 97;

return index;

}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// TODO
FILE *file = fopen(dictionary, "r");

if (file == NULL)
{
    printf("Could not open dictionary.\n");
    return false;
}

char theword[45];

while (fscanf(file, "%s", theword) != EOF)
{
    node *n = malloc(sizeof(node));

    if (n == NULL)
    {
        return false;
    }

    int wordlength = strlen(theword);

    int x = hash(theword);

    char tempword[45];

    if (table[x] == NULL)
    {
        for (int j = 0; j < wordlength; j++)
        {
            n->word[j] = theword[j];
        }

        n->next = NULL;

        table[x] = n;
    }

    for (node *temp = table[x]; temp != NULL; temp = temp->next)
    {
        node *temp2 = temp->next;

        if (temp2 == NULL)
        {
            for (int k = 0; k < strlen(theword); k++)
            {
                n->word[k] = theword[k];
            }
            temp->next = n;

            n->next = NULL;
        }
    }
}
return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
int count = 0;

for (int i = 0; i < N; i++)
{
    for (node *temp = table[i]; temp != NULL; temp = temp->next)
    {
        count++;
    }
}
return count;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for (int i = 0; i < N; i++)
{
    node *temp = table[i];

    while (temp != NULL)
    {
        node *temp2 = temp->next;
        free(temp);
        temp = temp2;
    }
}
return true;
}

Body:
The memory leak is caused by not closing a FILE pointer, but your code has another issue that writes to the outside of a memory space. The following is the error message. Here is the [link] to debug and reproduce this error.

  Memory access warning: memory spaces are not freed; continue execution.
  # 1 memory space is allocated at
  #    file:/musl-1.1.10/src/stdio/__fdopen.c::20, 10
  # total 1164 bytes
  #

  Memory access error: writing to the outside of a memory space; abort execution.
  # Writing 1 bytes to 0xffefc609 will clobber other memory-spaces.
  #
  # The memory-space-to-be-written (start:0xffefc5dc, size:45 bytes) is bound to 'theword' at
  #    file:/dictionary.c::57, 8
  #
  #  0xffefc5dc               0xffefc608
  #  +------------------------------+
  #  |the memory-space-to-be-written|......
  #  +------------------------------+
  #                                  ^~~~~~~~~~
  #        the write starts at 0xffefc609 that is right after the memory-space end.
  #
  # Stack trace (most recent call first) of the write.
  # [0]  file:/musl-1.1.10/src/stdio/vfscanf.c::271, 12
  # [1]  file:/musl-1.1.10/src/stdio/fscanf.c::28, 8
  # [2]  file:/dictionary.c::59, 10
  # [3]  file:/speller.c::40, 19
  # [4]  [libc-start-main]
Segmentation fault