问:
Eigen: dividing a vector by a scalar in two steps works but not in one step
So I'm trying to implement Power iteration to find the greatest eigenvalue and corresponding eigenvector in C++. I'm using the Eigen library. The weird thing is that, when I divide a vector by a scalar in a single line (marked in line (1)), it throws an error, and is as helpful as C++ errors can be:

```<code>No viable conversion from 'typename internal::enable_if<true, const CwiseBinaryOp<internal::scalar_quotient_op<typename internal::traits<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0> >::Scalar, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>, const Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, const typename internal::plain_constant_type<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>::type> >::type'
(aka 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<double, double>, const Eigen::Product<Eigen::Product<Eigen::Transpose<Eigen::Matrix<double, -1, 1, 0, -1, 1> >, Eigen::Matrix<double, -1, -1, 1, -1, -1>, 0>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, 0>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, const Eigen::Matrix<double, 1, 1, 0, 1, 1> > >')
to 'double'
</code>```

but when I do it in two steps (marked in line (2)), everything is fine and no errors are thrown. So I find it very weird that Eigen can't do division by scalars in a single step. What is happening here, why it fails when I do it on a single line?

```<code>pair<double, Vector> power_iteration(const Matrix& X, unsigned num_iter, double eps)
{
    Vector b = Vector::Random(X.cols());
    b.normalize();
    Vector b_old;
    for(unsigned int i = 0; i < num_iter; i++){
        b_old =b;
        b = X*b_old;
        b.normalize();
        double cos_angle = b.dot(b_old);
        if(cos_angle > 1-eps){
            i= num_iter+1;
        }
    }

   (1)  double eigenvalue = (b.transpose() * X * b)/(b.transpose().dot(b));

   (2)  double eigenvalue2 = b.transpose() * X * b;
    eigenvalue2 = eigenvalue2/b.transpose().dot(b);

    return make_pair(eigenvalue, b / b.norm());
}
</code>```

答:
Eigen distinguishes between 1x1 matrices and scalars, e.g., b.transpose()*b is actually a 1x1 matrix. There are some special cases where products resulting in a 1x1 matrix are implicitly convertible to a scalar, but the preferred way is to always use a.dot(b) for these products (if indeed you want to have a scalar).

Moreover b.tranpose().dot(b) is actually the same as just b.dot(b) or just b.squaredNorm() (the latter might be slightly faster, since b needs to be read only once, although compilers are often smart enough to optimize both to the same assembly code).

Overall, I suggest using this notation:

```<code>double eigenvalue = b.dot(X * b) / b.squaredNorm();
// or:
double eigenvalue = (b.transpose()*X).dot(b) / b.squaredNorm();
</code>```

Body:
So I'm trying to implement Power iteration to find the greatest eigenvalue and corresponding eigenvector in C++. I'm using the Eigen library. The weird thing is that, when I divide a vector by a scalar in a single line (marked in line (1)), it throws an error, and is as helpful as C++ errors can be:

No viable conversion from 'typename internal::enable_if<true, const CwiseBinaryOp<internal::scalar_quotient_op<typename internal::traits<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0> >::Scalar, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>, const Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, const typename internal::plain_constant_type<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>::type> >::type'
(aka 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<double, double>, const Eigen::Product<Eigen::Product<Eigen::Transpose<Eigen::Matrix<double, -1, 1, 0, -1, 1> >, Eigen::Matrix<double, -1, -1, 1, -1, -1>, 0>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, 0>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, const Eigen::Matrix<double, 1, 1, 0, 1, 1> > >')
to 'double'

but when I do it in two steps (marked in line (2)), everything is fine and no errors are thrown. So I find it very weird that Eigen can't do division by scalars in a single step. What is happening here, why it fails when I do it on a single line?

pair<double, Vector> power_iteration(const Matrix& X, unsigned num_iter, double eps)
{
    Vector b = Vector::Random(X.cols());
    b.normalize();
    Vector b_old;
    for(unsigned int i = 0; i < num_iter; i++){
        b_old =b;
        b = X*b_old;
        b.normalize();
        double cos_angle = b.dot(b_old);
        if(cos_angle > 1-eps){
            i= num_iter+1;
        }
    }

   (1)  double eigenvalue = (b.transpose() * X * b)/(b.transpose().dot(b));

   (2)  double eigenvalue2 = b.transpose() * X * b;
    eigenvalue2 = eigenvalue2/b.transpose().dot(b);

    return make_pair(eigenvalue, b / b.norm());
}

Body:
Eigen distinguishes between 1x1 matrices and scalars, e.g., b.transpose()*b is actually a 1x1 matrix. There are some special cases where products resulting in a 1x1 matrix are implicitly convertible to a scalar, but the preferred way is to always use a.dot(b) for these products (if indeed you want to have a scalar).

Moreover b.tranpose().dot(b) is actually the same as just b.dot(b) or just b.squaredNorm() (the latter might be slightly faster, since b needs to be read only once, although compilers are often smart enough to optimize both to the same assembly code).

Overall, I suggest using this notation:

double eigenvalue = b.dot(X * b) / b.squaredNorm();
// or:
double eigenvalue = (b.transpose()*X).dot(b) / b.squaredNorm();


来源: stackexchange

问:
Concatenate Strings and Variables of two conditions while iterating in python
I have an iteration over a dataframe, but for the example here I used a list.

```<code>seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []

for i in range(1, len(seq)):
    if seq[i] > seq[i-1]:
        box.append(seq[i])
    else:
        box.append(seq[i-1]+10)

box
</code>```

Now i would like to add to each appended value a string prefix like this:

For all values from the If statement letter 'A-'

For all values from else statement letter 'B-'

My desired output is:

```<code>[B-10, A-0, A-1, A-2, B-12, B-11, B-10......
</code>```

I tried it with .join and with simple comma or + inside the append method, but none of it works.
Any suggestions how to accomplish this ?

ContentLicense: CC BY-SA 4.0

Body:
I have an iteration over a dataframe, but for the example here I used a list.

seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []

for i in range(1, len(seq)):
    if seq[i] > seq[i-1]:
        box.append(seq[i])
    else:
        box.append(seq[i-1]+10)

box

Now i would like to add to each appended value a string prefix like this:

For all values from the If statement letter 'A-'

For all values from else statement letter 'B-'

My desired output is:

[B-10, A-0, A-1, A-2, B-12, B-11, B-10......

I tried it with .join and with simple comma or + inside the append method, but none of it works.
Any suggestions how to accomplish this ?

Body:
You can use the f-string literal to add the related letter:

seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []

for i in range(1, len(seq)):
    if seq[i] > seq[i-1]:
        box.append(f"A-{seq[i]}")
    else:
        box.append(f"B-{seq[i-1]+10}")

print(box)
OUT: ['B-10', 'A-0', 'A-1', 'A-2', 'B-12', 'B-11', 'B-10', 'B-9', 'B-8', 'B-7', 'B-6', 'A--4', 'A--3', 'A--2', 'A--1']


问:
Docker Wordpress not connecting with docker Mysql Compose
I am trying to set up multiple WordPress sites being hosting on the same server using docker using nginx reverse proxy server. I have a network setup with the nginx proxy listening on port 80 called nginx-proxy. I confirmed they are all on the same docker network. However, I am still getting WordPress is unable to communicate with the database. I can confirm that the credentials are correct and that MySQL is running on the other docker container.

With my testing, the forwarding proxy is working if I update the virtual host and open it in the web browser it does open the error message on that page. I can ping both the containers from within their shell. I am not sure what I am doing wrong I am newer to dockers networking within version 3. I don't believe docker has differenced between platforms, but in case it does I am running it on Mac OS.

I know there are other posts similar to this using Link and version 2 however, I was not able to find a version 3 with information that fixed my issue.

```<code>version: "3.3"

    services:
       db_node_domain:
         image: mysql:5.7
         volumes:
           - db_data:/var/lib/mysql
         restart: always
         environment:
           MYSQL_ROOT_PASSWORD: PASSWORD
           MYSQL_DATABASE: wordpress
           MYSQL_USER: wordpress
           MYSQL_PASSWORD: PASSWORD
         container_name: wordpress_db

       wordpress:
         depends_on:
           - db_node_domain
         image: wordpress:latest
         expose:
           - 80
         restart: always
         environment:
           VIRTUAL_HOST: domain.com
           WORDPRESS_DB_HOST: db_node_domain:3306
           WORDPRESS_DB_USER: wordpress
           WORDPRESS_DB_PASSWORD: PASSWORD
         container_name: wordpress
    volumes:
        db_data: {}

    networks:
      default:
        external:
          name: nginx-proxy
</code>```

Please let me know if any more information is required. Thank you for any assistance you might be able to provide.

答:
You can use this as your docker compose file below.

Reference:
https://github.com/docker/awesome-compose/tree/master/wordpress-mysql

```<code>version: '3.7'
services:
  db:
    image: mysql:8.0.19
    command: '--default-authentication-plugin=mysql_native_password'
    restart: always
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=somewordpress
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress
  wordpress:
    image: wordpress:latest
    ports:
      - 80:80
    restart: always
    environment:
      - WORDPRESS_DB_HOST=db
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_PASSWORD=wordpress
      - WORDPRESS_DB_NAME=wordpress
volumes:
  db_data:
</code>```

Body:
I am trying to set up multiple WordPress sites being hosting on the same server using docker using nginx reverse proxy server. I have a network setup with the nginx proxy listening on port 80 called nginx-proxy. I confirmed they are all on the same docker network. However, I am still getting WordPress is unable to communicate with the database. I can confirm that the credentials are correct and that MySQL is running on the other docker container.

With my testing, the forwarding proxy is working if I update the virtual host and open it in the web browser it does open the error message on that page. I can ping both the containers from within their shell. I am not sure what I am doing wrong I am newer to dockers networking within version 3. I don't believe docker has differenced between platforms, but in case it does I am running it on Mac OS.

I know there are other posts similar to this using Link and version 2 however, I was not able to find a version 3 with information that fixed my issue.

version: "3.3"

    services:
       db_node_domain:
         image: mysql:5.7
         volumes:
           - db_data:/var/lib/mysql
         restart: always
         environment:
           MYSQL_ROOT_PASSWORD: PASSWORD
           MYSQL_DATABASE: wordpress
           MYSQL_USER: wordpress
           MYSQL_PASSWORD: PASSWORD
         container_name: wordpress_db

       wordpress:
         depends_on:
           - db_node_domain
         image: wordpress:latest
         expose:
           - 80
         restart: always
         environment:
           VIRTUAL_HOST: domain.com
           WORDPRESS_DB_HOST: db_node_domain:3306
           WORDPRESS_DB_USER: wordpress
           WORDPRESS_DB_PASSWORD: PASSWORD
         container_name: wordpress
    volumes:
        db_data: {}

    networks:
      default:
        external:
          name: nginx-proxy

Please let me know if any more information is required. Thank you for any assistance you might be able to provide.

Body:
You can use this as your docker compose file below.

Reference:
https://github.com/docker/awesome-compose/tree/master/wordpress-mysql

version: '3.7'
services:
  db:
    image: mysql:8.0.19
    command: '--default-authentication-plugin=mysql_native_password'
    restart: always
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=somewordpress
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress
  wordpress:
    image: wordpress:latest
    ports:
      - 80:80
    restart: always
    environment:
      - WORDPRESS_DB_HOST=db
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_PASSWORD=wordpress
      - WORDPRESS_DB_NAME=wordpress
volumes:
  db_data:


问:
Push Variables Into HTML Using Google Script
I would like to use Google Script variables into a "mail_template" HTML document. I do not understand why my variables can't be used into this HTML document, while I can use them into the google script itself.

I have 3 documents:

A google script ( .gs ) linked to a Google sheet ( Let's call it "X" )

An html document linked to the above "X" Google sheet

And the "X" *Google sheet itself

The purpose of this work is to send designed email using Google sheet data.

I am beginner, and the documentation seems to be for more advanced users.
https://developers.google.com/apps-script/guides/html/templates

Some plugins are doing the same work, but they are not authorized into my workspace. It's very difficult, I am trying to solve that since 3 days, but I still can't.

<!DOCTYPE html>

    <base target="_top">

    <? solution1 ?>

 ```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// This constant is written in column O for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";

function testSchemas() { {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = sheet.getLastRow();
  var numRows = 1;
  var dataRange = sheet.getRange(startRow, 1, numRows, 15)
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var name = row[2];
    var surname = row[3];
    var salesRepEmail = row[4];
    var qualityAnalystEmail = "xxx@yahoo.fr"
    var customerEmail = row[5];
    var websiteURL = row[6];
    var solution1 = row[7];
    function doGet() {
  return HtmlService
      .createTemplateFromFile('mail_template')
      .evaluate();
}

    var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
    var emailSent = row[14];     // Third column
    if (emailSent != "EMAIL_SENT") {  // Prevents sending duplicates
     /*MailApp.sendEmail(customerEmail, subject, message, {
        cc: "",
        bcc: qualityAnalystEmail + ", " + salesRepEmail
      }); */
    MailApp.sendEmail({
    to: customerEmail,
    bcc: qualityAnalystEmail + ", " + salesRepEmail,
    subject: 'Résumé De Notre Consultation Du Site Mobile ' + websiteURL,
    htmlBody: htmlBody,
  });
}
      Logger.log(name);
      sheet.getRange(startRow + i, 15).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}</code>```

答:
I had a similar question. Anton's solution got me most of the way, but I had to add .getContent() after calling evaluate() and assign the evaluated template to a variable.

var template = HtmlService.createTemplateFromFile('mail_template');
template.myVar = myVar;
var emailToSend = officeTempl.evaluate().getContent();
```

<pre class="lang-js prettyprint-override"><code>htmlBody: emailToSend
</code>```

https://developers.google.com/apps-script/reference/html/html-template#evaluate

ContentLicense: CC BY-SA 3.0

Body:
I would like to use Google Script variables into a "mail_template" HTML document. I do not understand why my variables can't be used into this HTML document, while I can use them into the google script itself.

I have 3 documents:

A google script ( .gs ) linked to a Google sheet ( Let's call it "X" )

An html document linked to the above "X" Google sheet

And the "X" *Google sheet itself

The purpose of this work is to send designed email using Google sheet data.

I am beginner, and the documentation seems to be for more advanced users.
https://developers.google.com/apps-script/guides/html/templates

Some plugins are doing the same work, but they are not authorized into my workspace. It's very difficult, I am trying to solve that since 3 days, but I still can't.

<!DOCTYPE html>

    <base target="_top">

    <? solution1 ?>

// This constant is written in column O for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";

function testSchemas() { {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = sheet.getLastRow();
  var numRows = 1;
  var dataRange = sheet.getRange(startRow, 1, numRows, 15)
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var name = row[2];
    var surname = row[3];
    var salesRepEmail = row[4];
    var qualityAnalystEmail = "xxx@yahoo.fr"
    var customerEmail = row[5];
    var websiteURL = row[6];
    var solution1 = row[7];
    function doGet() {
  return HtmlService
      .createTemplateFromFile('mail_template')
      .evaluate();
}

    var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
    var emailSent = row[14];     // Third column
    if (emailSent != "EMAIL_SENT") {  // Prevents sending duplicates
     /*MailApp.sendEmail(customerEmail, subject, message, {
        cc: "",
        bcc: qualityAnalystEmail + ", " + salesRepEmail
      }); */
    MailApp.sendEmail({
    to: customerEmail,
    bcc: qualityAnalystEmail + ", " + salesRepEmail,
    subject: 'Résumé De Notre Consultation Du Site Mobile ' + websiteURL,
    htmlBody: htmlBody,
  });
}
      Logger.log(name);
      sheet.getRange(startRow + i, 15).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}

Body:
I had a similar question. Anton's solution got me most of the way, but I had to add .getContent() after calling evaluate() and assign the evaluated template to a variable.

var template = HtmlService.createTemplateFromFile('mail_template');
template.myVar = myVar;
var emailToSend = officeTempl.evaluate().getContent();

htmlBody: emailToSend

https://developers.google.com/apps-script/reference/html/html-template#evaluate


问:
How does Android application store state
I want to ask that where does the password gets stored after we login to the application from our phone. I need to know the mechanism of working of how the state is saved in the case of mobile applications.</p>

答:
There's a number of different ways this can be implemented.

If you're using a backend service to authenticate your users such as Firebase Auth then their username and password is authenticated on the server side and you are passed back an oAuth2 token that allows the client to verify that they are authorised (logged in) to access the database. Backend API Auth implementation is very varied and depends on your Database.  (MongoDB, Amazon, Firebase etc).

Otherwise, you can use SharedPreferences to store whether a user is logged in or not after you have authenticated them. I wouldn't advise this implementation as it's open to exploitation and would suggest that you use the API method above and authenticate the user each time they enter your app. Authentication does not mean logging in...it mearly checks their oAuth2 token with the server to make sure it's valid.


问:
Is there a way to chain Javascript functions without creating a new object?
Imagine we have a Button element

```<code>const ourButton = document.getElementById("#theButton");
</code>```

And we want a fluent API to change the styles of this button without creating a new object, so chain a function like this:

```<code>style(ourButton).property("padding").value("32px");
</code>```

Is this possible? I can't seem to figure out how to create this behaviour. I tried building a Fluent API "the conventional way" by creating a constructor function like this:

var FStyle = function(node) {
  this.node = node;
}

FStyle.prototype.property = function(property) {
  this.property = property;
  return this;
}

FStyle.prototype.value = function(value) {
  this.value = value;
  this.node.style[this.property] = this.value;
  return this;
}
```

<p>and using it by constructing a new object:</p>

<pre class="lang-js prettyprint-override"><code>const ourButtonStyle = new FStyle(ourButton);
ourButtonStyle.property("padding").value("64px");
</code>```

Which works, once. If I would like to add a new style I have to create a whole new object. Why is this?

TL;DR: For learning purposes I'm trying to chain functions but don't understand it fully enough to understand the above behaviour. Returning this in a normal function to chain other functions to it won't do the job either. In the end I would like to "pipe" the result of a function to an other function.

答:
Although not easily seen, the issue here is the namings!

You are creating a prototype function called property and then essentially you overwrite this function with the value you got from the function call. Check the comments in the code below.

```<code>FStyle.prototype.property = function(property) {
  // at this point "ourButtonStyle.property" is a function
  this.property = property;
  // here "ourButtonStyle.property" is a string
  return this;
}
</code>```

An easy fix would be to rename these with something slightly deifferent

```<code>var FStyle = function(node) {
  this.node = node;
}

FStyle.prototype.property = function(prop) {
  this.prop = prop;
  return this;
}

FStyle.prototype.value = function(val) {
  this.val = val;
  this.node.style[this.prop] = this.val;
  return this;
}
</code>```

Body:
Imagine we have a Button element

const ourButton = document.getElementById("#theButton");

And we want a fluent API to change the styles of this button without creating a new object, so chain a function like this:

style(ourButton).property("padding").value("32px");

Is this possible? I can't seem to figure out how to create this behaviour. I tried building a Fluent API "the conventional way" by creating a constructor function like this:

var FStyle = function(node) {
  this.node = node;
}

FStyle.prototype.property = function(property) {
  this.property = property;
  return this;
}

FStyle.prototype.value = function(value) {
  this.value = value;
  this.node.style[this.property] = this.value;
  return this;
}

and using it by constructing a new object:

const ourButtonStyle = new FStyle(ourButton);
ourButtonStyle.property("padding").value("64px");

Which works, once. If I would like to add a new style I have to create a whole new object. Why is this?

TL;DR: For learning purposes I'm trying to chain functions but don't understand it fully enough to understand the above behaviour. Returning this in a normal function to chain other functions to it won't do the job either. In the end I would like to "pipe" the result of a function to an other function.

Body:
Although not easily seen, the issue here is the namings!

You are creating a prototype function called property and then essentially you overwrite this function with the value you got from the function call. Check the comments in the code below.

FStyle.prototype.property = function(property) {
  // at this point "ourButtonStyle.property" is a function
  this.property = property;
  // here "ourButtonStyle.property" is a string
  return this;
}

An easy fix would be to rename these with something slightly deifferent

var FStyle = function(node) {
  this.node = node;
}

FStyle.prototype.property = function(prop) {
  this.prop = prop;
  return this;
}

FStyle.prototype.value = function(val) {
  this.val = val;
  this.node.style[this.prop] = this.val;
  return this;
}


问:
Replace Comma Outside Double Quote - Python - Regex
I want to open a CSV file, using open(). I read it per line. For some reason, I'm not using Pandas.

I want to replace comma , with _XXX_, but I want to avoid replacing commas inside double quotes " because that comma is not a separation tag, so I can't use:

```<code>string_ = string_.replace(',', '_XXX_')
</code>```

How to do this? User regex maybe?

I've found replace comma inside quotation,
Python regex: find and replace commas between quotation marks, but i need replace comma OUTSIDE quotation.

答:
You may use a re.sub with a simple "[^"]*" regex (or (?s)"[^"\\]*(?:\\.[^"\\]*)*" if you need to handle escaped sequences in between double quotes, too) to match strings between double quotes, capture this pattern into Group 1, and then match a comma in all other contexts. Then, pass the match object to a callable used as the replacement argument where you may further manipulate the match.

```<code>import re
print( re.sub(r'("[^"]*")|,',
    lambda x: x.group(1) if x.group(1) else x.group().replace(",", ""),
    '1,2,"test,3,7","4, 5,6, ... "') )
    # => 12"test,3,7""4, 5,6, ... "

print( re.sub(r'(?s)("[^"\\]*(?:\\.[^"\\]*)*")|,',
    lambda x: x.group(1) if x.group(1) else x.group().replace(",", ""),
    r'1,2,"test, \"a,b,c\" ,03","4, 5,6, ... "') )
    # => 12"test, \"a,b,c\" ,03""4, 5,6, ... "
</code>```

See the Python demo.

Regex details

("[^"]*")|,:

("[^"]*") - Capturing group 1: a ", then any 0 or more chars other than " and then a "

| - or

, - a comma

The other one is

(?s) - the inline version of a re.S / re.DOTALL flag

("[^"\\]*(?:\\.[^"\\]*)*") - Group 1: a ", then any 0 or more chars other than " and \ then 0 or more sequences of a \ and any one char followed with 0 or more chars other than " and \ and then a "

| - or

, - comma.

Body:
I want to open a CSV file, using open(). I read it per line. For some reason, I'm not using Pandas.

I want to replace comma , with _XXX_, but I want to avoid replacing commas inside double quotes " because that comma is not a separation tag, so I can't use:

string_ = string_.replace(',', '_XXX_')

How to do this? User regex maybe?

I've found replace comma inside quotation,
Python regex: find and replace commas between quotation marks, but i need replace comma OUTSIDE quotation.

Body:
You may use a re.sub with a simple "[^"]*" regex (or (?s)"[^"\\]*(?:\\.[^"\\]*)*" if you need to handle escaped sequences in between double quotes, too) to match strings between double quotes, capture this pattern into Group 1, and then match a comma in all other contexts. Then, pass the match object to a callable used as the replacement argument where you may further manipulate the match.

import re
print( re.sub(r'("[^"]*")|,',
    lambda x: x.group(1) if x.group(1) else x.group().replace(",", ""),
    '1,2,"test,3,7","4, 5,6, ... "') )
    # => 12"test,3,7""4, 5,6, ... "

print( re.sub(r'(?s)("[^"\\]*(?:\\.[^"\\]*)*")|,',
    lambda x: x.group(1) if x.group(1) else x.group().replace(",", ""),
    r'1,2,"test, \"a,b,c\" ,03","4, 5,6, ... "') )
    # => 12"test, \"a,b,c\" ,03""4, 5,6, ... "

See the Python demo.

Regex details

("[^"]*")|,:

("[^"]*") - Capturing group 1: a ", then any 0 or more chars other than " and then a "

| - or

, - a comma

The other one is

(?s) - the inline version of a re.S / re.DOTALL flag

("[^"\\]*(?:\\.[^"\\]*)*") - Group 1: a ", then any 0 or more chars other than " and \ then 0 or more sequences of a \ and any one char followed with 0 or more chars other than " and \ and then a "

| - or

, - comma.


问:
Proxy/convert existing GraphQL API to REST
We have an existing private GraphQL server that powers our React application and would like to possibly expose a subset of the functionality as REST endpoints. This way we do not have to support 2 code bases, one for GraphQL and one for the REST APIs.

How would I take an existing GraphQL server and create a wrapper/proxy layer to expose of the schema as REST endpoints?

答:
Check out this package (graphql2rest): https://github.com/sisense/graphql2rest

You can use it to automatically generate a REST API from your existing GraphQL API - just what you need.

"GraphQL2REST is a Node.js library that reads your GraphQL schema and a user-provided manifest file and automatically generates an Express router with fully RESTful HTTP routes — a full-fledged REST API."


问:
How to deduce nesting class template type from typedef composition?
I would like to define a type from an typedef alias for a specialized class template. Using the same (but unknown) class template type and modifying the contained type.

How to deduce the class template type of the alias?

I tried using template template parameters $ clang++ prog.cc -Wall -Wextra -std=c++14 -pedantic:

```<code>// ----------------------
// third-party header file; may not be modified

template<typename V>
struct UnknownContainer
{
    V m;
};

typedef UnknownContainer<int> KnownAlias;

// ----------------------
// my file (includes third-party header)
// only knows KnownAlias, not UnknownContainer

#include <iostream>
#include <cstdlib>
#include <type_traits>

template< template <typename> class C >
using MakeConstValueType = C< const int >;

typedef MakeConstValueType<KnownAlias> MyContainer;

// example usage

void foo(const MyContainer& c)
{
    std::cout << "value = " << c.m << std::endl;
}

int main()
{
    MyContainer c { 42 };
    foo(c);
}
</code>```

But I get this error:

prog.cc:23:28: error: template argument for template template parameter must be a class template or type alias template
typedef MakeConstValueType<KnownAlias> MyContainer;
                           ^
```

Any ideas?

答:
It's doable, but you have to take stock of the error. You wrote a template accept as an argument another template, but you pass it a concrete type. That's a mismatch. Templates aren't types, but recipes for creating them. You can use partial template specialization to recognize when your meta-function is given a type that's generated from a template, but that will require us to use a class template to specialize over.

Over all, it can look like this

```<code>template<class Container, typename NewValT> struct MakeConstValueTypeHelper;

template< template <typename> class C, typename ValueT, typename NewValT>
struct MakeConstValueTypeHelper<C<ValueT>, NewValT> {
    using type = C<NewValT>;
};

template< class C >
using MakeConstValueType = typename MakeConstValueTypeHelper<C, const int>::type;
</code>```

Now the template parameter matches the argument you intend to give it. The partial specialization unfolds the type into its components, and does the transformation you are after.

Body:
I would like to define a type from an typedef alias for a specialized class template. Using the same (but unknown) class template type and modifying the contained type.

How to deduce the class template type of the alias?

I tried using template template parameters $ clang++ prog.cc -Wall -Wextra -std=c++14 -pedantic:

// ----------------------
// third-party header file; may not be modified

template<typename V>
struct UnknownContainer
{
    V m;
};

typedef UnknownContainer<int> KnownAlias;

// ----------------------
// my file (includes third-party header)
// only knows KnownAlias, not UnknownContainer

#include <iostream>
#include <cstdlib>
#include <type_traits>

template< template <typename> class C >
using MakeConstValueType = C< const int >;

typedef MakeConstValueType<KnownAlias> MyContainer;

// example usage

void foo(const MyContainer& c)
{
    std::cout << "value = " << c.m << std::endl;
}

int main()
{
    MyContainer c { 42 };
    foo(c);
}

But I get this error:

prog.cc:23:28: error: template argument for template template parameter must be a class template or type alias template
typedef MakeConstValueType<KnownAlias> MyContainer;
                           ^

Any ideas?

Body:
It's doable, but you have to take stock of the error. You wrote a template accept as an argument another template, but you pass it a concrete type. That's a mismatch. Templates aren't types, but recipes for creating them. You can use partial template specialization to recognize when your meta-function is given a type that's generated from a template, but that will require us to use a class template to specialize over.

Over all, it can look like this

template<class Container, typename NewValT> struct MakeConstValueTypeHelper;

template< template <typename> class C, typename ValueT, typename NewValT>
struct MakeConstValueTypeHelper<C<ValueT>, NewValT> {
    using type = C<NewValT>;
};

template< class C >
using MakeConstValueType = typename MakeConstValueTypeHelper<C, const int>::type;

Now the template parameter matches the argument you intend to give it. The partial specialization unfolds the type into its components, and does the transformation you are after.


问:
Getting an value error from extended user model
I am trying to create a form that allows me to update an extended user model, see my views below

```<code>
def employee(request, pk):

    employee= Employee.objects.get(id=pk)
    user = User.objects.get(id=pk)
    user_form = UserForm(instance=user)
    Employee = EmployeeProfileForm(instance=employee)

    if 'edit_employee' in request.POST:
        if request.method == 'POST':
            user_form = UserForm(request.POST,instance=user)
            employee_form = EmployeeProfileForm(request.POST,instance=user.employee)

            if user_form.is_valid() and employee_form.is_valid():
                user = user_form.save()
                employee = employee_form.save(commit=False)
                employee.user = user
                employee.save()
                return redirect('/')

                return render(request, 'accounts/new_employee_profile.html', {'user_form': user_form,'employee_form':employee_form})

</code>```

models.py

```<code>class UserManager(BaseUserManager):
    def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError("Users must have email address")
        user_obj = self.model(email = self.normalize_email(email))
        if not password:
            raise ValueError("Users must have a password")

        user_obj.set_password(password)
        user_obj.staff = is_staff
        user_obj.admin = is_admin
        user_obj.active = is_active
        user_obj.save(using=self._db)

        return user_obj

    def create_staffuser(self,email,password=None):
        user = self.create_user(email, password=password,is_staff=True)

        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(email, password=password, is_staff=True, is_admin=True)

        return user

class User(AbstractBaseUser):

    email = models.EmailField(max_length=255,unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    # email and password are required by default
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin

    @property
    def is_active(self):
        return self.active

class Employee(models.Model):

    user = models.OneToOneField(User,on_delete=models.CASCADE)
    full_name = models.CharField(max_length=200, null=True)
    birth_year = models.CharField(max_length=4, null=True)
    department = models.CharField(max_length=200, null=True, blank=True)
    profession = models.CharField(max_length=200, null=True, blank=True)

    def __str__(self):
        return self.full_name

</code>```

forms.py

```<code>

class UserForm(forms.ModelForm):

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = '__all__'

    def clean_password2(self):

        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):

        user = super(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class EmployeeProfileForm(ModelForm):
    class Meta:
        model = Employee
        fields = '__all__'

</code>```

template

```<code><div class="row">
    <div class="col-md-12">
        <div class="card card-body">
            <form action="" method="POST">

                  {{user_form.as_p|crispy}}
                {{employee_form.as_p|crispy }}

                <hr>
                <input type="submit" name="Edit">
            </form>
        </div>
    </div>
</div>
</code>```

I am getting an error below based on my views as follows

```<code>The view accounts.views.EmployeeProfile didn't return an HttpResponse object. It returned None instead.

</code>```

I have a template before the accessing the template to update the form as follows

```<code><td><a class="btn btn-sm btn-info" name= "edit_employee" href="{% url 'employee_profile' employee.id %}">Edit</a></td>

</code>```

How will I have to change the code shown, in order to update or edit my form?

Given that the form needs to be updated and submitted at the same time as it is a extended user model which is the User model and the employee model.

答:
every view must return a HttpResponse. The error you are getting is self-explanatory.

here you are getting this error because you have not explicitly returned anything ins case of your if statements are false.

if these cases are false, by default None will be returned, which is not an expected return data type for Django views.

explicitly returning HttpResponse in case of following if cases  will solve the issue

```<code>if 'edit_employee' in request.POST:
        if request.method == 'POST':
        .
        .
        if user_form.is_valid() and employee_form.is_valid():
</code>```

Reference: https://docs.djangoproject.com/en/3.0/topics/http/views/#a-simple-view

Body:
I am trying to create a form that allows me to update an extended user model, see my views below

def employee(request, pk):

    employee= Employee.objects.get(id=pk)
    user = User.objects.get(id=pk)
    user_form = UserForm(instance=user)
    Employee = EmployeeProfileForm(instance=employee)

    if 'edit_employee' in request.POST:
        if request.method == 'POST':
            user_form = UserForm(request.POST,instance=user)
            employee_form = EmployeeProfileForm(request.POST,instance=user.employee)

            if user_form.is_valid() and employee_form.is_valid():
                user = user_form.save()
                employee = employee_form.save(commit=False)
                employee.user = user
                employee.save()
                return redirect('/')

                return render(request, 'accounts/new_employee_profile.html', {'user_form': user_form,'employee_form':employee_form})

models.py

class UserManager(BaseUserManager):
    def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError("Users must have email address")
        user_obj = self.model(email = self.normalize_email(email))
        if not password:
            raise ValueError("Users must have a password")

        user_obj.set_password(password)
        user_obj.staff = is_staff
        user_obj.admin = is_admin
        user_obj.active = is_active
        user_obj.save(using=self._db)

        return user_obj

    def create_staffuser(self,email,password=None):
        user = self.create_user(email, password=password,is_staff=True)

        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(email, password=password, is_staff=True, is_admin=True)

        return user

class User(AbstractBaseUser):

    email = models.EmailField(max_length=255,unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    # email and password are required by default
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin

    @property
    def is_active(self):
        return self.active

class Employee(models.Model):

    user = models.OneToOneField(User,on_delete=models.CASCADE)
    full_name = models.CharField(max_length=200, null=True)
    birth_year = models.CharField(max_length=4, null=True)
    department = models.CharField(max_length=200, null=True, blank=True)
    profession = models.CharField(max_length=200, null=True, blank=True)

    def __str__(self):
        return self.full_name

forms.py

class UserForm(forms.ModelForm):

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = '__all__'

    def clean_password2(self):

        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):

        user = super(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class EmployeeProfileForm(ModelForm):
    class Meta:
        model = Employee
        fields = '__all__'

template

            <form action="" method="POST">

                  {{user_form.as_p|crispy}}
                {{employee_form.as_p|crispy }}

                <input type="submit" name="Edit">
            </form>

I am getting an error below based on my views as follows

The view accounts.views.EmployeeProfile didn't return an HttpResponse object. It returned None instead.

I have a template before the accessing the template to update the form as follows

Edit

How will I have to change the code shown, in order to update or edit my form?

Given that the form needs to be updated and submitted at the same time as it is a extended user model which is the User model and the employee model.

Body:
every view must return a HttpResponse. The error you are getting is self-explanatory.

here you are getting this error because you have not explicitly returned anything ins case of your if statements are false.

if these cases are false, by default None will be returned, which is not an expected return data type for Django views.

explicitly returning HttpResponse in case of following if cases  will solve the issue

if 'edit_employee' in request.POST:
        if request.method == 'POST':
        .
        .
        if user_form.is_valid() and employee_form.is_valid():

Reference: https://docs.djangoproject.com/en/3.0/topics/http/views/#a-simple-view


问:
How to add an dynamically a checkbox element on a Tabcontrol after Tabcontrol.Pages is from GUI Designer?
can i add tabcontrol elements after programm started?

i use a Tabcontrol from GUI-Designer and wanna manipulate a TabPage.
i want there new dynamical checkboxes on Formular _load.

i can't see these checkboxes on my TabPages

```<code>For i = 0 To frmMain.cmbZielSpache.Items.Count - 1

        Dim cBox = New CheckBox()
        cBox.Name = "GEN_" & i
        cBox.Location = New Point(offsetX, offsetY)
        cBox.Text = frmMain.cmbZielSpache.Items(i)

        If frmMain.cmbZielSpache.Items(i) = frmMain.cmbZielSpache.Text Or My.Settings.chkTranslate_normal_alleSprachen = True Then
            cBox.Checked = True
        End If

        offsetX = offsetX + 120

        Me.Controls.Add(cBox)
        AddHandler cBox.CheckedChanged, AddressOf checkChangedHandler

    Next i
</code>```

Instead of using Me.Controls i wanna add the checkboxes after programm started dynamically.

答:
The solution is TabControl1.TabPages(0).Controls.add()</p>

```<code>Sub checkChangedHandler(sender As Object, e As EventArgs)
    lblSprachenListeZielSprachen.Text = "Ziel Übersetzungsprache: "
    For Each chkBox In TabControl1.TabPages(0).Controls.OfType(Of CheckBox)()
        'Check here whether your check boxes are checked true/false
        If chkBox.Checked = True Then
            If Not chkBox.Name.IndexOf("GEN_") = -1 Then
                lblSprachenListeZielSprachen.Text &= chkBox.Text & ","
            End If
        End If
    Next
    gblAktiveÜbersetzungssprachen = lblSprachenListeZielSprachen.Text.Replace("Ziel Übersetzungsprache: ", "")
End Sub

 For i = 0 To frmMain.cmbZielSpache.Items.Count - 1

        Dim cBox = New CheckBox()
        cBox.Name = "GEN_" & i
        cBox.Location = New Point(offsetX, offsetY)
        cBox.Text = frmMain.cmbZielSpache.Items(i)

        If frmMain.cmbZielSpache.Items(i) = frmMain.cmbZielSpache.Text Or My.Settings.chkTranslate_normal_alleSprachen = True Then
            cBox.Checked = True
        End If

        offsetX = offsetX + 120

        AddHandler cBox.CheckedChanged, AddressOf checkChangedHandler

        Me.TabControl1.TabPages(0).Controls.Add(cBox)

    Next i
</code>```

Body:
can i add tabcontrol elements after programm started?

i use a Tabcontrol from GUI-Designer and wanna manipulate a TabPage.
i want there new dynamical checkboxes on Formular _load.

i can't see these checkboxes on my TabPages

For i = 0 To frmMain.cmbZielSpache.Items.Count - 1

        Dim cBox = New CheckBox()
        cBox.Name = "GEN_" & i
        cBox.Location = New Point(offsetX, offsetY)
        cBox.Text = frmMain.cmbZielSpache.Items(i)

        If frmMain.cmbZielSpache.Items(i) = frmMain.cmbZielSpache.Text Or My.Settings.chkTranslate_normal_alleSprachen = True Then
            cBox.Checked = True
        End If

        offsetX = offsetX + 120

        Me.Controls.Add(cBox)
        AddHandler cBox.CheckedChanged, AddressOf checkChangedHandler

    Next i

Instead of using Me.Controls i wanna add the checkboxes after programm started dynamically.

Body:
The solution is TabControl1.TabPages(0).Controls.add()

Sub checkChangedHandler(sender As Object, e As EventArgs)
    lblSprachenListeZielSprachen.Text = "Ziel Übersetzungsprache: "
    For Each chkBox In TabControl1.TabPages(0).Controls.OfType(Of CheckBox)()
        'Check here whether your check boxes are checked true/false
        If chkBox.Checked = True Then
            If Not chkBox.Name.IndexOf("GEN_") = -1 Then
                lblSprachenListeZielSprachen.Text &= chkBox.Text & ","
            End If
        End If
    Next
    gblAktiveÜbersetzungssprachen = lblSprachenListeZielSprachen.Text.Replace("Ziel Übersetzungsprache: ", "")
End Sub

 For i = 0 To frmMain.cmbZielSpache.Items.Count - 1

        Dim cBox = New CheckBox()
        cBox.Name = "GEN_" & i
        cBox.Location = New Point(offsetX, offsetY)
        cBox.Text = frmMain.cmbZielSpache.Items(i)

        If frmMain.cmbZielSpache.Items(i) = frmMain.cmbZielSpache.Text Or My.Settings.chkTranslate_normal_alleSprachen = True Then
            cBox.Checked = True
        End If

        offsetX = offsetX + 120

        AddHandler cBox.CheckedChanged, AddressOf checkChangedHandler

        Me.TabControl1.TabPages(0).Controls.Add(cBox)

    Next i


问:
SQLAlchemy - subquery in a WHERE clause
I've just recently started using SQLAlchemy and am still having trouble wrapping my head around some of the concepts.

Boiled down to the essential elements, I have two tables like this (this is through Flask-SQLAlchemy):

```<code>class User(db.Model):
    __tablename__ = 'users'
    user_id = db.Column(db.Integer, primary_key=True)

class Posts(db.Model):
    __tablename__ = 'posts'
    post_id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
    post_time = db.Column(db.DateTime)

    user = db.relationship('User', backref='posts')
</code>```

How would I go about querying for a list of users and their newest post (excluding users with no posts). If I was using SQL, I would do:

```<code>SELECT [whatever]
FROM posts AS p
    LEFT JOIN users AS u ON u.user_id = p.user_id
WHERE p.post_time = (SELECT MAX(post_time) FROM posts WHERE user_id = u.user_id)
</code>```

So I know exactly the "desired" SQL to get the effect I want, but no idea how to express it "properly" in SQLAlchemy.

Edit: in case it's important, I'm on SQLAlchemy 0.6.6.

答:
This should work (different SQL, same result):

```<code>t = Session.query(
    Posts.user_id,
    func.max(Posts.post_time).label('max_post_time'),
).group_by(Posts.user_id).subquery('t')

query = Session.query(User, Posts).filter(and_(
    User.user_id == Posts.user_id,
    User.user_id == t.c.user_id,
    Posts.post_time == t.c.max_post_time,
))

for user, post in query:
    print user.user_id, post.post_id
</code>```

Where c stands for 'columns'

Title: SQLAlchemy - subquery in a WHERE clause

Body:
I've just recently started using SQLAlchemy and am still having trouble wrapping my head around some of the concepts.

Boiled down to the essential elements, I have two tables like this (this is through Flask-SQLAlchemy):

class User(db.Model):
    __tablename__ = 'users'
    user_id = db.Column(db.Integer, primary_key=True)

class Posts(db.Model):
    __tablename__ = 'posts'
    post_id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
    post_time = db.Column(db.DateTime)

    user = db.relationship('User', backref='posts')

How would I go about querying for a list of users and their newest post (excluding users with no posts). If I was using SQL, I would do:

SELECT [whatever]
FROM posts AS p
    LEFT JOIN users AS u ON u.user_id = p.user_id
WHERE p.post_time = (SELECT MAX(post_time) FROM posts WHERE user_id = u.user_id)

So I know exactly the "desired" SQL to get the effect I want, but no idea how to express it "properly" in SQLAlchemy.

Edit: in case it's important, I'm on SQLAlchemy 0.6.6.

Body:
This should work (different SQL, same result):

t = Session.query(
    Posts.user_id,
    func.max(Posts.post_time).label('max_post_time'),
).group_by(Posts.user_id).subquery('t')

query = Session.query(User, Posts).filter(and_(
    User.user_id == Posts.user_id,
    User.user_id == t.c.user_id,
    Posts.post_time == t.c.max_post_time,
))

for user, post in query:
    print user.user_id, post.post_id

Where c stands for 'columns'


问:
MySQL SELECT count with ORDER BY
```<code>SELECT * FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC
229298400   90901   33
232322400   90901   33
227487600   90901   37
229903200   90901   38
228092400   90901   41
228693600   90901   43
225673200   90901   45
230508000   90901   47

SELECT position FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC LIMIT 1
33

SELECT position, count(*) as Weeks FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC LIMIT 1
45  8
</code>```

Please explain why '45' (second last?) is returned and how to count all entries and get the highest one.

Title: MySQL SELECT count with ORDER BY

Body:
SELECT * FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC
229298400   90901   33
232322400   90901   33
227487600   90901   37
229903200   90901   38
228092400   90901   41
228693600   90901   43
225673200   90901   45
230508000   90901   47

SELECT position FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC LIMIT 1
33

SELECT position, count(*) as Weeks FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC LIMIT 1
45  8

Please explain why '45' (second last?) is returned and how to count all entries and get the highest one.

Body:
If you intend to query on entry_id then max(position)

DROP TABLE IF EXISTS T;
CREATE TABLE t(id int,entry_id int,position int);
insert into t values
(229298400 ,  90901  , 33),
(232322400 ,  90901  , 33),
(227487600 ,  90901  , 37),
(229903200 ,  90901  , 38),
(228092400 ,  90901  , 41),
(228693600 ,  90901  , 43),
(225673200 ,  90901  , 45),
(230508000 ,  90901  , 47);

select max(position) , count(*)
from t
where entry_id = 90901;

+---------------+----------+
| max(position) | count(*) |
+---------------+----------+
|            47 |        8 |
+---------------+----------+
1 row in set (0.001 sec)

if you want the same for every entry_id then

select entry_id, max(position) , count(*)
from t
group by entry_id

+----------+---------------+----------+
| entry_id | max(position) | count(*) |
+----------+---------------+----------+
|    90901 |            47 |        8 |
+----------+---------------+----------+
1 row in set (0.001 sec)


问:
Pygame mask collisions not detected even with offsets at zero
I am writing a game using pygame. A skier object moves left and right on the x axis, whilst tree objects move up the screen on the y axis. From outside the extracted code, the Tree class method collide is called passing the object tree and skier (i.e. Tree.collide(tree,skier)). I have modified the collide method so that it prints the x and y offsets and whether the collision test is met (i.e. is ret_mask none). Having limited the underlying program to one skier and one tree with the same x-co-ordinates, I see the tree pass right through the skier generating a printed offset_x and offset_y of zero, but is still get a ret_mask of None even with the tree passing completely through the skier and off up the screen on the y axis. Looking at some older code, I tried adding .convert() when loading the PNGs and also setting colorkey(white) - as indicated by the comments. However, this made no difference.

Any help on why I am not getting collisions greatly appreciated!

# Load Image PNGs
white=(255, 255, 255) #added definition of white
SKIER=pygame.image.load(os.path.join('assets','skier_img.png')).convert() #added .convert() to end
SKIER.set_colorkey(white) #added line
TREE=pygame.image.load(os.path.join('assets','tree_img.png')).convert() #added .convert() to end
SKIER.set_colorkey(white) #added line

# Define Object Classes
class Sprite:
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.img=None

class Skier(Sprite):
    def __init__(self,x,y):
        super().__init__(x,y)
        self.img=SKIER
        self.mask=pygame.mask.from_surface(self.img)

class Tree(Sprite):
    def __init__(self,x,y):
        super().__init__(x,y)
        self.img=TREE
        self.mask=pygame.mask.from_surface(self.img)

    def move(self,vel):
        self.y-=vel

    def collide(obj1,obj2):
        offset_x=obj2.x-obj1.x
        offset_y=obj2.y-obj1.y
        ret_mask=obj1.mask.overlap(obj2.mask,(offset_x,offset_y))
        if (obj1.mask.overlap(obj2.mask,(offset_x,offset_y)) != None):
            print('Collision Detected!')
        else:
            print(f'offset_x is {offset_x} and offset_y is {offset_y} and mask output is {ret_mask}')
```

答:
Sorry everyone! I worked it out.
Actually, the steps I took with the .convert() method and the set_colorkey(white) DID WORK.
It is just that I had an error in my code due to doing a copy and paste: I set the colorkey on the SKIER twice rather than doing the TREE.
Also, huge thanks to Rabbid76 who reformatted the code in my question properly - sorry about that I posted in a hurry.
Overall a zero score in covering myself in glory....</p>


问:
componentWillReceiveProps to React hooks
I want to change class based component to functional component and i have

```<code>const initialState={

     displayName: "",
        email: "",
        password: "",
        confirmPassword: "",
        error: "",
    }

componentWillReceiveProps(nextProps,nextContext){
const userError=nextProps;
if(userError){
this.setState({error:userError.message});
}
}
</code>```

And i make selector

```<code>export const selectUserError = createSelector(
  [selectUser],
  (user) => user.error
);

 {this.state.error ? (
        <SweetAlert
          show={this.state.error}
          type="warning"
          title="Something went wrong"
          text={this.props.userError}
          onConfirm={() => this.setState({ error: "" })}
        />
      ) : null}
</code>```

and i pass into mapState to props.
Can anyone help with this?

答:
Instead of storing the props in state, you can simply use the data from props</p>

```<code>const {userError} = this.props;
...
 {userError && userError.message ? (
        <SweetAlert
          show={!!userError.message}
          type="warning"
          title="Something went wrong"
          text={userError.message}
          onConfirm={() => this.props.dispatch({ type: 'RESET_ERROR', error: "" })} // Dispatch and action here that updates state in store
        />
      ) : null}
</code>```

Body:
I want to change class based component to functional component and i have

const initialState={

     displayName: "",
        email: "",
        password: "",
        confirmPassword: "",
        error: "",
    }

componentWillReceiveProps(nextProps,nextContext){
const userError=nextProps;
if(userError){
this.setState({error:userError.message});
}
}

And i make selector

export const selectUserError = createSelector(
  [selectUser],
  (user) => user.error
);

 {this.state.error ? (
        <SweetAlert
          show={this.state.error}
          type="warning"
          title="Something went wrong"
          text={this.props.userError}
          onConfirm={() => this.setState({ error: "" })}
        />
      ) : null}

and i pass into mapState to props.
Can anyone help with this?

Body:
Instead of storing the props in state, you can simply use the data from props

const {userError} = this.props;
...
 {userError && userError.message ? (
        <SweetAlert
          show={!!userError.message}
          type="warning"
          title="Something went wrong"
          text={userError.message}
          onConfirm={() => this.props.dispatch({ type: 'RESET_ERROR', error: "" })} // Dispatch and action here that updates state in store
        />
      ) : null}


问:
Parse buffer image to base64 on React Native
I am trying to show an image gotten from a server in a React Native app. What I am getting in the response look like this:

I tried to build a Buffer object using buffer and then parse to base64

```<code>const imageBuffer = Buffer.from(JSON.stringify(res.data)) // This res.data is the whole object, including the type "Buffer" and the data array
const imageBase64 = imageBuffer.toString('base64')
setImage(imageBase64)
</code>```

This returns a base64 image but it doesn't show using the React Native Image component

```<code><Image source={{ uri: `data:image/jpeg;base64,${image}` }} />
</code>```

I didn't found how to handle images with this structure (a buffer as a numbers array) on React Native. I was thinking that maybe it is a way to do this without the library mentioned or without parse the buffer to a base64 but I don't know.

Thank you

答:
I dont see any width and height provided to your image, this is the first common issue I faced and wasted my whole day, after providing the width and height, even if the image is not shown see the below solution

I have used this function to convert BufferArray into Base64

source link

```<code>  arrayBufferToBase64 = buffer => {
    let binary = '';
    let bytes = new Uint8Array(buffer);
    let len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  };
</code>```

I have utilized the above function like this

```<code>              <Image
                style={{
                  width: 200,
                  height: 200,
                  resizeMode: 'cover',
                  backgroundColor: 'red',
                }}
                source={{
                  uri:
                    'data:image/jpeg;base64,' +
                    this.arrayBufferToBase64(data.data), //data.data in your case
                }}
              />
</code>```

Body:
I am trying to show an image gotten from a server in a React Native app. What I am getting in the response look like this:

I tried to build a Buffer object using buffer and then parse to base64

const imageBuffer = Buffer.from(JSON.stringify(res.data)) // This res.data is the whole object, including the type "Buffer" and the data array
const imageBase64 = imageBuffer.toString('base64')
setImage(imageBase64)

This returns a base64 image but it doesn't show using the React Native Image component

<Image source={{ uri: `data:image/jpeg;base64,${image}` }} />

I didn't found how to handle images with this structure (a buffer as a numbers array) on React Native. I was thinking that maybe it is a way to do this without the library mentioned or without parse the buffer to a base64 but I don't know.

Thank you

Body:
I dont see any width and height provided to your image, this is the first common issue I faced and wasted my whole day, after providing the width and height, even if the image is not shown see the below solution

I have used this function to convert BufferArray into Base64

source link

  arrayBufferToBase64 = buffer => {
    let binary = '';
    let bytes = new Uint8Array(buffer);
    let len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  };

I have utilized the above function like this

              <Image
                style={{
                  width: 200,
                  height: 200,
                  resizeMode: 'cover',
                  backgroundColor: 'red',
                }}
                source={{
                  uri:
                    'data:image/jpeg;base64,' +
                    this.arrayBufferToBase64(data.data), //data.data in your case
                }}
              />


问:
MongoDB lookup when foreign field and local field are array of objects
I have two collections 'questions' and 'answers'.
questions document is like this:

```<code>      [
        {
          _id: "8326ccbn73487290nc",
          questions: [
           {id: "12345", question: "Test", correct_answer: '0'},
           {id: "123456", question: "Test 2", correct_answer: '1'},
           {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
       },
       {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
     ]
</code>```

answers document is like this:

```<code>{
  id: '327rhrne7fr873',
  user_id: '43757fn574057fnf',
  question_id: '8326ccbn73487290nc',
  answers: [
    { id: '12345', student_answer: '1'},
    { id: '123456', student_answer: '0'},
  ]
}
</code>```

so i want to return something like this:

```<code>[
    {
        _id: '8326ccbn73487290nc',
        questions: [
          {id: "12345", question: "Test", correct_answer: '0', student_answers: '1'},
          {id: "123456", question: "Test 2", correct_answer: '1', , student_answers: '0'},
          {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
    },
    {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
]
</code>```

Can anyone help me how can i do something like that.

答:
Although it's possible to get your desired structure in MongoDB. If you do not need extra aggregation steps, I would suggest to query only the data you need, and do the data mapping in your application layer, because it's much easier and we don't want to put too much work on the database.

However, you can use the following approach to get (close to) your expected output, I have kept the field student_answer, from answers collection and did not rename it to student_answers, you can do the extra steps if needed.

```<code>db.questions.aggregate([
  {
    $lookup: {
      from: "answers",
      let: {
        question_id: "$_id"
      },
      as: "answer",
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$question_id",
                    "$$question_id"
                  ]
                },
                {
                  $eq: [
                    "$user_id",
                    userId // insert user id variable here
                  ]
                }
              ]
            }
          }
        }
      ]
    }
  },
  {
    $unwind: {
      path: "$answer",
      preserveNullAndEmptyArrays: true
    }
  }, // up until this step, you already got all the data you need. You can stop here and do the extra steps in your application layer
  {
    $set: {
      questions: {
        $map: {
          input: "$questions",
          in: {
            $mergeObjects: [
              "$$this",
              {
                $arrayElemAt: [
                  {
                    $filter: {
                      input: "$answer.answers",
                      as: "answer",
                      cond: {
                        $eq: [
                          "$$this.id",
                          "$$answer.id"
                        ]
                      }
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $unset: "answer" // cleanup by removing temporary field answer
  }
])

</code>```

Mongo Playground

Body:
I have two collections 'questions' and 'answers'.
questions document is like this:

      [
        {
          _id: "8326ccbn73487290nc",
          questions: [
           {id: "12345", question: "Test", correct_answer: '0'},
           {id: "123456", question: "Test 2", correct_answer: '1'},
           {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
       },
       {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
     ]

answers document is like this:

{
  id: '327rhrne7fr873',
  user_id: '43757fn574057fnf',
  question_id: '8326ccbn73487290nc',
  answers: [
    { id: '12345', student_answer: '1'},
    { id: '123456', student_answer: '0'},
  ]
}

so i want to return something like this:

[
    {
        _id: '8326ccbn73487290nc',
        questions: [
          {id: "12345", question: "Test", correct_answer: '0', student_answers: '1'},
          {id: "123456", question: "Test 2", correct_answer: '1', , student_answers: '0'},
          {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
    },
    {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
]

Can anyone help me how can i do something like that.

Body:
Although it's possible to get your desired structure in MongoDB. If you do not need extra aggregation steps, I would suggest to query only the data you need, and do the data mapping in your application layer, because it's much easier and we don't want to put too much work on the database.

However, you can use the following approach to get (close to) your expected output, I have kept the field student_answer, from answers collection and did not rename it to student_answers, you can do the extra steps if needed.

db.questions.aggregate([
  {
    $lookup: {
      from: "answers",
      let: {
        question_id: "$_id"
      },
      as: "answer",
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$question_id",
                    "$$question_id"
                  ]
                },
                {
                  $eq: [
                    "$user_id",
                    userId // insert user id variable here
                  ]
                }
              ]
            }
          }
        }
      ]
    }
  },
  {
    $unwind: {
      path: "$answer",
      preserveNullAndEmptyArrays: true
    }
  }, // up until this step, you already got all the data you need. You can stop here and do the extra steps in your application layer
  {
    $set: {
      questions: {
        $map: {
          input: "$questions",
          in: {
            $mergeObjects: [
              "$$this",
              {
                $arrayElemAt: [
                  {
                    $filter: {
                      input: "$answer.answers",
                      as: "answer",
                      cond: {
                        $eq: [
                          "$$this.id",
                          "$$answer.id"
                        ]
                      }
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $unset: "answer" // cleanup by removing temporary field answer
  }
])

Mongo Playground


问:
Is it possible to create plot (matplotlib) with a href in its title?
I wanted to make this link interactive, unfortunately it doesn't display any html content.
Is there any way to make this title as a href?

```<code>    from matplotlib import pyplot as plt
    import numpy as np

    fig, axs1 = plt.subplots(1)
    import numpy as np
    x = np.linspace(0, 2 * np.pi, 400)
    y = np.sin(x ** 2)
    axs1.plot(x)
    axs1.set_title("<a href=vk.com>vk.com</a>")
    plt.show()

</code>```

答:
You can set text labels as hyperlink. But you can't set title as hyperlink.

For the first one, see a stack-overflow answer.

Body:
I wanted to make this link interactive, unfortunately it doesn't display any html content.
Is there any way to make this title as a href?

    from matplotlib import pyplot as plt
    import numpy as np

    fig, axs1 = plt.subplots(1)
    import numpy as np
    x = np.linspace(0, 2 * np.pi, 400)
    y = np.sin(x ** 2)
    axs1.plot(x)
    axs1.set_title("vk.com")
    plt.show()


问:
Getting multiple different ratings for different items to work
So I've been trying to get a star rating for multiple items to work, but with how my code is, I think they're using each other's ratings for themselves.

HTML:

```<code>                <div class="thumbnail">
                    <img src="https://images.unsplash.com/photo-1470315232801-e91a8bb8adb6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1248&q=80" />
                    <div class="caption">
                        <h3>Buck Moon</h3>
                        <p>Alan Emory</p>
                        <p>32 upvotes</p>
                        <div class="row">
                            <div class="col-md-offset-1">
                                <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="" starmark(this) id="1three" style="font-size:40px;cursor:pointer"></span>
                                <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="" starmark(this) id="2three" style="font-size:40px;cursor:pointer"></span>
                                <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="" starmark(this) id="3three" style="font-size:40px;cursor:pointer"></span>
                                <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="" starmark(this) id="4three" style="font-size:40px;cursor:pointer"></span>
                                <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="" starmark(this) id="5three" style="font-size:40px;cursor:pointer"></span>
                                <br />
                                <button class="btn2 btn-default" onclick="showrating()"></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
</code>```

I've set the button to be a submit for the rating, but not sure why it keeps the other instances of the star rating.

How do I fix this using a separate file or whatever I need to do to make them apply to different buttons? Also, I've tried renaming the ratings and it still keeps those in the buttons.

答:
You can do it like this:

function starmark(el) {
  $(".fa-star").removeClass("active");
  $(el).addClass("active");
}

function showrating() {
  let rating = $(".fa-star.active").attr("id").charAt(0);
  console.log(rating);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  color:red;
}</code>```

        1
        2
        3
        4
        5

        <button class="btn2 btn-default" onclick="showrating()">ShowRating</button>

```

Body:
So I've been trying to get a star rating for multiple items to work, but with how my code is, I think they're using each other's ratings for themselves.

HTML:

Buck Moon

Alan Emory

32 upvotes

                                <button class="btn2 btn-default" onclick="showrating()"></button>

I've set the button to be a submit for the rating, but not sure why it keeps the other instances of the star rating.

How do I fix this using a separate file or whatever I need to do to make them apply to different buttons? Also, I've tried renaming the ratings and it still keeps those in the buttons.

Body:
You can do it like this:

function starmark(el) {
  $(".fa-star").removeClass("active");
  $(el).addClass("active");
}

function showrating() {
  let rating = $(".fa-star.active").attr("id").charAt(0);
  console.log(rating);
}

.active {
  color:red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
      <div class="col-md-offset-1">
        <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="starmark(this)"  id="1three" style="font-size:40px;cursor:pointer">1</span>
        <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="starmark(this)"  id="2three" style="font-size:40px;cursor:pointer">2</span>
        <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="starmark(this)"  id="3three" style="font-size:40px;cursor:pointer">3</span>
        <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="starmark(this)"  id="4three" style="font-size:40px;cursor:pointer">4</span>
        <span class="fa fa-star checked" onmouseover="starmark(this)" onclick="starmark(this)"  id="5three" style="font-size:40px;cursor:pointer">5</span>
        <br />
        <button class="btn2 btn-default" onclick="showrating()">ShowRating</button>
      </div>
    </div>


答:
Use mask instead:

.box {
  display: inline-block;
  width: 200px;
  height: 200px;
  background: url(https://picsum.photos/id/100/800/800) center/cover;
  -webkit-mask: radial-gradient(circle 40px, #0000 98%, #fff);
          mask: radial-gradient(circle 40px, #0000 98%, #fff);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div>

<div class="box" style="width:300px;height:300px"></div></code>```

You can have it responsive like below:

.box {
  display:inline-block;
  width:200px;
  height:200px;
  background:url(https://picsum.photos/id/100/800/800) center/cover;
  -webkit-mask:radial-gradient(circle closest-side,#0000 calc(100% - 30px),#fff calc(100% - 32px));
          mask:radial-gradient(circle closest-side,#0000 calc(100% - 30px),#fff calc(100% - 32px));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div>

<div class="box" style="width:300px;height:300px"></div></code>```

Title: how to clip a circle inside a shape

Body:
It's a rectangle inside a shape。

-webkit-clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);
clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);

how can i clip a circle inside?

Body:
Use mask instead:

.box {
  display: inline-block;
  width: 200px;
  height: 200px;
  background: url(https://picsum.photos/id/100/800/800) center/cover;
  -webkit-mask: radial-gradient(circle 40px, #0000 98%, #fff);
          mask: radial-gradient(circle 40px, #0000 98%, #fff);
}

<div class="box"></div>

<div class="box" style="width:300px;height:300px"></div>

You can have it responsive like below:

.box {
  display:inline-block;
  width:200px;
  height:200px;
  background:url(https://picsum.photos/id/100/800/800) center/cover;
  -webkit-mask:radial-gradient(circle closest-side,#0000 calc(100% - 30px),#fff calc(100% - 32px));
          mask:radial-gradient(circle closest-side,#0000 calc(100% - 30px),#fff calc(100% - 32px));
}

<div class="box"></div>

<div class="box" style="width:300px;height:300px"></div>


问:
How do I convert these SVG properties into CSS declarations?
I have the following HTML:

<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <circle cx="10.5" cy="10.5" r="7.5"></circle>
  <line x1="21" y1="21" x2="15.8" y2="15.8"></line>
</svg>
```

<p>The HTML looks clunky at best, how do I convert it's properties into CSS?</p>

<p>For example:</p>

<pre class="lang-css prettyprint-override"><code>#search-svg {
  width: 20;
  height: 20;
  viewBox: 0 0 24 24;
  fill: none;
  stroke: currentColor;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round
}
</code>```

I know that the width, height and fill properties exist and can be converted into CSS.

However I don't know how the other properties work or what their CSS equivalents are, and a quick search on caniuse yeilds no results for CSS properties beginning with stroke.

Thank you.

答:
I checked it and almost all properties from your example works, you have to remember that size properties needs unit eg. px.

```<code>svg {
  width: 40px;
  height: 40px;
  fill: red;
  stroke: green;
  stroke-width: 4px;
  stroke-linecap: round;
  stroke-linejoin: round;
}

circle {
  cx: 12px;
  cy: 13px;
  r: 6px;
}
</code>```

Also found an source of more data about SVG properties https://css-tricks.com/svg-properties-and-css/

Body:
I have the following HTML:

<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <circle cx="10.5" cy="10.5" r="7.5"></circle>
  <line x1="21" y1="21" x2="15.8" y2="15.8"></line>
</svg>

The HTML looks clunky at best, how do I convert it's properties into CSS?

For example:

#search-svg {
  width: 20;
  height: 20;
  viewBox: 0 0 24 24;
  fill: none;
  stroke: currentColor;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round
}

I know that the width, height and fill properties exist and can be converted into CSS.

However I don't know how the other properties work or what their CSS equivalents are, and a quick search on caniuse yeilds no results for CSS properties beginning with stroke.

Thank you.

Body:
I checked it and almost all properties from your example works, you have to remember that size properties needs unit eg. px.

svg {
  width: 40px;
  height: 40px;
  fill: red;
  stroke: green;
  stroke-width: 4px;
  stroke-linecap: round;
  stroke-linejoin: round;
}

circle {
  cx: 12px;
  cy: 13px;
  r: 6px;
}

Also found an source of more data about SVG properties https://css-tricks.com/svg-properties-and-css/


问:
Trouble using extract_tables() function in tabulizer package:
I am trying to scrape tables from a PDF but from my local directory rather than from a web-browser (as it is not opening directly into a browser). Yet, I download the pdf onto my local directory and trying from there to read my tables only!

When I run my code:

```<code>PATH <-"C:\\Users\\gabrielburcea\\Rprojects\\Reports_scraping\\data_scraped\\icnarc_29052020\\icnarc_200529.pdf"
test <- extract_tables(PATH, output = "data.frame", pages = c(10, 11))
</code>```

I get the following error which I cannot find anywhere on internet:

```<code>Error in .jcall("RJavaTools", "Ljava/lang/Object;", "newInstance", .jfindClass(class),  :
java.io.FileNotFoundException: /Library/Frameworks/R.framework/Versions/3.6/Resources/library (Is a directory)
</code>```

Is there a way to solve this issue?

The .pdf I am trying to scrape has been downloaded to my computer from the this website.

The report is titled ICNARC COVID-19 report 2020-05-29.pdf and can be downloaded using the link of the right-side of the page.

Below is the output of traceback() after I've received my error message.

```<code>   8: stop(list(message = "java.io.FileNotFoundException: /Library/Frameworks/R.framework/Versions/3.6/Resources/library (Is a directory)",
           call = .jcall("RJavaTools", "Ljava/lang/Object;", "newInstance",
               .jfindClass(class), .jarray(p, "java/lang/Object", dispatch = FALSE),
               .jarray(pc, "java/lang/Class", dispatch = FALSE), evalString = FALSE,
               evalArray = FALSE, use.true.class = TRUE), jobj = new("jobjRef",
               jobj = <pointer: 0x7fd1ba0972b0>, jclass = "java/io/FileNotFoundException")))
    7: .jcheck(silent = FALSE)
    6: .jcall("RJavaTools", "Ljava/lang/Object;", "newInstance", .jfindClass(class),
           .jarray(p, "java/lang/Object", dispatch = FALSE), .jarray(pc,
               "java/lang/Class", dispatch = FALSE), evalString = FALSE,
           evalArray = FALSE, use.true.class = TRUE)
    5: .J(Class@name, ...)
    4: new(J("java.io.FileInputStream"), name <- localfile)
    3: new(J("java.io.FileInputStream"), name <- localfile)
    2: load_doc(file, password = password, copy = copy)
    1: extract_tables(PATH, output = "data.frame", pages = c(10, 11))
</code>```

and sessionInfo() returns this:

```<code>    R version 3.6.1 (2019-07-05)
    Platform: x86_64-apple-darwin15.6.0 (64-bit)
    Running under: macOS Mojave 10.14.6

    Matrix products: default
    BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
    LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

    locale:
    [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

    attached base packages:
    [1] stats     graphics  grDevices utils     datasets  methods   base

    other attached packages:
     [1] forcats_0.4.0   stringr_1.4.0   dplyr_0.8.5     purrr_0.3.3     readr_1.3.1     tidyr_1.0.3     tibble_3.0.1
     [8] ggplot2_3.3.0   tidyverse_1.3.0 tabulizer_0.2.2

    loaded via a namespace (and not attached):

         [1] Rcpp_1.0.1          cellranger_1.1.0    pillar_1.4.3        compiler_3.6.1      dbplyr_1.4.2
         [6] tools_3.6.1         lubridate_1.7.4     jsonlite_1.6        lifecycle_0.2.0     gtable_0.3.0
        [11] nlme_3.1-140        lattice_0.20-38     pkgconfig_2.0.2     png_0.1-7           rlang_0.4.6
        [16] reprex_0.3.0        cli_2.0.2           DBI_1.0.0           rstudioapi_0.11     haven_2.2.0
        [21] rJava_0.9-12        withr_2.1.2         xml2_1.3.2          httr_1.4.1          fs_1.3.1
        [26] hms_0.5.3           generics_0.0.2      vctrs_0.3.0         grid_3.6.1          tidyselect_1.1.0
        [31] glue_1.3.1          R6_2.4.0            fansi_0.4.0         readxl_1.3.1        modelr_0.1.8
        [36] magrittr_1.5        scales_1.0.0        tabulizerjars_1.0.1 backports_1.1.4     ellipsis_0.3.0
        [41] rvest_0.3.5         assertthat_0.2.1    colorspace_1.4-1    stringi_1.4.6       munsell_0.5.0
        [46] broom_0.5.6         crayon_1.3.4
</code>```

Thanks in advance for any help!

答:
As discussed in comments, code is working fine on windows.

```<code>library(tabulizer)
link <- "https://www.icnarc.org/DataServices/Attachments/Download/8419d345-c7a1-ea11-9126-00505601089b"
dfr.list <- extract_tables(link, output="data.frame", pages=10:11)
</code>```

To get every table out of the list use list2env where you set env=ironment to .GlobalEnv which is your workspace getwd(). Beforehand you need to give the unnamed list names.

```<code>names(dfr.list) <- paste0("dfr", 1:length(dfr.list))  ## give names
list2env(dfr.list, envir=.GlobalEnv)  ## put to environment

ls()
# [1] "dfr.list"    "dfr1"        "dfr2"        "dfr3"        "link"
# [2] "tables.list"
</code>```

.pdf extraction often is not perfect and we have to clean the data afterwards. To improve the result try to play around with the area=, columns=, and options of extract_tables, read the help page ?extract_tables, consult the documentation.

Body:
I am trying to scrape tables from a PDF but from my local directory rather than from a web-browser (as it is not opening directly into a browser). Yet, I download the pdf onto my local directory and trying from there to read my tables only!

When I run my code:

PATH <-"C:\\Users\\gabrielburcea\\Rprojects\\Reports_scraping\\data_scraped\\icnarc_29052020\\icnarc_200529.pdf"
test <- extract_tables(PATH, output = "data.frame", pages = c(10, 11))

I get the following error which I cannot find anywhere on internet:

Error in .jcall("RJavaTools", "Ljava/lang/Object;", "newInstance", .jfindClass(class),  :
java.io.FileNotFoundException: /Library/Frameworks/R.framework/Versions/3.6/Resources/library (Is a directory)

Is there a way to solve this issue?

The .pdf I am trying to scrape has been downloaded to my computer from the this website.

The report is titled ICNARC COVID-19 report 2020-05-29.pdf and can be downloaded using the link of the right-side of the page.

Below is the output of traceback() after I've received my error message.

   8: stop(list(message = "java.io.FileNotFoundException: /Library/Frameworks/R.framework/Versions/3.6/Resources/library (Is a directory)",
           call = .jcall("RJavaTools", "Ljava/lang/Object;", "newInstance",
               .jfindClass(class), .jarray(p, "java/lang/Object", dispatch = FALSE),
               .jarray(pc, "java/lang/Class", dispatch = FALSE), evalString = FALSE,
               evalArray = FALSE, use.true.class = TRUE), jobj = new("jobjRef",
               jobj = <pointer: 0x7fd1ba0972b0>, jclass = "java/io/FileNotFoundException")))
    7: .jcheck(silent = FALSE)
    6: .jcall("RJavaTools", "Ljava/lang/Object;", "newInstance", .jfindClass(class),
           .jarray(p, "java/lang/Object", dispatch = FALSE), .jarray(pc,
               "java/lang/Class", dispatch = FALSE), evalString = FALSE,
           evalArray = FALSE, use.true.class = TRUE)
    5: .J(Class@name, ...)
    4: new(J("java.io.FileInputStream"), name <- localfile)
    3: new(J("java.io.FileInputStream"), name <- localfile)
    2: load_doc(file, password = password, copy = copy)
    1: extract_tables(PATH, output = "data.frame", pages = c(10, 11))

and sessionInfo() returns this:

    R version 3.6.1 (2019-07-05)
    Platform: x86_64-apple-darwin15.6.0 (64-bit)
    Running under: macOS Mojave 10.14.6

    Matrix products: default
    BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
    LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

    locale:
    [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

    attached base packages:
    [1] stats     graphics  grDevices utils     datasets  methods   base

    other attached packages:
     [1] forcats_0.4.0   stringr_1.4.0   dplyr_0.8.5     purrr_0.3.3     readr_1.3.1     tidyr_1.0.3     tibble_3.0.1
     [8] ggplot2_3.3.0   tidyverse_1.3.0 tabulizer_0.2.2

    loaded via a namespace (and not attached):

         [1] Rcpp_1.0.1          cellranger_1.1.0    pillar_1.4.3        compiler_3.6.1      dbplyr_1.4.2
         [6] tools_3.6.1         lubridate_1.7.4     jsonlite_1.6        lifecycle_0.2.0     gtable_0.3.0
        [11] nlme_3.1-140        lattice_0.20-38     pkgconfig_2.0.2     png_0.1-7           rlang_0.4.6
        [16] reprex_0.3.0        cli_2.0.2           DBI_1.0.0           rstudioapi_0.11     haven_2.2.0
        [21] rJava_0.9-12        withr_2.1.2         xml2_1.3.2          httr_1.4.1          fs_1.3.1
        [26] hms_0.5.3           generics_0.0.2      vctrs_0.3.0         grid_3.6.1          tidyselect_1.1.0
        [31] glue_1.3.1          R6_2.4.0            fansi_0.4.0         readxl_1.3.1        modelr_0.1.8
        [36] magrittr_1.5        scales_1.0.0        tabulizerjars_1.0.1 backports_1.1.4     ellipsis_0.3.0
        [41] rvest_0.3.5         assertthat_0.2.1    colorspace_1.4-1    stringi_1.4.6       munsell_0.5.0
        [46] broom_0.5.6         crayon_1.3.4

Thanks in advance for any help!

Body:
As discussed in comments, code is working fine on windows.

library(tabulizer)
link <- "https://www.icnarc.org/DataServices/Attachments/Download/8419d345-c7a1-ea11-9126-00505601089b"
dfr.list <- extract_tables(link, output="data.frame", pages=10:11)

To get every table out of the list use list2env where you set env=ironment to .GlobalEnv which is your workspace getwd(). Beforehand you need to give the unnamed list names.

names(dfr.list) <- paste0("dfr", 1:length(dfr.list))  ## give names
list2env(dfr.list, envir=.GlobalEnv)  ## put to environment

ls()
# [1] "dfr.list"    "dfr1"        "dfr2"        "dfr3"        "link"
# [2] "tables.list"

.pdf extraction often is not perfect and we have to clean the data afterwards. To improve the result try to play around with the area=, columns=, and options of extract_tables, read the help page ?extract_tables, consult the documentation.


问:
Access to array offset on value of type int - drupal
I'm doing a personnal project using Drupal. In localhost everything is working fine but when I put it on my raspberry server i have this error:

Notice: Trying to access array offset on value of type int in Drupal\Core\Render\Element::children() (line 81 of core/lib/Drupal/Core/Render/Element.php).

I have far more error but its all like this one. I looked on the internet and there is a lot of information saying that it comes from php. I'm using PHP 7.2.4 and the server is using php 7.4.6.

Information about my server:

Raspberry pi 3 model b, os raspbian

If you need more information, I can provide it to you.

Cordially

答:
Yes, the version difference of PHP 7.2.4 and PHP 7.4.6 can explain the different behavior.

Why not installing 7.4.6 on your local machine and test the code with exact same PHP as your final target (raspberry pi)?

or downgrade the PHP on your raspberry pi to 7.2.4?

you could give it a try to downgrade raspberry pi to PHP7.2:

create a backup of your SD card

install PHP7.2 sudo apt install -y php7.2 php7.2-cli php7.2-common

make PHP7.2 the default sudo update-alternatives --set php /usr/bin/php7.2

double check php -v should tell PHP7.2

done


答:
If you want to change the svg css, you should also change the child tag css.

 #search-svg {
   width: 50px;
   height: 50px;

 }
 #search-svg circle {
  fill:none;
  stroke: currentColor;
    stroke-width: 3;
    stroke-linecap: round;
   stroke-linejoin: round
 }
 #search-svg line{
  stroke: currentColor;
  stroke-linecap: round;
    stroke-linejoin: round
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Test</title>
</head>
<body>
 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" id ="search-svg">
   <circle cx="10.5" cy="10.5" r="7.5"></circle>
   <line x1="21" y1="21" x2="15.8" y2="15.8"></line>
 </svg>
</body>
</html></code>```

Title: How do I convert these SVG properties into CSS declarations?

Body:
If you want to change the svg css, you should also change the child tag css.

 #search-svg {
   width: 50px;
   height: 50px;

 }
 #search-svg circle {
  fill:none;
  stroke: currentColor;
    stroke-width: 3;
    stroke-linecap: round;
   stroke-linejoin: round
 }
 #search-svg line{
  stroke: currentColor;
  stroke-linecap: round;
    stroke-linejoin: round
 }

<!DOCTYPE html>
<html>
<head>
 <title>Test</title>
</head>
<body>
 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" id ="search-svg">
   <circle cx="10.5" cy="10.5" r="7.5"></circle>
   <line x1="21" y1="21" x2="15.8" y2="15.8"></line>
 </svg>
</body>
</html>


问:
How does Android application store state
I want to ask that where does the password gets stored after we login to the application from our phone. I need to know the mechanism of working of how the state is saved in the case of mobile applications.</p>

答:
It's not much safe to store passwords. Usually apps store some token(Though it really depends on authentication method).
And in addition to Antonio's answer,android has released EncryptedSharedPreferences which encrypts key & values to provide more security.</p>