问:
How do I access local PDF files in my Chrome Extension app?
Google Chrome allows you to preview local PDF files in the browser like pictured below:

I am working on an extension that takes whatever PDF is in the browser preview and opens it in my custom editor/markup tool.

I have been successful in loading PDFs from remote URLs because I can just send the remote URL to my server, download it there, and open the PDF in my app using PDFjs.

How can I accomplish the same functionality for local PDF files?

I have looked into possibly using javascript to create a File object from local PDF files but Chrome doesn't allow access to the local file system.

I am hoping to accomplish this functionality by the user just clicking my extension icon, similar to the popular extension, Kami.

答:
you need to add permissions to your extension:

```<code>"permissions": ["file://*/*"]
</code>```

to ensure that you have permissions for local files, use:

```<code>chrome.extension.isAllowedFileSchemeAccess
</code>```

P.S. have a good day and do not use upwork for these type of questions :-D

Body:
you need to add permissions to your extension:

"permissions": ["file://*/*"]

to ensure that you have permissions for local files, use:

chrome.extension.isAllowedFileSchemeAccess

P.S. have a good day and do not use upwork for these type of questions :-D


来源: stackexchange

问:
Powershell New-SelfSignedCertificate script error 0x80090029
so, i'm using the method in powershell New-SelfSignedCertificate to get a certificate, when i type New-SelfSignedCertificate -Subject "Flock os ████ ████████" -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3") -KeyAlgorithm RSA -KeyLength 2032 -FriendlyName "Flock Os signed script from quality managment department " -NotAfter 12-31-2032
Powershell gives me

`New-SelfSignedCertificate : CertEnroll::CX509Enrollment::_CreateRequest: The requested operation is not supported.
0x80090029 (-2146893783 NTE_NOT_SUPPORTED)
At line:1 char:2

New-SelfSignedCertificate -Subject "Flock os ████ ████████" -TextExt ...

```<code> + CategoryInfo          : NotSpecified: (:) [New-SelfSignedCertificate], Exception
 + FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.NewSelfSignedCertificateCommand

</code>```

can somone help me with the correct command?

答:
RSA key sizes in use today are 2048 and 4096.
You need to change value for your -KeyLength parameter to 2048

ContentLicense: CC BY-SA 4.0

Body:
so, i'm using the method in powershell New-SelfSignedCertificate to get a certificate, when i type New-SelfSignedCertificate -Subject "Flock os ████ ████████" -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3") -KeyAlgorithm RSA -KeyLength 2032 -FriendlyName "Flock Os signed script from quality managment department " -NotAfter 12-31-2032
Powershell gives me

`New-SelfSignedCertificate : CertEnroll::CX509Enrollment::_CreateRequest: The requested operation is not supported.
0x80090029 (-2146893783 NTE_NOT_SUPPORTED)
At line:1 char:2

New-SelfSignedCertificate -Subject "Flock os ████ ████████" -TextExt ...

 + CategoryInfo          : NotSpecified: (:) [New-SelfSignedCertificate], Exception
 + FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.NewSelfSignedCertificateCommand

can somone help me with the correct command?


问:
Is a public instance behind a Load Balancer that much less secure than a private instance behind a NAT Gateway? Due to what risks?
I want to understand the relative security gained when comparing a private instance protected behind a NAT Gateway and a public instance that only accepts connections from its Load Balancer.

How (due to what specific risks) is the latter less secure than the former?

To be upfront, my motivation is to understand how to minimize cost for acceptable security in my AWS network infrastructure. NAT Gateways add cost, and I want to be convinced the costs are necessary before springing for them.

I'm starting from AWS's reference three-tier architecture for a VPC where:

a public subnet hosts a Load Balancer (for incoming connections) and a NAT Gateway (for outgoing), which both must have Public IPs

a private subnet for application instances, which only have Private IPs and communicate out via the earlier NAT gateway

a protected subnet for data (out of scope for this question)

I get how eliminating its public IP protects an instance from unsolicited external connections.

But: Can't I do the same by configuring the security group for an instance with a public IP (which is necessary to use the internet gateway directly) to only accept incoming connections from its load balancer?

I want to understand: Is there a sufficiently secure alternative network architecture which does away with NAT Gateways (or NAT instances — basically, NAT Tax)? Is there a sufficiently secure two-tier architecture?

For example, how much less secure (due to what specific risks) would this two-tier architecture be?

a public subnet hosts a Load Balancer and application instances, and instance security groups only accept connections from the Load Balancer

a private subnet hosts data, and only connects with application instances

Thanks for your time. I'm new to AWS (and StackOverflow) and am looking forward to learn more.

答:
There's two reasons for wanting to use a Private Subnet:

More layers of security = Better security

It's the traditional way of doing it in non-Cloud networks and security practitioners like doing things a traditional way

The fact is, using Security Groups is a perfectly acceptable way of blocking access to an Amazon EC2 instance. It's a form of security that isn't available in traditional networks since they normally apply security at the subnet-level while Security Groups can be applied at the resource-level.

You could configured the Inbound rules in the Security Group of your EC2 instances to only accept incoming connections from the Load Balancer security group. This will stop any other connections -- both within the VPC and from the Internet, even if the instances have a Public IP address.

In many corporations, improved security is more important than cost, so they are happy to pay extra to have more 'layers' of security. This way, if one layer is incorrectly configured and somebody gains access to something they should not be allowed to access, there is additional security that can (hopefully) prevent them from further access. It's always a trade-off between cost and 'risk appetite'.

Oh, there is something a 3rd reason for using a Private Subnet, which is to route all Outgoing traffic through a NAT Gateway to make all traffic appear to be coming from a single IP address, which is useful when whitelisting IP addresses with external services.


问:
Traefik custom error middleware for HTTP status 502 doesn’t work
I would like to serve custom error pages for common HTTP error codes. I was following this tutorial. For this purpose, I created the following docker-compose.yml file to test the functionality. It consists of:

errorPageHandler which is a nginx server which is able to return static HTML pages (404.html and 502.html).

whoami1 which routes the request to port 80 of traefik/whoami image

whoami2 which routes the request to non-existent port 81 of traefik/whoami image which results in 502 - Bad Gateway

version: "3.7"

services:
  errorPageHandler:
    image: "nginx:latest"
    networks:
      - traefik-net
    volumes:
      - "./ErrorPages:/usr/share/nginx/ErrorPages"
      - "./default.conf:/etc/nginx/conf.d/default.conf"
    deploy:
      replicas: 1
      labels:
        # enable Traefik for this service
        - "traefik.enable=true"
        - "traefik.docker.network=traefik-net"

        # router (catches all requests with lowest possible priority)
        - "traefik.http.routers.error-router.rule=HostRegexp(`{catchall:.*}`)"
        - "traefik.http.routers.error-router.priority=1"
        - "traefik.http.routers.error-router.middlewares=error-pages-middleware"

        # middleware
        - "traefik.http.middlewares.error-pages-middleware.errors.status=400-599"
        - "traefik.http.middlewares.error-pages-middleware.errors.service=error-pages-service"
        - "traefik.http.middlewares.error-pages-middleware.errors.query=/{status}.html"

        # service
        - "traefik.http.services.error-pages-service.loadbalancer.server.port=80"

  whoami1:
    image: "traefik/whoami"
    networks:
      - traefik-net
    deploy:
      replicas: 1
      labels:
        # enable Traefik for this service
        - "traefik.enable=true"
        - "traefik.docker.network=traefik-net"

        # router
        - "traefik.http.routers.whoami1.rule=HostRegexp(`whoami1.local`)"
        - "traefik.http.routers.whoami1.service=whoami1"

        # service
        - "traefik.http.services.whoami1.loadbalancer.server.port=80"
        - "traefik.http.services.whoami1.loadbalancer.server.scheme=http"

  whoami2:
    image: "traefik/whoami"
    networks:
      - traefik-net
    deploy:
      replicas: 1
      labels:
        # enable Traefik for this service
        - "traefik.enable=true"
        - "traefik.docker.network=traefik-net"

        # router
        - "traefik.http.routers.whoami2.rule=HostRegexp(`whoami2.local`)"
        - "traefik.http.routers.whoami2.service=whoami2"

        # service
        - "traefik.http.services.whoami2.loadbalancer.server.port=81" # purposely wrong port
        - "traefik.http.services.whoami2.loadbalancer.server.scheme=http"

networks:
  traefik-net:
    external: true
    name: traefik-net
```
<p>Folder <code>ErrorPages</code> contains two static HTML files, <code>404.html</code> and <code>502.html</code>. Content of <code>default.conf</code> is:</p>
```server {
    listen       80;
    server_name  localhost;

    error_page  404    /404.html;
    error_page  502    /502.html;

    location / {
        root  /usr/share/nginx/ErrorPages;
        internal;
    }
}
```
<p>I added the following entries to my <code>hosts</code> file (<code>172.15.16.17</code> is IP of the server where Traefik and all of the mentioned services are deployed):</p>
```172.15.16.17 error404.local
172.15.16.17 whoami1.local
172.15.16.17 whoami2.local
```

My observations:

When I visit http://error404.local, Traefik routes the request to nginx and 404.html is returned. This is expected behavior because http://error404.local doesn't match any of the routes defined in Traefik.

When I visit http://whoami1.local, Traefik routes request to whoami1 service and information about container is displayed on the page (expected behavior).

When I visit http://whoami2.local, Traefik doesn't route request to nginx service, but it displays its default Bad Gateway page. Why doesn't it route the request to the nginx?

答:
The traefik routers (whoami1 and whoami2) needs to use the error middleware that you defined

https://doc.traefik.io/traefik/middlewares/http/errorpages/
Traefik error middleware docs

So add the following labels to their respective containers

```<code>- "traefik.http.whoami1.middlewares=error-pages-middleware"

- "traefik.http.whoami2.middlewares=error-pages-middleware"
</code>```

the Traefik dashboard will show that the routes are using the middleware (refer image) One of my routes from my traefik dashboard

Another option would be to add the middleware to the entrypoint so that all routes use the error middleware (Add this to traefik container compose)

```<code>command:
  - "--entrypoints.websecure.address=:443"
  - "--entrypoints.websecure.http.middlewares=error-pages-middleware@docker"
</code>```

Body:
I would like to serve custom error pages for common HTTP error codes. I was following this tutorial. For this purpose, I created the following docker-compose.yml file to test the functionality. It consists of:

errorPageHandler which is a nginx server which is able to return static HTML pages (404.html and 502.html).

whoami1 which routes the request to port 80 of traefik/whoami image

whoami2 which routes the request to non-existent port 81 of traefik/whoami image which results in 502 - Bad Gateway

version: "3.7"

services:
  errorPageHandler:
    image: "nginx:latest"
    networks:
      - traefik-net
    volumes:
      - "./ErrorPages:/usr/share/nginx/ErrorPages"
      - "./default.conf:/etc/nginx/conf.d/default.conf"
    deploy:
      replicas: 1
      labels:
        # enable Traefik for this service
        - "traefik.enable=true"
        - "traefik.docker.network=traefik-net"

        # router (catches all requests with lowest possible priority)
        - "traefik.http.routers.error-router.rule=HostRegexp(`{catchall:.*}`)"
        - "traefik.http.routers.error-router.priority=1"
        - "traefik.http.routers.error-router.middlewares=error-pages-middleware"

        # middleware
        - "traefik.http.middlewares.error-pages-middleware.errors.status=400-599"
        - "traefik.http.middlewares.error-pages-middleware.errors.service=error-pages-service"
        - "traefik.http.middlewares.error-pages-middleware.errors.query=/{status}.html"

        # service
        - "traefik.http.services.error-pages-service.loadbalancer.server.port=80"

  whoami1:
    image: "traefik/whoami"
    networks:
      - traefik-net
    deploy:
      replicas: 1
      labels:
        # enable Traefik for this service
        - "traefik.enable=true"
        - "traefik.docker.network=traefik-net"

        # router
        - "traefik.http.routers.whoami1.rule=HostRegexp(`whoami1.local`)"
        - "traefik.http.routers.whoami1.service=whoami1"

        # service
        - "traefik.http.services.whoami1.loadbalancer.server.port=80"
        - "traefik.http.services.whoami1.loadbalancer.server.scheme=http"

  whoami2:
    image: "traefik/whoami"
    networks:
      - traefik-net
    deploy:
      replicas: 1
      labels:
        # enable Traefik for this service
        - "traefik.enable=true"
        - "traefik.docker.network=traefik-net"

        # router
        - "traefik.http.routers.whoami2.rule=HostRegexp(`whoami2.local`)"
        - "traefik.http.routers.whoami2.service=whoami2"

        # service
        - "traefik.http.services.whoami2.loadbalancer.server.port=81" # purposely wrong port
        - "traefik.http.services.whoami2.loadbalancer.server.scheme=http"

networks:
  traefik-net:
    external: true
    name: traefik-net

Folder ErrorPages contains two static HTML files, 404.html and 502.html. Content of default.conf is:

server {
    listen       80;
    server_name  localhost;

    error_page  404    /404.html;
    error_page  502    /502.html;

    location / {
        root  /usr/share/nginx/ErrorPages;
        internal;
    }
}

I added the following entries to my hosts file (172.15.16.17 is IP of the server where Traefik and all of the mentioned services are deployed):

172.15.16.17 error404.local
172.15.16.17 whoami1.local
172.15.16.17 whoami2.local

My observations:

When I visit http://error404.local, Traefik routes the request to nginx and 404.html is returned. This is expected behavior because http://error404.local doesn't match any of the routes defined in Traefik.

When I visit http://whoami1.local, Traefik routes request to whoami1 service and information about container is displayed on the page (expected behavior).

When I visit http://whoami2.local, Traefik doesn't route request to nginx service, but it displays its default Bad Gateway page. Why doesn't it route the request to the nginx?

Body:
The traefik routers (whoami1 and whoami2) needs to use the error middleware that you defined

https://doc.traefik.io/traefik/middlewares/http/errorpages/
Traefik error middleware docs

So add the following labels to their respective containers

- "traefik.http.whoami1.middlewares=error-pages-middleware"

- "traefik.http.whoami2.middlewares=error-pages-middleware"

the Traefik dashboard will show that the routes are using the middleware (refer image) One of my routes from my traefik dashboard

Another option would be to add the middleware to the entrypoint so that all routes use the error middleware (Add this to traefik container compose)

command:
  - "--entrypoints.websecure.address=:443"
  - "--entrypoints.websecure.http.middlewares=error-pages-middleware@docker"


问:
ReactJS upload multiple image in base64 into an array
I want to create an image uplaoder based on base64 and I want to get results as an array but I got empty! array, I know maybe it's a asynchronous issue, but I don't know how to use async, await in map any idea?

```<code>const [array, setArray] = useState([]);

const fileBase64 = (img) => {
    let result = [...img];

    setUrlImage(img);

    result && result.map(function (img){
        let fileReader = new FileReader();
        fileReader.readAsDataURL(img);
        fileReader.onloadend = async () => {
            let res = await fileReader.result;
            setArray([...array, res])
        };
    })
    console.log(array)
}

const handleImage = (e) => {
    let image = [...e.target.files];
    fileBase64(image);
}

<input type="file" multiple={true} onChange={handleImage}/>
</code>```

答:
Due to this asynchronous nature, state is being set i.e. push before data urls are set in array.

And that's the reason your your array return empty.

To fix it, you can use create Promise which gets resolved after load event of each file. And use Promise.all which would be resolved after each Promise has resolved and then use setArray:

```<code>fileBase64  = (img) => {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader();
    fileReader.onerror = reject
    fileReader.onload = function () {
      resolve(fileReader.result)
    }
    fileReader.readAsDataURL(img)
  })
}

handleImage = (e) => {
  let image = e.target.files;
  Promise.all(Array.from(image).map(this.readAsDataURL))
    .then((urls) => {
      setArray(urls)
    })
    .catch((error) => {
      console.error(error)
    })
}
</code>```

Body:
I want to create an image uplaoder based on base64 and I want to get results as an array but I got empty! array, I know maybe it's a asynchronous issue, but I don't know how to use async, await in map any idea?

const [array, setArray] = useState([]);

const fileBase64 = (img) => {
    let result = [...img];

    setUrlImage(img);

    result && result.map(function (img){
        let fileReader = new FileReader();
        fileReader.readAsDataURL(img);
        fileReader.onloadend = async () => {
            let res = await fileReader.result;
            setArray([...array, res])
        };
    })
    console.log(array)
}

const handleImage = (e) => {
    let image = [...e.target.files];
    fileBase64(image);
}

<input type="file" multiple={true} onChange={handleImage}/>

Body:
Due to this asynchronous nature, state is being set i.e. push before data urls are set in array.

And that's the reason your your array return empty.

To fix it, you can use create Promise which gets resolved after load event of each file. And use Promise.all which would be resolved after each Promise has resolved and then use setArray:

fileBase64  = (img) => {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader();
    fileReader.onerror = reject
    fileReader.onload = function () {
      resolve(fileReader.result)
    }
    fileReader.readAsDataURL(img)
  })
}

handleImage = (e) => {
  let image = e.target.files;
  Promise.all(Array.from(image).map(this.readAsDataURL))
    .then((urls) => {
      setArray(urls)
    })
    .catch((error) => {
      console.error(error)
    })
}


问:
How to speed up pandas apply?
I have a large DataFrame of 3.14 million rows and I need to group them using 1 column then calculate the std dev and mean by groups. I have done the following and it works as expected, but it is very slow (20000 rows alone take 1min+). I am pretty sure there are much faster ways but I could not find any when I tried to google.

```<code>def gen_time_feats(df):
    feats = df.loc[:, 'f_0':'f_299']
    for col in feats.columns:
        df[f'{col}_avg'] = np.mean(feats[col].values)
        df[f'{col}_std'] = np.std(feats[col].values)
    return df

df_grouped = df.groupby('group_id')
df_with_time_feat = df_grouped.apply(gen_time_feats)
</code>```

The DataFrame has 300 columns and I want to append the std dev and mean for each column as additional columns, so in the end it will become 900 columns.

答:
I think this is the simplest. On my PC, it took about 16 seconds for a table with 3.14 million rows.

desc = pd.merge(df.groupby("group_id").mean(),
                df.groupby("group_id").std(ddof=0),
                suffixes=("_avg", "_std"), left_index=True, right_index=True)
# print(desc)  # This table contains mean and std for each group.

result = df.merge(desc.reset_index(), on='group_id')
```

Title: How to speed up pandas apply?

Body:
I have a large DataFrame of 3.14 million rows and I need to group them using 1 column then calculate the std dev and mean by groups. I have done the following and it works as expected, but it is very slow (20000 rows alone take 1min+). I am pretty sure there are much faster ways but I could not find any when I tried to google.

def gen_time_feats(df):
    feats = df.loc[:, 'f_0':'f_299']
    for col in feats.columns:
        df[f'{col}_avg'] = np.mean(feats[col].values)
        df[f'{col}_std'] = np.std(feats[col].values)
    return df

df_grouped = df.groupby('group_id')
df_with_time_feat = df_grouped.apply(gen_time_feats)

The DataFrame has 300 columns and I want to append the std dev and mean for each column as additional columns, so in the end it will become 900 columns.


问:
How to pass struct array arguments to a function the right way?
Source Code:

```<code>#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}
</code>```

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

答:
If you want to input a variable number of employees, then you should use the STL
container std::vector. Please have a look at its
documentation.

Below you find the usage of std::vector for your given code as well as some
hints starting with the label //CKE:.

#include <iostream>
#include <vector> //CKE: Very powerful STL container for arrays

using namespace std;

struct Employee {
   string name;
   int age = INT_MIN; //CKE: Always initialize variables in C++
   float salary = 0.; //CKE: Always initialize variables in C++
};

void displayData(const Employee&); //CKE: Use const reference if possible

int main() {

   vector<Employee> employees; //CKE: Declaration of dynamic array in C++
   size_t counter = 0;         //CKE: Counts number of given data sets
   string addOneMore;          //CKE: Holds check for more input data
   do {
       ++counter;
       Employee employee;
      cout << "Enter name for employee " << counter << ": ";
      cin >> employee.name;
      cout << "Enter age for employee " << counter << ": ";
      cin >> employee.age;
      cout << "Enter salary for employee " << counter << ": ";
      cin >> employee.salary;
      employees.push_back(employee); //CKE: Save data in dynamic array
      cout << "Want to add another employee? (y/n): ";
      cin >> addOneMore;
   } while (addOneMore == "y");

   for (const auto& employee : employees) { //CKE: Use range base loop for output
      displayData(employee);
   }
   return 0; //CKE: Always return an integer in int main function of C++
}

void displayData(const Employee& employee) { //CKE: No copying of struct Employee
   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;
}
```

Body:
Source Code:

#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?


问:
To select dropdown menu on PHP/selenium doesn't work
I'm tring to select this dropdown list using PHP/selenium.

My code is below:

```<code>sleep(3);
$driver->findElement( WebDriverBy::xpath("//*[@id='main']/form/section[2]/mer-select[1]/div/label/div[2]/select") )
->findElement( WebDriverBy::cssSelector("option[value='2']") )->click();
</code>```

and I tried all attempts suggested in this post.
Non of them works.

I want your help.
Thank you.

答:
If this css:

```<code>select.input-node.medium.placeholder[name='category1']
</code>```

or this xpath:

```<code>//select[contains(@class,'input-node medium placeholder') and @name='category1']
</code>```

represent unique node in HTMLDOM which means 1/1 matching node then you can use the below code to select the desired option from the drop down.

Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste the xpath/css and see, if your desired element is getting highlighted with 1/1 matching node.

Code:

```<code>$select = new WebDriverSelect($driver->findElement(WebDriverBy::cssSelector("select.input-node.medium.placeholder[name='category1']")));
$select->selectByValue('3');
</code>```

Body:
I'm tring to select this dropdown list using PHP/selenium.

My code is below:

sleep(3);
$driver->findElement( WebDriverBy::xpath("//*[@id='main']/form/section[2]/mer-select[1]/div/label/div[2]/select") )
->findElement( WebDriverBy::cssSelector("option[value='2']") )->click();

and I tried all attempts suggested in this post.
Non of them works.

I want your help.
Thank you.

Body:
If this css:

select.input-node.medium.placeholder[name='category1']

or this xpath:

//select[contains(@class,'input-node medium placeholder') and @name='category1']

represent unique node in HTMLDOM which means 1/1 matching node then you can use the below code to select the desired option from the drop down.

Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste the xpath/css and see, if your desired element is getting highlighted with 1/1 matching node.

Code:

$select = new WebDriverSelect($driver->findElement(WebDriverBy::cssSelector("select.input-node.medium.placeholder[name='category1']")));
$select->selectByValue('3');


问:
Live-chat Jquery plugin tawk.to not visible
I'm preparing a website for the company i work for , nothing special , but still is something.

Problem is , today i've been asked to install a live-chat for assistance in the website , and up to now , i havent been able to make any kind of plugin work.

So , here is my page :

html,
body {
  height: 100%;
  margin: 0px;
}
.img-portfolio {
  margin-bottom: 30px;
}
.img-hover:hover {
  opacity: 0.8;
}
header.carousel {
  height: 50%;
}
header.carousel .item,
header.carousel .item.active,
header.carousel .carousel-inner {
  height: 100%;
}
header.carousel .fill {
  width: 100%;
  height: 100%;
  background-position: center;
  background-size: 100% 100%;
}
#styleone {
  background-image: url(../images/SIAN-Powerplant.png);
  background-size: 100% 100%;
}
#styletwo {
  background: url(../images/slide2.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
#stylethree {
  background-image: url(../images/slide3.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
#stylefour {
  background-image: url(../images/slide4.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.error-404 {
  font-size: 100px;
}
.price {
  display: block;
  font-size: 50px;
  line-height: 50px;
}
.price sup {
  top: -20px;
  left: 2px;
  font-size: 20px;
}
.period {
  display: block;
  font-style: italic;
}
footer {
  margin: 50px 0;
}
@media(max-width:991px) {
  .customer-img, .img-related {
    margin-bottom: 30px;
  }
}
@media(max-width:767px) {
  .img-portfolio {
    margin-bottom: 15px;
  }
  header.carousel .carousel {
    height: 70%;
  }
}
.dropdown-submenu {
  position: relative;
}
.dropdown-submenu>.dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -6px;
  margin-left: -1px;
  -webkit-border-radius: 0 6px 6px 6px;
  -moz-border-radius: 0 6px 6px 6px;
  border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
  display: block;
}
.dropdown-submenu>a:after {
  display: block;
  content: " ";
  float: right;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
  border-width: 5px 0 5px 5px;
  border-left-color: #cccccc;
  margin-top: 5px;
  margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
  border-left-color: #ffffff;
}
.dropdown-submenu.pull-left {
  float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
  left: -100%;
  margin-left: 10px;
  -webkit-border-radius: 6px 0 6px 6px;
  -moz-border-radius: 6px 0 6px 6px;
  border-radius: 6px 0 6px 6px;
}
.button {
  transition: all 1.000s ease;
  -webkit-transition: all 1.000s ease;
  -moz-transition: all 1.000s ease;
  -o-transition: all 1.000s ease;
  -ms-transform: scale(1);
  -webkit-transform: scale(1);
  -moz-transform: scale(1);
  -o-transform: scale(1);
  transform: scale(1);
}
.button:hover {
  -webkit-transform: scale(1.100);
  -moz-transform: scale(1.100);
  -o-transform: scale(1.100);
  -ms-transform: scale(1.100);
  transform: scale(1.100)
}
.circular {
  border-radius: 15% 15% 15% 15%;
}
.square {
  padding: 15%;
}
.line-color-elettronica {
  background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSI0OCUiIHN0b3AtY29sb3I9IiMxZTU3OTkiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjN2RiOWU4IiBzdG9wLW9wYWNpdHk9IjAiLz4KICA8L2xpbmVhckdyYWRpZW50PgogIDxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZC11Y2dnLWdlbmVyYXRlZCkiIC8+Cjwvc3ZnPg==);
  background: -moz-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: -webkit-gradient(linear, left top, right top, color-stop(48%, rgba(240, 84, 66, 1)), color-stop(100%, rgba(125, 185, 232, 0)));
  background: -webkit-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: -o-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: -ms-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: linear-gradient(to right, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#1e5799', endColorstr='#007db9e8', GradientType=1);
}
.line-color2 {
  background: -moz-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: -webkit-gradient(linear, left top, right top, color-stop(20%, rgba(255, 159, 50, 1)), color-stop(56%, rgba(125, 185, 232, 0)));
  background: -webkit-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: -o-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: -ms-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: linear-gradient(to right, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#ff9f32', endColorstr='#007db9e8', GradientType=1);
}
.line-color-idraulica {
  background: rgba(33, 180, 226, 1);
  /* Old Browsers */
  background: -moz-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0.0) 100%);
  /* FF3.6+ */
  background: -webkit-gradient(left top, right top, color-stop(0%, rgba(17, 121, 147, 1)), color-stop(100%, rgba(183, 222, 237, 0)));
  /* Chrome, Safari4+ */
  background: -webkit-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* IE 10+ */
  background: linear-gradient(to right, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#21b4e2', endColorstr='#b7deed', GradientType=1);
  /* IE6-9 */
}
.line-color-ER {
  background: rgba(67, 130, 64, 1);
  /* Old Browsers */
  background: -moz-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0.0) 100%);
  /* FF3.6+ */
  background: -webkit-gradient(left top, right top, color-stop(0%, rgba(67, 130, 64, 1)), color-stop(100%, rgba(183, 222, 237, 0)));
  /* Chrome, Safari4+ */
  background: -webkit-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* IE 10+ */
  background: linear-gradient(to right, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#21b4e2', endColorstr='#b7deed', GradientType=1);
  /* IE6-9 */
}
.line-color-certificazioni {
  background: rgba(253, 218, 36, 1);
  /* Old Browsers */
  background: -moz-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0.0) 100%);
  /* FF3.6+ */
  background: -webkit-gradient(left top, right top, color-stop(0%, rgba(253, 218, 36, 1)), color-stop(100%, rgba(183, 222, 237, 0)));
  /* Chrome, Safari4+ */
  background: -webkit-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* IE 10+ */
  background: linear-gradient(to right, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#21b4e2', endColorstr='#b7deed', GradientType=1);
  /* IE6-9 */
}
.panelmodificato {
  border-radius: 0% 0% 15% 15%;
  margin-bottom: 20px;
  background-color: #fff;
  border: 1px solid transparent;
  border-radius: 4px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .03);
  box-shadow: 0 1px 1px rgba(0, 0, 0, .03);
}
.shadow {
  -webkit-box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.6);
  -moz-box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.6);
  box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.6);
}
.service-nav img {
  width: 90%;
  height: 90%;
}
.navbar {
  margin-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Sian Tecnology S.R.L. - Azienda installazione e distribuzione sistemi di sicurezza , apparecchiature fotovoltaice , fototermiche , e idrauliche">
  <meta name="author" content="Sian Tecnology S.R.L.">

  <title>Sian Technology S.R.L.</title>

  <!-- Bootstrap -->
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <!-- Optional theme -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

  <!-- Custom CSS -->
  <link href="css/modern-business.css" rel="stylesheet">

  <!-- Custom Fonts -->
  <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

  <!-- Navigazione -->
  <nav class="navbar navbar-default navbar-static-top">
    <div class="container">
      <!-- Brand e toggle raggruppati per migliore visibilita mobile -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>

          <img alt="Sian Tecnology SRL" src="images/logo-navbar.png" class="brand navbar-brand">

      </div>
      <!-- Collezzione nav-links e altro materiale -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav navbar-right">
          <li>
            Su di noi
          </li>
          <li class="dropdown">
            Servizi<b class="caret"></b>
            <ul class="dropdown-menu">
              <li class="menu-item dropdown dropdown-submenu">
                Impianti elettrici<b class="caret"></b>
                <ul class="dropdown-menu">
                  <li>
                    Civili
                  </li>
                  <li>
                    Industriali
                  </li>
                  <li>
                    Domotica
                  </li>
                  <li>
                    Sicurezza
                  </li>
                  <li>
                    Fotovoltaico
                  </li>
                  <li>
                    Illuminazione
                  </li>
                </ul>
              </li>
              <li class="menu-item dropdown dropdown-submenu">
                Impianti Idraulici<b class="caret"></b>
                <ul class="dropdown-menu">
                  <li>Civili
                  </li>
                  <li>Industriali
                  </li>
                  <li>Condizionamento
                  </li>
                  <li>Pompe di calore
                  </li>
                  <li>Solare termico
                  </li>
                  <li>Termo Dinamico
                  </li>
                </ul>
              </li>
              <li>
                Certificazioni
              </li>
            </ul>
          </li>
          <li>
            Contatti
          </li>
          <!--TODO: inserire foto & company
                    <li>
                        Portfolio
                    </li>
                    -->
          <li>
            Blog
          </li>
          <li class="dropdown">
            Informazioni<b class="caret"></b>
            <ul class="dropdown-menu">
              <li>
                FAQ
              </li>
              <li>
                Prodotti
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
  </nav>

  <!-- Header Carousel -->
  <header id="myCarousel" class="carousel slide">
    <!-- indicatori -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
      <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>

    <!-- Wrapper foto slide -->
    <div class="carousel-inner">
      <div class="item active">
        <div class="fill" id="stylethree"></div>
        <!-- <div class="carousel-caption">
                    <h2>Prima Slide</h2>
                </div> -->
      </div>
      <div class="item">
        <div class="fill" id="styleone"></div>
        <!-- <div class="carousel-caption">
                    <h2>Seconda Slide</h2>
                </div> -->
      </div>
      <div class="item">
        <div class="fill" id="styletwo"></div>
        <!-- <div class="carousel-caption">
                    <h2>Terza slide</h2>
                </div> -->
      </div>
      <div class="item">
        <div class="fill" id="stylefour"></div>
        <!-- <div class="carousel-caption">
                    <h2>Quarta slide</h2>
                </div> -->
      </div>
    </div>

    <!-- Controlli -->

      <span class="icon-prev"></span>

      <span class="icon-next"></span>

    <div class="col-md-12 text-center panel panel-default">
      <div class="col-md-3">
        Tecnologia
      </div>
      <div class="col-md-3">
        Esperienza
      </div>
      <div class="col-md-3">
        Affidabilita
      </div>
      <div class="col-md-3">
        Innovazione
      </div>
    </div>
  </header>

  <!-- Contenuto pagina -->
  <div class="container">

    <!-- Marketing -->
    <div class="row">
      <hr>

      <div class="col-md-5 col-md-offset-7 fullpage">

        <div class="col-md-12 text-center">
          <div class="well">
            <h1>Hello</h1>
            <div class="panel panel-default">
              <hr>
              <br>
              <br>
              <br>
              <br>
              <br>aaaaaaaaaaaaa
              <br>
              <br>
              <br>
              <br>
              <br>
              <hr>
            </div>
          </div>
        </div>

        <div class="col-md-12 text-center">
          <ul class="list-unstyled list-inline list-social-icons">
            <li>
              <i class="fa fa-facebook-square fa-5x fade-icon"></i>
            </li>
            <li>
              <i class="fa fa-pinterest-square fa-5x fade-pinterest"></i>
            </li>
            <li>
              <i class="fa fa-twitter-square fa-5x fade-icon"></i>
            </li>
            <li>
              <i class="fa fa-google-plus-square fa-5x fade-google"></i>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <!-- /.row -->
    <hr>
    <!--Noleggio-->
    <div class="row">
      <div class="col-md-12">
        <img src="images/HQmusica.jpg" width="100%" height="100%;" alt="Sian SRL - Noleggio impianti audio per feste e eventi" style="border: 1px solid black">
      </div>
    </div>

    <!-- Portfolio Section -->
    <div class="row">
      <div class="col-lg-12">
        <h2 class="page-header">Brands</h2>
      </div>
      <div class="col-md-4 col-sm-6 pagination-centered text-center">

          <img class="img-responsive img-portfolio img-hover" src="images/Logo-ABB.jpg" alt="Partner Sian Tecnology - ABB Europe">

      </div>
      <div class="col-md-4 col-sm-6">

          <img class="img-responsive img-portfolio img-hover" src="images/Logo-Qcells.jpg" alt="Partner Sian Tecnology - Q-Cell's International">

      </div>
      <div class="col-md-4 col-sm-6">

          <img class="img-responsive img-portfolio img-hover" src="images/Logo-benq.png" alt="Brand utilizzato da Sian Tecnology - Benq">

      </div>
    </div>
    <div class="row">
      <div class="col-md-4 col-sm-6">

          <img class="img-responsive img-portfolio img-hover" src="images/logo-LG.png" alt="Brand utilizzato da Sian Tecnology - LG International">

      </div>
      <div class="col-md-4 col-sm-6">

          <img class="img-responsive img-portfolio img-hover" src="images/logo-wurth.png" alt="Brand utilizzato da Sian Tecnology - Wurth">

      </div>
      <div class="col-md-4 col-sm-6">

          <img class="img-responsive img-portfolio img-hover" src="images/logo-solar.png" alt="Brand utilizzato da Sian Tecnology - SolarEdge">

      </div>
    </div>
    <!-- /.row -->
    <hr>
    <!-- Call to Action -->
    <div class="well">
      <div class="row">
        <div class="col-md-8">
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias, expedita, saepe, vero rerum deleniti beatae veniam harum neque nemo praesentium cum alias asperiores commodi.</p>
        </div>
        <div class="col-md-4">
          Cerchiamo te !
        </div>
      </div>
    </div>

    <hr>

    <!-- Footer -->
    <footer>
      <div class="row">
        <div class="col-lg-12">
          <p>Copyright © Sian Tecnology SRL - 2014-2016</p>
        </div>
      </div>
    </footer>

    <!-- /.container -->

    <!-- jQuery -->
    <script src="js/jquery.js"></script>
    <script src="js/jquery.nicescroll.js"></script>
    <script>
      $(document).ready(

        function() {

          $("html").niceScroll();

        }

      );
    </script>

    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>

    <!-- Script to Activate the Carousel -->
    <script>
      $('.carousel').carousel({
        interval: 5000 //changes the speed
      })
    </script>
  </div>
  <!--Start of Tawk.to Script-->
  <script type="text/javascript">
    var Tawk_API = Tawk_API || {},
      Tawk_LoadStart = new Date();
    (function() {
      var s1 = document.createElement("script"),
        s0 = document.getElementsByTagName("script")[0];
      s1.async = true;
      s1.src = 'https://embed.tawk.to/56d59cac343e11f1034e44dc/default';
      s1.charset = 'UTF-8';
      s1.setAttribute('crossorigin', '*');
      s0.parentNode.insertBefore(s1, s0);
    })();
  </script>
  <script>
    if (window.jQuery) {
      // jQuery is loaded
    } else {
      // jQuery is not loaded
    }
  </script>
  <!--End of Tawk.to Script-->
</body>

</html></code>```

Main problem is :

< script type = "text/javascript" >
  var Tawk_API = Tawk_API || {},
    Tawk_LoadStart = new Date();
(function() {
  var s1 = document.createElement("script"),
    s0 = document.getElementsByTagName("script")[0];
  s1.async = true;
  s1.src = 'https://embed.tawk.to/56d59cac343e11f1034e44dc/default';
  s1.charset = 'UTF-8';
  s1.setAttribute('crossorigin', '*');
  s0.parentNode.insertBefore(s1, s0);
})(); < /script>
```

which just does nothing , and i dont know what i'm supposed to do , to make this "livechat" work... any suggestion please ?

P.S.
Do note that i'm using bootstrap latest version , and that the site looks quite a mess whitout the img's.

答:
Try adding below <meta> tag inside  tag of your webpage.

```<code><meta name="referrer" content="no-referrer-when-downgrade">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm preparing a website for the company i work for , nothing special , but still is something.

Problem is , today i've been asked to install a live-chat for assistance in the website , and up to now , i havent been able to make any kind of plugin work.

So , here is my page :

html,
body {
  height: 100%;
  margin: 0px;
}
.img-portfolio {
  margin-bottom: 30px;
}
.img-hover:hover {
  opacity: 0.8;
}
header.carousel {
  height: 50%;
}
header.carousel .item,
header.carousel .item.active,
header.carousel .carousel-inner {
  height: 100%;
}
header.carousel .fill {
  width: 100%;
  height: 100%;
  background-position: center;
  background-size: 100% 100%;
}
#styleone {
  background-image: url(../images/SIAN-Powerplant.png);
  background-size: 100% 100%;
}
#styletwo {
  background: url(../images/slide2.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
#stylethree {
  background-image: url(../images/slide3.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
#stylefour {
  background-image: url(../images/slide4.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.error-404 {
  font-size: 100px;
}
.price {
  display: block;
  font-size: 50px;
  line-height: 50px;
}
.price sup {
  top: -20px;
  left: 2px;
  font-size: 20px;
}
.period {
  display: block;
  font-style: italic;
}
footer {
  margin: 50px 0;
}
@media(max-width:991px) {
  .customer-img, .img-related {
    margin-bottom: 30px;
  }
}
@media(max-width:767px) {
  .img-portfolio {
    margin-bottom: 15px;
  }
  header.carousel .carousel {
    height: 70%;
  }
}
.dropdown-submenu {
  position: relative;
}
.dropdown-submenu>.dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -6px;
  margin-left: -1px;
  -webkit-border-radius: 0 6px 6px 6px;
  -moz-border-radius: 0 6px 6px 6px;
  border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
  display: block;
}
.dropdown-submenu>a:after {
  display: block;
  content: " ";
  float: right;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
  border-width: 5px 0 5px 5px;
  border-left-color: #cccccc;
  margin-top: 5px;
  margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
  border-left-color: #ffffff;
}
.dropdown-submenu.pull-left {
  float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
  left: -100%;
  margin-left: 10px;
  -webkit-border-radius: 6px 0 6px 6px;
  -moz-border-radius: 6px 0 6px 6px;
  border-radius: 6px 0 6px 6px;
}
.button {
  transition: all 1.000s ease;
  -webkit-transition: all 1.000s ease;
  -moz-transition: all 1.000s ease;
  -o-transition: all 1.000s ease;
  -ms-transform: scale(1);
  -webkit-transform: scale(1);
  -moz-transform: scale(1);
  -o-transform: scale(1);
  transform: scale(1);
}
.button:hover {
  -webkit-transform: scale(1.100);
  -moz-transform: scale(1.100);
  -o-transform: scale(1.100);
  -ms-transform: scale(1.100);
  transform: scale(1.100)
}
.circular {
  border-radius: 15% 15% 15% 15%;
}
.square {
  padding: 15%;
}
.line-color-elettronica {
  background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSI0OCUiIHN0b3AtY29sb3I9IiMxZTU3OTkiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjN2RiOWU4IiBzdG9wLW9wYWNpdHk9IjAiLz4KICA8L2xpbmVhckdyYWRpZW50PgogIDxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZC11Y2dnLWdlbmVyYXRlZCkiIC8+Cjwvc3ZnPg==);
  background: -moz-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: -webkit-gradient(linear, left top, right top, color-stop(48%, rgba(240, 84, 66, 1)), color-stop(100%, rgba(125, 185, 232, 0)));
  background: -webkit-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: -o-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: -ms-linear-gradient(left, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  background: linear-gradient(to right, rgba(240, 84, 66, 1) 48%, rgba(125, 185, 232, 0) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#1e5799', endColorstr='#007db9e8', GradientType=1);
}
.line-color2 {
  background: -moz-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: -webkit-gradient(linear, left top, right top, color-stop(20%, rgba(255, 159, 50, 1)), color-stop(56%, rgba(125, 185, 232, 0)));
  background: -webkit-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: -o-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: -ms-linear-gradient(left, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  background: linear-gradient(to right, rgba(255, 159, 50, 1) 20%, rgba(125, 185, 232, 0) 56%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#ff9f32', endColorstr='#007db9e8', GradientType=1);
}
.line-color-idraulica {
  background: rgba(33, 180, 226, 1);
  /* Old Browsers */
  background: -moz-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0.0) 100%);
  /* FF3.6+ */
  background: -webkit-gradient(left top, right top, color-stop(0%, rgba(17, 121, 147, 1)), color-stop(100%, rgba(183, 222, 237, 0)));
  /* Chrome, Safari4+ */
  background: -webkit-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(left, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* IE 10+ */
  background: linear-gradient(to right, rgba(17, 121, 147, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#21b4e2', endColorstr='#b7deed', GradientType=1);
  /* IE6-9 */
}
.line-color-ER {
  background: rgba(67, 130, 64, 1);
  /* Old Browsers */
  background: -moz-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0.0) 100%);
  /* FF3.6+ */
  background: -webkit-gradient(left top, right top, color-stop(0%, rgba(67, 130, 64, 1)), color-stop(100%, rgba(183, 222, 237, 0)));
  /* Chrome, Safari4+ */
  background: -webkit-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(left, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* IE 10+ */
  background: linear-gradient(to right, rgba(67, 130, 64, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#21b4e2', endColorstr='#b7deed', GradientType=1);
  /* IE6-9 */
}
.line-color-certificazioni {
  background: rgba(253, 218, 36, 1);
  /* Old Browsers */
  background: -moz-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0.0) 100%);
  /* FF3.6+ */
  background: -webkit-gradient(left top, right top, color-stop(0%, rgba(253, 218, 36, 1)), color-stop(100%, rgba(183, 222, 237, 0)));
  /* Chrome, Safari4+ */
  background: -webkit-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(left, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* IE 10+ */
  background: linear-gradient(to right, rgba(253, 218, 36, 1) 0%, rgba(183, 222, 237, 0) 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#21b4e2', endColorstr='#b7deed', GradientType=1);
  /* IE6-9 */
}
.panelmodificato {
  border-radius: 0% 0% 15% 15%;
  margin-bottom: 20px;
  background-color: #fff;
  border: 1px solid transparent;
  border-radius: 4px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .03);
  box-shadow: 0 1px 1px rgba(0, 0, 0, .03);
}
.shadow {
  -webkit-box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.6);
  -moz-box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.6);
  box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.6);
}
.service-nav img {
  width: 90%;
  height: 90%;
}
.navbar {
  margin-bottom: 0px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Sian Tecnology S.R.L. - Azienda installazione e distribuzione sistemi di sicurezza , apparecchiature fotovoltaice , fototermiche , e idrauliche">
  <meta name="author" content="Sian Tecnology S.R.L.">

  <title>Sian Technology S.R.L.</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

  <link href="css/modern-business.css" rel="stylesheet">

  <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          Toggle navigation

        </button>

            Su di noi

            Servizi

                Impianti elettrici

                    Civili

                    Industriali

                    Domotica

                    Sicurezza

                    Fotovoltaico

                    Illuminazione

                Impianti Idraulici

Civili

Industriali

Condizionamento

Pompe di calore

Solare termico

Termo Dinamico

                Certificazioni

            Contatti

            Blog

            Informazioni

                FAQ

                Prodotti

        Tecnologia

        Esperienza

        Affidabilita

        Innovazione

Hello

aaaaaaaaaaaaa

Brands

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias, expedita, saepe, vero rerum deleniti beatae veniam harum neque nemo praesentium cum alias asperiores commodi.

          Cerchiamo te !

Copyright © Sian Tecnology SRL - 2014-2016

Main problem is :

< script type = "text/javascript" >
  var Tawk_API = Tawk_API || {},
    Tawk_LoadStart = new Date();
(function() {
  var s1 = document.createElement("script"),
    s0 = document.getElementsByTagName("script")[0];
  s1.async = true;
  s1.src = 'https://embed.tawk.to/56d59cac343e11f1034e44dc/default';
  s1.charset = 'UTF-8';
  s1.setAttribute('crossorigin', '*');
  s0.parentNode.insertBefore(s1, s0);
})(); < /script>

which just does nothing , and i dont know what i'm supposed to do , to make this "livechat" work... any suggestion please ?

P.S.
Do note that i'm using bootstrap latest version , and that the site looks quite a mess whitout the img's.

Body:
Try adding below <meta> tag inside <head> tag of your webpage.

<meta name="referrer" content="no-referrer-when-downgrade">


问:
What does the ( ' > ) symbol mean in the command line in MySQL?
I'm new to sql and for some reason, the arrow symbol ( -> ) that I am used to seeing in teh command line, which mean it is ready for input, is now displayed as ( '> ) and it does not accept commands. What does it mean and how do I get back to ( -> ) ?

Thanks

答:
find the attached image

use '/ command and press enter then it will go on next line starting with ->
then use ; and press enter.

it happens if there is unbalanced '(single quote) in query.


问:
How to remove entire substring from '<' to '>' in Java
I have a program that takes an input string. I want to delete anything inside the characters '<' and '>'. For example if the string says

```<code>"P.S.<!--
BODY
   {
   color:white;
   background-color: transparent;
   font-family:sans-serif;
   }
--> Hello how are you today?"
</code>```

I want the output string to only contain "P.S. Hello how are you today?". Is there a simple way to do this in Java? Thanks

答:
If you would prefer to avoid using regular expressions you can use substring:

```<code>String origText = "P.S.<!--"+
    "BODY"+
       "{"+
       "color:white;"+
       "background-color: transparent;"+
       "font-family:sans-serif;"+
       "}"+
    "--> Hello how are you today?";
String revised = origText.substring(0, origText.indexOf('<')) +
    origText.substring(origText.lastIndexOf('>')+1, origText.length());
</code>```

`Java String Class Reference

Body:
I have a program that takes an input string. I want to delete anything inside the characters '<' and '>'. For example if the string says

"P.S. Hello how are you today?"

I want the output string to only contain "P.S. Hello how are you today?". Is there a simple way to do this in Java? Thanks

Body:
If you would prefer to avoid using regular expressions you can use substring:

String origText = "P.S.<!--"+
    "BODY"+
       "{"+
       "color:white;"+
       "background-color: transparent;"+
       "font-family:sans-serif;"+
       "}"+
    "--> Hello how are you today?";
String revised = origText.substring(0, origText.indexOf('<')) +
    origText.substring(origText.lastIndexOf('>')+1, origText.length());

`Java String Class Reference


问:
Accessibility focus is reset in Fragments
I have a button on the screen, when I open a new Fragment by clicking on that button with TalkBack and return to the previous Fragment (fm.popBackStack()), the button should get accessability focus again. But instead, the focus is reset to the first element on the screen as on the first visit. The same with RecyclerView, when I open a new Fragment by clicking on an item, then when I return, the focus should return to the same item on which it was. It works as expected with activity, but not with fragments. How it can be fixed?

Tested on Android 9, 11 and Fragment 1.3.0, 1.4.0, 1.4.1 versions

答:
This will be a long answer because this question has various solutions depending on your needs, and I decided to take time and be thorough because accessibility is essential!

tl;dr solution for your problem:

To correctly save the instance state of Fragment you should do the following:

In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

```<code>class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's state here
    }
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's state here
}
}
</code>```

And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate()

```<code>class MyActivity extends Activity {
    private MyFragment

    public void onCreate(Bundle savedInstanceState) {
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's instance
            mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
            ...
        }
        ...
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's instance
        getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
    }
}
</code>```

Deep dive - Managing UI state

You can efficiently save and restore the UI state by dividing the work among the various types of persistence mechanisms. In most cases, each of these mechanisms should store a different kind of data used in the activity, based on the tradeoffs of data complexity, access speed, and lifetime:

Local persistence: Stores all data you don't want to lose if you open and close the activity.
Example: A collection of song objects, including audio files and metadata.
ViewModel: Stores all the data needed to display the associated UI Controller in memory.
Example: The song objects of the most recent search and search query.

onSaveInstanceState(): Stores a small amount of data needed to quickly reload the activity state if the system stops and then recreates the UI Controller. Instead of storing complex objects here, persist the complex objects in local storage and store a unique ID for these objects in onSaveInstanceState()
Example: Storing the most recent search query.
As an example, consider an activity that allows you to search through your library of songs. Here's how different events should be handled:

The ViewModel immediately delegates this data locally when the user adds a song. If this newly added song should be shown in the UI, you should also update the data in the ViewModel object to reflect the addition of the song. Remember to do all database inserts off of the main thread.

When the user searches for a song, whatever complex song data you load from the database for the UI Controller should be immediately stored in the ViewModel object. You should also save the search query itself in the ViewModel object.

When the activity goes into the background, the system calls onSaveInstanceState(). You should save the search query in the onSaveInstanceState() bundle. This small amount of data is easy to save. It's also all the information you need to get the activity back into its current state.

Options for preserving UI state

When the user's expectations about UI state do not match default system
behaviour, you must save and restore the user's UI state to ensure that the
system-initiated destruction is transparent to the user.

Each of the options for preserving UI state vary along the following dimensions that impact the user experience:

ViewModel
Saved instance state
Persistent storage

Storage location
in memory
serialized to disk
on disk or network

Survives configuration change
Yes
Yes
Yes

Survives system-initiated process death
No
Yes
Yes

Survives user complete activity dismissal/onFinish()
No
No
Yes

Data limitations
complex objects are fine, but space is limited by available memory
only for primitive types and simple, small objects such as String
only limited by disk space or cost/time of retrieval from the network resource

Read/write time
quick (memory access only)
slow (requires serialization/deserialization and disk access)
slow (requires disk access or network transaction)

SavedStateRegistry

Beginning with Fragment 1.1.0, UI controllers, such as an Activity or Fragment, implement SavedStateRegistryOwner and provide a SavedStateRegistry that is bound to that controller. SavedStateRegistry allows components to hook into your UI controller's saved state to consume or contribute to it. For example, the Saved State module for ViewModel uses SavedStateRegistry to create a SavedStateHandle and provide it to your ViewModel objects. You can retrieve the SavedStateRegistry from within your UI controller by calling getSavedStateRegistry().

Components that contribute to the saved state must implement SavedStateRegistry.SavedStateProvider defines a single method called saveState(). The saveState() method allows your component to return a Bundle containing any state that should be saved from that component. SavedStateRegistry calls this method during the saving state phase of the UI controller's lifecycle.

```<code>class SearchManager implements SavedStateRegistry.SavedStateProvider {
    private static String QUERY = "query";
    private String query = null;
    ...

    @NonNull
    @Override
    public Bundle saveState() {
        Bundle bundle = new Bundle();
        bundle.putString(QUERY, query);
        return bundle;
    }
}
</code>```

To register a SavedStateProvider, call registerSavedStateProvider() on the SavedStateRegistry, passing a key to associate with the provider's data as well as the provider. The previously saved data for the provider can be retrieved from the saved state by calling consumeRestoredStateForKey() on the SavedStateRegistry, passing in the key associated with the provider's data.

Within an Activity or Fragment, you can register a SavedStateProvider in onCreate() after calling super.onCreate(). Alternatively, you can set a LifecycleObserver on a SavedStateRegistryOwner, which implements LifecycleOwner, and register the SavedStateProvider once the ON_CREATE event occurs. Using a LifecycleObserver lets you decouple the registration and retrieval of the previously saved state from the SavedStateRegistryOwner itself.

```<code>class SearchManager implements SavedStateRegistry.SavedStateProvider {
    private static String PROVIDER = "search_manager";
    private static String QUERY = "query";
    private String query = null;

    public SearchManager(SavedStateRegistryOwner registryOwner) {
        registryOwner.getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
            if (event == Lifecycle.Event.ON_CREATE) {
                SavedStateRegistry registry = registryOwner.getSavedStateRegistry();

                // Register this object for future calls to saveState()
                registry.registerSavedStateProvider(PROVIDER, this);

                // Get the previously saved state and restore it
                Bundle state = registry.consumeRestoredStateForKey(PROVIDER);

                // Apply the previously saved state
                if (state != null) {
                    query = state.getString(QUERY);
                }
            }
        });
    }

    @NonNull
    @Override
    public Bundle saveState() {
        Bundle bundle = new Bundle();
        bundle.putString(QUERY, query);
        return bundle;
    }

    ...
}

class SearchFragment extends Fragment {
    private SearchManager searchManager = new SearchManager(this);
    ...
}
</code>```

Use ViewModel to handle configuration changes

ViewModel is ideal for storing and managing UI-related data while actively using the application. It allows quick access to UI data and helps you avoid refetching data from network or disk across rotation, window resizing, and other commonly occurring configuration changes.

ViewModel retains the data in memory, which means it is cheaper to retrieve than data from the disk or the network. A ViewModel is associated with an activity (or some other lifecycle owner) - it stays in memory during a configuration change. The system automatically associates the ViewModel with the new activity instance that results from the configuration change.

ViewModels are automatically destroyed by the system when your user backs out of your activity or fragment or if you call finish(), which means the state will be cleared as the user expects in these scenarios.

Unlike saved instance states, ViewModels are destroyed during a system-initiated process death. This is why you should use ViewModel objects in combination with onSaveInstanceState() (or some other disk persistence), stashing identifiers in savedInstanceState to help view models reload the data after system death.

If you already have an in-memory solution in place for storing your UI state across configuration changes, you may not need to use ViewModel.

Use onSaveInstanceState() as backup to handle system-initiated process death

The onSaveInstanceState() callback stores data needed to reload the state of a UI controller, such as an activity or a fragment, if the system destroys and later recreates that controller.

Saved instance state bundles persist through configuration changes and process death but are limited by storage and speed because onSavedInstanceState() serializes data to disk. Serialization can consume a lot of memory if the serialized objects are complicated. Because this process happens on the main thread during a configuration change, long-running serialization can cause dropped frames and visual stutter.

Do not use onSavedInstanceState() to store large amounts of data, such as bitmaps or complex data structures requiring lengthy serialization or deserialization. Instead, store only primitive types and simple, small objects such as String. As such, use onSaveInstanceState() to store a minimal amount of data necessary, such as an ID, to re-create the data necessary to restore the UI back to its previous state should the other persistence mechanisms fail. Most apps should implement onSaveInstanceState() to handle system-initiated process death.

Depending on your app's use cases, you might not need to use onSaveInstanceState() at all.

Body:
This will be a long answer because this question has various solutions depending on your needs, and I decided to take time and be thorough because accessibility is essential!

tl;dr solution for your problem:

To correctly save the instance state of Fragment you should do the following:

In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's state here
    }
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's state here
}
}

And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate()

class MyActivity extends Activity {
    private MyFragment

    public void onCreate(Bundle savedInstanceState) {
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's instance
            mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
            ...
        }
        ...
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's instance
        getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
    }
}

Deep dive - Managing UI state

You can efficiently save and restore the UI state by dividing the work among the various types of persistence mechanisms. In most cases, each of these mechanisms should store a different kind of data used in the activity, based on the tradeoffs of data complexity, access speed, and lifetime:

Local persistence: Stores all data you don't want to lose if you open and close the activity.
Example: A collection of song objects, including audio files and metadata.
ViewModel: Stores all the data needed to display the associated UI Controller in memory.
Example: The song objects of the most recent search and search query.

onSaveInstanceState(): Stores a small amount of data needed to quickly reload the activity state if the system stops and then recreates the UI Controller. Instead of storing complex objects here, persist the complex objects in local storage and store a unique ID for these objects in onSaveInstanceState()
Example: Storing the most recent search query.
As an example, consider an activity that allows you to search through your library of songs. Here's how different events should be handled:

The ViewModel immediately delegates this data locally when the user adds a song. If this newly added song should be shown in the UI, you should also update the data in the ViewModel object to reflect the addition of the song. Remember to do all database inserts off of the main thread.

When the user searches for a song, whatever complex song data you load from the database for the UI Controller should be immediately stored in the ViewModel object. You should also save the search query itself in the ViewModel object.

When the activity goes into the background, the system calls onSaveInstanceState(). You should save the search query in the onSaveInstanceState() bundle. This small amount of data is easy to save. It's also all the information you need to get the activity back into its current state.

Options for preserving UI state

When the user's expectations about UI state do not match default system
behaviour, you must save and restore the user's UI state to ensure that the
system-initiated destruction is transparent to the user.

Each of the options for preserving UI state vary along the following dimensions that impact the user experience:

ViewModel
Saved instance state
Persistent storage

Storage location
in memory
serialized to disk
on disk or network

Survives configuration change
Yes
Yes
Yes

Survives system-initiated process death
No
Yes
Yes

Survives user complete activity dismissal/onFinish()
No
No
Yes

Data limitations
complex objects are fine, but space is limited by available memory
only for primitive types and simple, small objects such as String
only limited by disk space or cost/time of retrieval from the network resource

Read/write time
quick (memory access only)
slow (requires serialization/deserialization and disk access)
slow (requires disk access or network transaction)

SavedStateRegistry

Beginning with Fragment 1.1.0, UI controllers, such as an Activity or Fragment, implement SavedStateRegistryOwner and provide a SavedStateRegistry that is bound to that controller. SavedStateRegistry allows components to hook into your UI controller's saved state to consume or contribute to it. For example, the Saved State module for ViewModel uses SavedStateRegistry to create a SavedStateHandle and provide it to your ViewModel objects. You can retrieve the SavedStateRegistry from within your UI controller by calling getSavedStateRegistry().

Components that contribute to the saved state must implement SavedStateRegistry.SavedStateProvider defines a single method called saveState(). The saveState() method allows your component to return a Bundle containing any state that should be saved from that component. SavedStateRegistry calls this method during the saving state phase of the UI controller's lifecycle.

class SearchManager implements SavedStateRegistry.SavedStateProvider {
    private static String QUERY = "query";
    private String query = null;
    ...

    @NonNull
    @Override
    public Bundle saveState() {
        Bundle bundle = new Bundle();
        bundle.putString(QUERY, query);
        return bundle;
    }
}

To register a SavedStateProvider, call registerSavedStateProvider() on the SavedStateRegistry, passing a key to associate with the provider's data as well as the provider. The previously saved data for the provider can be retrieved from the saved state by calling consumeRestoredStateForKey() on the SavedStateRegistry, passing in the key associated with the provider's data.

Within an Activity or Fragment, you can register a SavedStateProvider in onCreate() after calling super.onCreate(). Alternatively, you can set a LifecycleObserver on a SavedStateRegistryOwner, which implements LifecycleOwner, and register the SavedStateProvider once the ON_CREATE event occurs. Using a LifecycleObserver lets you decouple the registration and retrieval of the previously saved state from the SavedStateRegistryOwner itself.

class SearchManager implements SavedStateRegistry.SavedStateProvider {
    private static String PROVIDER = "search_manager";
    private static String QUERY = "query";
    private String query = null;

    public SearchManager(SavedStateRegistryOwner registryOwner) {
        registryOwner.getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
            if (event == Lifecycle.Event.ON_CREATE) {
                SavedStateRegistry registry = registryOwner.getSavedStateRegistry();

                // Register this object for future calls to saveState()
                registry.registerSavedStateProvider(PROVIDER, this);

                // Get the previously saved state and restore it
                Bundle state = registry.consumeRestoredStateForKey(PROVIDER);

                // Apply the previously saved state
                if (state != null) {
                    query = state.getString(QUERY);
                }
            }
        });
    }

    @NonNull
    @Override
    public Bundle saveState() {
        Bundle bundle = new Bundle();
        bundle.putString(QUERY, query);
        return bundle;
    }

    ...
}

class SearchFragment extends Fragment {
    private SearchManager searchManager = new SearchManager(this);
    ...
}

Use ViewModel to handle configuration changes

ViewModel is ideal for storing and managing UI-related data while actively using the application. It allows quick access to UI data and helps you avoid refetching data from network or disk across rotation, window resizing, and other commonly occurring configuration changes.

ViewModel retains the data in memory, which means it is cheaper to retrieve than data from the disk or the network. A ViewModel is associated with an activity (or some other lifecycle owner) - it stays in memory during a configuration change. The system automatically associates the ViewModel with the new activity instance that results from the configuration change.

ViewModels are automatically destroyed by the system when your user backs out of your activity or fragment or if you call finish(), which means the state will be cleared as the user expects in these scenarios.

Unlike saved instance states, ViewModels are destroyed during a system-initiated process death. This is why you should use ViewModel objects in combination with onSaveInstanceState() (or some other disk persistence), stashing identifiers in savedInstanceState to help view models reload the data after system death.

If you already have an in-memory solution in place for storing your UI state across configuration changes, you may not need to use ViewModel.

Use onSaveInstanceState() as backup to handle system-initiated process death

The onSaveInstanceState() callback stores data needed to reload the state of a UI controller, such as an activity or a fragment, if the system destroys and later recreates that controller.

Saved instance state bundles persist through configuration changes and process death but are limited by storage and speed because onSavedInstanceState() serializes data to disk. Serialization can consume a lot of memory if the serialized objects are complicated. Because this process happens on the main thread during a configuration change, long-running serialization can cause dropped frames and visual stutter.

Do not use onSavedInstanceState() to store large amounts of data, such as bitmaps or complex data structures requiring lengthy serialization or deserialization. Instead, store only primitive types and simple, small objects such as String. As such, use onSaveInstanceState() to store a minimal amount of data necessary, such as an ID, to re-create the data necessary to restore the UI back to its previous state should the other persistence mechanisms fail. Most apps should implement onSaveInstanceState() to handle system-initiated process death.

Depending on your app's use cases, you might not need to use onSaveInstanceState() at all.


问:
What the logic behind b1 ? b1 : b2 in my coding in if-conditions?
1.Here is the assignment.

Declare a function or that works like ||, but without using the || operator.
/**

@param {any} ??? - the first operand

@param {any} ??? - the second operand

@returns {any} the same result as applying the || operator to the given operands, in order

2.Here is what tried(actually people gave me advice on return b1 ? b1 : b2.But i couldn't understand it ,and haven't found a proper explanation about it online.

```<code>function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}
</code>```

3.Here are the coding tests, and the code above passed all of them. But would anyone tell me the logic of b1 ? b1 : b2. I am a beginner, please help me !

//TEST 1

```<code>actual = or("bananas", false);

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 2

```<code>actual = or("", "bananas");

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 3

```<code>actual = or(true, true);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 4

```<code>actual = or(true, false);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

答:
Example to help you to understand the Conditional (ternary) operator in JavaScript, and so about b1 ? b1 : b2.

```<code>function whatUserTyped(str) {
    let b1 = str;
    let b2 = '-Nothing-';

    if (b1) {
        return b1;
    } else {
        return b2;
    }
}

function whatUserTypedButConditionalOperator(str) {
    let b1 = str;
    let b2 = '-Nothing-';

    let rst = b1 ? b1 : b2;

    return rst;
}

let str1 = 'hahaha'; //User typed 'hahaha' into a input[type=text] or textarea or whatever;
let str2 = ''; //Empty string value. User left the input or textarea empty.

console.log('You said ' + whatUserTyped(str1)); //'You said hahaha'
console.log('You said ' + whatUserTyped(str2)); //'You said -Nothing-'

console.log('You said ' + whatUserTypedButConditionalOperator(str1)); //'You said hahaha'
console.log('You said ' + whatUserTypedButConditionalOperator(str2)); //'You said -Nothing-'
</code>```

The Conditional (ternary) operator is condition ? exprIfTrue : exprIfFalse. It's a form of syntactic sugar for if...else statement.

Well the b1 ? b1 : b2 is very tricky. Most of times if the b1 is falsy, it's not recommended to return another str/obj or whatever instantly.

Most time it is used like this: a ? b : c

```<code>function isBob(thatGuy) {
    let a;

    if (thatGuy === 'Bob') {
        a = true;
    } else {
        a = false;
    }

    b = 'That Guy is Bob';
    c = 'That Guy is not Bob';

    return (a ?  b : c);
}

console.log(isBob('Bob')); //That Guy is Bob
console.log(isBob('Jimmy')); //That Guy is not Bob
</code>```

The a is considered as Boolean and most time a is Truthy, because in JavaScript, All values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN), thus the tricky b1 ? b1 : b2 is not very suitable.

References:

MDN - Conditional (ternary) operator

MDN - Truthy

MDN - Falsy

Body:
1.Here is the assignment.

Declare a function or that works like ||, but without using the || operator.
/**

@param {any} ??? - the first operand

@param {any} ??? - the second operand

@returns {any} the same result as applying the || operator to the given operands, in order

2.Here is what tried(actually people gave me advice on return b1 ? b1 : b2.But i couldn't understand it ,and haven't found a proper explanation about it online.

function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}

3.Here are the coding tests, and the code above passed all of them. But would anyone tell me the logic of b1 ? b1 : b2. I am a beginner, please help me !

//TEST 1

actual = or("bananas", false);

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 2

actual = or("", "bananas");

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 3

actual = or(true, true);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 4

actual = or(true, false);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

Body:
Example to help you to understand the Conditional (ternary) operator in JavaScript, and so about b1 ? b1 : b2.

function whatUserTyped(str) {
    let b1 = str;
    let b2 = '-Nothing-';

    if (b1) {
        return b1;
    } else {
        return b2;
    }
}

function whatUserTypedButConditionalOperator(str) {
    let b1 = str;
    let b2 = '-Nothing-';

    let rst = b1 ? b1 : b2;

    return rst;
}

let str1 = 'hahaha'; //User typed 'hahaha' into a input[type=text] or textarea or whatever;
let str2 = ''; //Empty string value. User left the input or textarea empty.

console.log('You said ' + whatUserTyped(str1)); //'You said hahaha'
console.log('You said ' + whatUserTyped(str2)); //'You said -Nothing-'

console.log('You said ' + whatUserTypedButConditionalOperator(str1)); //'You said hahaha'
console.log('You said ' + whatUserTypedButConditionalOperator(str2)); //'You said -Nothing-'

The Conditional (ternary) operator is condition ? exprIfTrue : exprIfFalse. It's a form of syntactic sugar for if...else statement.

Well the b1 ? b1 : b2 is very tricky. Most of times if the b1 is falsy, it's not recommended to return another str/obj or whatever instantly.

Most time it is used like this: a ? b : c

function isBob(thatGuy) {
    let a;

    if (thatGuy === 'Bob') {
        a = true;
    } else {
        a = false;
    }

    b = 'That Guy is Bob';
    c = 'That Guy is not Bob';

    return (a ?  b : c);
}

console.log(isBob('Bob')); //That Guy is Bob
console.log(isBob('Jimmy')); //That Guy is not Bob

The a is considered as Boolean and most time a is Truthy, because in JavaScript, All values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN), thus the tricky b1 ? b1 : b2 is not very suitable.

References:

MDN - Conditional (ternary) operator

MDN - Truthy

MDN - Falsy


问:
How to get full html source from jsdom
I am using JSDOM to modify html text using jquery. After I modify it with jquery, i need the full html. I tried the code below, but it wob't give <!Doctype html> and all. How to get the full html?

mycode

import jquery from "jquery";
import { JSDOM } from "jsdom";

function addElement(html){
      const { window } = new JSDOM(html);
      const $ = jquery(window);
      $("body").html("Hello SO!")
      return $("html").html()

}

```

Thanks in advance

答:
May be this will help</p>
```<code>` <!DOCTYPE html>
<html lang="en">
    <head> ${document.head.getInnerHTML()} </head>
    <body> ${document.body.getInnerHTML()} </body>
</html> `
</code>```

Title: How to get full html source from jsdom

Body:
I am using JSDOM to modify html text using jquery. After I modify it with jquery, i need the full html. I tried the code below, but it wob't give <!Doctype html> and all. How to get the full html?

mycode

import jquery from "jquery";
import { JSDOM } from "jsdom";

function addElement(html){
      const { window } = new JSDOM(html);
      const $ = jquery(window);
      $("body").html("Hello SO!")
      return $("html").html()

}

Thanks in advance

Body:
May be this will help

` <!DOCTYPE html>
<html lang="en">
    <head> ${document.head.getInnerHTML()} </head>
    <body> ${document.body.getInnerHTML()} </body>
</html> `


问:
i am having problem in my vsCode like when i write .container its is not giving me any suggestion for making a class conainer with div element
What should i do for that i, think there must be any option that i have to turn it, please help me to get out of this....Here you can see

Please Help me to resolve this problem

in my laptop when i installed vs code it works perfectly, but when i installed vscode in my desktop it is not giving me any suggestion to auto complete the tag

like when i write .container then it not giving any suggestion that i can click on it and it will change .container to

答:
You need to modify your setting to get this.
Go to setting (Ctrl + , ) search for "emmet.triggerExpansionOnTab" then select the checkbox.
Now you when you type .container and hit Tab button and you get the results.

You can follow this link for more details: https://code.visualstudio.com/docs/editor/emmet#_using-tab-for-emmet-expansions


问:
BASHRC PS1 show datetime but plus 3 hours
Every of us set own convenience working with Linux shell, for example I use
/root/.bashrc

```<code>PS1='[\h:\w] \D{%F %T}\n\$ '
</code>```

to show servername + current server datetime + newline for command - so it looks like

```<code>[servername217:~] 2022-02-06 00:55:02
#
</code>```

But I met a stumbling block with syntax trying to set not server time, but my home, for example plus 3 hours. It's easy to make with regular BASH

```<code>date -d '+ 3 hour' '+%F %T'
</code>```

but when I try to use, for example,

```<code>PS1='[\h:\w] [date -d '+ 3 hour' '+%F %T']\n\$ '
</code>```

I always get an error. It seems PS1 understands only

```<code>\D{%F %T}
</code>```

but how to add 3 hours to %T under this format ? Or there is an another way ?

Body:
Every of us set own convenience working with Linux shell, for example I use
/root/.bashrc

PS1='[\h:\w] \D{%F %T}\n\$ '

to show servername + current server datetime + newline for command - so it looks like

[servername217:~] 2022-02-06 00:55:02
#

But I met a stumbling block with syntax trying to set not server time, but my home, for example plus 3 hours. It's easy to make with regular BASH

date -d '+ 3 hour' '+%F %T'

but when I try to use, for example,

PS1='[\h:\w] [date -d '+ 3 hour' '+%F %T']\n\$ '

I always get an error. It seems PS1 understands only

\D{%F %T}

but how to add 3 hours to %T under this format ? Or there is an another way ?

Body:
This might help:

PS1="[\h:\w] \$(date -d '+ 3 hour' '+%F %T')\n\$ "


问:
Shopware6 cannot disable PayPal Ratepay Banner (auto-reenabled after page reload)
In Shopware 6, the PayPal Ratepay Banner (PayPal Pay Later Message) is enabled by default. Theoretically the banner should be possible to disable in Settings > Addons > PayPal. But after clicking the corresponding button, saving and reloading the page the button is enabled again.

Shopware Version: v6.4.7.0 stable

Paypal Version: 4.1.0

Language: German

答:
Please make sure you flushed the caches after changing the setting

If you have multiple storefronts, make sure it is disabled for the current store view


问:
Git cherry picking and commits
I'm trying to migrate parts of a feature branch into the main application. The feature branch was part of a prototype that had diverged from master a while back.

Feature --> A --> B --> C --> D ---> E

Master --> many changes on prototype --> feature

e.g. I'm after C, D, E. I'm having a problem where there's were many commits of a file that requires many conflict resolutions. E.g. commits C, D, E are all for a file (let's call it file A). After reading the Atlassian page on git commits:

"Whereas SVN tracks differences of a file, Git’s version control model
is based on snapshots. For example, a SVN commit consists of a diff
compared to the original file added to the repository. Git, on the
other hand, records the entire contents of each file in every commit"

It seems that I can pull the last commit i.e. the commit E and receive all changes to file A? Without git cherrypicking C and D and having to fix merge conflicts three times?

The only down side I can see from this is if there were multiple file changes in the earlier commits e.g. Commit D had File A and File B but File B wasn't committed again in D or E. Then I could be missing File B.

Is my understanding correct? I'm am trying to complete this merge in a more efficient way.

Cheers

答:
First of all, it seems unclear what you are trying to achieve here.

From my understanding, you want to add all your commits from the feature branch to the main branch. The best way to achieve the same is to do a git pull and then git rebase, if there are any merge conflicts git will ask you to solve them before the merge. There is not better way than this.

If you will attempt to a cherry-pick of only the last commit E, git will just add the changes from commit E only, without considering any changes made before.

Title: Git cherry picking and commits