问:
jQuery QRcode does not work with canvas
I'm using this library: https://larsjung.de/jquery-qrcode/ to draw a QR Code inside my canvas, but it doesn't work.

My code:

```<code>var a_canvas = document.getElementById("latoSinistro");
var context = a_canvas.getContext("2d");

context.font = "8px appMeFont";
context.textAlign="center";
context.fillText(dati.anagrafica[linguaInUso].prodName, 121, 93);
context.fillText(dati.anagrafica[linguaInUso].pointName, 121, 103);

$("#latoSinistro").qrcode({
    "render": 'canvas',
    "minVersion": 1,
    "maxVersion": 10,
    "ecLevel": 'M',
    "left": 121,
    "top": 130,
    "fill": '#000',
    "background": null,
    "mode": 0,
    "size": 100,
    "color": "#000000",
    "text": "www.app/cod/"+idProdotto
});
</code>```

答:
make sure you have declare in your view

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

make sure your var idProdotto value has been assigned to make qr code generate clearly

Title: jQuery QRcode does not work with canvas

Body:
I'm using this library: https://larsjung.de/jquery-qrcode/ to draw a QR Code inside my canvas, but it doesn't work.

My code:

var a_canvas = document.getElementById("latoSinistro");
var context = a_canvas.getContext("2d");

context.font = "8px appMeFont";
context.textAlign="center";
context.fillText(dati.anagrafica[linguaInUso].prodName, 121, 93);
context.fillText(dati.anagrafica[linguaInUso].pointName, 121, 103);

$("#latoSinistro").qrcode({
    "render": 'canvas',
    "minVersion": 1,
    "maxVersion": 10,
    "ecLevel": 'M',
    "left": 121,
    "top": 130,
    "fill": '#000',
    "background": null,
    "mode": 0,
    "size": 100,
    "color": "#000000",
    "text": "www.app/cod/"+idProdotto
});

Body:
make sure you have declare in your view

<div id="latoSinistro"
</div>

make sure your var idProdotto value has been assigned to make qr code generate clearly


来源: stackexchange

问:
Getting timeout error in New Year Chaos problem using scala
I have got a working scala code for New Year Chaos problem in Hackerrank, but Im recieving timeout errors in some test cases

https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays

Please help me with optimization of below code:

```<code>def minimumBribes(q: Array[Int]){
        val c = q.sorted
        var swap = 0
        var count_swap=0
        import scala.util.control._
        val loop = new Breaks
        var temp = 0
        var flag = true

        loop.breakable
        {
            for (i <- q.length-1 to 0 by -1)

            {
                    swap = 0
                 if (q(i) != i+1)
                 {
                        swap=i-q.indexOf(i+1)
                        if (swap > 2) {println("Too Chaotic");flag=false;loop.break()}
                        else
                            {
                                temp= q(q.indexOf(i+1))
                                q(q.indexOf(i+1)) = q(i-1)
                                q(i-1) = q(i)
                                q(i) = temp

                                count_swap += swap
                                if(q.deep == c.deep){
                                loop.break()
                                }
                            }
                }
            }

        }
        if (flag)println(count_swap)

    }

</code>```

答:
To be honest I don't understand your implementation but

1) q.sorted could possibly already run out of time given that n is ~10^5.

2) q.sorted call is actually redundant since it's just a 1..n sequence.

3) using q.indexOf makes your algorithm O(n^2) complex. It's possible to solve it in linear time.

ContentLicense: CC BY-SA 4.0

Body:
I have got a working scala code for New Year Chaos problem in Hackerrank, but Im recieving timeout errors in some test cases

https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays

Please help me with optimization of below code:

def minimumBribes(q: Array[Int]){
        val c = q.sorted
        var swap = 0
        var count_swap=0
        import scala.util.control._
        val loop = new Breaks
        var temp = 0
        var flag = true

        loop.breakable
        {
            for (i <- q.length-1 to 0 by -1)

            {
                    swap = 0
                 if (q(i) != i+1)
                 {
                        swap=i-q.indexOf(i+1)
                        if (swap > 2) {println("Too Chaotic");flag=false;loop.break()}
                        else
                            {
                                temp= q(q.indexOf(i+1))
                                q(q.indexOf(i+1)) = q(i-1)
                                q(i-1) = q(i)
                                q(i) = temp

                                count_swap += swap
                                if(q.deep == c.deep){
                                loop.break()
                                }
                            }
                }
            }

        }
        if (flag)println(count_swap)

    }


问:
Algorithm to construct Fibonacci's tree with given minimum
I want to make a Fibonacci tree but with a minimum number other than 1, and I can't seem to find anything about it.

Here's an example of a "normal" fibonacci tree, with the minimum node 1.

```<code>        5
      /   \
     3     7
   /   \  /
  2    4 6
 /
1
</code>```

What I want to do is for example, with minimum 3:

With height 0: it would be the empty tree.

With height 1:

```<code>3
</code>```

With height 2:

```<code>   4
  /
 3
</code>```

With height 3:

```<code>     5
   /   \
  4     6
 /
3
</code>```

With height 4:

```<code>         7
      /    \
     5      9
   /   \   /
  4    6  8
 /
3
</code>```

...And so on.

My problem is, I can't seem to see a pattern in it, so I can't think of an algorithm to write.

I know that the left subtree's height is h-1 (where h is the original given height) and the right subtree's height is h-2. And I can't see how they calculate the root's number. But other than that, I'm really stuck.

答:
Since the Fibonacci tree is a recursively defined structure, the easiest way is to think about a recursive algorithm.

This is some sort of C-style pseudo code (not covering any edge cases - I leave that to you as part of the exercise).

function createTree(height)
{
  // basic cases
  if(height == 0) return NULL;
  if(height == 1)
  {
    node = new Node;
    node.numNodesInTree = 1;
  }
  else
  {
    // according to the definition of the fibonacci tree
    node = new Node;
    node.leftChild  = createTree(height - 1);
    node.rightChild = createTree(height - 2);
    node.numNodesInTree =   node.leftChild.numNodesInTree
                          + node.rightChild.numNodesInTree
                          + 1; // also count the current node
  }
  return node;
}
```

<p>You end up with a tree that has the Fibonacci structure, but not the right numbers <strong>yet</strong>. As a little helper, you have the number of nodes for each sub tree.</p>

<p>Then you can do something like:</p>

<pre class="lang-c prettyprint-override"><code>function fillTree(offset, node, minimum) // offset means "all numbers in this subtree must be bigger than offset"
{
  // According to the binary search tree definition,
  // all numbers in the left sub tree have to be lower than
  // the current node.
  // All nodes in the right sub tree have to be larger.
  node.value =   node.leftChild.numNodesInTree // the number has to be bigger than all numbers in the left sub tree
               + 1                             // (that's the "one bigger")
               + offset                        // offset for right subtrees
               + minimum - 1;                  // Just stupidly add the minimum (as mentioned in the comment to your question)
  fillTree(offset, node.leftChild, minimum);      // propagate offset to left children
  fillTree(node.value, node.rightChild, minimum); // for the right sub tree, the current node's value is the new offset
                                                  // because all nodes in the right sub tree have to be bigger than the current node (binary search criterion)
}
</code>```

Then you can call it like:

root = createTree(height);
fillTree(0, root, 3); // when initially calling it, the offset is always 0
                      // You can set the minimum arbitrarily (i.e. 3 as in your example)
```

Since this is pseudo code, I obviously haven't tested it, but you could get the idea behind that.

Body:
I want to make a Fibonacci tree but with a minimum number other than 1, and I can't seem to find anything about it.

Here's an example of a "normal" fibonacci tree, with the minimum node 1.

        5
      /   \
     3     7
   /   \  /
  2    4 6
 /
1

What I want to do is for example, with minimum 3:

With height 0: it would be the empty tree.

With height 1:

3

With height 2:

   4
  /
 3

With height 3:

     5
   /   \
  4     6
 /
3

With height 4:

         7
      /    \
     5      9
   /   \   /
  4    6  8
 /
3

...And so on.

My problem is, I can't seem to see a pattern in it, so I can't think of an algorithm to write.

I know that the left subtree's height is h-1 (where h is the original given height) and the right subtree's height is h-2. And I can't see how they calculate the root's number. But other than that, I'm really stuck.

Body:
Since the Fibonacci tree is a recursively defined structure, the easiest way is to think about a recursive algorithm.

This is some sort of C-style pseudo code (not covering any edge cases - I leave that to you as part of the exercise).

function createTree(height)
{
  // basic cases
  if(height == 0) return NULL;
  if(height == 1)
  {
    node = new Node;
    node.numNodesInTree = 1;
  }
  else
  {
    // according to the definition of the fibonacci tree
    node = new Node;
    node.leftChild  = createTree(height - 1);
    node.rightChild = createTree(height - 2);
    node.numNodesInTree =   node.leftChild.numNodesInTree
                          + node.rightChild.numNodesInTree
                          + 1; // also count the current node
  }
  return node;
}

You end up with a tree that has the Fibonacci structure, but not the right numbers yet. As a little helper, you have the number of nodes for each sub tree.

Then you can do something like:

function fillTree(offset, node, minimum) // offset means "all numbers in this subtree must be bigger than offset"
{
  // According to the binary search tree definition,
  // all numbers in the left sub tree have to be lower than
  // the current node.
  // All nodes in the right sub tree have to be larger.
  node.value =   node.leftChild.numNodesInTree // the number has to be bigger than all numbers in the left sub tree
               + 1                             // (that's the "one bigger")
               + offset                        // offset for right subtrees
               + minimum - 1;                  // Just stupidly add the minimum (as mentioned in the comment to your question)
  fillTree(offset, node.leftChild, minimum);      // propagate offset to left children
  fillTree(node.value, node.rightChild, minimum); // for the right sub tree, the current node's value is the new offset
                                                  // because all nodes in the right sub tree have to be bigger than the current node (binary search criterion)
}

Then you can call it like:

root = createTree(height);
fillTree(0, root, 3); // when initially calling it, the offset is always 0
                      // You can set the minimum arbitrarily (i.e. 3 as in your example)

Since this is pseudo code, I obviously haven't tested it, but you could get the idea behind that.


问:
Problem when loading Service by injection
I'm trying to create a service, which can be injected anywhere. For this I am trying to pass as argument the HttpClient component of Symfony 4.3

I show you the service

https://i.stack.imgur.com/2384M.png

```<code>    <?php

namespace App\Service\Callback;

use Symfony\Component\HttpClient\HttpClient;

class Back
{

    private $client;

    public function __construct(HttpClient $httpClient)
    {
        $this->client = $httpClient::create();
    }

    public function sendCallback ( $method, $urlCallback, $option)
    {
        $response = $this->client->request($method,$urlCallback,$option);

        $statusCode = $response->getStatusCode();
        return $statusCode;
    }

}
</code>```

Well, I'm trying to load it in the services.yml

```<code># This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: 'en'
    base_url_front: '%env(BASE_URL_FRONT)%'
    mobile_type: 2

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    Nexy\Slack\Client: '@nexy_slack.client'

    Symfony\Component\HttpClient\HttpClient: '@http.client'

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    App\Service\Models\:
        resource: '../src/Service/Models'
        tags: ['@doctrine.orm.entity_manager','@nexy_slack.client']

    slack_client:
        class: 'App\Service\SlackClient'
        autowire : true
        arguments: ['@nexy_slack.client','@kernel']
        public : true

    callback_client:
        class: 'App\Service\Callback\Back'
        autowire: true
        arguments: ['@http.client']
        public: true

    App\Service\Apiclient\AteneaService:
        arguments: ["%kernel.environment%"]

    App\Service\Apiclient\UpmService:
        arguments: ["%kernel.environment%"]

    App\Service\Apiclient\HermesService:
        arguments: ["%kernel.environment%"]

    App\Service\Socket\:
        resource: '../src/Service/Socket'
        tags: ['@kernel','@nexy_slack.client']
</code>```

The problem is that if I run php bin / console debug: autowiring in the terminal, to know if I created it, it returns the following error :

You have requested a non-existent service "http.client".

In the end what I want to achieve is something like this:

```<code>public function getClient(Back $back)
{

    $back->sendCallback('GET','http://vro-back.localhost:8888/callback/test');

}
</code>```

But I can not because I can not inject it.

At the end if you look at the services.yml, I'm trying to create an alias for an HttpClient component, so I can pass it as an argument to the constructor of the Back class

And the route that I'm trying to load, exists ...

Symfony \ Component \ HttpClient \ HttpClient;

This is the component with which I am trying to work

https://symfony.com/doc/current/components/http_client.html

I would appreciate any help.

答:
You need to type-hint the interface instead

```<code>public function __construct(HttpClientInterface $httpClient)
{
    $this->httpClient = $httpClient;
}
</code>```

And remove service.yaml configuration
https://symfony.com/doc/current/components/http_client.html

Body:
I'm trying to create a service, which can be injected anywhere. For this I am trying to pass as argument the HttpClient component of Symfony 4.3

I show you the service

https://i.stack.imgur.com/2384M.png

    <?php

namespace App\Service\Callback;

use Symfony\Component\HttpClient\HttpClient;

class Back
{

    private $client;

    public function __construct(HttpClient $httpClient)
    {
        $this->client = $httpClient::create();
    }

    public function sendCallback ( $method, $urlCallback, $option)
    {
        $response = $this->client->request($method,$urlCallback,$option);

        $statusCode = $response->getStatusCode();
        return $statusCode;
    }

}

Well, I'm trying to load it in the services.yml

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: 'en'
    base_url_front: '%env(BASE_URL_FRONT)%'
    mobile_type: 2

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    Nexy\Slack\Client: '@nexy_slack.client'

    Symfony\Component\HttpClient\HttpClient: '@http.client'

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    App\Service\Models\:
        resource: '../src/Service/Models'
        tags: ['@doctrine.orm.entity_manager','@nexy_slack.client']

    slack_client:
        class: 'App\Service\SlackClient'
        autowire : true
        arguments: ['@nexy_slack.client','@kernel']
        public : true

    callback_client:
        class: 'App\Service\Callback\Back'
        autowire: true
        arguments: ['@http.client']
        public: true

    App\Service\Apiclient\AteneaService:
        arguments: ["%kernel.environment%"]

    App\Service\Apiclient\UpmService:
        arguments: ["%kernel.environment%"]

    App\Service\Apiclient\HermesService:
        arguments: ["%kernel.environment%"]

    App\Service\Socket\:
        resource: '../src/Service/Socket'
        tags: ['@kernel','@nexy_slack.client']

The problem is that if I run php bin / console debug: autowiring in the terminal, to know if I created it, it returns the following error :

You have requested a non-existent service "http.client".

In the end what I want to achieve is something like this:

public function getClient(Back $back)
{

    $back->sendCallback('GET','http://vro-back.localhost:8888/callback/test');

}

But I can not because I can not inject it.

At the end if you look at the services.yml, I'm trying to create an alias for an HttpClient component, so I can pass it as an argument to the constructor of the Back class

And the route that I'm trying to load, exists ...

Symfony \ Component \ HttpClient \ HttpClient;

This is the component with which I am trying to work

https://symfony.com/doc/current/components/http_client.html

I would appreciate any help.

Body:
You need to type-hint the interface instead

public function __construct(HttpClientInterface $httpClient)
{
    $this->httpClient = $httpClient;
}

And remove service.yaml configuration
https://symfony.com/doc/current/components/http_client.html


问:
How to clear memory completely of all matplotlib plots
I have a data analysis module that contains functions which call on the matplotlib.pyplot API multiple times to generate up to 30 figures in each run. These figures get immediately written to disk after they are generated, and so I need to clear them from memory.

Currently, at the end of each of my function, I do:

```<code>import matplotlib.pyplot as plt

plt.clf()
</code>```

However, I'm not too sure if this statement can actually clear the memory. I'm especially concerned since I see that each time I run my module for debugging, my free memory space keeps decreasing.

What do I need to do to really clear my memory each time after I have written the plots to disk?

答:
I have data analysis module that contains functions which call on Matplotlib pyplot API multiple

Can you edit your functions which is calling matplotlib? I was facing the same issue, I tried following command but none of it worked.

```<code>plt.close(fig)
fig.clf()
gc.collect()
%reset_selective -f fig
</code>```

Then one trick worked for me, instead of creating a new figure every time, I pass the same fig object to the function and this solved my issue.

for example use,

```<code>fig = plt.figure()
for i in range(100):
    plt.plot(x,y)
</code>```

instead of,

```<code>for i in range(100):
    fig = plt.figure()
    plt.plot(x,y)
</code>```

Body:
I have a data analysis module that contains functions which call on the matplotlib.pyplot API multiple times to generate up to 30 figures in each run. These figures get immediately written to disk after they are generated, and so I need to clear them from memory.

Currently, at the end of each of my function, I do:

import matplotlib.pyplot as plt

plt.clf()

However, I'm not too sure if this statement can actually clear the memory. I'm especially concerned since I see that each time I run my module for debugging, my free memory space keeps decreasing.

What do I need to do to really clear my memory each time after I have written the plots to disk?

Body:
I have data analysis module that contains functions which call on Matplotlib pyplot API multiple

Can you edit your functions which is calling matplotlib? I was facing the same issue, I tried following command but none of it worked.

plt.close(fig)
fig.clf()
gc.collect()
%reset_selective -f fig

Then one trick worked for me, instead of creating a new figure every time, I pass the same fig object to the function and this solved my issue.

for example use,

fig = plt.figure()
for i in range(100):
    plt.plot(x,y)

instead of,

for i in range(100):
    fig = plt.figure()
    plt.plot(x,y)


问:
Copying to arrays in NASM
I have to write in assembly code which copy 100 bytes in memory in loop. I wrote it like this:

```<code>section .data
    a times 100 db 1 ;reserve 100 bytes and fill with 1
    b times 100 db 0 ;reserve 100 bytes and fill with 0

    section _start
    global _start

    _start:
    mov rsi, a ;get array a address
    mov rdi, b ;get arrat b address

    _for: ;początek pętli
    cmp cx, 100     ;loop
    jae _end_for        ;loop
    push cx         ;loop

    mov byte al, [rsi]  ;get one byte from array a from al
    mov byte [rdi], al  ;put one byte from al to array b
    inc rsi         ;set rsi to next byte in array a
    inc rdi         ;set rdi to next byte in array b

    pop cx          ;loop
    inc cx          ;loop
    jmp _for        ;loop

_end_for:

_end:
    mov rax, 60
    mov rdi, 0
    syscall
</code>```

I'm not sure about the copying part. I read the value from the address to the register and then put it into another. That looks good to me, but I'm not sure about incrementing rsi and rdi.

Is it really enough?

I'm new to NASM and assembly, so please help :-)

答:
Is it really enough?

Yes; the code you've shown is enough to copy the array.

For performance/optimization the code you've shown could be better; but optimization is a slippery slope that takes a detour through "rep movsb is better for code size", passes through "SIMD with loop unrolling" and ends at "you can avoid the need to copy the array".

Title: Copying to arrays in NASM

Body:
I have to write in assembly code which copy 100 bytes in memory in loop. I wrote it like this:

section .data
    a times 100 db 1 ;reserve 100 bytes and fill with 1
    b times 100 db 0 ;reserve 100 bytes and fill with 0

    section _start
    global _start

    _start:
    mov rsi, a ;get array a address
    mov rdi, b ;get arrat b address

    _for: ;początek pętli
    cmp cx, 100     ;loop
    jae _end_for        ;loop
    push cx         ;loop

    mov byte al, [rsi]  ;get one byte from array a from al
    mov byte [rdi], al  ;put one byte from al to array b
    inc rsi         ;set rsi to next byte in array a
    inc rdi         ;set rdi to next byte in array b

    pop cx          ;loop
    inc cx          ;loop
    jmp _for        ;loop

_end_for:

_end:
    mov rax, 60
    mov rdi, 0
    syscall

I'm not sure about the copying part. I read the value from the address to the register and then put it into another. That looks good to me, but I'm not sure about incrementing rsi and rdi.

Is it really enough?

I'm new to NASM and assembly, so please help :-)


问:
LINQ Group elements that are equal together
I have a simple question on LINQ and haven't found an answer that directly addresses my question. Say I have an arbitrary collection of objects: {cat, apple, orange, cat, orange, apple, cat}. I want to order to use LINQ to order these lists by equality, e.g. so now the collection reads {apple, apple, orange, orange, cat, cat, cat}. It doesn't matter what order the types are (i.e. whether apple comes first or cat, for example), only that they are appropriately grouped.

Say I have access to Equals() or some boolean method to determine if any two instances are equal. How would I do this?

答:
Just sort the list. Since equal elements have the same rank in the order, they will be grouped together:

```<code> var items = new []{"cat", "apple", "orange", "cat", "orange", "apple", "cat"};
 var sorted = items.OrderBy(x => x);
</code>```

Result:

apple apple cat cat cat orange orange

Body:
Just sort the list. Since equal elements have the same rank in the order, they will be grouped together:

 var items = new []{"cat", "apple", "orange", "cat", "orange", "apple", "cat"};
 var sorted = items.OrderBy(x => x);

Result:

apple apple cat cat cat orange orange


问:
array manipulation
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:</p>

```<code>int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}
</code>```

答:
To do it manually, you need to copy the old data with the size of the original array, right now you're walking off the end of the original array.

Try this:

```<code>int *expand(int *&arr, int size)
{
    int *newArray;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: array manipulation

Body:
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:

int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}

Body:
To do it manually, you need to copy the old data with the size of the original array, right now you're walking off the end of the original array.

Try this:

int *expand(int *&arr, int size)
{
    int *newArray;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;
}


问:
What security rules should be added to Google Cloud Firestore to keep data safe where no authentication is required to access the app
I have an android app which is using Firestore as database. I need to make it secure but I am not using authentication service as it is not required.

I was thinking if I can sent a unique ID from android app which can be recognised in Firestore rules and only users(people using my app) can read or write to Firestore.

Below is my security rules -

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow readwrite ;
    }
  }
}
</code>```

I expect my Firestore database to be safe from non-users.

答:
I was thinking if I can sent a unique ID

You can't pass arbitrary values to security rules. To send that securely and get it into the security rules, you will have to pass it into the user's authentication token as a custom claim.

But even if you do that, what will keep a malicious user from finding that same secret values (it must be available in your app after all), and passing it into the security rules in the same way.

Coming to think of it, anonymous authentication and custom claims may be your solution. Use anonymous authentication on the client to generate a UID for the user, then (on a trusted environment, such as your development machine, a server you control, or Cloud Functions) give that user a custom claim, and check for that custom claim in your security rules.

Body:
I have an android app which is using Firestore as database. I need to make it secure but I am not using authentication service as it is not required.

I was thinking if I can sent a unique ID from android app which can be recognised in Firestore rules and only users(people using my app) can read or write to Firestore.

Below is my security rules -

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow readwrite ;
    }
  }
}

I expect my Firestore database to be safe from non-users.


问:
Can't send changed data from *ngFor generated form with inputs of object type
I have a problem with a form. I have a JSON object which includes some data and in HTML form I use ngFor to set every input tag in this form to have as value one of every value in this JSON.

The problem is that I won't after this when one of this inputs data change and the send button is clicked (its not necessary to have changes in the inputs values) all values to be stored back in the object and send to a method to console.log them.

The form template is:

```<code>    <form class="example-form"  style="margin-left: 500px;">
      <mat-form-field class="example-full-width" *ngFor=" let item of test | keyvalue">
        <input matInput placeholder="{{item.key}}" value="{{item.value}}" name="" >

      </mat-form-field>

      <button type="submit" (click)="send()">Send</button>

    </form>
</code>```

```<code>    async ngOnInit() {

        this.test= await this.authService.getMultilingual('au');
    }
</code>```

答:
Should you not be using ngModel? - that way you are binding the value in the json to the value of the input and subsequently changing the input value results in changing the data vale that you send?</p>

```<code><input matInput placeholder="{{item.key}}" [(ngModel)]="item.value" name="" >
</code>```

Body:
I have a problem with a form. I have a JSON object which includes some data and in HTML form I use ngFor to set every input tag in this form to have as value one of every value in this JSON.

The problem is that I won't after this when one of this inputs data change and the send button is clicked (its not necessary to have changes in the inputs values) all values to be stored back in the object and send to a method to console.log them.

The form template is:

    <form class="example-form"  style="margin-left: 500px;">
      <mat-form-field class="example-full-width" *ngFor=" let item of test | keyvalue">
        <input matInput placeholder="{{item.key}}" value="{{item.value}}" name="" >

      </mat-form-field>

      <button type="submit" (click)="send()">Send</button>

    </form>

    async ngOnInit() {

        this.test= await this.authService.getMultilingual('au');
    }

Body:
Should you not be using ngModel? - that way you are binding the value in the json to the value of the input and subsequently changing the input value results in changing the data vale that you send?

<input matInput placeholder="{{item.key}}" [(ngModel)]="item.value" name="" >


问:
Generating Pyramid to Show Numbers in Module 10
I am trying to generate pyramid starts with the number one (1), in each row the first digit determines the number of row. In addition, the first number in the row also determines the number of numbers in that order (according to module 10). All other numbers in a row we calculate by adding the number from the left and the number above it, according to module 10.

```<code>int n = 12;
int i, j;

for (i = 1; i <= n; i++) {
    for (j = 0; j <= i; j++) {
      int module = i % 10;

      System.out.print(module + " ");

    }

    System.out.println();
  }
}

</code>```

With my implementation, I get

```<code>1 1
2 2 2
3 3 3 3
4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6 6
7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2
</code>```

The actual result should be

```<code>1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6
1 1 0 6 4 2 2 0 2 8 4
2 3 4 4 0 4 6 8 8 0 8 2
</code>```

What am I missing?

答:
First you write a helper method to calculate the digit to display. This method takes as an argument the row index and column index or the row number and column number, whatever you are more comfortable with. Assuming we use 0-based indices for the row and column, we can define the following values for that method:

When the column index is 0 (so we are in the first column), the return value is the row index + 1 modulo 10.

When the row index is 0 (so we are at the top), the return value is 1.

For all the other positions, we use a recursive call of the helper method to add "the number from the left" with "the number above it".

The helper method will look like this:

```<code>/**
 * Calculate the digits. The arguments are 0 based.
 *
 * @param row The row index
 * @param column The column index
 * @return The digit to display
 */
public static int calculateDigit(int row, int column) {
    if (row < 0) {
        throw new IllegalArgumentException("The row index must not be negative");
    }
    if (column < 0) {
        throw new IllegalArgumentException("The column index must not be negative");
    }
    if (column == 0) {
        return (row+1) % 10; // simply return the row number
    }
    if (row == 0) {
        return 1; // in the first row, so it is the "1"
    }
    // calculate the new number based on the expression
    // "adding the number from the left and the number above it"
    int left = calculateDigit(row, column-1);
    int above = calculateDigit(row-1, column-1);
    int sum = left + above;
    int modulo = sum % 10;
    return modulo;
}
</code>```

You can use this helper method in the simple two for loops you already have.

```<code>for (int r=0; r<10; r++) {
    for (int c=0; c<=r; c++) {
        int value = calculateDigit(r, c);
        System.out.print(value+" ");
    }
    System.out.println();
}
</code>```

And this will get you the expected output:

```<code>1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6
</code>```

Body:
I am trying to generate pyramid starts with the number one (1), in each row the first digit determines the number of row. In addition, the first number in the row also determines the number of numbers in that order (according to module 10). All other numbers in a row we calculate by adding the number from the left and the number above it, according to module 10.

int n = 12;
int i, j;

for (i = 1; i <= n; i++) {
    for (j = 0; j <= i; j++) {
      int module = i % 10;

      System.out.print(module + " ");

    }

    System.out.println();
  }
}

With my implementation, I get

1 1
2 2 2
3 3 3 3
4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6 6
7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2

The actual result should be

1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6
1 1 0 6 4 2 2 0 2 8 4
2 3 4 4 0 4 6 8 8 0 8 2

What am I missing?

Body:
First you write a helper method to calculate the digit to display. This method takes as an argument the row index and column index or the row number and column number, whatever you are more comfortable with. Assuming we use 0-based indices for the row and column, we can define the following values for that method:

When the column index is 0 (so we are in the first column), the return value is the row index + 1 modulo 10.

When the row index is 0 (so we are at the top), the return value is 1.

For all the other positions, we use a recursive call of the helper method to add "the number from the left" with "the number above it".

The helper method will look like this:

/**
 * Calculate the digits. The arguments are 0 based.
 *
 * @param row The row index
 * @param column The column index
 * @return The digit to display
 */
public static int calculateDigit(int row, int column) {
    if (row < 0) {
        throw new IllegalArgumentException("The row index must not be negative");
    }
    if (column < 0) {
        throw new IllegalArgumentException("The column index must not be negative");
    }
    if (column == 0) {
        return (row+1) % 10; // simply return the row number
    }
    if (row == 0) {
        return 1; // in the first row, so it is the "1"
    }
    // calculate the new number based on the expression
    // "adding the number from the left and the number above it"
    int left = calculateDigit(row, column-1);
    int above = calculateDigit(row-1, column-1);
    int sum = left + above;
    int modulo = sum % 10;
    return modulo;
}

You can use this helper method in the simple two for loops you already have.

for (int r=0; r<10; r++) {
    for (int c=0; c<=r; c++) {
        int value = calculateDigit(r, c);
        System.out.print(value+" ");
    }
    System.out.println();
}

And this will get you the expected output:

1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6


问:
TypeError: 'bool' object is not callable in Pygame
This is my error:

```<code>g.run() TypeError: 'bool' object is not callable
</code>```

Here is my code:

```<code>import pygame
import time
pygame.init()

pygame.display.set_caption('Platformer')
class Game:
    def __init__(self):
        self.x=7
        self.y=400
        self.width=40
        self.height=60
        self.vel=7
        self.run=True
        self.isJump=False
        self.jumpCount=10
        self.clock = pygame.time.Clock()
        self.clock.tick(60)
        self.flag = False
        self.win=pygame.display.set_mode((1200, 600))
    #def playerCollide():
    def GameLoop(self):
        while run:
            print(y)
            if self.flag == False:
                print('yes')

            pygame.time.delay(15)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                    self.run == False
            keys = pygame.key.get_pressed()

            if self.flag == False and keys[pygame.K_SPACE] or keys[pygame.K_UP]:
                self.starttime = pygame.time.get_ticks()
                self.flag = True
                self.isJump=True
            if self.flag == True and pygame.time.get_ticks() - starttime >= 475:
                self.flag = False

            if keys[pygame.K_LEFT] and self.x > self.vel:
                self.x-=self.vel
            if keys[pygame.K_RIGHT] and self.x < 1200 - self.width - self.vel :
                self.x+=self.vel
            if not(self.isJump):
                if keys[pygame.K_DOWN] and self.y < 600 - self.height - self.vel:
                    self.y += 0

            else:
                if self.jumpCount >= -10:
                    self.y -= (self.jumpCount * abs(self.jumpCount)) * .55
                    self.jumpCount -= 1
                else:
                    self.jumpCount = 10
                    self.isJump = False
            self.win.fill((255,255,255))
            pygame.draw.rect(self.win, (0, 0, 0), (self.x,y, self.width, self.height))
            pygame.display.update()

g=Game()
g.run()
</code>```

答:
Instead of calling:

```<code>g.run()
</code>```

You need to call:

```<code>g.GameLoop()
</code>```

Since run is just a boolean variable in your class.

Body:
This is my error:

g.run() TypeError: 'bool' object is not callable

Here is my code:

import pygame
import time
pygame.init()

pygame.display.set_caption('Platformer')
class Game:
    def __init__(self):
        self.x=7
        self.y=400
        self.width=40
        self.height=60
        self.vel=7
        self.run=True
        self.isJump=False
        self.jumpCount=10
        self.clock = pygame.time.Clock()
        self.clock.tick(60)
        self.flag = False
        self.win=pygame.display.set_mode((1200, 600))
    #def playerCollide():
    def GameLoop(self):
        while run:
            print(y)
            if self.flag == False:
                print('yes')

            pygame.time.delay(15)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                    self.run == False
            keys = pygame.key.get_pressed()

            if self.flag == False and keys[pygame.K_SPACE] or keys[pygame.K_UP]:
                self.starttime = pygame.time.get_ticks()
                self.flag = True
                self.isJump=True
            if self.flag == True and pygame.time.get_ticks() - starttime >= 475:
                self.flag = False

            if keys[pygame.K_LEFT] and self.x > self.vel:
                self.x-=self.vel
            if keys[pygame.K_RIGHT] and self.x < 1200 - self.width - self.vel :
                self.x+=self.vel
            if not(self.isJump):
                if keys[pygame.K_DOWN] and self.y < 600 - self.height - self.vel:
                    self.y += 0

            else:
                if self.jumpCount >= -10:
                    self.y -= (self.jumpCount * abs(self.jumpCount)) * .55
                    self.jumpCount -= 1
                else:
                    self.jumpCount = 10
                    self.isJump = False
            self.win.fill((255,255,255))
            pygame.draw.rect(self.win, (0, 0, 0), (self.x,y, self.width, self.height))
            pygame.display.update()

g=Game()
g.run()

Body:
Instead of calling:

g.run()

You need to call:

g.GameLoop()

Since run is just a boolean variable in your class.


答:
A quick solution would be to order by object hash code. The code should look something like:

```<code>collection.OrderBy(o => o.GetHashCode());
</code>```

Another option is to use GroupBy to group the objects by Equality, HashCode or some custom Comparer function and then flatten the collection again.

```<code>collection.GroupBy(o => o.GetHashCode()).SelectMany(o => o);
</code>```

or

```<code>collection.GroupBy(o => o, <CustomComparerFunction>).SelectMany(o => o);
</code>```

Title: LINQ Group elements that are equal together

Body:
I have a simple question on LINQ and haven't found an answer that directly addresses my question. Say I have an arbitrary collection of objects: {cat, apple, orange, cat, orange, apple, cat}. I want to order to use LINQ to order these lists by equality, e.g. so now the collection reads {apple, apple, orange, orange, cat, cat, cat}. It doesn't matter what order the types are (i.e. whether apple comes first or cat, for example), only that they are appropriately grouped.

Say I have access to Equals() or some boolean method to determine if any two instances are equal. How would I do this?

Body:
A quick solution would be to order by object hash code. The code should look something like:

collection.OrderBy(o => o.GetHashCode());

Another option is to use GroupBy to group the objects by Equality, HashCode or some custom Comparer function and then flatten the collection again.

collection.GroupBy(o => o.GetHashCode()).SelectMany(o => o);

or

collection.GroupBy(o => o, <CustomComparerFunction>).SelectMany(o => o);


问:
How to add spinner/loader in yii2 php
I want to add a spinner/loader in one of my forms. The scenario is simple: When I hit the create button then it will show a spinner/loader. On hitting the create button a call to a web-service is made so the spinner/loader will show from call start to call end.

Below is my controller:

```<code>$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);
$msn = $m->meter_serial; // current selected meter serial number is saved

$date_time = str_replace(' ', 'T', date('Y-m-d H:i:s')); // current date time

$api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $msn . '/' .$date_time; // my base URL

$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization:key'));

$curl_response = curl_exec($curl);
$json = json_decode($curl_response);
$meter_alive = $json->data->Response;
.
.
.
.
// my other code that is saving data
.
.
.
.
return $this->render('create', ['model' => $model,]);
</code>```

The submit button is below:

```<code><div class="form-group">
   <?= Html::submitButton($model->isNewRecord ? 'Verify Communication' : 'Update', ['id'=> 'spin','name'=>'create','class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>

</div>
</code>```

As told above when I press the Verify Communication button a call is made to the web-service and during this time I want to show a spinner/loader.

For creating/showing a spinner/loader I have searched many articles.

Show Loading

Kartik Spinner

Submit Spinner

Yii2 Model Loader

Yii2 Jquery Loading

But none of the above articles have mentioned the full implementation details. Although I have tried each and every step mentioned in the articles.

Any help would be highly appreciated.

答:
No validation on user request

```<code>$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);
</code>```

it's too much

```<code>$msn = $m->meter_serial;
</code>```

do this

```<code>$api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $m->meter_serial . '/' .$date_time;
</code>```

Curl request need to be moved to separated method

```<code>function curlRequest(msn) {
  $api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $msn . '/' .$date_time; // my base URL
  $curl = curl_init($api_url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization:key'));
  $curl_response = curl_exec($curl);
  $json = json_decode($curl_response); // WTF snake case only in Python

  return $json->data->Response;
}
</code>```

And now answer to your question
You need add click event to your button. You using Yii2 his have jQuery for more powerful DOM-tools. Use $.hide() and $.show() for you button class and draw preloader. You can use Promise if you need feedback from server of his save data.

Title: How to add spinner/loader in yii2 php

Body:
I want to add a spinner/loader in one of my forms. The scenario is simple: When I hit the create button then it will show a spinner/loader. On hitting the create button a call to a web-service is made so the spinner/loader will show from call start to call end.

Below is my controller:

$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);
$msn = $m->meter_serial; // current selected meter serial number is saved

$date_time = str_replace(' ', 'T', date('Y-m-d H:i:s')); // current date time

$api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $msn . '/' .$date_time; // my base URL

$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization:key'));

$curl_response = curl_exec($curl);
$json = json_decode($curl_response);
$meter_alive = $json->data->Response;
.
.
.
.
// my other code that is saving data
.
.
.
.
return $this->render('create', ['model' => $model,]);

The submit button is below:

   <?= Html::submitButton($model->isNewRecord ? 'Verify Communication' : 'Update', ['id'=> 'spin','name'=>'create','class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>

As told above when I press the Verify Communication button a call is made to the web-service and during this time I want to show a spinner/loader.

For creating/showing a spinner/loader I have searched many articles.

Show Loading

Kartik Spinner

Submit Spinner

Yii2 Model Loader

Yii2 Jquery Loading

But none of the above articles have mentioned the full implementation details. Although I have tried each and every step mentioned in the articles.

Any help would be highly appreciated.

Body:
No validation on user request

$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);

it's too much

$msn = $m->meter_serial;

do this

$api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $m->meter_serial . '/' .$date_time;

Curl request need to be moved to separated method

function curlRequest(msn) {
  $api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $msn . '/' .$date_time; // my base URL
  $curl = curl_init($api_url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization:key'));
  $curl_response = curl_exec($curl);
  $json = json_decode($curl_response); // WTF snake case only in Python

  return $json->data->Response;
}

And now answer to your question
You need add click event to your button. You using Yii2 his have jQuery for more powerful DOM-tools. Use $.hide() and $.show() for you button class and draw preloader. You can use Promise if you need feedback from server of his save data.


答:
```<code>var values = new List<string> { "cat", "apple", "orange", "cat", "orange", "apple", "cat" };
var orderedAlphabetically = values.OrderBy(v => v);
</code>```


答:
Adding to what Adrian said,

If you wanted to group them together...

```<code>var items = new []{"cat", "apple", "orange", "cat", "orange", "apple", "cat"};
var sorted = items.GroupBy(x => x).OrderBy(x => x).Select(x => x);
</code>```

You now have 3 distinct groups ordered by their count

apple orange cat

You can further iterate over the group

```<code>foreach (var x in sorted)
{
   foreach (var y in x)
   {
      Console.Write(y);
    }
}
</code>```

apple apple orange orange cat cat cat

Body:
Adding to what Adrian said,

If you wanted to group them together...

var items = new []{"cat", "apple", "orange", "cat", "orange", "apple", "cat"};
var sorted = items.GroupBy(x => x).OrderBy(x => x).Select(x => x);

You now have 3 distinct groups ordered by their count

apple orange cat

You can further iterate over the group

foreach (var x in sorted)
{
   foreach (var y in x)
   {
      Console.Write(y);
    }
}

apple apple orange orange cat cat cat


问:
Setting textbox encoding in Windows Forms
When I try to get some text from file and display it in textbox it is okay until I want to write Czech characters (e. g. čšž). They show up like: Moj� nejv�t�� z�libou je �e�en� koresponden�n�ch semin���

Should I set encoding to loaded text just before I assign it to textBox1.text or it is possible to change encoding of textBox1.Text itself?

I use following code:

```<code>textBox1.Text = File.ReadAllText(file);
</code>```

答:
From MSDN for ReadAllText()

This method attempts to automatically
  detect the encoding of a file based on
  the presence of byte order marks.
  Encoding formats UTF-8 and UTF-32
  (both big-endian and little-endian)
  can be detected.

Use the ReadAllText(String, Encoding)
  method overload when reading files
  that might contain imported text,
  because unrecognized characters may
  not be read correctly.

Try using the other overload to explicitly specify the Encoding since automatic detection is not working in your case, something like

```<code>textBox1.Text = File.ReadAllText(file, Encoding.UTF8);
</code>```

Body:
When I try to get some text from file and display it in textbox it is okay until I want to write Czech characters (e. g. čšž). They show up like: Moj� nejv�t�� z�libou je �e�en� koresponden�n�ch semin���

Should I set encoding to loaded text just before I assign it to textBox1.text or it is possible to change encoding of textBox1.Text itself?

I use following code:

textBox1.Text = File.ReadAllText(file);

Body:
From MSDN for ReadAllText()

This method attempts to automatically
  detect the encoding of a file based on
  the presence of byte order marks.
  Encoding formats UTF-8 and UTF-32
  (both big-endian and little-endian)
  can be detected.

Use the ReadAllText(String, Encoding)
  method overload when reading files
  that might contain imported text,
  because unrecognized characters may
  not be read correctly.

Try using the other overload to explicitly specify the Encoding since automatic detection is not working in your case, something like

textBox1.Text = File.ReadAllText(file, Encoding.UTF8);


问:
Phaser 3 create circle zone
There is a certain class "monster". He has a zone of so-called Agro. Which is activated when a player enters it. But the problem is that I can’t, and I don’t know how to make it round. There are experts in this field who can tell you how to do it right?

Class code on TS:

```<code>import Creature from "./Creature";

export default class Monster extends Creature {
    private readonly speed: number;
    private agroZone!: Phaser.GameObjects.Zone;
    private target!: Phaser.Physics.Arcade.Sprite

    constructor(scene: Phaser.Scene, x: number, y: number, texture: string,
frames?: string | number) {
        super(scene, x, y, texture, frames);

        this.hp.max = 10;
        this.hp.current = 10;
        this.hpBarConfig = {
            x: 250,
            y: 10,
            color: 0x15fa03,
            fixed:true
        };

        this.updateHpBar();

        this.speed = 50;

        this.scene.events.on('update', this.updateScene);
    }

    private updateScene = () => {
      this.checkAgroZone(this.target);
    };

    public initAgroZone = (target: Phaser.Physics.Arcade.Sprite) =>{
        this.target = target;
        this.agroZone = this.scene.add.zone(this.body.x, this.body.y, 200, 200);
        this.agroZone.setOrigin(0.5, 0.5);
        this.scene.physics.world.enable(this.agroZone, 0);
        this.agroZone.body.moves = false;
        this.scene.physics.add.overlap(target, this.agroZone);

        this.agroZone.on("enterzone", () => {console.log("!!!!!!!!!!!");});
    };

    private checkAgroZone = (target) => {
        if(target){
            const touching = this.agroZone.body.touching;
            const wasTouching = this.agroZone.body.wasTouching;

            if (touching.none && !wasTouching.none) {
                this.agroZone.emit('leavezone');
            }
            else if (!touching.none && wasTouching.none) {
                this.agroZone.emit('enterzone');
            }

            this.agroZone.body.debugBodyColor =
this.agroZone.body.touching.none ? 0x00ffff : 0xffff00;
        }
    };

    chaseTarget(obj: Phaser.Physics.Arcade.Sprite){
        this.scene.physics.moveToObject(this, obj, this.speed);
    }
}
</code>```

答:
In case you want to draw a cricle here is how to do

var config = {
    width: 800,
    height: 600,
    type: Phaser.AUTO,
    loader: {
      baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
      crossOrigin: 'anonymous'
    },
    parent: 'phaser-example',
    physics: {
      default: 'arcade'
    },
    scene: {
      preload: preload,
      create: create,
      update:update
    }
};

var game = new Phaser.Game(config);

var player;
var cursors;

function preload()
{
  this.load.image('dude', 'sprites/phaser-dude.png')
}

function create ()
{

  var graphics = this.add.graphics({ fillStyle: { color: 0xff0000 } });
  var circle = new Phaser.Geom.Circle(50, 50, 50);
  graphics.fillCircleShape(circle);
  this.physics.add.existing(graphics);

  player = this.physics.add.sprite(300, 100, 'dude');
  player.setCollideWorldBounds(true);

  cursors = this.input.keyboard.createCursorKeys();

  this.physics.add.overlap(player, graphics, inZone);
}

function inZone (){
  console.log("Player in the circle")
}

function update()
{
  if (cursors.left.isDown)
  {
      player.setVelocityX(-160);
  }
  else if (cursors.right.isDown)
  {
      player.setVelocityX(160);
  }
  else if (cursors.down.isDown)
  {
      player.setVelocityY(160);

  }
  else if (cursors.up.isDown)
  {
      player.setVelocityY(-160);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script></code>```

Title: Phaser 3 create circle zone

Body:
There is a certain class "monster". He has a zone of so-called Agro. Which is activated when a player enters it. But the problem is that I can’t, and I don’t know how to make it round. There are experts in this field who can tell you how to do it right?

Class code on TS:

import Creature from "./Creature";

export default class Monster extends Creature {
    private readonly speed: number;
    private agroZone!: Phaser.GameObjects.Zone;
    private target!: Phaser.Physics.Arcade.Sprite

    constructor(scene: Phaser.Scene, x: number, y: number, texture: string,
frames?: string | number) {
        super(scene, x, y, texture, frames);

        this.hp.max = 10;
        this.hp.current = 10;
        this.hpBarConfig = {
            x: 250,
            y: 10,
            color: 0x15fa03,
            fixed:true
        };

        this.updateHpBar();

        this.speed = 50;

        this.scene.events.on('update', this.updateScene);
    }

    private updateScene = () => {
      this.checkAgroZone(this.target);
    };

    public initAgroZone = (target: Phaser.Physics.Arcade.Sprite) =>{
        this.target = target;
        this.agroZone = this.scene.add.zone(this.body.x, this.body.y, 200, 200);
        this.agroZone.setOrigin(0.5, 0.5);
        this.scene.physics.world.enable(this.agroZone, 0);
        this.agroZone.body.moves = false;
        this.scene.physics.add.overlap(target, this.agroZone);

        this.agroZone.on("enterzone", () => {console.log("!!!!!!!!!!!");});
    };

    private checkAgroZone = (target) => {
        if(target){
            const touching = this.agroZone.body.touching;
            const wasTouching = this.agroZone.body.wasTouching;

            if (touching.none && !wasTouching.none) {
                this.agroZone.emit('leavezone');
            }
            else if (!touching.none && wasTouching.none) {
                this.agroZone.emit('enterzone');
            }

            this.agroZone.body.debugBodyColor =
this.agroZone.body.touching.none ? 0x00ffff : 0xffff00;
        }
    };

    chaseTarget(obj: Phaser.Physics.Arcade.Sprite){
        this.scene.physics.moveToObject(this, obj, this.speed);
    }
}

Body:
In case you want to draw a cricle here is how to do

var config = {
    width: 800,
    height: 600,
    type: Phaser.AUTO,
    loader: {
      baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
      crossOrigin: 'anonymous'
    },
    parent: 'phaser-example',
    physics: {
      default: 'arcade'
    },
    scene: {
      preload: preload,
      create: create,
      update:update
    }
};

var game = new Phaser.Game(config);

var player;
var cursors;

function preload()
{
  this.load.image('dude', 'sprites/phaser-dude.png')
}

function create ()
{

  var graphics = this.add.graphics({ fillStyle: { color: 0xff0000 } });
  var circle = new Phaser.Geom.Circle(50, 50, 50);
  graphics.fillCircleShape(circle);
  this.physics.add.existing(graphics);

  player = this.physics.add.sprite(300, 100, 'dude');
  player.setCollideWorldBounds(true);

  cursors = this.input.keyboard.createCursorKeys();

  this.physics.add.overlap(player, graphics, inZone);
}

function inZone (){
  console.log("Player in the circle")
}

function update()
{
  if (cursors.left.isDown)
  {
      player.setVelocityX(-160);
  }
  else if (cursors.right.isDown)
  {
      player.setVelocityX(160);
  }
  else if (cursors.down.isDown)
  {
      player.setVelocityY(160);

  }
  else if (cursors.up.isDown)
  {
      player.setVelocityY(-160);
  }
}

<script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script>


问:
Add cornerRadius to the 1st and 3td UICollectionViewCell in a 3 cells per row layout
I have a UICollectionView that has 3 cells per row. I need to set topLeft and bottomLeft cornerRadius to the left one, and topRight and bottomRight to the right one. The center one does not have cornerRadius.

Extension method the sets cornerRadius

```<code>func setRadius(corners: UIRectCorner, radius: CGFloat) {
    let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
    let mask = CAShapeLayer()
    mask.path = path.cgPath
    layer.mask = mask
}
</code>```

I have used this code to find out which one of the cells needs to have cornerRadius.

```<code>    let index = indexPath.row

    if index == 0 || index % 3 == 0 {
        cell.setRadius(corners: [.topLeft, .bottomLeft], radius: TPSetting.cornerRadius)
    }

    else  if ( index - 2) % 3 == 0 {
        cell.setRadius(corners: [.topRight, .bottomRight], radius: TPSetting.cornerRadius)
    } else {
        cell.layer.cornerRadius = 0
    }
</code>```

This works as expected for the first time. But when upon calling collectionView.reloadData(), it messes up and the center one gets also topRight and bottomRight cornerRadius.

How to fix this issue?

答:
Cells being reused without being deallocated when you scroll / reload data. That's expected behaviour.

In order to "reset" introduced changes to corner radius, you can:

Subclass cell.

Override prepareForReuse method in subclass to undo changes introduced in setRadius method. Docs

Don't forget to call super.prepareForReuse inside overriden method.

Put the code inside method:

```<code>self.layer.mask = nil
self.layer.cornerRadius = 0
</code>```

Body:
I have a UICollectionView that has 3 cells per row. I need to set topLeft and bottomLeft cornerRadius to the left one, and topRight and bottomRight to the right one. The center one does not have cornerRadius.

Extension method the sets cornerRadius

func setRadius(corners: UIRectCorner, radius: CGFloat) {
    let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
    let mask = CAShapeLayer()
    mask.path = path.cgPath
    layer.mask = mask
}

I have used this code to find out which one of the cells needs to have cornerRadius.

    let index = indexPath.row

    if index == 0 || index % 3 == 0 {
        cell.setRadius(corners: [.topLeft, .bottomLeft], radius: TPSetting.cornerRadius)
    }

    else  if ( index - 2) % 3 == 0 {
        cell.setRadius(corners: [.topRight, .bottomRight], radius: TPSetting.cornerRadius)
    } else {
        cell.layer.cornerRadius = 0
    }

This works as expected for the first time. But when upon calling collectionView.reloadData(), it messes up and the center one gets also topRight and bottomRight cornerRadius.

How to fix this issue?

Body:
Cells being reused without being deallocated when you scroll / reload data. That's expected behaviour.

In order to "reset" introduced changes to corner radius, you can:

Subclass cell.

Override prepareForReuse method in subclass to undo changes introduced in setRadius method. Docs

Don't forget to call super.prepareForReuse inside overriden method.

Put the code inside method:

self.layer.mask = nil
self.layer.cornerRadius = 0


问:
I'm having trouble understanding how .next(), .nextInt(), and .hasNextInt() all work in relation to one another in java?
I've looked at the documentation for the methods but I still can't quite understand how they work. Here are my questions: .hasNextInt() checks the next integer value and doesn't consume anything, yet in my code below the first time it appears it allows a user to enter a value; why is that? Afterwards I have to use .next() to clear the current value of the scanner object I'm using and will not be prompted for a new value if I remove this from the while loop.

As for .nextInt(), it's only on the first iteration in the code that it checks for the last integer value in the scanner object, but when I enter it again it allows me to enter in a new value. This all seems very inconsistent and I'm having a hard time understanding what's going on under the hood.

```<code>    int integer=0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter an integer");

    while(!scan.hasNextInt())
    {
        System.out.println("Wrong");
        scan.next();
    }

    integer = scan.nextInt();
    System.out.println(integer);

    int newNumber = scan.nextInt();
    System.out.println(newNumber);
</code>```

答:
the nextInt function doesn't consume new line characters

therefore you need to run a Scanner.nextLine to consume the rest of the line,

It's already explained in more detail here

Scanner is skipping nextLine() after using next() or nextFoo()?

Body:
I've looked at the documentation for the methods but I still can't quite understand how they work. Here are my questions: .hasNextInt() checks the next integer value and doesn't consume anything, yet in my code below the first time it appears it allows a user to enter a value; why is that? Afterwards I have to use .next() to clear the current value of the scanner object I'm using and will not be prompted for a new value if I remove this from the while loop.

As for .nextInt(), it's only on the first iteration in the code that it checks for the last integer value in the scanner object, but when I enter it again it allows me to enter in a new value. This all seems very inconsistent and I'm having a hard time understanding what's going on under the hood.

    int integer=0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter an integer");

    while(!scan.hasNextInt())
    {
        System.out.println("Wrong");
        scan.next();
    }

    integer = scan.nextInt();
    System.out.println(integer);

    int newNumber = scan.nextInt();
    System.out.println(newNumber);


问:
Is there a focus lost event dispatcher for a kivy TextInput?

Problem:

Is there a way to fire an event if a multiline = True TextInput lost its focus?

Background:

I have tried on_touch_up function.  But it returns the instances of all my TextInputs, not just the current widget.  I tried text_validate_unfocus = False, with the same result.

Code:

```<code>import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty, NumericProperty
from kivy.uix.textinput import TextInput
from kivy.uix.bubble import Bubble
from kivy.lang import Builder
from kivy.storage.jsonstore import JsonStore

Builder.load_string('''
#: import Window kivy.core.window.Window
<Button>:
    background_normal: ''
<Label>:
    canvas.before:
        Color:
            rgba: (0,0.59,0.36,1)
        Rectangle:
            pos: self.pos
            size: self.size
<TextInput>:
    hint_text: 'Nuwe nota'
    font_size: self.height / 4.5 if self.focus else self.height / 3
    background_normal: ''
    background_active: ''
    foreground_color: (0,0.61,0.36,1) if self.focus else (0.71,0.75,0.71,1)
    unfocus_on_touch: False
    canvas.after:
        Color:
            rgb: (0,0,0,1)
        Line:
            points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1]
    size_hint_y: None
    height: Window.height / 6 if self.focus else Window.height / 12
<ChoiceBubble>:
    orientation: 'horizontal'
    size_hint: (None, None)
    size: (160, 120)
    pos_hint: {'top': 0.2, 'right': 0.8}
    arrow_pos: 'top_left'
    BubbleButton:
        text: 'Save'
    BubbleButton:
        text: 'Encrypt..'
    BubbleButton:
        text: 'Delete'
        on_release: root.del_txt_input()
<Notation>:
    canvas:
        Color:
            rgba: (0,0.43,0.37,1)
        Rectangle:
            pos: self.pos
            size: self.size
    Label:
        pos_hint: {'top': 1, 'right': 0.8}
        size_hint: [0.8, None]
        height: Window.height / 15
    Button:
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 0.9}
        size_hint: [0.1, None]
        height: Window.height / 15
        Image:
            source: 'gear_2.png'
            center_y: self.parent.center_y
            center_x: self.parent.center_x
            size: self.parent.width /1.5, self.parent.height/ 1.5
            allow_stretch: True
    Button:
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 1}
        size_hint: [0.1, None]
        height: Window.height / 15
        on_release: root.add_input()
        Image:
            source: 'plus_text12354.png'
            center_y: self.parent.center_y
            center_x: self.parent.center_x
            size: self.parent.width /1.5, self.parent.height/ 1.5
            allow_stretch: True
    ScrollView:
        size_hint_y: None
        size: Window.width, Window.height
        pos_hint: {'top': 0.92, 'right': 1}
        GridLayout:
            id: text_holder
            cols: 1
            pos_hint: {'top': 0.92, 'right': 1}
            padding: 4
            size_hint_x: 1
            size_hint_y: None
            height: self.minimum_height

''')
class ChoiceBubble(Bubble):
    pass
class TextInput(TextInput):
    got_txt = ObjectProperty(None)
    def on_touch_up(self, touch):
        if not self.collide_point(*touch.pos):
            self.text_validate_unfocus = False
            note = Notation()
            note.show_bubble
            self.got_txt=note.que_txt_input(self)
        return super(TextInput, self).on_touch_up(touch)
class Notation(FloatLayout):
    which_txt = ObjectProperty(None)
    new_txt = ObjectProperty(None)
    cnt = NumericProperty(0)
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.the_file=JsonStore('txt_input.json')
        self.cnt = self.the_file.count()
        lst = self.the_file.keys
    def add_input(self):
        txt_hld = self.ids.text_holder
        self.cnt += 1
        self.new_txt = TextInput(id=str(self.cnt))
        self.the_file.put(str(self.cnt), the_id=str(self.cnt), the_input='')
        txt_hld.add_widget(self.new_txt)
    def que_txt_input(self, instance):
        self.which_txt = instance
        print(instance.text, instance)
        return instance
    def del_txt_input(self):
        print(self.which_txt)
    def the_file(self, notestore):
        self.notestore = notestore
    def show_bubble(self):
        self.add_widget(ChoiceBubble())
    def get_store(self):
        the_keys = list(self.the_file.keys)
        print(the_keys)
        return the_keys

class theNoteApp(App):
    title = 'My Notes'
    def build(self):
        return Notation()

if __name__ == '__main__':
    theNoteApp().run()

</code>```

Desired Result:

Once the focus is lost I want a bubble widget to be added to the top of my root class.  This will give the user the option to save, encrypt or delete the TextInput id and text that just lost its focus, to a JSON file.

答:
The on_focus event will fire when the focus boolean changes.

I have tried on_touch_up function. But it returns the instances of all my TextInputs, not just the current widget.

This is because you didn't write any code that would limit it to the widget you care about, you can do this if you want to.

Body:
Problem:

Is there a way to fire an event if a multiline = True TextInput lost its focus?

Background:

I have tried on_touch_up function.  But it returns the instances of all my TextInputs, not just the current widget.  I tried text_validate_unfocus = False, with the same result.

Code:

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty, NumericProperty
from kivy.uix.textinput import TextInput
from kivy.uix.bubble import Bubble
from kivy.lang import Builder
from kivy.storage.jsonstore import JsonStore

Builder.load_string('''
#: import Window kivy.core.window.Window
<Button>:
    background_normal: ''
:
    canvas.before:
        Color:
            rgba: (0,0.59,0.36,1)
        Rectangle:
            pos: self.pos
            size: self.size
<TextInput>:
    hint_text: 'Nuwe nota'
    font_size: self.height / 4.5 if self.focus else self.height / 3
    background_normal: ''
    background_active: ''
    foreground_color: (0,0.61,0.36,1) if self.focus else (0.71,0.75,0.71,1)
    unfocus_on_touch: False
    canvas.after:
        Color:
            rgb: (0,0,0,1)
        Line:
            points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1]
    size_hint_y: None
    height: Window.height / 6 if self.focus else Window.height / 12
<ChoiceBubble>:
    orientation: 'horizontal'
    size_hint: (None, None)
    size: (160, 120)
    pos_hint: {'top': 0.2, 'right': 0.8}
    arrow_pos: 'top_left'
    BubbleButton:
        text: 'Save'
    BubbleButton:
        text: 'Encrypt..'
    BubbleButton:
        text: 'Delete'
        on_release: root.del_txt_input()
<Notation>:
    canvas:
        Color:
            rgba: (0,0.43,0.37,1)
        Rectangle:
            pos: self.pos
            size: self.size
    Label:
        pos_hint: {'top': 1, 'right': 0.8}
        size_hint: [0.8, None]
        height: Window.height / 15
    Button:
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 0.9}
        size_hint: [0.1, None]
        height: Window.height / 15
        Image:
            source: 'gear_2.png'
            center_y: self.parent.center_y
            center_x: self.parent.center_x
            size: self.parent.width /1.5, self.parent.height/ 1.5
            allow_stretch: True
    Button:
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 1}
        size_hint: [0.1, None]
        height: Window.height / 15
        on_release: root.add_input()
        Image:
            source: 'plus_text12354.png'
            center_y: self.parent.center_y
            center_x: self.parent.center_x
            size: self.parent.width /1.5, self.parent.height/ 1.5
            allow_stretch: True
    ScrollView:
        size_hint_y: None
        size: Window.width, Window.height
        pos_hint: {'top': 0.92, 'right': 1}
        GridLayout:
            id: text_holder
            cols: 1
            pos_hint: {'top': 0.92, 'right': 1}
            padding: 4
            size_hint_x: 1
            size_hint_y: None
            height: self.minimum_height

''')
class ChoiceBubble(Bubble):
    pass
class TextInput(TextInput):
    got_txt = ObjectProperty(None)
    def on_touch_up(self, touch):
        if not self.collide_point(*touch.pos):
            self.text_validate_unfocus = False
            note = Notation()
            note.show_bubble
            self.got_txt=note.que_txt_input(self)
        return super(TextInput, self).on_touch_up(touch)
class Notation(FloatLayout):
    which_txt = ObjectProperty(None)
    new_txt = ObjectProperty(None)
    cnt = NumericProperty(0)
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.the_file=JsonStore('txt_input.json')
        self.cnt = self.the_file.count()
        lst = self.the_file.keys
    def add_input(self):
        txt_hld = self.ids.text_holder
        self.cnt += 1
        self.new_txt = TextInput(id=str(self.cnt))
        self.the_file.put(str(self.cnt), the_id=str(self.cnt), the_input='')
        txt_hld.add_widget(self.new_txt)
    def que_txt_input(self, instance):
        self.which_txt = instance
        print(instance.text, instance)
        return instance
    def del_txt_input(self):
        print(self.which_txt)
    def the_file(self, notestore):
        self.notestore = notestore
    def show_bubble(self):
        self.add_widget(ChoiceBubble())
    def get_store(self):
        the_keys = list(self.the_file.keys)
        print(the_keys)
        return the_keys

class theNoteApp(App):
    title = 'My Notes'
    def build(self):
        return Notation()

if __name__ == '__main__':
    theNoteApp().run()

Desired Result:

Once the focus is lost I want a bubble widget to be added to the top of my root class.  This will give the user the option to save, encrypt or delete the TextInput id and text that just lost its focus, to a JSON file.


问:
Override the enter key, but keep default behavior for other keys in a wpf datagrid
It really bothers me that the pressing the enter key in a Datagrid moves the selection down one item, I'd like to be able to decide what it does in a normal keydown event.

So what I did was create a new class that inherits DataGrid and override the OnKeyDown event and use that as my datagrid.

This creates a whole new set of problems, since I apparently have to rewrite all the other keypresses (arrow key navigation, shift+arrow key selection, pgup/pgdn, etc..). I've been trying to hack it, but it just seems so pointless spending time rewriting something that has already been written and probably better then whatever I'll come up with.

So how can I make the enter key do what I want without messing with the other default keybindings of the datagrid?

Thanks in advance

答:
If it works similiarly to winforms, for the key presses that you aren't handling, than flag the handled as false, and it will pass the key press along.
KeyEventArgs Class

Handled Gets or sets a value that indicates the present state of the event handling for a routed event as it travels the route. (Inherited from RoutedEventArgs.)


问:
How can I send ether between two ACCOUNTS in remix IDE?
I can only send the ether if I deposit the ether while creating the contract. But in this case, even if the ether is in my wallet, I can send as much ether as the amount of ether in the contract. For example:
I have 100 ethereum in my account and I used 10 ether while creating smart contract, but I have to send 15 ether to other account. But I can't send because it is more than the amount of ether contract. I need to send ether to other account from my wallet.

Environment is Remix IDE, Contract versions is
pragma solidity ^0.5.0;

```<code>    function payBack (address payable user) public payable returns(bool) {
        uint256 money =  balanceOf(user)*convertNumber/1e18;

        require (msg.sender.balance/1e18 > money, "not enough money" );
        user.send(money*1000000000000000000);
        return true;

    }
</code>```

答:
Welcome to Stack Overflow

If you're using https://remix.ethereum.org you can see the "Environment" in the top right hand corner of the IDE.

According to the docs:

There are 3 type of environments Remix can be plugged to: Javascript VM, Injected provider, or Web3 provider. (for details see Running transactions)

These three environments are:

The JavascriptVM is running a sandboxed blockchain in your browser where execution runs in your browser. This means you don’t need any other software or Ethereum node to run it. This makes it very simple to deploy contract and interact with contracts limits your ability to manage account

The Web3 provider will make remix connect to a remote node. You will need to provide the URL address to the selected provider: geth, parity or any Ethereum client. You can use a tool like ganache-cli which simulates a blockchain locally on your computer as well.

The Injected Provider will make remix connect to an injected web3 provider. Metamask is an example of providers that inject web3, thus can be used with this option.

See docs for more information about environments.

I'm going to guess you're using the JavaScriptVM environment which means, unfortunately, you won't have access to web3 command tools (which need Web3 Provider or Injection). Without web3 you can't move funds between accounts by constructing transactions.

What you can do is download ganache-cli or your favourite web3 provider, and manipulate accounts from the terminal using web3 commands.

For example:

```<code>   $ ganache-cli

Available Accounts <ADDRESSES YOU CAN MOVE FUNDS BETWEEN>
==================
(0) 0x9f0bf61721a61e7f72abac48eed65e318668e71f (~100 ETH)
(1) 0x74bc67c48eefc359d296023acd4ac9158575ab56 (~100 ETH)
(2) 0xec548e4b5246795b81904bc67cedfe26b528b173 (~100 ETH)
(3) 0x06fe6ca72d985252729a2ba2a40147d4905a56c4 (~100 ETH)
(4) 0x262498200090fdaa7db8d430e681e39d6257d3ce (~100 ETH)
(5) 0x9736aa7dc69bee01166352c3e51023ee5ab57a08 (~100 ETH)
(6) 0x19ee475e3c64935546d9c4a67d01232c53d45c2b (~100 ETH)
(7) 0xee4dec500f7b08dfe20646a8a6661a81204eb1cb (~100 ETH)
(8) 0xf5b6a5ce718ad527eb877a0c8554e1d2382c9beb (~100 ETH)
(9) 0x590e03591cc82e9308d1e8e8869c248e13356920 (~100 ETH)

<Secret private keys not shown >

HD Wallet
==================
<Mnemonics not shown >

Base HD Path:  m/44'/60'/0'/0/{account_index}

Gas Price
==================
20000000000

Gas Limit
==================
6721975

Listening on 127.0.0.1:8545
</code>```

Body:
I can only send the ether if I deposit the ether while creating the contract. But in this case, even if the ether is in my wallet, I can send as much ether as the amount of ether in the contract. For example:
I have 100 ethereum in my account and I used 10 ether while creating smart contract, but I have to send 15 ether to other account. But I can't send because it is more than the amount of ether contract. I need to send ether to other account from my wallet.

Environment is Remix IDE, Contract versions is
pragma solidity ^0.5.0;

    function payBack (address payable user) public payable returns(bool) {
        uint256 money =  balanceOf(user)*convertNumber/1e18;

        require (msg.sender.balance/1e18 > money, "not enough money" );
        user.send(money*1000000000000000000);
        return true;

    }

Body:
 Welcome to Stack Overflow

If you're using https://remix.ethereum.org you can see the "Environment" in the top right hand corner of the IDE.

According to the docs:

There are 3 type of environments Remix can be plugged to: Javascript VM, Injected provider, or Web3 provider. (for details see Running transactions)

These three environments are:

The JavascriptVM is running a sandboxed blockchain in your browser where execution runs in your browser. This means you don’t need any other software or Ethereum node to run it. This makes it very simple to deploy contract and interact with contracts limits your ability to manage account

The Web3 provider will make remix connect to a remote node. You will need to provide the URL address to the selected provider: geth, parity or any Ethereum client. You can use a tool like ganache-cli which simulates a blockchain locally on your computer as well.

The Injected Provider will make remix connect to an injected web3 provider. Metamask is an example of providers that inject web3, thus can be used with this option.

See docs for more information about environments.

I'm going to guess you're using the JavaScriptVM environment which means, unfortunately, you won't have access to web3 command tools (which need Web3 Provider or Injection). Without web3 you can't move funds between accounts by constructing transactions.

What you can do is download ganache-cli or your favourite web3 provider, and manipulate accounts from the terminal using web3 commands.

For example:

   $ ganache-cli

Available Accounts <ADDRESSES YOU CAN MOVE FUNDS BETWEEN>
==================
(0) 0x9f0bf61721a61e7f72abac48eed65e318668e71f (~100 ETH)
(1) 0x74bc67c48eefc359d296023acd4ac9158575ab56 (~100 ETH)
(2) 0xec548e4b5246795b81904bc67cedfe26b528b173 (~100 ETH)
(3) 0x06fe6ca72d985252729a2ba2a40147d4905a56c4 (~100 ETH)
(4) 0x262498200090fdaa7db8d430e681e39d6257d3ce (~100 ETH)
(5) 0x9736aa7dc69bee01166352c3e51023ee5ab57a08 (~100 ETH)
(6) 0x19ee475e3c64935546d9c4a67d01232c53d45c2b (~100 ETH)
(7) 0xee4dec500f7b08dfe20646a8a6661a81204eb1cb (~100 ETH)
(8) 0xf5b6a5ce718ad527eb877a0c8554e1d2382c9beb (~100 ETH)
(9) 0x590e03591cc82e9308d1e8e8869c248e13356920 (~100 ETH)

<Secret private keys not shown >

HD Wallet
==================
<Mnemonics not shown >

Base HD Path:  m/44'/60'/0'/0/{account_index}

Gas Price
==================
20000000000

Gas Limit
==================
6721975

Listening on 127.0.0.1:8545


问:
Kotlin data class copy method not deep copying all members
Could someone explain how exactly the copy method for Kotlin data classes work? It seems like for some members, a (deep) copy is not actually created and the references are still to the original.

```<code>fun test() {
    val bar = Bar(0)
    val foo = Foo(5, bar, mutableListOf(1, 2, 3))
    println("foo    : $foo")

    val barCopy = bar.copy()
    val fooCopy = foo.copy()
    foo.a = 10
    bar.x = 2
    foo.list.add(4)

    println("foo    : $foo")
    println("fooCopy: $fooCopy")
    println("barCopy: $barCopy")
}

data class Foo(var a: Int,
               val bar: Bar,
               val list: MutableList<Int> = mutableListOf())

data class Bar(var x: Int = 0)
</code>```

Output:

  foo    : Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

  foo    : Foo(a=10, bar=Bar(x=2), list=[1, 2, 3, 4])

  fooCopy: Foo(a=5, bar=Bar(x=2), list=[1, 2, 3, 4])

  barCopy: Bar(x=0)

Why is barCopy.x=0 (expected), but fooCopy.bar.x=2 (I would think it would be 0). Since Bar is also a data class, I would expect foo.bar to also be a copy when foo.copy() is executed.

To deep copy all members, I can do something like this:

```<code>val fooCopy = foo.copy(bar = foo.bar.copy(), list = foo.list.toMutableList())
</code>```

fooCopy: Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

But am I missing something or is there a better way to do this without needing to specify that these members need to force a deep copy?

答:
Building on a previous answer, an easy if somewhat inelegant solution is to use the kotlinx.serialization facility. Add the plugin to build.gradle as per the docs, then to make a deep copy of an object, annotate it with @Serializable and add a copy method which converts the object to a serialised binary form, then back again. The new object will not reference any objects in the original.

```<code>import kotlinx.serialization.Serializable
import kotlinx.serialization.cbor.Cbor

@Serializable
data class DataClass(val yourData: Whatever, val yourList: List<Stuff>) {

    var moreStuff: Map<String, String> = mapOf()

    fun copy(): DataClass {
        return Cbor.load(serializer(), Cbor.dump(serializer(), this))
    }
</code>```

This won't be as fast as a handwritten copy function, but it does not require updating if the object is changed, so is more robust.

Body:
Could someone explain how exactly the copy method for Kotlin data classes work? It seems like for some members, a (deep) copy is not actually created and the references are still to the original.

fun test() {
    val bar = Bar(0)
    val foo = Foo(5, bar, mutableListOf(1, 2, 3))
    println("foo    : $foo")

    val barCopy = bar.copy()
    val fooCopy = foo.copy()
    foo.a = 10
    bar.x = 2
    foo.list.add(4)

    println("foo    : $foo")
    println("fooCopy: $fooCopy")
    println("barCopy: $barCopy")
}

data class Foo(var a: Int,
               val bar: Bar,
               val list: MutableList<Int> = mutableListOf())

data class Bar(var x: Int = 0)

Output:

  foo    : Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

  foo    : Foo(a=10, bar=Bar(x=2), list=[1, 2, 3, 4])

  fooCopy: Foo(a=5, bar=Bar(x=2), list=[1, 2, 3, 4])

  barCopy: Bar(x=0)

Why is barCopy.x=0 (expected), but fooCopy.bar.x=2 (I would think it would be 0). Since Bar is also a data class, I would expect foo.bar to also be a copy when foo.copy() is executed.

To deep copy all members, I can do something like this:

val fooCopy = foo.copy(bar = foo.bar.copy(), list = foo.list.toMutableList())

fooCopy: Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

But am I missing something or is there a better way to do this without needing to specify that these members need to force a deep copy?

Body:
Building on a previous answer, an easy if somewhat inelegant solution is to use the kotlinx.serialization facility. Add the plugin to build.gradle as per the docs, then to make a deep copy of an object, annotate it with @Serializable and add a copy method which converts the object to a serialised binary form, then back again. The new object will not reference any objects in the original.

import kotlinx.serialization.Serializable
import kotlinx.serialization.cbor.Cbor

@Serializable
data class DataClass(val yourData: Whatever, val yourList: List<Stuff>) {

    var moreStuff: Map<String, String> = mapOf()

    fun copy(): DataClass {
        return Cbor.load(serializer(), Cbor.dump(serializer(), this))
    }

This won't be as fast as a handwritten copy function, but it does not require updating if the object is changed, so is more robust.


问:
Fetching links from multiple
 with same class
I want to get all links from the UL with the class list-chapter but I only get half the link I want because the links are separated in two
 that are inside a div like so

links1

links2

. I'm new to python and I am really stuck.

Also if possible I would like to add "http://www.example.com" before everylink and save them one by one in a list so I can access them with list[1].

Thanks, here is the code

```<code># import libraries
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
"""Getting Started Example for Python 2.7+/3.3+"""

chapter = 1
chapterlist = 1
links = []
name = ""
reallink = ""
while chapter < 31:
    quote_page = Request('http://website.com/page.html?page=' + str(chapter) + '&per-page=50', headers={'User-Agent': 'Mosezilla/5.0'})
    page = urlopen(quote_page).read()
    soup = BeautifulSoup(page, "html.parser")
    name_box = soup.find("ul", attrs={"class": "list-chapter"})
    links += name_box.find_all("a")
    reallink += str([a['href'] for a in links])
    chapter += 1
f = open("links.txt", "w+")
i = 1
f.write(reallink)
f.close()
</code>```

答:
You are using find which will return first match as opposed to find_all which would return a list of matches.

Assuming your ul class is correct I would use select instead and collect child a tags of those:

Replace these lines:

```<code>name_box = soup.find("ul", attrs={"class": "list-chapter"})
links += name_box.find_all("a")
reallink += str([a['href'] for a in links])
</code>```

With

```<code>realinks = ['http://www.example.com' + item['href'] for item in soup.select('ul.list-chapter a')] #I'm assuming href already has leading /
</code>```

Title: Fetching links from multiple <ul> with same class

Body:
I want to get all links from the UL with the class list-chapter but I only get half the link I want because the links are separated in two
 that are inside a div like so

links1

links2

. I'm new to python and I am really stuck.

Also if possible I would like to add "http://www.example.com" before everylink and save them one by one in a list so I can access them with list[1].

Thanks, here is the code

# import libraries
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
"""Getting Started Example for Python 2.7+/3.3+"""

chapter = 1
chapterlist = 1
links = []
name = ""
reallink = ""
while chapter < 31:
    quote_page = Request('http://website.com/page.html?page=' + str(chapter) + '&per-page=50', headers={'User-Agent': 'Mosezilla/5.0'})
    page = urlopen(quote_page).read()
    soup = BeautifulSoup(page, "html.parser")
    name_box = soup.find("ul", attrs={"class": "list-chapter"})
    links += name_box.find_all("a")
    reallink += str([a['href'] for a in links])
    chapter += 1
f = open("links.txt", "w+")
i = 1
f.write(reallink)
f.close()

Body:
You are using find which will return first match as opposed to find_all which would return a list of matches.

Assuming your ul class is correct I would use select instead and collect child a tags of those:

Replace these lines:

name_box = soup.find("ul", attrs={"class": "list-chapter"})
links += name_box.find_all("a")
reallink += str([a['href'] for a in links])

With

realinks = ['http://www.example.com' + item['href'] for item in soup.select('ul.list-chapter a')] #I'm assuming href already has leading /


问:
Is there an elegant way of preventing numpy from slapping a dtype on empty lists?
Consider the following example which may look silly but really is a stripped down version of a real world annoyance:

```<code>import numpy as np
a = np.zeros(5, int)
b = [*range(5)]
for i in reversed(range(5)):
    a[:i] += b[:i]

# Traceback (most recent call last):
#  File "<stdin>", line 2, in <module>
# TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
</code>```

This exception is raised at the last iteration because numpy can no longer infer the correct dtype of the rhs list.

It is, of course, easy to explicitly check for empty operands

```<code>for i in reversed(range(5)):
    if b[:i]:
        a[:i] += b[:i]
</code>```

but I was wondering whether there is a more elegant solution.

答:
Just wanted to share what I went for in the end. At least it is short:</p>

```<code>for i in reversed(range(5)):
    a[:i] += b[:i] or 0

a
# array([0, 3, 4, 3, 0])
</code>```

Body:
Consider the following example which may look silly but really is a stripped down version of a real world annoyance:

import numpy as np
a = np.zeros(5, int)
b = [*range(5)]
for i in reversed(range(5)):
    a[:i] += b[:i]

# Traceback (most recent call last):
#  File "<stdin>", line 2, in <module>
# TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

This exception is raised at the last iteration because numpy can no longer infer the correct dtype of the rhs list.

It is, of course, easy to explicitly check for empty operands

for i in reversed(range(5)):
    if b[:i]:
        a[:i] += b[:i]

but I was wondering whether there is a more elegant solution.

Body:
Just wanted to share what I went for in the end. At least it is short:

for i in reversed(range(5)):
    a[:i] += b[:i] or 0

a
# array([0, 3, 4, 3, 0])


答:
You will need to bind a PreviewKeyDown handler to the Datagrid and then manually check whether the key value is  Key.Enter.

If yes, set e.Handled = true.

Title: Override the enter key, but keep default behavior for other keys in a wpf datagrid

Body:
It really bothers me that the pressing the enter key in a Datagrid moves the selection down one item, I'd like to be able to decide what it does in a normal keydown event.

So what I did was create a new class that inherits DataGrid and override the OnKeyDown event and use that as my datagrid.

This creates a whole new set of problems, since I apparently have to rewrite all the other keypresses (arrow key navigation, shift+arrow key selection, pgup/pgdn, etc..). I've been trying to hack it, but it just seems so pointless spending time rewriting something that has already been written and probably better then whatever I'll come up with.

So how can I make the enter key do what I want without messing with the other default keybindings of the datagrid?

Thanks in advance


问:
access 2003 on windows 10 - RaiseEvent seems not to work
A very simple mdb: form1 has just a button Command0, form2 has just a button Command0.

The button on form1 loads form2.

The button on form2 raises event "doit".

This event never gets triggered.

Why?
This is all the code there is in the form:

FORM1

```<code>Option Compare Database
Private WithEvents msg As Form
Private Sub Command0_Click()
    DoCmd.OpenForm "form2"
    Set msg = Forms("form2")
End Sub
Sub msg_doit()
    Stop
End Sub
</code>```

FORM2

```<code>Option Compare Database
Public Event doit()

Private Sub Command0_Click()
    RaiseEvent doit
End Sub
</code>```

答:
You need to use the proper (specific) interface that contains your event.

For forms, the Access.Form interface is the general one (for all forms) and only contains the built-in methods and events, the Access.Form_MyFormName is the specific interface that contains all public methods and events you declared as well.

The only thing you need to change is:

```<code>Private WithEvents msg As Form_form2
</code>```

Then it should just work.

OwnerDisplayName: bobbibo

Body:
A very simple mdb: form1 has just a button Command0, form2 has just a button Command0.

The button on form1 loads form2.

The button on form2 raises event "doit".

This event never gets triggered.

Why?
This is all the code there is in the form:

FORM1

Option Compare Database
Private WithEvents msg As Form
Private Sub Command0_Click()
    DoCmd.OpenForm "form2"
    Set msg = Forms("form2")
End Sub
Sub msg_doit()
    Stop
End Sub

FORM2

Option Compare Database
Public Event doit()

Private Sub Command0_Click()
    RaiseEvent doit
End Sub

Body:
You need to use the proper (specific) interface that contains your event.

For forms, the Access.Form interface is the general one (for all forms) and only contains the built-in methods and events, the Access.Form_MyFormName is the specific interface that contains all public methods and events you declared as well.

The only thing you need to change is:

Private WithEvents msg As Form_form2

Then it should just work.