问:
Provisioning Windows VM including File Provisioner for AWS using Terraform results in Timeout
I'm aware that there already exists several posts similar to this one - I've went through them and adapted my Terraform configuration file, but it makes no difference.

Therefore, I'd like to publish my configuration file and my use case: I'd like to provision a (Windows) Virtual Machine on AWS, using Terraform. It works without the File Provisioning part - including them, the provisioning results in a timeout.

This includes adaptations from previous posts:

SSH connection restriction
SSH isnt working in Windows with Terraform provisioner connection type

Usage of a Security group
Terraform File provisioner can't connect ec2 over ssh. timeout - last error: dial tcp 92.242.xxx.xx:22: i/o timeout

I also get a timeout when using "winrm" instead of "ssh".

I'd be happy if you could provide any hint for following config file:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  access_key = "<my access key>"
  secret_key = "<my secret key>"
  region = "eu-central-1"
}

resource "aws_instance" "webserver" {
    ami = "ami-07dfec7a6d529b77a"
    instance_type = "t2.micro"
    security_groups = [aws_security_group.sgwebserver.name]
    key_name = aws_key_pair.pubkey.key_name

    tags = {
        "Name" = "WebServer-Win"
    }
}

resource "null_resource" "deployBundle" {

    connection {
      type        = "ssh"
      user        = "Administrator"
      private_key = "${file("C:/Users/<my user name>/aws_keypair/aws_instance.pem")}"
      host        = aws_instance.webserver.public_ip
    }

    provisioner "file" {
      source = "files/test.txt"
      destination = "C:/test.txt"
    }

    depends_on = [ aws_instance.webserver ]
}

resource "aws_security_group" "sgwebserver" {
  name        = "sgwebserver"
  description = "Allow ssh inbound traffic"

  ingress {
    from_port        = 0
    to_port          = 6556
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
  }

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
  }

  tags = {
      Name = "sgwebserver"
  }

}

resource "aws_key_pair" "pubkey" {
    key_name = "aws-cloud"
    public_key = file("key/aws_instance.pub")
}

resource "aws_eip" "elasticip" {
    instance = aws_instance.webserver.id
}

output "eip" {
    value = aws_eip.elasticip.public_ip
}

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = "my-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["eu-central-1a", "eu-central-1b", "eu-central-1c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]

  enable_nat_gateway = true
  enable_vpn_gateway = true

  tags = {
    Terraform = "true"
    Environment = "dev"
  }
}

```

Thanks a lot in advance!

答:
Windows EC2 instances don't support SSH, they support RDP. You would have to install SSH server software on the instance before you could SSH into it.

I suggest doing something like placing the file in S3, and using a user data script to trigger the Windows EC2 instance to download the file on startup.

Body:
I'm aware that there already exists several posts similar to this one - I've went through them and adapted my Terraform configuration file, but it makes no difference.

Therefore, I'd like to publish my configuration file and my use case: I'd like to provision a (Windows) Virtual Machine on AWS, using Terraform. It works without the File Provisioning part - including them, the provisioning results in a timeout.

This includes adaptations from previous posts:

SSH connection restriction
SSH isnt working in Windows with Terraform provisioner connection type

Usage of a Security group
Terraform File provisioner can't connect ec2 over ssh. timeout - last error: dial tcp 92.242.xxx.xx:22: i/o timeout

I also get a timeout when using "winrm" instead of "ssh".

I'd be happy if you could provide any hint for following config file:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  access_key = "<my access key>"
  secret_key = "<my secret key>"
  region = "eu-central-1"
}

resource "aws_instance" "webserver" {
    ami = "ami-07dfec7a6d529b77a"
    instance_type = "t2.micro"
    security_groups = [aws_security_group.sgwebserver.name]
    key_name = aws_key_pair.pubkey.key_name

    tags = {
        "Name" = "WebServer-Win"
    }
}

resource "null_resource" "deployBundle" {

    connection {
      type        = "ssh"
      user        = "Administrator"
      private_key = "${file("C:/Users/<my user name>/aws_keypair/aws_instance.pem")}"
      host        = aws_instance.webserver.public_ip
    }

    provisioner "file" {
      source = "files/test.txt"
      destination = "C:/test.txt"
    }

    depends_on = [ aws_instance.webserver ]
}

resource "aws_security_group" "sgwebserver" {
  name        = "sgwebserver"
  description = "Allow ssh inbound traffic"

  ingress {
    from_port        = 0
    to_port          = 6556
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
  }

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
  }

  tags = {
      Name = "sgwebserver"
  }

}

resource "aws_key_pair" "pubkey" {
    key_name = "aws-cloud"
    public_key = file("key/aws_instance.pub")
}

resource "aws_eip" "elasticip" {
    instance = aws_instance.webserver.id
}

output "eip" {
    value = aws_eip.elasticip.public_ip
}

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = "my-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["eu-central-1a", "eu-central-1b", "eu-central-1c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]

  enable_nat_gateway = true
  enable_vpn_gateway = true

  tags = {
    Terraform = "true"
    Environment = "dev"
  }
}

Thanks a lot in advance!


来源: stackexchange

问:
Form.Close() doesn't close window immediately
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

```<code>public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }
</code>```

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

答:
If for some reason, Application.Exit isn't cutting it for you, you could try this code (put it in the form's FormClosing event):

```<code>while (Application.OpenForms.Count > 1)
{
  Form form = Application.OpenForms[1];
  form.Close();
  while (!form.IsDisposed) Application.DoEvents();
}
</code>```

or if you want it to time out if it can't close all the forms after a while,

```<code>while (Application.OpenForms.Count > 1)
{
  Form form = Application.OpenForms[1];
  form.Close();
  DateTime StartTime = DateTime.Now;
  while (!form.IsDisposed && (StartTime - DateTime.Now).TotalMilliseconds < 1000)
    Application.DoEvents(); //1-second timeout here
  if (!form.IsDisposed) //if it's still not closed
  {
    //send a message to the user that the application can't exit right now
    mbox("some forms are still open or whatever");
    e.Cancel = true;
    return;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

Body:
If for some reason, Application.Exit isn't cutting it for you, you could try this code (put it in the form's FormClosing event):

while (Application.OpenForms.Count > 1)
{
  Form form = Application.OpenForms[1];
  form.Close();
  while (!form.IsDisposed) Application.DoEvents();
}

or if you want it to time out if it can't close all the forms after a while,

while (Application.OpenForms.Count > 1)
{
  Form form = Application.OpenForms[1];
  form.Close();
  DateTime StartTime = DateTime.Now;
  while (!form.IsDisposed && (StartTime - DateTime.Now).TotalMilliseconds < 1000)
    Application.DoEvents(); //1-second timeout here
  if (!form.IsDisposed) //if it's still not closed
  {
    //send a message to the user that the application can't exit right now
    mbox("some forms are still open or whatever");
    e.Cancel = true;
    return;
  }
}


问:
Best Practises of @Repository in Spring boot framework
I have a Spring boot application which has a UserRepository but I have not annotated that repository with @Repository but still my application works fine.

Why @Repository annotation is optional in Spring boot and what is the best practise that should we annotate it or not in repository classes.

答:
@Repository is used to indicate interface that extends a jpa repository, for example. Notice in the example below, the interface extends the Beer class and the BeerQueries query interface.</p>
```<code>package com.algaworks.brewer.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.algaworks.brewer.model.Beer;
import com.algaworks.brewer.repository.helper.beer.BeersQueries;

@Repository
public interface Beers extends JpaRepository<Beer, Long>, BeersQueries {

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
@Repository is used to indicate interface that extends a jpa repository, for example. Notice in the example below, the interface extends the Beer class and the BeerQueries query interface.

package com.algaworks.brewer.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.algaworks.brewer.model.Beer;
import com.algaworks.brewer.repository.helper.beer.BeersQueries;

@Repository
public interface Beers extends JpaRepository<Beer, Long>, BeersQueries {

}


问:
Is it safe to share domain restricted API keys?
I'm using Google's Perspective API and have an API key. I've restricted this to the specific domain I'm going to be using, but I would like to know if it's safe to release the key in my code? As this would be in the client's browser I don't want to make a backend just for that, but I will if necessary.

Essentially: Is it safe to share a domain restricted API key?

答:
I do not think it is safe. Google does not recommend it. You can check the official article for the best practices.

"Do not embed API keys directly in code: API keys that are embedded in code can be accidentally exposed to the public, for example, if you forget to remove the keys from code that you share. Instead of embedding your API keys in your applications, store them in environment variables or in files outside of your application's source tree."


问:
Remove empty values from PHP array but keep 0
I have an array

```<code>array (size=7)
0 => string '2'
1 => string ''
2 => string ''
3 => string '0'
4 => string ''
5 => string ''
6 => string '2.5'
</code>```

I used:-

array_filter()

to remove the null values and it returns

```<code>Array ( [0] => 2 [6] => 2 )
</code>```

array_filter() removes null value and also '0' value.

Any builtin function is available in PHP to remove NULL values only.

答:
As of PHP 7.4:

$withoutNulls = array_filter($withNulls, static fn($e) => $e !== null);
```

Body:
I have an array

array (size=7)
0 => string '2'
1 => string ''
2 => string ''
3 => string '0'
4 => string ''
5 => string ''
6 => string '2.5'

I used:-

array_filter()

to remove the null values and it returns

Array ( [0] => 2 [6] => 2 )

array_filter() removes null value and also '0' value.

Any builtin function is available in PHP to remove NULL values only.


问:
When I execute this command (shub login), in python I get error. I execute this command after installing the shub package
```<code>Traceback (most recent call last):
  File "C:\Users\mohammadprgrm\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\mohammadprgrm\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\mohammadprgrm\Desktop\py\env\Scripts\shub.exe\__main__.py", line 4, in <module>
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\shub\tool.py", line 7, in <module>
    from shub.utils import update_available
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\shub\utils.py", line 42, in <module>
    from scrapinghub import ScrapinghubClient, ScrapinghubAPIError, HubstorageClient
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\scrapinghub\__init__.py", line 13, in <module>
    from .hubstorage import HubstorageClient
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\scrapinghub\hubstorage\__init__.py", line 6, in <module>
    from .client import HubstorageClient
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\scrapinghub\hubstorage\client.py", line 8, in <module>
    from .project import Project
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\scrapinghub\hubstorage\project.py", line 3, in <module>
    from .job import Job
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\scrapinghub\hubstorage\job.py", line 2, in <module>
    from .resourcetype import (ItemsResourceType, DownloadableResource,
  File "C:\Users\mohammadprgrm\Desktop\py\env\lib\site-packages\scrapinghub\hubstorage\resourcetype.py", line 5, in <module>
    from collections import MutableMapping
ImportError: cannot import name 'MutableMapping' from 'collections' (C:\Users\mohammadprgrm\AppData\Local\Programs\Python\Python310\lib\collections\__init__.py)
</code>```

答:
That version of the scrapinghub package is evidently not compatible with Python 3.10.

Downgrade to Python 3.9, or upgrade the package to a new, compatible version if there is one which there may not be yet: https://github.com/scrapinghub/python-scrapinghub/issues/160


问:
Better way to join multiple tables using SQL
I am messing around with the toy databases on W3School for learning SQL and I was trying to make a table that allowed me to find out the following information on a given OrderID:

Name of the products in the order.

Total cost of each product in the order (so if they ordered 10 of 1 item, what is the cost).

Name of the suppliers of those products.

Name of the shipper for the order.

I ended up achieving it through this code:

```<code>SELECT
    Price * Quantity AS TotalCost,
    ProductName, SupplierName, ShipperName
FROM
    (SELECT *
     FROM
         (SELECT *
          FROM
              (SELECT *
               FROM Products
               LEFT JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID) AS Products
          LEFT JOIN
              OrderDetails ON Products.ProductID = OrderDetails.ProductID) AS OrderDetails
     LEFT JOIN
         Orders ON OrderDetails.OrderID = Orders.OrderID) AS Orders
LEFT JOIN
    Shippers ON Orders.ShipperID = Shippers.ShipperID
WHERE
    Orders.OrderDetails.OrderID = 10248;
</code>```

However this seems like a total mess and I assume there must be a better way of achieving the same result. I did look around at other threads to see if I could find other ways, and the threads seemed to suggest that these subqueries are not necessary and that I could just chain the JOINs together without using subqueries, but when I tried this I got errors from the W3School compiler. Not sure if this is a problem with the website itself or if the error was on my end. For example, if I try this I get an error:

```<code>SELECT
    Price * Quantity AS TotalCost,
    ProductName, SupplierName, ShipperName
FROM
    Products
LEFT JOIN
    Suppliers ON Products.SupplierID = Suppliers.SupplierID
LEFT JOIN
    OrderDetails ON Products.ProductID = OrderDetails.ProductID
LEFT JOIN
    Orders ON OrderDetails.OrderID = Orders.OrderID
LEFT JOIN
    Shippers ON Orders.ShipperID = Shippers.ShipperID
WHERE
    Orders.OrderDetails.OrderID = 10248;
</code>```

Error:

Syntax error (missing operator) in query expression 'Products.SupplierID=Suppliers.SupplierID LEFT JOIN OrderDetails ON Products.ProductID=OrderDetails.ProductID LEFT JOIN Orders ON OrderDetails.OrderID=Orders.OrderID LEFT JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID'.

答:
You're not to far off. Please try the following version tidied up with tables aliases:

```<code>SELECT Price*Quantity AS TotalCost, ProductName, SupplierName, ShipperName
FROM Products p
LEFT JOIN Suppliers s ON p.SupplierID = s.SupplierID
LEFT JOIN OrderDetails od ON p.ProductID = od.ProductID
LEFT JOIN Orders o ON od.OrderID = o.OrderID
LEFT JOIN Shippers sh ON o.ShipperID = sh.ShipperID
WHERE o.OrderID = 10248;
</code>```

The only thing that is really changed is the WHERE clause.

Body:
I am messing around with the toy databases on W3School for learning SQL and I was trying to make a table that allowed me to find out the following information on a given OrderID:

Name of the products in the order.

Total cost of each product in the order (so if they ordered 10 of 1 item, what is the cost).

Name of the suppliers of those products.

Name of the shipper for the order.

I ended up achieving it through this code:

SELECT
    Price * Quantity AS TotalCost,
    ProductName, SupplierName, ShipperName
FROM
    (SELECT *
     FROM
         (SELECT *
          FROM
              (SELECT *
               FROM Products
               LEFT JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID) AS Products
          LEFT JOIN
              OrderDetails ON Products.ProductID = OrderDetails.ProductID) AS OrderDetails
     LEFT JOIN
         Orders ON OrderDetails.OrderID = Orders.OrderID) AS Orders
LEFT JOIN
    Shippers ON Orders.ShipperID = Shippers.ShipperID
WHERE
    Orders.OrderDetails.OrderID = 10248;

However this seems like a total mess and I assume there must be a better way of achieving the same result. I did look around at other threads to see if I could find other ways, and the threads seemed to suggest that these subqueries are not necessary and that I could just chain the JOINs together without using subqueries, but when I tried this I got errors from the W3School compiler. Not sure if this is a problem with the website itself or if the error was on my end. For example, if I try this I get an error:

SELECT
    Price * Quantity AS TotalCost,
    ProductName, SupplierName, ShipperName
FROM
    Products
LEFT JOIN
    Suppliers ON Products.SupplierID = Suppliers.SupplierID
LEFT JOIN
    OrderDetails ON Products.ProductID = OrderDetails.ProductID
LEFT JOIN
    Orders ON OrderDetails.OrderID = Orders.OrderID
LEFT JOIN
    Shippers ON Orders.ShipperID = Shippers.ShipperID
WHERE
    Orders.OrderDetails.OrderID = 10248;

Error:

Syntax error (missing operator) in query expression 'Products.SupplierID=Suppliers.SupplierID LEFT JOIN OrderDetails ON Products.ProductID=OrderDetails.ProductID LEFT JOIN Orders ON OrderDetails.OrderID=Orders.OrderID LEFT JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID'.

Body:
You're not to far off. Please try the following version tidied up with tables aliases:

SELECT Price*Quantity AS TotalCost, ProductName, SupplierName, ShipperName
FROM Products p
LEFT JOIN Suppliers s ON p.SupplierID = s.SupplierID
LEFT JOIN OrderDetails od ON p.ProductID = od.ProductID
LEFT JOIN Orders o ON od.OrderID = o.OrderID
LEFT JOIN Shippers sh ON o.ShipperID = sh.ShipperID
WHERE o.OrderID = 10248;

The only thing that is really changed is the WHERE clause.


问:
Launch one Coroutine at a time - Kotlin
We have a button in the UI, which, when pressed, will make some remote network call in its own coroutine. However, if the user spams the button for whatever reason, it is possible that the remote data might somehow get corrupted. We would like to prevent this by discarding all requests until the current one is completed.

There are many ways to do this. I have create a simple extension function on CoroutineScope to only launch if the CoroutineScope is not active. This is what I have created:

Extension Function

```<code>fun CoroutineScope.safeLaunch(dispatcher: CoroutineDispatcher, block: () -> Unit): Job {
    return if (!isActive) {
        launch(dispatcher) {
            block()
        }
    } else {
        launch {}
    }
}
</code>```

Example Use

```<code>fun loadNotifications() {
    viewModelScope.safeLaunch(IO) {
        getNotifications.invoke() // Suspend function invoke should only be from a coroutine or another suspend function
    }
}
</code>```

The problem is, the above won't compile as I get an error saying

Suspend function invoke should only be from a coroutine or another
suspend function

Does anyone know what I'm doing wrong or how to make it work?

答:
There are multiple problems with this code:

Fixing the error you mentioned is very easy and requires to only specify block as suspendable: block: suspend () -> Unit.

isActive doesn't mean the job/scope is actively running something, but that it hasn't finished. isActive in your example always returns true, even before launching any coroutine on it.

If your server can't handle concurrent actions, then you should really fix this on server side. Limiting the client isn't a proper fix as it can be still exploited by users. Also, you need to remember that multiple clients can perform the same action at the same time.

As you mentioned, there are several ways how this situation can be handled on the client side:

In the case of UI and the button, it is probably the best for the user experience to disable the button or overlay the screen/button with a loading indicator. It gives the user the feedback that the operation is running in the background and at the same time it fixes the problem with multiple calls to the server.

In general case, if we just need to limit concurrency and reject any additional tasks while the last one is still running, probably the easiest is to use Mutex:

private val scope = CoroutineScope(EmptyCoroutineContext)
private val mutex = Mutex()

fun safeLaunch(block: suspend () -> Unit) {
    if (!mutex.tryLock()) {
        return
    }

    scope.launch {
        try {
            block()
        } finally {
            mutex.unlock()
        }
    }
}
```

Note we need a separate mutex per scope or per the type of the task. <s>I don't think it is possible to create such utility as a generic extension function, working with any coroutine scope.</s> Actually, we can implement it in a very similar way to your original code, but by looking at the current job's children. Still, I consider such solution hacking and I discourage it.

Title: Launch one Coroutine at a time - Kotlin

Body:
We have a button in the UI, which, when pressed, will make some remote network call in its own coroutine. However, if the user spams the button for whatever reason, it is possible that the remote data might somehow get corrupted. We would like to prevent this by discarding all requests until the current one is completed.

There are many ways to do this. I have create a simple extension function on CoroutineScope to only launch if the CoroutineScope is not active. This is what I have created:

Extension Function

fun CoroutineScope.safeLaunch(dispatcher: CoroutineDispatcher, block: () -> Unit): Job {
    return if (!isActive) {
        launch(dispatcher) {
            block()
        }
    } else {
        launch {}
    }
}

Example Use

fun loadNotifications() {
    viewModelScope.safeLaunch(IO) {
        getNotifications.invoke() // Suspend function invoke should only be from a coroutine or another suspend function
    }
}

The problem is, the above won't compile as I get an error saying

Suspend function invoke should only be from a coroutine or another
suspend function

Does anyone know what I'm doing wrong or how to make it work?

Body:
There are multiple problems with this code:

Fixing the error you mentioned is very easy and requires to only specify block as suspendable: block: suspend () -> Unit.

isActive doesn't mean the job/scope is actively running something, but that it hasn't finished. isActive in your example always returns true, even before launching any coroutine on it.

If your server can't handle concurrent actions, then you should really fix this on server side. Limiting the client isn't a proper fix as it can be still exploited by users. Also, you need to remember that multiple clients can perform the same action at the same time.

As you mentioned, there are several ways how this situation can be handled on the client side:

In the case of UI and the button, it is probably the best for the user experience to disable the button or overlay the screen/button with a loading indicator. It gives the user the feedback that the operation is running in the background and at the same time it fixes the problem with multiple calls to the server.

In general case, if we just need to limit concurrency and reject any additional tasks while the last one is still running, probably the easiest is to use Mutex:

private val scope = CoroutineScope(EmptyCoroutineContext)
private val mutex = Mutex()

fun safeLaunch(block: suspend () -> Unit) {
    if (!mutex.tryLock()) {
        return
    }

    scope.launch {
        try {
            block()
        } finally {
            mutex.unlock()
        }
    }
}

Note we need a separate mutex per scope or per the type of the task. <s>I don't think it is possible to create such utility as a generic extension function, working with any coroutine scope.</s> Actually, we can implement it in a very similar way to your original code, but by looking at the current job's children. Still, I consider such solution hacking and I discourage it.


问:
jQuery .sortable is not a function
Even though I've followed the directions in the jQuery UI documentation, I'm getting the error that .sortable is not a function.

Here is my code:

```<code><div style="float: left;">
    <span class="caption" style="width: 255px; display: block;">
        Assigned Limits
    </span>
    <div class="assigned-limit-box">
        <ul id="limAssigned" class="ul-base">
        </ul>
    </div>
</div>
</code>```

This is my js:

```<code>$('#limAssigned').sortable();
</code>```

My jQuery js is loaded before my jQuery UI js.

What am I doing wrong?

答:
I have solved this using both the scripts.</p>

```<code><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
</code>```

Title: jQuery .sortable is not a function

Body:
Even though I've followed the directions in the jQuery UI documentation, I'm getting the error that .sortable is not a function.

Here is my code:

        Assigned Limits

This is my js:

$('#limAssigned').sortable();

My jQuery js is loaded before my jQuery UI js.

What am I doing wrong?

Body:
I have solved this using both the scripts.

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>


问:
Is there any way to fetch fullnames for ProfilePasswordPolicy records using API?
Is there any way to fetch 'fullname' for ProfilePasswordPolicy records? I am trying to update and read records of ProfilePasswordPolicy but getting the error shown in the screenshot.

SOAP API error

I can get fullnames using workbench but want to get it using programmatically (API).
Workbench

答:
You can retrieve fullNames with listMetadata action:</p>
```<code><?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <env:Header>
        <CallOptions xmlns="http://soap.sforce.com/2006/04/metadata">
            <client />
        </CallOptions>
        <SessionHeader xmlns="http://soap.sforce.com/2006/04/metadata">
            <sessionId>SESSION_ID_REMOVED</sessionId>
        </SessionHeader>
    </env:Header>
    <env:Body>
        <listMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <queries>
                <type>ProfilePasswordPolicy</type>
            </queries>
            <asOfVersion>53.0</asOfVersion>
        </listMetadata>
    </env:Body>
</env:Envelope>
</code>```

Body:
You can retrieve fullNames with listMetadata action:

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <env:Header>
        <CallOptions xmlns="http://soap.sforce.com/2006/04/metadata">
            <client />
        </CallOptions>
        <SessionHeader xmlns="http://soap.sforce.com/2006/04/metadata">
            <sessionId>SESSION_ID_REMOVED</sessionId>
        </SessionHeader>
    </env:Header>
    <env:Body>
        <listMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <queries>
                <type>ProfilePasswordPolicy</type>
            </queries>
            <asOfVersion>53.0</asOfVersion>
        </listMetadata>
    </env:Body>
</env:Envelope>


问:
Adding files to stripe connect
I'm trying to add some files (identity documents) to stripe to create a connected account, but I'm having trouble with uploading them from client side to stripe. My backend is in Node.js and the Stripe documentation says it should use this format:

```<code>const Stripe = require('stripe');
const stripe = Stripe('stripeAPIKEY');
var fp = fs.readFileSync('/path/to/a/file.jpg');
var file = await stripe.files.create({
  purpose: 'identity_document',
  file: {
    data: fp,
    name: 'file.jpg',
    type: 'image/jpg',
  },
});
</code>```

I need to upload the file data (the variable fp), but I can't seem to get the relevant path for when the user uploads their document in the client side in Javascript. Here is my function call to Stripe:

```<code>export const uploadPersonIdFile = async (identityDocument: any) => {
    const fp = fs.readFileSync(identityDocument);
    const personId = await stripe.files.create({
        purpose: 'identity_document',
        file: {
            data: fp,
            name: 'idDocument.jpg',
            type: 'image/jpg',
        },
    });
    return personId;
}
</code>```

My client side looks like this:

```<code>        const inpFileU = $("#utilityButton");
        const previewImage = $("#image-preview__image-U");
        const previewDefaultText = $("#image-preview__default-text-U");

        inpFileU.change(function(){
            const file = this.files[0];
            if(file){
                const reader = new FileReader();
                previewImage.css("display", "block");
                reader.addEventListener("load", function(){
                    previewImage.attr("src", this.result);
                });
                reader.readAsDataURL(file);
                utilityFileName = file.name;

                await uploadMerchantUtilityDocument({
                    utilityDocument: utilityFileName
                }).then((result) => {
                    /** @type {any} */
                    const data = result.data;
                    const textData = data.text;
                    console.log(JSON.stringify(data));
                    console.log(JSON.stringify(textData));
                }).catch((error) => {
                    console.log("Error message: " + error.message);
                    console.log("Error details: " + error.details);
                });

            } else {
              console.log('no file');
            }
        });
</code>```

I upload the file and then the error message response I keep getting is this:
Error: ENOENT: no such file or directory, open 'insuranceImage.jpeg'

How should I upload my file? I think my fp variable is wrong, but I don't know what to replace it with

答:
Ok, so after a while I was helped by a pro online. Here's what he did (because stripe's documentation isn't too great on file uploading)...

I created a base64 variable from FileReader(), which came from creating an array base64String = [] This array took hold of the result from reader.load, like so:

```<code>reader.addEventListener("load", function(){
      base64String.push(this.result);
});
</code>```

This base64String array was then used as the identityDocument variable for the backend function.

So my base64 variable in the client-side kept on starting with 'image/jpeg; base64,' and I needed to get rid of that. No point using the fs.readFileSync as we're not uploading a file to stripe, we're uploading raw base64 data. So, the following code in node.js fits in well to solve this:

```<code>const parts = utilityDocument.split(",");
const base64 = parts[1];
const buffer = Buffer.from(base64, "base64");
</code>```

so the full function that calls to stripe is so:

```<code>export const uploadPersonIdFile = async (uid: any, identityDocument: any) => {
    const parts = identityDocument.split(",");
    const base64 = parts[1];
    const buffer = Buffer.from(base64, "base64");
    const personId = await stripe.files.create({
        purpose: 'identity_document',
        file: {
            data: buffer,
            name: 'identity.jpg',
            type: 'image/jpg',
        },
    });
    await updateMerchantId(uid, { idDocument: personId.id });
    return personId;
}
</code>```

Title: Adding files to stripe connect

Body:
I'm trying to add some files (identity documents) to stripe to create a connected account, but I'm having trouble with uploading them from client side to stripe. My backend is in Node.js and the Stripe documentation says it should use this format:

const Stripe = require('stripe');
const stripe = Stripe('stripeAPIKEY');
var fp = fs.readFileSync('/path/to/a/file.jpg');
var file = await stripe.files.create({
  purpose: 'identity_document',
  file: {
    data: fp,
    name: 'file.jpg',
    type: 'image/jpg',
  },
});

I need to upload the file data (the variable fp), but I can't seem to get the relevant path for when the user uploads their document in the client side in Javascript. Here is my function call to Stripe:

export const uploadPersonIdFile = async (identityDocument: any) => {
    const fp = fs.readFileSync(identityDocument);
    const personId = await stripe.files.create({
        purpose: 'identity_document',
        file: {
            data: fp,
            name: 'idDocument.jpg',
            type: 'image/jpg',
        },
    });
    return personId;
}

My client side looks like this:

        const inpFileU = $("#utilityButton");
        const previewImage = $("#image-preview__image-U");
        const previewDefaultText = $("#image-preview__default-text-U");

        inpFileU.change(function(){
            const file = this.files[0];
            if(file){
                const reader = new FileReader();
                previewImage.css("display", "block");
                reader.addEventListener("load", function(){
                    previewImage.attr("src", this.result);
                });
                reader.readAsDataURL(file);
                utilityFileName = file.name;

                await uploadMerchantUtilityDocument({
                    utilityDocument: utilityFileName
                }).then((result) => {
                    /** @type {any} */
                    const data = result.data;
                    const textData = data.text;
                    console.log(JSON.stringify(data));
                    console.log(JSON.stringify(textData));
                }).catch((error) => {
                    console.log("Error message: " + error.message);
                    console.log("Error details: " + error.details);
                });

            } else {
              console.log('no file');
            }
        });

I upload the file and then the error message response I keep getting is this:
Error: ENOENT: no such file or directory, open 'insuranceImage.jpeg'

How should I upload my file? I think my fp variable is wrong, but I don't know what to replace it with

Body:
Ok, so after a while I was helped by a pro online. Here's what he did (because stripe's documentation isn't too great on file uploading)...

I created a base64 variable from FileReader(), which came from creating an array base64String = [] This array took hold of the result from reader.load, like so:

reader.addEventListener("load", function(){
      base64String.push(this.result);
});

This base64String array was then used as the identityDocument variable for the backend function.

So my base64 variable in the client-side kept on starting with 'image/jpeg; base64,' and I needed to get rid of that. No point using the fs.readFileSync as we're not uploading a file to stripe, we're uploading raw base64 data. So, the following code in node.js fits in well to solve this:

const parts = utilityDocument.split(",");
const base64 = parts[1];
const buffer = Buffer.from(base64, "base64");

so the full function that calls to stripe is so:

export const uploadPersonIdFile = async (uid: any, identityDocument: any) => {
    const parts = identityDocument.split(",");
    const base64 = parts[1];
    const buffer = Buffer.from(base64, "base64");
    const personId = await stripe.files.create({
        purpose: 'identity_document',
        file: {
            data: buffer,
            name: 'identity.jpg',
            type: 'image/jpg',
        },
    });
    await updateMerchantId(uid, { idDocument: personId.id });
    return personId;
}


问:
codeigniter show (my)sql insert warnings
I have this controller and model:

```<code>class MyModel extends CI_Model
{
  public function __construct()
  {
    parent::__construct();
  }
  public function insert($data_array)
  {
    $this->db->insert('table', $data_array);

    if($this->db->affected_rows() == 1) {
      return true;
    }
    return false;
  }
}

class Panel extends CI_Controller
{
  public function submitPrimer()
  {
    // evaluate data
    $this->load->library('form_validation');
    $this->load->model('MyModel', 'mymodel');

    // validate, set_rules....

    $data = array(
     'column1'  => $value1;
     // .....
    );

    if($this->mymodel->insert($data)) {
      echo "inserted";
    }
  }
}
</code>```

Is there any kind of $this->db->show_warnings() in CI. In mysql console there is 'show warnings' command which says for example if you have datatype: float and you insert like this: insert into table (attribute_float) values(''). The proper way would be insert into table (attribute_float) values(NULL).

I also am wondering if 'insert' should go to models. I always assumed only 'select/get' data would go.

答:
As much as I'm aware, and from user guide, I don't think that Codeigniter has such a function, for such validation use form_validation library, it's pretty good.

As for insert/edit/delete, they usually go to the model, but it depends on you.

Body:
I have this controller and model:

class MyModel extends CI_Model
{
  public function __construct()
  {
    parent::__construct();
  }
  public function insert($data_array)
  {
    $this->db->insert('table', $data_array);

    if($this->db->affected_rows() == 1) {
      return true;
    }
    return false;
  }
}

class Panel extends CI_Controller
{
  public function submitPrimer()
  {
    // evaluate data
    $this->load->library('form_validation');
    $this->load->model('MyModel', 'mymodel');

    // validate, set_rules....

    $data = array(
     'column1'  => $value1;
     // .....
    );

    if($this->mymodel->insert($data)) {
      echo "inserted";
    }
  }
}

Is there any kind of $this->db->show_warnings() in CI. In mysql console there is 'show warnings' command which says for example if you have datatype: float and you insert like this: insert into table (attribute_float) values(''). The proper way would be insert into table (attribute_float) values(NULL).

I also am wondering if 'insert' should go to models. I always assumed only 'select/get' data would go.


问:
Infer schema from json string
I have this dataframe :

```<code>cSchema = StructType([StructField("id1", StringType()), StructField("id2", StringType()), StructField("params", StringType())\
                      ,StructField("Col2", IntegerType())])

test_list = [[1, 2, '{"param1": "val1", "param2": "val2"}', 1], [1, 3, '{"param1": "val4", "param2": "val5"}', 3]]

df = spark.createDataFrame(test_list,schema=cSchema)

+---+---+--------------------+----+
|id1|id2|              params|Col2|
+---+---+--------------------+----+
|  1|  2|{"param1": "val1"...|   1|
|  1|  3|{"param1": "val4"...|   3|
+---+---+--------------------+----+
</code>```

I want to explode params into columns :

```<code>+---+---+----+------+------+
|id1|id2|Col2|param1|param2|
+---+---+----+------+------+
|  1|  2|   1|  val1|  val2|
|  1|  3|   3|  val4|  val5|
+---+---+----+------+------+
</code>```

So I coded this :

```<code>schema2 = StructType([StructField("param1", StringType()), StructField("param2", StringType())])

df.withColumn(
  "params", from_json("params", schema2)
).select(
  col('id1'), col('id2'),col('Col2'), col('params.*')
).show()
</code>```

The problem is that params schema is dynamic (variable schema2), he may change from one execution to another, so I need to infer the schema dynamically (It's ok to have all columns with String Type)... And I can't figure out of a way to do this..

Can anyone help me up with that please ?

答:
If you want to get a larger sample of data to compare, you can read the params field into a list, convert that to an RDD, then read using "spark.read.json()"

```<code>params_list = df.select("params").rdd.flatMap(lambda x: x).collect()
params_rdd = sc.parallelize(params_list)
spark.read.json(params_rdd).schema
</code>```

Caveat here being that you probably don't want to load too much data, as it's all being stuffed into local variables. Try taking the top 1000 or whatever an appropriate sample size may be.

Title: Infer schema from json string

Body:
I have this dataframe :

cSchema = StructType([StructField("id1", StringType()), StructField("id2", StringType()), StructField("params", StringType())\
                      ,StructField("Col2", IntegerType())])

test_list = [[1, 2, '{"param1": "val1", "param2": "val2"}', 1], [1, 3, '{"param1": "val4", "param2": "val5"}', 3]]

df = spark.createDataFrame(test_list,schema=cSchema)

+---+---+--------------------+----+
|id1|id2|              params|Col2|
+---+---+--------------------+----+
|  1|  2|{"param1": "val1"...|   1|
|  1|  3|{"param1": "val4"...|   3|
+---+---+--------------------+----+

I want to explode params into columns :

+---+---+----+------+------+
|id1|id2|Col2|param1|param2|
+---+---+----+------+------+
|  1|  2|   1|  val1|  val2|
|  1|  3|   3|  val4|  val5|
+---+---+----+------+------+

So I coded this :

schema2 = StructType([StructField("param1", StringType()), StructField("param2", StringType())])

df.withColumn(
  "params", from_json("params", schema2)
).select(
  col('id1'), col('id2'),col('Col2'), col('params.*')
).show()

The problem is that params schema is dynamic (variable schema2), he may change from one execution to another, so I need to infer the schema dynamically (It's ok to have all columns with String Type)... And I can't figure out of a way to do this..

Can anyone help me up with that please ?

Body:
If you want to get a larger sample of data to compare, you can read the params field into a list, convert that to an RDD, then read using "spark.read.json()"

params_list = df.select("params").rdd.flatMap(lambda x: x).collect()
params_rdd = sc.parallelize(params_list)
spark.read.json(params_rdd).schema

Caveat here being that you probably don't want to load too much data, as it's all being stuffed into local variables. Try taking the top 1000 or whatever an appropriate sample size may be.


问:
I have a hard time understanding the purpose of a "backing property"
I am learning Kotlin right now. For context, I am a Java developer for +10 years.

I stumbled upon the concept of backing properties. As I understand it, the problem to be solved is this: I have a property in a class. I want this property to be mutable and visible only in the containing class, so I declare it as private var. The property should only be modified in the containing class, but it should be readable outside the class. So, the Kotlin docs propose something like this:

private var _word = "test"
val word: String
   get() = _word
```
<p>This works and fulfills the above requirements, but this looks a bit odd, for a Java developer. In Java, we only need 1 field (there is no such thing as a property in Java):</p>
```private String word = "test";

public String getWord() {
   return word;
}
```
<p>AFAIK, same result.</p>
<p>Today I learned that in Kotlin, I simply can make a setter private. So what about this Kotlin code:</p>
```var word = "test"
     private set
```

All requirements fulfilled, much more concise code.

Im I missing something? Why do I need a backing property?

答:
One other use for backing properties is to allow you to store a null value internally, but expose a non-null type, and provide some fallback value (which you might not want to store, if null has a specific meaning).

Here's the example from the docs:

```<code>private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }
</code>```

What's happening here is your typical singleton getInstance()-style accessor, where if the object isn't instantiated yet, you create and store it before returning it. Unlike a lazy delegate, it's internally a var meaning it can be replaced with a new Map, or null in this example (with some handler code anticipating a potential concurrency issue)

The caller sees none of this though - outwardly it's just a plain val that returns a non-null Map, accessed like any other property, with no need to handle a potential null. All that nullability is abstracted away, it's an internal detail.

You'd have to do the same thing in Java (let's say if you wanted to use the @NonNull annotation on your getter), creating an internal variable and wrangling its state. It's just that in Kotlin, you get a basic backing field "for free" (if you even need one) and it's only if that isn't adequately needs-suiting that you need to start creating and poking at properties yourself

Body:
I am learning Kotlin right now. For context, I am a Java developer for +10 years.

I stumbled upon the concept of backing properties. As I understand it, the problem to be solved is this: I have a property in a class. I want this property to be mutable and visible only in the containing class, so I declare it as private var. The property should only be modified in the containing class, but it should be readable outside the class. So, the Kotlin docs propose something like this:

private var _word = "test"
val word: String
   get() = _word

This works and fulfills the above requirements, but this looks a bit odd, for a Java developer. In Java, we only need 1 field (there is no such thing as a property in Java):

private String word = "test";

public String getWord() {
   return word;
}

AFAIK, same result.

Today I learned that in Kotlin, I simply can make a setter private. So what about this Kotlin code:

var word = "test"
     private set

All requirements fulfilled, much more concise code.

Im I missing something? Why do I need a backing property?

Body:
One other use for backing properties is to allow you to store a null value internally, but expose a non-null type, and provide some fallback value (which you might not want to store, if null has a specific meaning).

Here's the example from the docs:

private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }

What's happening here is your typical singleton getInstance()-style accessor, where if the object isn't instantiated yet, you create and store it before returning it. Unlike a lazy delegate, it's internally a var meaning it can be replaced with a new Map, or null in this example (with some handler code anticipating a potential concurrency issue)

The caller sees none of this though - outwardly it's just a plain val that returns a non-null Map, accessed like any other property, with no need to handle a potential null. All that nullability is abstracted away, it's an internal detail.

You'd have to do the same thing in Java (let's say if you wanted to use the @NonNull annotation on your getter), creating an internal variable and wrangling its state. It's just that in Kotlin, you get a basic backing field "for free" (if you even need one) and it's only if that isn't adequately needs-suiting that you need to start creating and poking at properties yourself


问:
MSOLAP Version 15.1.6x.2x
I am trying to find installer for MSOLAP Version 15.1.6x.2x, which is an older version of what is currently available from here.

I have scoured internet and I am not able to find this version for download. The newer version doesn't work with the solution I currently have. SSMS apparently installs this driver but SSMS is not an option in my case.

Can anyone point where this driver might be available?

答:
You can get older versions from the SQL Server Feature Packs, eg
Microsoft® SQL Server® 2016 Service Pack 3 Feature Pack</p>

Title: MSOLAP Version 15.1.6x.2x


问:
ViewStub must have a non-null ViewGroup viewParent
I am using ViewStubs to load show data in my layout. Since I'm using ButterKnife to bind the layout components, I have custom classes that hold the individual viewstub layout's components, e.g one such viewstub is as follows.

```<code> <ViewStub
      android:id="@+id/featuredContentStub"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:inflatedId="@+id/featuredContent"
      android:layout="@layout/featured_content" />
</code>```

The class to handle the @layout/featured_content components is as follows:

```<code>public class FeaturedContentView {
        @BindView(R.id.art)
        ImageView art;
        @BindView(R.id.shade)
        View shade;
        @BindView(R.id.title)
        TextView featuredTitle;
        @BindView(R.id.performer)
        TextView performer;
        @BindView(R.id.featured_title)
        KerningTextView featuredText;
        @BindView(R.id.play_button)
        Button play;
        @BindView(R.id.shareText)
        TextView shareText;
        @BindView(R.id.addToFavorites)
        ImageView addToFavs;

        FeaturedContentView(View view) {
            ButterKnife.bind(this, view);
        }
    }
</code>```

I inflate the layout like this:

```<code>if (viewstub != null) {
        View view = viewstub.inflate();
        featuredContentView = new FeaturedContentView(view);
}
</code>```

The above method is called in two different places in my fragment. It inflates correctly the first time but fails the second time citing java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent.

How can i handle this situation.

答:
If you look at source code of the viewstub.inflate() function, once the view referenced by the viewstub is inflated it removes the layout reference from the viewstub.

Hence you'll always get this error when viewstub.inflate gets called the second time. Here's how to prevent it:

```<code>if (mViewStub.getParent() != null) {
   mViewStub.inflate();
} else {
   mViewStub.setVisibility(View.VISIBLE);
}
</code>```

Body:
I am using ViewStubs to load show data in my layout. Since I'm using ButterKnife to bind the layout components, I have custom classes that hold the individual viewstub layout's components, e.g one such viewstub is as follows.

 <ViewStub
      android:id="@+id/featuredContentStub"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:inflatedId="@+id/featuredContent"
      android:layout="@layout/featured_content" />

The class to handle the @layout/featured_content components is as follows:

public class FeaturedContentView {
        @BindView(R.id.art)
        ImageView art;
        @BindView(R.id.shade)
        View shade;
        @BindView(R.id.title)
        TextView featuredTitle;
        @BindView(R.id.performer)
        TextView performer;
        @BindView(R.id.featured_title)
        KerningTextView featuredText;
        @BindView(R.id.play_button)
        Button play;
        @BindView(R.id.shareText)
        TextView shareText;
        @BindView(R.id.addToFavorites)
        ImageView addToFavs;

        FeaturedContentView(View view) {
            ButterKnife.bind(this, view);
        }
    }

I inflate the layout like this:

if (viewstub != null) {
        View view = viewstub.inflate();
        featuredContentView = new FeaturedContentView(view);
}

The above method is called in two different places in my fragment. It inflates correctly the first time but fails the second time citing java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent.

How can i handle this situation.

Body:
If you look at source code of the viewstub.inflate() function, once the view referenced by the viewstub is inflated it removes the layout reference from the viewstub.

Hence you'll always get this error when viewstub.inflate gets called the second time. Here's how to prevent it:

if (mViewStub.getParent() != null) {
   mViewStub.inflate();
} else {
   mViewStub.setVisibility(View.VISIBLE);
}


问:
Which class can I use to pass a "RecordSet" between an WinForm VB.Net EXE program and a classes DLL?
I have developped a VB.Net DLL that can read Postgres, Oracle and OleDb.

To allow this DLL to execute some SQL commands, I pass it a Connection object and I use it to execute some SQL SELECT command.

My problem now is that I want to pass all data contained in a GridView object that contains data obtained using a SQL command in EXE program (not in DLL) and that user can have changed.

Which type of object can I pass considering following constraints ?

argument passed cannot be a WinForm control as DataGridView (no Winform object in DLL)

another database's table cannot be filled with DataGridView content (not performant)

class used must be part of an .Net assembly (not a COM, too old technology)

Until now, the only solution found consist of using ADO or Microsoft ActiveX Data Object Record Set, but this class is not an .Net assembly and solution found on DataBase Journal does'nt work because Items property of Field class is Read Only.

Here is my code

```<code>    Dim rstADO As ADODB.Recordset
    rstADO = New ADODB.Recordset
    With rstADO
        .Fields.Append("EmployeeID", ADODB.DataTypeEnum.adInteger, 0, ADODB.FieldAttributeEnum.adFldKeyColumn)
        .Fields.Append("FirstName", ADODB.DataTypeEnum.adVarChar, 10, ADODB.FieldAttributeEnum.adFldMayBeNull)

        .CursorType = ADODB.CursorTypeEnum.adOpenKeyset
        .CursorLocation = ADODB.CursorLocationEnum.adUseClient
        .LockType = ADODB.LockTypeEnum.adLockPessimistic
        .Open()

        For Each row As DataGridViewRow In grid.Rows
            .AddNew()
            For i = 0 To grid.Columns.Count - 1
                .Fields(i) = row.Cells(i).Value
            Next i
            .Update()
        Next row
    End With
</code>```

Line .Fields(i) dispay following error
BC30526: 'Item' property is 'ReadOnly'.

Which class can I use ?

答:
I have used solution proposed by tramex user.

I want to extract all columns except Edit et PDF columns and I need to add a special column named cash based on another column present in DataGridView.

Here is my code

```<code>Dim dt As New DataTable
Dim sName As String
Dim type As Type

Dim oSKipList() As String = {"Edit", "PDF"}
For Each col As DataGridViewColumn In grid.Columns
    sName = col.Name.Replace("Col_", "")
    If Not oSKipList.Contains(sName) Then
        type = col.CellTemplate.FormattedValueType
        dt.Columns.Add(sName, type)
    End If
Next col
dt.Columns.Add("cash", Type.GetType("System.String"))

For Each row As DataGridViewRow In grid.Rows
    Dim dr As DataRow = dt.NewRow
    Dim n = 0
    For Each col As DataGridViewColumn In grid.Columns
        sName = col.Name.Replace("Col_", "")
        If Not oSKipList.Contains(sName) Then
            Dim i = col.Index
            dr(n) = row.Cells(i).Value
            n += 1
        End If
    Next col
    dr(n) = IIf(dr("Account") = "-", "CASH", "")
    dt.Rows.Add(dr)
Next row

oExcelReport.SetDataTable(dt)
</code>```

The first part of this code initialize Columns and the second part initialize Rows.

This code is working fine on my program.

Body:
I have developped a VB.Net DLL that can read Postgres, Oracle and OleDb.

To allow this DLL to execute some SQL commands, I pass it a Connection object and I use it to execute some SQL SELECT command.

My problem now is that I want to pass all data contained in a GridView object that contains data obtained using a SQL command in EXE program (not in DLL) and that user can have changed.

Which type of object can I pass considering following constraints ?

argument passed cannot be a WinForm control as DataGridView (no Winform object in DLL)

another database's table cannot be filled with DataGridView content (not performant)

class used must be part of an .Net assembly (not a COM, too old technology)

Until now, the only solution found consist of using ADO or Microsoft ActiveX Data Object Record Set, but this class is not an .Net assembly and solution found on DataBase Journal does'nt work because Items property of Field class is Read Only.

Here is my code

    Dim rstADO As ADODB.Recordset
    rstADO = New ADODB.Recordset
    With rstADO
        .Fields.Append("EmployeeID", ADODB.DataTypeEnum.adInteger, 0, ADODB.FieldAttributeEnum.adFldKeyColumn)
        .Fields.Append("FirstName", ADODB.DataTypeEnum.adVarChar, 10, ADODB.FieldAttributeEnum.adFldMayBeNull)

        .CursorType = ADODB.CursorTypeEnum.adOpenKeyset
        .CursorLocation = ADODB.CursorLocationEnum.adUseClient
        .LockType = ADODB.LockTypeEnum.adLockPessimistic
        .Open()

        For Each row As DataGridViewRow In grid.Rows
            .AddNew()
            For i = 0 To grid.Columns.Count - 1
                .Fields(i) = row.Cells(i).Value
            Next i
            .Update()
        Next row
    End With

Line .Fields(i) dispay following error
BC30526: 'Item' property is 'ReadOnly'.

Which class can I use ?

Body:
I have used solution proposed by tramex user.

I want to extract all columns except Edit et PDF columns and I need to add a special column named cash based on another column present in DataGridView.

Here is my code

Dim dt As New DataTable
Dim sName As String
Dim type As Type

Dim oSKipList() As String = {"Edit", "PDF"}
For Each col As DataGridViewColumn In grid.Columns
    sName = col.Name.Replace("Col_", "")
    If Not oSKipList.Contains(sName) Then
        type = col.CellTemplate.FormattedValueType
        dt.Columns.Add(sName, type)
    End If
Next col
dt.Columns.Add("cash", Type.GetType("System.String"))

For Each row As DataGridViewRow In grid.Rows
    Dim dr As DataRow = dt.NewRow
    Dim n = 0
    For Each col As DataGridViewColumn In grid.Columns
        sName = col.Name.Replace("Col_", "")
        If Not oSKipList.Contains(sName) Then
            Dim i = col.Index
            dr(n) = row.Cells(i).Value
            n += 1
        End If
    Next col
    dr(n) = IIf(dr("Account") = "-", "CASH", "")
    dt.Rows.Add(dr)
Next row

oExcelReport.SetDataTable(dt)

The first part of this code initialize Columns and the second part initialize Rows.

This code is working fine on my program.


问:
Class with virtual function, when derived from QObject, leads to linking error
Following is the code that works fine

class HttpService {
public:
    virtual ~HttpService(); // implemented in .cpp
protected:
    HttpService(struct MHD_Connection *conn) {}
};
class HttpFileService : public HttpService
{
public:
    virtual ~HttpFileService() ; // implemented in .cpp
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};
```

<p>Now, when I make <code>HttpService</code> a derived class of <code>QObject</code>, like below:</p>

<pre class="lang-c prettyprint-override"><code>#include <QObject>                      // change #1
class HttpService  : public QObject {   // change #2
    Q_OBJECT                            // change #3
public:
    virtual ~HttpService();
protected:
    HttpService(struct MHD_Connection *conn) {}
};

class HttpFileService : public HttpService {
    Q_OBJECT                            // change #4
public:
    virtual ~HttpFileService() ;
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};
</code>```

I encounter the following linking error:

```<code>Undefined symbols for architecture x86_64:
  "vtable for HttpService", referenced from:
      HttpService::~HttpService()in httpservice.o
</code>```

Changing HttpService's constructor to the following doesn't help either

```<code>explicit HttpService(QObject *parent = 0) : QObject(parent)
</code>```

答: Are you linking to the correct qt libraries?</p>

Body:
Following is the code that works fine

class HttpService {
public:
    virtual ~HttpService(); // implemented in .cpp
protected:
    HttpService(struct MHD_Connection *conn) {}
};
class HttpFileService : public HttpService
{
public:
    virtual ~HttpFileService() ; // implemented in .cpp
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};

Now, when I make HttpService a derived class of QObject, like below:

#include <QObject>                      // change #1
class HttpService  : public QObject {   // change #2
    Q_OBJECT                            // change #3
public:
    virtual ~HttpService();
protected:
    HttpService(struct MHD_Connection *conn) {}
};

class HttpFileService : public HttpService {
    Q_OBJECT                            // change #4
public:
    virtual ~HttpFileService() ;
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};

I encounter the following linking error:

Undefined symbols for architecture x86_64:
  "vtable for HttpService", referenced from:
      HttpService::~HttpService()in httpservice.o

Changing HttpService's constructor to the following doesn't help either

explicit HttpService(QObject *parent = 0) : QObject(parent)


问:
dplyr: How to rearrange this dataframe and create new columns by extracting parts of other columns
Let's say I have this dataframe

```<code>> a
  T..Gene.names Intensity.Mut_125 Intensity.Mut_250 Intensity.Mut.1000 Intensity.Mut.500
1          NCAN               NaN           25.6628            23.8427               NaN
2          AMBP           22.8276           27.0801            25.4740           23.5596
3          CHGB           25.4463           30.0065            27.8181           27.3170
4           APP           25.0346           29.7784            27.0848           24.7314
</code>```

I need to re-arrange my dataframe so each a$T..Gene.names correspond to a new column. Then, I need a new column called a$sample that extracts the word between Intensity and the number (either 125, 250, 500, 1000 or 2000). An issue is that this word and following number is separated by either . or _ Finally, I need a column named a$volume that correspond to the number. NA should be converted to 0.

I tried several attempts with pivot_longer and pivot_wider but this is above my current skill level.

Expected output

```<code>sample     volume       NCAN         AMBP        CHGB        APP
   Mut        125          0      22.8276     25.4463    25.0346
   Mut        250    25.6638      27.0801     30.0065    29.7784
   Mut        500          0      23.5596     27.3170    24.7314
   Mut       1000    23.8427      25.4740     27.8181    27.0848
</code>```

I prefer a dplyr-solution

```<code>a <- structure(list(T..Gene.names = c("NCAN", "AMBP", "CHGB", "APP"
), Intensity.Mut_125 = c(NaN, 22.8276, 25.4463, 25.0346), Intensity.Mut_250 = c(25.6628,
27.0801, 30.0065, 29.7784), Intensity.Mut.1000 = c(23.8427, 25.474,
27.8181, 27.0848), Intensity.Mut.500 = c(NaN, 23.5596, 27.317,
24.7314)), row.names = c(NA, 4L), class = "data.frame")
</code>```

Body:
Let's say I have this dataframe

> a
  T..Gene.names Intensity.Mut_125 Intensity.Mut_250 Intensity.Mut.1000 Intensity.Mut.500
1          NCAN               NaN           25.6628            23.8427               NaN
2          AMBP           22.8276           27.0801            25.4740           23.5596
3          CHGB           25.4463           30.0065            27.8181           27.3170
4           APP           25.0346           29.7784            27.0848           24.7314

I need to re-arrange my dataframe so each a$T..Gene.names correspond to a new column. Then, I need a new column called a$sample that extracts the word between Intensity and the number (either 125, 250, 500, 1000 or 2000). An issue is that this word and following number is separated by either . or _ Finally, I need a column named a$volume that correspond to the number. NA should be converted to 0.

I tried several attempts with pivot_longer and pivot_wider but this is above my current skill level.

Expected output

sample     volume       NCAN         AMBP        CHGB        APP
   Mut        125          0      22.8276     25.4463    25.0346
   Mut        250    25.6638      27.0801     30.0065    29.7784
   Mut        500          0      23.5596     27.3170    24.7314
   Mut       1000    23.8427      25.4740     27.8181    27.0848

I prefer a dplyr-solution

a <- structure(list(T..Gene.names = c("NCAN", "AMBP", "CHGB", "APP"
), Intensity.Mut_125 = c(NaN, 22.8276, 25.4463, 25.0346), Intensity.Mut_250 = c(25.6628,
27.0801, 30.0065, 29.7784), Intensity.Mut.1000 = c(23.8427, 25.474,
27.8181, 27.0848), Intensity.Mut.500 = c(NaN, 23.5596, 27.317,
24.7314)), row.names = c(NA, 4L), class = "data.frame")

Body:
reshape2::recast(a, variable~T..Gene.names,fill = 0) %>%
  separate(variable, c('type','sample', 'volume'))

       type sample volume    AMBP     APP    CHGB    NCAN
1 Intensity    Mut    125 22.8276 25.0346 25.4463  0.0000
2 Intensity    Mut    250 27.0801 29.7784 30.0065 25.6628
3 Intensity    Mut   1000 25.4740 27.0848 27.8181 23.8427
4 Intensity    Mut    500 23.5596 24.7314 27.3170  0.0000


问:
Timeout doesn't time out in AsyncRead
I'm trying to implement an async read wrapper that will add read timeout functionality. The objective is that the API is plain AsyncRead. In other words, I don't want to add io.read(buf).timeout(t) everywehere in the code. Instead, the read instance itself should return the appropriate io::ErrorKind::TimedOut after the given timeout expires.

I can't poll the delay to Ready though. It's always Pending. I've tried with async-std, futures, smol-timeout - the same result. While the timeout does trigger when awaited, it just doesn't when polled. I know timeouts aren't easy. Something needs to wake it up. What am I doing wrong? How to pull this through?

use async_std::{
    future::Future,
    io,
    pin::Pin,
    task::{sleep, Context, Poll},
};
use std::time::Duration;

pub struct PrudentIo<IO> {
    expired: Option<Pin<Box<dyn Future<Output = ()> + Sync + Send>>>,
    timeout: Duration,
    io: IO,
}

impl<IO> PrudentIo<IO> {
    pub fn new(timeout: Duration, io: IO) -> Self {
        PrudentIo {
            expired: None,
            timeout,
            io,
        }
    }
}

fn delay(t: Duration) -> Option<Pin<Box<dyn Future<Output = ()> + Sync + Send + 'static>>> {
    if t.is_zero() {
        return None;
    }
    Some(Box::pin(sleep(t)))
}

impl<IO: io::Read + Unpin> io::Read for PrudentIo<IO> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        if let Some(ref mut expired) = self.expired {
            match expired.as_mut().poll(cx) {
                Poll::Ready(_) => {
                    println!("expired ready");
                    // too much time passed since last read/write
                    return Poll::Ready(Err(io::ErrorKind::TimedOut.into()));
                }
                Poll::Pending => {
                    println!("expired pending");
                    // in good time
                }
            }
        }

        let res = Pin::new(&mut self.io).poll_read(cx, buf);
        println!("read {:?}", res);

        match res {
            Poll::Pending => {
                if self.expired.is_none() {
                    // No data, start checking for a timeout
                    self.expired = delay(self.timeout);
                }
            }
            Poll::Ready(_) => self.expired = None,
        }

        res
    }
}
impl<IO: io::Write + Unpin> io::Write for PrudentIo<IO> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.io).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.io).poll_flush(cx)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.io).poll_close(cx)
    }
}

#[cfg(test)]
mod io_tests {
    use super::*;
    use async_std::io::ReadExt;
    use async_std::prelude::FutureExt;
    use async_std::{
        io::{copy, Cursor},
        net::TcpStream,
    };
    use std::time::Duration;

    #[async_std::test]
    async fn fail_read_after_timeout() -> io::Result<()> {
        let mut output = b"______".to_vec();
        let io = PendIo;
        let mut io = PrudentIo::new(Duration::from_millis(5), io);
        let mut io = Pin::new(&mut io);
        insta::assert_debug_snapshot!(io.read(&mut output[..]).timeout(Duration::from_secs(1)).await,@"Ok(io::Err(timeou))");
        Ok(())
    }
    #[async_std::test]
    async fn timeout_expires() {
        let later = delay(Duration::from_millis(1)).expect("some").await;
        insta::assert_debug_snapshot!(later,@r"()");
    }
    /// Mock IO always pending
    struct PendIo;
    impl io::Read for PendIo {
        fn poll_read(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            _buf: &mut [u8],
        ) -> Poll<futures_io::Result<usize>> {
            Poll::Pending
        }
    }
    impl io::Write for PendIo {
        fn poll_write(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            _buf: &[u8],
        ) -> Poll<futures_io::Result<usize>> {
            Poll::Pending
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<futures_io::Result<()>> {
            Poll::Pending
        }

        fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<futures_io::Result<()>> {
            Poll::Pending
        }
    }
}

```

答:
Async timeouts work as follows:

You create the timeout future.

The runtime calls poll into the timeout, it checks whether the timeout has expired.

If it is expired, it returns Ready and done.

If it is not expired, it somehow registers a callback for when the right time has passed it calls cx.waker().wake(), or similar.

When the time has passed, the callback from #4 is invoked, that calls wake() in the proper waker, which instructs the runtime to call poll again.

This time poll will return Ready. Done!

The problem with your code is that you create the delay from inside the poll() implementation: self.expired = delay(self.timeout);. But then you return Pending without polling the timeout even once. This way, there is no callback registered anywhere that would call the Waker. No waker, no timeout.

I see several solutions:

A. Do not initialize PrudentIo::expired to None but create the timeout directly in the constructor. That way the timeout will always be polled before the io at least once, and it will be woken. But you will create a timeout always, even if it is not actually needed.

B. When creating the timeout do a recursive poll:

```<code>Poll::Pending => {
    if self.expired.is_none() {
        // No data, start checking for a timeout
        self.expired = delay(self.timeout);
        return self.poll_read(cx, buf);
    }
</code>```

This will call the io twice, unnecesarily, so it may not be optimal.

C. Add a call to poll after creating the timeout:

```<code>Poll::Pending => {
    if self.expired.is_none() {
        // No data, start checking for a timeout
        self.expired = delay(self.timeout);
        self.expired.as_mut().unwrap().as_mut().poll(cx);
    }
</code>```

Maybe you should match the output of poll in case it returns Ready, but hey, it's a new timeout, it's probably pending yet, and it seems to work nicely.

Title: Timeout doesn't time out in AsyncRead

Body:
Async timeouts work as follows:

You create the timeout future.

The runtime calls poll into the timeout, it checks whether the timeout has expired.

If it is expired, it returns Ready and done.

If it is not expired, it somehow registers a callback for when the right time has passed it calls cx.waker().wake(), or similar.

When the time has passed, the callback from #4 is invoked, that calls wake() in the proper waker, which instructs the runtime to call poll again.

This time poll will return Ready. Done!

The problem with your code is that you create the delay from inside the poll() implementation: self.expired = delay(self.timeout);. But then you return Pending without polling the timeout even once. This way, there is no callback registered anywhere that would call the Waker. No waker, no timeout.

I see several solutions:

A. Do not initialize PrudentIo::expired to None but create the timeout directly in the constructor. That way the timeout will always be polled before the io at least once, and it will be woken. But you will create a timeout always, even if it is not actually needed.

B. When creating the timeout do a recursive poll:

Poll::Pending => {
    if self.expired.is_none() {
        // No data, start checking for a timeout
        self.expired = delay(self.timeout);
        return self.poll_read(cx, buf);
    }

This will call the io twice, unnecesarily, so it may not be optimal.

C. Add a call to poll after creating the timeout:

Poll::Pending => {
    if self.expired.is_none() {
        // No data, start checking for a timeout
        self.expired = delay(self.timeout);
        self.expired.as_mut().unwrap().as_mut().poll(cx);
    }

Maybe you should match the output of poll in case it returns Ready, but hey, it's a new timeout, it's probably pending yet, and it seems to work nicely.


问:
Scheduling job to start 9.00 am and then every 15 minutes in autosys
I'm new to autosys.
I wanted to plan a work that starts at 9.00 and runs every 15 minutes. Is this the proper syntax?</p>
```<code>start.times=start_times: "09:00"
start_mins:00,15,30,45
</code>```

答:
You need a run window.
A run window cannot wrap around midnight or whatever time you start your new day processing. The default is midnight
If you want a start time for a job to run every 15 minutes then use this

start_mins: 00,15,30,45

run_window: "09:00-22:00"

22:00 can be whatever you want or as far as 23:59 if your new day processing starts at midnight.

Body:
I'm new to autosys.
I wanted to plan a work that starts at 9.00 and runs every 15 minutes. Is this the proper syntax?

start.times=start_times: "09:00"
start_mins:00,15,30,45


问:
Using pixel values, how to reduce image size to an arbitrary fraction (say 0.8 or 0.7 or 0.6 times)?
I am trying to modify projection of image by manipulating pixel values.

To do this, I need to reduce the size of different portions of the image by different fractions.

As an example, if the image width is 1000 pixels, I may need to reduce the pixel numbers 600 - 800 (200 pixels) to 150 pixels in the final image, and pixel numbers 800 - 1000 (200 pixels) to 100 pixels in the final image.

For the second case (reducing 200 pixels to 100 pixels), I can take a mean of 2 pixels at a time to get a pixel in the final image. But how to do the first one (reducing 200 pixels to 150 pixels)?

I am very grateful for your time.

答:
A fairly good quality downsampling can be obtained as follows:

Overlay an w x h grid (desired resolution) over the W x H grid of the original image (available resolution).

A low resolution cell overlaps several higher resolution cells, and you can estimate the color of the cell as a weighted average, based on the areas of the intersections (see figure).

In the case of a reduction factor 0.5, you indeed end up with 2x2 pixel averages. With factors between 0.5 and 1, you overlap four pixels and the weighted average corresponds to bilinear interpolation. For smaller factors, more pixels are involved.

Final notes:

That transformation is separable, meaning that you can implement it in two passes, first horizontally, W x H to w x H, then vertically, w x H to w x h. This simplifies the implementation.

Using these principles, you can even work with a continuously variable reduction factor, by considering the corresponding grid.


问:
How does the background to an html element occupy the entire viewport?
Without even providing any height to the html element, how does the background cover the entire viewport. When I inspect the computed height of the html element it's just 8px which is because of the margin that body gets from user agent stylesheet.

html {
  background: hotpink;
}```
</div>
</div>
</p>
<p>This even happens if you give a background to <code>body: {background: hotpink}</code> when the computed height of <code>body</code> is <code>0px</code>.</p>
<p>With <code>body</code>, I know that it's actually not the <code>body</code> whose background is visible, it's the <code>html</code> that reverse inherits the background of <code>body</code>. So, it's kind of similar to setting it on the <code>html</code>.</p>
<p>But my doubt is how does it occupy the full viewport when it has no content or any heights specified?</p>
<p>And it seems that this behavior is only with the <code>background</code> property because adding a <code>border</code> makes it really clear that the <code>height</code> of <code>html</code> is <code>8px</code> only.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  background: hotpink;
  border: 2px dotted rebeccapurple;
}</code>```

答:
~ Per W3

The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for 'background-position') at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.

In CSS, values are never propagated upward, meaning an element never passes values up to its ancestors. However, there are exceptions to the upward propagation rule in HTML:

background styles that are applied to the body element can be passed to the HTML element, which is the document's root element, therefore, defines the canvas.

~ The Definitive Guide

So in your example, the body element is the root-element, and as required by the CSS rules from the browser, it loses the initial background style and the new background style applies to the containing canvas, therefore making the entire screen is hot pink.

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
Without even providing any height to the html element, how does the background cover the entire viewport. When I inspect the computed height of the html element it's just 8px which is because of the margin that body gets from user agent stylesheet.

html {
  background: hotpink;
}

This even happens if you give a background to body: {background: hotpink} when the computed height of body is 0px.

With body, I know that it's actually not the body whose background is visible, it's the html that reverse inherits the background of body. So, it's kind of similar to setting it on the html.

But my doubt is how does it occupy the full viewport when it has no content or any heights specified?

And it seems that this behavior is only with the background property because adding a border makes it really clear that the height of html is 8px only.

html {
  background: hotpink;
  border: 2px dotted rebeccapurple;
}