问:
Bootstrap 4 Navbar with container, dropdown alignment
I would like to limit the contents of the main navbar with a container, I saw it done in a video and I also read in a tutorial that can be done, but is it so? In both cases they did not use dropdowns. The content is correctly aligned to the right and left, but with desktop resolutions larger than the container the dropdown that I have all the way to the right, appears aligned to the page, not to the container.

The dropdown uses a class dropdown-menu-right, which setsleft: auto and right: 0, it makes sense that it is aligned to the page, obviously if I remove it it is completely aligned to the left of the page, there is a way with bootstrap classes, without strange hacks, to keep it aligned to the container?

I'm using svelte with sveltestrap, the generated html seems to me like a normal navbar, but I might have missed something, I've been banging my head for a while.

svelte repl

答:
Add class position-relative to container. Menu will align according to container.</p>

```<code><div class="container position-relative"></div>
</code>```

Body:
Add class position-relative to container. Menu will align according to container.

<div class="container position-relative"></div>


来源: stackexchange

问:
Filter intermediary ManytoMany django with negation
This question is related to: Filter intermediary ManytoMany django

```<code>class Ingredient(Model):
    name = CharField(max_length=55, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Product(Model):
    name = CharField(max_length=55)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name', )

class ProductIngredient(Model):
    product = ForeignKey(Product, on_delete=CASCADE, related_name='product_ingredients')
    ingredient = ForeignKey(Ingredient, on_delete=CASCADE)
    optional = BooleanField(default=False)

    class Meta:
        unique_together = (('product', 'ingredient'),)
        ordering = ('product__name',)

    def __str__(self):
        return f'{self.product} - {self.ingredient}'
</code>```

I want to make two queries:

select all products, whose ingredients don't contain strawberry AND milk

select all products, whose ingredients don't contain strawberry OR milk

In this case I'm totally lost.

答:
Referring to your linked question you could use Q objects with an .exclude() instead of a .filter(). You can also negate Q objects by prefixing with a tilde (~):

Products with ingredients not containing strawberry AND milk

```<code>.filter(
    ~Q(product__ingredients__ingredient__name='strawberry') &
    ~Q(product__ingredients__ingredient__name='milk')
)
</code>```

Products with ingredients not containing strawberry OR milk

```<code>.filter(~Q(product__ingredients__ingredient__name__in=['strawberry', 'milk']))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This question is related to: Filter intermediary ManytoMany django

class Ingredient(Model):
    name = CharField(max_length=55, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Product(Model):
    name = CharField(max_length=55)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name', )

class ProductIngredient(Model):
    product = ForeignKey(Product, on_delete=CASCADE, related_name='product_ingredients')
    ingredient = ForeignKey(Ingredient, on_delete=CASCADE)
    optional = BooleanField(default=False)

    class Meta:
        unique_together = (('product', 'ingredient'),)
        ordering = ('product__name',)

    def __str__(self):
        return f'{self.product} - {self.ingredient}'

I want to make two queries:

select all products, whose ingredients don't contain strawberry AND milk

select all products, whose ingredients don't contain strawberry OR milk

In this case I'm totally lost.

Body:
Referring to your linked question you could use Q objects with an .exclude() instead of a .filter(). You can also negate Q objects by prefixing with a tilde (~):

Products with ingredients not containing strawberry AND milk

.filter(
    ~Q(product__ingredients__ingredient__name='strawberry') &
    ~Q(product__ingredients__ingredient__name='milk')
)

Products with ingredients not containing strawberry OR milk

.filter(~Q(product__ingredients__ingredient__name__in=['strawberry', 'milk']))


问:
how to handle React axios how to handle net::ERR_CONNECTION_REFUSED
It was asked before, but if I follow the solution still in the console there is an uncouth error:-

```<code>    getExchangeAmount(){
  var url = 'http://localhost:8080/excurrency?currency='+this.state.currency+
            '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}
</code>```

in the console:-

GET
  http://localhost:8080/excurrency?currency=EGP&exCurrency=EGP&amount=1
  net::ERR_CONNECTION_REFUSED

The above is in red which is an error. how to avoid or catch this?

答:
if you are using a node server so install cors package on the server side:

```<code>npm i cors --save
</code>```

in index.js of server side:

```<code>const cors= require('cors');
app.use(cors());
</code>```

then your code shall work..

if you are not using a node server so try this:

```<code>    getExchangeAmount(){
  var url = '/excurrency?currency='+this.state.currency+
            '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}
</code>```

Body:
It was asked before, but if I follow the solution still in the console there is an uncouth error:-

    getExchangeAmount(){
  var url = 'http://localhost:8080/excurrency?currency='+this.state.currency+
            '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}

in the console:-

GET
  http://localhost:8080/excurrency?currency=EGP&exCurrency=EGP&amount=1
  net::ERR_CONNECTION_REFUSED

The above is in red which is an error. how to avoid or catch this?

Body:
if you are using a node server so install cors package on the server side:

npm i cors --save

in index.js of server side:

const cors= require('cors');
app.use(cors());

then your code shall work..

if you are not using a node server so try this:

    getExchangeAmount(){
  var url = '/excurrency?currency='+this.state.currency+
            '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}


问:
How to Trigger, based on mouse position, variable fonts?
I was looking to trigger different sections with a variable font based on my mouse movement.

For the first section, everything looks great, but when I tried to trigger the second section, it does not work as I expected since it is connected to the first one I guess.

I would need to make the section working independently and in the correct way (to have an idea see section one how is reacting in debug mode)

I was wondering what I have to modify in my Javascript code to make my snippet work with all the sections I want, working independently with their respective variable font interaction. Any ideas?

```<code>  var x = e.pageX - $(this).offset().left;
  var y = e.pageY;
  var $tlSquare = $('.division--top.division--left');
  var $trSquare = $('.division--top.division--right');
  var $blSquare = $('.division--bottom.division--left');
  var $brSquare = $('.division--bottom.division--right');
  var squareWidth = $(this).width(),
    squareHeight = $(this).height();

  $tlSquare.width(x).height(y);
  $trSquare.width(squareWidth - x).height(y);
  $blSquare.width(x).height(squareHeight - y);
  $brSquare.width(squareWidth - x).height(squareHeight - y);

  stretchLetter(false);
});

stretchLetter(false);

$('.square').on('mouseleave', function() {
  $('.division').width('50%').height('50%');
  $('.letter').css('transform', '');
  stretchLetter(false);
});

function stretchLetter(animation) {
  $('.letter').each(function() {
    var parentWidth = $(this).parent().width();
    var parentHeight = $(this).parent().height();
    var thisWidth = $(this).width();
    var thisHeight = $(this).height();
    var widthPercent = parentWidth / thisWidth;
    var heightPercent = parentHeight / thisHeight;
    var timing = animation == true ? .5 : 0;

    TweenMax.to($(this), timing, {
      scaleX: widthPercent,
      scaleY: heightPercent
    })
    //$(this).css('transform', 'scalex('+ widthPercent +') scaley('+ heightPercent +')');
  });
}
</code>```

```<code>body,
html {
  margin: 0;
  padding: 0;
  font-weight: bold;
  font-family: helvetica;
}

section {
  height: 200px;
  background: blue;
  color: white;
  font-size: 28px;
}

.wrapper {
  display: flex;
  justify-content: center;
  /*justify-content: flex-end;*/
  width: 100%;
  height: 100vh;
  //background-color: blue;
  overflow: hidden;
}

.square {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: black;
}

.square-2 {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: yellow;
}

.division {
  //display: flex;
  //align-items: center;
  //justify-content: center;
  width: 50%;
  height: 50%;
  //background-color: red;
  //border: 1px solid white;
  box-sizing: border-box;
}

.letter {
  cursor: -webkit-grab;
  cursor: grab;
}

.letter {
  display: inline-block;
  font-size: 50vh;
  margin: 0;
  padding: 0;
  line-height: .8;
  transform-origin: top left;
  color: white;
}

/* .division:nth-child(1){
    background-color: blue;
}
.division:nth-child(2){
    background-color: red;
}
.division:nth-child(3){
    background-color: green;
}
.division:nth-child(4){
    background-color: orange;
} */

.circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 1px solid white;
  background-color: blue;
  box-sizing: border-box;
}
</code>```

```<code><section>SECTION-01</section>
<main>
  <div class="wrapper">
    <div class="square">
      <div class="division division--top division--left">
        <div class="letter">L</div>
      </div>
      <div class="division division--top division--right">
        <div class="letter">A</div>
      </div>
      <div class="division division--bottom division--left">
        <div class="letter">S</div>
      </div>
      <div class="division division--bottom division--right">
        <div class="letter">T</div>
      </div>
    </div>
</main>
  <section>SECTION-02</section>
  <div class="wrapper">
    <div class="square">
      <div class="division division--top division--left">
        <div class="letter">F</div>
      </div>
      <div class="division division--top division--right">
        <div class="letter">A</div>
      </div>
      <div class="division division--bottom division--left">
        <div class="letter">S</div>
      </div>
      <div class="division division--bottom division--right">
        <div class="letter">T</div>
      </div>
    </div>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</code>```

https://jsfiddle.net/CAT999/ohaf61qp/5/

答:
Updated the snippet to work on individual block. I hope this will be helpful

var $ = jQuery
$('.square').on('mousemove', function(e) {
  var x = e.pageX - $(this).offset().left;
  var y = e.pageY;
  var $tlSquare = $(this).find('.division--top.division--left');
  var $trSquare = $(this).find('.division--top.division--right');
  var $blSquare = $(this).find('.division--bottom.division--left');
  var $brSquare = $(this).find('.division--bottom.division--right');

  var squareWidth = $(this).width(),
    squareHeight = $(this).height();

  $tlSquare.width(x).height(y);
  $trSquare.width(squareWidth - x).height(y);
  $blSquare.width(x).height(squareHeight - y);
  $brSquare.width(squareWidth - x).height(squareHeight - y);
  const childrens = $(this).children().children();
  stretchLetter(false, childrens);
});

/* stretchLetter(false); */

$('.square').on('mouseleave', function() {
  const child = $(this).children();
  child.each(function() {
    $(this).width('50%').height('50%');
  })
  child.children().each(function() {

    $(this).css('transform', '');
  })
  const childrens = $(this).children().children();
  stretchLetter(false, childrens);
});

function stretchLetter(animation, el) {
  el.each(function() {
    var parentWidth = $(this).parent().width();
    var parentHeight = $(this).parent().height();
    var thisWidth = $(this).width();
    var thisHeight = $(this).height();

    var widthPercent = parentWidth / thisWidth;
    var heightPercent = parentHeight / thisHeight;

    var timing = animation == true ? .5 : 0;

    TweenMax.to($(this), timing, {
      scaleX: widthPercent,
      scaleY: heightPercent
    })
    //$(this).css('transform', 'scalex('+ widthPercent +') scaley('+ heightPercent +')');
  });
}
$(document).ready(function() {
  const el = $(".square")
    .children()
    .children();
  stretchLetter(false, el);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,
html {
  margin: 0;
  padding: 0;
  font-weight: bold;
  font-family: helvetica;
}

section {
  height: 200px;
  background: blue;
  color: white;
  font-size: 28px;
}

.wrapper {
  display: flex;
  justify-content: center;
  /*justify-content: flex-end;*/
  width: 100%;
  height: 100vh;
  //background-color: blue;
  overflow: hidden;
}

.square {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: black;

}

.square-2 {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: yellow;

}

.division {
  //display: flex;
  //align-items: center;
  //justify-content: center;
  width: 50%;
  height: 50%;
  //background-color: red;
  //border: 1px solid white;
  box-sizing: border-box;
}

.letter {
  cursor: -webkit-grab;
  cursor: grab;
}

.letter {
  display: inline-block;
  font-size: 50vh;
  margin: 0;
  padding: 0;
  line-height: .8;
  transform-origin: top left;
  color: white;
}

/* .division:nth-child(1){
 background-color: blue;
}
.division:nth-child(2){
 background-color: red;
}
.division:nth-child(3){
 background-color: green;
}
.division:nth-child(4){
 background-color: orange;
} */

.circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 1px solid white;
  background-color: blue;
  box-sizing: border-box;
}</code>```

SECTION-01

L

A

S

T

SECTION-02

F

A

S

T

  ```

OwnerDisplayName: CATT

Body:
I was looking to trigger different sections with a variable font based on my mouse movement.

For the first section, everything looks great, but when I tried to trigger the second section, it does not work as I expected since it is connected to the first one I guess.

I would need to make the section working independently and in the correct way (to have an idea see section one how is reacting in debug mode)

I was wondering what I have to modify in my Javascript code to make my snippet work with all the sections I want, working independently with their respective variable font interaction. Any ideas?

  var x = e.pageX - $(this).offset().left;
  var y = e.pageY;
  var $tlSquare = $('.division--top.division--left');
  var $trSquare = $('.division--top.division--right');
  var $blSquare = $('.division--bottom.division--left');
  var $brSquare = $('.division--bottom.division--right');
  var squareWidth = $(this).width(),
    squareHeight = $(this).height();

  $tlSquare.width(x).height(y);
  $trSquare.width(squareWidth - x).height(y);
  $blSquare.width(x).height(squareHeight - y);
  $brSquare.width(squareWidth - x).height(squareHeight - y);

  stretchLetter(false);
});

stretchLetter(false);

$('.square').on('mouseleave', function() {
  $('.division').width('50%').height('50%');
  $('.letter').css('transform', '');
  stretchLetter(false);
});

function stretchLetter(animation) {
  $('.letter').each(function() {
    var parentWidth = $(this).parent().width();
    var parentHeight = $(this).parent().height();
    var thisWidth = $(this).width();
    var thisHeight = $(this).height();
    var widthPercent = parentWidth / thisWidth;
    var heightPercent = parentHeight / thisHeight;
    var timing = animation == true ? .5 : 0;

    TweenMax.to($(this), timing, {
      scaleX: widthPercent,
      scaleY: heightPercent
    })
    //$(this).css('transform', 'scalex('+ widthPercent +') scaley('+ heightPercent +')');
  });
}

body,
html {
  margin: 0;
  padding: 0;
  font-weight: bold;
  font-family: helvetica;
}

section {
  height: 200px;
  background: blue;
  color: white;
  font-size: 28px;
}

.wrapper {
  display: flex;
  justify-content: center;
  /*justify-content: flex-end;*/
  width: 100%;
  height: 100vh;
  //background-color: blue;
  overflow: hidden;
}

.square {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: black;
}

.square-2 {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: yellow;
}

.division {
  //display: flex;
  //align-items: center;
  //justify-content: center;
  width: 50%;
  height: 50%;
  //background-color: red;
  //border: 1px solid white;
  box-sizing: border-box;
}

.letter {
  cursor: -webkit-grab;
  cursor: grab;
}

.letter {
  display: inline-block;
  font-size: 50vh;
  margin: 0;
  padding: 0;
  line-height: .8;
  transform-origin: top left;
  color: white;
}

/* .division:nth-child(1){
    background-color: blue;
}
.division:nth-child(2){
    background-color: red;
}
.division:nth-child(3){
    background-color: green;
}
.division:nth-child(4){
    background-color: orange;
} */

.circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 1px solid white;
  background-color: blue;
  box-sizing: border-box;
}

SECTION-01

L

A

S

T

SECTION-02

F

A

S

T

https://jsfiddle.net/CAT999/ohaf61qp/5/

Body:
Updated the snippet to work on individual block. I hope this will be helpful

var $ = jQuery
$('.square').on('mousemove', function(e) {
  var x = e.pageX - $(this).offset().left;
  var y = e.pageY;
  var $tlSquare = $(this).find('.division--top.division--left');
  var $trSquare = $(this).find('.division--top.division--right');
  var $blSquare = $(this).find('.division--bottom.division--left');
  var $brSquare = $(this).find('.division--bottom.division--right');

  var squareWidth = $(this).width(),
    squareHeight = $(this).height();

  $tlSquare.width(x).height(y);
  $trSquare.width(squareWidth - x).height(y);
  $blSquare.width(x).height(squareHeight - y);
  $brSquare.width(squareWidth - x).height(squareHeight - y);
  const childrens = $(this).children().children();
  stretchLetter(false, childrens);
});

/* stretchLetter(false); */

$('.square').on('mouseleave', function() {
  const child = $(this).children();
  child.each(function() {
    $(this).width('50%').height('50%');
  })
  child.children().each(function() {

    $(this).css('transform', '');
  })
  const childrens = $(this).children().children();
  stretchLetter(false, childrens);
});

function stretchLetter(animation, el) {
  el.each(function() {
    var parentWidth = $(this).parent().width();
    var parentHeight = $(this).parent().height();
    var thisWidth = $(this).width();
    var thisHeight = $(this).height();

    var widthPercent = parentWidth / thisWidth;
    var heightPercent = parentHeight / thisHeight;

    var timing = animation == true ? .5 : 0;

    TweenMax.to($(this), timing, {
      scaleX: widthPercent,
      scaleY: heightPercent
    })
    //$(this).css('transform', 'scalex('+ widthPercent +') scaley('+ heightPercent +')');
  });
}
$(document).ready(function() {
  const el = $(".square")
    .children()
    .children();
  stretchLetter(false, el);
});

body,
html {
  margin: 0;
  padding: 0;
  font-weight: bold;
  font-family: helvetica;
}

section {
  height: 200px;
  background: blue;
  color: white;
  font-size: 28px;
}

.wrapper {
  display: flex;
  justify-content: center;
  /*justify-content: flex-end;*/
  width: 100%;
  height: 100vh;
  //background-color: blue;
  overflow: hidden;
}

.square {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: black;

}

.square-2 {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: yellow;

}

.division {
  //display: flex;
  //align-items: center;
  //justify-content: center;
  width: 50%;
  height: 50%;
  //background-color: red;
  //border: 1px solid white;
  box-sizing: border-box;
}

.letter {
  cursor: -webkit-grab;
  cursor: grab;
}

.letter {
  display: inline-block;
  font-size: 50vh;
  margin: 0;
  padding: 0;
  line-height: .8;
  transform-origin: top left;
  color: white;
}

/* .division:nth-child(1){
 background-color: blue;
}
.division:nth-child(2){
 background-color: red;
}
.division:nth-child(3){
 background-color: green;
}
.division:nth-child(4){
 background-color: orange;
} */

.circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 1px solid white;
  background-color: blue;
  box-sizing: border-box;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>SECTION-01</section>
<main>
  <div class="wrapper">
    <div class="square">
      <div class="division division--top division--left">
        <div class="letter">L</div>
      </div>
      <div class="division division--top division--right">
        <div class="letter">A</div>
      </div>

      <div class="division division--bottom division--left">
        <div class="letter">S</div>
      </div>
      <div class="division division--bottom division--right">
        <div class="letter">T</div>
      </div>
    </div>
</main>
<section>SECTION-02</section>

<!--FOR SINGLE USE THIS ONE <div class="wrapper">
 <div class="square">
  <div class="division division--top division--left">
   <div class="letter">M</div>
  </div>
  <div class="division division--top division--right">
   <div class="letter">A</div>
  </div>
  <div class="division division--bottom division--left">
   <div class="letter">T</div>
  </div>
  <div class="division division--bottom division--right">
   <div class="letter">T</div>
  </div>
 </div>
</div-->

<div class="wrapper">
  <div class="square">
    <div class="division division--top division--left">
      <div class="letter">F</div>
    </div>
    <div class="division division--top division--right">
      <div class="letter">A</div>
    </div>

    <div class="division division--bottom division--left">
      <div class="letter">S</div>
    </div>
    <div class="division division--bottom division--right">
      <div class="letter">T</div>
    </div>
  </div>
  </main>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"></script>


问:
`psql` command to view all existing tablespaces?
What's the psql command to view all existing tablespaces?

\l+ displays all existing databases with their configured tablespace, but it won't display tablespaces which have been created but don't yet contain a database.

答:
Here is the psql command that you can use:</p>

```<code>postgres=# \db+
                                      List of tablespaces
        Name    |  Owner   | Location | Access privileges | Options |  Size  | Description
    ------------+----------+----------+-------------------+---------+--------+-------------
     pg_default | postgres |          |                   |         | 448 MB |
     pg_global  | postgres |          |                   |         | 631 kB |
    (2 rows)
</code>```

Body:
Here is the psql command that you can use:

postgres=# \db+
                                      List of tablespaces
        Name    |  Owner   | Location | Access privileges | Options |  Size  | Description
    ------------+----------+----------+-------------------+---------+--------+-------------
     pg_default | postgres |          |                   |         | 448 MB |
     pg_global  | postgres |          |                   |         | 631 kB |
    (2 rows)


问:
Powershell loop that counts down
I'm trying to print a warning to let the user know that 0 isn't a valid option for an assignment for class. Just started learning about powershell and can't find any help on how to set a parameter like this.

Assignment is 3.)   Write a loop that calculates $num^2 for each iteration and prints the value using Write-Host. This loop must execute at least once and beginning counting down. When $num = 0, the loop should end. Prevent this loop from receiving $num as 0 as this will cause an infinite loop. If 0 is set as $num, print a warning to let the user know that 0 isn’t a valid option.

So far this is what I have

$num=Read-Host -Prompt 'Enter a number'
do
{
   write-host $num
   $num--
}
until($num -eq -1)
```

Any help would be greatly appreciated

答:
Try this:</p>

```<code>$num = Read-Host -Prompt 'Enter a number'
$num = [int]::Parse( $num )

do
{
   write-host "$num square is $([Math]::Pow($num,2))"
}
while(--$num)
</code>```

Title: Powershell loop that counts down

Body:
I'm trying to print a warning to let the user know that 0 isn't a valid option for an assignment for class. Just started learning about powershell and can't find any help on how to set a parameter like this.

Assignment is 3.)   Write a loop that calculates $num^2 for each iteration and prints the value using Write-Host. This loop must execute at least once and beginning counting down. When $num = 0, the loop should end. Prevent this loop from receiving $num as 0 as this will cause an infinite loop. If 0 is set as $num, print a warning to let the user know that 0 isn’t a valid option.

So far this is what I have

$num=Read-Host -Prompt 'Enter a number'
do
{
   write-host $num
   $num--
}
until($num -eq -1)

Any help would be greatly appreciated

Body:
Try this:

$num = Read-Host -Prompt 'Enter a number'
$num = [int]::Parse( $num )

do
{
   write-host "$num square is $([Math]::Pow($num,2))"
}
while(--$num)


问:
Best library to implement jsonrpc 2.0 in java with bidirectional support
I am in search of a library to implement jsonrpc 2.0 in java with bidirecional support. I have found these two (JJsonRpc, jsonrpc4j) some recommendation of which one is better?</p>

答:
In the end I decided to write my own integration to the api json rpc using

OKHttp for HTTP connections and Jackson Core for fast JSON serialisation / deserialisation

Implementation Code:

https://github.com/AraguaneyBits/bitcoinrpc4java/blob/master/src/main/java/com/araguaneybits/crypto/bitcoinrpc/methods/BtcRpcGateway.java


问:
How to Calculate change between rows in Pandas Data Frame
Suppose I have a daily sales record column. And from it I want to create two new columns. That keep track of the change from a month a go. For each day on the record. How would I go about doing this in Pandas Data frame. new to pandas and stuck here.
here is a sample data set

And what I am looking for is to create a new column "Change from a month ago",
which will tracks the difference between in daily sales between today and 30 days ago.

答:
You may want to invent your own convention for what is one month before but the common one is already implemented if pd.DateOffset().

If you use it, you can build a delta column that way:

```<code>df['delta'] = df['Daily Sales'] - df.merge(df[['Date', 'Daily Sales']]
                                           .assign(M1 = df['Date']
                                             + pd.DateOffset(months=1))
             .drop_duplicates('M1').drop(columns='Date')
             .rename({'Daily Sales': 'prev'}, axis=1),
         left_on='Date', right_on='M1', how='left')['prev']
</code>```

The decomposition of the above (magic) formule is:

extract only the Date and Dayly Sailes columns for further processing

add one month to the Date column and name it M1

drop duplicates on that date that could occur because of the use of DateOffset

rename the Daily Sales command to prev

merge it by common dates (using M1 column) with the original dataframe

the one month difference is the difference between the Daily Sailes column of the original dataframe and the prev column in the merged one.

Body:
You may want to invent your own convention for what is one month before but the common one is already implemented if pd.DateOffset().

If you use it, you can build a delta column that way:

df['delta'] = df['Daily Sales'] - df.merge(df[['Date', 'Daily Sales']]
                                           .assign(M1 = df['Date']
                                             + pd.DateOffset(months=1))
             .drop_duplicates('M1').drop(columns='Date')
             .rename({'Daily Sales': 'prev'}, axis=1),
         left_on='Date', right_on='M1', how='left')['prev']

The decomposition of the above (magic) formule is:

extract only the Date and Dayly Sailes columns for further processing

add one month to the Date column and name it M1

drop duplicates on that date that could occur because of the use of DateOffset

rename the Daily Sales command to prev

merge it by common dates (using M1 column) with the original dataframe

the one month difference is the difference between the Daily Sailes column of the original dataframe and the prev column in the merged one.


问:
Intellij thinks TypeScript function names are properties
After wrestling with a part of my angular app that just wouldn't work I finally found the culprit - Intellij for some reason mixes up the functions inside TS classes with properties. Example below:

get name() is clearly a function. But Intellij flags it as "unused property name". More so, once or twice the property name accessed with the getter/setter would change by itself if I changed just the function name - without doing it via refactor.

The same "unused property name" appears on top of all my properties as well. Some properties may show that tooltip, while others may not. Sometimes even properties that are not greyed out will show that tooltip.

I have disabled all my plugins and invalidated my cache. Tried to manually write the set/get instead of generation. Nothing works.

UPDATE: Tried doing this with VScode and it worked.

I then imported the same project to Intellij and it gave another error, but now something about how the property is recursive:

答:
There is nothing technically wrong in calling getters/setters properties, they are 'accessor properties' - essentially functions that work on getting and setting a value, but look like regular properties to an external code. And marking them unused is expected if they are not used anywhere in your code - this is a way Unused global symbol inspection works.

If you don't like public properties/variables/function to be reported as unused, try disabling the Unused global symbol in Settings | Editor | Inspections | JavaScript and TypeScript | Unused symbols


问:
Is it possible to select multiple offsets with SQL
I'd like to select multiple offsets with a single SELECT SQL query. Is this possible?

For example, let's say I have a table of non-continuous dates called dates.

```<code>date
----------
2020-01-01
2020-01-09
2020-01-16
2020-01-22
2020-01-29
2020-02-01
2020-02-04
2020-02-10
2020-02-13
</code>```

I'd like to select the 1st, 4th and 7th offsets from the most recent date. In this example, the query should return:

```<code>offset    date
------    -------
1         2020-02-10
4         2020-01-29
7         2020-01-09
</code>```

Ideally, I would like to write the query as follows:

```<code>SELECT
    *
FROM
    dates
ORDER BY
    date DESC
OFFSET
    (1, 4, 7)
</code>```

Obviously, this does not compile due to the LIMIT/OFFSET clause.

I could try a UNION, but not only is this extremely verbose it does not work because the LIMIT/OFFSET clause must come after the last UNION.

FAIL:

```<code>SELECT 1, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 1
UNION
SELECT 4, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 4
UNION
SELECT 7, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 7
</code>```

Is there an elegant query to do this? The other option I can think of is to use row_number() with a window function, and then do something like SELECT * WHERE row_number IN (1, 4, 7). HOWEVER, in some cases I am forced to use an older version of SQLite that does not support window functions.

答:
I think you want row_number():

```<code>select t.*
from (select t.*,
             row_number() over (order by date desc) as offset
      from t
      where date < date('now')  -- you might want local time
     ) t
where offset in (1, 4, 7);
</code>```

Body:
I'd like to select multiple offsets with a single SELECT SQL query. Is this possible?

For example, let's say I have a table of non-continuous dates called dates.

date
----------
2020-01-01
2020-01-09
2020-01-16
2020-01-22
2020-01-29
2020-02-01
2020-02-04
2020-02-10
2020-02-13

I'd like to select the 1st, 4th and 7th offsets from the most recent date. In this example, the query should return:

offset    date
------    -------
1         2020-02-10
4         2020-01-29
7         2020-01-09

Ideally, I would like to write the query as follows:

SELECT
    *
FROM
    dates
ORDER BY
    date DESC
OFFSET
    (1, 4, 7)

Obviously, this does not compile due to the LIMIT/OFFSET clause.

I could try a UNION, but not only is this extremely verbose it does not work because the LIMIT/OFFSET clause must come after the last UNION.

FAIL:

SELECT 1, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 1
UNION
SELECT 4, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 4
UNION
SELECT 7, date FROM dates ORDER BY date DESC LIMIT 1 OFFSET 7

Is there an elegant query to do this? The other option I can think of is to use row_number() with a window function, and then do something like SELECT * WHERE row_number IN (1, 4, 7). HOWEVER, in some cases I am forced to use an older version of SQLite that does not support window functions.

Body:
I think you want row_number():

select t.*
from (select t.*,
             row_number() over (order by date desc) as offset
      from t
      where date < date('now')  -- you might want local time
     ) t
where offset in (1, 4, 7);


问:
Django - Trying to pass an instance of a model field to a form field
I'm going to do my best not to sound like a real dummy, but no promises. I am a paramedic and I'm trying to make an app to document unit checks electronically.I have a model field that is foreign keyed to a few other models in my project. This field designates the unit the user is staffing for that day. I want the user to choose the unit he/she is staffing that day and have that information auto-fill any forms filled out for that session. I've tried storing the object using sessions and I get this "Object of type 'MedicUnit' is not JSON serializable". I've used the model_to_dict method and tried to pass the string of the unit name through the form_valid method but I get this "Cannot assign "'Medic 2'": "DailyCheck.medic_unit_number" must be a "MedicUnit" instance." I'm relatively new to programming and Django and this seems like a very easy problem to fix, but my google searching skills are not getting me anywhere. Here is my code:

Model.py for the origin of the unit_name model field

```<code>class MedicUnit(models.Model):
    unit_name = models.CharField(max_length=50, default='')
    is_active = models.BooleanField(default=True)

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

Model.py for one of the foreign key references to the unit_name

```<code>class DailyCheck(models.Model):
    daily_user = models.ForeignKey(User, on_delete=models.PROTECT)
    record_date = models.DateTimeField(auto_now=True)
    medic_unit_number = models.ForeignKey('components.MedicUnit', related_name='medic_unit_number', on_delete=models.PROTECT, default='')
    unit_property_number = models.ForeignKey('components.Vehicle', related_name='unit_property_number', on_delete=models.PROTECT, default='')
    mileage = models.IntegerField(default=0)
    narc_seal_number = models.IntegerField(default=0)
    emergency_lights = models.BooleanField()
    driving_lights = models.BooleanField()
    red_bag = models.BooleanField()
    LP_15 = models.BooleanField()
    BLS_bag = models.BooleanField()
    RTF_bag = models.BooleanField()
    suction = models.BooleanField()
    oxygen = models.BooleanField()
    free_text = models.TextField(default='')
</code>```

views.py for the directly above model

```<code>def check_home_view(request):
    if request.method == 'POST':
        form = ChooseMedicUnit(request.POST or None)
        if form.is_valid():
            unit_name = form.cleaned_data.get('medic_unit_number')
            request.session['unit_name'] = model_to_dict(unit_name)
            print(request.session['unit_name'])
            return redirect('daily')
    else:
        form = ChooseMedicUnit()
    return render(request, 'checks/checks_home.html', {'form':form})

class checkAdd(CreateView):
    model = DailyCheck
    fields = ['unit_property_number', 'mileage', 'narc_seal_number', 'emergency_lights', 'driving_lights', 'red_bag', 'LP_15', 'BLS_bag', 'RTF_bag', 'suction', 'oxygen', 'free_text']
    success_url = '/checks'

    def form_valid(self, form):
        form.instance.daily_user = self.request.user
        form.instance.medic_unit_number = self.request.session['unit_name']['unit_name']
        return super().form_valid(form)
</code>```

forms.py

```<code>class ChooseMedicUnit(forms.ModelForm):
    class Meta:
        model = DailyCheck
        fields = ['medic_unit_number']
</code>```

答:
Thank you so much for the answer Andrey. I will try that too. I found that all I had to do was  import the MedicUnit model to my view and change my form_valid method to the following:

```<code>def form_valid(self, form):
        form.instance.daily_user = self.request.user
        form.instance.medic_unit_number = MedicUnit.ojbects.get(pk=self.request.session['unit_name']['id'])
        return super().form_valid(form)
</code>```

Apparently sessions cannot store objects since after Django 1.5 I think. Someone may have to fact check me on that. So I referenced an instance of the object with a dictionary value from the model_to_dict data stored in the session with the MedicUnit.object.get call.

If you are having the same problem, you can print the session info to the terminal with a print statement just like in my check_home_view function view. I used that info to see what key was necessary to call primary key number.

I will check Andrey's solution later today and see how well that works. It seems a bit cleaner than my solution.

Body:
I'm going to do my best not to sound like a real dummy, but no promises. I am a paramedic and I'm trying to make an app to document unit checks electronically.I have a model field that is foreign keyed to a few other models in my project. This field designates the unit the user is staffing for that day. I want the user to choose the unit he/she is staffing that day and have that information auto-fill any forms filled out for that session. I've tried storing the object using sessions and I get this "Object of type 'MedicUnit' is not JSON serializable". I've used the model_to_dict method and tried to pass the string of the unit name through the form_valid method but I get this "Cannot assign "'Medic 2'": "DailyCheck.medic_unit_number" must be a "MedicUnit" instance." I'm relatively new to programming and Django and this seems like a very easy problem to fix, but my google searching skills are not getting me anywhere. Here is my code:

Model.py for the origin of the unit_name model field

class MedicUnit(models.Model):
    unit_name = models.CharField(max_length=50, default='')
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.unit_name

Model.py for one of the foreign key references to the unit_name

class DailyCheck(models.Model):
    daily_user = models.ForeignKey(User, on_delete=models.PROTECT)
    record_date = models.DateTimeField(auto_now=True)
    medic_unit_number = models.ForeignKey('components.MedicUnit', related_name='medic_unit_number', on_delete=models.PROTECT, default='')
    unit_property_number = models.ForeignKey('components.Vehicle', related_name='unit_property_number', on_delete=models.PROTECT, default='')
    mileage = models.IntegerField(default=0)
    narc_seal_number = models.IntegerField(default=0)
    emergency_lights = models.BooleanField()
    driving_lights = models.BooleanField()
    red_bag = models.BooleanField()
    LP_15 = models.BooleanField()
    BLS_bag = models.BooleanField()
    RTF_bag = models.BooleanField()
    suction = models.BooleanField()
    oxygen = models.BooleanField()
    free_text = models.TextField(default='')

views.py for the directly above model

def check_home_view(request):
    if request.method == 'POST':
        form = ChooseMedicUnit(request.POST or None)
        if form.is_valid():
            unit_name = form.cleaned_data.get('medic_unit_number')
            request.session['unit_name'] = model_to_dict(unit_name)
            print(request.session['unit_name'])
            return redirect('daily')
    else:
        form = ChooseMedicUnit()
    return render(request, 'checks/checks_home.html', {'form':form})

class checkAdd(CreateView):
    model = DailyCheck
    fields = ['unit_property_number', 'mileage', 'narc_seal_number', 'emergency_lights', 'driving_lights', 'red_bag', 'LP_15', 'BLS_bag', 'RTF_bag', 'suction', 'oxygen', 'free_text']
    success_url = '/checks'

    def form_valid(self, form):
        form.instance.daily_user = self.request.user
        form.instance.medic_unit_number = self.request.session['unit_name']['unit_name']
        return super().form_valid(form)

forms.py

class ChooseMedicUnit(forms.ModelForm):
    class Meta:
        model = DailyCheck
        fields = ['medic_unit_number']

Body:
Thank you so much for the answer Andrey. I will try that too. I found that all I had to do was  import the MedicUnit model to my view and change my form_valid method to the following:

def form_valid(self, form):
        form.instance.daily_user = self.request.user
        form.instance.medic_unit_number = MedicUnit.ojbects.get(pk=self.request.session['unit_name']['id'])
        return super().form_valid(form)

Apparently sessions cannot store objects since after Django 1.5 I think. Someone may have to fact check me on that. So I referenced an instance of the object with a dictionary value from the model_to_dict data stored in the session with the MedicUnit.object.get call.

If you are having the same problem, you can print the session info to the terminal with a print statement just like in my check_home_view function view. I used that info to see what key was necessary to call primary key number.

I will check Andrey's solution later today and see how well that works. It seems a bit cleaner than my solution.


问:
DNS resolving of Azure VMs from on-premise network
I have a problem with DNS resolving Azure machines from on-premise network connected with VPN to VMs' virtual network. In other cloud providers there are solutions to this problem, but I can't find one in Azure. In AWS I could create Inbound Route53 Endpoint which gives me IPs in the VPC that machines from my on-premise network can reach. In GCP there is forwarding DNS server policy. Is there any similar solutions in Azure ?</p>

答:
To resolve the DNS name of Azure VMs from an on-premise network, you need forward queries to your managed DNS proxy server in the corresponding virtual network, the proxy server forwards queries to Azure for resolution. The DNS servers in the virtual networks can forward DNS queries to the recursive resolvers (168.63.129.16) in Azure.

Note that Azure Private Zones does not help in this situation, you have to use your own DNS proxy server. Read here.

For more references:

Name resolution for resources in Azure virtual networks

Name resolution using your own DNS server


问:
Add new value to an existing object with a variable content as the key?
I have an object 'unit', whose keys are different teams. Teams' keys are employees. Each employee is an object with its own fields. I'm looping through some files, getting each employee object. Once I get an employee object, I want to place into its proper team within the unit object. For example:

```<code>var indiv = {'Rich':{'a':3,'b':4,'c':5}};
var teamname = "TeamA";
var unit = {};
unit[teamname] = indiv;

//[object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... }
//   }
// }
</code>```

Now, how can I add the following element to this object?

```<code>var indiv2 = {'Tom':{'a':6,'b':8,'c':10}};
</code>```

So that the result is:

```<code>// [object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... },
//     Tom: [object Object] { ... }
//   }
// }
</code>```

Any clues? Is the only option turning TeamA into an array of objects?

Thanks!

答:
Assuming you have

```<code>const indiv = {'Rich':{'a':3,'b':4,'c':5}}
const indiv2 = {'Tom':{'a':6,'b':8,'c':10}}
</code>```

You can use Object.assign

const indiv = {'Rich':{'a':3,'b':4,'c':5}}
const indiv2 = {'Tom':{'a':6,'b':8,'c':10}}
const unit = { teamA: {} }
Object.assign(unit.teamA, indiv)
console.log(unit.teamA)
Object.assign(unit.teamA, indiv2)
console.log(unit.teamA)```

Body:
I have an object 'unit', whose keys are different teams. Teams' keys are employees. Each employee is an object with its own fields. I'm looping through some files, getting each employee object. Once I get an employee object, I want to place into its proper team within the unit object. For example:

var indiv = {'Rich':{'a':3,'b':4,'c':5}};
var teamname = "TeamA";
var unit = {};
unit[teamname] = indiv;

//[object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... }
//   }
// }

Now, how can I add the following element to this object?

var indiv2 = {'Tom':{'a':6,'b':8,'c':10}};

So that the result is:

// [object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... },
//     Tom: [object Object] { ... }
//   }
// }

Any clues? Is the only option turning TeamA into an array of objects?

Thanks!

Body:
Assuming you have

const indiv = {'Rich':{'a':3,'b':4,'c':5}}
const indiv2 = {'Tom':{'a':6,'b':8,'c':10}}

You can use Object.assign

const indiv = {'Rich':{'a':3,'b':4,'c':5}}
const indiv2 = {'Tom':{'a':6,'b':8,'c':10}}
const unit = { teamA: {} }
Object.assign(unit.teamA, indiv)
console.log(unit.teamA)
Object.assign(unit.teamA, indiv2)
console.log(unit.teamA)


问:
Access Google Calendar API using Application-Specific Password
I'm working on a cron script to check my Google calendar on a daily basis.
I'd like to know if it's possible to use Application-Specific Passwords
(see: https://support.google.com/accounts/answer/185833?hl=it)
and insert the generated password in my script.
The OAUTH requires the user interaction and since I'm working on a script I cannot follow that way.
I've also read about the "service accounts", but hope I could avoid it just by using Application-Specific Passwords. What's the difference? Any hint?

Many thanks
Francesco

EDIT1: The code I'm trying with:

```<code><?php
require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$calendarList = $service->calendarList->listCalendarList();
</code>```

EDIT2: $service->calendarList->listCalendarList() gives empty list use:

```<code><?php
require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$listEvents = $service->events->listEvents("...@group.calendar.google.com");// taken from sharing calendar settings
$events = $listEvents->getItems();
print_r($events);

</code>```

答:
There are two ways to authenticate to the Google Calendar API

OAuth2 prompt user for access. (Not intended server-server interaction but can be done if a refresh token is generated by a user and then stored where the server can access it later.)

Using authorized service account credentials. (Ideal for server-server).

There is no other way to access a users data you must have their permission.

Look into Using OAuth 2.0 for Server to Server Applications.

service account

```<code>require_once __DIR__ . '/vendor/autoload.php';

// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');

/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed.
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
</code>```

code ripped from ServiceAccount.php

Body:
I'm working on a cron script to check my Google calendar on a daily basis.
I'd like to know if it's possible to use Application-Specific Passwords
(see: https://support.google.com/accounts/answer/185833?hl=it)
and insert the generated password in my script.
The OAUTH requires the user interaction and since I'm working on a script I cannot follow that way.
I've also read about the "service accounts", but hope I could avoid it just by using Application-Specific Passwords. What's the difference? Any hint?

Many thanks
Francesco

EDIT1: The code I'm trying with:

<?php
require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$calendarList = $service->calendarList->listCalendarList();

EDIT2: $service->calendarList->listCalendarList() gives empty list use:

<?php
require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$listEvents = $service->events->listEvents("...@group.calendar.google.com");// taken from sharing calendar settings
$events = $listEvents->getItems();
print_r($events);

Body:
There are two ways to authenticate to the Google Calendar API

OAuth2 prompt user for access. (Not intended server-server interaction but can be done if a refresh token is generated by a user and then stored where the server can access it later.)

Using authorized service account credentials. (Ideal for server-server).

There is no other way to access a users data you must have their permission.

Look into Using OAuth 2.0 for Server to Server Applications.

service account

require_once __DIR__ . '/vendor/autoload.php';

// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');

/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed.
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

code ripped from ServiceAccount.php


问:
can we print all the tables names who are referenced to a single table via a foreign key in psql
can we print all the tables names who are referenced to a single table via a foreign key in psql</p>

答:
As stated here:
https://stackoverflow.com/a/1154078/6932732

```<code>SELECT conname,
  pg_catalog.pg_get_constraintdef(r.oid, true) as condef
FROM pg_catalog.pg_constraint r
WHERE r.conrelid = 'Table_Name'::regclass AND r.contype = 'f' ORDER BY 1
</code>```

By replacing Table_Name with the name of the table you want to exam, you will get the foreign keys and the associated references.

If you want to print the actual names of the referenced tables, you will need a more complex query as stated here: https://stackoverflow.com/a/1152321/6932732

```<code>SELECT
    tc.table_schema,
    tc.constraint_name,
    tc.table_name,
    kcu.column_name,
    ccu.table_schema AS foreign_table_schema,
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name
FROM
    information_schema.table_constraints AS tc
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
      AND tc.table_schema = kcu.table_schema
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
      AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='Table_Name';
</code>```

By replacing Table_Name with the name of the table you want to exam, you will get the foreign keys and the associated references, while the actual table names will be in in the foreign_table_name column.

Body:
As stated here:
https://stackoverflow.com/a/1154078/6932732

SELECT conname,
  pg_catalog.pg_get_constraintdef(r.oid, true) as condef
FROM pg_catalog.pg_constraint r
WHERE r.conrelid = 'Table_Name'::regclass AND r.contype = 'f' ORDER BY 1

By replacing Table_Name with the name of the table you want to exam, you will get the foreign keys and the associated references.

If you want to print the actual names of the referenced tables, you will need a more complex query as stated here: https://stackoverflow.com/a/1152321/6932732

SELECT
    tc.table_schema,
    tc.constraint_name,
    tc.table_name,
    kcu.column_name,
    ccu.table_schema AS foreign_table_schema,
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name
FROM
    information_schema.table_constraints AS tc
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
      AND tc.table_schema = kcu.table_schema
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
      AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='Table_Name';

By replacing Table_Name with the name of the table you want to exam, you will get the foreign keys and the associated references, while the actual table names will be in in the foreign_table_name column.


问:
Vue JS pass prop to route string
I want to pass prop into the link that I navigate to:

```<code><v-btn router :to="/main/+{{siteType}}">

export default {
  props: ["siteType"]
}
</code>```

How can I pass siteType prop to the link string?

答:
Bind a computed property to it instead, because you cannot use mustache inside attributes, as per documentation:

Mustaches cannot be used inside HTML attributes. Instead, use a v-bind directive

Example:

```<code><v-btn router :to="myCustomLink">

export default {
  props: ["siteType"],
  computed: {
    myCustomLink: function() {
      return `/main/${this.siteType}`,
    }
  }
}
</code>```

Title: Vue JS pass prop to route string

Body:
I want to pass prop into the link that I navigate to:

<v-btn router :to="/main/+{{siteType}}">

export default {
  props: ["siteType"]
}

How can I pass siteType prop to the link string?

Body:
Bind a computed property to it instead, because you cannot use mustache inside attributes, as per documentation:

Mustaches cannot be used inside HTML attributes. Instead, use a v-bind directive

Example:

<v-btn router :to="myCustomLink">

export default {
  props: ["siteType"],
  computed: {
    myCustomLink: function() {
      return `/main/${this.siteType}`,
    }
  }
}


问:
how to fill missing values in a vector with the mean of value before and after the missing one
Currently I am trying to impute values in a vector in R. The conditions
of the imputation are.

Find all NA values

Then check if they have an existing value before and after them

Also check if the value which follows the NA is larger than
the value before the NA

If the conditions are met, calculate a mean taking the values before
and after.

Replace the NA value with the imputed one

```<code># example one
input_one = c(1,NA,3,4,NA,6,NA,NA)

# example two
input_two = c(NA,NA,3,4,5,6,NA,NA)

# example three
input_three = c(NA,NA,3,4,NA,6,NA,NA)

</code>```

I started out to write code to detect the values which can
be imputed. But I got stuck with the following.

```<code># incomplete function to detect the values
sapply(split(!is.na(input[c(rbind(which(is.na(c(input)))-1, which(is.na(c(input)))+1))]),
             rep(1:(length(!is.na(input[c(which(is.na(c(input)))-1, which(is.na(c(input)))+1)]))/2), each = 2)), all)
</code>```

This however only detects the NAs which might be
imputable and it only works with example one. It is incomplete and
unfortunately super hard to read and understand.

Any help with this would be highly appreciated.

答:
Here's an example using the imputeTS library. It takes account of more than one NA in the sequence, ensures that the mean is calculated if the next valid observation is greater than the last valid observation and also ignores NA at the beginning and end.

```<code>library(imputeTS)
myimpute <- function(series) {
    # Find where each NA is
    nalocations <- is.na(series)
    # Find the last and the previous observation for each row
    last1 <- lag(series)
    next1 <- lead(series)
    # Carry forward the last and next observations over sequences of NA
    # Each row will then get a last and next that can be averaged
    cflast <- na_locf(last1, na_remaining = 'keep')
    cfnext <- na_locf(next1, option = 'nocb', na_remaining = 'keep')
    # Make a data frame
    df <- data.frame(series, nalocations, last1, cflast, next1, cfnext)
    # Calculate the mean where there is currently a NA
    # making sure that the next is greater than the last
    df$mean <- ifelse(df$nalocations, ifelse(df$cflast < df$cfnext, (df$cflast+df$cfnext)/2, NA), NA)
    imputedseries <- ifelse(df$nalocations, ifelse(!is.na(df$mean), df$mean, NA), series)
    #list(df,  imputedseries) # comment this in and return it to see the intermediate data frame for debugging
    imputedseries
}
myimpute(c(NA,NA,3,4,NA,NA,6,NA,NA,8,NA,7,NA,NA,9,NA,11,NA,NA))

# [1] NA NA  3  4  5  5  6  7  7  8 NA  7  8  8  9 10 11 NA NA
</code>```

Body:
Currently I am trying to impute values in a vector in R. The conditions
of the imputation are.

Find all NA values

Then check if they have an existing value before and after them

Also check if the value which follows the NA is larger than
the value before the NA

If the conditions are met, calculate a mean taking the values before
and after.

Replace the NA value with the imputed one

# example one
input_one = c(1,NA,3,4,NA,6,NA,NA)

# example two
input_two = c(NA,NA,3,4,5,6,NA,NA)

# example three
input_three = c(NA,NA,3,4,NA,6,NA,NA)

I started out to write code to detect the values which can
be imputed. But I got stuck with the following.

# incomplete function to detect the values
sapply(split(!is.na(input[c(rbind(which(is.na(c(input)))-1, which(is.na(c(input)))+1))]),
             rep(1:(length(!is.na(input[c(which(is.na(c(input)))-1, which(is.na(c(input)))+1)]))/2), each = 2)), all)

This however only detects the NAs which might be
imputable and it only works with example one. It is incomplete and
unfortunately super hard to read and understand.

Any help with this would be highly appreciated.

Body:
Here's an example using the imputeTS library. It takes account of more than one NA in the sequence, ensures that the mean is calculated if the next valid observation is greater than the last valid observation and also ignores NA at the beginning and end.

library(imputeTS)
myimpute <- function(series) {
    # Find where each NA is
    nalocations <- is.na(series)
    # Find the last and the previous observation for each row
    last1 <- lag(series)
    next1 <- lead(series)
    # Carry forward the last and next observations over sequences of NA
    # Each row will then get a last and next that can be averaged
    cflast <- na_locf(last1, na_remaining = 'keep')
    cfnext <- na_locf(next1, option = 'nocb', na_remaining = 'keep')
    # Make a data frame
    df <- data.frame(series, nalocations, last1, cflast, next1, cfnext)
    # Calculate the mean where there is currently a NA
    # making sure that the next is greater than the last
    df$mean <- ifelse(df$nalocations, ifelse(df$cflast < df$cfnext, (df$cflast+df$cfnext)/2, NA), NA)
    imputedseries <- ifelse(df$nalocations, ifelse(!is.na(df$mean), df$mean, NA), series)
    #list(df,  imputedseries) # comment this in and return it to see the intermediate data frame for debugging
    imputedseries
}
myimpute(c(NA,NA,3,4,NA,NA,6,NA,NA,8,NA,7,NA,NA,9,NA,11,NA,NA))

# [1] NA NA  3  4  5  5  6  7  7  8 NA  7  8  8  9 10 11 NA NA


问:
How to calculate/display number as "Top 5", "Top 10", "Top 15" and so on?
How would you create a function (in PHP) to return a value for the appropriate rounded ranking group (e.g. "Top 5", "Top 10", "Top 15", ... "Top 1 million", "Top 5 million", "Top 10 million", "Top 15 million").

Note that it should round up to the nearest 1, 5 or 10 - e.g. "Top 15 million" rather than "Top 12 million".

Example:

Rank = Output

1-5 = 5 (Top 5 ranking)

6-10 = 10 (Top 10 ranking)

11-15 = 15 (Top 15 ranking)

This should work all the way up to trillions.

My current function works (sort of) however it would return a value for a ranking group of top 15 as top 20 instead.

```<code>   private function format_number_iollions($amount,$style=null) {
        $amount = (0 + str_replace(',', '', $amount));
        if (!is_numeric($amount)){
            return false;
        }

        $plusString = '';
        switch ($style){
            case 'plus':
                $plusString = '+';
            break;
        }

        if ($style==='rank' && $amount<=10){
            return 10;
        }

        // filter and format it
        if ($amount>1000000000000){

            if ($style==='rank'){
                $v = ceil(($amount/1000000000000));
            } else {
                $v = floor(($amount/1000000000000));
            }

            $v .= $plusString.' trillion';
        } else if ($amount>1000000000){
            if ($style==='rank'){
                $v = ceil(($amount/1000000000));
            } else {
                $v = floor(($amount/1000000000));
            }

            $v .= $plusString.' billion';
        } else if ($amount>1000000){
            if ($style==='rank'){
                $v = ceil(($amount/1000000));
            } else {
                $v = floor(($amount/1000000));
            }

            $v .= $plusString.' million';
        } else if ($amount>100000){
            if ($style==='rank'){
                $v = ceil(($amount/100000));
            } else {
                $v = floor(($amount/100000));
            }

            $v .= '00,000'.$plusString;
        } else if ($amount>10000){
            if ($style==='rank'){
                $v = ceil(($amount/10000));
            } else {
                $v = floor(($amount/10000));
            }

            $v .= '0,000'.$plusString;
        } else if ($amount>1000){
            if ($style==='rank'){
                $v = ceil(($amount/1000));
            } else {
                $v = floor(($amount/1000));
            }

            $v .= ',000'.$plusString;
        } else if ($amount>100){
            if ($style==='rank'){
                $v = ceil(($amount/100));
            } else {
                $v = floor(($amount/100));
            }

            $v .= '00'.$plusString;
        } else if ($amount>10){
            if ($style==='rank'){
                $v = ceil(($amount/10));
            } else {
                $v = floor(($amount/10));
            }

            $v .= '0'.$plusString;
        } else {
            return number_format($amount);
        }

        return $v;
    }
</code>```

UPDATE - the final solution is this function (if anyone needs it):

```<code>private function get_rank_group($rawrank) {
    // Divide by 1000 and count how many divisions were done
    $rank_scale = 0;
    while ($rawrank >= 1000) {
        $rawrank /= 1000;
        $rank_scale++;
    }
    // Determine which Top X can be
    if ($rawrank >= 100) {
        $lim_name = (floor(($rawrank-1) / 50) + 1) * 50;
    } else {
        $lim_name = (floor(($rawrank-1) / 5) + 1) * 5;
    }
    // if its in the next higher level
    if ($lim_name >= 1000) {
        $lim_name = '1';
        $rank_scale++;
    }
    static $rank_scale_names = array('', ',000', ' Million', ' Billion', ' Trillion',  ' Quadrillion', ' Quintillion', ' Sextillion', ' Septillion');
    if (!isset($rank_scale_names[$rank_scale])){
        return null; //too much - add higher word-numbers to $rank_scale_names
    } else {
        return "$lim_name{$rank_scale_names[$rank_scale]}";
    }
}
</code>```

答:
As an improvement of AterLux's Solution

```<code>...
// Determine which Top X can be
if ($rawrank >= 100) {
    $lim_name = (floor(($rawrank-1) / 50) + 1) * 50;
} else {
    $lim_name = (floor(($rawrank-1) / 5) + 1) * 5;
}
// if its in the next higher level
if ($lim_name >= 1000) {
    $lim_name = '1';
    $rank_scale++;
}
static $rank_scale_names = array( ...
</code>```

Output

```<code>1 -> Top 5
5 -> Top 5
9 -> Top 10
10 -> Top 10
12 -> Top 15
16 -> Top 20
49 -> Top 50
50 -> Top 50
51 -> Top 55
299 -> Top 300
300 -> Top 300
301 -> Top 350
995 -> Top 1 Thousand
12345 -> Top 15 Thousand
654321 -> Top 700 Thousand
234567890 -> Top 250 Million
1234567890123456789 -> Top 5 Quintillion
</code>```

Body:
How would you create a function (in PHP) to return a value for the appropriate rounded ranking group (e.g. "Top 5", "Top 10", "Top 15", ... "Top 1 million", "Top 5 million", "Top 10 million", "Top 15 million").

Note that it should round up to the nearest 1, 5 or 10 - e.g. "Top 15 million" rather than "Top 12 million".

Example:

Rank = Output

1-5 = 5 (Top 5 ranking)

6-10 = 10 (Top 10 ranking)

11-15 = 15 (Top 15 ranking)

This should work all the way up to trillions.

My current function works (sort of) however it would return a value for a ranking group of top 15 as top 20 instead.

   private function format_number_iollions($amount,$style=null) {
        $amount = (0 + str_replace(',', '', $amount));
        if (!is_numeric($amount)){
            return false;
        }

        $plusString = '';
        switch ($style){
            case 'plus':
                $plusString = '+';
            break;
        }

        if ($style==='rank' && $amount<=10){
            return 10;
        }

        // filter and format it
        if ($amount>1000000000000){

            if ($style==='rank'){
                $v = ceil(($amount/1000000000000));
            } else {
                $v = floor(($amount/1000000000000));
            }

            $v .= $plusString.' trillion';
        } else if ($amount>1000000000){
            if ($style==='rank'){
                $v = ceil(($amount/1000000000));
            } else {
                $v = floor(($amount/1000000000));
            }

            $v .= $plusString.' billion';
        } else if ($amount>1000000){
            if ($style==='rank'){
                $v = ceil(($amount/1000000));
            } else {
                $v = floor(($amount/1000000));
            }

            $v .= $plusString.' million';
        } else if ($amount>100000){
            if ($style==='rank'){
                $v = ceil(($amount/100000));
            } else {
                $v = floor(($amount/100000));
            }

            $v .= '00,000'.$plusString;
        } else if ($amount>10000){
            if ($style==='rank'){
                $v = ceil(($amount/10000));
            } else {
                $v = floor(($amount/10000));
            }

            $v .= '0,000'.$plusString;
        } else if ($amount>1000){
            if ($style==='rank'){
                $v = ceil(($amount/1000));
            } else {
                $v = floor(($amount/1000));
            }

            $v .= ',000'.$plusString;
        } else if ($amount>100){
            if ($style==='rank'){
                $v = ceil(($amount/100));
            } else {
                $v = floor(($amount/100));
            }

            $v .= '00'.$plusString;
        } else if ($amount>10){
            if ($style==='rank'){
                $v = ceil(($amount/10));
            } else {
                $v = floor(($amount/10));
            }

            $v .= '0'.$plusString;
        } else {
            return number_format($amount);
        }

        return $v;
    }

UPDATE - the final solution is this function (if anyone needs it):

private function get_rank_group($rawrank) {
    // Divide by 1000 and count how many divisions were done
    $rank_scale = 0;
    while ($rawrank >= 1000) {
        $rawrank /= 1000;
        $rank_scale++;
    }
    // Determine which Top X can be
    if ($rawrank >= 100) {
        $lim_name = (floor(($rawrank-1) / 50) + 1) * 50;
    } else {
        $lim_name = (floor(($rawrank-1) / 5) + 1) * 5;
    }
    // if its in the next higher level
    if ($lim_name >= 1000) {
        $lim_name = '1';
        $rank_scale++;
    }
    static $rank_scale_names = array('', ',000', ' Million', ' Billion', ' Trillion',  ' Quadrillion', ' Quintillion', ' Sextillion', ' Septillion');
    if (!isset($rank_scale_names[$rank_scale])){
        return null; //too much - add higher word-numbers to $rank_scale_names
    } else {
        return "$lim_name{$rank_scale_names[$rank_scale]}";
    }
}

Body:
As an improvement of AterLux's Solution

...
// Determine which Top X can be
if ($rawrank >= 100) {
    $lim_name = (floor(($rawrank-1) / 50) + 1) * 50;
} else {
    $lim_name = (floor(($rawrank-1) / 5) + 1) * 5;
}
// if its in the next higher level
if ($lim_name >= 1000) {
    $lim_name = '1';
    $rank_scale++;
}
static $rank_scale_names = array( ...

Output

1 -> Top 5
5 -> Top 5
9 -> Top 10
10 -> Top 10
12 -> Top 15
16 -> Top 20
49 -> Top 50
50 -> Top 50
51 -> Top 55
299 -> Top 300
300 -> Top 300
301 -> Top 350
995 -> Top 1 Thousand
12345 -> Top 15 Thousand
654321 -> Top 700 Thousand
234567890 -> Top 250 Million
1234567890123456789 -> Top 5 Quintillion


问:
Running command from Node.js with sudo
Being new to Node.js, I have this question..

I see it mentioned in a few places that node should not be run as root, such as this. I am just using node to set up a simple web service and executing a python script which requires root access. I just don't understand where the danger lies, as in what could the hacker do.

My node.js file is something like this:-

```<code>var http = require('http');
var express = require('express');

var app = express();

app.use(express['static'](__dirname));

app.get('/alert', function(req, res) {
    var addr = req.query.addr;
    //~ need to check if it is a valid address??
    console.log('Received addr -' + addr);

    var spawn = require('child_process').spawn;

    var process = spawn('python', ['custom-text-led/custom-text.py', addr]);

    process.stdout.on('data', function(data) {
        console.log('Data:' + data);
    });

})

app.get('*', function(req, res) {
    res.status(404).send('Unrecognized API call');
});

app.use(function(err, req, res, next) {
    if (req.xhr) {
        res.status(500).send('Opps, something went wrong');
    } else {
        next(err);
    }
});

app.listen(3000);

console.log('App server running at port 3000');
</code>```

答:
According to this post from superuser of StackExchange platform, you can pipe the password to other sudo commands, like this:

```<code>echo <password> | sudo -S <command>
</code>```

and according to this StackOverflow post, you can pipe commands in spawn like this:

```<code>child.spawn('sh', args)
var args = ['-c', <the entire command you want to run as a string>];
</code>```

After some hours struggling I found the solution. To wrap it all up, your answer would be something like:

```<code>import { spawn } from "child_process";
const process = spawn("sh", ["-c", "sudo -K << <password> <the entire command you want to run with sudo>"]);
</code>```

I hope it would help you and others like me.

ContentLicense: CC BY-SA 3.0

Title: Running command from Node.js with sudo

Body:
Being new to Node.js, I have this question..

I see it mentioned in a few places that node should not be run as root, such as this. I am just using node to set up a simple web service and executing a python script which requires root access. I just don't understand where the danger lies, as in what could the hacker do.

My node.js file is something like this:-

var http = require('http');
var express = require('express');

var app = express();

app.use(express['static'](__dirname));

app.get('/alert', function(req, res) {
    var addr = req.query.addr;
    //~ need to check if it is a valid address??
    console.log('Received addr -' + addr);

    var spawn = require('child_process').spawn;

    var process = spawn('python', ['custom-text-led/custom-text.py', addr]);

    process.stdout.on('data', function(data) {
        console.log('Data:' + data);
    });

})

app.get('*', function(req, res) {
    res.status(404).send('Unrecognized API call');
});

app.use(function(err, req, res, next) {
    if (req.xhr) {
        res.status(500).send('Opps, something went wrong');
    } else {
        next(err);
    }
});

app.listen(3000);

console.log('App server running at port 3000');

Body:
According to this post from superuser of StackExchange platform, you can pipe the password to other sudo commands, like this:

echo <password> | sudo -S <command>

and according to this StackOverflow post, you can pipe commands in spawn like this:

child.spawn('sh', args)
var args = ['-c', <the entire command you want to run as a string>];

After some hours struggling I found the solution. To wrap it all up, your answer would be something like:

import { spawn } from "child_process";
const process = spawn("sh", ["-c", "sudo -K << <password> <the entire command you want to run with sudo>"]);

I hope it would help you and others like me.


问:
Move value from row below to adjacent column in SQL
I would need some help with below case:
My data contains dates of order arrival in one column.

I want to add second column what would use date from one row below:

答:
Use lead():

```<code>select t.dept, t.date as arrival, t.next_arrival
from (select t.*, lead(date) over (partition by dept order by date) as next_arrival
      from t
     ) t
where t.next_arrival is not null;
</code>```

If you are happy with all rows in the result set and the next_arrival being NULL, then you don't need the subquery.

Body:
Use lead():

select t.dept, t.date as arrival, t.next_arrival
from (select t.*, lead(date) over (partition by dept order by date) as next_arrival
      from t
     ) t
where t.next_arrival is not null;

If you are happy with all rows in the result set and the next_arrival being NULL, then you don't need the subquery.


问:
Count characters of dynamically created textareas with different id and name attr
I am having two textareas one under another

```<code><div class="form-group">
<span id="textarea_feedback1"></span>
<span> Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
<hr>
<span id="textarea_feedback2"></span>
<span> Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>
</code>```

Both textareas are created dynamically and they have different id and name attr. At some point, they might be 2, 3, 4... and so on.
What I am trying to do is to create a char counter for each textarea that also applies dynamically.

It would have had been easy if the number of the textareas was fixed (i.e, always 2).

But I am having trouble finding a way to apply one and the same JQuery script to textareas with a different name and id attribute.

I was thinking about adding a unique attribute like areaid="" to each textarea, so I can somehow modify dynamically the script.

This is the script I have

```<code>$(document).ready(function() {
var text_max = 400;

$('#textarea_feedback1').html('<span>'+text_max + '</span>');

$('#answer1').on('input click keyup', function() {
    var text_length = $('#answer1').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback1').html('<span>'+text_remaining + '</span>');
});

});
</code>```

Basically, what I think that it should happen is, that based on the areaid attr to also change the value of the span id="textarea_feedback" and textatea id="answer" to match the areaid value, so somehow the script would work separately to as many textareas I have.

Here is jsfiddle

答:
You can also not rely on IDs at all, if you do it like this:

$(document).ready(function() {
  var maxLen = 400,
    $formGroup = $(".form-group"),
    $addBtn = $("#add-textarea-btn");

  $addBtn.click(createTextarea);
  // Apply the function on pre-existing textareas
  $("textarea", $formGroup).each(function(i, $el) {
    updateCharCount.call($el);
  });
  // And whenever you edit one
  $formGroup.on("input", "textarea", updateCharCount);

  function createTextarea() {
    $formGroup.append(
      $(
        "
" +
        ' Characters left' +
        '
<textarea placeholder="Type your answer here"></textarea>'
      )
    );
    updateCharCount.call($("textarea").last());
  }

  function updateCharCount() {
    var $charLeft = $(this).prevAll(".chars-left").first(); // Get previous chars-left
    $charLeft.text(maxLen - $(this).val().length);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="form-group">
  <span class="chars-left"></span><span> Characters left</span>
  <br />
  <textarea placeholder="Type your answer here">There is some content already</textarea>
</div>
<button id="add-textarea-btn">New textarea</button></code>```

Body:
I am having two textareas one under another

 Characters left

<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>

 Characters left

<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>

Both textareas are created dynamically and they have different id and name attr. At some point, they might be 2, 3, 4... and so on.
What I am trying to do is to create a char counter for each textarea that also applies dynamically.

It would have had been easy if the number of the textareas was fixed (i.e, always 2).

But I am having trouble finding a way to apply one and the same JQuery script to textareas with a different name and id attribute.

I was thinking about adding a unique attribute like areaid="" to each textarea, so I can somehow modify dynamically the script.

This is the script I have

$(document).ready(function() {
var text_max = 400;

$('#textarea_feedback1').html(''+text_max + '');

$('#answer1').on('input click keyup', function() {
    var text_length = $('#answer1').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback1').html(''+text_remaining + '');
});

});

Basically, what I think that it should happen is, that based on the areaid attr to also change the value of the span id="textarea_feedback" and textatea id="answer" to match the areaid value, so somehow the script would work separately to as many textareas I have.

Here is jsfiddle

Body:
You can also not rely on IDs at all, if you do it like this:

$(document).ready(function() {
  var maxLen = 400,
    $formGroup = $(".form-group"),
    $addBtn = $("#add-textarea-btn");

  $addBtn.click(createTextarea);
  // Apply the function on pre-existing textareas
  $("textarea", $formGroup).each(function(i, $el) {
    updateCharCount.call($el);
  });
  // And whenever you edit one
  $formGroup.on("input", "textarea", updateCharCount);

  function createTextarea() {
    $formGroup.append(
      $(
        "<hr />" +
        '<span class="chars-left"></span><span> Characters left</span>' +
        '<br /><textarea placeholder="Type your answer here"></textarea>'
      )
    );
    updateCharCount.call($("textarea").last());
  }

  function updateCharCount() {
    var $charLeft = $(this).prevAll(".chars-left").first(); // Get previous chars-left
    $charLeft.text(maxLen - $(this).val().length);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="form-group">
  <span class="chars-left"></span><span> Characters left</span>
  <br />
  <textarea placeholder="Type your answer here">There is some content already</textarea>
</div>
<button id="add-textarea-btn">New textarea</button>


问:
Can the Android emulator record and play back audio using pc hardware?
I don't have an android phone, but i'm trying to develop for it anyway.  The only way to test my application at the moment is to use the emulator, which I've read does not support audio recording.  However, I read about the startup command "-audio " which allows audio input/output from your pc using the 'winaudio' backend.  I haven't been able to get it to work though, is it possible to record using my pc's microphone?  If so, what am I doing wrong?</p>

答:
Yes, it can.
On Mac OSX, you must set the microphone on the emulator settings, after it's opened.

While the emulator is opened, on the right side bar (where the volume buttons are localized), click on the three dots (last button of the list) to open the emulator settings.

On the settings screen (called "Extended controls"), select Microphone and turn on the option "Virtual microphone uses host audio input".

ContentLicense: CC BY-SA 2.5


问:
Rating star is cutting from the end
i have implemented android native rating bar but when i set number of star to 10 it will cut from the end of the screen its happening in some devices can anybody help me how can i manage to display 10 star consistently on all mobile devices?</p>

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_marginBottom="@dimen/_15sdp"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/tValueLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/_5sdp"
    android:textSize="@dimen/_11ssp" />

<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/ratingBarStyleIndicator"
    android:isIndicator="false"
    android:layout_marginTop="@dimen/_5sdp"
    android:stepSize="1.0" />

</LinearLayout>
</code>```

答:
try this to minimize size of stars </p>

```<code>android:scaleX=".4"
android:scaleY=".4"
</code>```

<p>I hope it will work with you </p>

Title: Rating star is cutting from the end

Body:
i have implemented android native rating bar but when i set number of star to 10 it will cut from the end of the screen its happening in some devices can anybody help me how can i manage to display 10 star consistently on all mobile devices?

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_marginBottom="@dimen/_15sdp"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/tValueLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/_5sdp"
    android:textSize="@dimen/_11ssp" />

<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/ratingBarStyleIndicator"
    android:isIndicator="false"
    android:layout_marginTop="@dimen/_5sdp"
    android:stepSize="1.0" />

</LinearLayout>

Body:
try this to minimize size of stars

android:scaleX=".4"
android:scaleY=".4"

I hope it will work with you


问:
ModuleNotFoundError: No module named 'tensorflow' In Jupyter Notebook
I'm getting this error in my Jupyter Notebook. The complete error is bellow:

```<code>---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
 in
      1 import numpy as np # working with data
      2 import pandas as pd
----> 3 from keras.layers.core import Dense, Activation, Dropout
      4 from keras.layers.recurrent import LSTM
      5 from keras.models import Sequential

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\__init__.py in
      1 from __future__ import absolute_import
      2
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\__init__.py in
      4 from . import data_utils
      5 from . import io_utils
----> 6 from . import conv_utils
      7 from . import losses_utils
      8 from . import metrics_utils

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\conv_utils.py in
      7 from six.moves import range
      8 import numpy as np
----> 9 from .. import backend as K
     10
     11

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\__init__.py in
----> 1 from .load_backend import epsilon
      2 from .load_backend import set_epsilon
      3 from .load_backend import floatx
      4 from .load_backend import set_floatx
      5 from .load_backend import cast_to_floatx

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\load_backend.py in
     88 elif _BACKEND == 'tensorflow':
     89     sys.stderr.write('Using TensorFlow backend.\n')
---> 90     from .tensorflow_backend import *
     91 else:
     92     # Try and load external backend.

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\tensorflow_backend.py in
      3 from __future__ import print_function
      4
----> 5 import tensorflow as tf
      6 from tensorflow.python.eager import context
      7 from tensorflow.python.framework import device as tfdev

ModuleNotFoundError: No module named 'tensorflow'
</code>```

In cmd: My python version is:

```<code>C:\Users\casper>python --version
Python 3.6.5 :: Anaconda, Inc.
</code>```

Anaconda version:

```<code>C:\Users\casper>conda --version
conda 4.5.4
</code>```

In Anaconda Prompt I install Tensorflow like below:

```<code>conda create -n tensorflow python=3.6
// CPU edition
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorflow
</code>```

In Anaconda Prompt: My Tensorflow version is:

```<code>(base) C:\Users\casper>activate tensorflow

(tensorflow) C:\Users\casper>python
Python 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 12:30:02) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
2020-02-14 19:36:32.468120: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-02-14 19:36:32.474896: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> tf.__version__
'2.1.0'
>>> tf.__path__
['D:\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow']
</code>```

It's really the first time I'm working with all these libraries and technologies, I lost the track, I can see all around its different Python versions, It's really messed up for me now. How could I fix it ?

答:
Try running Anaconda as admin (right-click -> run as administrator).
And try these commands as well (taken from the Anaconda Documentation):

```<code>conda create -n tf tensorflow
conda activate tf
</code>```

You may need to restart you PC.

Body:
I'm getting this error in my Jupyter Notebook. The complete error is bellow:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
 in
      1 import numpy as np # working with data
      2 import pandas as pd
----> 3 from keras.layers.core import Dense, Activation, Dropout
      4 from keras.layers.recurrent import LSTM
      5 from keras.models import Sequential

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\__init__.py in
      1 from __future__ import absolute_import
      2
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\__init__.py in
      4 from . import data_utils
      5 from . import io_utils
----> 6 from . import conv_utils
      7 from . import losses_utils
      8 from . import metrics_utils

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\utils\conv_utils.py in
      7 from six.moves import range
      8 import numpy as np
----> 9 from .. import backend as K
     10
     11

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\__init__.py in
----> 1 from .load_backend import epsilon
      2 from .load_backend import set_epsilon
      3 from .load_backend import floatx
      4 from .load_backend import set_floatx
      5 from .load_backend import cast_to_floatx

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\load_backend.py in
     88 elif _BACKEND == 'tensorflow':
     89     sys.stderr.write('Using TensorFlow backend.\n')
---> 90     from .tensorflow_backend import *
     91 else:
     92     # Try and load external backend.

~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\keras\backend\tensorflow_backend.py in
      3 from __future__ import print_function
      4
----> 5 import tensorflow as tf
      6 from tensorflow.python.eager import context
      7 from tensorflow.python.framework import device as tfdev

ModuleNotFoundError: No module named 'tensorflow'

In cmd: My python version is:

C:\Users\casper>python --version
Python 3.6.5 :: Anaconda, Inc.

Anaconda version:

C:\Users\casper>conda --version
conda 4.5.4

In Anaconda Prompt I install Tensorflow like below:

conda create -n tensorflow python=3.6
// CPU edition
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorflow

In Anaconda Prompt: My Tensorflow version is:

(base) C:\Users\casper>activate tensorflow

(tensorflow) C:\Users\casper>python
Python 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 12:30:02) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
2020-02-14 19:36:32.468120: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-02-14 19:36:32.474896: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> tf.__version__
'2.1.0'
>>> tf.__path__
['D:\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow']

It's really the first time I'm working with all these libraries and technologies, I lost the track, I can see all around its different Python versions, It's really messed up for me now. How could I fix it ?

Body:
Try running Anaconda as admin (right-click -> run as administrator).
And try these commands as well (taken from the Anaconda Documentation):

conda create -n tf tensorflow
conda activate tf

You may need to restart you PC.