问:
Convert a 3d text rotation javascript file to angular component specific typescript file
I have a javascript file for rotating a text in 3d format to be converted to angular component specific typescript file. The codepen for the same is - https://codepen.io/jouanmarcel/pen/wxdqNq

I am also providing my angular files :

index.html

```<code><!doctype html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>RotateText</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css" crossorigin="anonymous">
 </head>
 <body>
  <app-root></app-root>
 </body>
</html>
</code>```

styles.css

```<code>* {
margin: 0px !important;
padding: 0px !important;
box-sizing: border-box !important;
}

body {
font-family: "Roboto Mono" !important;
font-size: 50px !important;
padding: 50px 0 0 100px !important;
display: flex !important;
align-items: stretch !important;
flex-direction: column !important;
font-weight: 700 !important;
color: #fff !important;
background-image: radial-gradient(#e85e3c, #7c1717) !important;
background-repeat: no-repeat !important;
height: 100vh !important;
}
</code>```

app.component.html

```<code><router-outlet></router-outlet>
</code>```

landing.component.html

```<code><div class="t3xts t3xt-1">NO!</div>
<div class="t3xts t3xt-2">THIS IS</div>
<div class="t3xts t3xt-3">PATRICK!</div><a class="ref" href="https://jouanmarcel.com" target="_blank"> Jouan Marcel</a>
</code>```

landing.component.css

```<code>.t3xts {
line-height: 1 !important;
position: relative !important;
perspective: 1000px !important;
text-transform: uppercase !important;
}

.t3xt {
transform-style: preserve-3d !important;
position: absolute !important;
top: 0 !important;
text-transform: uppercase !important;
}

.t3xt-out {
animation: text-out .5s ease !important;
}

.t3xt-in {
animation: text-in .5s ease !important;
}

@keyframes text-out {
to {
    transform: rotateX(90deg) !important;
    opacity: 0 !important;
}
}

@keyframes text-in {
from {
    opacity: 0 !important;
    transform: rotateX(-90deg) !important;
}

to {
    transform: rotateX(0deg) !important;
    opacity: 1 !important;
}
}

.ref {
background-color: #000 !important;
border-radius: 3px !important;
padding: 5px 8px !important;
position: absolute !important;
font-size: 16px !important;
bottom: 10px !important;
right: 10px !important;
color: #fff !important;
font-weight: 300 !important;
font-family: sans-serif !important;
text-decoration: none !important;
}

.ref::first-letter {
font-size: 12px !important;
}
</code>```

landing.component.ts (The file which is to contain the converted javascript code)

```<code>import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-landing',
 templateUrl: './landing.component.html',
 styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

constructor() { }

ngOnInit() {
}

n3xt(text, element){
var sample = document.querySelector(element);
if (sample.dataset.animating === 'true') return;
var sampleH = 50; // will keep it fixed, otherwise sample.offsetHeight

var sampleT = sample.textContent; // old text

var sampleNT = text; // new text

sample.dataset.animating = 'true';
sample.style.height = sampleH + 'px'; // original text element

var samO = document.createElement('div');
samO.style.transformOrigin = '0 ' + sampleH / 2 + 'px -' + sampleH / 2 + 'px';
samO.classList.add('t3xt');
samO.textContent = sampleT; // new text element

var samN = samO.cloneNode();
samN.textContent = sampleNT;
sample.textContent = '';
sample.appendChild(samO);
sample.appendChild(samN);
samO.classList.add('t3xt-out');
samN.classList.add('t3xt-in');
samN.addEventListener('animationend', function (event) {
sample.removeChild(samO);
sample.removeChild(samN);
sample.textContent = sampleNT;
sample.dataset.animating = 'false';
});
}

var phraseIndex = 1;
var wordIndex = 0;
var t3xts = [["No!", "This is", "Patrick!"], ["I can't", "see my", "forehead"], ["Is mayonnaise", "an
instrument?"], ["F stands", "for Fun", ""], ["I wumbo", "you wumbo", "he/she/me wumbo"], ["It may
be", "stupid, but", "it's also dumb"], ["Moss always", "points to", "civilization"]]; // start it off

setTimeout(changetext, 200);

changetext() {
 if (wordIndex > 2) {
   wordIndex = 0;
   phraseIndex++;
}

if (phraseIndex >= t3xts.length) {
phraseIndex = 0;
}

var term = t3xts[phraseIndex][wordIndex];
n3xt(term, '.t3xt-' + ++wordIndex);

if (wordIndex == 3) {
setTimeout(changetext, 2000);
} else {
setTimeout(changetext, 150);
}
}

}
</code>```

animate.js ( The code which I want to convert to landing.component.ts)

```<code>function n3xt(text, element) {
var sample = document.querySelector(element);
if (sample.dataset.animating === 'true') return;
var sampleH = 50; // will keep it fixed, otherwise sample.offsetHeight

var sampleT = sample.textContent; // old text

var sampleNT = text; // new text

sample.dataset.animating = 'true';
sample.style.height = sampleH + 'px'; // original text element

var samO = document.createElement('div');
samO.style.transformOrigin = '0 ' + sampleH / 2 + 'px -' + sampleH / 2 + 'px';
samO.classList.add('t3xt');
samO.textContent = sampleT; // new text element

var samN = samO.cloneNode();
samN.textContent = sampleNT;
sample.textContent = '';
sample.appendChild(samO);
sample.appendChild(samN);
samO.classList.add('t3xt-out');
samN.classList.add('t3xt-in');
samN.addEventListener('animationend', function (event) {
sample.removeChild(samO);
sample.removeChild(samN);
sample.textContent = sampleNT;
sample.dataset.animating = 'false';
});
}

var phraseIndex = 1;
var wordIndex = 0;
var t3xts = [["No!", "This is", "Patrick!"], ["I can't", "see my", "forehead"], ["Is mayonnaise", "an
instrument?"], ["F stands", "for Fun", ""], ["I wumbo", "you wumbo", "he/she/me wumbo"], ["It may
be", "stupid, but", "it's also dumb"], ["Moss always", "points to", "civilization"]]; // start it off

setTimeout(changetext, 200);

function changetext() {
if (wordIndex > 2) {
wordIndex = 0;
phraseIndex++;
}

if (phraseIndex >= t3xts.length) {
phraseIndex = 0;
}

var term = t3xts[phraseIndex][wordIndex];
n3xt(term, '.t3xt-' + ++wordIndex);

if (wordIndex == 3) {
setTimeout(changetext, 2000);
} else {
setTimeout(changetext, 150);
}
}
</code>```

Can anyone please help me convert the javascript code to the typescript code?

答:
Check out the stackblitz sample Stackblitz

This is how I updated the component

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'animation-container',
  templateUrl: './text-rotate.component.html',
  styleUrls: [ './text-rotate.component.css' ]
})
export class AnimationContainer implements OnInit {

 phraseIndex = 1;
  wordIndex = 0;
  t3xts = [
  ["No!", "This is", "Patrick!"],
  ["I can't", "see my", "forehead"],
  ["Is mayonnaise", "an instrument?"],
  ["F stands", "for Fun", ""],
  ["I wumbo", "you wumbo", "he/she/me wumbo"],
  ["It may be", "stupid, but", "it's also dumb"],
  ["Moss always", "points to", "civilization"]
];

n3xt(text, element) {
  let sample = document.querySelector(element);
  if (sample.dataset.animating === "true") return;
  let sampleH = 50; // will keep it fixed, otherwise sample.offsetHeight
  let sampleT = sample.textContent; // old text
  let sampleNT = text; // new text
  sample.dataset.animating = "true";
  sample.style.height = sampleH + "px";

  // original text element
  let samO = document.createElement("div");
  samO.style.transformOrigin = "0 " + sampleH / 2 + "px -" + sampleH / 2 + "px";
  samO.classList.add("t3xt");
  samO.textContent = sampleT;

  // new text element
  let samN = samO.cloneNode();
  samN.textContent = sampleNT;
  sample.textContent = "";
  sample.appendChild(samO);
  sample.appendChild(samN);

  samO.classList.add("t3xt-out");
  samN.classList.add("t3xt-in");

  samN.addEventListener("animationend", function(event) {
    sample.removeChild(samO);
    sample.removeChild(samN);
    sample.textContent = sampleNT;
    sample.dataset.animating = "false";
  });
}

  changetext(){
  if (this.wordIndex > 2) {
    this.wordIndex = 0;
    this.phraseIndex++;
  }
  if (this.phraseIndex >= this.t3xts.length) {
    this.phraseIndex = 0;
  }
  let term = this.t3xts[this.phraseIndex][this.wordIndex];
  this.n3xt(term, ".t3xt-" + ++this.wordIndex);

  if (this.wordIndex == 3) {
    setTimeout(()=>this.changetext(), 2000);
  } else {
    setTimeout(()=>this.changetext(), 150);
  }
}
ngOnInit(){
  setTimeout(()=>this.changetext(), 200);
}
}
</code>```

Body:
I have a javascript file for rotating a text in 3d format to be converted to angular component specific typescript file. The codepen for the same is - https://codepen.io/jouanmarcel/pen/wxdqNq

I am also providing my angular files :

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>RotateText</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css" crossorigin="anonymous">

  <app-root></app-root>

styles.css

* {
margin: 0px !important;
padding: 0px !important;
box-sizing: border-box !important;
}

body {
font-family: "Roboto Mono" !important;
font-size: 50px !important;
padding: 50px 0 0 100px !important;
display: flex !important;
align-items: stretch !important;
flex-direction: column !important;
font-weight: 700 !important;
color: #fff !important;
background-image: radial-gradient(#e85e3c, #7c1717) !important;
background-repeat: no-repeat !important;
height: 100vh !important;
}

app.component.html

<router-outlet></router-outlet>

landing.component.html

NO!

THIS IS

PATRICK!
 Jouan Marcel

landing.component.css

.t3xts {
line-height: 1 !important;
position: relative !important;
perspective: 1000px !important;
text-transform: uppercase !important;
}

.t3xt {
transform-style: preserve-3d !important;
position: absolute !important;
top: 0 !important;
text-transform: uppercase !important;
}

.t3xt-out {
animation: text-out .5s ease !important;
}

.t3xt-in {
animation: text-in .5s ease !important;
}

@keyframes text-out {
to {
    transform: rotateX(90deg) !important;
    opacity: 0 !important;
}
}

@keyframes text-in {
from {
    opacity: 0 !important;
    transform: rotateX(-90deg) !important;
}

to {
    transform: rotateX(0deg) !important;
    opacity: 1 !important;
}
}

.ref {
background-color: #000 !important;
border-radius: 3px !important;
padding: 5px 8px !important;
position: absolute !important;
font-size: 16px !important;
bottom: 10px !important;
right: 10px !important;
color: #fff !important;
font-weight: 300 !important;
font-family: sans-serif !important;
text-decoration: none !important;
}

.ref::first-letter {
font-size: 12px !important;
}

landing.component.ts (The file which is to contain the converted javascript code)

import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-landing',
 templateUrl: './landing.component.html',
 styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

constructor() { }

ngOnInit() {
}

n3xt(text, element){
var sample = document.querySelector(element);
if (sample.dataset.animating === 'true') return;
var sampleH = 50; // will keep it fixed, otherwise sample.offsetHeight

var sampleT = sample.textContent; // old text

var sampleNT = text; // new text

sample.dataset.animating = 'true';
sample.style.height = sampleH + 'px'; // original text element

var samO = document.createElement('div');
samO.style.transformOrigin = '0 ' + sampleH / 2 + 'px -' + sampleH / 2 + 'px';
samO.classList.add('t3xt');
samO.textContent = sampleT; // new text element

var samN = samO.cloneNode();
samN.textContent = sampleNT;
sample.textContent = '';
sample.appendChild(samO);
sample.appendChild(samN);
samO.classList.add('t3xt-out');
samN.classList.add('t3xt-in');
samN.addEventListener('animationend', function (event) {
sample.removeChild(samO);
sample.removeChild(samN);
sample.textContent = sampleNT;
sample.dataset.animating = 'false';
});
}

var phraseIndex = 1;
var wordIndex = 0;
var t3xts = [["No!", "This is", "Patrick!"], ["I can't", "see my", "forehead"], ["Is mayonnaise", "an
instrument?"], ["F stands", "for Fun", ""], ["I wumbo", "you wumbo", "he/she/me wumbo"], ["It may
be", "stupid, but", "it's also dumb"], ["Moss always", "points to", "civilization"]]; // start it off

setTimeout(changetext, 200);

changetext() {
 if (wordIndex > 2) {
   wordIndex = 0;
   phraseIndex++;
}

if (phraseIndex >= t3xts.length) {
phraseIndex = 0;
}

var term = t3xts[phraseIndex][wordIndex];
n3xt(term, '.t3xt-' + ++wordIndex);

if (wordIndex == 3) {
setTimeout(changetext, 2000);
} else {
setTimeout(changetext, 150);
}
}

}

animate.js ( The code which I want to convert to landing.component.ts)

function n3xt(text, element) {
var sample = document.querySelector(element);
if (sample.dataset.animating === 'true') return;
var sampleH = 50; // will keep it fixed, otherwise sample.offsetHeight

var sampleT = sample.textContent; // old text

var sampleNT = text; // new text

sample.dataset.animating = 'true';
sample.style.height = sampleH + 'px'; // original text element

var samO = document.createElement('div');
samO.style.transformOrigin = '0 ' + sampleH / 2 + 'px -' + sampleH / 2 + 'px';
samO.classList.add('t3xt');
samO.textContent = sampleT; // new text element

var samN = samO.cloneNode();
samN.textContent = sampleNT;
sample.textContent = '';
sample.appendChild(samO);
sample.appendChild(samN);
samO.classList.add('t3xt-out');
samN.classList.add('t3xt-in');
samN.addEventListener('animationend', function (event) {
sample.removeChild(samO);
sample.removeChild(samN);
sample.textContent = sampleNT;
sample.dataset.animating = 'false';
});
}

var phraseIndex = 1;
var wordIndex = 0;
var t3xts = [["No!", "This is", "Patrick!"], ["I can't", "see my", "forehead"], ["Is mayonnaise", "an
instrument?"], ["F stands", "for Fun", ""], ["I wumbo", "you wumbo", "he/she/me wumbo"], ["It may
be", "stupid, but", "it's also dumb"], ["Moss always", "points to", "civilization"]]; // start it off

setTimeout(changetext, 200);

function changetext() {
if (wordIndex > 2) {
wordIndex = 0;
phraseIndex++;
}

if (phraseIndex >= t3xts.length) {
phraseIndex = 0;
}

var term = t3xts[phraseIndex][wordIndex];
n3xt(term, '.t3xt-' + ++wordIndex);

if (wordIndex == 3) {
setTimeout(changetext, 2000);
} else {
setTimeout(changetext, 150);
}
}

Can anyone please help me convert the javascript code to the typescript code?

Body:
Check out the stackblitz sample Stackblitz

This is how I updated the component

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'animation-container',
  templateUrl: './text-rotate.component.html',
  styleUrls: [ './text-rotate.component.css' ]
})
export class AnimationContainer implements OnInit {

 phraseIndex = 1;
  wordIndex = 0;
  t3xts = [
  ["No!", "This is", "Patrick!"],
  ["I can't", "see my", "forehead"],
  ["Is mayonnaise", "an instrument?"],
  ["F stands", "for Fun", ""],
  ["I wumbo", "you wumbo", "he/she/me wumbo"],
  ["It may be", "stupid, but", "it's also dumb"],
  ["Moss always", "points to", "civilization"]
];

n3xt(text, element) {
  let sample = document.querySelector(element);
  if (sample.dataset.animating === "true") return;
  let sampleH = 50; // will keep it fixed, otherwise sample.offsetHeight
  let sampleT = sample.textContent; // old text
  let sampleNT = text; // new text
  sample.dataset.animating = "true";
  sample.style.height = sampleH + "px";

  // original text element
  let samO = document.createElement("div");
  samO.style.transformOrigin = "0 " + sampleH / 2 + "px -" + sampleH / 2 + "px";
  samO.classList.add("t3xt");
  samO.textContent = sampleT;

  // new text element
  let samN = samO.cloneNode();
  samN.textContent = sampleNT;
  sample.textContent = "";
  sample.appendChild(samO);
  sample.appendChild(samN);

  samO.classList.add("t3xt-out");
  samN.classList.add("t3xt-in");

  samN.addEventListener("animationend", function(event) {
    sample.removeChild(samO);
    sample.removeChild(samN);
    sample.textContent = sampleNT;
    sample.dataset.animating = "false";
  });
}

  changetext(){
  if (this.wordIndex > 2) {
    this.wordIndex = 0;
    this.phraseIndex++;
  }
  if (this.phraseIndex >= this.t3xts.length) {
    this.phraseIndex = 0;
  }
  let term = this.t3xts[this.phraseIndex][this.wordIndex];
  this.n3xt(term, ".t3xt-" + ++this.wordIndex);

  if (this.wordIndex == 3) {
    setTimeout(()=>this.changetext(), 2000);
  } else {
    setTimeout(()=>this.changetext(), 150);
  }
}
ngOnInit(){
  setTimeout(()=>this.changetext(), 200);
}
}


来源: stackexchange

问:
Reason why deep and shallow copy differences between "primitive" and "non-primitive" objects?
I know the difference between shallow and deep copy in Python, and the question is not about when to use one or the other. However I find this trivial example pretty amusing and non-intuitive

```<code>from copy import deepcopy

 a=0
 b=deepcopy(a)
 c=a
 a+=1
 print(a,b,c)
</code>```

output: 1 0 0

```<code> from copy import deepcopy
 a=[0]
 b=deepcopy(a)
 c=a
 a[0]+=1
 print(a,b,c)
</code>```

output: [1] 0 [1]

I would like to know the reason why this design choice was made, since the two snippets of code are in my opinion quite equivalent however their output is completely different. To make myself more explicit I wonder why = is a deepcopy in the case of a "primitive" variable  and a shallow copy in the case of a "non-primitive" (but still part of the basic language) variable like a list? I personally find this behavior counter-intuitive
Note: I used python 3

答:
The catch here is mutability and immutability.

There is no such thing is primitive and non primitive in python, everything is a type, some are just inbuilt.

You need to understand how python stores data in variables. Assuming you come from a C background, you can think of all python variables are pointers.

All python variables store the reference to the location where the value of the variable actually is.

The builtin id function somewhat lets us look into where the value of a variable is actually stored.

```<code>>>> x = 12345678
>>> id(x)
1886797010128
>>> y = x
>>> id(y)
1886797010128
>>> y += 1
>>> y
12345679
>>> x
12345678
>>> id(y)
1886794729648
</code>```

The variable x points to location 1886797010128 and location 1886797010128 holds the value of 10. int is an immutable type in python, which means that the data stored in the location 1886797010128 can't be changed.

When we assign y = x, y now also points to the same address, since it's not necessary to allocate more memory for the same value.

When y is changed (remember that int is an immutable type and it's value can't be changed), a new int is created in the new location 1886794729648 and y now points to this new int object at the new address.

The same happens when you try to update the value of a variable that holds immutable data.

```<code>>>> id(x)
140707671077744
>>> x = 30
>>> id(x)
140707671078064
</code>```

Changing the value of a variable that has immutable data simply makes the variable point to a new object with the updated value.

This is not the case with mutable types like list.

```<code>>>> a = [1, 2, 3]
>>> b = a
>>> id(a), id(b)
(1886794896456, 1886794896456)
>>> b.append(4)
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>>
</code>```

a is a list and is mutable, changing it using methods like append will actually mutate the value at address 1886794896456. Since b also points to the same address, the value of a also gets updated.

A deepcopy creates a new object at a different memory location with the same value as its parameter, i.e. the object passed to it.

I would like to know the reason why this design choice was made

This is simply because of how python is designed as an object oriented language. Similar behavior can be seen in java objects.

I personally find this behavior counter-intuitive

Intuition comes from practice. Practicing one language cannot help with how other languages work, there are different design patterns and conventions for different languages and I think some amount of effort should be put in to learn what they are for the language we are about to use.

ContentLicense: CC BY-SA 4.0

Body:
I know the difference between shallow and deep copy in Python, and the question is not about when to use one or the other. However I find this trivial example pretty amusing and non-intuitive

from copy import deepcopy

 a=0
 b=deepcopy(a)
 c=a
 a+=1
 print(a,b,c)

output: 1 0 0

 from copy import deepcopy
 a=[0]
 b=deepcopy(a)
 c=a
 a[0]+=1
 print(a,b,c)

output: [1] 0 [1]

I would like to know the reason why this design choice was made, since the two snippets of code are in my opinion quite equivalent however their output is completely different. To make myself more explicit I wonder why = is a deepcopy in the case of a "primitive" variable  and a shallow copy in the case of a "non-primitive" (but still part of the basic language) variable like a list? I personally find this behavior counter-intuitive
Note: I used python 3

Body:
The catch here is mutability and immutability.

There is no such thing is primitive and non primitive in python, everything is a type, some are just inbuilt.

You need to understand how python stores data in variables. Assuming you come from a C background, you can think of all python variables are pointers.

All python variables store the reference to the location where the value of the variable actually is.

The builtin id function somewhat lets us look into where the value of a variable is actually stored.

>>> x = 12345678
>>> id(x)
1886797010128
>>> y = x
>>> id(y)
1886797010128
>>> y += 1
>>> y
12345679
>>> x
12345678
>>> id(y)
1886794729648

The variable x points to location 1886797010128 and location 1886797010128 holds the value of 10. int is an immutable type in python, which means that the data stored in the location 1886797010128 can't be changed.

When we assign y = x, y now also points to the same address, since it's not necessary to allocate more memory for the same value.

When y is changed (remember that int is an immutable type and it's value can't be changed), a new int is created in the new location 1886794729648 and y now points to this new int object at the new address.

The same happens when you try to update the value of a variable that holds immutable data.

>>> id(x)
140707671077744
>>> x = 30
>>> id(x)
140707671078064

Changing the value of a variable that has immutable data simply makes the variable point to a new object with the updated value.

This is not the case with mutable types like list.

>>> a = [1, 2, 3]
>>> b = a
>>> id(a), id(b)
(1886794896456, 1886794896456)
>>> b.append(4)
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>>

a is a list and is mutable, changing it using methods like append will actually mutate the value at address 1886794896456. Since b also points to the same address, the value of a also gets updated.

A deepcopy creates a new object at a different memory location with the same value as its parameter, i.e. the object passed to it.

I would like to know the reason why this design choice was made

This is simply because of how python is designed as an object oriented language. Similar behavior can be seen in java objects.

I personally find this behavior counter-intuitive

Intuition comes from practice. Practicing one language cannot help with how other languages work, there are different design patterns and conventions for different languages and I think some amount of effort should be put in to learn what they are for the language we are about to use.


问:
Make a square with letters
I have this:

```<code>ooooo
ooooo
ooooo
ooooo
ooooo
</code>```

Put o on everything except the middle so it turns into this:

```<code>ooooo
o   o
o   o
o   o
ooooo
</code>```

Is there anyway I can do that in Javascript?
My code currently is:
HTML:

```<code><input type = 'text' id = 'box' placeholder = 'Enter n'  onkeyup = 'bigbox();'/>
        <br><br>

        <div id="output"></div>
</code>```

Script:

```<code> function bigbox() {

            number = document.getElementById('box').value;
            display = document.getElementById("output");

        for(let j = 0; j<number; j++) {
            for(let i = 0; i<number; i++)
            text += "o";
            text += "<br>";

            }

        display.innerHTML = text;
</code>```

答:
You just need to add a little logic to determine whether a o or a space should be output.

Essentially, an o should be output if:

It's the first or last row, or

it's the first or last column.

See the below example snippet:

function bigbox() {
  number = document.getElementById('box').value;
  display = document.getElementById("output");
  var text = '';

  for(let j = 0; j < number; j++) {
    for(let i = 0; i < number; i++) {
      if (j == 0 || j == number - 1 || i == 0 || i == number - 1) {
        text += "o";
      } else {
        text += ' ';
      }
    }
    text += "
";
  }
  display.innerHTML = text;
}

bigbox();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#output {
  font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}</code>```

<input id="box" value="5" />

```

Title: Make a square with letters

Body:
I have this:

ooooo
ooooo
ooooo
ooooo
ooooo

Put o on everything except the middle so it turns into this:

ooooo
o   o
o   o
o   o
ooooo

Is there anyway I can do that in Javascript?
My code currently is:
HTML:

<input type = 'text' id = 'box' placeholder = 'Enter n'  onkeyup = 'bigbox();'/>

Script:

 function bigbox() {

            number = document.getElementById('box').value;
            display = document.getElementById("output");

        for(let j = 0; j<number; j++) {
            for(let i = 0; i<number; i++)
            text += "o";
            text += "
";

            }

        display.innerHTML = text;

Body:
You just need to add a little logic to determine whether a o or a space should be output.

Essentially, an o should be output if:

It's the first or last row, or

it's the first or last column.

See the below example snippet:

function bigbox() {
  number = document.getElementById('box').value;
  display = document.getElementById("output");
  var text = '';

  for(let j = 0; j < number; j++) {
    for(let i = 0; i < number; i++) {
      if (j == 0 || j == number - 1 || i == 0 || i == number - 1) {
        text += "o";
      } else {
        text += '&nbsp;';
      }
    }
    text += "<br>";
  }
  display.innerHTML = text;
}

bigbox();

#output {
  font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}

<input id="box" value="5" />
<div id="output"></div>


问:
Generate all combinations of an unknown number of variables
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

```<code>variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
</code>```

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

```<code>"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.
</code>```

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

```<code>a  b  c
x  y  z
x  y  z
x  y  z
x  y  z
</code>```

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

```<code>[
  (x, y, z)
  (x, y, z)
]
...
</code>```

答:
Try this way:

```<code>var=[]
for k in variables.keys():
  var.append(np.arange(variables[k][0],variables[k][1]+1,variables[k][2]))

np.array(np.meshgrid(var[0],var[1],var[2])).T.reshape(-1,3)

</code>```

for combination I took help from here

Body:
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

a  b  c
x  y  z
x  y  z
x  y  z
x  y  z

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

[
  (x, y, z)
  (x, y, z)
]
...

Body:
Try this way:

var=[]
for k in variables.keys():
  var.append(np.arange(variables[k][0],variables[k][1]+1,variables[k][2]))

np.array(np.meshgrid(var[0],var[1],var[2])).T.reshape(-1,3)

for combination I took help from here


答:
You could add if one of the indices is zero or plus one equal to the wanted site of the square, then take a border character or space.

Basically this line

```<code>text += i === 0 || i + 1 === size || j === 0 || j + 1 === size ? "o": " ";
</code>```

contains three parts:

An addition assignment +=, which takes an expression and adds it to the left hand side variable.

```<code>text += someExpression
</code>```

A conditional (ternary) operator ?: which takes an expression and checks if this is truthy (like any number except zero or NaN, any non empty string, an object or array, true) or falsy (like zero/NaN, '', null, undefined, false).

If truthy, it take the value after the ? and if falsy the value after :.

It is a kind of short form of an if statement with getting an expression.

```<code>expression ? alternative1 : alternative2 // code
truthy   ->  alternative1                // result
falsy    ->                 alternative2
</code>```

A condition part. The conditions are a connected with logical OR ||, this returns the first truthy value, or the last falsy one.

```<code>condition1 || condition2 || condition3 || ...
</code>```

The conditions check the indices and if zero or the greatest valid value, then you hit a border, otherwise you are inside of the square.

function bigbox(size) {
    var display = document.getElementById("output"),
        text = "";

    size = +size;
    for (let j = 0; j < size; j++) {
        for (let i = 0; i < size; i++) {
            text += i === 0 || i + 1 === size || j === 0 || j + 1 === size ? "o": " ";
        }
        text += "
";
    }
    display.innerHTML = text;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="box" onchange="bigbox(this.value)">
<pre id="output">``````

Title: Make a square with letters

Body:
You could add if one of the indices is zero or plus one equal to the wanted site of the square, then take a border character or space.

Basically this line

text += i === 0 || i + 1 === size || j === 0 || j + 1 === size ? "o": " ";

contains three parts:

An addition assignment +=, which takes an expression and adds it to the left hand side variable.

text += someExpression

A conditional (ternary) operator ?: which takes an expression and checks if this is truthy (like any number except zero or NaN, any non empty string, an object or array, true) or falsy (like zero/NaN, '', null, undefined, false).

If truthy, it take the value after the ? and if falsy the value after :.

It is a kind of short form of an if statement with getting an expression.

expression ? alternative1 : alternative2 // code
truthy   ->  alternative1                // result
falsy    ->                 alternative2

A condition part. The conditions are a connected with logical OR ||, this returns the first truthy value, or the last falsy one.

condition1 || condition2 || condition3 || ...

The conditions check the indices and if zero or the greatest valid value, then you hit a border, otherwise you are inside of the square.

function bigbox(size) {
    var display = document.getElementById("output"),
        text = "";

    size = +size;
    for (let j = 0; j < size; j++) {
        for (let i = 0; i < size; i++) {
            text += i === 0 || i + 1 === size || j === 0 || j + 1 === size ? "o": " ";
        }
        text += "<br>";
    }
    display.innerHTML = text;
}

<input type="text" id="box" onchange="bigbox(this.value)">
<pre id="output"></pre>


问:
Difference between random.sample(sample,k) and itertools.combinations(p,r)
Hello I am new to python, and have just started writing basic python scripts. I have decided to write a password generator program. I came across random.sample() and itertools.combinations() functions. And I would like to know the difference between them. I have read the documentation and came to the following conclusion:

1. random.sample() will return a list of unique combination from the population provided there r no repeated values in the population.

2. combinations() will also return a tuple of (p,r) possible combinations where r is the length. and there was this line,"Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination." which i didn't understand. I assume it says that input elements must be unique to get unique combinations

So i came to final conclusion that both are same. I would like to know whether i am right or wrong (with explanations pls). Thank you.

答:
They are not the same, actually they do completely different things. itertools.combinations() is a generator - it returns a sequence of all combinations from a given set of values. random.sample() provides one (randomly selected) combination. Run these two snippets:

```<code>import random
print(random.sample([1,2,3], 2))
</code>```

and

```<code>import itertools
for c in itertools.combinations([1,2,3],2):
    print(c)
</code>```

and note the difference.

Body:
They are not the same, actually they do completely different things. itertools.combinations() is a generator - it returns a sequence of all combinations from a given set of values. random.sample() provides one (randomly selected) combination. Run these two snippets:

import random
print(random.sample([1,2,3], 2))

and

import itertools
for c in itertools.combinations([1,2,3],2):
    print(c)

and note the difference.


问:
Spring Boot JPA : How to map a filed to a column whose data type is not fixed
I have an entity class with two fields.

```<code>@Entity(name = "additional_attributes")
class AdditionalAttributes {

  @Id
  private Integer id;
  private String attributeName;
  private Object attributevalue;

  // getter and setter
  // manytoone with mandatory table
</code>```

}

The datatype of attributeValue is Object here, which means the value can be anything like integer/boolean/float.

How to handle this scenario to save the right value and again while fetching I should get the exact value (which was of type boolean/integer etc) ??

答:
You should add attribute class marker field Class<?> attributeClass. Another approach is to create enum AttributeType and use it as marker field

```<code>@Entity(name = "additional_attributes")
class AdditionalAttributes {

  @Id
  private Integer id;
  private String attributeName;

  Class<?> attributeClass;
  String attributevalue;

  public void setAttribute(Object attribute){
      attributeClass = attribute.getClass()
      attributevalue = attribute.toString();
  }
}
</code>```

To set attribute use this:

```<code>Integer integerAttribute = 100;
additionalAttributes.setAttribute(integerAttribute);

Boolean booleanAttribute = true;
additionalAttributes.setAttribute(booleanAttribute);
</code>```

and then there are two approaches:

1) Add to entity or service class common attribute parcer

```<code>public Object getAttribute() throws NumberFormatException {
      if(attributeClass == Integer.class) {
          return Integer.parseInt(attributevalue);
      }

      if(attributeClass == Boolean.class) {
          return Boolean.parseBoolean(attributevalue);
      }

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

Usage:

```<code>Object attribute = additionalAttributes.getAttribute();
</code>```

2) Or use pair of methods to get attribute

```<code>public boolean isIntegerAttribute() {
   return attributeClass == Integer.class;
}

public Integer getIntegerAttribute() throws NumberFormatException {
   return Integer.parseInt(attributevalue);
}

public boolean isBooleanAttribute() {
   return attributeClass == Boolean.class;
}

public Boolean getBooleanAttribute() {
   return Boolean.parseBoolean(attributevalue);
}

//...
</code>```

Usage:

```<code>if(additionalAttributes.isIntegerAttribute()) {
    Integer integerAttribute = additionalAttributes.getIntegerAttribute();
    //...
}

if(additionalAttributes.isBooleanAttribute()) {
    Boolean booleanAttribute = additionalAttributes.getBooleanAttribute();
    //...
}
</code>```

Body:
I have an entity class with two fields.

@Entity(name = "additional_attributes")
class AdditionalAttributes {

  @Id
  private Integer id;
  private String attributeName;
  private Object attributevalue;

  // getter and setter
  // manytoone with mandatory table

}

The datatype of attributeValue is Object here, which means the value can be anything like integer/boolean/float.

How to handle this scenario to save the right value and again while fetching I should get the exact value (which was of type boolean/integer etc) ??

Body:
You should add attribute class marker field Class<?> attributeClass. Another approach is to create enum AttributeType and use it as marker field

@Entity(name = "additional_attributes")
class AdditionalAttributes {

  @Id
  private Integer id;
  private String attributeName;

  Class<?> attributeClass;
  String attributevalue;

  public void setAttribute(Object attribute){
      attributeClass = attribute.getClass()
      attributevalue = attribute.toString();
  }
}

To set attribute use this:

Integer integerAttribute = 100;
additionalAttributes.setAttribute(integerAttribute);

Boolean booleanAttribute = true;
additionalAttributes.setAttribute(booleanAttribute);

and then there are two approaches:

1) Add to entity or service class common attribute parcer

public Object getAttribute() throws NumberFormatException {
      if(attributeClass == Integer.class) {
          return Integer.parseInt(attributevalue);
      }

      if(attributeClass == Boolean.class) {
          return Boolean.parseBoolean(attributevalue);
      }

      //...
}

Usage:

Object attribute = additionalAttributes.getAttribute();

2) Or use pair of methods to get attribute

public boolean isIntegerAttribute() {
   return attributeClass == Integer.class;
}

public Integer getIntegerAttribute() throws NumberFormatException {
   return Integer.parseInt(attributevalue);
}

public boolean isBooleanAttribute() {
   return attributeClass == Boolean.class;
}

public Boolean getBooleanAttribute() {
   return Boolean.parseBoolean(attributevalue);
}

//...

Usage:

if(additionalAttributes.isIntegerAttribute()) {
    Integer integerAttribute = additionalAttributes.getIntegerAttribute();
    //...
}

if(additionalAttributes.isBooleanAttribute()) {
    Boolean booleanAttribute = additionalAttributes.getBooleanAttribute();
    //...
}


问:
Concurrent Fwrite in PHP?
I have a fwrite function to write log for delay insert to the database.

We have a visit rate of 20,000 Visits per hour.

so it's 0.18s per fwrite.

My question is that is it possible that PHP will miss several log when there are 2 or 3 visitor come in at the same time?

If it's then how can I make this concurrent?

My code is just normal Fopen fwrite fclose.

答:
How are you firing off the writes? If each requests (1 per visit) has an associated fwrite with it, you won't miss any. Perhaps they could become slow(er) as your web server is queuing / handling requests (peak traffic), but PHP is request driven, so for every page load, you'll have the fwrite execute.

I say you won't miss any because, unless your doing some non blocking I/O, your script is going to block on the fwrite call. In other words, fwrite will execute.

You're going to have trouble getting any sort of concurrency on a request driven app written in PHP without doing some really funky stuff.

ContentLicense: CC BY-SA 3.0

Title: Concurrent Fwrite in PHP?


问:
Why can we use `std::move` on a `const` object?
In C++11, we can write this code:

```<code>struct Cat {
   Cat(){}
};

const Cat cat;
std::move(cat); //this is valid in C++11
</code>```

when I call std::move, it means I want to move the object, i.e. I will change the object. To move a const object is unreasonable, so why does std::move not restrict this behaviour?  It will be a trap in the future, right?

Here trap means as Brandon mentioned in the comment:

" I think he means it "traps" him sneaky sneaky because if he doesn't
  realize, he ends up with a copy which is not what he intended."

In the book 'Effective Modern C++' by Scott Meyers, he gives an example:

```<code>class Annotation {
public:
    explicit Annotation(const std::string text)
     : value(std::move(text)) //here we want to call string(string&&),
                              //but because text is const,
                              //the return type of std::move(text) is const std::string&&
                              //so we actually called string(const string&)
                              //it is a bug which is very hard to find out
private:
    std::string value;
};
</code>```

If std::move was forbidden from operating on a const object, we could easily find out the bug, right?

答:
Fortunately you can use clang-tidy's check to find such issues:
https://clang.llvm.org/extra/clang-tidy/checks/performance/move-const-arg.html</p>

Body:
In C++11, we can write this code:

struct Cat {
   Cat(){}
};

const Cat cat;
std::move(cat); //this is valid in C++11

when I call std::move, it means I want to move the object, i.e. I will change the object. To move a const object is unreasonable, so why does std::move not restrict this behaviour?  It will be a trap in the future, right?

Here trap means as Brandon mentioned in the comment:

" I think he means it "traps" him sneaky sneaky because if he doesn't
  realize, he ends up with a copy which is not what he intended."

In the book 'Effective Modern C++' by Scott Meyers, he gives an example:

class Annotation {
public:
    explicit Annotation(const std::string text)
     : value(std::move(text)) //here we want to call string(string&&),
                              //but because text is const,
                              //the return type of std::move(text) is const std::string&&
                              //so we actually called string(const string&)
                              //it is a bug which is very hard to find out
private:
    std::string value;
};

If std::move was forbidden from operating on a const object, we could easily find out the bug, right?


问:
Can't resolve '@material-ui/core/TableContainer
I want to import table container for my react application. but I can't use it because of my material ui version error.
How i update my version to latest version. I suppose that it's the solution for that error.
I have already tried npm uninstall and npm uninstall, but didn't solve yet. Help me.</p>

```<code>{
  "name": "material-dashboard-react",
  "version": "1.6.0",
  "description": "Material Dashboard React. Coded by Creative Tim",
  "private": false,
  "main": "dist/index.js",
  "dependencies": {
    "@khanacademy/react-multi-select": "^0.3.3",
    "@lls/react-light-calendar": "^2.0.7",
    "@material-ui/core": "^3.9.4",
    "@material-ui/icons": "3.0.2",
    "@progress/kendo-react-dropdowns": "^3.4.1",
    "@progress/kendo-react-intl": "^3.4.1",
    "animate.css": "^3.7.2",
    "axios": "^0.19.1",
    "bootstrap": "^4.3.1",
    "chartist": "0.10.1",
    "classnames": "2.2.6",
    "firebase": "^7.0.0",
    "history": "4.7.2",
    "jquery": "^1.9.1",
    "material-ui-next-responsive-table": "^0.5.1",
    "multi-select-react": "^0.1.8",
    "multiselect-dropdown-react": "^1.0.5",
    "multiselect-react-dropdown": "^1.2.4",
    "perfect-scrollbar": "1.4.0",
    "prettier": "1.16.4",
    "prop-types": "15.7.1",
    "react": "^16.8.1",
    "react-bootstrap": "^1.0.0-beta.12",
    "react-bootstrap-dialog": "^0.13.0",
    "react-bootstrap-modal": "^4.2.0",
    "react-chartist": "0.13.3",
    "react-confirm-alert": "^2.4.1",
    "react-datepicker": "^2.9.6",
    "react-devtools": "^4.4.0",
    "react-dialog": "^1.0.2",
    "react-dom": "16.8.1",
    "react-dropdown": "^1.6.4",
    "react-dropdown-multiselect": "^1.0.0",
    "react-dropdown-tree-select": "^2.1.1",
    "react-google-maps": "9.4.5",
    "react-light-calendar": "^1.0.3",
    "react-multiple-select-dropdown": "^2.0.0",
    "react-multiselect-checkboxes": "^0.1.1",
    "react-notification-alert": "0.0.12",
    "react-notifications": "^1.4.3",
    "react-notifications-component": "^2.1.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.5",
    "react-select": "^3.0.8",
    "react-swipeable-views": "0.13.1",
    "react-table-container": "^2.0.3",
    "react-toastify": "^5.4.0",
</code>```

答:
@material-ui/core version ^3.9.4 doesn't have <TableContainer>

so you need to update @materia-ui/core version

latest version v4.9.2, so please update version and try

Body:
I want to import table container for my react application. but I can't use it because of my material ui version error.
How i update my version to latest version. I suppose that it's the solution for that error.
I have already tried npm uninstall and npm uninstall, but didn't solve yet. Help me.

{
  "name": "material-dashboard-react",
  "version": "1.6.0",
  "description": "Material Dashboard React. Coded by Creative Tim",
  "private": false,
  "main": "dist/index.js",
  "dependencies": {
    "@khanacademy/react-multi-select": "^0.3.3",
    "@lls/react-light-calendar": "^2.0.7",
    "@material-ui/core": "^3.9.4",
    "@material-ui/icons": "3.0.2",
    "@progress/kendo-react-dropdowns": "^3.4.1",
    "@progress/kendo-react-intl": "^3.4.1",
    "animate.css": "^3.7.2",
    "axios": "^0.19.1",
    "bootstrap": "^4.3.1",
    "chartist": "0.10.1",
    "classnames": "2.2.6",
    "firebase": "^7.0.0",
    "history": "4.7.2",
    "jquery": "^1.9.1",
    "material-ui-next-responsive-table": "^0.5.1",
    "multi-select-react": "^0.1.8",
    "multiselect-dropdown-react": "^1.0.5",
    "multiselect-react-dropdown": "^1.2.4",
    "perfect-scrollbar": "1.4.0",
    "prettier": "1.16.4",
    "prop-types": "15.7.1",
    "react": "^16.8.1",
    "react-bootstrap": "^1.0.0-beta.12",
    "react-bootstrap-dialog": "^0.13.0",
    "react-bootstrap-modal": "^4.2.0",
    "react-chartist": "0.13.3",
    "react-confirm-alert": "^2.4.1",
    "react-datepicker": "^2.9.6",
    "react-devtools": "^4.4.0",
    "react-dialog": "^1.0.2",
    "react-dom": "16.8.1",
    "react-dropdown": "^1.6.4",
    "react-dropdown-multiselect": "^1.0.0",
    "react-dropdown-tree-select": "^2.1.1",
    "react-google-maps": "9.4.5",
    "react-light-calendar": "^1.0.3",
    "react-multiple-select-dropdown": "^2.0.0",
    "react-multiselect-checkboxes": "^0.1.1",
    "react-notification-alert": "0.0.12",
    "react-notifications": "^1.4.3",
    "react-notifications-component": "^2.1.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.5",
    "react-select": "^3.0.8",
    "react-swipeable-views": "0.13.1",
    "react-table-container": "^2.0.3",
    "react-toastify": "^5.4.0",


问:
How to compose two images using Magick.net
Im currently trying to compose two blob images from my Azure Storage using Magick.net

Its almost working. But I think I just need some little fine tuning which I dont know how to do it.

Image1 = Main (Background)
Image2 = Overlay

Routine:
Image2 is actually a peninput with a black background. So I need to make the background from black to transparent and resizing to the same size as Image1.
After this I use a function to composite Image2 over image1.

This is my function but it does not work

```<code>        public MagickImage ComebineBitmap(MagickImage Main, MagickImage Overlay)
    {
        Main.Composite(Overlay);
        Overlay.Resize(Main.BaseWidth, Main.BaseHeight);
        Overlay.Transparent(MagickColors.Black);
        Main.Composite(Overlay);
        return Main;
    }
</code>```

答:
```<code>    public MagickImage ComebineBitmap(MagickImage Main, MagickImage Overlay)
    {
    MagickGeometry gm = new MagickGeometry();
    gm.Width = Main.Width;
    gm.Height = Main.Height;
    gm.IgnoreAspectRatio = true;

        Overlay.Density = Main.Density;
        Overlay.BitDepth(Main.BitDepth());

        Overlay.LiquidRescale(gm);
        Overlay.Transparent(MagickColors.Black);

        Main.Composite(Overlay, CompositeOperator.SrcOver);

       return Main;
    }
</code>```

Body:
Im currently trying to compose two blob images from my Azure Storage using Magick.net

Its almost working. But I think I just need some little fine tuning which I dont know how to do it.

Image1 = Main (Background)
Image2 = Overlay

Routine:
Image2 is actually a peninput with a black background. So I need to make the background from black to transparent and resizing to the same size as Image1.
After this I use a function to composite Image2 over image1.

This is my function but it does not work

        public MagickImage ComebineBitmap(MagickImage Main, MagickImage Overlay)
    {
        Main.Composite(Overlay);
        Overlay.Resize(Main.BaseWidth, Main.BaseHeight);
        Overlay.Transparent(MagickColors.Black);
        Main.Composite(Overlay);
        return Main;
    }


答: You can put that middle part in a  tag and do the styling to that tag.</p>

Title: Make a square with letters


问:
Azure multistage pipelines: conditionally skip one stage but not the next
I have an Azure multi-stage CI/CD pipeline. It has stages for Test and UAT deployment.

I want the UAT release to run if Test succeeds or is skipped, but not if it fails.

I can't.  Whatever I try, if Test is skipped, UAT is also skipped.  Unless I use always(), but then UAT will run even if Test fails.

```<code>  ...
  - stage: Test
    condition: and(succeeded(), ne(variables['build.sourceBranchName'], 'DoUAT')) # Skip for UAT deployment tests
    ...

  - stage: UAT
    condition: and(succeeded(), in(variables['build.sourceBranchName'], 'master', 'DoUAT')) # Only deploy off master branch and branch to test UAT deploys.
    ...
</code>```

How do I skip one stage but not the next one?

答:
You can use not(failed('Test')) condition, please try below condition.

```<code>- stage: UAT
    condition: and(not(failed('Test')), in(variables['build.sourceBranchName'], 'master', DoUAT')) # Only deploy off master branch and branch to test UAT deploys.
    ...
</code>```

I tested and it worked, check below screenshot.

Body:
I have an Azure multi-stage CI/CD pipeline. It has stages for Test and UAT deployment.

I want the UAT release to run if Test succeeds or is skipped, but not if it fails.

I can't.  Whatever I try, if Test is skipped, UAT is also skipped.  Unless I use always(), but then UAT will run even if Test fails.

  ...
  - stage: Test
    condition: and(succeeded(), ne(variables['build.sourceBranchName'], 'DoUAT')) # Skip for UAT deployment tests
    ...

  - stage: UAT
    condition: and(succeeded(), in(variables['build.sourceBranchName'], 'master', 'DoUAT')) # Only deploy off master branch and branch to test UAT deploys.
    ...

How do I skip one stage but not the next one?

Body:
You can use not(failed('Test')) condition, please try below condition.

- stage: UAT
    condition: and(not(failed('Test')), in(variables['build.sourceBranchName'], 'master', DoUAT')) # Only deploy off master branch and branch to test UAT deploys.
    ...

I tested and it worked, check below screenshot.


问:
Scheme::R5RS. Trying to make the absolute value procedure
I'm trying to make the absolute value procedure and code got an error. I don't know why :/

```<code>(define (abs x)
   (cond ((> x 0) x)
       ((= x 0) 0)
       ((< x 0) (- x))))
</code>```

Error message:

```<code>define-values: assignment disallowed;
 cannot change constant
  constant: abs
</code>```

答:
The abs procedure is already part of the language you're using and you can't create another procedure with the same name. Simply rename it (and the implementation can be simplified a bit, by the way):

```<code>(define (myabs x)
  (cond ((>= x 0) x)
        (else (- x))))
</code>```

Body:
I'm trying to make the absolute value procedure and code got an error. I don't know why :/

(define (abs x)
   (cond ((> x 0) x)
       ((= x 0) 0)
       ((< x 0) (- x))))

Error message:

define-values: assignment disallowed;
 cannot change constant
  constant: abs

Body:
The abs procedure is already part of the language you're using and you can't create another procedure with the same name. Simply rename it (and the implementation can be simplified a bit, by the way):

(define (myabs x)
  (cond ((>= x 0) x)
        (else (- x))))


问:
How can I use HATEOAS and Query Parameters for RESTful search?
I would like to design a RESTful search URI using query parameters. For example, this URI returns a list of all users:

GET /users

And the first 25 users with the last name "Harvey":

GET /users?surname=Harvey&maxResults=25

How can I use hypermedia to describe what query parameters are allowed by the "/users" resource? I noticed that the new Google Tasks API just documents all the query parameters in the reference guide. I will document the list, but I would like to do it with HATEOAS too.

Thank you in advance!

答:
Using the syntax described in the current draft of the URI template spec you would do:</p>
```<code>/users{?surname,maxresults}
</code>```

Body:
Using the syntax described in the current draft of the URI template spec you would do:

/users{?surname,maxresults}


问:
getting first answer as undefined in json responce
i dont know why the first value is undefined ,and only getting result without json.parse()  and
the script and html is actually on the same page,
in php i just encode data into json and echo it,
,(dont mind this line)some one help me with stackoverflow is not letting me to post without larger question how to post question with a single line

      well this is what iam actually doing
    iam getting but it seams not the proper one
      <!DOCTYPE html>

         <title></title>

        <button >get data</button>

        r1

    <?php $con=mysqli_connect("localhost","root","","test"); ?>

    <?php
    header("Content-Type: application/json; charset=UTF-8");

    $sql="SELECT * FROM test where id='1'";
    $result=mysqli_query($con,$sql);

    while($row=mysqli_fetch_array($result))
    {

    $data[]=$row;
    //result is [{"0":"1","id":"1","1":"31232","number":"31232","2":"sdasd","text":"sdasd"}]

    }

    $d=json_encode($data);
    echo $d;

    ?>```

答:
Try Like this

```<code>$.ajax({
      url: "ing.php",
      type: "POST",
      success: function(data){
        var res;
        // var j=JSON.parse(data);
        var obj = jQuery.parseJSON(data);

        for(x in obj){
          res += "<div>"+ obj[x].id + "</div><div>"+ obj[x].number + "</div>";

        }
        document.getElementById("result").innerHTML=res;
        }
      });
</code>```

Body:
Try Like this

$.ajax({
      url: "ing.php",
      type: "POST",
      success: function(data){
        var res;
        // var j=JSON.parse(data);
        var obj = jQuery.parseJSON(data);

        for(x in obj){
          res += "<div>"+ obj[x].id + "</div><div>"+ obj[x].number + "</div>";

        }
        document.getElementById("result").innerHTML=res;
        }
      });


问:
How to check if a number in my contacts is registered to Whatsapp?
But I need this with numbers with country codes (like starting with +123 456 78 90 -that's the way I add the number as a contact)
I need a function/class to check if this number has Whatsapp.
I need this for an .apk I made in Android Studio.  </p>

答:
There is no proper way to check whether the contact no is registered on WhatsApp or not. But you can do one thing to check whether no is registered on WhatsApp or not.

Just pass that number to WhatsApp application using explicit intent and after passing to WhatsApp, WhatsApp open one popup which says "The given no is registered on WhatsApp" by this you can get to know whether no is registered or not.

```<code>Intent sendIntent = new Intent("android.intent.action.MAIN");
     sendIntent.putExtra("jid", whatsAppNumber + "@s.whatsapp.net");
     sendIntent.putExtra(Intent.EXTRA_TEXT, "whatsAppMessage");
     sendIntent.setAction(Intent.ACTION_SEND);
     sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     sendIntent.setPackage("com.whatsapp.w4b");
     sendIntent.setType("text/*");
     startActivity(sendIntent);
</code>```

Here "com.whatsapp.w4b" is used for the Business WhatsApp application if you want to use normal WhatsApp then you just need to change com.whatsapp.w4b to com.whatsapp

whatsAppNumber is a number to which you want to send the WhatsApp a message

Or Second way is to find a contact from internal contact data

```<code>ArrayList<String> whatsAppContact = new ArrayList();
Cursor c = getContentResolver().query(
    RawContacts.CONTENT_URI,
    new String[] { RawContacts.CONTACT_ID, RawContacts.DISPLAY_NAME_PRIMARY },
    RawContacts.ACCOUNT_TYPE + "= ?",
    new String[] { "com.whatsapp" },
    null);
ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int name =
c.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY);
while (c.moveToNext())
{
whatsAppContact.add(c.getString(name));
 }
</code>```

Body:
There is no proper way to check whether the contact no is registered on WhatsApp or not. But you can do one thing to check whether no is registered on WhatsApp or not.

Just pass that number to WhatsApp application using explicit intent and after passing to WhatsApp, WhatsApp open one popup which says "The given no is registered on WhatsApp" by this you can get to know whether no is registered or not.

Intent sendIntent = new Intent("android.intent.action.MAIN");
     sendIntent.putExtra("jid", whatsAppNumber + "@s.whatsapp.net");
     sendIntent.putExtra(Intent.EXTRA_TEXT, "whatsAppMessage");
     sendIntent.setAction(Intent.ACTION_SEND);
     sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     sendIntent.setPackage("com.whatsapp.w4b");
     sendIntent.setType("text/*");
     startActivity(sendIntent);

Here "com.whatsapp.w4b" is used for the Business WhatsApp application if you want to use normal WhatsApp then you just need to change com.whatsapp.w4b to com.whatsapp

whatsAppNumber is a number to which you want to send the WhatsApp a message

Or Second way is to find a contact from internal contact data

ArrayList<String> whatsAppContact = new ArrayList();
Cursor c = getContentResolver().query(
    RawContacts.CONTENT_URI,
    new String[] { RawContacts.CONTACT_ID, RawContacts.DISPLAY_NAME_PRIMARY },
    RawContacts.ACCOUNT_TYPE + "= ?",
    new String[] { "com.whatsapp" },
    null);
ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int name =
c.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY);
while (c.moveToNext())
{
whatsAppContact.add(c.getString(name));
 }


问:
Expect script works fine in command line but does not work in cron job
I have python script which call shell script like this:

```<code>p = subprocess.Popen([/path/to/script.sh], stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
output, error = p.communicate()
</code>```

expect script:

```<code>#!/usr/bin/env expect
set username "user"
set password "pass"
cd /my/repo
spawn /usr/bin/git pull origin master
expect "Username"
send "$username\r"
expect "Password"
send "$password\r"
interact
</code>```

When I run py-script manually it works fine, I see output like:

Username for repo: user
Password for repo:
* branch            master     -> FETCH_HEAD
Already up to date.
```

<p>But when I run my script via cron I see this:</p>

<pre class="lang-none prettyprint-override"><code>Username for repo: user
Password for repo:
</code>```

And nothing happens. What am I doing wrong?

My /etc/crontab file:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

10 *    * * * my_username /usr/bin/python3 /path/to/python/script.py
```

答:
You need to change interact to expect -timeout -1 eof.

interact only works when the Expect script is running on a tty but the cron job does not run on a tty.

You can verify this from an interactive shell:

```<code># this works
expect -c 'spawn sleep 5; interact'

# this does not work
true | expect -c 'spawn sleep 5; interact'

# this works
true | expect -c 'spawn sleep 5; expect -timeout -1 eof'
</code>```

Body:
I have python script which call shell script like this:

p = subprocess.Popen([/path/to/script.sh], stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
output, error = p.communicate()

expect script:

#!/usr/bin/env expect
set username "user"
set password "pass"
cd /my/repo
spawn /usr/bin/git pull origin master
expect "Username"
send "$username\r"
expect "Password"
send "$password\r"
interact

When I run py-script manually it works fine, I see output like:

Username for repo: user
Password for repo:
* branch            master     -> FETCH_HEAD
Already up to date.

But when I run my script via cron I see this:

Username for repo: user
Password for repo:

And nothing happens. What am I doing wrong?

My /etc/crontab file:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

10 *    * * * my_username /usr/bin/python3 /path/to/python/script.py

Body:
You need to change interact to expect -timeout -1 eof.

interact only works when the Expect script is running on a tty but the cron job does not run on a tty.

You can verify this from an interactive shell:

# this works
expect -c 'spawn sleep 5; interact'

# this does not work
true | expect -c 'spawn sleep 5; interact'

# this works
true | expect -c 'spawn sleep 5; expect -timeout -1 eof'


问:
Nested function returning a variable through the outer function in python
I have a requirement which I am going to try an explain through the below example:

Suppose we have a segment of code like this:

```<code>def a:
    def b:
        x = 2
</code>```

Now I want to return x through the function a. Is there any way to do it in python?

答:
```<code>def a():
    def b():
        x = 2
        return x
    return b()

a()
</code>```

Body:
I have a requirement which I am going to try an explain through the below example:

Suppose we have a segment of code like this:

def a:
    def b:
        x = 2

Now I want to return x through the function a. Is there any way to do it in python?


问:
Will SQL Server 2000 be able to use indexes in a view over a union of a view across linked servers
I have the following scenario:

2 DB servers (Linked to each other)

DB1 has a (large) table with transaction records
DB2 has a (not quite as large yet) table with transaction records (of a similar nature but without some of the data as it is a different system)
There are a bunch of reports that pull records out of the transaction table in DB1 and joins them up with lots of tables from DB1.

I can use data in DB1 to make the data from DB2 look like data in DB1.

If I create a view in DB1 that pulls the transaction data from DB2 and joins it up with data from DB1 to have the same columns as the transaction data in DB1, and then create another view that union-alls the data from DB1 and the first view, will queries against this second view still take advantage of any of the indexes on the transaction data in DB1 and DB2?

Or are there better ways of retro fitting data from a new system to an old system so that the old reports can report on the new data?

答: Without knowing more details about your setup, I think your preference should be to leave the data for the two systems in place regardless of whether queries through linked servers end up using indexes.  The way you have things set up sounds reasonable given the circumstance.  However, I would think since you know that you need to combine the two data sets, I'd consider migrating the data from one server to the other, provided the one server can handle both transaction loads.  This should provide better performance overall for your queries I would think.  Again, though, it would greatly depend on what your server and network infrastructure is like.

ContentLicense: CC BY-SA 2.5


问:
Azure DevOps Build Pipeline - Build Spring Boot based on specific application.profile
I have a Spring Boot application and I make use of Azure DevOps to automatically build/test the project and deploy the artifact.

My question is as follows: How can I build based on a specific application.profile? Right now it just builds but in my project I have the following 3 files:

application.properties

application-test.properties

application-acceptance.properties

How can I for example build based on "application-test.properties"?

Currently my code looks like this:

```<code>stages:
 - stage: Build
displayName: Build stage
  jobs:
 - job: MavenPackageAndPublishArtifacts
displayName: Maven Package and Publish Artifacts
pool:vmImage: $(vmImageName)

steps:
- task: Maven@3
  displayName: 'Maven Package'
  inputs:
    mavenPomFile: 'pom.xml'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.11'
    jdkArchitectureOption: 'x64'

- task: CopyFiles@2
  displayName: 'Copy Files to artifact staging directory'
  inputs:
    SourceFolder: '$(System.DefaultWorkingDirectory)'
    Contents: '**/target/*.?(war|jar)'
    TargetFolder: $(Build.ArtifactStagingDirectory)

- upload: $(Build.ArtifactStagingDirectory)
  artifact: drop
</code>```

答:
According to SpringBoot maven build war using specific application.properties

Setting the SPRING_PROFILES_ACTIVE environment variable will
  activate the intended profile. for example, in order to activate the
  qa profile, set the SPRING_PROFILES_ACTIVE environment variable to
  qa. Read more about profile specific properties here in Spring
  Boot Documentation.

About how to use environment, you could also take a look at this blog: Using Environment Variables in Azure DevOps Pipelines

Body:
I have a Spring Boot application and I make use of Azure DevOps to automatically build/test the project and deploy the artifact.

My question is as follows: How can I build based on a specific application.profile? Right now it just builds but in my project I have the following 3 files:

application.properties

application-test.properties

application-acceptance.properties

How can I for example build based on "application-test.properties"?

Currently my code looks like this:

stages:
 - stage: Build
displayName: Build stage
  jobs:
 - job: MavenPackageAndPublishArtifacts
displayName: Maven Package and Publish Artifacts
pool:vmImage: $(vmImageName)

steps:
- task: Maven@3
  displayName: 'Maven Package'
  inputs:
    mavenPomFile: 'pom.xml'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.11'
    jdkArchitectureOption: 'x64'

- task: CopyFiles@2
  displayName: 'Copy Files to artifact staging directory'
  inputs:
    SourceFolder: '$(System.DefaultWorkingDirectory)'
    Contents: '**/target/*.?(war|jar)'
    TargetFolder: $(Build.ArtifactStagingDirectory)

- upload: $(Build.ArtifactStagingDirectory)
  artifact: drop


问:
BatchWrite in AWS dynamo db skipping some items
I am trying to write Items to AWS dynamo db using node SDK. The problem I am facing is that when I write batch items to AWS in parallel using threads, some of the items are not written to database. The number of items are written are random. For instance, If I run my code 3 times, at one time it would be 150, next it would 200 and third time it could be 135. In addition, when I write the items sequentially without threads, even then some of the items are not written.However, in this case the items are less missing. For instance if the total number of items is 300 then the items written are 298.  I investigated the problem to see if there any unprocessed items but the batchWrite method returns nothing. It means that all the items are being processed correctly. Please note that I have OnDemand provision for my respective database so I do not expect any throttling issues. So here is my code.

```<code> exports.run = async function() {

  **This is the function which runs first !!!!!**

  const data = await getArrayOfObjects();
  console.log("TOTAL PRICE CHANGES")
  console.log(data.length)
  const batchesOfData = makeBatches(data)
  const threads = new Set();
  console.log("**********")
  console.log(batchesOfData.length)
  console.log("**********")
  for(let i = 0; i < batchesOfData.length; i++) {
    console.log("BATCH!!!!!")
    console.log(i)
    console.log(batchesOfData[i].length)
    // Sequential Approach
    const response = await compensationHelper.createItems(batchesOfData[i])
    console.log("RESPONSE")
    console.log(response)

    Parallel approach
    // const workerResult = await runService(batchesOfData[i])
    // console.log("WORKER RESUULT!!!!")
    // console.log(workerResult);

  }
}

exports.updateItemsInBatch = async function(data, tableName) {
  console.log("WRITING DATA")
  console.log(data.length)
  const batchItems = {
    RequestItems: {},
  };

  batchItems.RequestItems[tableName] = data;
  try {
    const result = await documentClient.batchWrite(batchItems).promise();
    console.log("UNPROCESSED ITEMS")
    console.log(result)
    if (result instanceof Error) {
      console.log(`[Error]: ${JSON.stringify(Error)}`);
      throw new Error(result);
    }
    return Promise.resolve(true);
  } catch (err) {
    console.error(`[Error]: ${JSON.stringify(err.message)}`);
    return Promise.reject(new Error(err));
  }
};

exports.convertToAWSCompatibleFormat = function(data) {
  const awsCompatibleData = [];
  data.forEach(record => awsCompatibleData.push({ PutRequest: { Item: record } }));
  return awsCompatibleData;
};

const createItems = async function(itemList) {
  try {
    const objectsList = [];
    for (let index = 0; index < itemList.length; index++) {
      try {
        const itemListObj = itemList[index];
        const ObjToBeInserted = {
          // some data assignments here
        };

        objectsList.push(ObjToBeInserted);
        if (
          objectsList.length >= AWS_BATCH_SIZE ||
          index === itemList.length - 1
        ) {
            const awsCompatiableFormat = convertToAWSCompatibleFormat(
              objectsList
            );
            await updateItemsInBatch(
              awsCompatiableFormat,
              process.env.myTableName
            );
        }
      } catch (error) {
        console.log(`[Error]: ${JSON.stringify(error)}`);
      }
    }

    return Promise.resolve(true);
  } catch (err) {
    return Promise.reject(new Error(err));
  }
};

const makeBatches = products => {
  const productBatches = [];
  let countr = -1;
  for (let index = 0; index < products.length; index++) {
    if (index % AWS_BATCH_SIZE === 0) {
      countr++;
      productBatches[countr] = [];
      if (countr === MAX_BATCHES) {
        break;
      }
    }
    try {
      productBatches[countr].push(products[index]);
    } catch (error) {
      continue;
    }
  }
  return productBatches;
};

async function runService(workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(path.join(__dirname, './worker.js'), { workerData });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    })
  })
}

// My worker file
'use strict';

const { workerData, parentPort } = require('worker_threads')
const creatItems = require('myscripts')
// You can do any heavy stuff here, in a synchronous way
// without blocking the "main thread"
console.log("I AM A NEW THREAD")
createItems(workerData)
// console.log('Going to write tons of content on file '+workerData);
parentPort.postMessage({ fileName: workerData, status: 'Done' })
</code>```

答: I had duplicate keys issue which means that primary and the sort key had duplicate values in the batch, however, in my case this error was not returned from the AWS BatchWrite method if my timestamp was in fraction of seconds 2020-02-09T08:02:36.71, which was a bit surprising. I resolved the issue by making my createdAt(sort key) to be more granular like this => 2020-02-09T08:02:36.7187 Thus making it non-repetitive.

Body:
I am trying to write Items to AWS dynamo db using node SDK. The problem I am facing is that when I write batch items to AWS in parallel using threads, some of the items are not written to database. The number of items are written are random. For instance, If I run my code 3 times, at one time it would be 150, next it would 200 and third time it could be 135. In addition, when I write the items sequentially without threads, even then some of the items are not written.However, in this case the items are less missing. For instance if the total number of items is 300 then the items written are 298.  I investigated the problem to see if there any unprocessed items but the batchWrite method returns nothing. It means that all the items are being processed correctly. Please note that I have OnDemand provision for my respective database so I do not expect any throttling issues. So here is my code.

 exports.run = async function() {

  **This is the function which runs first !!!!!**

  const data = await getArrayOfObjects();
  console.log("TOTAL PRICE CHANGES")
  console.log(data.length)
  const batchesOfData = makeBatches(data)
  const threads = new Set();
  console.log("**********")
  console.log(batchesOfData.length)
  console.log("**********")
  for(let i = 0; i < batchesOfData.length; i++) {
    console.log("BATCH!!!!!")
    console.log(i)
    console.log(batchesOfData[i].length)
    // Sequential Approach
    const response = await compensationHelper.createItems(batchesOfData[i])
    console.log("RESPONSE")
    console.log(response)

    Parallel approach
    // const workerResult = await runService(batchesOfData[i])
    // console.log("WORKER RESUULT!!!!")
    // console.log(workerResult);

  }
}

exports.updateItemsInBatch = async function(data, tableName) {
  console.log("WRITING DATA")
  console.log(data.length)
  const batchItems = {
    RequestItems: {},
  };

  batchItems.RequestItems[tableName] = data;
  try {
    const result = await documentClient.batchWrite(batchItems).promise();
    console.log("UNPROCESSED ITEMS")
    console.log(result)
    if (result instanceof Error) {
      console.log(`[Error]: ${JSON.stringify(Error)}`);
      throw new Error(result);
    }
    return Promise.resolve(true);
  } catch (err) {
    console.error(`[Error]: ${JSON.stringify(err.message)}`);
    return Promise.reject(new Error(err));
  }
};

exports.convertToAWSCompatibleFormat = function(data) {
  const awsCompatibleData = [];
  data.forEach(record => awsCompatibleData.push({ PutRequest: { Item: record } }));
  return awsCompatibleData;
};

const createItems = async function(itemList) {
  try {
    const objectsList = [];
    for (let index = 0; index < itemList.length; index++) {
      try {
        const itemListObj = itemList[index];
        const ObjToBeInserted = {
          // some data assignments here
        };

        objectsList.push(ObjToBeInserted);
        if (
          objectsList.length >= AWS_BATCH_SIZE ||
          index === itemList.length - 1
        ) {
            const awsCompatiableFormat = convertToAWSCompatibleFormat(
              objectsList
            );
            await updateItemsInBatch(
              awsCompatiableFormat,
              process.env.myTableName
            );
        }
      } catch (error) {
        console.log(`[Error]: ${JSON.stringify(error)}`);
      }
    }

    return Promise.resolve(true);
  } catch (err) {
    return Promise.reject(new Error(err));
  }
};

const makeBatches = products => {
  const productBatches = [];
  let countr = -1;
  for (let index = 0; index < products.length; index++) {
    if (index % AWS_BATCH_SIZE === 0) {
      countr++;
      productBatches[countr] = [];
      if (countr === MAX_BATCHES) {
        break;
      }
    }
    try {
      productBatches[countr].push(products[index]);
    } catch (error) {
      continue;
    }
  }
  return productBatches;
};

async function runService(workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(path.join(__dirname, './worker.js'), { workerData });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    })
  })
}

// My worker file
'use strict';

const { workerData, parentPort } = require('worker_threads')
const creatItems = require('myscripts')
// You can do any heavy stuff here, in a synchronous way
// without blocking the "main thread"
console.log("I AM A NEW THREAD")
createItems(workerData)
// console.log('Going to write tons of content on file '+workerData);
parentPort.postMessage({ fileName: workerData, status: 'Done' })


问:
AWS CLI command not run when executed via npm run command
System specification -

```<code>node version - v10.15.0
npm version - 6.4.1
aws-cli version - aws-cli/1.16.81 Python/3.6.0 Windows/10 botocore/1.12.71
sam-cli version - SAM CLI, version 0.41.0

Running on a windows machine.
</code>```

So I have a node project, which would be deployed to aws-sam. I have scripts for sam-validate, prepare, package. But when I run this script via npm run <package-name>, commands don't run. For example If I run npm run package, I get the following -

```<code>aws --region <region-name> s3api head-bucket --bucket <bucket-name>
Command not run
Command executed in 0 msec
aws --region <<region-name>> cloudformation package --template-file template.yaml --s3-bucket <bucket-name> --output-template-file template-deploy.yaml
Command not run
Command executed in 0 msec
</code>```

But surprisingly If I run those commands from powershell individually, then it works fine. Which made me come to the realization that scripts are okay, as the generated commands do work when I run them individually.

I checked my environment variables. All the things(node path, aws cli path etc.) are there.

What am I missing here? Simply put the problem is - Do I need to do anything else to run aws-cli or sam-cli commands through node scripts?

答:
There might be an issue with your scripts i think,

Consider writing the script in python like

```<code>import subprocesses
commandToBeExecutedOnShell='any command'
subprocess.check_call(commandToBeExecutedOnShell, shell=True)
</code>```

You can then either run the scripts from python itself or

create a separate node app which calls python functions

Reference This

and then run that node app using npm run

Body:
System specification -

node version - v10.15.0
npm version - 6.4.1
aws-cli version - aws-cli/1.16.81 Python/3.6.0 Windows/10 botocore/1.12.71
sam-cli version - SAM CLI, version 0.41.0

Running on a windows machine.

So I have a node project, which would be deployed to aws-sam. I have scripts for sam-validate, prepare, package. But when I run this script via npm run <package-name>, commands don't run. For example If I run npm run package, I get the following -

aws --region <region-name> s3api head-bucket --bucket <bucket-name>
Command not run
Command executed in 0 msec
aws --region <<region-name>> cloudformation package --template-file template.yaml --s3-bucket <bucket-name> --output-template-file template-deploy.yaml
Command not run
Command executed in 0 msec

But surprisingly If I run those commands from powershell individually, then it works fine. Which made me come to the realization that scripts are okay, as the generated commands do work when I run them individually.

I checked my environment variables. All the things(node path, aws cli path etc.) are there.

What am I missing here? Simply put the problem is - Do I need to do anything else to run aws-cli or sam-cli commands through node scripts?

Body:
There might be an issue with your scripts i think,

Consider writing the script in python like

import subprocesses
commandToBeExecutedOnShell='any command'
subprocess.check_call(commandToBeExecutedOnShell, shell=True)

You can then either run the scripts from python itself or

create a separate node app which calls python functions

Reference This

and then run that node app using npm run


问:
Why do I keep getting this error when trying to create a virtual environment with Python 3 on MacOS?
So I'm following a book that's teaching me how to make a Learning Log using Python and the Django web framework. I was asked to go to a terminal and create a directory called "learning_log" and change the working directory to "learning_log" (did that with no problems). However, when I try to create the virtual environment, I get an error (seen at the bottom of this post). Why am I getting this error and how can I fix this to move forward in the book?

I already tried installing a virtualenv with pip and pip3 (as the book prescribed). I was then instructed to enter the command:

learning_log$ virtualenv ll_env

And I get:

bash: virtualenv: command not found

Since I'm using Python3.6, I tried:

learning_log$ virtualenv ll_env --python=python3

And I still get:

bash: virtualenv: command not found

Brandons-MacBook-Pro:learning_log brandondusch$ python -m venv ll_env
Error: Command '['/Users/brandondusch/learning_log/ll_env/bin/python', '-Im', 'ensurepip', '--upgrade', '-
-default-pip']' returned non-zero exit status 1.

答: I had the same error. I restarted my computer and tried it again, but the error was still there. Then I tried python3 -m venv ll_env and it moved forward.


问:
Converting double to string
I am not sure it is me or what but I am having a problem converting a double to string.

here is my code:

```<code>double total = 44;
String total2 = Double.toString(total);
</code>```

Am i doing something wrong or am i missing a step here.

I get error NumberFormatException when trying to convert this.

```<code>totalCost.setOnTouchListener(new OnTouchListener() {
  public boolean onTouch(View v, MotionEvent event) {
    try {
      double priceG = Double.parseDouble(priceGal.getText().toString());
      double valG = Double.parseDouble(volGal.toString());
      double total = priceG * valG;
      String tot = new Double(total).toString();
      totalCost.setText(tot);
    } catch(Exception e) {
      Log.e("text", e.toString());
    }

    return false;
  }
});
</code>```

I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box.

答:
There are three ways to convert double to String.

Double.toString(d)

String.valueOf(d)

""+d

public class DoubleToString {

```<code>public static void main(String[] args) {
    double d = 122;
    System.out.println(Double.toString(d));
    System.out.println(String.valueOf(d));
    System.out.println(""+d);

}
</code>```

}

String to double

Double.parseDouble(str);

Title: Converting double to string

Body:
I am not sure it is me or what but I am having a problem converting a double to string.

here is my code:

double total = 44;
String total2 = Double.toString(total);

Am i doing something wrong or am i missing a step here.

I get error NumberFormatException when trying to convert this.

totalCost.setOnTouchListener(new OnTouchListener() {
  public boolean onTouch(View v, MotionEvent event) {
    try {
      double priceG = Double.parseDouble(priceGal.getText().toString());
      double valG = Double.parseDouble(volGal.toString());
      double total = priceG * valG;
      String tot = new Double(total).toString();
      totalCost.setText(tot);
    } catch(Exception e) {
      Log.e("text", e.toString());
    }

    return false;
  }
});

I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box.

Body:
There are three ways to convert double to String.

Double.toString(d)

String.valueOf(d)

""+d

public class DoubleToString {

public static void main(String[] args) {
    double d = 122;
    System.out.println(Double.toString(d));
    System.out.println(String.valueOf(d));
    System.out.println(""+d);

}

}

String to double

Double.parseDouble(str);


问:
How to close GLFW window when we close QT application
When i close the QT GUI i want the GLFW window to be closed accordingly.

For glfw we can query if window is closed or not by  glfwWindowShouldClose function.

Do we have anything like that in QT where we can keep Querying if the application GUI is closed.

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TreeModel model;
    QTApplication w(model);
    int return_code = 0;
    QTApplication.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   // Create the render window
    if (window == NULL)
    {
        QMessageBox msgBox;
        msgBox.setText("Not able to create GL Window");
        msgBox.exec();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();
    if (GLEW_OK != GlewInitResult)   // Check if glew is initialized properly
    {
        glfwTerminate();
    }
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    while (!glfwWindowShouldClose(window))
    {
        // Do Rendering here

    }
    return_code =  a.exec();
    glfwTerminate();
    return return_code;
}
</code>```

}

答:
There is a signal for that, emitted by the application:

QGuiApplication::lastWindowClosed()

It looks like what you want to do is intermangle the Qt event loop with your own loop. Here is a hint about how to do that from the Qt docs:

To make your application perform idle processing (i.e. executing a special function whenever there are no pending events), use a QTimer with 0 timeout. More sophisticated idle processing schemes can be achieved using processEvents().

So this is how I would approach this:

Setup a QTimer that connects to a method that does rendering (if window should not close) and restarts the timer

Call a.exec()

In the method called by the timer, if window should close, call a.quit()

Body:
When i close the QT GUI i want the GLFW window to be closed accordingly.

For glfw we can query if window is closed or not by  glfwWindowShouldClose function.

Do we have anything like that in QT where we can keep Querying if the application GUI is closed.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TreeModel model;
    QTApplication w(model);
    int return_code = 0;
    QTApplication.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   // Create the render window
    if (window == NULL)
    {
        QMessageBox msgBox;
        msgBox.setText("Not able to create GL Window");
        msgBox.exec();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();
    if (GLEW_OK != GlewInitResult)   // Check if glew is initialized properly
    {
        glfwTerminate();
    }
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    while (!glfwWindowShouldClose(window))
    {
        // Do Rendering here

    }
    return_code =  a.exec();
    glfwTerminate();
    return return_code;
}

}


问:
A collection of closest values from two arrays
I'm looking for optimization of an algorithm to solve a simple problem which may be hard to explain. I'm not looking for a speed or performance but simplicity and clarity when you read the code. Maybe someone has more clever solution than mine. I imagine one-liner would probably be an overkill.

I have two collections of cells ordered by date. Each of the cell can have a price value. We can assume that there can't be a price in two cells for the same date. I want to have one collection of dates, but where is no price for the date:

which collection have a closest price from the past

if there is no price in the past, look in the future

Here's what I have so far (it gives accurate results):

const array1 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12' },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15', price: 10 },
  { date: '2019-11-16' },
];

const array2 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12', price: 10 },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15' },
  { date: '2019-11-16' },
];

const merged = Object.values(array1).map((element, index) => {
  let filled;
  if (element.price) {
    filled = 1;
  }
  if (array2[index].price) {
    filled = 2;
  }
  if (filled) {
    return {
      date: element.date,
      filled
    }
  } else {
    return {
      date: element.date
    }
  }
});

const first = merged.find(element => element.filled);

let currentFill = first && first.filled;

const emptyMap = merged.map((element, index, array) => {
  if (!element.filled) {
    return {
      date: element.date,
      empty: currentFill
    }
  }
  currentFill = element.filled;
  return element;
})

console.log(emptyMap);```

答:
Here's my spin on this:

const array1 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12' },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15', price: 10 },
  { date: '2019-11-16' },
];

const array2 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12', price: 10 },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15' },
  { date: '2019-11-16' },
];

const mappedToCollection = array1.map((el, i) => ({
  date: el.date,
  //You can just as easily store the actual collection here and not just a number
  collection: (el.price && 1) ||
    (array2[i].price && 2) ||
    undefined,
}));

const firstExactMatch = mappedToCollection.find(el => el.collection);

const closestCollections = mappedToCollection.reduce((acc, el, i) => [
  ...acc,
  {
    date: el.date,
    collection: el.collection ||
      (acc[i-1] && acc[i-1].collection) ||
      (firstExactMatch && firstExactMatch.collection),
    exactMatch: !!el.collection,
  },
], []);

console.log(closestCollections);```

As stated in the question, not the most performant or short solution, but tried to make it readable and explicit.

Body:
Here's my spin on this:

const array1 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12' },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15', price: 10 },
  { date: '2019-11-16' },
];

const array2 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12', price: 10 },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15' },
  { date: '2019-11-16' },
];

const mappedToCollection = array1.map((el, i) => ({
  date: el.date,
  //You can just as easily store the actual collection here and not just a number
  collection: (el.price && 1) ||
    (array2[i].price && 2) ||
    undefined,
}));

const firstExactMatch = mappedToCollection.find(el => el.collection);

const closestCollections = mappedToCollection.reduce((acc, el, i) => [
  ...acc,
  {
    date: el.date,
    collection: el.collection ||
      (acc[i-1] && acc[i-1].collection) ||
      (firstExactMatch && firstExactMatch.collection),
    exactMatch: !!el.collection,
  },
], []);

console.log(closestCollections);

As stated in the question, not the most performant or short solution, but tried to make it readable and explicit.


问:
Unity: Hide Navigation Bar
How do I hide only the navigation bar in an Android app made in Unity?

I've already tried Screen.fullScreen = false, but that shows both the status bar and the navigation bar over the content.

答:
```<code>// Resume Unity
@Override
protected void onResume() {
    super.onResume();
    mUnityPlayer.resume();
    mUnityPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
</code>```

This will hide the navigation panel even if you disable full screen mode in Unity Editor.

Title: Unity: Hide Navigation Bar

Body:
// Resume Unity
@Override
protected void onResume() {
    super.onResume();
    mUnityPlayer.resume();
    mUnityPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

This will hide the navigation panel even if you disable full screen mode in Unity Editor.


问:
String will not split using Regex
As seen in the snippet, I have a Regex that should identify any empty lines. (I'm aware I can just do /n/n, but it doesn't suit my purposes). I've tested it in a word editor, and it picks up every new line when using the find tool. But in JS, I'm still getting the entire file. What am I missing, here?

const mockData = `This is some fake data
with multiple sentences

and line breaks`;

const newArr = mockData.split(/^\s*$/);

console.log(newArr[0]);```

答:
You have a multiline string but aren't using the m (multiline) flag. Without it ^ and $ match the start/end of the entire string, so you'd only split if the entirety of the string was composed of whitespace:

//multiline - all whitespace
const mockData = `

`;

const newArr = mockData.split(/^\s*$/);

console.log(newArr);```
</div>
</div>
</p>

<p>Using the <code>m</code> flag, the <code>^</code> and <code>$</code> characters instead match start/end of <em>each line</em>. So now the regex works to split on lines that are either empty or composed of newline characters:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const mockData = `This is some fake data
with multiple sentences

and line breaks`;

const newArr = mockData.split(/^\s*$/m);

console.log(newArr);</code>```

If you intend to split at newlines and empty lines leaving no blanks, then you can eschew the ^ and $ characters entirely, since they are actually more trouble. The engine might do a split before a newline because that's the end of the line $. So, instead of trying to get around that with more regex, just split on whitespace + a newline or newline + whitespace.

const mockData = `This is some fake data
with multiple sentences

and line breaks`;

const newArr = mockData.split(/\s*[\r\n]+|[\r\n]+\s*/);

console.log(newArr);```

With this you don't need to use the multiline flag, since you never use the behaviour it introduces.

Also, I should note that  [\r\n]+ is a slight cheat on my part. The end of line characters are either \r\n or just \n, you very likely will never encounter a simple \r. However, the proper regex then is \r?\n which I find ugly, especially if you try to repeat it - (\r?\n)+. A character class is ever so slightly inaccurate yet in a way that should never have any effect on accuracy.

Title: String will not split using Regex

Body:
You have a multiline string but aren't using the m (multiline) flag. Without it ^ and $ match the start/end of the entire string, so you'd only split if the entirety of the string was composed of whitespace:

//multiline - all whitespace
const mockData = `

`;

const newArr = mockData.split(/^\s*$/);

console.log(newArr);

Using the m flag, the ^ and $ characters instead match start/end of each line. So now the regex works to split on lines that are either empty or composed of newline characters:

const mockData = `This is some fake data
with multiple sentences

and line breaks`;

const newArr = mockData.split(/^\s*$/m);

console.log(newArr);

If you intend to split at newlines and empty lines leaving no blanks, then you can eschew the ^ and $ characters entirely, since they are actually more trouble. The engine might do a split before a newline because that's the end of the line $. So, instead of trying to get around that with more regex, just split on whitespace + a newline or newline + whitespace.

const mockData = `This is some fake data
with multiple sentences

and line breaks`;

const newArr = mockData.split(/\s*[\r\n]+|[\r\n]+\s*/);

console.log(newArr);

With this you don't need to use the multiline flag, since you never use the behaviour it introduces.

Also, I should note that  [\r\n]+ is a slight cheat on my part. The end of line characters are either \r\n or just \n, you very likely will never encounter a simple \r. However, the proper regex then is \r?\n which I find ugly, especially if you try to repeat it - (\r?\n)+. A character class is ever so slightly inaccurate yet in a way that should never have any effect on accuracy.


问:
What are the variables that determine the number of nodes required in Hyperledger Indy Setup?
As part of one of my project implementation, I have to use Hyperledger Indy for providing digital identity to users. The estimated number of users on the platform is 20k. I am stuck on determining what must be the number of nodes required to run Hyperledger Indy for efficient use on production.</p>

答:
The number of nodes depends on the number of faulty nodes you want to permit. To support f faults in the system, you need 3f+1 total nodes. So if you are OK with only 2 nodes failing at any one time, you need f=2 or 7 total nodes. The practical limit has found to be f=8 or 25 total nodes. That balances a robust network with the speed of consensus.

How that relates to the number of users on the platform is a different question. It depends on (a) how many issuers, and (b) how much revocation is happening.
If there is only one issuer and no revocation, there would only be 3 extra transactions beyond the genesis transactions. Not many...