问:
Git: "Corrupt loose object"
Whenever I pull from my remote, I get the following error about compression. When I run the manual compression, I get the same:

```<code>$ git gc
error: Could not read 3813783126d41a3200b35b6681357c213352ab31
fatal: bad tree object 3813783126d41a3200b35b6681357c213352ab31
error: failed to run repack
</code>```

Does anyone know, what to do about that?

From cat-file I get this:

```<code>$ git cat-file -t 3813783126d41a3200b35b6681357c213352ab31
error: unable to find 3813783126d41a3200b35b6681357c213352ab31
fatal: git cat-file 3813783126d41a3200b35b6681357c213352ab31: bad file
</code>```

And from git fsck I get this ( don't know if it's actually related):

```<code>$ git fsck
error: inflate: data stream error (invalid distance too far back)
error: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a'
fatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted
</code>```

Can anyone help me decipher this?

答:
I had a similar issue on a Windows 10 computer with onedrive backing up my documents folder where I have my git repositories.

Looking at the object in the git object directory I did not see a green checkmark but the blue sync icon for that file. All other object files appeared to have the green checkmark.  Playing around, trying things, I tried selecting the option always keep this folder on this device but got an error: error 0x80071129 the tag present in the reparse point buffer is invalid.

This link (https://answers.microsoft.com/en-us/msoffice/forum/all/error-0x80071129-the-tag-present-in-the-reparse/b8011cee-98c5-4c33-ba99-d0eec7c535a0) suggests to run chkdsk /r /f as an admin to fix the issue (have to reboot computer).  I did that and it fixed my issue.

Title: Git: "Corrupt loose object"

Body:
Whenever I pull from my remote, I get the following error about compression. When I run the manual compression, I get the same:

$ git gc
error: Could not read 3813783126d41a3200b35b6681357c213352ab31
fatal: bad tree object 3813783126d41a3200b35b6681357c213352ab31
error: failed to run repack

Does anyone know, what to do about that?

From cat-file I get this:

$ git cat-file -t 3813783126d41a3200b35b6681357c213352ab31
error: unable to find 3813783126d41a3200b35b6681357c213352ab31
fatal: git cat-file 3813783126d41a3200b35b6681357c213352ab31: bad file

And from git fsck I get this ( don't know if it's actually related):

$ git fsck
error: inflate: data stream error (invalid distance too far back)
error: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a'
fatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted

Can anyone help me decipher this?


来源: stackexchange

问:
What is the proper syntax for a single quoted param within a pair of double quotes (bash)
I have a bash script that is custom tool for running docker containers. I can't show entire script. In the following scenario:

```<code>    local dockerArgs=(
            "--restart=on-failure:5"
            "--memory 512m"
            "--cpu-shares 1024"
            "--pids-limit 100"
            "--health-cmd='stat /etc/passwd'"
            "--security-opt=no-new-privileges"
            "-v /containers/logs/:/containers/logs/"
            "-v /etc/conf/prometheus/:/etc/conf/prometheus/"
    )
</code>```

, all the params are processed correctly except the health-cmd param. It the only one with the single-quoted value. The script fails due to the above syntax for health-cmd. Grateful for any ideas to fix. Thanks

答:
--health-cmd='stat /etc/passwd' and "--health-cmd=stat /etc/passwd" are equivalent words, each of which is equivalent to the pair of words --health-cmd and stat /etc/passwd to your program. You can write either

```<code>local dockerArgs=(
   ...
   --health-cmd 'stat /etc/passwd'
   ...
)
</code>```

or

```<code>local dockerArgs=(
   ...
   "--health-cmd=stat /etc/passwd"  # or --health-cmd='stat /etc/passwd'
   ...
)
</code>```

and

```<code>docker ... "${dockerArgs[@]}"
</code>```

will work the same same either way.

ContentLicense: CC BY-SA 4.0

Body:
I have a bash script that is custom tool for running docker containers. I can't show entire script. In the following scenario:

    local dockerArgs=(
            "--restart=on-failure:5"
            "--memory 512m"
            "--cpu-shares 1024"
            "--pids-limit 100"
            "--health-cmd='stat /etc/passwd'"
            "--security-opt=no-new-privileges"
            "-v /containers/logs/:/containers/logs/"
            "-v /etc/conf/prometheus/:/etc/conf/prometheus/"
    )

, all the params are processed correctly except the health-cmd param. It the only one with the single-quoted value. The script fails due to the above syntax for health-cmd. Grateful for any ideas to fix. Thanks

Body:
--health-cmd='stat /etc/passwd' and "--health-cmd=stat /etc/passwd" are equivalent words, each of which is equivalent to the pair of words --health-cmd and stat /etc/passwd to your program. You can write either

local dockerArgs=(
   ...
   --health-cmd 'stat /etc/passwd'
   ...
)

or

local dockerArgs=(
   ...
   "--health-cmd=stat /etc/passwd"  # or --health-cmd='stat /etc/passwd'
   ...
)

and

docker ... "${dockerArgs[@]}"

will work the same same either way.


问:
How do I make background Image on each division row from URL
I need to display different background URL on each row base on the item in MySQL. I use php mySQL fetch array to get the item name and background URL. So far,  I was able to get the URL background and display in row by using CSS,  but every time I choose different item all division row get's overwritten by this new background. This result to have duplicate background.
I have attached of sample image where the background image of division row got overwritten and duplicate image.

[Duplicate Row Background][1]  [1]: https://i.stack.imgur.com/qxLOI.png

Snippet of Php fetch array to echo the division and the CSS id of Background Image.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code>while ($row = mysqli_fetch_array($query))
                    {
                        $pro_id = $row['pro_id'];

                                $sql1 = "SELECT * FROM products WHERE product_id = '$pro_id' ";
                                $query1 = mysqli_query($conn , $sql1);
                                while ($row1 = mysqli_fetch_array($query1))
                                {

                                    $id = $row1['product_id'];
                                    $name = $row1['product_title'];
                                    $element = $row1['product_price'];
                                    $faction = $row1['product_description'];
                                    $picture = $row1['product_image'];
                                    $class = $row1['product_keywords'];
                                    $rarity = $row1['sales'];
                                    $bgurl = $row1['bgurl'];

                                echo
                                '

                                   <div class="container" id ="background-container">

                                    <div class="row pt-2 pb-1" style="border-top: .5px  solid grey; border-bottom: .5px  solid grey;" >
                                    <div class="col-4" >
                                        <p class="squad1-title" >'.$bgurl.'</p>
                                    </div>
                                    <div class="col-7">

                                    </div>

                                    <div class="remove" >
                                        <i class="fa fa-minus-square removeitem" style="padding center" data-proid="'.$id.'" title="Remove"> </i>
                                    </div>
                                    </div>
                                   </div>
                                ';
                                }
                    }</code>```

答:
In CSS
#background-container ---> Single tag in HTML

.background-container ---> Multiple tag in HTML

The problem is you overwrite the last one

Change

#background-container {
  display:table;
  width:100%;
  border-collapse:collapse;
  background: url(<?php echo  $bgurl; ?>) center;
   -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

```
<p>By</p>
<pre class="lang-html prettyprint-override"><code>.background-container {
  display:table;
  width:100%;
  border-collapse:collapse;

   -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

<div class="container" class="background-container" style="background: url(<?php echo  $bgurl; ?>) center;">
</code>```

Or something similar.

Body:
I need to display different background URL on each row base on the item in MySQL. I use php mySQL fetch array to get the item name and background URL. So far,  I was able to get the URL background and display in row by using CSS,  but every time I choose different item all division row get's overwritten by this new background. This result to have duplicate background.
I have attached of sample image where the background image of division row got overwritten and duplicate image.

[Duplicate Row Background][1]  [1]: https://i.stack.imgur.com/qxLOI.png

Snippet of Php fetch array to echo the division and the CSS id of Background Image.

while ($row = mysqli_fetch_array($query))
                    {
                        $pro_id = $row['pro_id'];

                                $sql1 = "SELECT * FROM products WHERE product_id = '$pro_id' ";
                                $query1 = mysqli_query($conn , $sql1);
                                while ($row1 = mysqli_fetch_array($query1))
                                {

                                    $id = $row1['product_id'];
                                    $name = $row1['product_title'];
                                    $element = $row1['product_price'];
                                    $faction = $row1['product_description'];
                                    $picture = $row1['product_image'];
                                    $class = $row1['product_keywords'];
                                    $rarity = $row1['sales'];
                                    $bgurl = $row1['bgurl'];

                                echo
                                '

'.$bgurl.'

                                ';
                                }
                    }

Body:
In CSS
#background-container ---> Single tag in HTML

.background-container ---> Multiple tag in HTML

The problem is you overwrite the last one

Change

#background-container {
  display:table;
  width:100%;
  border-collapse:collapse;
  background: url(<?php echo  $bgurl; ?>) center;
   -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

<div class="container" id ="background-container">

By

.background-container {
  display:table;
  width:100%;
  border-collapse:collapse;

   -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

<div class="container" class="background-container" style="background: url(<?php echo  $bgurl; ?>) center;">

Or something similar.


问:
How to disable talkback action on a clickable composable item
I have a composable function that displays some text. The talkback is working great as it reads the text. but how can I disable the clickable notification in accessibility for that composable so that I can have a secret click listener to send analytics.

any time I try to add a clickable like this

```<code>Column(
        modifier = Modifier.fillMaxWidth().clickable {

        },
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    )
</code>```

When this column is on focus it says 'Double click to activate', and I want to avoid that as there is no user-facing feature on that click.

答:
As described in the accessibility doc you can use the semantics properties.
Use the invisibleToUser property to mark an element to be invisible to the user.

```<code>Column(
    modifier = Modifier.semantics {
        this.invisibleToUser()}
){}
</code>```

Body:
I have a composable function that displays some text. The talkback is working great as it reads the text. but how can I disable the clickable notification in accessibility for that composable so that I can have a secret click listener to send analytics.

any time I try to add a clickable like this

Column(
        modifier = Modifier.fillMaxWidth().clickable {

        },
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    )

When this column is on focus it says 'Double click to activate', and I want to avoid that as there is no user-facing feature on that click.

Body:
As described in the accessibility doc you can use the semantics properties.
Use the invisibleToUser property to mark an element to be invisible to the user.

Column(
    modifier = Modifier.semantics {
        this.invisibleToUser()}
){}


问:
NUXT JS SassError: Undefined variable "$black"
I declare an SCSS variable $black in my file general.scss and in default.vue I want to use it but I have this error SassError: Undefined variable "$black".

I'm using Nuxt.js!

screenshot variable declaration

screenshot variable utilisation

screenshot organisation folder

If you have any response or help for me, thank you and sorry for my bad english :) !

[EDIT]

I don't know why but my account is blocked, so the solution of my problemes is in this tutorial

Thanks all for your times (love)

答:
I used the Sass @use rule, because support for the @import rule will be dropped according to this timeline.

Example:

```

By default, the namespace is just the last component of the module’s URL.

Body:
I used the Sass @use rule, because support for the @import rule will be dropped according to this timeline.

Example:

<style lang="scss">
    @use '@/assets/style/general.scss';

    h2 {
        color: general.$black;
    }
</style>

By default, the namespace is just the last component of the module’s URL.


问:
How do I format a string based on certain delimeters in reactjs?
Let a = "cat AND mouse AND hen OR pig AND cow OR horse"

Expected output ="((cat AND mouse AND hen) OR (pig AND cow) OR horse)"

All the consecutive AND should be inside a bracket.

答:
var a = "cat AND mouse AND hen OR pig AND cow OR horse"
var orSplits =
a = "("+a.replace(/ OR /g, ") OR (")+")";
console.log(a)```


问:
Visual Studio 2022: Cannot open include file: 'ctype.h'
I've got the infamous error message in C++ build: "Cannot open include file: 'ctype.h'". I know a similar question was already asked multiple times, but my case seems different because I am using the latest Visual Studio 2022 and seems to behave differently.

I have a bunch of existing C++ projects, they use plain 32-bit Windows API with DirectX 6, and I used VC++ build tools 2015 and Windows SDK 8.1 to compile it without any issues in previous versions of Visual Studio. Everything was fine in Visual Studio 2019, no special setup was needed, until I uninstalled it and installed Visual Studio 2022.

Now I can open my solutions, it nicely shows they are using C++ build tools 2015, which I installed together with VS2022, and the solutions also shows correctly that they use Windows 8.1 SDK. But Windows 8.1 SDK is not present in VS2022 installation, I installed it separately. I also tried to "repair" VS2022 installation, but that only deleted all my UI preferences, but not fixed anything in build. Also, I tried to reinstall Windows 8.1 SDK, but it said it is already OK.

When looking to Visual Studio, I can't see any place where I can set default include and lib directories, I can only list what is being used right now. VS2022 shows this list:

```<code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include
C:\Program Files\Windows Kits\10\Include\10.0.10240.0\ucrt
C:\Program Files (x86)\Windows Kits\8.1\Include\um
C:\Program Files (x86)\Windows Kits\8.1\Include\shared
C:\Program Files (x86)\Windows Kits\8.1\Include\winrt
</code>```

The actual error message I receive is this:

```<code>c:\program files (x86)\windows kits\8.1\include\um\winnt.h(31): fatal error C1083: Cannot open include file: 'ctype.h': No such file or directory
</code>```

So it says that winnt.h from windows kits 8.1 cannot find ctype.h. And yes, there is no ctype.h in that folder or anywhere around, I can see it only in C:\Program Files\Microsoft Visual Studio\2022\Professional\SDK\ScopeCppSDK\vc15\SDK\include\ucrt
which I think is the folder with VC++ 2015 build tools. So this seems correct, but I am wondering why this folder is not a part of default include directories when VC++ 2015 build tools are set in project settings. Because it seems that VS2022 is correctly picking my Windows 8.1 SDK, but not picking correctly the older C++ compiler.

When I try to add the folder where ctype.h resides to include folders, I receive another type of errors saying that other files are incompatible with these include files. Of course, this system of directories needs to be in sync. So please what is the correct way of using this?

Also, I tried to switch the VC++ build tools to 2022 version. Unfortunately, that also does not fix the issue. And Windows 10 SDK is not installed, the software wants to stay compatible with older Windows, so I don't need it.

答:
I found a bug report which is related: https://developercommunity.visualstudio.com/t/windows-81-sdk-1/151682

Although Microsoft staff declined to accept it as a bug, it is happening for me as well. When I install only Windows 8.1 SDK, no project can be compiled with it. I even tried to create a new Windows API project in VS2022, the project was created, but failed to compile with the same error.

So I tried to install Windows 10 SDK (from VS2022 installed, but that is probably not important) and this added some missing files which now help to compile Windows 8.1 SDK projects. Problem seems to be solved, my old C++ code can now be compiled with Windows 8.1 SDK and both C++ build tools 2015 and 2022.

Body:
I've got the infamous error message in C++ build: "Cannot open include file: 'ctype.h'". I know a similar question was already asked multiple times, but my case seems different because I am using the latest Visual Studio 2022 and seems to behave differently.

I have a bunch of existing C++ projects, they use plain 32-bit Windows API with DirectX 6, and I used VC++ build tools 2015 and Windows SDK 8.1 to compile it without any issues in previous versions of Visual Studio. Everything was fine in Visual Studio 2019, no special setup was needed, until I uninstalled it and installed Visual Studio 2022.

Now I can open my solutions, it nicely shows they are using C++ build tools 2015, which I installed together with VS2022, and the solutions also shows correctly that they use Windows 8.1 SDK. But Windows 8.1 SDK is not present in VS2022 installation, I installed it separately. I also tried to "repair" VS2022 installation, but that only deleted all my UI preferences, but not fixed anything in build. Also, I tried to reinstall Windows 8.1 SDK, but it said it is already OK.

When looking to Visual Studio, I can't see any place where I can set default include and lib directories, I can only list what is being used right now. VS2022 shows this list:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include
C:\Program Files\Windows Kits\10\Include\10.0.10240.0\ucrt
C:\Program Files (x86)\Windows Kits\8.1\Include\um
C:\Program Files (x86)\Windows Kits\8.1\Include\shared
C:\Program Files (x86)\Windows Kits\8.1\Include\winrt

The actual error message I receive is this:

c:\program files (x86)\windows kits\8.1\include\um\winnt.h(31): fatal error C1083: Cannot open include file: 'ctype.h': No such file or directory

So it says that winnt.h from windows kits 8.1 cannot find ctype.h. And yes, there is no ctype.h in that folder or anywhere around, I can see it only in C:\Program Files\Microsoft Visual Studio\2022\Professional\SDK\ScopeCppSDK\vc15\SDK\include\ucrt
which I think is the folder with VC++ 2015 build tools. So this seems correct, but I am wondering why this folder is not a part of default include directories when VC++ 2015 build tools are set in project settings. Because it seems that VS2022 is correctly picking my Windows 8.1 SDK, but not picking correctly the older C++ compiler.

When I try to add the folder where ctype.h resides to include folders, I receive another type of errors saying that other files are incompatible with these include files. Of course, this system of directories needs to be in sync. So please what is the correct way of using this?

Also, I tried to switch the VC++ build tools to 2022 version. Unfortunately, that also does not fix the issue. And Windows 10 SDK is not installed, the software wants to stay compatible with older Windows, so I don't need it.


问:
In the PyTorch Distributed Data Parallel (DDP) tutorial, how does `setup` know it's rank?
For the tutorial Getting Started with Distributed Data Parallel

How does setup() function knows the rank when mp.spawn() doesn't pass the rank?

def setup(rank, world_size):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'

    # initialize the process group
    dist.init_process_group("gloo", rank=rank, world_size=world_size)

```
<pre class="lang-py prettyprint-override"><code>def demo_basic(rank, world_size):
    print(f"Running basic DDP example on rank {rank}.")
    setup(rank, world_size)
    .......

</code>```

def run_demo(demo_fn, world_size):
    mp.spawn(demo_fn,
             args=(world_size,),
             nprocs=world_size,
             join=True)
```
<pre class="lang-py prettyprint-override"><code>if __name__ == "__main__":
    n_gpus = torch.cuda.device_count()
    assert n_gpus >= 2, f"Requires at least 2 GPUs to run, but got {n_gpus}"
    world_size = n_gpus
    run_demo(demo_basic, world_size)
</code>```

答:
mp.spawn does pass the rank to the function it calls.

From the torch.multiprocessing.spawn docs

torch.multiprocessing.spawn(fn, args=(), nprocs=1, join=True, daemon=False, start_method='spawn')

...

fn (function) -

Function is called as the entrypoint of the spawned process. This
function must be defined at the top level of a module so it can be
pickled and spawned. This is a requirement imposed by multiprocessing. The function is called as fn(i, *args), where i is the process index
and args is the passed through tuple of arguments.

So when spawn invokes fn it passes it the process index as the first argument.

Body:
For the tutorial Getting Started with Distributed Data Parallel

How does setup() function knows the rank when mp.spawn() doesn't pass the rank?

def setup(rank, world_size):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'

    # initialize the process group
    dist.init_process_group("gloo", rank=rank, world_size=world_size)

def demo_basic(rank, world_size):
    print(f"Running basic DDP example on rank {rank}.")
    setup(rank, world_size)
    .......

def run_demo(demo_fn, world_size):
    mp.spawn(demo_fn,
             args=(world_size,),
             nprocs=world_size,
             join=True)

if __name__ == "__main__":
    n_gpus = torch.cuda.device_count()
    assert n_gpus >= 2, f"Requires at least 2 GPUs to run, but got {n_gpus}"
    world_size = n_gpus
    run_demo(demo_basic, world_size)


问:
(Phaser 3 Arcade) Issue with collisions between 2 circular bodies
I instantiate a bunch of extended Phaser.Physics.Arcade.Sprite that move around the screen. When they hit each others, everything works has expected with the basic arcade body.

Although, It doesn't if I add "this.body.setCircle(200);" (or "this.setCircle(200);" btw, I'm not sure about the difference) in their constructor.
Instead of smoothly deflecting on impact as I would have hoped, they stop immediately.

Here's the code of my class:

```<code>import Phaser from "phaser";

export default class Sheep extends Phaser.Physics.Arcade.Sprite {
  target: Phaser.Math.Vector2 = new Phaser.Math.Vector2();
  speed: number = 50;
  reach: boolean = true;

  constructor(scene: Phaser.Scene, x: number, y: number, spriteKey: string) {
    super(scene, x, y, spriteKey);
    this.setOrigin(0, 0);
    scene.physics.add.existing(this);
    scene.add.existing(this);
    this.setCircle(5);
    this.visible = false;
    //this.scale = 0.05;
    //this.setBounce(1);
  }
  setRandomTarget() {
    this.target = new Phaser.Math.Vector2(
      Math.random() * this.scene.scale.width,
      Math.random() * this.scene.scale.height
    );
  }
  preUpdate(time: number, delta: number) {
    super.preUpdate(delta, time);
    if (
      this.reach ||
      this.target.distance(new Phaser.Math.Vector2(this.x, this.y)) <=
        this.speed
    ) {
      this.setRandomTarget();
      this.reach = false;
      this.setHeading();
    }
  }
  setHeading() {
    let vPos = new Phaser.Math.Vector2(this.x, this.y);
    let vTarget = this.target.clone();
    let velocity = vTarget.subtract(vPos).normalize().scale(this.speed);
    this.setVelocity(velocity.x, velocity.y);
  }
}
</code>```

Here's the code to create them and add them to the scene:

```<code>for (let i = 0; i < 10; i++) {
      this.sheeps.push(
        new Sheep(
          this,
          Math.round(Math.random() * width),
          Math.round(Math.random() * height),
          "sheep2"
        )
      );
    }
    let sheepGroup = this.physics.add.group(this.sheeps);

    this.physics.add.collider(sheepGroup, sheepGroup);
</code>```

Here's the result:
Circular collision
Rectangular collision

答:
Part one of your question

If you extend from Phaser.Physics.Arcade.Sprite in the constructor you can do both, this.setCircle (link documentation) or this.body.setCircle (link documentation) should do the same thing.

Part two of your question (look below for Update, solution)

Why it doesn't work, is difficult to say, without seeing your code, but here is how I would diagnose the problem:

turn on the debug setting for physics (I assume the collision box is somehow offset)

```<code>var config = {
        ...
        physics: {
           default: 'arcade',
           arcade: {
              ...
              debug: true
           }
        },
  };
</code>```

check the browser console for errors (immediate motion stop, indicates a probal error)

Update/Solution:

After going over your code, I would have to say the problem is the line

let sheepGroup = this.physics.add.group(this.sheeps);

just change it to

let sheepGroup = this.add.group(this.sheeps);

and it should work. The physics of the phaser group is interfering with the physics bodies of the sheeps.

Here the demo, I used for testing:

class Sheep extends Phaser.Physics.Arcade.Sprite {

  constructor(scene, x, y, spriteKey) {
    super(scene, x, y, spriteKey);
    this.target = new Phaser.Math.Vector2();
    this.speed = 50;
    this.reach = true;
    this.setOrigin(0, 0);
    scene.add.existing(this);
    scene.physics.add.existing(this);

    this.setCircle(5);
    this.visible = false;
    //this.scale = 0.05;
    this.setBounce(1);

  }
  setRandomTarget() {
    this.target = new Phaser.Math.Vector2(
      Math.random() * this.scene.scale.width,
      Math.random() * this.scene.scale.height
    );
  }
  preUpdate(time, delta) {
    super.preUpdate(delta, time);
    if (
      this.reach ||
      this.target.distance(new Phaser.Math.Vector2(this.x, this.y)) <=
        this.speed
    ) {
      this.setRandomTarget();
      this.reach = false;
      this.setHeading();
    }
  }

  setHeading() {
    let vPos = new Phaser.Math.Vector2(this.x, this.y);
    let vTarget = this.target.clone();
    let velocity = vTarget
        .subtract(vPos)
        .normalize()
        .scale(this.speed);

    this.setVelocity(velocity.x, velocity.y);
  }
}

var config = {
    type: Phaser.AUTO,
    width: 400,
    height: 200,
    physics: {
        default: 'arcade',
        arcade: {
            debug: true
        }
    },
    scene: { create }
};

var controls;

var game = new Phaser.Game(config);

function create ()
{
    this.sheeps = [];
  for (let i = 0; i < 20
  ; i++) {
      this.sheeps.push(
        new Sheep(
          this,
          Math.round(Math.random() * 400),
          Math.round(Math.random() * 200),
          "sheep2"
        )
      );
    }
    let sheepGroup = this.add.group(this.sheeps);

    this.physics.add.collider(sheepGroup, sheepGroup);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script></code>```

Body:
I instantiate a bunch of extended Phaser.Physics.Arcade.Sprite that move around the screen. When they hit each others, everything works has expected with the basic arcade body.

Although, It doesn't if I add "this.body.setCircle(200);" (or "this.setCircle(200);" btw, I'm not sure about the difference) in their constructor.
Instead of smoothly deflecting on impact as I would have hoped, they stop immediately.

Here's the code of my class:

import Phaser from "phaser";

export default class Sheep extends Phaser.Physics.Arcade.Sprite {
  target: Phaser.Math.Vector2 = new Phaser.Math.Vector2();
  speed: number = 50;
  reach: boolean = true;

  constructor(scene: Phaser.Scene, x: number, y: number, spriteKey: string) {
    super(scene, x, y, spriteKey);
    this.setOrigin(0, 0);
    scene.physics.add.existing(this);
    scene.add.existing(this);
    this.setCircle(5);
    this.visible = false;
    //this.scale = 0.05;
    //this.setBounce(1);
  }
  setRandomTarget() {
    this.target = new Phaser.Math.Vector2(
      Math.random() * this.scene.scale.width,
      Math.random() * this.scene.scale.height
    );
  }
  preUpdate(time: number, delta: number) {
    super.preUpdate(delta, time);
    if (
      this.reach ||
      this.target.distance(new Phaser.Math.Vector2(this.x, this.y)) <=
        this.speed
    ) {
      this.setRandomTarget();
      this.reach = false;
      this.setHeading();
    }
  }
  setHeading() {
    let vPos = new Phaser.Math.Vector2(this.x, this.y);
    let vTarget = this.target.clone();
    let velocity = vTarget.subtract(vPos).normalize().scale(this.speed);
    this.setVelocity(velocity.x, velocity.y);
  }
}

Here's the code to create them and add them to the scene:

for (let i = 0; i < 10; i++) {
      this.sheeps.push(
        new Sheep(
          this,
          Math.round(Math.random() * width),
          Math.round(Math.random() * height),
          "sheep2"
        )
      );
    }
    let sheepGroup = this.physics.add.group(this.sheeps);

    this.physics.add.collider(sheepGroup, sheepGroup);

Here's the result:
Circular collision
Rectangular collision

Body:
Part one of your question

If you extend from Phaser.Physics.Arcade.Sprite in the constructor you can do both, this.setCircle (link documentation) or this.body.setCircle (link documentation) should do the same thing.

Part two of your question (look below for Update, solution)

Why it doesn't work, is difficult to say, without seeing your code, but here is how I would diagnose the problem:

turn on the debug setting for physics (I assume the collision box is somehow offset)

var config = {
        ...
        physics: {
           default: 'arcade',
           arcade: {
              ...
              debug: true
           }
        },
  };

check the browser console for errors (immediate motion stop, indicates a probal error)

Update/Solution:

After going over your code, I would have to say the problem is the line

let sheepGroup = this.physics.add.group(this.sheeps);

just change it to

let sheepGroup = this.add.group(this.sheeps);

and it should work. The physics of the phaser group is interfering with the physics bodies of the sheeps.

Here the demo, I used for testing:

class Sheep extends Phaser.Physics.Arcade.Sprite {

  constructor(scene, x, y, spriteKey) {
    super(scene, x, y, spriteKey);
    this.target = new Phaser.Math.Vector2();
    this.speed = 50;
    this.reach = true;
    this.setOrigin(0, 0);
    scene.add.existing(this);
    scene.physics.add.existing(this);

    this.setCircle(5);
    this.visible = false;
    //this.scale = 0.05;
    this.setBounce(1);

  }
  setRandomTarget() {
    this.target = new Phaser.Math.Vector2(
      Math.random() * this.scene.scale.width,
      Math.random() * this.scene.scale.height
    );
  }
  preUpdate(time, delta) {
    super.preUpdate(delta, time);
    if (
      this.reach ||
      this.target.distance(new Phaser.Math.Vector2(this.x, this.y)) <=
        this.speed
    ) {
      this.setRandomTarget();
      this.reach = false;
      this.setHeading();
    }
  }

  setHeading() {
    let vPos = new Phaser.Math.Vector2(this.x, this.y);
    let vTarget = this.target.clone();
    let velocity = vTarget
        .subtract(vPos)
        .normalize()
        .scale(this.speed);

    this.setVelocity(velocity.x, velocity.y);
  }
}

var config = {
    type: Phaser.AUTO,
    width: 400,
    height: 200,
    physics: {
        default: 'arcade',
        arcade: {
            debug: true
        }
    },
    scene: { create }
};

var controls;

var game = new Phaser.Game(config);

function create ()
{
    this.sheeps = [];
  for (let i = 0; i < 20
  ; i++) {
      this.sheeps.push(
        new Sheep(
          this,
          Math.round(Math.random() * 400),
          Math.round(Math.random() * 200),
          "sheep2"
        )
      );
    }
    let sheepGroup = this.add.group(this.sheeps);

    this.physics.add.collider(sheepGroup, sheepGroup);

}

<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>


问:
Comparing dates across different data frames and return output
I have two data frames with different data for the same people. Data frame 1 (dfx) has unique ids and dates people had appointments and data frame 2 has unique ids and a start and end date.

It looks something like below:

```<code>c1 <- c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2")
d1 <- c("2017", "2018", "2019", "2020", "2021", "2019", "2019", "2019", "2020", "2021")

dfx <- data.frame(c1,d1)
</code>```
```<code>c2 <- c("1", "1", "2")
ds <- c("2017", "2020", "2017")
de <- c("2018", "2021", "2018")

dfy <- data.frame(c2,ds,de)
</code>```

I'm working with data frame 2 and I want to know if dates in data frame 1 is within the start and end dates in data frame 2. I am trying to get an output in dfy saying TRUE or FALSE for overlap.

For this example, the output should return TRUE, TRUE, FALSE.

I've tried working with this on dplyr and not getting the result I'm looking. I'll appreciate any help. Thanks.

dplyr code:

```<code>overlap <- dfy %>%
  group_by(c2) %>%
  mutate (on_hold = any(mapply(function(id, start, end) any(id == dfx$c1 & dfx$d1 > start & dfx$d1 < end), c2, ds, de))) %>%
  arrange(c2, ds, de, on_hold)
</code>```

Body:
I have two data frames with different data for the same people. Data frame 1 (dfx) has unique ids and dates people had appointments and data frame 2 has unique ids and a start and end date.

It looks something like below:

c1 <- c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2")
d1 <- c("2017", "2018", "2019", "2020", "2021", "2019", "2019", "2019", "2020", "2021")

dfx <- data.frame(c1,d1)

c2 <- c("1", "1", "2")
ds <- c("2017", "2020", "2017")
de <- c("2018", "2021", "2018")

dfy <- data.frame(c2,ds,de)

I'm working with data frame 2 and I want to know if dates in data frame 1 is within the start and end dates in data frame 2. I am trying to get an output in dfy saying TRUE or FALSE for overlap.

For this example, the output should return TRUE, TRUE, FALSE.

I've tried working with this on dplyr and not getting the result I'm looking. I'll appreciate any help. Thanks.

dplyr code:

overlap <- dfy %>%
  group_by(c2) %>%
  mutate (on_hold = any(mapply(function(id, start, end) any(id == dfx$c1 & dfx$d1 > start & dfx$d1 < end), c2, ds, de))) %>%
  arrange(c2, ds, de, on_hold)

Body:
solution

ranges <- dfx %>%
  group_by(c1) %>%
  summarise(range = list(unique(d1)))

left_join(dfy, ranges, by = c("c2" = "c1")) %>%
  rowwise() %>%
  mutate(in_range = ds %in% range & de %in% range)

output

# A tibble: 3 x 5
# Rowwise:
  c2    ds    de    range     in_range
  <fct> <fct> <fct> <list>    <lgl>
1 1     2017  2018  <fct [5]> TRUE
2 1     2020  2021  <fct [5]> TRUE
3 2     2017  2018  <fct [3]> FALSE

data as provided by OP

c1 <- c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2")
d1 <- c("2017", "2018", "2019", "2020", "2021", "2019", "2019", "2019", "2020", "2021")

dfx <- data.frame(c1,d1)

c2 <- c("1", "1", "2")
ds <- c("2017", "2020", "2017")
de <- c("2018", "2021", "2018")

dfy <- data.frame(c2,ds,de)


问:
How to filter object array that contains messages from different numbers and leave only last message
if for example i have an array that contains all messages sent or received to number 123456789

```<code>  Messages: [
    { FromNumber: 9999, ToNumber: 123456789, Message: "first" },
    { FromNumber: 9999, ToNumber: 123456789, Message: "second" },
    { FromNumber: 123456789, ToNumber: 9999, Message: "me first2" },
    { FromNumber: 123456789, ToNumber: 9999, Message: "me second2" },
    { FromNumber: 123456789, ToNumber: 1234, Message: "me first" },
    { FromNumber: 1234, ToNumber: 123456789, Message: "second" },
  ],
</code>```

And the result should look like

```<code>Messages: [
    { FromNumber: 123456789, ToNumber: 9999, Message: "me second2" },
    { FromNumber: 1234, ToNumber: 123456789, Message: "second" },
  ],
</code>```

I tried something like this but that did not work, what would be the best solution?

```<code>Messages.filter(
    (v, i, a) => a.findLastIndex((t) => t.ToNumber === v.FromNumber && t.FromNumber === v.ToNumber) === i
  );
</code>```

答:
You could collect objects by their key, different from the common key and return the objects.

const
    messages = [{ FromNumber: 9999, ToNumber: 123456789, Message: "first" }, { FromNumber: 9999, ToNumber: 123456789, Message: "second" }, { FromNumber: 123456789, ToNumber: 9999, Message: "me first2" }, { FromNumber: 123456789, ToNumber: 9999, Message: "me second2" }, { FromNumber: 123456789, ToNumber: 1234, Message: "me first" }, { FromNumber: 1234, ToNumber: 123456789, Message: "second" }],
    common = 123456789,
    result = Object.values(messages.reduce((r, o) => {
        const key = o.FromNumber !== common ? o.FromNumber : o.ToNumber;
        r[key] = o;
        return r;
    }, {}));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
if for example i have an array that contains all messages sent or received to number 123456789

  Messages: [
    { FromNumber: 9999, ToNumber: 123456789, Message: "first" },
    { FromNumber: 9999, ToNumber: 123456789, Message: "second" },
    { FromNumber: 123456789, ToNumber: 9999, Message: "me first2" },
    { FromNumber: 123456789, ToNumber: 9999, Message: "me second2" },
    { FromNumber: 123456789, ToNumber: 1234, Message: "me first" },
    { FromNumber: 1234, ToNumber: 123456789, Message: "second" },
  ],

And the result should look like

Messages: [
    { FromNumber: 123456789, ToNumber: 9999, Message: "me second2" },
    { FromNumber: 1234, ToNumber: 123456789, Message: "second" },
  ],

I tried something like this but that did not work, what would be the best solution?

Messages.filter(
    (v, i, a) => a.findLastIndex((t) => t.ToNumber === v.FromNumber && t.FromNumber === v.ToNumber) === i
  );

Body:
You could collect objects by their key, different from the common key and return the objects.

const
    messages = [{ FromNumber: 9999, ToNumber: 123456789, Message: "first" }, { FromNumber: 9999, ToNumber: 123456789, Message: "second" }, { FromNumber: 123456789, ToNumber: 9999, Message: "me first2" }, { FromNumber: 123456789, ToNumber: 9999, Message: "me second2" }, { FromNumber: 123456789, ToNumber: 1234, Message: "me first" }, { FromNumber: 1234, ToNumber: 123456789, Message: "second" }],
    common = 123456789,
    result = Object.values(messages.reduce((r, o) => {
        const key = o.FromNumber !== common ? o.FromNumber : o.ToNumber;
        r[key] = o;
        return r;
    }, {}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Use map with nested lists
I am struggling with using map from the library purrr correctly. I would like to calculate the weighted mean of my sample by nesting a common observations in a list and then using map(). (I know this would also work with group_by)

MWE: Suppose I have observed 3 different subjects (indicated by 'id'), I have their sample weights ('weights') and corresponding observations ('obs').

```<code>df <- tibble(id = c(1, 1, 2, 2, 3,3), weights = c(0.3,0.7,0.25,0.75,0.14,0.86), obs = 6:1)
df
# A tibble: 6 x 3
     id weights   obs
  <dbl>   <dbl> <int>
1     1    0.3      6
2     1    0.7      5
3     2    0.25     4
4     2    0.75     3
5     3    0.14     2
6     3    0.86     1
</code>```

I would like to calculate the weighted average in each subject.Therefore, I nest the weights and observations.

```<code>df %>% nest(data = c(weights, obs))
# A tibble: 3 x 2
     id data
  <dbl> <list>
1     1 <tibble [2 x 2]>
2     2 <tibble [2 x 2]>
3     3 <tibble [2 x 2]>
</code>```

Now I would like to use map to apply a function to each element of data. More precisely, I try to solve it as following

```<code>df %>% nest(data = c(weights, obs)) %>% map(data, ~ (.x$weights*.x$obs)/sum(.x$weights))

Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found
</code>```

As you can see this results in a lot of error messages. In order to better understand map I tried to multiply the weights vector of each ID with 2.

```<code>df %>% nest(data = c(weights, obs)) %>% map(data, ~ .x$weights*2)
$id
[1] ".x[[i]]"         "~.x$weights * 2"

$data
[1] ".x[[i]]"         "~.x$weights * 2"

Warning messages:
1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
2: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found
3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
4: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found

</code>```

and

```<code>df %>% nest(data = c(weights, obs)) %>% map(data, function(x) x$weights*2)
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
$id
[1] ".x[[i]]"                   "function(x) x$weights * 2"

$data
[1] ".x[[i]]"                   "function(x) x$weights * 2"

</code>```

So I also get error messages here. I am quite lost even after reading the documentation of map. I do not see my error. I am happy about any insights!

Thanks a lot!

答:
Could do split-map_dbl for a named vector as return or map_df if a tibble is desired:

tibble(id = c(1, 1, 2, 2, 3,3), weights = c(0.3,0.7,0.25,0.75,0.14,0.86), obs = 6:1) %>%
    split.data.frame(.$id) %>%
    map_dbl(
        ~sum(.x$weights * .x$obs)/sum(.x$weights)
    )
   1    2    3
5.30 3.25 1.14
tibble(id = c(1, 1, 2, 2, 3,3), weights = c(0.3,0.7,0.25,0.75,0.14,0.86), obs = 6:1) %>%
    split.data.frame(.$id) %>%
    map_df(
        ~sum(.x$weights * .x$obs)/sum(.x$weights)
    )
    # A tibble: 1 x 3
    `1`   `2`   `3`
  <dbl> <dbl> <dbl>
1   5.3  3.25  1.14

```

Title: Use map with nested lists

Body:
I am struggling with using map from the library purrr correctly. I would like to calculate the weighted mean of my sample by nesting a common observations in a list and then using map(). (I know this would also work with group_by)

MWE: Suppose I have observed 3 different subjects (indicated by 'id'), I have their sample weights ('weights') and corresponding observations ('obs').

df <- tibble(id = c(1, 1, 2, 2, 3,3), weights = c(0.3,0.7,0.25,0.75,0.14,0.86), obs = 6:1)
df
# A tibble: 6 x 3
     id weights   obs
  <dbl>   <dbl> <int>
1     1    0.3      6
2     1    0.7      5
3     2    0.25     4
4     2    0.75     3
5     3    0.14     2
6     3    0.86     1

I would like to calculate the weighted average in each subject.Therefore, I nest the weights and observations.

df %>% nest(data = c(weights, obs))
# A tibble: 3 x 2
     id data
  <dbl> <list>
1     1 <tibble [2 x 2]>
2     2 <tibble [2 x 2]>
3     3 <tibble [2 x 2]>

Now I would like to use map to apply a function to each element of data. More precisely, I try to solve it as following

df %>% nest(data = c(weights, obs)) %>% map(data, ~ (.x$weights*.x$obs)/sum(.x$weights))

Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘~(.x$weights * .x$obs)/sum(.x$weights)’ not found

As you can see this results in a lot of error messages. In order to better understand map I tried to multiply the weights vector of each ID with 2.

df %>% nest(data = c(weights, obs)) %>% map(data, ~ .x$weights*2)
$id
[1] ".x[[i]]"         "~.x$weights * 2"

$data
[1] ".x[[i]]"         "~.x$weights * 2"

Warning messages:
1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
2: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found
3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
4: In .f(.x[[i]], ...) : data set ‘~.x$weights * 2’ not found

and

df %>% nest(data = c(weights, obs)) %>% map(data, function(x) x$weights*2)
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
Warning in .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
Warning in .f(.x[[i]], ...) :
  data set ‘function(x) x$weights * 2’ not found
$id
[1] ".x[[i]]"                   "function(x) x$weights * 2"

$data
[1] ".x[[i]]"                   "function(x) x$weights * 2"

So I also get error messages here. I am quite lost even after reading the documentation of map. I do not see my error. I am happy about any insights!

Thanks a lot!


问:
How to fill null values in a Pyspark Dataframe column with values from the same column, whose corresponding value in another column is same
I have below data:

df=

user_id
user_name

101
abc

102
def

null
ghi

104
ghi

null
abc

104
ghi

102
def

101
abc

expected output=

user_id
user_name

101
abc

102
def

104
ghi

104
ghi

101
abc

104
ghi

102
def

101
abc

I tried using the below codes:
code1=

```<code>df.where(df.user_id.isNotNull()).select("user_id", "user_name").distinct().show()
</code>```

output:

user_id
user_name

101
abc

102
def

104
ghi

2nd code=

```<code>df.filter(F.col("user_id").isNull()).withColumn("user_id", F.when(df.user_id.isNull(), "a")).show()
</code>```

output:

user_id
user_name
dep

a
ghi
test

a
abc
dev

I need to somehow use this both code lines in 1 single code, so that the "a" can be updated and I get the desired output. Can someone pls help?

答:
You can join the code1 to original dataframe and use coalesce to fill the value. coalesce takes the first non-null values in either column.

```<code># I add renaming of column to avoid the duplicate column name.
code1 = (df.where(df.user_id.isNotNull())
        .select("user_id", "user_name")
        .withColumnRenamed("user_id", "fill_user_id")
        .distinct())

# Join with original dataframe and fill the value
df = (df.join(code1, on="user_name", how="left")
     .select(F.coalesce("user_id", "fill_user_id").alias("user_id"), "user_name"))
</code>```

Result

+-------+---------+
|user_id|user_name|
+-------+---------+
|    104|      ghi|
|    104|      ghi|
|    104|      ghi|
|    101|      abc|
|    101|      abc|
|    101|      abc|
|    102|      def|
|    102|      def|
+-------+---------+
```
<p>An alternative solution is to use Window function to fill. With Window function, you can fill missing values with just 1 function. I use <code>first</code> with <code>ignorenulls=True</code> option to take first non-null value with the same user_name.</p>
```df = df.withColumn("user_id",
         F.first("user_id", ignorenulls=True).over(Window.partitionBy("user_name")))
```

Body:
I have below data:

df=

user_id
user_name

101
abc

102
def

null
ghi

104
ghi

null
abc

104
ghi

102
def

101
abc

expected output=

user_id
user_name

101
abc

102
def

104
ghi

104
ghi

101
abc

104
ghi

102
def

101
abc

I tried using the below codes:
code1=

df.where(df.user_id.isNotNull()).select("user_id", "user_name").distinct().show()

output:

user_id
user_name

101
abc

102
def

104
ghi

2nd code=

df.filter(F.col("user_id").isNull()).withColumn("user_id", F.when(df.user_id.isNull(), "a")).show()

output:

user_id
user_name
dep

a
ghi
test

a
abc
dev

I need to somehow use this both code lines in 1 single code, so that the "a" can be updated and I get the desired output. Can someone pls help?

Body:
You can join the code1 to original dataframe and use coalesce to fill the value. coalesce takes the first non-null values in either column.

# I add renaming of column to avoid the duplicate column name.
code1 = (df.where(df.user_id.isNotNull())
        .select("user_id", "user_name")
        .withColumnRenamed("user_id", "fill_user_id")
        .distinct())

# Join with original dataframe and fill the value
df = (df.join(code1, on="user_name", how="left")
     .select(F.coalesce("user_id", "fill_user_id").alias("user_id"), "user_name"))

Result

+-------+---------+
|user_id|user_name|
+-------+---------+
|    104|      ghi|
|    104|      ghi|
|    104|      ghi|
|    101|      abc|
|    101|      abc|
|    101|      abc|
|    102|      def|
|    102|      def|
+-------+---------+

An alternative solution is to use Window function to fill. With Window function, you can fill missing values with just 1 function. I use first with ignorenulls=True option to take first non-null value with the same user_name.

df = df.withColumn("user_id",
         F.first("user_id", ignorenulls=True).over(Window.partitionBy("user_name")))


问:
Update Method RowInserted Not Called On Submit for Blazorise DataGrid
I need to have all the CRUD methods be external.  But there is something missing. What?

I set the UseInternalEditing=false, define RowInserting and the external method OnRowInserted is not reached.

Code

```<code><DataGrid TItem="AppInstructor"
      EditMode="Blazorise.DataGrid.DataGridEditMode.Inline"
      Editable="true"
      RowInserted="@OnRowInserted"
      UseInternalEditing="false"
      ShowValidationFeedback="true"
      Data="@_instService.GetALL()">
<DataGridCommandColumn TItem="AppInstructor">
    <SaveCommandTemplate>
        <Button Color="Color.Primary" Clicked="@context.Clicked">Save</Button>
    </SaveCommandTemplate>
    <EditCommandTemplate>
        <Button Color="Color.Primary" Clicked="@context.Clicked">Edit</Button>
    </EditCommandTemplate>
</DataGridCommandColumn>
<DataGridColumn TItem="AppInstructor" Field="@nameof(AppInstructor.LastName)" Editable="true" Caption="First Name" Sortable="true">
</DataGridColumn>
<DataGridColumn TItem="AppInstructor" Field="@nameof(AppInstructor.LastName)" Editable="true" Caption="Last Name" Sortable="true">
</DataGridColumn>
</code>```

Code section

```<code>@code {

private void OnRowInserted(SavedRowItem<AppInstructor,
                           Dictionary<string, object>> e)
{
   ...
}
</code>```

答:
You have to add PreventDefaultOnSubmit to have your custom click event trigger.

```<code><SaveCommandTemplate>
    <Button Type="ButtonType.Submit"
            PreventDefaultOnSubmit
            Color="Color.Primary"
            Clicked="@context.Clicked">Save</Button>

</SaveCommandTemplate>
</code>```

Then RowInserted="OnRowInserted" will be called.

Body:
I need to have all the CRUD methods be external.  But there is something missing. What?

I set the UseInternalEditing=false, define RowInserting and the external method OnRowInserted is not reached.

Code

<DataGrid TItem="AppInstructor"
      EditMode="Blazorise.DataGrid.DataGridEditMode.Inline"
      Editable="true"
      RowInserted="@OnRowInserted"
      UseInternalEditing="false"
      ShowValidationFeedback="true"
      Data="@_instService.GetALL()">
<DataGridCommandColumn TItem="AppInstructor">
    <SaveCommandTemplate>
        <Button Color="Color.Primary" Clicked="@context.Clicked">Save</Button>
    </SaveCommandTemplate>
    <EditCommandTemplate>
        <Button Color="Color.Primary" Clicked="@context.Clicked">Edit</Button>
    </EditCommandTemplate>
</DataGridCommandColumn>
<DataGridColumn TItem="AppInstructor" Field="@nameof(AppInstructor.LastName)" Editable="true" Caption="First Name" Sortable="true">
</DataGridColumn>
<DataGridColumn TItem="AppInstructor" Field="@nameof(AppInstructor.LastName)" Editable="true" Caption="Last Name" Sortable="true">
</DataGridColumn>

Code section

@code {

private void OnRowInserted(SavedRowItem<AppInstructor,
                           Dictionary<string, object>> e)
{
   ...
}

Body:
You have to add PreventDefaultOnSubmit to have your custom click event trigger.

<SaveCommandTemplate>
    <Button Type="ButtonType.Submit"
            PreventDefaultOnSubmit
            Color="Color.Primary"
            Clicked="@context.Clicked">Save</Button>

</SaveCommandTemplate>

Then RowInserted="OnRowInserted" will be called.


问:
Laravel: symlink(): Permission denied on centos how to fix?
I am installing a project made in laravel on a server with a CENTOS 7.9 vmware [cpnael] v94.0.8 operating system, modify the permissions I needed to operate the project.

When I run the project I get the present error:

```<code>[2021-05-10 16:26:39] production.ERROR: symlink(): Permission denied {"exception":"[object] (ErrorException(code: 0): symlink(): Permission denied at /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:315)
[stacktrace]
#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'symlink(): Perm...', '/home/cbdev/pub...', 315, Array)
#1 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(315): symlink('/home/cbdev/pub...', '/home/cbdev/pub...')
#2 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Foundation/Console/StorageLinkCommand.php(45): Illuminate\\Filesystem\\Filesystem->link('/home/cbdev/pub...', '/home/cbdev/pub...')
#3 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Foundation\\Console\\StorageLinkCommand->handle()
#4 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/Util.php(40): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#5 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure(Object(Closure))
#6 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Illuminate\\Foundation\\Application), Array, Object(Closure))
#7 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/Container.php(611): Illuminate\\Container\\BoundMethod::call(Object(Illuminate\\Foundation\\Application), Array, Array, NULL)
#8 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\\Container\\Container->call(Array)
</code>```

How can I solve this problem?

答:
If php artisan storage:link does not help, it can happen that your hosting does not allow you to make symlinks with a command.

Try to contact the support of your hosting if this is the case, or try to make the symlink manually using midnight commander (use the command mc in the ssh of the webserver then create the symlink between public storage and storage/app/public)  ,
or with the ln linux command (https://linuxize.com/post/how-to-create-symbolic-links-in-linux-using-the-ln-command/).

Body:
I am installing a project made in laravel on a server with a CENTOS 7.9 vmware [cpnael] v94.0.8 operating system, modify the permissions I needed to operate the project.

When I run the project I get the present error:

[2021-05-10 16:26:39] production.ERROR: symlink(): Permission denied {"exception":"[object] (ErrorException(code: 0): symlink(): Permission denied at /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:315)
[stacktrace]
#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'symlink(): Perm...', '/home/cbdev/pub...', 315, Array)
#1 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(315): symlink('/home/cbdev/pub...', '/home/cbdev/pub...')
#2 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Foundation/Console/StorageLinkCommand.php(45): Illuminate\\Filesystem\\Filesystem->link('/home/cbdev/pub...', '/home/cbdev/pub...')
#3 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Foundation\\Console\\StorageLinkCommand->handle()
#4 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/Util.php(40): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#5 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\Util::unwrapIfClosure(Object(Closure))
#6 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Illuminate\\Foundation\\Application), Array, Object(Closure))
#7 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Container/Container.php(611): Illuminate\\Container\\BoundMethod::call(Object(Illuminate\\Foundation\\Application), Array, Array, NULL)
#8 /home/cbdev/public_html/crater/vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\\Container\\Container->call(Array)

How can I solve this problem?


问:
Apple Push Notification service PHP cpu usage too high. how can I Improve performance?
My task is sending push notification to multiple users which is working fine with following function

```<code>function push_to_apns_badge($token_array)
{
    $apnsHost = 'gateway.sandbox.push.apple.com';
    $apnsPort = 2195;
    $pem_path  = MODULE_DIR.'push_notification'.DIRECTORY_SEPARATOR;
    $apnsCert = $pem_path.'apns-dev.pem';

    if(is_array($token_array) && count($token_array))
    {
        foreach ($token_array as $token)
        {
            $streamContext = stream_context_create();
            stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

            $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
            $badge_count = (int)$token['badge'];
            $payload = get_payload_badge($badge_count);

            $apnsMessage = get_one_message_to_write_badge($token['token'],$payload);
            $wrt = fwrite($apns, $apnsMessage);

            $_error_str .= " $error $errorString ";
            socket_close($apns);
            fclose($apns);
        }
    }
    return array(true,$_error_str);
}
</code>```

But it will take too much cpu usage.

Can I improve Performance somehow? or something missing there?

Thanks

答:
You are making too many connections to Apple and they could block you if you do it this way.

I suspect the creating and tearing down of the connection with each message is also your slow point there!

Apple recommend opening a connection, sending your messages, leaving it open for as long as you can, and to send future messages down that same connection too.

You may want to look at Urban Airship which will send 1 million messages a month free?

ContentLicense: CC BY-SA 3.0

Body:
My task is sending push notification to multiple users which is working fine with following function

function push_to_apns_badge($token_array)
{
    $apnsHost = 'gateway.sandbox.push.apple.com';
    $apnsPort = 2195;
    $pem_path  = MODULE_DIR.'push_notification'.DIRECTORY_SEPARATOR;
    $apnsCert = $pem_path.'apns-dev.pem';

    if(is_array($token_array) && count($token_array))
    {
        foreach ($token_array as $token)
        {
            $streamContext = stream_context_create();
            stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

            $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
            $badge_count = (int)$token['badge'];
            $payload = get_payload_badge($badge_count);

            $apnsMessage = get_one_message_to_write_badge($token['token'],$payload);
            $wrt = fwrite($apns, $apnsMessage);

            $_error_str .= " $error $errorString ";
            socket_close($apns);
            fclose($apns);
        }
    }
    return array(true,$_error_str);
}

But it will take too much cpu usage.

Can I improve Performance somehow? or something missing there?

Thanks


问:
Can someone provide an example of how to use an Angular FormArray with an Angular Material MatSelect
I know you can use a FormControl with an array to build out a multi option MatSelect, but am trying to use FormArrays to handle a multi select. I keep getting errors and after searching Google for a while have ended up with a workaround that just grabs the value from the FormArray, sets it to a FormControl as an array, and then subscribes to that to set the original FormArray value form the FormControl. I don't like this solution though and was wondering if anyone has a working example of how to use a FormArray with a MatSelect</p>
```<code>  <mat-select
    multiple
    placeholder="placeholder text"
    [formControlArray]="nameOfFormControlArray">
    <mat-option
      *ngFor="let option of options | keyvalue: originalOrder ; let i = index"
      [value]="option.key === 'true' ? true : (!option.key || option.key === 'false') ? false : option.key"
      [attr.name]="formControlName">
      {{ option.value.name || option.key }}
    </mat-option>
  </mat-select>
</code>```

答:
Here is the workaround I am using if it helps anyone. I created 'formControl' that is just a regular FormControl. OnInit it is loaded with he saved values and used with the MatSelect. At the same time it's valueChanges is subscribed to and used to populate the formControlArray. The array is cleared each time to remove all the FormControls in it, then each value is pushed in as a new FormControl instance. It isn't super clean, but it works.</p>
```<code>      this.formControl.valueChanges.subscribe((values) => {
        formControlArray.clear({ emitEvent: false });

        values.forEach((value) => formControlArray.push(new FormControl(value)));
        this.parentFormGroup.get(this.formControlName).markAsDirty();
      });
    }
</code>```

Body:
I know you can use a FormControl with an array to build out a multi option MatSelect, but am trying to use FormArrays to handle a multi select. I keep getting errors and after searching Google for a while have ended up with a workaround that just grabs the value from the FormArray, sets it to a FormControl as an array, and then subscribes to that to set the original FormArray value form the FormControl. I don't like this solution though and was wondering if anyone has a working example of how to use a FormArray with a MatSelect

  <mat-select
    multiple
    placeholder="placeholder text"
    [formControlArray]="nameOfFormControlArray">
    <mat-option
      *ngFor="let option of options | keyvalue: originalOrder ; let i = index"
      [value]="option.key === 'true' ? true : (!option.key || option.key === 'false') ? false : option.key"
      [attr.name]="formControlName">
      {{ option.value.name || option.key }}
    </mat-option>
  </mat-select>

Body:
Here is the workaround I am using if it helps anyone. I created 'formControl' that is just a regular FormControl. OnInit it is loaded with he saved values and used with the MatSelect. At the same time it's valueChanges is subscribed to and used to populate the formControlArray. The array is cleared each time to remove all the FormControls in it, then each value is pushed in as a new FormControl instance. It isn't super clean, but it works.

      this.formControl.valueChanges.subscribe((values) => {
        formControlArray.clear({ emitEvent: false });

        values.forEach((value) => formControlArray.push(new FormControl(value)));
        this.parentFormGroup.get(this.formControlName).markAsDirty();
      });
    }


问:
Calling multiple handler methods in react js onSubmit
I am working on a React JS project which uses a search form component with an onSubmit. I want to call multiple search handler methods which makes Axios calls to multiple backend APIs at the same time. I am using a class component, my onSubmit calls a searchHandler method which contains multiple axios calls to the backend. But when I submit the form I get an error: frontend error

This is my search handler function which my onSubmit calls, it contains two Axios calls:

applicationSearchHandler(event) {
    event.preventDefault();

    console.log(this.state.number, this.state.orgChoice);

    LoanAppDataService.getPromoCodeExpiryInfo(
      this.state.orgChoice,
      this.state.promoCode,
      this.state.number
    )
      .then((response) => {
        if (response && response.data && response.data.length > 0) {
          console.log(response.data[0].applicationId);

          this.setState((state) => ({
            ...this.state,
            expiryStatusMessage: response.data[0].message,
            isSearched: true,
            error: false,
          }));
        }
      })
      .catch((error) => {
        this.setState({
          error: !this.state.error,
          errorAlert: "",
          isSearched: false,
        });
      });

    LoanAppDataService.getCorrectPromoCodeInfoEmailAndOrgId(
      this.state.emailId,
      this.state.orgChoice
    )
      .then((response) => {
        this.setState((state) => ({
          associatedPromoMessage: response.data[0].message,
          isSearched: true,
          error: false,
        }));
      })
      .catch((error) => {
        this.setState({
          error: !this.state.error,
          errorAlert: "",
          isSearched: false,
        });
      });

    this.setState((state) => ({
      ...this.state,
      number: "",
      customerName: "",
      orgChoice: "",
    }));

    const isValid = this.validateSsn();
  }```
</div>
</div>
</p>
<p>This is how my onSubmit looks like:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form onSubmit={this.applicationSearchHandler}></code>```

I don't exactly know how to rectify this error, I tried multiple approaches but nothing seems to be working for now.

答:
You get an error In this part of your code

expiryStatusMessage: response.data[0].message

Most Probably response.data[0] is null or undefined and this code tries to find a message from null, So it gives Error

You can use nullish operator here like that

expiryStatusMessage: response.data[0]?.message

Body:
I am working on a React JS project which uses a search form component with an onSubmit. I want to call multiple search handler methods which makes Axios calls to multiple backend APIs at the same time. I am using a class component, my onSubmit calls a searchHandler method which contains multiple axios calls to the backend. But when I submit the form I get an error: frontend error

This is my search handler function which my onSubmit calls, it contains two Axios calls:

applicationSearchHandler(event) {
    event.preventDefault();

    console.log(this.state.number, this.state.orgChoice);

    LoanAppDataService.getPromoCodeExpiryInfo(
      this.state.orgChoice,
      this.state.promoCode,
      this.state.number
    )
      .then((response) => {
        if (response && response.data && response.data.length > 0) {
          console.log(response.data[0].applicationId);

          this.setState((state) => ({
            ...this.state,
            expiryStatusMessage: response.data[0].message,
            isSearched: true,
            error: false,
          }));
        }
      })
      .catch((error) => {
        this.setState({
          error: !this.state.error,
          errorAlert: "",
          isSearched: false,
        });
      });

    LoanAppDataService.getCorrectPromoCodeInfoEmailAndOrgId(
      this.state.emailId,
      this.state.orgChoice
    )
      .then((response) => {
        this.setState((state) => ({
          associatedPromoMessage: response.data[0].message,
          isSearched: true,
          error: false,
        }));
      })
      .catch((error) => {
        this.setState({
          error: !this.state.error,
          errorAlert: "",
          isSearched: false,
        });
      });

    this.setState((state) => ({
      ...this.state,
      number: "",
      customerName: "",
      orgChoice: "",
    }));

    const isValid = this.validateSsn();
  }

This is how my onSubmit looks like:

<form onSubmit={this.applicationSearchHandler}>

I don't exactly know how to rectify this error, I tried multiple approaches but nothing seems to be working for now.


问:
When should I unsubscribe from firestore listener?
I am writing a social app where users can check if they have new messages when they navigate to ChatList page. My idea is the following. On useEffect I load the newest 10 chats. Then if the user wants to see their oldest chats, I will have "more" button which will load nxt batch of chats. I don't want to load everything at once, since some users may have lost of chats. This is part of my code:

```<code>import { fetchInitialChats, fetchNextChats } from "./actions";

function ChatList(props) {
  const limit = 10;
  const [chats, setChats] = useState([]);
  const [lastFetched, setLastFetched] = useState(null);

  useEffect(() => {
    console.log("fetch initial chats");
    async function initialFetch() {
      let result;
      try {
        result = await fetchInitialChats(setLastFetched, limit);
        console.log("result: ", result);
        setChats(result);
        setError(false);
      } catch (error) {
        setError(true);
        console.log("Error during initial fetch of chats: ", error);
      }
    }
    initialFetch();
  }, []);
</code>```

In my actions.js file I implement fetchInitialChats and  fetchNextChats:

```<code>export const fetchInitialChats = async (setLastFetched, limit) => {
  console.log("fetching initial batch of chats");
  let chats = [];
  let query = await firebase
    .firestore()
    .collection("Chats")
    .where("users", "array-contains", firebase.auth().currentUser.uid)
    .orderBy("lastMessageTimestamp", "desc")
    .limit(limit);
  const unsubRef = query.onSnapshot((snapshot) => {
    chats = snapshot.docs.map((doc) => {
      const data = doc.data();
      const id = doc.id;
      return { id, ...data };
    });
   if (snapshot.docs.length > 0) {
     const last = snapshot.docs[snapshot.docs.length - 1];
     setLastFetched(last);
   }
  });
  unsubRef();
  return chats;
};
</code>```

My questions are two:

Is this the right way to subscribe from a listener? Do I need to unsubscribe from useEffect or from somewhere else?

Is this actually the right way to perform pagination when using lister. If I am fetching chats with simple get(), without listening for new updates, sure, this is the way to go. What if I am listening to live updates and I want to perform pagination?

答:
Fetching items once don't require listening to new updates.

export const fetchInitialChats = async (setLastFetched, limit) => {
  console.log("fetching initial batch of chats");

  let chatsRef = firebase
    .firestore()
    .collection("Chats")
    .where("users", "array-contains", firebase.auth().currentUser.uid)
    .orderBy("lastMessageTimestamp", "desc")
    .limit(limit);

  const snapshots = await chatsRef.get();

  // Utility function to extract docs from collection snapshots
  const extractSnapshots = (snapshots) => {
    let extracts = [];
    snapshots.forEach((documentSnapshot) => {
      extracts.push(documentSnapshot.data());
    });
    return extracts;
  };

  const chats = extractSnapshots(snapshots);

console.log({chats})

  if (chats.length > 0) {
    const last = chats[chats.length - 1];
    setLastFetched(last);
  }

  return chats;
};

```
<p>then fetch initial chats when component mounted</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
  // fetchInitialChats(20)
}, []);

</code>```

Body:
I am writing a social app where users can check if they have new messages when they navigate to ChatList page. My idea is the following. On useEffect I load the newest 10 chats. Then if the user wants to see their oldest chats, I will have "more" button which will load nxt batch of chats. I don't want to load everything at once, since some users may have lost of chats. This is part of my code:

import { fetchInitialChats, fetchNextChats } from "./actions";

function ChatList(props) {
  const limit = 10;
  const [chats, setChats] = useState([]);
  const [lastFetched, setLastFetched] = useState(null);

  useEffect(() => {
    console.log("fetch initial chats");
    async function initialFetch() {
      let result;
      try {
        result = await fetchInitialChats(setLastFetched, limit);
        console.log("result: ", result);
        setChats(result);
        setError(false);
      } catch (error) {
        setError(true);
        console.log("Error during initial fetch of chats: ", error);
      }
    }
    initialFetch();
  }, []);

In my actions.js file I implement fetchInitialChats and  fetchNextChats:

export const fetchInitialChats = async (setLastFetched, limit) => {
  console.log("fetching initial batch of chats");
  let chats = [];
  let query = await firebase
    .firestore()
    .collection("Chats")
    .where("users", "array-contains", firebase.auth().currentUser.uid)
    .orderBy("lastMessageTimestamp", "desc")
    .limit(limit);
  const unsubRef = query.onSnapshot((snapshot) => {
    chats = snapshot.docs.map((doc) => {
      const data = doc.data();
      const id = doc.id;
      return { id, ...data };
    });
   if (snapshot.docs.length > 0) {
     const last = snapshot.docs[snapshot.docs.length - 1];
     setLastFetched(last);
   }
  });
  unsubRef();
  return chats;
};

My questions are two:

Is this the right way to subscribe from a listener? Do I need to unsubscribe from useEffect or from somewhere else?

Is this actually the right way to perform pagination when using lister. If I am fetching chats with simple get(), without listening for new updates, sure, this is the way to go. What if I am listening to live updates and I want to perform pagination?

Body:
Fetching items once don't require listening to new updates.

export const fetchInitialChats = async (setLastFetched, limit) => {
  console.log("fetching initial batch of chats");

  let chatsRef = firebase
    .firestore()
    .collection("Chats")
    .where("users", "array-contains", firebase.auth().currentUser.uid)
    .orderBy("lastMessageTimestamp", "desc")
    .limit(limit);

  const snapshots = await chatsRef.get();

  // Utility function to extract docs from collection snapshots
  const extractSnapshots = (snapshots) => {
    let extracts = [];
    snapshots.forEach((documentSnapshot) => {
      extracts.push(documentSnapshot.data());
    });
    return extracts;
  };

  const chats = extractSnapshots(snapshots);

console.log({chats})

  if (chats.length > 0) {
    const last = chats[chats.length - 1];
    setLastFetched(last);
  }

  return chats;
};

then fetch initial chats when component mounted

useEffect(() => {
  // fetchInitialChats(20)
}, []);


问:
Exec systemctl after deployment by capistrano
I want to restart Nginx-unit after deployment by Capistrano

```<code>namespace :deploy do
    desc 'Collec Static Files'
    task :collectImg do
        on roles(:app) do
            execute "sudo systemctl restart unit"
        end
    end
    after :publishing, :collectImg
end
</code>```

After above code, there comes error log like this.

Is there any good way to use systemctl in deployment script???

```<code>DEBUG [08ce969a] Command: sudo systemctl restart unit

DEBUG [08ce969a]    sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper
</code>```

答:
First - Great you are using NGINX Unit with Capistrano!

This problem is related to a couple of issues at a time.

1. Enable tty mode

Add this to your deployment configuration deploy.rb. Capistrano 3.

set :pty, true
```
<p>More Information about PTY</p>
<h2>2. Modify your sudoers file on the App Server</h2>
<p>You have to allow the deployment user to execute sudo commands without the need of entering a password. You can / should limit this power to specific resources. I have added <code>restart</code> and <code>status</code> as examples.</p>
<pre class="lang-sh prettyprint-override"><code>deploy ALL=NOPASSWD:/bin/systemctl restart unit.serivce, /bin/systemctl status unit.serivce
</code>```

As a reference see Capistrano Auth

Would like to chat about your capistrano configuration on our Community NGINX channel.

Body:
I want to restart Nginx-unit after deployment by Capistrano

namespace :deploy do
    desc 'Collec Static Files'
    task :collectImg do
        on roles(:app) do
            execute "sudo systemctl restart unit"
        end
    end
    after :publishing, :collectImg
end

After above code, there comes error log like this.

Is there any good way to use systemctl in deployment script???

DEBUG [08ce969a] Command: sudo systemctl restart unit

DEBUG [08ce969a]    sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper

Body:
First - Great you are using NGINX Unit with Capistrano!

This problem is related to a couple of issues at a time.

1. Enable tty mode

Add this to your deployment configuration deploy.rb. Capistrano 3.

set :pty, true

More Information about PTY

2. Modify your sudoers file on the App Server

You have to allow the deployment user to execute sudo commands without the need of entering a password. You can / should limit this power to specific resources. I have added restart and status as examples.

deploy ALL=NOPASSWD:/bin/systemctl restart unit.serivce, /bin/systemctl status unit.serivce

As a reference see Capistrano Auth

Would like to chat about your capistrano configuration on our Community NGINX channel.


问:
RouteValueDictionary in a c# library project to support html extension helpers?
I am trying to refactor a solution that includes 2 MVC projects: a "User-Experience" project and a corresponding "Content Management System project"

I have set up an independent  C# library -- "Services" -- project in the same solution space to do many things. I want to share Html extension methods used by both web projects by placing them in this "neutral" project so that there are no dependencies between the two MVC projects.

I have a problem with  using the RouteValueDictionary object (to.MergeAttributes) in this class library. I've included a reference to Sytem.Web.Routing in the Services project, but when I attempt to include a using statement at the top of the helper-class file, VStudio refuses to recognize the declaration ("Cannot resolve symbol 'Routing'").

This makes intuitive sense -- only a web project that can engage in URL routing should need a RouteValueDictionary.

But it appears common to use the RouteValueDictionary object inside htmlhelper classes because it can take an anonymous object consisting of name-value pairs and convert it to a Dictionary  in its constructor like this:

```<code>tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
</code>```

...thus providing a way of passing in any number of tag attribute name-value pairs into a tag and a relatively simple syntax for calling the helper in the view:

```<code><%:Html.SomeTag(Model.Id, new {@class = "myClass", title = "myTitle"} %>
</code>```

So if I  can't use the RouteValueDictionary in my helper class, I'm forced with a more cumbersome syntax for my views, like this:

```<code><%:Html.SomeTag(Model.Id, new Dictionary<string, string>{ {"class", "myClass"}, {"title", "myTitle} }%>
</code>```

QUESTION: So, is there a way to re-write the helper class to get the simpler view syntax without using RouteValueDictionary, or is there a way to allow the use of RouteValueDictionary in a C# library project?

答:
What project target have you given your class? The only thing I can think of is that you have your project target set to .NET 3.5 Client Profile which doesn't support any web stuff.

UPDATE: Based on your comments, the final resolution was to add a reference to System.Web.dll to your project.

In .NET 4.0, the System.Web.Routing.dll is type-forwarded to System.Web.dll. This is because the functionality in System.Web.Routing.dll from .NET 3.5 was migrated to the core System.Web assembly. The System.Web.Routing.dll (v4.0) exists to satisfy type-forwarding (to maintain backwards compatibility when migrating projects).

When you add a reference to System.Web.Routing.dll to your .NET 4.0 project, you also need to add a reference to System.Web.dll.

Body:
I am trying to refactor a solution that includes 2 MVC projects: a "User-Experience" project and a corresponding "Content Management System project"

I have set up an independent  C# library -- "Services" -- project in the same solution space to do many things. I want to share Html extension methods used by both web projects by placing them in this "neutral" project so that there are no dependencies between the two MVC projects.

I have a problem with  using the RouteValueDictionary object (to.MergeAttributes) in this class library. I've included a reference to Sytem.Web.Routing in the Services project, but when I attempt to include a using statement at the top of the helper-class file, VStudio refuses to recognize the declaration ("Cannot resolve symbol 'Routing'").

This makes intuitive sense -- only a web project that can engage in URL routing should need a RouteValueDictionary.

But it appears common to use the RouteValueDictionary object inside htmlhelper classes because it can take an anonymous object consisting of name-value pairs and convert it to a Dictionary  in its constructor like this:

tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));

...thus providing a way of passing in any number of tag attribute name-value pairs into a tag and a relatively simple syntax for calling the helper in the view:

<%:Html.SomeTag(Model.Id, new {@class = "myClass", title = "myTitle"} %>

So if I  can't use the RouteValueDictionary in my helper class, I'm forced with a more cumbersome syntax for my views, like this:

<%:Html.SomeTag(Model.Id, new Dictionary<string, string>{ {"class", "myClass"}, {"title", "myTitle} }%>

QUESTION: So, is there a way to re-write the helper class to get the simpler view syntax without using RouteValueDictionary, or is there a way to allow the use of RouteValueDictionary in a C# library project?


问:
ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
Since im new in firebase, im having trouble with duplicated name already exists, and i need your help.

```<code>E/flutter (21802): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
E/flutter (21802): #0      MethodChannelFirebase.initializeApp
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:111
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #1      Firebase.initializeApp
package:firebase_core/src/firebase.dart:41
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #2      main
package:flutterbuyandsell/main.dart:47
E/flutter (21802): <asynchronous suspension>
E/flutter (21802):
</code>```

…/method_channel/method_channel_firebase.dart:111

package:firebase_core/src/firebase.dart:41

package:flutterbuyandsell/main.dart:47

答: if you make changes to your options while you run the app with flutter run -d chrome and you use just hot reload after you made your changes to the options, it tries to initialise a second app, which doesn't work. Just terminate your running session with ctrl+c and start a fresh session, the error will be gone.

Body:
Since im new in firebase, im having trouble with duplicated name already exists, and i need your help.

E/flutter (21802): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
E/flutter (21802): #0      MethodChannelFirebase.initializeApp
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:111
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #1      Firebase.initializeApp
package:firebase_core/src/firebase.dart:41
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #2      main
package:flutterbuyandsell/main.dart:47
E/flutter (21802): <asynchronous suspension>
E/flutter (21802):

…/method_channel/method_channel_firebase.dart:111

package:firebase_core/src/firebase.dart:41

package:flutterbuyandsell/main.dart:47


问:
exporting the data to an excel sheet after being filtered on the admin panel?
so, after i filter information, is there a way I can export that filtered list as an excel sheet? I would prefer to have a button that you can click in the admin page to just export all the info as an excel sheet that is visible currently in the panel.

If this is too confusing please ask more question, I would be happy to help you help me!

my list filters :

```<code>    list_filter = ('Class','Age',)
</code>```

答:
You can use this external library.

https://django-import-export.readthedocs.io/en/latest/

Export on excel the filtered view in admin site

Body:
so, after i filter information, is there a way I can export that filtered list as an excel sheet? I would prefer to have a button that you can click in the admin page to just export all the info as an excel sheet that is visible currently in the panel.

If this is too confusing please ask more question, I would be happy to help you help me!

my list filters :

    list_filter = ('Class','Age',)


问:
How to write a while loop until two outputs are the same ? [PYTHON]
I need to write a program that uses Newton's method to get an number's square root. Basically it needs to keep iterating until two consecutive values are the same. I think I am nearly there I just don't know what to put in the last part of the while loop.</p>
```<code>def SquareRoot(X):

    root = X
    print(X)

    while root != DONT KNOW :
        root = 0.5*(root+(X/root))
        print(root)

SquareRoot(64)
</code>```

答:
you can do:

```<code>def SquareRoot(X):

    root = X
    print(X)

    while root**2 != X :
        root = 0.5*(root+(X/root))
        print(root)
SquareRoot(64)
</code>```

but you can't do it for irrationals,

but to make it work you could round:

```<code>>>> def SquareRoot(X):
...     root = X
...     print(X)
...     while round(root**2,12) != X :
...         root = 0.5*(root+(X/root))
...         print(round(root,12))
...     return round(root,12)
...
>>> SquareRoot(2)
2
1.5
1.416666666667
1.414215686275
1.414213562375
1.414213562373
1.414213562373
</code>```

Body:
I need to write a program that uses Newton's method to get an number's square root. Basically it needs to keep iterating until two consecutive values are the same. I think I am nearly there I just don't know what to put in the last part of the while loop.

def SquareRoot(X):

    root = X
    print(X)

    while root != DONT KNOW :
        root = 0.5*(root+(X/root))
        print(root)

SquareRoot(64)

Body:
you can do:

def SquareRoot(X):

    root = X
    print(X)

    while root**2 != X :
        root = 0.5*(root+(X/root))
        print(root)
SquareRoot(64)

but you can't do it for irrationals,

but to make it work you could round:

>>> def SquareRoot(X):
...     root = X
...     print(X)
...     while round(root**2,12) != X :
...         root = 0.5*(root+(X/root))
...         print(round(root,12))
...     return round(root,12)
...
>>> SquareRoot(2)
2
1.5
1.416666666667
1.414215686275
1.414213562375
1.414213562373
1.414213562373


问:
Spread the amount to all rows when a condition is met
I have a dataset as below:

```<code>date          country       price       product
20210101       US              5        laptop
20210101       Italy          10        laptop
20210201       Australia      15        laptop
20210301       France         10        monitor
20210301       US             15        monitor
</code>```

What I would like to do is to add another column that always takes the original price of the US when product names are the same across all the countries. The desired output should be:

```<code>date          country       price       product       original_price
20210101       US              5        laptop             5
20210101       Italy          10        laptop             5
20210201       Australia      15        laptop             5
20210301       France         10        monitor            15
20210301       US             15        monitor            15
</code>```

I was thinking of using conditional logic such as below but it's not working:

```<code>COALESCE
(MAX(CASE WHEN country = 'US' THEN price END),
 MAX(CASE WHEN country != 'US' THEN price END))
</code>```

If anyone could give me a hint on a method or an approach to tackle this, it would be highly appreciated.

答:
For MySql 8.0+ you can use MAX() window function:

```<code>SELECT *,
       MAX(CASE WHEN country = 'US' THEN price END) OVER (PARTITION BY product) original_price
FROM tablename;
</code>```

For previous versions use a correlated subquery:

```<code>SELECT t1.*,
       (SELECT t2.price FROM tablename t2 WHERE t2.product = t1.product AND t2.country = 'US') original_price
FROM tablename t1;
</code>```

See the demo.

Body:
I have a dataset as below:

date          country       price       product
20210101       US              5        laptop
20210101       Italy          10        laptop
20210201       Australia      15        laptop
20210301       France         10        monitor
20210301       US             15        monitor

What I would like to do is to add another column that always takes the original price of the US when product names are the same across all the countries. The desired output should be:

date          country       price       product       original_price
20210101       US              5        laptop             5
20210101       Italy          10        laptop             5
20210201       Australia      15        laptop             5
20210301       France         10        monitor            15
20210301       US             15        monitor            15

I was thinking of using conditional logic such as below but it's not working:

COALESCE
(MAX(CASE WHEN country = 'US' THEN price END),
 MAX(CASE WHEN country != 'US' THEN price END))

If anyone could give me a hint on a method or an approach to tackle this, it would be highly appreciated.

Body:
For MySql 8.0+ you can use MAX() window function:

SELECT *,
       MAX(CASE WHEN country = 'US' THEN price END) OVER (PARTITION BY product) original_price
FROM tablename;

For previous versions use a correlated subquery:

SELECT t1.*,
       (SELECT t2.price FROM tablename t2 WHERE t2.product = t1.product AND t2.country = 'US') original_price
FROM tablename t1;

See the demo.


问:
How can I get the vk user id using kotlin?
I want to make a "share vk" button, for this I use an http request https://api.vk.com/method/wall.post . But it needs a user ID. How can I get it? Or is there another way to post on the vk wall?</p>

答: I think the easiest way to know how to get the parameter you need - is to ask their support</p>


问:
Selenium-chromedriver: Cannot construct KeyEvent from non-typeable key
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

```<code>....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....
</code>```

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

```<code>def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end
</code>```

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

答:
This is hopefully a temporary problem that will be solved in a later release
https://github.com/SeleniumHQ/selenium/issues/10318

A test macro using JS to fill in the field solved my needs (Ruby) for basic scenarios like

```<code>fill_in :user_email, with: user.email
</code>```

Test macro:

```<code>def fill_in_chrome98_tmp_fix(locator, with:)
  element = find(:fillable_field, locator)
  dom_id = element.native.dom_attribute("id")
  raise "No DOM ID" if dom_id.blank?
  page.execute_script("document.getElementById('#{dom_id}').value = '#{with}'")
end
</code>```

Body:
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

Body:
This is hopefully a temporary problem that will be solved in a later release
https://github.com/SeleniumHQ/selenium/issues/10318

A test macro using JS to fill in the field solved my needs (Ruby) for basic scenarios like

fill_in :user_email, with: user.email

Test macro:

def fill_in_chrome98_tmp_fix(locator, with:)
  element = find(:fillable_field, locator)
  dom_id = element.native.dom_attribute("id")
  raise "No DOM ID" if dom_id.blank?
  page.execute_script("document.getElementById('#{dom_id}').value = '#{with}'")
end


问:
How to open external app file in React Native
Using the package react-native-receive-sharing-intent, I receive this intent from the Obisidan app when a page is shared:

```<code>{
    "contentUri": "content://md.obsidian.fileprovider/my_images/Documents/Myoas/Hello%20obsidian.md",
    "fileName": "Hello obsidian.md",
    "filePath": "/data/user/0/com.xxxxxxx.xxxxxx/cache/Hello obsidian.md",
    "mimeType": "text/markdown",
    "subject": null,
    "text": null,
    "weblink": null
}
</code>```

Now my goal is to open programmatically the Obsidian app showing the same file.

I tried that but it is not working. This opens the web browser and gives an error:

```<code>import { Linking } from "react-native";
Linking.openURL("content://md.obsidian.fileprovider/my_images/Documents/Myoas/Hello%20obsidian.md");
</code>```

I don't want a copy of the file or open the markdown file in my app.

I want to open the original file in the external app.

答:
I find a solution here:</p>
```<code>Linking.openUrl("obsidian://action?param1=value&param2=value")
</code>```

Body:
Using the package react-native-receive-sharing-intent, I receive this intent from the Obisidan app when a page is shared:

{
    "contentUri": "content://md.obsidian.fileprovider/my_images/Documents/Myoas/Hello%20obsidian.md",
    "fileName": "Hello obsidian.md",
    "filePath": "/data/user/0/com.xxxxxxx.xxxxxx/cache/Hello obsidian.md",
    "mimeType": "text/markdown",
    "subject": null,
    "text": null,
    "weblink": null
}

Now my goal is to open programmatically the Obsidian app showing the same file.

I tried that but it is not working. This opens the web browser and gives an error:

import { Linking } from "react-native";
Linking.openURL("content://md.obsidian.fileprovider/my_images/Documents/Myoas/Hello%20obsidian.md");

I don't want a copy of the file or open the markdown file in my app.

I want to open the original file in the external app.

Body:
I find a solution here:

Linking.openUrl("obsidian://action?param1=value&param2=value")