问:
Error in solidity code: Return argument type bytes1 is not implicitly convertible to expected type
I have setter and getter:

```<code>    function setFunc(bytes calldata _value) public {
        getBytes = _value;
    }

function getFunc() public view returns(bytes calldata) {
        return getBytes;
    }
</code>```

When I run my code, the compiler shows that

```<code>TypeError: Return argument type bytes1 is not implicitly convertible to expected type (type of first return variable) bytes calldata.
  --> contracts/GetterSetter.sol:38:16:
   |
38 |         return getBytes[];
   |                ^^^^^^^^^^
</code>```

Before that I had another error:

```<code>TypeError: Data location must be "memory" or "calldata" for return parameter in function, but none was given.
  --> contracts/GetterSetter.sol:37:51:
   |
37 |     function requestedBytes() public view returns(bytes) {
   |                                                   ^^^^^
</code>```

Could you help to resolve it and what input example should I provide into setter for correct functions working?

I will be really appreciate for your help!

答:
Hm.. I tried in Remix and it looks like woks as it should, but when I run it with Hardhat, it returns Zero.</p>
```<code>    await getset.setBytes32('0x7465737400000000000000000000000000000000000000000000000000000000');

    const getBytes32 = await getset.requestedBytes32();
    console.log('Bytes32:', getBytes32);
</code>```

Body:
I have setter and getter:

    function setFunc(bytes calldata _value) public {
        getBytes = _value;
    }

function getFunc() public view returns(bytes calldata) {
        return getBytes;
    }

When I run my code, the compiler shows that

TypeError: Return argument type bytes1 is not implicitly convertible to expected type (type of first return variable) bytes calldata.
  --> contracts/GetterSetter.sol:38:16:
   |
38 |         return getBytes[];
   |                ^^^^^^^^^^

Before that I had another error:

TypeError: Data location must be "memory" or "calldata" for return parameter in function, but none was given.
  --> contracts/GetterSetter.sol:37:51:
   |
37 |     function requestedBytes() public view returns(bytes) {
   |                                                   ^^^^^

Could you help to resolve it and what input example should I provide into setter for correct functions working?

I will be really appreciate for your help!

Body:
Hm.. I tried in Remix and it looks like woks as it should, but when I run it with Hardhat, it returns Zero.

    await getset.setBytes32('0x7465737400000000000000000000000000000000000000000000000000000000');

    const getBytes32 = await getset.requestedBytes32();
    console.log('Bytes32:', getBytes32);


来源: stackexchange

问:
How to properly use require.js to require a node module?
So, I have no experience with Node or require.js. I know questions similar to this one have already been posted, but unfortunately, their solutions were no use in my case, sorry.

So all I'm trying to achieve here is to use the random-words Node module in my app (client-side). After I have installed it with npm install random-words, I am trying to use this:

```<code>var randomWords = require('random-words');
console.log(randomWords());
</code>```

but with no luck. I have been trying to get this to work for over 2 hours now, reading the documentation, watching tutorials, searching on Stack Overflow but I always get an error. Right now, I am getting this output/errors:

```<code>Require inside of index.html executed

    Uncaught ReferenceError: module is not defined
        at index.js:338
    (anonymous) @ index.js:338

    require.js:5 Uncaught Error: Module name "node_modules/random-words" has not been loaded yet for context: _. Use require([])
    https://requirejs.org/docs/errors.html#notloaded
        at makeError (require.js:5)
        at Object.s [as require] (require.js:5)
        at requirejs (require.js:5)
        at script.js:2
        at Object.execCb (require.js:5)
        at e.check (require.js:5)
        at e.<anonymous> (require.js:5)
        at require.js:5
        at require.js:5
        at each (require.js:5)
</code>```

Here is my directory structure:

```<code>My App
|-- js
|   |-- script.js
|   `-- node_modules
|       `-- random-words
|           |-- tests
|           |   `-- test.js
|           |-- index.js
|           `-- package.json
|-- config.js
|-- index.html
|-- package-lock.json
`-- require.js
</code>```

My code inside index.html:

```<code><script data-main='config' src='require.js'></script>
    <script>
    require(['config'], function(){
        require(['script']);
        console.log("Require inside of index.html executed");
    });
    </script>
</code>```

My code inside config.js:

```<code>requirejs.config({
    baseUrl: 'js',
    paths: {
        randomWords: 'node_modules/random-words/index'
    }
});
</code>```

My code inside script.js:

```<code>define(['randomWords'], function(){
                var randomWords = require('node_modules/random-words');
                console.log("Script.js code executed");
        });
</code>```

Thanks in advance for any response/advice, I am getting really desperate and will not be able to move on until I get this to work.

答:
I stumbled across the same problem, and found the answer here under the "Common Errors" section of requirejs.org:

This occurs when there is a require('name') call, but the 'name' module has not been loaded yet.
If the error message includes Use require([]), then it was a top-level require call (not a require call inside a define() call) that should be using the async, callback version of require to load the code

So instead of:

```<code>var randomWords = require('random-words');
console.log(randomWords());
</code>```

using:

```<code>var randomWords = require(['random-words'], function (random) {
    });
console.log(randomWords());
</code>```

fixed the issue for me.

ContentLicense: CC BY-SA 4.0

Body:
So, I have no experience with Node or require.js. I know questions similar to this one have already been posted, but unfortunately, their solutions were no use in my case, sorry.

So all I'm trying to achieve here is to use the random-words Node module in my app (client-side). After I have installed it with npm install random-words, I am trying to use this:

var randomWords = require('random-words');
console.log(randomWords());

but with no luck. I have been trying to get this to work for over 2 hours now, reading the documentation, watching tutorials, searching on Stack Overflow but I always get an error. Right now, I am getting this output/errors:

Require inside of index.html executed

    Uncaught ReferenceError: module is not defined
        at index.js:338
    (anonymous) @ index.js:338

    require.js:5 Uncaught Error: Module name "node_modules/random-words" has not been loaded yet for context: _. Use require([])
    https://requirejs.org/docs/errors.html#notloaded
        at makeError (require.js:5)
        at Object.s [as require] (require.js:5)
        at requirejs (require.js:5)
        at script.js:2
        at Object.execCb (require.js:5)
        at e.check (require.js:5)
        at e.<anonymous> (require.js:5)
        at require.js:5
        at require.js:5
        at each (require.js:5)

Here is my directory structure:

My App
|-- js
|   |-- script.js
|   `-- node_modules
|       `-- random-words
|           |-- tests
|           |   `-- test.js
|           |-- index.js
|           `-- package.json
|-- config.js
|-- index.html
|-- package-lock.json
`-- require.js

My code inside index.html:

My code inside config.js:

requirejs.config({
    baseUrl: 'js',
    paths: {
        randomWords: 'node_modules/random-words/index'
    }
});

My code inside script.js:

define(['randomWords'], function(){
                var randomWords = require('node_modules/random-words');
                console.log("Script.js code executed");
        });

Thanks in advance for any response/advice, I am getting really desperate and will not be able to move on until I get this to work.

Body:
I stumbled across the same problem, and found the answer here under the "Common Errors" section of requirejs.org:

This occurs when there is a require('name') call, but the 'name' module has not been loaded yet.
If the error message includes Use require([]), then it was a top-level require call (not a require call inside a define() call) that should be using the async, callback version of require to load the code

So instead of:

var randomWords = require('random-words');
console.log(randomWords());

using:

var randomWords = require(['random-words'], function (random) {
    });
console.log(randomWords());

fixed the issue for me.


问:
Is there any code in flutter to change the border color when a TextFormField has a value?
```<code>TextFormField(
                style: TextStyle(color: Colors.black),
                textAlign: TextAlign.center,
                controller: _HeightController,
                validator: (value) {
                  if (value!.trim().isEmpty) {
                    return 'enter some text';
                  } else {
                    return null;
                  }
                },
                decoration:InputDecoration(
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(
                      color: pro.backColor_main,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(

color: Color(0xffC2C2C2),
                  width: 2.0,
                ),
              ),
              hintText: '키를 입력해주세요',
              hintStyle: TextStyle(fontSize: 13.sp,
                color: Color(0xffA9A9A9),
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              fillColor: Colors.white,
              filled: true,
            ),
            keyboardType: TextInputType.number,
          ),
</code>```

This is my textformfield code.

Changing color when TextFormField is selected

Changing color when TextFormField is not selected

I understand that changing the color of the border of TextFormField itself.

But I want to keep the color of pro.main(blue) after a value is entered in TextFormField
This is because if you deselect the selection after entering a value, it becomes gray.

In this case, I wonder if there is a code to change the outline color if there is a value in the TextFormField.

答:
```<code>  class MyHomePage extends StatefulWidget {
    const MyHomePage({Key? key, required this.title}) : super(key: key);

    final String title;

    @override
    State<MyHomePage> createState() => _MyHomePageState();
  }

  class _MyHomePageState extends State<MyHomePage> {
    late TextEditingController _HeightController;
    @override
    void initState() {
      _HeightController  = TextEditingController();

    }

    @override
    void dispose() {
      _HeightController.dispose();
    }

    @override
    Widget build(BuildContext context) {

      return Scaffold(
        appBar: AppBar(

          title: Text(widget.title),
        ),
        body: Center(

          child: TextFormField(
            style: TextStyle(color: Colors.black),
            textAlign: TextAlign.center,
            controller: _HeightController,
            validator: (value) {
              if (value!.trim().isEmpty) {
                return 'enter some text';
              } else {
                return null;
              }
            },
            onChanged: (_){
              setState(() {
              });
            },
            decoration:InputDecoration(
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
                borderSide: BorderSide(
                  color: Colors.indigo,
                ),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
                borderSide: BorderSide(
                  color: _HeightController.value.text.isEmpty ? Color(0xffC2C2C2) : Colors.blueAccent,
                  width: _HeightController.value.text.isEmpty ? 2.0 : 3.0,
                ),
              ),
              hintText: '키를 입력해주세요',
              hintStyle: TextStyle(fontSize: 13,
                color: Color(0xffA9A9A9),
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),

              ),
               fillColor: Colors.white,
              filled: true,
            ),
            keyboardType: TextInputType.number,
          ),
        ),
      );
    }
  }
</code>```

when it's empty :

when it's not empty :

Body:
TextFormField(
                style: TextStyle(color: Colors.black),
                textAlign: TextAlign.center,
                controller: _HeightController,
                validator: (value) {
                  if (value!.trim().isEmpty) {
                    return 'enter some text';
                  } else {
                    return null;
                  }
                },
                decoration:InputDecoration(
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(
                      color: pro.backColor_main,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(

color: Color(0xffC2C2C2),
                  width: 2.0,
                ),
              ),
              hintText: '키를 입력해주세요',
              hintStyle: TextStyle(fontSize: 13.sp,
                color: Color(0xffA9A9A9),
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              fillColor: Colors.white,
              filled: true,
            ),
            keyboardType: TextInputType.number,
          ),

This is my textformfield code.

Changing color when TextFormField is selected

Changing color when TextFormField is not selected

I understand that changing the color of the border of TextFormField itself.

But I want to keep the color of pro.main(blue) after a value is entered in TextFormField
This is because if you deselect the selection after entering a value, it becomes gray.

In this case, I wonder if there is a code to change the outline color if there is a value in the TextFormField.

Body:
  class MyHomePage extends StatefulWidget {
    const MyHomePage({Key? key, required this.title}) : super(key: key);

    final String title;

    @override
    State<MyHomePage> createState() => _MyHomePageState();
  }

  class _MyHomePageState extends State<MyHomePage> {
    late TextEditingController _HeightController;
    @override
    void initState() {
      _HeightController  = TextEditingController();

    }

    @override
    void dispose() {
      _HeightController.dispose();
    }

    @override
    Widget build(BuildContext context) {

      return Scaffold(
        appBar: AppBar(

          title: Text(widget.title),
        ),
        body: Center(

          child: TextFormField(
            style: TextStyle(color: Colors.black),
            textAlign: TextAlign.center,
            controller: _HeightController,
            validator: (value) {
              if (value!.trim().isEmpty) {
                return 'enter some text';
              } else {
                return null;
              }
            },
            onChanged: (_){
              setState(() {
              });
            },
            decoration:InputDecoration(
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
                borderSide: BorderSide(
                  color: Colors.indigo,
                ),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
                borderSide: BorderSide(
                  color: _HeightController.value.text.isEmpty ? Color(0xffC2C2C2) : Colors.blueAccent,
                  width: _HeightController.value.text.isEmpty ? 2.0 : 3.0,
                ),
              ),
              hintText: '키를 입력해주세요',
              hintStyle: TextStyle(fontSize: 13,
                color: Color(0xffA9A9A9),
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),

              ),
               fillColor: Colors.white,
              filled: true,
            ),
            keyboardType: TextInputType.number,
          ),
        ),
      );
    }
  }

when it's empty :

when it's not empty :


问:
Get Private IP from ASG
I need to output private IP from Auto Scaling Group of EC2 instance that configuration by Terraform. How can i get private IP from ASG?

# Launch config for ASG
resource "aws_launch_configuration" "asg_conf" {
  name            = "ASG-Conf-${var.env}"
  image_id        = data.aws_ami.ubuntu.id                # Get image from data
  instance_type   = var.instance_type                     # use t2.micro ad default
  security_groups = [var.sg_app.id, var.sg_alb.id]        # SG for APP
  key_name        = var.ssh_key                           # SSH key for connection to EC2
  user_data       = file("./modules/ec2/shell/apache.sh") # install apache

  lifecycle {
    create_before_destroy = true
  }
}

# Auto Scaling Group
resource "aws_autoscaling_group" "asg" {
  count                = length(var.private_subnet_id) # count numbers of private subnets
  name                 = "ASG-${var.env}-${count.index + 1}"
  vpc_zone_identifier  = [var.private_subnet_id[count.index]]
  launch_configuration = aws_launch_configuration.asg_conf.name
  target_group_arns    = [var.alb_target.arn]

  min_size         = 1 # Min size of creating EC2
  max_size         = 1 # Max size of creating EC2

  health_check_grace_period = 120
  health_check_type         = "ELB"
  force_delete              = true

  lifecycle {
    create_before_destroy = true
  }

  tag {
    key                 = "Name"
    value               = "Webserver-ec2-${count.index + 1}"
    propagate_at_launch = true
  }
}

output {
  # How can i get this???
  value = aws_autoscaling_group.asg.private_ip
}```

My infrastructure create 1 EC2 instance in 2 private AZ by ASG and i need output IP from this ASG

答: You need custom data source to get the IPs. But this really does not make much sense as instances in ASG can be changed by AWS at any time, thus making your IPs obsolete.</p>

Title: Get Private IP from ASG

Body:
I need to output private IP from Auto Scaling Group of EC2 instance that configuration by Terraform. How can i get private IP from ASG?

# Launch config for ASG
resource "aws_launch_configuration" "asg_conf" {
  name            = "ASG-Conf-${var.env}"
  image_id        = data.aws_ami.ubuntu.id                # Get image from data
  instance_type   = var.instance_type                     # use t2.micro ad default
  security_groups = [var.sg_app.id, var.sg_alb.id]        # SG for APP
  key_name        = var.ssh_key                           # SSH key for connection to EC2
  user_data       = file("./modules/ec2/shell/apache.sh") # install apache

  lifecycle {
    create_before_destroy = true
  }
}

# Auto Scaling Group
resource "aws_autoscaling_group" "asg" {
  count                = length(var.private_subnet_id) # count numbers of private subnets
  name                 = "ASG-${var.env}-${count.index + 1}"
  vpc_zone_identifier  = [var.private_subnet_id[count.index]]
  launch_configuration = aws_launch_configuration.asg_conf.name
  target_group_arns    = [var.alb_target.arn]

  min_size         = 1 # Min size of creating EC2
  max_size         = 1 # Max size of creating EC2

  health_check_grace_period = 120
  health_check_type         = "ELB"
  force_delete              = true

  lifecycle {
    create_before_destroy = true
  }

  tag {
    key                 = "Name"
    value               = "Webserver-ec2-${count.index + 1}"
    propagate_at_launch = true
  }
}

output {
  # How can i get this???
  value = aws_autoscaling_group.asg.private_ip
}

My infrastructure create 1 EC2 instance in 2 private AZ by ASG and i need output IP from this ASG


问:
Converting a list of strings into a nested list of floats and strings skipping the first item
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats.
I've tried to use the append method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my output as the result? This is my code:

```<code>def func(L):
    n = []
    lists = [i.split(',') for i in L]
    for xlist in lists:
        xlist[1:] = [float(item) for item in xlist[1:]]
        n.append(xlist)
        print(n)

if __name__ == '__main__':
    func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38'])

OUTPUT: [['PersonX', 10.0, 92.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]

EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]
</code>```

Thanks in advance for any help.

答:
Just unindent the print outside of the loop to only perform the operation once at the end:

```<code>def func(L):
    n = []
    lists = [i.split(',') for i in L]
    for xlist in lists:
        xlist[1:] = [float(item) for item in xlist[1:]]
        n.append(xlist)
    print(n)
</code>```

Note however that by using print, you don't really output a list with integers. You should rather use return n

Body:
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats.
I've tried to use the append method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my output as the result? This is my code:

def func(L):
    n = []
    lists = [i.split(',') for i in L]
    for xlist in lists:
        xlist[1:] = [float(item) for item in xlist[1:]]
        n.append(xlist)
        print(n)

if __name__ == '__main__':
    func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38'])

OUTPUT: [['PersonX', 10.0, 92.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]

EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]

Thanks in advance for any help.

Body:
Just unindent the print outside of the loop to only perform the operation once at the end:

def func(L):
    n = []
    lists = [i.split(',') for i in L]
    for xlist in lists:
        xlist[1:] = [float(item) for item in xlist[1:]]
        n.append(xlist)
    print(n)

Note however that by using print, you don't really output a list with integers. You should rather use return n


问:
Inherited frames - missing properties
I have a project which consists of numerous different frames. Some of those frames are inherited from each other. Here's the basic setup:

TBaseFrame

TFrame1

TFrame1A

TFrame1B

TFrame2

TFrame2A

...and so on.

Everything was working fine and dandy. I've been able to compile and run my project with this setup all day long. However, at some point, it started completely failing and crashing.

On application startup, shortly after the main screen shows, I receive this error:

Oddly, nothing in my application is even creating or using any of those frames yet - the frames are on a form which is explicitly created only after login (and I confirmed it's not on auto-create).

Once I press OK, my application terminates, and then shows this error:

After some digging, I discovered something very odd in the IDE. I closed Delphi and re-opened it, and I'm still seeing this discrepancy.

On the base frame (TBaseFrame), it does not show any ClientWidth or ClientHeight properties:

However the inherited frame (TFrame1) does:

It seems as if the inherited frame is being treated as if it's a form, especially seeing a Caption property there which shouldn't belong.

Why did this happen and how do I fix it?

EDIT

To add, when I go to my project options, it's offering me to add many of the frames to auto-create, which should not be possible. And in fact one of the frames (the most recently created one) is already set to auto-create. But it's a frame, not a form.

EDIT 2

After finding and removing the 1 frame from the project's auto-create, as well as removing another (unrelated) frame which had class name conflicts and re-adding it to the project, now I'm able to at least compile the project and run it. Yet still numerous frames appear as if they're forms.

答:
You are experiencing a problem with the IDE designer of some Delphi versions where it forgets about an inherited frame being a frame.

To fix this, open the project source and add a ": TFrame" after the component name of the affected frame. Save, close and reopen the project.

This is an example how it should look like:

```<code> MyFrame1 in 'MyFrame1.pas' {Frame1: TFrame};
</code>```

Title: Inherited frames - missing properties

Body:
You are experiencing a problem with the IDE designer of some Delphi versions where it forgets about an inherited frame being a frame.

To fix this, open the project source and add a ": TFrame" after the component name of the affected frame. Save, close and reopen the project.

This is an example how it should look like:

 MyFrame1 in 'MyFrame1.pas' {Frame1: TFrame};


问:
Plotting histogram for categorical values
I am using seaborn and I want to plot only categorical values (sex,smoker,day,time,size) with facet histogram (total 5 histogram on same place).

```<code>    import seaborn as sns
    tips = sns.load_dataset("tips")
    tips

    # Plotting
    g = sns.FacetGrid(tips, col="sex",  row="smoker")
    g.map_dataframe(sns.histplot, x="time")
</code>```

I try with this line of code but this doesn't give me the results I expected. So can anybody help me with how to solve this problem?

答:
Maybe you can create subplots via matplotlib and fill them with the histograms?

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns

tips = sns.load_dataset("tips")
columns = ['sex', 'smoker', 'day', 'time', 'size']
sns.set()
fig, axs = plt.subplots(ncols=len(columns), figsize=(15, 5))
for ax, column in zip(axs, columns):
    sns.histplot(tips[column], discrete=True, ax=ax)
    ax.xaxis.set_major_locator(MultipleLocator(1))  # set ticks at each position
    if ax != axs[0]:
        ax.set_ylabel('')
plt.tight_layout()
plt.show()
```

Body:
I am using seaborn and I want to plot only categorical values (sex,smoker,day,time,size) with facet histogram (total 5 histogram on same place).

    import seaborn as sns
    tips = sns.load_dataset("tips")
    tips

    # Plotting
    g = sns.FacetGrid(tips, col="sex",  row="smoker")
    g.map_dataframe(sns.histplot, x="time")

I try with this line of code but this doesn't give me the results I expected. So can anybody help me with how to solve this problem?


问:
align div horizontally after screen resize using css
I'm trying to align div horizontally as the browser resizes, currently, I have 3 divs. As per the requirement, I can add an additional div. My problem is as soon I increase the window size above 2500, the right side of the screen becomes empty & all the divs are floating to left. As I cannot set the div width to 30-33% as per the requirement. Below is my code. kindly help.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  float: left;
  display: flex;
  width: 100%
}

div.box {
  float: left;
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 30%;
  border: 1px solid #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">

  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div></code>```

答:
As @Arman Ebrahimi had already mentioned correctly. Use flex box only. The issue of responsibility can be handled well with media queries.

Working example

* {
  box-sizing: border-box;
}

div.box-container {
  display: flex;
  flex-wrap: wrap;
  font-size: 30px;
  text-align: center;
  gap: 10px;
  width: 80%;
  margin: 0 auto;
  /* or use justify-content: center; */
}

.box {
  background-color: #f1f1f1;
  padding: 10px;
  flex: 30%;
  border: 1px solid #cccccc;
  word-break: break-word;
  height: 326px;
}

@media (max-width: 800px) {
  .box {
    flex: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>

  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
</div></code>```

Body:
I'm trying to align div horizontally as the browser resizes, currently, I have 3 divs. As per the requirement, I can add an additional div. My problem is as soon I increase the window size above 2500, the right side of the screen becomes empty & all the divs are floating to left. As I cannot set the div width to 30-33% as per the requirement. Below is my code. kindly help.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  float: left;
  display: flex;
  width: 100%
}

div.box {
  float: left;
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 30%;
  border: 1px solid #cccccc;
}

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

Body:
As @Arman Ebrahimi had already mentioned correctly. Use flex box only. The issue of responsibility can be handled well with media queries.

Working example

* {
  box-sizing: border-box;
}

div.box-container {
  display: flex;
  flex-wrap: wrap;
  font-size: 30px;
  text-align: center;
  gap: 10px;
  width: 80%;
  margin: 0 auto;
  /* or use justify-content: center; */
}

.box {
  background-color: #f1f1f1;
  padding: 10px;
  flex: 30%;
  border: 1px solid #cccccc;
  word-break: break-word;
  height: 326px;
}

@media (max-width: 800px) {
  .box {
    flex: 100%;
  }
}

<div class="box-container">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>

  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
</div>


问:
Why will my physics 2D raycast not display or work correctly?
Basically i wanted to make a raycast for jumping but for some reason the distance of the raycast is wrong and never changes and the position of it is so wrong i cant even seem to find it:

```<code>    ray2D = Physics2D.Raycast(transform.position, -Vector2.up, .1f, GroundedLayers);
    Debug.Log(ray2D.distance);
    isGrounded = groundCheck();
</code>```

Grounded layers do not include the player, distance always returns as 0, grounded is always false and the gizmos line only draws when i open the prefab and not at all in the scene:

here the distance is set to .1f but displays the same as 1f

(EDIT: ok so i checked and for some reason the raycast happens around 0, -1 even tho thats nowhere near the player transform?)

答:
Try Vector2.down instead?

Alternative things to try:

Is the player in the scene the same as the prefab?
Increase the distance.
Add a new GameObject at the feet of the player, reference that in your script and call the Raycast from there.
Is ray2d a RayCastHit2d?
Are your ground object tags correct, including all grammer/caps?
Try outputting in debug, ray2d.collider.name to see what you're actually hitting.
If you're using a rigid body, try rigidbody2d. position instead of transform.position

Do you have the player selected in the hierarchy? This is needed to see the gizmos.

Body:
Basically i wanted to make a raycast for jumping but for some reason the distance of the raycast is wrong and never changes and the position of it is so wrong i cant even seem to find it:

    ray2D = Physics2D.Raycast(transform.position, -Vector2.up, .1f, GroundedLayers);
    Debug.Log(ray2D.distance);
    isGrounded = groundCheck();

Grounded layers do not include the player, distance always returns as 0, grounded is always false and the gizmos line only draws when i open the prefab and not at all in the scene:

here the distance is set to .1f but displays the same as 1f

(EDIT: ok so i checked and for some reason the raycast happens around 0, -1 even tho thats nowhere near the player transform?)


问:
How can I optimize this function to find statistical mode in vector-like container with billions of elements
I have a very slow and hefty function to find statistical mode (including multiple modes) which is working but unusably slow.

The requirements are as follows.

Must take an std::vector-like container by reference

Returns an std::vector of std::pair with the 'first' being the statistical mode and the 'second' being the number of occurrences (the number of occurrences must be identical for every statistical mode found or there is a bug (not currently verifying this)

Must be able to find all statistical modes in a container

4. Must be able to operate on containers billions of elements long and run in a reasonable amount of time

That last one is the one I'm having trouble with. Currently my code takes about 7 seconds to run on std::vectors containing only 1,000,000 elements.

Thus computing the mode(s) for a container of 1 billion elements would take about 2.38 hours. Ideally this code would run in under 1 minute.

How can I optimize this, I know std::unordered set is kind of expensive but I don't know how to implement this function without a set-like container using an array or vector.

```<code> template<typename CONTAINER_T, typename T = CONTAINER_T::value_type>
    [[nodiscard]] inline constexpr std::vector<std::pair<T, size_t>> mode(CONTAINER_T& arr)
    {
        std::unordered_set<T> seen;

        size_t max_count = 0;
        std::vector<std::pair<T, size_t>> ret;

        for (auto i = arr.begin(); i != arr.end(); ++i)
        {
            if (*std::find(std::execution::par_unseq, seen.cbegin(), seen.cend(), *i) == *seen.cend())
            {
                const size_t count = std::count(std::execution::par_unseq, i, arr.end(), *i);

                if (count > max_count)
                {
                    max_count = count;
                    ret = { {*i, max_count} };
                }//End if
                else if (count == max_count)
                {
                    ret.emplace_back(*i, max_count);
                }//End if
                seen.insert(*i);
            }//End if
        }//End for

        return ret;
    }//End of mode
</code>```

答:
Something along these lines perhaps:</p>
```<code>template<typename CONTAINER_T, typename T = CONTAINER_T::value_type>
std::vector<std::pair<T, size_t>> mode(CONTAINER_T& arr) {
  size_t max_count = 0;
  std::unodered_map<T, size_t> counts;
  for (auto& elem : arr) {
    size_t count = ++counts[elem];
    max_count = std::max(max_count, count);
  }
  std::vector<std::pair<T, size_t>> result;
  for (auto& pair : counts) {
    if (pair.second == max_count) {
      result.push_back(pair);
    }
  }
  return result;
}
</code>```

Body:
I have a very slow and hefty function to find statistical mode (including multiple modes) which is working but unusably slow.

The requirements are as follows.

Must take an std::vector-like container by reference

Returns an std::vector of std::pair with the 'first' being the statistical mode and the 'second' being the number of occurrences (the number of occurrences must be identical for every statistical mode found or there is a bug (not currently verifying this)

Must be able to find all statistical modes in a container

4. Must be able to operate on containers billions of elements long and run in a reasonable amount of time

That last one is the one I'm having trouble with. Currently my code takes about 7 seconds to run on std::vectors containing only 1,000,000 elements.

Thus computing the mode(s) for a container of 1 billion elements would take about 2.38 hours. Ideally this code would run in under 1 minute.

How can I optimize this, I know std::unordered set is kind of expensive but I don't know how to implement this function without a set-like container using an array or vector.

 template<typename CONTAINER_T, typename T = CONTAINER_T::value_type>
    [[nodiscard]] inline constexpr std::vector<std::pair<T, size_t>> mode(CONTAINER_T& arr)
    {
        std::unordered_set<T> seen;

        size_t max_count = 0;
        std::vector<std::pair<T, size_t>> ret;

        for (auto i = arr.begin(); i != arr.end(); ++i)
        {
            if (*std::find(std::execution::par_unseq, seen.cbegin(), seen.cend(), *i) == *seen.cend())
            {
                const size_t count = std::count(std::execution::par_unseq, i, arr.end(), *i);

                if (count > max_count)
                {
                    max_count = count;
                    ret = { {*i, max_count} };
                }//End if
                else if (count == max_count)
                {
                    ret.emplace_back(*i, max_count);
                }//End if
                seen.insert(*i);
            }//End if
        }//End for

        return ret;
    }//End of mode

Body:
Something along these lines perhaps:

template<typename CONTAINER_T, typename T = CONTAINER_T::value_type>
std::vector<std::pair<T, size_t>> mode(CONTAINER_T& arr) {
  size_t max_count = 0;
  std::unodered_map<T, size_t> counts;
  for (auto& elem : arr) {
    size_t count = ++counts[elem];
    max_count = std::max(max_count, count);
  }
  std::vector<std::pair<T, size_t>> result;
  for (auto& pair : counts) {
    if (pair.second == max_count) {
      result.push_back(pair);
    }
  }
  return result;
}


问:
Getting the second nearest [x,y] point using KNN algorithm
I am trying to find the nearest points on an x,y plane within given radius using kd trees. I mapped all the points in the tree, but the problem arise since the points I am providing to the algorithm to search for the nearest point are themself mapped in the tree. In other words, I'm getting the same point in return so the distance is basically 0. So I should be looking for the second nearest point I guess. The way I thought it might be achievable was doing the same thing but getting the result that was worst than the best_result but better than the root. I have been trying to implement this but have been unsuccessful so far. I did this with nested for loops its way easier with for loops to get the second-best result.

here's my kd tree implementation:

```<code>def kdtree(points, depth = 0 ):
    n = len(points)
    if n<=0:
        return None
    axis = depth % k
    sorted_points = sorted(points, key = lambda point: point[axis])

    if n % 2 == 0:
        median_idx = int(n/2)
    else:
        median_idx = floor(n/2)
    return{
        'point': sorted_points[median_idx],
        'left': kdtree(sorted_points[:median_idx], depth+1),
        'right': kdtree(sorted_points[median_idx+1:], depth+1)
    }
</code>```

Here is my function for searching the nearest point

```<code>kd_nearest_search (root, point, depth = 0):
    if root is None:
            return None
        axis = depth % k
        apposite_branch = None

        if point[axis] < root['point'][axis]:
            next_branch = root['left']
            opposite_branch = root['right']
        else:
            next_branch = root['right']
        opposite_branch = root['left']

    best_result = best_distance(point,kdtree_closest_point(next_branch,point,depth+1), root['point'])

    if distance(point,best_result) > (abs(point[axis] - root['point'][axis])):
        best_result = best_distance(point,kdtree_closest_point(next_branch,point,depth+1), best_result)

    return best_result
</code>```

答:
I don't know your kd implementation.  But I'll give you the basic idea.

Create tuples of (min_possible_distance, type, object) where the distance is the minimum possible distance to your searched for point the type can be either "box" or "point", and the object is whatever the thing is.

Put those tuples into a heap.

And now, in pseudocode, you do this:

```<code>place (0, "box", root_of_tree) into new heap
while heap is not empty:
    (distance, type, obj) = pop minimal element from heap.
    if type == "point":
        yield obj
    else:
       if obj has a point:
           store (distance, "point", point) in heap
       for child_box from obj:
           store (min_distance", "box", child_box) in heap
</code>```

This will yield points in the kd tree, from closest to farthest.  So you can just search until you find the second one.  But alternately you could ask for the 10 nearest and it would give you that instead.

Body:
I am trying to find the nearest points on an x,y plane within given radius using kd trees. I mapped all the points in the tree, but the problem arise since the points I am providing to the algorithm to search for the nearest point are themself mapped in the tree. In other words, I'm getting the same point in return so the distance is basically 0. So I should be looking for the second nearest point I guess. The way I thought it might be achievable was doing the same thing but getting the result that was worst than the best_result but better than the root. I have been trying to implement this but have been unsuccessful so far. I did this with nested for loops its way easier with for loops to get the second-best result.

here's my kd tree implementation:

def kdtree(points, depth = 0 ):
    n = len(points)
    if n<=0:
        return None
    axis = depth % k
    sorted_points = sorted(points, key = lambda point: point[axis])

    if n % 2 == 0:
        median_idx = int(n/2)
    else:
        median_idx = floor(n/2)
    return{
        'point': sorted_points[median_idx],
        'left': kdtree(sorted_points[:median_idx], depth+1),
        'right': kdtree(sorted_points[median_idx+1:], depth+1)
    }

Here is my function for searching the nearest point

kd_nearest_search (root, point, depth = 0):
    if root is None:
            return None
        axis = depth % k
        apposite_branch = None

        if point[axis] < root['point'][axis]:
            next_branch = root['left']
            opposite_branch = root['right']
        else:
            next_branch = root['right']
        opposite_branch = root['left']

    best_result = best_distance(point,kdtree_closest_point(next_branch,point,depth+1), root['point'])

    if distance(point,best_result) > (abs(point[axis] - root['point'][axis])):
        best_result = best_distance(point,kdtree_closest_point(next_branch,point,depth+1), best_result)

    return best_result

Body:
I don't know your kd implementation.  But I'll give you the basic idea.

Create tuples of (min_possible_distance, type, object) where the distance is the minimum possible distance to your searched for point the type can be either "box" or "point", and the object is whatever the thing is.

Put those tuples into a heap.

And now, in pseudocode, you do this:

place (0, "box", root_of_tree) into new heap
while heap is not empty:
    (distance, type, obj) = pop minimal element from heap.
    if type == "point":
        yield obj
    else:
       if obj has a point:
           store (distance, "point", point) in heap
       for child_box from obj:
           store (min_distance", "box", child_box) in heap

This will yield points in the kd tree, from closest to farthest.  So you can just search until you find the second one.  But alternately you could ask for the 10 nearest and it would give you that instead.


问:
How to convert an r datafile to csv without using R?
I am facing a weird task. I need to convert a datafile, which is in R to a csv file by using an automated vba script or a batch job. Installing R studio or a plug in for excel is not allowed due to compliance issues. Is this possible to do this conversion using a vba script and if yes, how? Thanks a lot!</p>

答:
As commented, R is an open source, programming language that is independent of any IDE like RStudio. Its installation includes terminal shells and command line tools such as Rscript.exe. VBA can run external command line using Shell or Windows Script Host. R can even receive arguments from the command caller!

R (receiving arguments)

args <- commandArgs(trailingOnly=TRUE)   # RECEIVE ALL COMMAND LINE ARGS

var1 <- args[1]
var2 <- args[2]

cat(paste(
    "Hi! This line is from R and received",
    var1, "and", var2, "from command line \n"
))
```
<p><strong>Cmd/PowerShell/Bash/etc.</strong> <em>(sending arguments)</em></p>
```# if R bin folder is in PATH environment variable
Rscript "C:\path\to\my_script.R" "Stack" "Overflow"

# if R bin folder is not in PATH environment variable
C:\path\to\R\bin\Rscript "C:\path\to\my_script.R" "Stack" "Overflow"
```
<p><strong>VBA</strong> <em>(replicating command line above)</em></p>
<pre class="lang-vb prettyprint-override"><code>Sub Run_RScript()
    Dim oShell As Object
    Dim var1 As String, var2 As String
    Dim Rcmd As String, output As String

    var1 = "" & "Stack" & ""       ' STRINGS REQUIRE DOUBLE QUOTES
    var2 = "" & "Overflow" & ""    ' STRINGS REQUIRE DOUBLE QUOTES

    Set oShell = CreateObject("WScript.Shell")
    Rcmd = "Rscript C:\path\to\myScript.R " & var1 & " " & var2
    output = oShell.Exec(Rcmd).StdOut.ReadAll

    Debug.Print output             ' PRINT TO IMMEDIATE WINDOW (CTRL+G)

    Set oShell = Nothing
End Sub
</code>```

Immediate Window (Ctrl+G)

Hi! This line is from R and received variables ( Stack and Overflow ) from command line
```

Body:
As commented, R is an open source, programming language that is independent of any IDE like RStudio. Its installation includes terminal shells and command line tools such as Rscript.exe. VBA can run external command line using Shell or Windows Script Host. R can even receive arguments from the command caller!

R (receiving arguments)

args <- commandArgs(trailingOnly=TRUE)   # RECEIVE ALL COMMAND LINE ARGS

var1 <- args[1]
var2 <- args[2]

cat(paste(
    "Hi! This line is from R and received",
    var1, "and", var2, "from command line \n"
))

Cmd/PowerShell/Bash/etc. (sending arguments)

# if R bin folder is in PATH environment variable
Rscript "C:\path\to\my_script.R" "Stack" "Overflow"

# if R bin folder is not in PATH environment variable
C:\path\to\R\bin\Rscript "C:\path\to\my_script.R" "Stack" "Overflow"

VBA (replicating command line above)

Sub Run_RScript()
    Dim oShell As Object
    Dim var1 As String, var2 As String
    Dim Rcmd As String, output As String

    var1 = "" & "Stack" & ""       ' STRINGS REQUIRE DOUBLE QUOTES
    var2 = "" & "Overflow" & ""    ' STRINGS REQUIRE DOUBLE QUOTES

    Set oShell = CreateObject("WScript.Shell")
    Rcmd = "Rscript C:\path\to\myScript.R " & var1 & " " & var2
    output = oShell.Exec(Rcmd).StdOut.ReadAll

    Debug.Print output             ' PRINT TO IMMEDIATE WINDOW (CTRL+G)

    Set oShell = Nothing
End Sub

Immediate Window (Ctrl+G)

Hi! This line is from R and received variables ( Stack and Overflow ) from command line


问:
Can't add rows to grouped data frames
This is a follow-up question of this How to add a row to a dataframe modifying only some columns.

After solving this question I wanted to apply the solution provided by stefan to a larger dataframe with group_by:

My dataframe:

```<code>df <- structure(list(test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1,
1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B",
"C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1)), class = "data.frame", row.names = c(NA,
-8L))

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
5       1       2      A          4
6       1       2      B          2
7       1       2      C          4
8       1       2      D          1

</code>```

I now want to add a new row to each group with this code, which gives an error:

```<code>df %>%
  group_by(test_nr) %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))

Error: Can't add rows to grouped data frames.
Run `rlang::last_error()` to see where the error occurred.

</code>```

My expected output would be:

```<code>   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75
</code>```

I have tried so far:

```<code>library(tidyverse)

df %>%
  group_by(test_nr) %>%
  group_split() %>%
  map_dfr(~ .x %>%
            add_row(!!! map(.[4], mean)))

   test_id test_nr region test_value
     <dbl>   <dbl> <chr>       <dbl>
 1       1       1 A            3
 2       1       1 B            1
 3       1       1 C            1
 4       1       1 D            2
 5      NA      NA NA           1.75
 6       1       2 A            4
 7       1       2 B            2
 8       1       2 C            4
 9       1       2 D            1
10      NA      NA NA           2.75

</code>```

How could I modify column 1 to 3 to place my values there?

答:
You can combine your two approaches:</p>
```<code>    df %>%
      split(~test_nr) %>%
      map_dfr(~ .x %>%
                add_row(test_id = .$test_id[1],
                        test_nr = .$test_nr[1],
                        region = "mean",
                        test_value = mean(.$test_value)))
</code>```

Title: Can't add rows to grouped data frames

Body:
This is a follow-up question of this How to add a row to a dataframe modifying only some columns.

After solving this question I wanted to apply the solution provided by stefan to a larger dataframe with group_by:

My dataframe:

df <- structure(list(test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1,
1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B",
"C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1)), class = "data.frame", row.names = c(NA,
-8L))

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
5       1       2      A          4
6       1       2      B          2
7       1       2      C          4
8       1       2      D          1

I now want to add a new row to each group with this code, which gives an error:

df %>%
  group_by(test_nr) %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))

Error: Can't add rows to grouped data frames.
Run `rlang::last_error()` to see where the error occurred.

My expected output would be:

   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75

I have tried so far:

library(tidyverse)

df %>%
  group_by(test_nr) %>%
  group_split() %>%
  map_dfr(~ .x %>%
            add_row(!!! map(.[4], mean)))

   test_id test_nr region test_value
     <dbl>   <dbl> <chr>       <dbl>
 1       1       1 A            3
 2       1       1 B            1
 3       1       1 C            1
 4       1       1 D            2
 5      NA      NA NA           1.75
 6       1       2 A            4
 7       1       2 B            2
 8       1       2 C            4
 9       1       2 D            1
10      NA      NA NA           2.75

How could I modify column 1 to 3 to place my values there?

Body:
You can combine your two approaches:

    df %>%
      split(~test_nr) %>%
      map_dfr(~ .x %>%
                add_row(test_id = .$test_id[1],
                        test_nr = .$test_nr[1],
                        region = "mean",
                        test_value = mean(.$test_value)))


问:
How to disable an Entry on tkinter when a Checkbutton is unchecked using for loop and dictionary
I'm working on a Windows application for my work and my knowledge on Python is very limited, so I didn't know how to figure this out :

I want to make each entry widget inside the frame disabled when its checkbutton is unchecked and enabled when its checkbutton is checked and make them all checked by default.
I tried this code that I took part of it from this tutorial but it didn't work as expected.

```<code>from tkinter import *

class Principal():
    def __init__(self):
        self.root= Tk()
        self.root.geometry('800x800')

        self.prixArticlesFrame = LabelFrame(self.root, text="Prix des articles", width=2000)
        self.prixArticlesFrame.place(relx = 0.75, rely = 0.15,anchor = N)

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(),
            "Remblai" : IntVar(),
            "Blocage" : IntVar(),
            "Beton de propreté": IntVar(),
            "Beton armé": IntVar(),
            "Acier à haute adherence": IntVar(),
            "Joint de dilatation": IntVar(),

        }
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            self.cur_check = Checkbutton(self.prixArticlesFrame,
            text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1,
            offvalue=0,command=self.ArticlesEntryState)
            self.cur_check.grid(row=index, column=0, padx=10, pady=10, sticky="W")

        self.DefautArticlesEntries={
            "Deblai" : StringVar(),
            "Remblai" : StringVar(),
            "Blocage" : StringVar(),
            "Beton de propreté": StringVar(),
            "Beton armé": StringVar(),
            "Acier à haute adherence": StringVar(),
            "Joint de dilatation": StringVar(),

        }

        for index, (key, value) in enumerate(self.DefautArticlesEntries.items()):
            self.cur_entry = 'DefautArticlesEntries' +key

            self.cur_entry=Entry(self.prixArticlesFrame,width=10,
                          textvariable=self.DefautArticlesEntries[key])
            self.cur_entry.grid(row=index,column=2,padx=10)
            self.cur_entry.config(state=NORMAL)
        self.root.mainloop()

    def ArticlesEntryState(self):
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):

            if self.DefautArticlesCheckButton[key].get() == 1:
                self.cur_entry.grid(row=index,column=2,padx=10)
                self.cur_entry.config(state=NORMAL)

            elif self.DefautArticlesCheckButton[key].get() == 0:
                self.cur_entry.config(state=DISABLED)

app = Principal()
</code>```

here is what I got in gif image

What I have done wrong?
Thanks

答:
Since you want all buttons checked by default, all variables should have an initial value that matches their onvalue.

Besides, both dicts refer to the variables rather than the actual widgets, so each Entry must be bound to the scope of the corresponding IntVar trace callback - otherwise, only the last loop item is referenced:

        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            value.set(1)
            check = Checkbutton(self.prixArticlesFrame, text=key, variable=value)
            check.grid(row=index, column=0, padx=10, pady=10, sticky="W")

        # ...

        for index, (key, value) in enumerate(self.DefautArticlesEntries.items()):
            entry = Entry(self.prixArticlesFrame, width=10, textvariable=value)
            entry.grid(row=index, column=1, padx=10)

            var = self.DefautArticlesCheckButton[key]
            handler = lambda *_, e=entry, v=var: e.config(state=NORMAL if v.get() else DISABLED)
            var.trace('w', handler)
```

Body:
I'm working on a Windows application for my work and my knowledge on Python is very limited, so I didn't know how to figure this out :

I want to make each entry widget inside the frame disabled when its checkbutton is unchecked and enabled when its checkbutton is checked and make them all checked by default.
I tried this code that I took part of it from this tutorial but it didn't work as expected.

from tkinter import *

class Principal():
    def __init__(self):
        self.root= Tk()
        self.root.geometry('800x800')

        self.prixArticlesFrame = LabelFrame(self.root, text="Prix des articles", width=2000)
        self.prixArticlesFrame.place(relx = 0.75, rely = 0.15,anchor = N)

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(),
            "Remblai" : IntVar(),
            "Blocage" : IntVar(),
            "Beton de propreté": IntVar(),
            "Beton armé": IntVar(),
            "Acier à haute adherence": IntVar(),
            "Joint de dilatation": IntVar(),

        }
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            self.cur_check = Checkbutton(self.prixArticlesFrame,
            text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1,
            offvalue=0,command=self.ArticlesEntryState)
            self.cur_check.grid(row=index, column=0, padx=10, pady=10, sticky="W")

        self.DefautArticlesEntries={
            "Deblai" : StringVar(),
            "Remblai" : StringVar(),
            "Blocage" : StringVar(),
            "Beton de propreté": StringVar(),
            "Beton armé": StringVar(),
            "Acier à haute adherence": StringVar(),
            "Joint de dilatation": StringVar(),

        }

        for index, (key, value) in enumerate(self.DefautArticlesEntries.items()):
            self.cur_entry = 'DefautArticlesEntries' +key

            self.cur_entry=Entry(self.prixArticlesFrame,width=10,
                          textvariable=self.DefautArticlesEntries[key])
            self.cur_entry.grid(row=index,column=2,padx=10)
            self.cur_entry.config(state=NORMAL)
        self.root.mainloop()

    def ArticlesEntryState(self):
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):

            if self.DefautArticlesCheckButton[key].get() == 1:
                self.cur_entry.grid(row=index,column=2,padx=10)
                self.cur_entry.config(state=NORMAL)

            elif self.DefautArticlesCheckButton[key].get() == 0:
                self.cur_entry.config(state=DISABLED)

app = Principal()

here is what I got in gif image

What I have done wrong?
Thanks


问:
selenium grid on docker sizing for maximum stability
We are having trouble upgrading to selenium 4.

The features and performance of selenium 4 look amazing, but we are having trouble getting our pipeline stable and consistently green.

We need some advice to help us fix some of the infrastructure issues we are seeing.

We are getting lots of org.openqa.selenium.NoSuchSessionException: invalid session id errors, and they are not consistant.  We are also getting other session runtime exceptions.

We are testing our own website, which is on the internet, using selenium.  We use selenium to click on buttons and fill out forms and stuff, via chromedriver in tests written in kotlin. Running these tests on a selenium 4.1.2 grid is basically broken for us.

We have a couple hundred selenium tests.  We want them to complete as quickly as possible, so we are trying to balance our base hardware with the maximum throughput of "UI actions".

We are running our selenium 4 grid on a feature branch on our build agents, which are TeamCity build agents on c5.4xlarge instances; each build has its own grid in its own docker network. Our grid's docker images are installed on our agents at runtime as part of starting our build.

We are invoking our build via gradle and testng, eg:

```<code>
test {
    systemProperties System.getProperties()
    useTestNG {
        suites 'src/test/resources/selenium-' + suite + '.xml'
        preserveOrder true
        threadCount 2
        parallel 'classes'
        useDefaultListeners = true
    }
    ignoreFailures = true
}

</code>```

We have tried increasing and decreasing the value of SE_NODE_SESSION_TIMEOUT in our docker compose file, and increasing and decreasing the number of grid nodes via the absence or presence of entries like:

```<code>services:

  selenium-hub:
    image: selenium/hub:4.1.2-20220208
    container_name: selenium-hub
    ports:
      - "4442:4442"
      - "4443:4443"
      - "4444:4444"

  chrome1:
    image: selenium/node-chrome:4.1.2-20220208
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
      - SE_NODE_SESSION_TIMEOUT=1200 # 1,200 secs = 20 mins
      - START_XVFB=${START_XVFB}
    ports:
      - "59001:5900"
</code>```

Our existing tests running under selenium 3.14x jars and selenium 3.14x grid are far far more stable than under 4.x.

What is the right hardware to run an n node selenium grid on?

What is the right balance of selenium clients pumping in commands to a grid executing them?

Why is selenium 3.x so different from 4.x?

If you worked at amazon and had 1,000 selenium tests, how would you size your selenium grid for 4.x?

I have __ testrunner threads, so I need __ grid nodes __ with __ cpus.

Any help or tips are appreciated!

Thanks!
-neil

答:
Why is selenium 3.x so different from 4.x?

Selenium Grid 3.x had got performance and reliability issues starting from serving 20-30+ nodes per a single hub.

So Selenium Hub, which was monolite in selenium 3.x has been splited on multiple components:

router

distributor

sessions-map

session-queue

event-bus

This has been done in order to improve the Selenium Grid Cluster reliability (since a single component down might bring less issues, e.g. the new sessions cannot created, but existing sessions works.).

There were also reasons to optimize jars size, cleanup some legacy code, allow a single hub to serve more nodes then earlier, etc.

But now, while Selenium Grid 4.x aimed to become more optimized, flexible and reliable it also became more complex to configure.

Just look at the full services list:

https://github.com/SeleniumHQ/docker-selenium/blob/trunk/docker-compose-v3-full-grid.yml

What is the right hardware to run an n node selenium grid on?

I would say - no any specific or optimized hardware is required for web-browsers launch.

For c5.4xlarge instance with 16CPU and 32GB RAM it should be possible to launch at least 1 browser instance per CPU. And for critical load - 2 browsers per CPU.

So for this env I would expect ~ 16-24 parallel selenium sessions (if you'll have a single selenium hub).

What is the right balance of selenium clients pumping in commands to a grid executing them?

Selenium 3.x was able to serve up-to 20-30 nodes without performance issues.

For Selenium 4.x I would expect this count increased, but I've not tested this.

Anyway, having 1 Selenium Hub per 2 Selenium Nodes as in your example, I think is overhead, but it's mandatory for docker-selenium to launch Selenium Hub even if you going to have even only one node.

If you worked at amazon and had 1,000 selenium tests, how would you size your selenium grid for 4.x?

Usually we test a single test application instance, so parallelism might be limited by the test application ability to serve multiple users requests.

I've faced a cases when I able to launch 10 more parallel threads, but test app starts returning 500 errors.

For 1000 selenium tests I'll try to launch 15-20 parallel sessions and look if further increasing parallel sessions count still brings some profit.

The main point here: what is the time limit for build? 7 minutes, or 30 minutes, or 60 minutes.. Strategy aligned to this.

Instability Causes

I'll try to list my thouts about your sessions instability causes:

For Selenium 4.x it's highly recommended to set the flag --shm-size, and it's missed in your config example.

From: https://github.com/SeleniumHQ/docker-selenium#--shm-size2g

When executing docker run for an image that contains a browser please use the flag --shm-size=2g to use the host's shared memory.

This is a known workaround to avoid the browser crashing inside a docker container, here are the documented issues for Chrome and Firefox. The shm size of 2gb is arbitrary but known to work well, your specific use case might need a different value, it is recommended to tune this value according to your needs.

Having 2 Nodes per Hub might be not optimal, a single Hub is able to serve at least 20+ Nodes.

1 Browser per CPU is optimal, 2 Browsers per CPU might be possible.

Reusing browser sessions per many tests?

I suggest do not reuse sessions. I try do not share sessions between tests,
and do not keep browser working > 10 minutes. I've noticed that
reliability decreases if the browser session have already worked for
some time. I think it's just a good practice to prevent an
additional instability.

Selenium Grid Alternatives?

I still don't think that Selenium Grid is quite reliable approach for implementing Selenium Clusters.

For the last 4 years I'm using Selenoid. And this is just my own experience (I'm just a fan), this tool is simple, reliable and works like a charm.

At least several years ago it was already providing everything I've expected from Selenium Grid and what Selenium Grid trying to achieve for now.

References

https://www.selenium.dev/documentation/grid/

https://www.selenium.dev/documentation/grid/components/

https://github.com/aerokube/selenoid

https://aerokube.com/selenoid/latest/

Body:
We are having trouble upgrading to selenium 4.

The features and performance of selenium 4 look amazing, but we are having trouble getting our pipeline stable and consistently green.

We need some advice to help us fix some of the infrastructure issues we are seeing.

We are getting lots of org.openqa.selenium.NoSuchSessionException: invalid session id errors, and they are not consistant.  We are also getting other session runtime exceptions.

We are testing our own website, which is on the internet, using selenium.  We use selenium to click on buttons and fill out forms and stuff, via chromedriver in tests written in kotlin. Running these tests on a selenium 4.1.2 grid is basically broken for us.

We have a couple hundred selenium tests.  We want them to complete as quickly as possible, so we are trying to balance our base hardware with the maximum throughput of "UI actions".

We are running our selenium 4 grid on a feature branch on our build agents, which are TeamCity build agents on c5.4xlarge instances; each build has its own grid in its own docker network. Our grid's docker images are installed on our agents at runtime as part of starting our build.

We are invoking our build via gradle and testng, eg:

test {
    systemProperties System.getProperties()
    useTestNG {
        suites 'src/test/resources/selenium-' + suite + '.xml'
        preserveOrder true
        threadCount 2
        parallel 'classes'
        useDefaultListeners = true
    }
    ignoreFailures = true
}

We have tried increasing and decreasing the value of SE_NODE_SESSION_TIMEOUT in our docker compose file, and increasing and decreasing the number of grid nodes via the absence or presence of entries like:

services:

  selenium-hub:
    image: selenium/hub:4.1.2-20220208
    container_name: selenium-hub
    ports:
      - "4442:4442"
      - "4443:4443"
      - "4444:4444"

  chrome1:
    image: selenium/node-chrome:4.1.2-20220208
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
      - SE_NODE_SESSION_TIMEOUT=1200 # 1,200 secs = 20 mins
      - START_XVFB=${START_XVFB}
    ports:
      - "59001:5900"

Our existing tests running under selenium 3.14x jars and selenium 3.14x grid are far far more stable than under 4.x.

What is the right hardware to run an n node selenium grid on?

What is the right balance of selenium clients pumping in commands to a grid executing them?

Why is selenium 3.x so different from 4.x?

If you worked at amazon and had 1,000 selenium tests, how would you size your selenium grid for 4.x?

I have __ testrunner threads, so I need __ grid nodes __ with __ cpus.

Any help or tips are appreciated!

Thanks!
-neil


问:
How do I put a conditional and a loop in the same line?
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

```<code>foreach (0 .. 10) {
    print $_ if $_ % 2;
}
</code>```

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

```<code>[i for i in range(10) if i % 2]
</code>```

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

答:
The general answer is to use grep.

say for grep $_ % 2, 0..10;
```
<p>As a case-specific solution, you can use the following:</p>
<pre class="lang-perl prettyprint-override"><code>say $_ * 2 for 0..5;
</code>```

Body:
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

foreach (0 .. 10) {
    print $_ if $_ % 2;
}

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

[i for i in range(10) if i % 2]

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

Body:
The general answer is to use grep.

say for grep $_ % 2, 0..10;

As a case-specific solution, you can use the following:

say $_ * 2 for 0..5;


问:
How to substitute @Sql in tests with Spring data r2dbc?
In Spring data JPA there is an @Sql annotation which is very handy for setting up integration tests for persistence layer. It can roll out test data before each test and perform a clean up after it.

However, I could not find it in spring-data-r2dbc module. Is there anything similar to easily handle this task in spring-data-r2dbc?

答:
If you want you can use @Sql in your integration Tests in a simple way, so you can use something you are familiar with. Even if you are using r2dbc you can add this dependencies in you pom.xml/gradle file:

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
    </dependency>
</code>```

so you have both driver (blocking and non blocking version). This dependency can be useful in other situation (if you use Flyway for example - it doesn't support reactive drivers yet). Then you can create a @Configuration class that you can use in your integration tests. In case you are using postgresql in your integration test you will have something like:

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@Configuration
public class TestConfig {

    /**
     * Necessary to run sql scripts with @Sql
     */
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
        dataSource.setUsername("postgres");
        dataSource.setPassword("1234");
        return dataSource;
    }

}
</code>```

To test your database your test will start with something like:

```<code>@DataR2dbcTest
@ActiveProfiles("test")
@Sql(value = "classpath:sql/MovieInfoRepositoryITest.sql")
@Import({TestConfig.class})
class MovieInfoRepositoryITest {
    ...
}
</code>```

Don't be afraid to use the JDBC drive where is not "painful" for your reactive application, like executing your sql scripts during tests.

Body:
If you want you can use @Sql in your integration Tests in a simple way, so you can use something you are familiar with. Even if you are using r2dbc you can add this dependencies in you pom.xml/gradle file:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
    </dependency>

so you have both driver (blocking and non blocking version). This dependency can be useful in other situation (if you use Flyway for example - it doesn't support reactive drivers yet). Then you can create a @Configuration class that you can use in your integration tests. In case you are using postgresql in your integration test you will have something like:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@Configuration
public class TestConfig {

    /**
     * Necessary to run sql scripts with @Sql
     */
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
        dataSource.setUsername("postgres");
        dataSource.setPassword("1234");
        return dataSource;
    }

}

To test your database your test will start with something like:

@DataR2dbcTest
@ActiveProfiles("test")
@Sql(value = "classpath:sql/MovieInfoRepositoryITest.sql")
@Import({TestConfig.class})
class MovieInfoRepositoryITest {
    ...
}

Don't be afraid to use the JDBC drive where is not "painful" for your reactive application, like executing your sql scripts during tests.


问:
How to show a loading screen when the output is being calculated in a background process?
This question is in the continuity of this one: Is it possible to stop executing of R code inside shiny (without stopping the shiny process)?.

The plot that I display in my app takes some time to produce, and I want the users to be able to stop its creation (for instance if they made a mistake in the options). I found this blog post about using callr in Shiny. The workflow is the following:

create an empty list of jobs/plots

clicking on "start" creates a background process to create the plot

if the user doesn't do anything, the plot is computed in the background. I use invalidateLater() every second to check if the background process is finished. If it is, then I display the plot.

if the user clicks on "stop" before the end of the process, the process is killed, removed from the list, and the previous plot is displayed (if there was no plot produced before, nothing is displayed)

First, I'm not sure how this would scale when several people use the app at the same time. Since every background process is independent, I don't think one user would be blocking the others, but I may be wrong.

Second, I'd like to show a waiting indicator on the plot. So far, I used the package waiter to do that, but the problem here is that renderPlot() is being invalidated every second to check if the background process is finished. Therefore, waiter appears and disappears repeatedly as the output is being invalidated.

Below is an example app that mimics the behavior I'd like to have:

library(shiny)
library(uuid)
library(ggplot2)
library(waiter)

ui <- fluidPage(
  useWaiter(),
  titlePanel("Test background job"),
  actionButton("start","Start Job"),
  actionButton("stop", "Stop job"),
  plotOutput("plot")
)

# the toy example job
slow_func <- function(var){
  library(ggplot2)
  Sys.sleep(5)
  ggplot(mtcars, aes(drat, !!sym(var))) +
    geom_point()
}

server <- function(input, output, session) {

  w <- Waiter$new(id = "plot")

  token <- reactiveValues(var = NULL, id = NULL, last_id = NULL)
  jobs <- reactiveValues()

  # When I press "start", run the slow function and append the output to
  # the list of jobs. To render the plot, check if the background process is
  # finished. If it's not, re-check one second later.

  long_run <- eventReactive(input$start, {
    token$var <- c(token$var, sample(names(mtcars), 1))
    token$id <- c(token$id, UUIDgenerate())
    token$last_id <- token$id[[length(token$id)]]
    message(paste0("running task with id: ", token$last_id))
    jobs[[token$last_id]] <- callr::r_bg(
      func = slow_func,
      args = list(var = token$var[[length(token$var)]])
    )
    return(jobs[[token$last_id]])
  })

  observeEvent(input$start, {
    output$plot <- renderPlot({
      w$show()
      if (long_run()$poll_io(0)["process"] == "timeout") {
        invalidateLater(1000)
      } else {
        jobs[[token$last_id]]$get_result()
      }
    })
  })

  # When I press "stop", kill the last process, remove it from the list of
  # jobs (because it didn't produce any output so it is useless), and display
  # the last process (which by definition is the last plot produced)

  observeEvent(input$stop, {

    if (length(token$id) > 0) {
      jobs[[token$last_id]]$kill()
      message(paste0("task ", token$last_id, " stopped"))
      token$id <- token$id[-length(token$id)]
      if (length(token$id) > 0) {
        token$last_id <- token$id[[length(token$id)]]
      }
    }

    output$plot <- renderPlot({
      if (length(token$id) > 0) {
        print(token$last_id)
        jobs[[token$last_id]]$get_result()
      } else {
        return(NULL)
      }
    })
  })

}

shinyApp(ui = ui, server = server)
```

Current behavior:

run the app, click on "Start job"

notice that the waiter overlay appears and disappears

Question: How can I get a constant loading screen on the plot when it is being calculated in the background?

答:
Regarding your first concern: this approach won't block other sessions. However, the polling via invalidateLater() will create some load.

A great library to look at in this context is ipc and its introductory vignette.

Regarding the second issue: There is a  simple fix for this behaviour. We can use req and its cancelOutput parameter - see ?req:

cancelOutput: If TRUE and an output is being evaluated, stop
processing as usual but instead of clearing the output, leave it in
whatever state it happens to be in.

```<code>library(shiny)
library(uuid)
library(ggplot2)
library(waiter)

ui <- fluidPage(
  useWaiter(),
  titlePanel("Test background job"),
  actionButton("start","Start Job"),
  actionButton("stop", "Stop job"),
  plotOutput("plot")
)

# the toy example job
slow_func <- function(var){
  library(ggplot2)
  Sys.sleep(5)
  ggplot(mtcars, aes(drat, !!sym(var))) +
    geom_point()
}

server <- function(input, output, session) {

  w <- Waiter$new(id = "plot")

  token <- reactiveValues(var = NULL, id = NULL, last_id = NULL)
  jobs <- reactiveValues()

  # When I press "start", run the slow function and append the output to
  # the list of jobs. To render the plot, check if the background process is
  # finished. If it's not, re-check one second later.

  long_run <- eventReactive(input$start, {
    token$var <- c(token$var, sample(names(mtcars), 1))
    token$id <- c(token$id, UUIDgenerate())
    token$last_id <- token$id[[length(token$id)]]
    message(paste0("running task with id: ", token$last_id))
    jobs[[token$last_id]] <- callr::r_bg(
      func = slow_func,
      args = list(var = token$var[[length(token$var)]])
    )
    return(jobs[[token$last_id]])
  })

  observeEvent(input$start, {
    output$plot <- renderPlot({
      w$show()
      if (long_run()$poll_io(0)["process"] == "timeout") {
        invalidateLater(1000)
        req(FALSE, cancelOutput = TRUE)
      } else {
        jobs[[token$last_id]]$get_result()
      }
    })
  })

  # When I press "stop", kill the last process, remove it from the list of
  # jobs (because it didn't produce any output so it is useless), and display
  # the last process (which by definition is the last plot produced)

  observeEvent(input$stop, {

    if (length(token$id) > 0) {
      jobs[[token$last_id]]$kill()
      message(paste0("task ", token$last_id, " stopped"))
      token$id <- token$id[-length(token$id)]
      if (length(token$id) > 0) {
        token$last_id <- token$id[[length(token$id)]]
      }
    }

    output$plot <- renderPlot({
      if (length(token$id) > 0) {
        print(token$last_id)
        jobs[[token$last_id]]$get_result()
      } else {
        return(NULL)
      }
    })
  })

}

shinyApp(ui = ui, server = server)
</code>```

Body:
This question is in the continuity of this one: Is it possible to stop executing of R code inside shiny (without stopping the shiny process)?.

The plot that I display in my app takes some time to produce, and I want the users to be able to stop its creation (for instance if they made a mistake in the options). I found this blog post about using callr in Shiny. The workflow is the following:

create an empty list of jobs/plots

clicking on "start" creates a background process to create the plot

if the user doesn't do anything, the plot is computed in the background. I use invalidateLater() every second to check if the background process is finished. If it is, then I display the plot.

if the user clicks on "stop" before the end of the process, the process is killed, removed from the list, and the previous plot is displayed (if there was no plot produced before, nothing is displayed)

First, I'm not sure how this would scale when several people use the app at the same time. Since every background process is independent, I don't think one user would be blocking the others, but I may be wrong.

Second, I'd like to show a waiting indicator on the plot. So far, I used the package waiter to do that, but the problem here is that renderPlot() is being invalidated every second to check if the background process is finished. Therefore, waiter appears and disappears repeatedly as the output is being invalidated.

Below is an example app that mimics the behavior I'd like to have:

library(shiny)
library(uuid)
library(ggplot2)
library(waiter)

ui <- fluidPage(
  useWaiter(),
  titlePanel("Test background job"),
  actionButton("start","Start Job"),
  actionButton("stop", "Stop job"),
  plotOutput("plot")
)

# the toy example job
slow_func <- function(var){
  library(ggplot2)
  Sys.sleep(5)
  ggplot(mtcars, aes(drat, !!sym(var))) +
    geom_point()
}

server <- function(input, output, session) {

  w <- Waiter$new(id = "plot")

  token <- reactiveValues(var = NULL, id = NULL, last_id = NULL)
  jobs <- reactiveValues()

  # When I press "start", run the slow function and append the output to
  # the list of jobs. To render the plot, check if the background process is
  # finished. If it's not, re-check one second later.

  long_run <- eventReactive(input$start, {
    token$var <- c(token$var, sample(names(mtcars), 1))
    token$id <- c(token$id, UUIDgenerate())
    token$last_id <- token$id[[length(token$id)]]
    message(paste0("running task with id: ", token$last_id))
    jobs[[token$last_id]] <- callr::r_bg(
      func = slow_func,
      args = list(var = token$var[[length(token$var)]])
    )
    return(jobs[[token$last_id]])
  })

  observeEvent(input$start, {
    output$plot <- renderPlot({
      w$show()
      if (long_run()$poll_io(0)["process"] == "timeout") {
        invalidateLater(1000)
      } else {
        jobs[[token$last_id]]$get_result()
      }
    })
  })

  # When I press "stop", kill the last process, remove it from the list of
  # jobs (because it didn't produce any output so it is useless), and display
  # the last process (which by definition is the last plot produced)

  observeEvent(input$stop, {

    if (length(token$id) > 0) {
      jobs[[token$last_id]]$kill()
      message(paste0("task ", token$last_id, " stopped"))
      token$id <- token$id[-length(token$id)]
      if (length(token$id) > 0) {
        token$last_id <- token$id[[length(token$id)]]
      }
    }

    output$plot <- renderPlot({
      if (length(token$id) > 0) {
        print(token$last_id)
        jobs[[token$last_id]]$get_result()
      } else {
        return(NULL)
      }
    })
  })

}

shinyApp(ui = ui, server = server)

Current behavior:

run the app, click on "Start job"

notice that the waiter overlay appears and disappears

Question: How can I get a constant loading screen on the plot when it is being calculated in the background?

Body:
Regarding your first concern: this approach won't block other sessions. However, the polling via invalidateLater() will create some load.

A great library to look at in this context is ipc and its introductory vignette.

Regarding the second issue: There is a  simple fix for this behaviour. We can use req and its cancelOutput parameter - see ?req:

cancelOutput: If TRUE and an output is being evaluated, stop
processing as usual but instead of clearing the output, leave it in
whatever state it happens to be in.

library(shiny)
library(uuid)
library(ggplot2)
library(waiter)

ui <- fluidPage(
  useWaiter(),
  titlePanel("Test background job"),
  actionButton("start","Start Job"),
  actionButton("stop", "Stop job"),
  plotOutput("plot")
)

# the toy example job
slow_func <- function(var){
  library(ggplot2)
  Sys.sleep(5)
  ggplot(mtcars, aes(drat, !!sym(var))) +
    geom_point()
}

server <- function(input, output, session) {

  w <- Waiter$new(id = "plot")

  token <- reactiveValues(var = NULL, id = NULL, last_id = NULL)
  jobs <- reactiveValues()

  # When I press "start", run the slow function and append the output to
  # the list of jobs. To render the plot, check if the background process is
  # finished. If it's not, re-check one second later.

  long_run <- eventReactive(input$start, {
    token$var <- c(token$var, sample(names(mtcars), 1))
    token$id <- c(token$id, UUIDgenerate())
    token$last_id <- token$id[[length(token$id)]]
    message(paste0("running task with id: ", token$last_id))
    jobs[[token$last_id]] <- callr::r_bg(
      func = slow_func,
      args = list(var = token$var[[length(token$var)]])
    )
    return(jobs[[token$last_id]])
  })

  observeEvent(input$start, {
    output$plot <- renderPlot({
      w$show()
      if (long_run()$poll_io(0)["process"] == "timeout") {
        invalidateLater(1000)
        req(FALSE, cancelOutput = TRUE)
      } else {
        jobs[[token$last_id]]$get_result()
      }
    })
  })

  # When I press "stop", kill the last process, remove it from the list of
  # jobs (because it didn't produce any output so it is useless), and display
  # the last process (which by definition is the last plot produced)

  observeEvent(input$stop, {

    if (length(token$id) > 0) {
      jobs[[token$last_id]]$kill()
      message(paste0("task ", token$last_id, " stopped"))
      token$id <- token$id[-length(token$id)]
      if (length(token$id) > 0) {
        token$last_id <- token$id[[length(token$id)]]
      }
    }

    output$plot <- renderPlot({
      if (length(token$id) > 0) {
        print(token$last_id)
        jobs[[token$last_id]]$get_result()
      } else {
        return(NULL)
      }
    })
  })

}

shinyApp(ui = ui, server = server)


问:
C++ Vector of Object searching for which object contains a specific last name error C2678 binary '==': no operator found
C++ is not really in my skills, so I have vector of objects which is obviously several copies of a class.

My class is named "Contact", and my function I am property passing in my vector objects as reference.

As soon as I try to add in this find, I guess an error

```<code>void Contact::searchContactByLastName(string name, vector<Contact>& allContacts) {

    cout << "In SearchContactByLastName \n";  //

    unsigned int count = allContacts.size();

    for (unsigned int i = 0; i < count; i++) {

        //this works
        cout << " Last Name " << i << " = " << allContacts[i].getLastName() << endl;
        // THIS IS WHAT DOES NOT WORK, even outside the for loop ....
        if (std::find(allContacts.begin(), allContacts.end(), name) != allContacts.end()) {
            // Found the item
        }
    }

}
</code>```

答:
Since you probably don't want to implement the == operator to match Contract and std::string, it's a good idea to std::find_if allowing you to pass the matching functionality as parameter.

```<code>if (std::find_if(allContacts.begin(), allContacts.end(), [&name](Contract const& contract) {return name == contract.getLastName();}) != allContacts.end()) {
    // Found the item
}

</code>```

Body:
C++ is not really in my skills, so I have vector of objects which is obviously several copies of a class.

My class is named "Contact", and my function I am property passing in my vector objects as reference.

As soon as I try to add in this find, I guess an error

void Contact::searchContactByLastName(string name, vector<Contact>& allContacts) {

    cout << "In SearchContactByLastName \n";  //

    unsigned int count = allContacts.size();

    for (unsigned int i = 0; i < count; i++) {

        //this works
        cout << " Last Name " << i << " = " << allContacts[i].getLastName() << endl;
        // THIS IS WHAT DOES NOT WORK, even outside the for loop ....
        if (std::find(allContacts.begin(), allContacts.end(), name) != allContacts.end()) {
            // Found the item
        }
    }

}

Body:
Since you probably don't want to implement the == operator to match Contract and std::string, it's a good idea to std::find_if allowing you to pass the matching functionality as parameter.

if (std::find_if(allContacts.begin(), allContacts.end(), [&name](Contract const& contract) {return name == contract.getLastName();}) != allContacts.end()) {
    // Found the item
}


问:
How do I move/copy a symlink to a different folder as a symlink under Solaris?
It is an odd behaviour seen only on Solaris that when I try to copy a symbolic link with the "cp -R -P" command to some other folder with a different name, it copies the entire directory/file it's pointing to.

For example:

```<code>link -> dir

cp -R -P link folder/new_link
</code>```

答: Try using cpio (with the -p (pass) option) or the old tar in a pipe trick.</p>

OwnerDisplayName: kadeshpa

ContentLicense: CC BY-SA 2.5

Body:
It is an odd behaviour seen only on Solaris that when I try to copy a symbolic link with the "cp -R -P" command to some other folder with a different name, it copies the entire directory/file it's pointing to.

For example:

link -> dir

cp -R -P link folder/new_link

LastEditorDisplayName: Eddie

OwnerDisplayName: MarkusQ

ContentLicense: CC BY-SA 3.0


问:
WPF linebreak problems
I have a TextBlock and want to show information from the database.
I wan't to display the text like this:

```<code>Task for Day xy
- blabla
- blabla
- more blablabla
</code>```

Somehow I need to include a character for the newlines.. I thoug about \n.. so the text in the database would look like:

Task for Day xy\n- blabla\n- blabla\n- more blablabla

doesn't work.

I tried and searched online for hours.. no solution how to do that.
Also this doesn't work:

```<code>Task for Day xy<LineBreak />- blabla<LineBreak />- blabla<LineBreak />- more blablabla
</code>```

the application shows exactly that string from the database without new lines..

here the part of the xaml:

```<code><Grid>
  <Grid.ColumnDefinitions>
      <ColumnDefinition Width="100" />
      <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <TextBlock Grid.Column="1" Text="{Binding Date, StringFormat={}{0:dd.MM.yyyy}}" Margin="6" />
  <TextBlock Grid.Column="2" Text="{Binding Notes}" Margin="6" />
</Grid>
</code>```

any ideas?

答: I would not recommend storing the line breaks in the database, as line breaks will not be the same across platforms.  I would just add the line breaks before displaying using System.Environment.NewLine.</p>

Title: WPF linebreak problems

Body:
I have a TextBlock and want to show information from the database.
I wan't to display the text like this:

Task for Day xy
- blabla
- blabla
- more blablabla

Somehow I need to include a character for the newlines.. I thoug about \n.. so the text in the database would look like:

Task for Day xy\n- blabla\n- blabla\n- more blablabla

doesn't work.

I tried and searched online for hours.. no solution how to do that.
Also this doesn't work:

Task for Day xy<LineBreak />- blabla<LineBreak />- blabla<LineBreak />- more blablabla

the application shows exactly that string from the database without new lines..

here the part of the xaml:

<Grid>
  <Grid.ColumnDefinitions>
      <ColumnDefinition Width="100" />
      <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <TextBlock Grid.Column="1" Text="{Binding Date, StringFormat={}{0:dd.MM.yyyy}}" Margin="6" />
  <TextBlock Grid.Column="2" Text="{Binding Notes}" Margin="6" />
</Grid>

any ideas?


问:
how to delete firebase Firstore document
I tried several methods, but when I actually click the delete button, not just one document is deleted, but all the documents. What should I do? Here's the code:

```<code>const db = firebase.firestore();
  db.collection('data').get().then((snapshot)=>{
    snapshot.forEach((doc)=>{

      const da = doc.id;

      function delei(){
        db.collection('data').doc(da).delete().then(()=>{
          console.log('deleted');
        })
      }

      var 템플릿 = `<div class="attend">
        <div class="date">${doc.data().날짜}</div>
        <div class="icons">
            <span class="download 48dp material-icons-outlined" onclick="location.href='${doc.data().엑셀}'">file_download</span>
            <span class="trash 48dp material-icons-outlined" onclick="${delei()}" >delete</span>
        </div>
    </div>`
      $('.big').append(템플릿);
    })
});
</code>```

thank you

答:
I hope you are doing great.
I will share with you two links to a beautiful tutorial about your question from YouTube.
For firebase v9:
https://www.youtube.com/watch?v=s1frrNxq4js
For earlier version (like yours):
https://www.youtube.com/watch?v=UZqXcoqC95E&list=PL4cUxeGkcC9itfjle0ji1xOZ2cjRGY_WB&index=5
I'm sorry that I didn't write the code but I saw your question and I was so tired, and I wanted to help with anything useful.</p>

Body:
I tried several methods, but when I actually click the delete button, not just one document is deleted, but all the documents. What should I do? Here's the code:

const db = firebase.firestore();
  db.collection('data').get().then((snapshot)=>{
    snapshot.forEach((doc)=>{

      const da = doc.id;

      function delei(){
        db.collection('data').doc(da).delete().then(()=>{
          console.log('deleted');
        })
      }

      var 템플릿 = `

${doc.data().날짜}

            file_download
            delete

`
      $('.big').append(템플릿);
    })
});

thank you