问:
Custom Servlet Filter not getting applied to all resources
I have created a simple Filter class that adds some response headers to all the resources requested.
I have created a jar file and added the same to tomcat lib folder. Also the filter is added to the web.xml for url mapping /*

When I request the page of my application I can see filter is been invoked as the sysout statements are printed correctly but the headers are getting added to some of the assets only.
I am pretty confused as to why it is getting added to only some assets and not to all.

Filter class as below

```<code>package com.headers.config;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MySecurityHeadersFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

chain.doFilter(request, response);

HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;

httpResp.addHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';base-uri 'self';form-action 'self';");
httpResp.addHeader("Expect-CT", "max-age=86400, enforce, report-uri=https://"+ httpReq.getHeader("host").trim() +"/bham/user/reportCT");
httpResp.addHeader("Feature-Policy", "vibrate 'none'; geolocation 'none';");
httpResp.addHeader("Referrer-Policy", "no-referrer-when-downgrade");

System.out.println("Response Headers: "+((HttpServletResponse) response).getHeaderNames());
}

@Override
public void destroy() {
}
}

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.headers.config</groupId>
<artifactId>MySecurityHeadersFilter</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>MySecurityHeadersFilter Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
    <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<build>
    <finalName>MySecurityHeadersFilter</finalName>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>
</code>```

Any help will be greatly appreciated.

I am using tomcat 9 and have added below filter mapping in web.xml. This is the only filter added

```<code><filter>
<filter-name>MySecurityHeadersFilter</filter-name>
<filter-class>com.cdp.headers.config.MySecurityHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MySecurityHeadersFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>MySecurityHeadersFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<async-supported>true</async-supported>
</filter>

<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>ExpiresFilter</filter-name>
<filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
<init-param>
<param-name>ExpiresByType text/css</param-name>
<param-value>access plus 10 minutes</param-value>
</init-param>
<init-param>
<param-name>ExpiresByType application/javascript</param-name>
<param-value>access plus 10 minutes</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>ExpiresFilter</filter-name>
<url-pattern>*.js</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ExpiresFilter</filter-name>
<url-pattern>*.css</url-pattern>
</filter-mapping>
</code>```

WHen I execute the URL this is what I can see in the catalina logs. The headers that I have added are not present.

```<code>Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
</code>```

答:
You can't set headers once the response is committed.

The reason your filter works for some requests and not others is that some requests commit the response before your filter can add the headers and some do not.

If you move the chain.doFilter(request, response); call to after the code where you set the headers the Filter should apply to everything.

If you want to ensure that the subsequent requests don't change the headers, you have several options. Committing the response is the simplest but it is rather a blunt instrument and may break some of the downstream requests (e.g. any that try to do a RequestDispatcher.forward(). A better solution is to wrap the response and intercept all the header altering calls and filter out the ones you don't want.

Body:
I have created a simple Filter class that adds some response headers to all the resources requested.
I have created a jar file and added the same to tomcat lib folder. Also the filter is added to the web.xml for url mapping /*

When I request the page of my application I can see filter is been invoked as the sysout statements are printed correctly but the headers are getting added to some of the assets only.
I am pretty confused as to why it is getting added to only some assets and not to all.

Filter class as below

package com.headers.config;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MySecurityHeadersFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

chain.doFilter(request, response);

HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;

httpResp.addHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';base-uri 'self';form-action 'self';");
httpResp.addHeader("Expect-CT", "max-age=86400, enforce, report-uri=https://"+ httpReq.getHeader("host").trim() +"/bham/user/reportCT");
httpResp.addHeader("Feature-Policy", "vibrate 'none'; geolocation 'none';");
httpResp.addHeader("Referrer-Policy", "no-referrer-when-downgrade");

System.out.println("Response Headers: "+((HttpServletResponse) response).getHeaderNames());
}

@Override
public void destroy() {
}
}

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.headers.config</groupId>
<artifactId>MySecurityHeadersFilter</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>MySecurityHeadersFilter Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<build>
    <finalName>MySecurityHeadersFilter</finalName>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

Any help will be greatly appreciated.

I am using tomcat 9 and have added below filter mapping in web.xml. This is the only filter added

<filter>
<filter-name>MySecurityHeadersFilter</filter-name>
<filter-class>com.cdp.headers.config.MySecurityHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MySecurityHeadersFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>MySecurityHeadersFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<async-supported>true</async-supported>
</filter>

<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>ExpiresFilter</filter-name>
<filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
<init-param>
<param-name>ExpiresByType text/css</param-name>
<param-value>access plus 10 minutes</param-value>
</init-param>
<init-param>
<param-name>ExpiresByType application/javascript</param-name>
<param-value>access plus 10 minutes</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>ExpiresFilter</filter-name>
<url-pattern>*.js</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ExpiresFilter</filter-name>
<url-pattern>*.css</url-pattern>
</filter-mapping>

WHen I execute the URL this is what I can see in the catalina logs. The headers that I have added are not present.

Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]
Response Headers: [Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Accept-Ranges, ETag, Last-Modified, Cache-Control, Expires, Content-Type, Content-Length, Date, Keep-Alive, Connection, Server]


来源: stackexchange

问:
Challenging MySQL query
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

```<code>SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt
</code>```

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

```<code>/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8
</code>```

答:
I've adjusted the other query from Your Previous Question to simply include a WHERE clause on your ParentID.  That was the condition I didn't know you were looking for to limit return set.  I added where the post ID = the one you want OR the ParentID = the one you want.

By having the ORDER by the POST ID, it will naturally have the originating parent ID in the first position as others would be derived from it sequentially.  I think that will solve you again.

ContentLicense: CC BY-SA 3.0

Title: Challenging MySQL query

Body:
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8


问:
How can I move -lm to the end using a makefile for c?
I have the following makefile

```<code>CC=cc
CFLAGS= -Wall -Wextra -pedantic -lm
DEPS = fileMake.h
OBJ = fileMake.o fileFunction.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

fileMake: $(OBJ)
    $(CC) -o $@ $^ $(CFLAGS)
</code>```

It produces the follwing output:

cc -Wall -Wextra -pedantic -lm    secondDegreeFormula.c   -o secondDegreeFormula

I would like to move the -lm to the end and remove the extra spaces, like:

cc -Wall -Wextra -pedantic secondDegreeFormula.c -o secondDegreeFormula -lm

how can I do this?

EDIT:

```<code>CC=cc
CFLAGS=-Wall -Wextra -pedantic
LIBS=-lm
DEPS=fileMake.h
OBJ=fileMake.o fileFunction.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS) $(LIBS)

fileMake: $(OBJ)
    $(CC) -o $@ $^ $(CFLAGS) $(LIBS)
</code>```

EDIT 2:

```<code>CC=cc
CFLAGS= -Wall -Wextra -pedantic
LIBS= -lm
DEPS=fileMake.h
OBJ=fileMake.o fileFunction.o

fileMake: $(OBJ)
    $(CC) $(CFLAGS) -o $@ $^ $(LIBS)
</code>```

答:
You need to make the dynamic libraries a separate variable and include that where appropriate.</p>

```<code>CFLAGS= -Wall -Wextra -pedantic
LIBS= -lm

...

fileMake: $(OBJ)
    $(CC) $(CFLAGS) -o $@ $^ $(LIBS)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following makefile

CC=cc
CFLAGS= -Wall -Wextra -pedantic -lm
DEPS = fileMake.h
OBJ = fileMake.o fileFunction.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

fileMake: $(OBJ)
    $(CC) -o $@ $^ $(CFLAGS)

It produces the follwing output:

cc -Wall -Wextra -pedantic -lm    secondDegreeFormula.c   -o secondDegreeFormula

I would like to move the -lm to the end and remove the extra spaces, like:

cc -Wall -Wextra -pedantic secondDegreeFormula.c -o secondDegreeFormula -lm

how can I do this?

EDIT:

CC=cc
CFLAGS=-Wall -Wextra -pedantic
LIBS=-lm
DEPS=fileMake.h
OBJ=fileMake.o fileFunction.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS) $(LIBS)

fileMake: $(OBJ)
    $(CC) -o $@ $^ $(CFLAGS) $(LIBS)

EDIT 2:

CC=cc
CFLAGS= -Wall -Wextra -pedantic
LIBS= -lm
DEPS=fileMake.h
OBJ=fileMake.o fileFunction.o

fileMake: $(OBJ)
    $(CC) $(CFLAGS) -o $@ $^ $(LIBS)

Body:
You need to make the dynamic libraries a separate variable and include that where appropriate.

CFLAGS= -Wall -Wextra -pedantic
LIBS= -lm

...

fileMake: $(OBJ)
    $(CC) $(CFLAGS) -o $@ $^ $(LIBS)


问:
putting a space between the 3rd and 4th characters of postal code in Python
I have a df (data frame) in Python with with a postal_code variable that has Canadian  postal codes. All the postal codes are collected in a row such as k1b6j2. But , for me to use the the 'pgeocode' package i need the postal code in a standard form which is like k1b 6j2 (there must be a space between the 3rd and 4th character)

So, is there a way to replace all the postal codes with the modified ones in the df?

Many Thanks,
Ben

答:
How about:</p>

```<code>pcode = 'k1b6j2'
pcode = pcode[:3] + ' ' + pcode[3:]
</code>```

Body:
How about:

pcode = 'k1b6j2'
pcode = pcode[:3] + ' ' + pcode[3:]


问:
How to display jpg from db web page?
I have got table and display datas from database (mysql). I use thymeleaf. All fields are ok but sb.cover doesnt show jpg (blob column in my database). Have you got any ideas how to put jpg in web page using thymeleaf? Thanks

```<code><tr th:each="sb, poz : ${product}">
    <td th:text="${poz.count}">1</td>
    <td th:icon="${sb.cover}"></td>
    <td th:text="${sb.title}"></td>
    <td th:text="${sb.price}"></td>
    <td ><b><a th:href="@{/details}">DETAILS</a></b></td>
    <td ><b><a th:href="@{/cart}">ADD TO CART</a></b></td>
    </tr>
</code>```

答:
this method that converts the bytearray to base64 String so you can convert your product cover to base64  sring.
you need to add in the product class :

```<code>    public String generateBase64Image()
{
    return Base64.encodeBase64String(this.getCover());
}
</code>```

in the web page you need to call the metho generateBase64Image() in in your web page :

```<code> <img th:src="@{'data:image/jpeg;base64,'+${product.generateBase64Image()}}"  />
</code>```

Title: How to display jpg from db web page?

Body:
I have got table and display datas from database (mysql). I use thymeleaf. All fields are ok but sb.cover doesnt show jpg (blob column in my database). Have you got any ideas how to put jpg in web page using thymeleaf? Thanks

    1

    DETAILS
    ADD TO CART

Body:
this method that converts the bytearray to base64 String so you can convert your product cover to base64  sring.
you need to add in the product class :

    public String generateBase64Image()
{
    return Base64.encodeBase64String(this.getCover());
}

in the web page you need to call the metho generateBase64Image() in in your web page :

 <img th:src="@{'data:image/jpeg;base64,'+${product.generateBase64Image()}}"  />


问:
How to extract matching values from a column in a dataframe when semicolons are present in R?
I have a large dataframe of published articles for which I would like to extract all articles relating to a few authors specified in a separate list. The authors in the dataframe are grouped together in one column separated by a ; . Not all authors need to match, I would like to extract any article which has one author matched to the list. An example is below.

```<code>Title<-c("A", "B", "C")

AU<-c("Mark; John; Paul", "Simone; Lily; Poppy", "Sarah; Luke")

df<-cbind(Title, AU)

authors<-as.character(c("Mark", "John", "Luke"))

df[sapply(strsplit((as.character(df$AU)), "; "), function(x) any(authors %in% x)),]
</code>```

I would expect to return;

```<code>Title   AU
  A      Mark; John
  C      Sarah; Luke
</code>```

However with my large dataframe this command does not work to return all AU, it only returns rows which have a single AU not multiple ones.

Here is a dput from my larger dataframe of 5 rows

```<code>structure(list(AU = c("FOOKES PG;DEARMAN WR;FRANKLIN JA", "SIMS DG;DOWNHAM MAPS;MCQUILLIN J;GARDNER PS",
"TURNER BR", "BUTLER J;MARSH H;GOODARZI F", "OVERTON M"), TI = c("SOME ENGINEERING ASPECTS OF ROCK WEATHERING WITH FIELD EXAMPLES FROM DARTMOOR AND ELSEWHERE",
"RESPIRATORY SYNCYTIAL VIRUS INFECTION IN NORTH-EAST ENGLAND",
"TECTONIC AND CLIMATIC CONTROLS ON CONTINENTAL DEPOSITIONAL FACIES IN THE KAROO BASIN OF NORTHERN NATAL, SOUTH AFRICA",
"WORLD COALS: GENESIS OF THE WORLD'S MAJOR COALFIELDS IN RELATION TO PLATE TECTONICS",
"WEATHER AND AGRICULTURAL CHANGE IN ENGLAND, 1660-1739"), SO = c("QUARTERLY JOURNAL OF ENGINEERING GEOLOGY",
"BRITISH MEDICAL JOURNAL", "SEDIMENTARY GEOLOGY", "FUEL", "AGRICULTURAL HISTORY"
), JI = c("Q. J. ENG. GEOL.", "BRIT. MED. J.", "SEDIMENT. GEOL.",
"FUEL", "AGRICULTURAL HISTORY")
</code>```

答:
An option with str_extract

```<code>library(dplyr)
library(stringr)
df %>%
   mutate(Names = str_extract_all(Names, str_c(authors, collapse="|"))) %>%
   filter(lengths(Names) > 0)
#  Title      Names
#1     A Mark, John
#2     C       Luke
</code>```

data

```<code>df <- data.frame(Title, Names)
</code>```

Body:
I have a large dataframe of published articles for which I would like to extract all articles relating to a few authors specified in a separate list. The authors in the dataframe are grouped together in one column separated by a ; . Not all authors need to match, I would like to extract any article which has one author matched to the list. An example is below.

Title<-c("A", "B", "C")

AU<-c("Mark; John; Paul", "Simone; Lily; Poppy", "Sarah; Luke")

df<-cbind(Title, AU)

authors<-as.character(c("Mark", "John", "Luke"))

df[sapply(strsplit((as.character(df$AU)), "; "), function(x) any(authors %in% x)),]

I would expect to return;

Title   AU
  A      Mark; John
  C      Sarah; Luke

However with my large dataframe this command does not work to return all AU, it only returns rows which have a single AU not multiple ones.

Here is a dput from my larger dataframe of 5 rows

structure(list(AU = c("FOOKES PG;DEARMAN WR;FRANKLIN JA", "SIMS DG;DOWNHAM MAPS;MCQUILLIN J;GARDNER PS",
"TURNER BR", "BUTLER J;MARSH H;GOODARZI F", "OVERTON M"), TI = c("SOME ENGINEERING ASPECTS OF ROCK WEATHERING WITH FIELD EXAMPLES FROM DARTMOOR AND ELSEWHERE",
"RESPIRATORY SYNCYTIAL VIRUS INFECTION IN NORTH-EAST ENGLAND",
"TECTONIC AND CLIMATIC CONTROLS ON CONTINENTAL DEPOSITIONAL FACIES IN THE KAROO BASIN OF NORTHERN NATAL, SOUTH AFRICA",
"WORLD COALS: GENESIS OF THE WORLD'S MAJOR COALFIELDS IN RELATION TO PLATE TECTONICS",
"WEATHER AND AGRICULTURAL CHANGE IN ENGLAND, 1660-1739"), SO = c("QUARTERLY JOURNAL OF ENGINEERING GEOLOGY",
"BRITISH MEDICAL JOURNAL", "SEDIMENTARY GEOLOGY", "FUEL", "AGRICULTURAL HISTORY"
), JI = c("Q. J. ENG. GEOL.", "BRIT. MED. J.", "SEDIMENT. GEOL.",
"FUEL", "AGRICULTURAL HISTORY")

Body:
An option with str_extract

library(dplyr)
library(stringr)
df %>%
   mutate(Names = str_extract_all(Names, str_c(authors, collapse="|"))) %>%
   filter(lengths(Names) > 0)
#  Title      Names
#1     A Mark, John
#2     C       Luke

data

df <- data.frame(Title, Names)


问:
force R to always display package name in error message
I sometimes load multiple packages that export functions of the same name. For example, both Hmisc and dplyr have a summarize function, and I sometimes load both packages. I then call summarize, thinking that I am calling dplyr::summarize when I am really calling Hmisc::summarize. When that happens, I get an error message like this:

```<code>Error in summarize(., mean = mean(instRating)) :
  argument "by" is missing, with no default
</code>```

The message is initially hard to understand, because my code contains no errors. It takes me a minute to realize that I've called a function in the wrong package. The error message would be easier to understand if its first line included the name of the relevant package:

```<code>Error in Hmisc::summarize(., mean = mean(instRating)) :
</code>```

Is there a way to force R to display the package name in these error messages?

I know that I can get around the problem by typing out dplyr::summarize or by changing the order in which I load packages. But my interest lies with adding detail to R's error messages.

答:
From the documentation of the base option error:

'error': either a function or an expression governing the handling
           of non-catastrophic errors such as those generated by 'stop'
           as well as by signals and internally detected errors.  If the
           option is a function, a call to that function, with no
           arguments, is generated as the expression.  By default the
           option is not set: see 'stop' for the behaviour in that case.
           The functions 'dump.frames' and 'recover' provide
           alternatives that allow post-mortem debugging.  Note that
           these need to specified as e.g. 'options(error =
           utils::recover)' in startup files such as '.Rprofile'.

So it should be possible to define a function that returns the name of the package where the function that’s throwing the error lives. For example:

```<code>library(dplyr)
library(Hmisc)
data(mtcars)

print_package <- function() {
    calls <- sys.calls()
    call <- calls[[length(calls) - 1]]
    fun.name <- as.character(call)[1]
    pkg.name <- sub("package:", "", getAnywhere(fun.name)$where[1], fixed = TRUE)
    message (paste0("In ", pkg.name))
}

options(error = print_package)

summarize(mtcars$mpg)
</code>```

Returns:

```<code>Error in summarize(mtcars$mpg) :
  argument "by" is missing, with no default
In Hmisc
</code>```

Edit (using rlang::trace_back)

It turns out that there is a much cleaner way of doing this (credit goes to Hadley Wickham and his "Advanced R, Second edition"):

```<code>library(dplyr)
library(Hmisc)
data(mtcars)

print_trace_back <- function() {
    print(rlang::trace_back(bottom = sys.frame(-1)))
}

options(error = print_trace_back)
</code>```

Seems to handle errors gracefully:

```<code>> summarize(mtcars$mpg)
Error in summarize(mtcars$mpg) :
  argument "by" is missing, with no default
    █
 1. └─Hmisc::summarize(mtcars$mpg)
>
> Hmisc::summarize(mtcars$mpg)
Error in Hmisc::summarize(mtcars$mpg) :
  argument "by" is missing, with no default
    █
 1. └─Hmisc::summarize(mtcars$mpg)
>
> summarize(mtcars$mpg, as.character(mtcars$apa), mean)
Error in tapply(X, INDEX, FUN, ..., simplify = simplify) :
  arguments must have same length
    █
 1. └─Hmisc::summarize(mtcars$mpg, as.character(mtcars$apa), mean)
 2.   └─Hmisc::mApply(X, byc, FUN, ..., keepmatrix = nc > 1)
 3.     └─base::tapply(X, INDEX, FUN, ..., simplify = simplify)
 4.       └─base::stop("arguments must have same length")
>
> (function() stop("Error"))()
Error in (function() stop("Error"))() : Error
    █
 1. └─(function() stop("Error"))()
 2.   └─base::stop("Error")
</code>```

Body:
I sometimes load multiple packages that export functions of the same name. For example, both Hmisc and dplyr have a summarize function, and I sometimes load both packages. I then call summarize, thinking that I am calling dplyr::summarize when I am really calling Hmisc::summarize. When that happens, I get an error message like this:

Error in summarize(., mean = mean(instRating)) :
  argument "by" is missing, with no default

The message is initially hard to understand, because my code contains no errors. It takes me a minute to realize that I've called a function in the wrong package. The error message would be easier to understand if its first line included the name of the relevant package:

Error in Hmisc::summarize(., mean = mean(instRating)) :

Is there a way to force R to display the package name in these error messages?

I know that I can get around the problem by typing out dplyr::summarize or by changing the order in which I load packages. But my interest lies with adding detail to R's error messages.

Body:
From the documentation of the base option error:

'error': either a function or an expression governing the handling
           of non-catastrophic errors such as those generated by 'stop'
           as well as by signals and internally detected errors.  If the
           option is a function, a call to that function, with no
           arguments, is generated as the expression.  By default the
           option is not set: see 'stop' for the behaviour in that case.
           The functions 'dump.frames' and 'recover' provide
           alternatives that allow post-mortem debugging.  Note that
           these need to specified as e.g. 'options(error =
           utils::recover)' in startup files such as '.Rprofile'.

So it should be possible to define a function that returns the name of the package where the function that’s throwing the error lives. For example:

library(dplyr)
library(Hmisc)
data(mtcars)

print_package <- function() {
    calls <- sys.calls()
    call <- calls[[length(calls) - 1]]
    fun.name <- as.character(call)[1]
    pkg.name <- sub("package:", "", getAnywhere(fun.name)$where[1], fixed = TRUE)
    message (paste0("In ", pkg.name))
}

options(error = print_package)

summarize(mtcars$mpg)

Returns:

Error in summarize(mtcars$mpg) :
  argument "by" is missing, with no default
In Hmisc

Edit (using rlang::trace_back)

It turns out that there is a much cleaner way of doing this (credit goes to Hadley Wickham and his "Advanced R, Second edition"):

library(dplyr)
library(Hmisc)
data(mtcars)

print_trace_back <- function() {
    print(rlang::trace_back(bottom = sys.frame(-1)))
}

options(error = print_trace_back)

Seems to handle errors gracefully:

> summarize(mtcars$mpg)
Error in summarize(mtcars$mpg) :
  argument "by" is missing, with no default
    █
 1. └─Hmisc::summarize(mtcars$mpg)
>
> Hmisc::summarize(mtcars$mpg)
Error in Hmisc::summarize(mtcars$mpg) :
  argument "by" is missing, with no default
    █
 1. └─Hmisc::summarize(mtcars$mpg)
>
> summarize(mtcars$mpg, as.character(mtcars$apa), mean)
Error in tapply(X, INDEX, FUN, ..., simplify = simplify) :
  arguments must have same length
    █
 1. └─Hmisc::summarize(mtcars$mpg, as.character(mtcars$apa), mean)
 2.   └─Hmisc::mApply(X, byc, FUN, ..., keepmatrix = nc > 1)
 3.     └─base::tapply(X, INDEX, FUN, ..., simplify = simplify)
 4.       └─base::stop("arguments must have same length")
>
> (function() stop("Error"))()
Error in (function() stop("Error"))() : Error
    █
 1. └─(function() stop("Error"))()
 2.   └─base::stop("Error")


问:
Why does calling a Bash command from Ruby throw an error?
I'm attempting to execute the following bash command on some images using Ruby:

```<code>class Pingcrush
  def initialize
    Dir.foreach('drawable') do |item|
      next if item == '.' or item == '..'
      # do work on real items
      if item.end_with?(".png") then
        %x["wine pngcrush.exe -brute drawable/#{item} new/#{item}"]
      end
    end
  end
end
Pingcrush.new
</code>```

The directory I am in is the parent to both drawable and new, however, when when I attempt to run the script I always get the same error:

```<code>sh: wine pngcrush.exe -brute drawable/feed_cl.png new/feed_cl.png: not found
</code>```

Why is this happening? I tried switching around the path I'm calling in Ruby and can't seem to make this work.

答:
Its executing your shell but can't find wine. Try setting the full path to where wine is installed.</p>

```<code>which wine
</code>```

Body:
I'm attempting to execute the following bash command on some images using Ruby:

class Pingcrush
  def initialize
    Dir.foreach('drawable') do |item|
      next if item == '.' or item == '..'
      # do work on real items
      if item.end_with?(".png") then
        %x["wine pngcrush.exe -brute drawable/#{item} new/#{item}"]
      end
    end
  end
end
Pingcrush.new

The directory I am in is the parent to both drawable and new, however, when when I attempt to run the script I always get the same error:

sh: wine pngcrush.exe -brute drawable/feed_cl.png new/feed_cl.png: not found

Why is this happening? I tried switching around the path I'm calling in Ruby and can't seem to make this work.

Body:
Its executing your shell but can't find wine. Try setting the full path to where wine is installed.

which wine


问:
Count Distinct ID if it has more than 7 periods
I am trying to counts students absent if they have skipped more than 8 bell periods on the same day. I was wondering if somebody could help me out here. I tried a distinct count with a counts of bell periods greater than 6 (that is the ballpark) but it is not working. I am providing a sample table below here.

答:
You need to count the items, but using ALLEXECPT, to count the items by only using the filter context of StudentID and Date

So for example based on your data, assuming that student 101 missed 9 bells then:

```<code>Measure =
VAR _countofmisses = CALCULATE(COUNTAX(Table1, 1), ALLEXCEPT(Table1, Table1[Student ],Table1[Date]))
RETURN
IF(_countofmisses >=7, "Missed", "OK")
</code>```

Which would give the following:

You can change the COUNTAX to a SUMX and still get the same result. All it is doing is counting/summing 1 for each row of the filter condition.

If I've read it wrong and student 101 has attended all 9 bells, just change the IF >= clause to the logic you need.

Body:
You need to count the items, but using ALLEXECPT, to count the items by only using the filter context of StudentID and Date

So for example based on your data, assuming that student 101 missed 9 bells then:

Measure =
VAR _countofmisses = CALCULATE(COUNTAX(Table1, 1), ALLEXCEPT(Table1, Table1[Student ],Table1[Date]))
RETURN
IF(_countofmisses >=7, "Missed", "OK")

Which would give the following:

You can change the COUNTAX to a SUMX and still get the same result. All it is doing is counting/summing 1 for each row of the filter condition.

If I've read it wrong and student 101 has attended all 9 bells, just change the IF >= clause to the logic you need.


问:
How can I verify my SSL certificate for discord?
Whenever I try to start my Discord bot, this Error Message comes up and I have no idea why my SSL certificate is expired, since if I visit Discordapp.com via Browser the certificate is still not expired (valid through Nov 2020).

How can I update this specific certificate?

I am on Win 10 (ver 2004)

```<code>Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 936, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore  # noqa
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 1050, in create_connection
    transport, protocol = await self._create_connection_transport(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 1080, in _create_connection_transport
    await waiter
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\asyncio\sslproto.py", line 529, in data_received
    ssldata, appdata = self._sslpipe.feed_ssldata(data)
  File "C:\Users\Fabian Mooslechner\AppData\Local\Programs\Python\Python38-32\lib\asyncio\sslproto.py", line 189, in feed_ssldata
    self._sslobj.do_handshake()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 944, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".\bot.py", line 196, in <module>
    bot.run(TOKEN)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 261, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 165, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\client.py", line 480, in _request
    conn = await self._connector.connect(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 523, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 858, in _create_connection
    _, proto = await self._create_direct_connection(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 1004, in _create_direct_connection
    raise last_exc
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 980, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 938, in _wrap_create_connection
    raise ClientConnectorCertificateError(
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discordapp.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)')]
</code>```

答:
Sectigo's AddTrust External CA Root Expired May 30th.

Install this certificate to solve the problem. The download link is on the left hand side, half way down the page. Or you can just download it directly here.
You can find more information about the issue on Sectigo's Knowledge base here

Body:
Whenever I try to start my Discord bot, this Error Message comes up and I have no idea why my SSL certificate is expired, since if I visit Discordapp.com via Browser the certificate is still not expired (valid through Nov 2020).

How can I update this specific certificate?

I am on Win 10 (ver 2004)

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 936, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore  # noqa
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 1050, in create_connection
    transport, protocol = await self._create_connection_transport(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 1080, in _create_connection_transport
    await waiter
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\asyncio\sslproto.py", line 529, in data_received
    ssldata, appdata = self._sslpipe.feed_ssldata(data)
  File "C:\Users\Fabian Mooslechner\AppData\Local\Programs\Python\Python38-32\lib\asyncio\sslproto.py", line 189, in feed_ssldata
    self._sslobj.do_handshake()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 944, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".\bot.py", line 196, in <module>
    bot.run(TOKEN)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 261, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 165, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\client.py", line 480, in _request
    conn = await self._connector.connect(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 523, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 858, in _create_connection
    _, proto = await self._create_direct_connection(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 1004, in _create_direct_connection
    raise last_exc
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 980, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\connector.py", line 938, in _wrap_create_connection
    raise ClientConnectorCertificateError(
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discordapp.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)')]


问:
Return Original List using Substring in LINQ
I have the following data

```<code>ItemId | ItemName | ItemBy | ItemCreatedOn
  1    | A100     |  User1 |  2016-10-04
  2    | A200     |  User1 |  2016-10-04
  3    | A300     |  User1 |  2016-10-04
  4    | A400     |  User1 |  2016-10-04
  5    | A600     |  User1 |  2016-10-04
  6    | D100     |  User1 |  2016-10-04
  7    | D900     |  User1 |  2016-10-04
  8    | D200     |  User1 |  2016-10-04
  9    | D300     |  User1 |  2016-10-04
</code>```

This is what I want to return:

```<code> ItemId | ItemName | ItemBy | ItemCreatedOn
  5     | A600   |  User1 |  2016-10-04
</code>```

My approach

Get all the list of items starting with A

```<code>var allItems = db.Items.Where(x.ItemName[0] == itemName[0]).ToList();
</code>```

use substring

```<code>var items = allItems.Select(x => x.Substring(1));
</code>```

The above returns a list of string, but I want to return a list of all the items without A so that I can use Max() on ItemName to get the record I need

How can I return the list of objects and then use Max correctly?

答:
```<code>var items = new List<Item>
{
    new Item{ItemId = 1, ItemName = "A300", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 2, ItemName = "A200", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 3, ItemName = "A300", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 4, ItemName = "A400", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 5, ItemName = "A600", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 6, ItemName = "D100", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 7, ItemName = "D900", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 8, ItemName = "D200", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")},
    new Item{ItemId = 9, ItemName = "D300", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04")}
};

// Group item by the number in ItemName.
// In order to hold and remember max number for each letter,
// we use anonymous object for element selector:
// further it allows us to carry the Item object itself and the number in ItemName.
var groups = items.GroupBy(
       item => Regex.Split(item.ItemName, "[0-9]+")[0],
       item => new { item, num = int.Parse(Regex.Match(item.ItemName, "[0-9]+").Value) });
foreach (var group in groups)
{
    // Define the max number
    var max = group.Max(x => x.num);
    // Knowing max number, we can now get the Item (packed in anonymous object).
    // You can retrieve it, if you will (var item = max_item.item;).
    var max_item = group.First(x => x.num == max);
    WriteLine($"Item with ItemName '{max_item.item.ItemName}' has max count: {max_item.num}");
}

// Output:
// Item with ItemName 'A600' has max count: 600
// Item with ItemName 'D900' has max count: 900
</code>```

Body:
I have the following data

ItemId | ItemName | ItemBy | ItemCreatedOn
  1    | A100     |  User1 |  2016-10-04
  2    | A200     |  User1 |  2016-10-04
  3    | A300     |  User1 |  2016-10-04
  4    | A400     |  User1 |  2016-10-04
  5    | A600     |  User1 |  2016-10-04
  6    | D100     |  User1 |  2016-10-04
  7    | D900     |  User1 |  2016-10-04
  8    | D200     |  User1 |  2016-10-04
  9    | D300     |  User1 |  2016-10-04

This is what I want to return:

 ItemId | ItemName | ItemBy | ItemCreatedOn
  5     | A600   |  User1 |  2016-10-04

My approach

Get all the list of items starting with A

var allItems = db.Items.Where(x.ItemName[0] == itemName[0]).ToList();

use substring

var items = allItems.Select(x => x.Substring(1));

The above returns a list of string, but I want to return a list of all the items without A so that I can use Max() on ItemName to get the record I need

How can I return the list of objects and then use Max correctly?


答:
You can simply redefine your column in the format you are expecting:

```<code>import pandas as pd
df = pd.DataFrame({'ID':[1,2,3,4],'postal_code':['k1b6j2','k1b6j3','k1b6j4','k1b6j5']}) ##Example dataset

   ID postal_code
0   1      k1b6j2
1   2      k1b6j3
2   3      k1b6j4
3   4      k1b6j5
</code>```

Redefine the postal_code column in the format you desire:

```<code>df['postal_code'] = df['postal_code'].astype(str)
df['postal_code'] = [(x[:3]+" "+x[3:]) for x in df['postal_code']]
</code>```

Output:

```<code>   ID postal_code
0   1     k1b 6j2
1   2     k1b 6j3
2   3     k1b 6j4
3   4     k1b 6j5
</code>```

Finally compared to some other methods in a 100k length dataframe:

```<code>df['postal_code'] = [(x[:3]+" "+x[3:]) for x in df['postal_code']]
First method time:  0.08260965347290039
df['postal_code'] = df["postal_code"].str[:3] + " " + df["postal_code"].str[3:]
Second method time:  0.112518310546875
</code>```

Title: putting a space between the 3rd and 4th characters of postal code in Python

Body:
I have a df (data frame) in Python with with a postal_code variable that has Canadian  postal codes. All the postal codes are collected in a row such as k1b6j2. But , for me to use the the 'pgeocode' package i need the postal code in a standard form which is like k1b 6j2 (there must be a space between the 3rd and 4th character)

So, is there a way to replace all the postal codes with the modified ones in the df?

Many Thanks,
Ben

Body:
You can simply redefine your column in the format you are expecting:

import pandas as pd
df = pd.DataFrame({'ID':[1,2,3,4],'postal_code':['k1b6j2','k1b6j3','k1b6j4','k1b6j5']}) ##Example dataset

   ID postal_code
0   1      k1b6j2
1   2      k1b6j3
2   3      k1b6j4
3   4      k1b6j5

Redefine the postal_code column in the format you desire:

df['postal_code'] = df['postal_code'].astype(str)
df['postal_code'] = [(x[:3]+" "+x[3:]) for x in df['postal_code']]

Output:

   ID postal_code
0   1     k1b 6j2
1   2     k1b 6j3
2   3     k1b 6j4
3   4     k1b 6j5

Finally compared to some other methods in a 100k length dataframe:

df['postal_code'] = [(x[:3]+" "+x[3:]) for x in df['postal_code']]
First method time:  0.08260965347290039
df['postal_code'] = df["postal_code"].str[:3] + " " + df["postal_code"].str[3:]
Second method time:  0.112518310546875


问:
The whole wpf application is blocked after i call Show() for new window
I am developing a WPF-application using mvvm pattern. And a strange problem occurred to me.
There is a form, which contains a devexpress DXGrid control. There is a command binded to double click gesture in presenter. When the command triggers a new window is created and shown through factory class(the Show() method is used).

So, it happens from time to time that the whole application(all application windows) is blocked when this window is shown. This lockup disappears after i focus any other application.

For the first time this problem occurred after updating devexpress version. Then this problem occurred any time new window was shown after double click on grid row. The problem was partially fixed by setting new window`s Owner property.

Now this problem occurs from time to time. It seems as if threads are involved here, but i dont understand how. =(

p.s.:
there is one more strange thing, when new window is shown and no lockup-problem occurred, the first window is still focused and i have to click on newly shown window before i can use any controls, placed on it.

I have tried:

set ShowActivated property

call Activate() after Show()

newform.Dispatcher.CheckAccess() to

determine which thread calls Show()

method

check newform.IsActive property after
show (value = true)

Could you tell me how to fix, please?
Thank you.

答:
Well to fix the issue of first window being focused rather than the newly shown window, you need to do the following, after calling the show method for the new window:

```<code>Mouse.Capture(null);
</code>```

Hopefully the issue would be resolved.

Body:
Well to fix the issue of first window being focused rather than the newly shown window, you need to do the following, after calling the show method for the new window:

Mouse.Capture(null);

Hopefully the issue would be resolved.


问:
How can I trigger a process after a returned publisher would be subscribed?
I have a function that returns a publisher. This publisher gives the results of a background process. I only want to trigger the background process when the publisher would be subscribed, so that no results are lost. The background process can update its results many times, so the variant with Future is not suitable.

```<code>private let passthroughSubject = PassthroughSubject<Data, Error>()

// This function will be used outside.
func fetchResults() -> AnyPublisher<Data, Error> {
     return passthroughSubject
     .eraseToAnyPublisher()
     .somehowTriggerTheBackgroundProcess()
}

extension MyModule: MyDelegate {
     func didUpdateResult(newResult: Data) {
          self.passthroughSubject.send(newResult)
     }
}
</code>```

What have I tried?

Future:

```<code>Future<Data, Error> { [weak self] promise in
     self?.passthroughSubject
          .sink(receiveCompletion: { completion in
               // My logic
          }, receiveValue: { value in
               // My logic
          })
          .store(in: &self.cancellableSet)
      self?.triggerBackgroundProcess()
}.eraseToAnyPublisher()
</code>```

Works the way I want but the subscriber is called only once (logical).

Deffered:

```<code>Deferred<AnyPublisher<Data, Error>>(createPublisher: { [weak self] in
   defer {
      self?.triggerBackgroundProcess()
   }
   return passthroughSubject.eraseToAnyPublisher()
}
</code>```

Debugger shows that everything is correct: first return then trigger but the subscriber is not called for the first time.

receiveSubscription:

```<code>passthroughSubject
.handleEvents(receiveSubscription: { [weak self] subscription in
   self?.triggerBackgroundProcess()
})
.eraseToAnyPublisher()
</code>```

The same effect as with Deffered.

Is it even possible what I want to achieve?
Or, it is better to create a public publisher subscribe it and receive results from background process. And the fetchResults() function doesn't return anything?

Thanks in advance for your help.

答:
It seems to me that your last bit of code is a perfectly viable solution: don't trigger the background process until you detect the subscription. Example:</p>

```<code>let subject = PassthroughSubject<String, Never>()
var storage = Set<AnyCancellable>()
func start() {
    self.subject
        .handleEvents(receiveSubscription: {_ in
            print("subscribed")
            DispatchQueue.main.async {
                self.doSomethingAsynchronous()
            }
        })
        .sink { print("got", $0) }
        .store(in: &storage)
}
func doSomethingAsynchronous() {
    DispatchQueue.global(qos: .userInitiated).async {
        DispatchQueue.main.async {
            self.subject.send("bingo")
        }
    }
}
</code>```

Body:
I have a function that returns a publisher. This publisher gives the results of a background process. I only want to trigger the background process when the publisher would be subscribed, so that no results are lost. The background process can update its results many times, so the variant with Future is not suitable.

private let passthroughSubject = PassthroughSubject<Data, Error>()

// This function will be used outside.
func fetchResults() -> AnyPublisher<Data, Error> {
     return passthroughSubject
     .eraseToAnyPublisher()
     .somehowTriggerTheBackgroundProcess()
}

extension MyModule: MyDelegate {
     func didUpdateResult(newResult: Data) {
          self.passthroughSubject.send(newResult)
     }
}

What have I tried?

Future:

Future<Data, Error> { [weak self] promise in
     self?.passthroughSubject
          .sink(receiveCompletion: { completion in
               // My logic
          }, receiveValue: { value in
               // My logic
          })
          .store(in: &self.cancellableSet)
      self?.triggerBackgroundProcess()
}.eraseToAnyPublisher()

Works the way I want but the subscriber is called only once (logical).

Deffered:

Deferred<AnyPublisher<Data, Error>>(createPublisher: { [weak self] in
   defer {
      self?.triggerBackgroundProcess()
   }
   return passthroughSubject.eraseToAnyPublisher()
}

Debugger shows that everything is correct: first return then trigger but the subscriber is not called for the first time.

receiveSubscription:

passthroughSubject
.handleEvents(receiveSubscription: { [weak self] subscription in
   self?.triggerBackgroundProcess()
})
.eraseToAnyPublisher()

The same effect as with Deffered.

Is it even possible what I want to achieve?
Or, it is better to create a public publisher subscribe it and receive results from background process. And the fetchResults() function doesn't return anything?

Thanks in advance for your help.

Body:
It seems to me that your last bit of code is a perfectly viable solution: don't trigger the background process until you detect the subscription. Example:

let subject = PassthroughSubject<String, Never>()
var storage = Set<AnyCancellable>()
func start() {
    self.subject
        .handleEvents(receiveSubscription: {_ in
            print("subscribed")
            DispatchQueue.main.async {
                self.doSomethingAsynchronous()
            }
        })
        .sink { print("got", $0) }
        .store(in: &storage)
}
func doSomethingAsynchronous() {
    DispatchQueue.global(qos: .userInitiated).async {
        DispatchQueue.main.async {
            self.subject.send("bingo")
        }
    }
}


问:
Accessing this type of Json object
I'm receiving the following JSON response and i want to access its elements and print the message to the page.

for example, I want print out trucks: Id 1,description: lovely truck etc..

```<code>var response= json.data.filter(item => item.success).map(function (d) {
                                return {
                                 success: d.request.trucks
                                }
                            })
</code>```

Here is my JSON Object

```<code>{
  "status": "ok",
  "cars": [],
  "boats": [],
  "bikes": [],
  "trucks": [
    {
      "Id": "1",
      "description": [
        "lovely truck!"
      ]
    },
    {
      "Id": "1",
      "description": [
        "lovely truck! xx"
      ]
    }
  ]
}
</code>```

答:
let's say the JSON object is stored to the variable d so it will be access like this:

```<code>var res1= d.trucks[0].id; // returns 1
var res2 = d.trucks[0].description; // returns lovely trucks
 console.log(res1);//shows in console
 console.log(res2);
//you can print to the here by using
 $("#msg").text(res1);
</code>```

To learn more about json objects visit:
https://www.w3schools.com/js/js_json_objects.asp

Hope it helps.

Title: Accessing this type of Json object

Body:
I'm receiving the following JSON response and i want to access its elements and print the message to the page.

for example, I want print out trucks: Id 1,description: lovely truck etc..

var response= json.data.filter(item => item.success).map(function (d) {
                                return {
                                 success: d.request.trucks
                                }
                            })

Here is my JSON Object

{
  "status": "ok",
  "cars": [],
  "boats": [],
  "bikes": [],
  "trucks": [
    {
      "Id": "1",
      "description": [
        "lovely truck!"
      ]
    },
    {
      "Id": "1",
      "description": [
        "lovely truck! xx"
      ]
    }
  ]
}

Body:
let's say the JSON object is stored to the variable d so it will be access like this:

var res1= d.trucks[0].id; // returns 1
var res2 = d.trucks[0].description; // returns lovely trucks
 console.log(res1);//shows in console
 console.log(res2);
//you can print to the here by using
 $("#msg").text(res1);

To learn more about json objects visit:
https://www.w3schools.com/js/js_json_objects.asp

Hope it helps.


问:
map() function not working in the class component
I have written the following codes but the console prompts an error that says 'this.state.result.map is not a function' (in the 'return'). Just wondering if anyone has any idea what is wrong. Thanks!

```<code>       class App extends React.Component {

            constructor (props) {
                super(props);
                this.state = {
                    result: []
                }
            }

            componentDidMount(){

                const fetchGithub = (loginName) =>
                fetch(`https://api.github.com/users/${loginName}/followers`)
                        .then(response => response.json());

                const processJson= () =>
                    fetchGithub('ericelliott')
                        .then(json => {
                                const userList = json.map(user =>
                                user.login
                                )
                            const result = userList.join(', ')
                            this.setState({result: result})
                        });

                processJson();

            }

            render(){

                return (
                    <div>
                        {this.state.result.map(user => (
                            <div>
                                <div>
                                    {user.login}
                                </div>
                            </div>
                        ))}
                    </div>
                )
            }
        }
</code>```

答: JS map is reserved for Arrays, as you are using const result = userList.join(', '). This turns your result array to a string therefore map function is no longer available. Just remove that line.</p>

Body:
I have written the following codes but the console prompts an error that says 'this.state.result.map is not a function' (in the 'return'). Just wondering if anyone has any idea what is wrong. Thanks!

       class App extends React.Component {

            constructor (props) {
                super(props);
                this.state = {
                    result: []
                }
            }

            componentDidMount(){

                const fetchGithub = (loginName) =>
                fetch(`https://api.github.com/users/${loginName}/followers`)
                        .then(response => response.json());

                const processJson= () =>
                    fetchGithub('ericelliott')
                        .then(json => {
                                const userList = json.map(user =>
                                user.login
                                )
                            const result = userList.join(', ')
                            this.setState({result: result})
                        });

                processJson();

            }

            render(){

                return (

                        {this.state.result.map(user => (

                                    {user.login}

                        ))}

                )
            }
        }


问:
Firebase Messaging causes crash
The app installs and works the first time it's installed from the IDE, but after doing some changes in the code, the second install crashes immediately with the following message:

Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Description: DYLD, dependent dylib '@rpath/FirebaseMessaging.framework/FirebaseMessaging' not found for '/private/var/containers/Bundle/Application/16B1A2D5-B6AC-4952-95D2-D054E16F59ED/appName.app/appName', tried but didn't find: '/private/var/containers/Bundle/Application/16B1A2D5-B6AC-4952-95D2-D054E16F59ED/appName.app/Frameworks/FirebaseMessaging.framework/FirebaseMessaging' '@rpath/FirebaseMessaging.framework/FirebaseMessaging' '/System/Library/Frameworks/FirebaseMessaging.framework/FirebaseMessaging'
Highlighted by Thread: 0

I'm using the following packages:

Xamarin.Firebase.iOS.CloudMessaging.4.1.1.1

Xamarin.Firebase.iOS.Analytics.6.0.4

Xamarin.Firebase.iOS.Core.6.1.0.1

Xamarin.Firebase.iOS.DynamicLinks.4.0.1

Xamarin.Firebase.iOS.InstanceID.4.2.1

Xamarin.Google.iOS.MobileAds.7.47.0.1

I've tried on multiple physical devices and also simulators - all crashed in the second install.

What I've tried:

Updating the libraries to the latest version.

Deleting Obj, Bin and XBD folders.

Cleaning the solution and rebuild.

Does anyone have a solution for this?

EDIT

Environment

Visual Studio Community 2019 for Mac Version 8.6.1 (build 26)

Xamarin.iOS
Version: 13.18.1.31 (Visual Studio Community)

答: The only thing that seems to fix this is downgrading VS, Xamarin.iOS SDK and Xcode. After the downgrade I was also able to use the latest version of the libraries.</p>

Title: Firebase Messaging causes crash


问:
Import strings from .txt and searching for first numeric character - python
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

```<code>'Elm Street 12'
'Baker Street 143'
</code>```

and output

```<code>'Elm Street 12' , 12
'Baker Street 143' , 14
</code>```

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.

答:
```<code>with open('file.txt') as inn:
    for line in inn:
        print "%s %s" % (line, [int(item) for item in line.split(' ') if item.isdigit()])
</code>```

Body:
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

'Elm Street 12'
'Baker Street 143'

and output

'Elm Street 12' , 12
'Baker Street 143' , 14

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.


问:
Have a List box that Filters on items within my subform that is a query
I have a list box that has three different categories to choose from on the form. I have vba code that is working that allows me to select more than one item in the list box which is fine. But the items I am selecting I am having troubles to get the results that I need.

For an Example; The three categories within the list box are not in the query with the actual category names. One Category I have is called "Picking" okay, I want to select "picking" and then when the button is clicked I want it to pull all Items within the query field "Item Number" that equals '0801' which represents the Category "Picking".

Note the code behind the button is a simple "On Click" Event Procedure

**The List box I am Having troubles with is called (StrAccounts)

**Picking which is the same thing as Acct in the query that I am trying filter on in in tbUpload

**I want the "Picking" Category in the List box to filter on Acct in the query where Acct = '0801'

**Placed_Orders which the Second category name within my ListBox and it is the same field in the query above "tbUpload", Acct, except I want
  this Placed_Orders to get all Acct in ('1108', '1114', '1117', '1113',
  '1110')

**Whatever Acct in the query tbUpload that doesn't contain the following numbers already mention above is the third category in my
  list box which is "Not_Placed"

**So whenever Not_Placed in the list box is clicked and the search button is selected I want  Accts in the query to pull, Accts <>
  '0801','1108','1114','1117','1113','1110'

```<code>Private Sub cmdSearch_Click()
Dim Varitem As Variant
Dim StrDEPT_OBS As String
Dim StrStatus As String
Dim StrACCT As String
Dim strSQL As String
Dim StrAccounts As String

'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me!List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me!List_Dept_OBS.ItemData(Varitem) & "'"
Next

'get selections from Status multiselect listbox
For Each Varitem In Me!List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me!List_Status.ItemData(Varitem) & "'"
Next

'get selections from Accts multiselect listbox
 For Each Varitem In Me!List_ACCTs.ItemsSelected
 StrStatus = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
 Next

 If Len(StrDEPT_OBS) > 0 Then
 StrDEPT_OBS = Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1)
 Else: MsgBox "You must enter an OBS"

 Exit Sub
 End If

 If Len(StrStatus) > 0 Then
 StrStatus = Right(StrStatus, Len(StrStatus) - 1)
 End If

 If Len(StrAccounts) > 0 Then
 StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
  End If

  strSQL = " SELECT * FROM tbUpload WHERE "
  strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
    If Len(StrStatus) = 0 Then
        strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "

    Else
        strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStatus & ") "
   End If

    If Len(StrAccounts) = 0 And StrAccounts = "Picking" Then
        strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"

    Else
    End If

    If Len(StrAccounts) = 0 And StrAccounts = "Placed_Orders" Then
     strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "

    Else
        strSQL = strSQL & "tbUpload.ACCT <> (" & [0801] & [1108] & [1114] & [1117] & [1113] & [1110] & ") " "Not_Placed"
End If

DoCmd.SetWarnings False
''DoCmd.OpenQuery ("UPLOAD")
 Me![tbUpload subform].Form.RecordSource = strSQL

 End Sub

If Len(StrAccounts) > 0 Then
'' StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
StrAccounts = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
End If

strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
    If Len(StrStatus) = 0 Then
        strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "

    Else
        strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStat   us & ") "
   End If

    If StrAccounts = "Lugging" Then
        strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"

    Else
    End If

    If StrAccounts = "Structure" Then
     strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "

    Else
    End If
</code>```

答:
Consider:

```<code>'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me.List_Dept_OBS.ItemsSelected
   StrDEPT_OBS = StrDEPT_OBS & ",'" & Me.List_Dept_OBS.ItemData(Varitem) & "'"
Next

If Len(StrDEPT_OBS) > 0 Then
    StrDEPT_OBS = "[Dept_ID] IN(" & Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1) & ") AND "
Else
    MsgBox "You must enter an OBS"
    Exit Sub
End If

'get selections from Status multiselect listbox
For Each Varitem In Me.List_Status.ItemsSelected
    StrStatus = StrStatus & ",'" & Me.List_Status.ItemData(Varitem) & "'"
Next

If Len(StrStatus) > 0 Then
   StrStatus = "[OPR_STAT_ID] IN(" & Right(StrStatus, Len(StrStatus) - 1) & ") AND "
End If

'get selection from Accts single select listbox and build account parameters array
Select Case Me.List_Accts
    Case "Picking"
        StrAccounts = "ACCT = 0801 AND "
    Case "Placed_Orders"
        StrAccounts = "ACCT IN(1108,1114,1117,1113,1110) AND "
    Case "Not_Placed"
        StrAccounts = "NOT ACCT IN(0801,1108,1114,1117,1113,1110) AND "
End Select

strSQL = StrDEPT_OBS & StrStatus & StrAccounts
If strSQL <> "" Then
    strSQL = " WHERE " & Left(strSQL, Len(strSQL) - 5)
End If

Me.[tbUpload subform].Form.RecordSource = "SELECT * FROM tbUpload" & strSQL & ";"
</code>```

For more info on dynamically building search criteria with VBA, review http://allenbrowne.com/ser-62.html

Body:
I have a list box that has three different categories to choose from on the form. I have vba code that is working that allows me to select more than one item in the list box which is fine. But the items I am selecting I am having troubles to get the results that I need.

For an Example; The three categories within the list box are not in the query with the actual category names. One Category I have is called "Picking" okay, I want to select "picking" and then when the button is clicked I want it to pull all Items within the query field "Item Number" that equals '0801' which represents the Category "Picking".

Note the code behind the button is a simple "On Click" Event Procedure

**The List box I am Having troubles with is called (StrAccounts)

**Picking which is the same thing as Acct in the query that I am trying filter on in in tbUpload

**I want the "Picking" Category in the List box to filter on Acct in the query where Acct = '0801'

**Placed_Orders which the Second category name within my ListBox and it is the same field in the query above "tbUpload", Acct, except I want
  this Placed_Orders to get all Acct in ('1108', '1114', '1117', '1113',
  '1110')

**Whatever Acct in the query tbUpload that doesn't contain the following numbers already mention above is the third category in my
  list box which is "Not_Placed"

**So whenever Not_Placed in the list box is clicked and the search button is selected I want  Accts in the query to pull, Accts <>
  '0801','1108','1114','1117','1113','1110'

Private Sub cmdSearch_Click()
Dim Varitem As Variant
Dim StrDEPT_OBS As String
Dim StrStatus As String
Dim StrACCT As String
Dim strSQL As String
Dim StrAccounts As String

'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me!List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me!List_Dept_OBS.ItemData(Varitem) & "'"
Next

'get selections from Status multiselect listbox
For Each Varitem In Me!List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me!List_Status.ItemData(Varitem) & "'"
Next

'get selections from Accts multiselect listbox
 For Each Varitem In Me!List_ACCTs.ItemsSelected
 StrStatus = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
 Next

 If Len(StrDEPT_OBS) > 0 Then
 StrDEPT_OBS = Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1)
 Else: MsgBox "You must enter an OBS"

 Exit Sub
 End If

 If Len(StrStatus) > 0 Then
 StrStatus = Right(StrStatus, Len(StrStatus) - 1)
 End If

 If Len(StrAccounts) > 0 Then
 StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
  End If

  strSQL = " SELECT * FROM tbUpload WHERE "
  strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
    If Len(StrStatus) = 0 Then
        strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "

    Else
        strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStatus & ") "
   End If

    If Len(StrAccounts) = 0 And StrAccounts = "Picking" Then
        strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"

    Else
    End If

    If Len(StrAccounts) = 0 And StrAccounts = "Placed_Orders" Then
     strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "

    Else
        strSQL = strSQL & "tbUpload.ACCT <> (" & [0801] & [1108] & [1114] & [1117] & [1113] & [1110] & ") " "Not_Placed"
End If

DoCmd.SetWarnings False
''DoCmd.OpenQuery ("UPLOAD")
 Me![tbUpload subform].Form.RecordSource = strSQL

 End Sub

If Len(StrAccounts) > 0 Then
'' StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
StrAccounts = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
End If

strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
    If Len(StrStatus) = 0 Then
        strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "

    Else
        strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStat   us & ") "
   End If

    If StrAccounts = "Lugging" Then
        strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"

    Else
    End If

    If StrAccounts = "Structure" Then
     strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "

    Else
    End If

Body:
Consider:

'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me.List_Dept_OBS.ItemsSelected
   StrDEPT_OBS = StrDEPT_OBS & ",'" & Me.List_Dept_OBS.ItemData(Varitem) & "'"
Next

If Len(StrDEPT_OBS) > 0 Then
    StrDEPT_OBS = "[Dept_ID] IN(" & Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1) & ") AND "
Else
    MsgBox "You must enter an OBS"
    Exit Sub
End If

'get selections from Status multiselect listbox
For Each Varitem In Me.List_Status.ItemsSelected
    StrStatus = StrStatus & ",'" & Me.List_Status.ItemData(Varitem) & "'"
Next

If Len(StrStatus) > 0 Then
   StrStatus = "[OPR_STAT_ID] IN(" & Right(StrStatus, Len(StrStatus) - 1) & ") AND "
End If

'get selection from Accts single select listbox and build account parameters array
Select Case Me.List_Accts
    Case "Picking"
        StrAccounts = "ACCT = 0801 AND "
    Case "Placed_Orders"
        StrAccounts = "ACCT IN(1108,1114,1117,1113,1110) AND "
    Case "Not_Placed"
        StrAccounts = "NOT ACCT IN(0801,1108,1114,1117,1113,1110) AND "
End Select

strSQL = StrDEPT_OBS & StrStatus & StrAccounts
If strSQL <> "" Then
    strSQL = " WHERE " & Left(strSQL, Len(strSQL) - 5)
End If

Me.[tbUpload subform].Form.RecordSource = "SELECT * FROM tbUpload" & strSQL & ";"

For more info on dynamically building search criteria with VBA, review http://allenbrowne.com/ser-62.html


问:
how to provide inbound access from public internet to an app hosted in an Azure private kubernetes cluster
I deployed an application in an Azure K8S cluster, using NGINX as gateway, with a public static IP, based on AKS & PUBLIC-IP and on AKS & NGINX.

Now I need to deploy the application in an Azure private cluster, ie, running in a private vnet (see CREATE PRIVATE AKS); attempting to assign a public static IP to NGINX does not work, which can be expected as the load-balancer expects a private IP, not a public IP.

How can I provide inbound access to my app hosted in a private cluster, using NGINX and a public static IP?

答:
Hi you have two ways two achieve that...Depending on your needs (and Azure costs...):

1-Use Azure Application Gateway. For myself I use Terraform. And here you can the see official documentation regarding internal IP address.

Now you can use this one as your new Ingress (and get rid of NGINX) like:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: guestbook
  annotations:
    kubernetes.io/ingress.class: azure/application-gateway
spec:
  rules:
  - http:
      paths:
      - backend:
          serviceName: frontend
          servicePort: 80
</code>```

Or you could use NGINX internally as your ingress like explained on option 2.

2- First you must have a Public IP with a Load Balancer associated with it.The backend from that LB must be up to your needs.

But here is the trick...Do not create NGINX with that public IP but with an internal IP and an internal load balancer, you can see how to do that in the following url:

https://learn.microsoft.com/en-us/azure/aks/ingress-internal-ip

And the important thing you must do is the nginx ovveride on the helm parameters:

```<code>controller:
  service:
    loadBalancerIP: 10.240.0.42
    annotations:
      service.beta.kubernetes.io/azure-load-balancer-internal: "true"
</code>```

Of course the internal VNET must be created an the load balancer IP must be a correct one.

And the final trick now that you have NGINX listening behind a private IP is to verify your traffic from the Public IP is redirected to that internal VNET...Of course it depends on how you have infrastructure setup behind that LB that holds the public IP.

Body:
Hi you have two ways two achieve that...Depending on your needs (and Azure costs...):

1-Use Azure Application Gateway. For myself I use Terraform. And here you can the see official documentation regarding internal IP address.

Now you can use this one as your new Ingress (and get rid of NGINX) like:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: guestbook
  annotations:
    kubernetes.io/ingress.class: azure/application-gateway
spec:
  rules:
  - http:
      paths:
      - backend:
          serviceName: frontend
          servicePort: 80

Or you could use NGINX internally as your ingress like explained on option 2.

2- First you must have a Public IP with a Load Balancer associated with it.The backend from that LB must be up to your needs.

But here is the trick...Do not create NGINX with that public IP but with an internal IP and an internal load balancer, you can see how to do that in the following url:

https://learn.microsoft.com/en-us/azure/aks/ingress-internal-ip

And the important thing you must do is the nginx ovveride on the helm parameters:

controller:
  service:
    loadBalancerIP: 10.240.0.42
    annotations:
      service.beta.kubernetes.io/azure-load-balancer-internal: "true"

Of course the internal VNET must be created an the load balancer IP must be a correct one.

And the final trick now that you have NGINX listening behind a private IP is to verify your traffic from the Public IP is redirected to that internal VNET...Of course it depends on how you have infrastructure setup behind that LB that holds the public IP.