问:
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>```

答: Makes no sense to me, filter applies to everything, chances are the request is not really getting to the server, do you see a call being made in the browser developer toolbar? does it return 200?. </p>

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

问:
Integral in Anylogic
I was wondering if anyone could please let me know the prototype of Integral function in Anylogic. Thanks a lot.

For example, how to put the lower and upper bound of integral?

答:
There's no such thing as an integral, nevertheless, the concept of stock and flow on a system dynamics model is equivalent to an integral

The lower and upper bound are your simulation initial and end time... And if you want to define other lower and upper bounds, you have to make your flows equal to 0 until you reach the initial time and after you reach the final time.

What you are integrating is the sum of the flows that are going in minus the sum of the flows going out of the stock and the result of that integral, is the value of the stock.

Of course, you can only integrate based on time, and using an approximation method such as Euler.

ContentLicense: CC BY-SA 4.0

Title: Integral in Anylogic


问:
iPhone Simulator: start iPad by default?
Can I somehow force a specific hardware device when running my universal app? Whenever I rebuild and test, iPhone 3 fires up and I have to switch over to iPad and rotate the device.
Annoying.</p>

答:
I finally solved this problem myself.

First, install new version of xCode, which is xCode 4.

Then set project scheme to iphone simulator and run app in xCode several times.

And re-install xCode 3 and the problem will be gone away!

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to create R shiny interactive map without lat and long in the dataset

using leaflet package to create interactive map using r shiny. my dataset provides the names of countries but not the lat or long. how can i create this where the map can detect by country names

答:
You can use a geojson map with the readOGR function, you can find the map on internet and link your dataset to it.

```<code>rgdal::readOGR(dsn = "GeoJSON map",
                     layer = "OGRGeoJSON",
                     stringsAsFactors = FALSE)
</code>```

Below is an example based on this stackoverflow post to make an interactive map on R Shiny. The selected countries are in click.list$ids, see the output$selected_var below.

Your data

```<code>## packages ##

packages <- c("leaflet", "shiny", "shinydashboard")

newPackages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(newPackages)) install.packages(newPackages)
lapply(packages, library, character.only = TRUE)
remove(packages, newPackages)

## map & data ##

Europe <- rgdal::readOGR(dsn = "https://data.opendatasoft.com/explore/dataset/european-union-countries@public/download/?format=geojson&timezone=Europe/Berlin",
                         layer = "OGRGeoJSON",
                         stringsAsFactors = FALSE)

data <- data.frame("name" = c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czechia", "Denmark", "Estonia",
                              "Finland", "France", "Germany", "Greece", "Hungary", "Iceland", "Ireland", "Italy", "Latvia",
                              "Liechtenstein", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Norway", "Poland", "Portugal",
                              "Romania", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "United Kingdom"),
                   "polcapita" = c(0.0087928207, 0.0100464969, 0.0075375536, 0.0049040898, 0.0097860082, 0.0119440135, 0.0087740252,
                                   0.0080851042, 0.0063462331, 0.0064707328, 0.0107846429, 0.0085740997, 0.0059612600, 0.0409884683,
                                   0.0138830047, 0.0067616652, 0.0049423915, 0.0053782730, 0.0053461017, 0.0165884166, 0.0046052235,
                                   0.0116079951, 0.0052533159, 0.0100049243, 0.0075509189, 0.0047028415, 0.0067531703, 0.0077087169,
                                   0.0064795469, 0.0008881585, 0.0053907055, 0.0053085690, 0.0069728195))

# example if you need to change the name of a country
Europe@data[Europe@data$name == "Czech Rep.", ]$name <- "Czechia"

# example if you want to add datas to the map
Europe@data$polcapita <- merge(x = Europe@data, y = data, sort = FALSE)$polcapita

pal <- colorNumeric(c("Green", "Red"), Europe$polcapita)
</code>```

The UI part

```<code>## create the UI ##

ui <- fluidPage(
  # place the contents inside a box
  shinydashboard::box(
    width = 12,
    title = "Click on the map!",
    # separate the box by a column
    column(width = 2,
           shiny::actionButton(inputId = "clearHighlight",
                               icon = icon( name = "eraser"),
                               label = "Clear the Map",
                               style = "color: #fff; background-color: #D75453; border-color: #C73232")),
    # separate the box by a column
    column(width = 10,
           leaflet::leafletOutput(outputId = "myMap", height = 850)),
    column(width = 5,
           textOutput("selected_var"))
  )
)
</code>```

The server part

```<code>## create the server ##

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

  # create foundational map
  foundational.map <- shiny::reactive({
    leaflet(Europe) %>%
      fitBounds(-20, 65, 20, 39) %>%
      addProviderTiles(providers$CartoDB.Positron) %>%
      addPolygons(data = Europe,
                  layerId = Europe$name,
                  color = ~pal(polcapita),
                  group = "click.list",
                  weight = 2,
                  fillOpacity = 0.3,
                  opacity = 1,
                  smoothFactor = 0.2,
                  stroke = FALSE)
  })

  output$myMap <- renderLeaflet({
    foundational.map()
  })

  # store the list of clicked polygons in a vector
  click.list <- shiny::reactiveValues(ids = vector())

  # add countries to selection
  shiny::observeEvent(input$myMap_shape_click, {

    click <- input$myMap_shape_click
    if(click$id %in% click.list$ids){
      click.list$ids <- click.list$ids[!click.list$ids%in%click$id]
      leaflet::leafletProxy(mapId = "myMap") %>%
        clearGroup("lin")
    } else{
      click.list$ids <- c(click.list$ids, click$id)
    }
    lines.of.interest <- Europe[ which(Europe$name %in% click.list$ids), ]
    leaflet::leafletProxy(mapId = "myMap") %>%
      addPolylines(data = lines.of.interest,
                   layerId = lines.of.interest$ids,
                   color = "#6cb5bc",
                   weight = 2,
                   opacity = 1,
                   group = "lin")
  })

  # Clear the map button
  shiny::observeEvent( input$clearHighlight, {
    output$myMap <- leaflet::renderLeaflet({
      click.list$ids <- NULL
      foundational.map()
    })
  })

  # selected countries
  output$selected_var <- renderText({
    paste("You have selected", click.list$ids)
  })

}
</code>```

To run the server

```<code>## run shinyApp ##
shiny::shinyApp(ui, server)
</code>```

I hope it answers your question !

Body:
You can use a geojson map with the readOGR function, you can find the map on internet and link your dataset to it.

rgdal::readOGR(dsn = "GeoJSON map",
                     layer = "OGRGeoJSON",
                     stringsAsFactors = FALSE)

Below is an example based on this stackoverflow post to make an interactive map on R Shiny. The selected countries are in click.list$ids, see the output$selected_var below.

Your data

## packages ##

packages <- c("leaflet", "shiny", "shinydashboard")

newPackages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(newPackages)) install.packages(newPackages)
lapply(packages, library, character.only = TRUE)
remove(packages, newPackages)

## map & data ##

Europe <- rgdal::readOGR(dsn = "https://data.opendatasoft.com/explore/dataset/european-union-countries@public/download/?format=geojson&timezone=Europe/Berlin",
                         layer = "OGRGeoJSON",
                         stringsAsFactors = FALSE)

data <- data.frame("name" = c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czechia", "Denmark", "Estonia",
                              "Finland", "France", "Germany", "Greece", "Hungary", "Iceland", "Ireland", "Italy", "Latvia",
                              "Liechtenstein", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Norway", "Poland", "Portugal",
                              "Romania", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "United Kingdom"),
                   "polcapita" = c(0.0087928207, 0.0100464969, 0.0075375536, 0.0049040898, 0.0097860082, 0.0119440135, 0.0087740252,
                                   0.0080851042, 0.0063462331, 0.0064707328, 0.0107846429, 0.0085740997, 0.0059612600, 0.0409884683,
                                   0.0138830047, 0.0067616652, 0.0049423915, 0.0053782730, 0.0053461017, 0.0165884166, 0.0046052235,
                                   0.0116079951, 0.0052533159, 0.0100049243, 0.0075509189, 0.0047028415, 0.0067531703, 0.0077087169,
                                   0.0064795469, 0.0008881585, 0.0053907055, 0.0053085690, 0.0069728195))

# example if you need to change the name of a country
Europe@data[Europe@data$name == "Czech Rep.", ]$name <- "Czechia"

# example if you want to add datas to the map
Europe@data$polcapita <- merge(x = Europe@data, y = data, sort = FALSE)$polcapita

pal <- colorNumeric(c("Green", "Red"), Europe$polcapita)

The UI part

## create the UI ##

ui <- fluidPage(
  # place the contents inside a box
  shinydashboard::box(
    width = 12,
    title = "Click on the map!",
    # separate the box by a column
    column(width = 2,
           shiny::actionButton(inputId = "clearHighlight",
                               icon = icon( name = "eraser"),
                               label = "Clear the Map",
                               style = "color: #fff; background-color: #D75453; border-color: #C73232")),
    # separate the box by a column
    column(width = 10,
           leaflet::leafletOutput(outputId = "myMap", height = 850)),
    column(width = 5,
           textOutput("selected_var"))
  )
)

The server part

## create the server ##

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

  # create foundational map
  foundational.map <- shiny::reactive({
    leaflet(Europe) %>%
      fitBounds(-20, 65, 20, 39) %>%
      addProviderTiles(providers$CartoDB.Positron) %>%
      addPolygons(data = Europe,
                  layerId = Europe$name,
                  color = ~pal(polcapita),
                  group = "click.list",
                  weight = 2,
                  fillOpacity = 0.3,
                  opacity = 1,
                  smoothFactor = 0.2,
                  stroke = FALSE)
  })

  output$myMap <- renderLeaflet({
    foundational.map()
  })

  # store the list of clicked polygons in a vector
  click.list <- shiny::reactiveValues(ids = vector())

  # add countries to selection
  shiny::observeEvent(input$myMap_shape_click, {

    click <- input$myMap_shape_click
    if(click$id %in% click.list$ids){
      click.list$ids <- click.list$ids[!click.list$ids%in%click$id]
      leaflet::leafletProxy(mapId = "myMap") %>%
        clearGroup("lin")
    } else{
      click.list$ids <- c(click.list$ids, click$id)
    }
    lines.of.interest <- Europe[ which(Europe$name %in% click.list$ids), ]
    leaflet::leafletProxy(mapId = "myMap") %>%
      addPolylines(data = lines.of.interest,
                   layerId = lines.of.interest$ids,
                   color = "#6cb5bc",
                   weight = 2,
                   opacity = 1,
                   group = "lin")
  })

  # Clear the map button
  shiny::observeEvent( input$clearHighlight, {
    output$myMap <- leaflet::renderLeaflet({
      click.list$ids <- NULL
      foundational.map()
    })
  })

  # selected countries
  output$selected_var <- renderText({
    paste("You have selected", click.list$ids)
  })

}

To run the server

## run shinyApp ##
shiny::shinyApp(ui, server)

I hope it answers your question !


问:
web api - commit database transaction in action filter
Edit: This question has been modified completely from its original version.

My objective is to commit the database transaction at the action filer level. I am using Web API .Net Framework (4.8) along with Unity DI.

My Transaction Filter Attribute:

```<code>public class TransactionFilterAttribute : ActionFilterAttribute
{
    private readonly PortalContext _context;
    private DbContextTransaction _transactionScope;

    public TransactionFilterAttribute(IUnityContainer container)
    {
        _context = container.Resolve<PortalContext>();
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        _transactionScope = _context.Database.BeginTransaction();
        using (_transactionScope)
        {
            base.OnActionExecuting(actionContext);
        }
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        try
        {
            base.OnActionExecuted(actionExecutedContext);
            _transactionScope.Commit(); //Error occurred
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }
}
</code>```

Unity Configuration:

```<code>public static class UnityConfig
{
    private static readonly Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer Container => container.Value;

    private static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<PortalContext>();
    }
}
</code>```

I am getting an error while executing _transactionScope.Commit()

Error: Value cannot be null.
Parameter name: connection --> The underlying provider failed on Commit.

Any help would be appreciated.

答:
This is purely a guess, but I'm wondering if the using clause in your OnActionExecuting override is to blame.

As soon as the base call to OnActionExecuting returns, your _transactionScope is Dispose'd. Thus, assuming that OnActionExecuted isn't called from within the base.OnActionExecuting method, _transactionScope will not be in the state you're expecting in OnActionExecuted.

Suggest:

```<code>public override void OnActionExecuting(HttpActionContext actionContext)
{
    _transactionScope = _context.Database.BeginTransaction();
    base.OnActionExecuting(actionContext);
}

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    try
    {
        base.OnActionExecuted(actionExecutedContext);
        _transactionScope.Commit(); //Error occurred
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
        _transactionScope.Rollback(); // because something went wrong during your transaction
    }
    finally
    {
        _transactionScope.Dispose(); // now that we're definitely done.
    }
}
</code>```

Body:
Edit: This question has been modified completely from its original version.

My objective is to commit the database transaction at the action filer level. I am using Web API .Net Framework (4.8) along with Unity DI.

My Transaction Filter Attribute:

public class TransactionFilterAttribute : ActionFilterAttribute
{
    private readonly PortalContext _context;
    private DbContextTransaction _transactionScope;

    public TransactionFilterAttribute(IUnityContainer container)
    {
        _context = container.Resolve<PortalContext>();
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        _transactionScope = _context.Database.BeginTransaction();
        using (_transactionScope)
        {
            base.OnActionExecuting(actionContext);
        }
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        try
        {
            base.OnActionExecuted(actionExecutedContext);
            _transactionScope.Commit(); //Error occurred
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }
}

Unity Configuration:

public static class UnityConfig
{
    private static readonly Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer Container => container.Value;

    private static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<PortalContext>();
    }
}

I am getting an error while executing _transactionScope.Commit()

Error: Value cannot be null.
Parameter name: connection --> The underlying provider failed on Commit.

Any help would be appreciated.

Body:
This is purely a guess, but I'm wondering if the using clause in your OnActionExecuting override is to blame.

As soon as the base call to OnActionExecuting returns, your _transactionScope is Dispose'd. Thus, assuming that OnActionExecuted isn't called from within the base.OnActionExecuting method, _transactionScope will not be in the state you're expecting in OnActionExecuted.

Suggest:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    _transactionScope = _context.Database.BeginTransaction();
    base.OnActionExecuting(actionContext);
}

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    try
    {
        base.OnActionExecuted(actionExecutedContext);
        _transactionScope.Commit(); //Error occurred
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
        _transactionScope.Rollback(); // because something went wrong during your transaction
    }
    finally
    {
        _transactionScope.Dispose(); // now that we're definitely done.
    }
}


问:
Method overloading with dynamic data types
Why compiler is restraining to overload method in below way, Compilation Error i get in update method with dynamic type parameter.

Error - Type 'Program' already defines a member called 'update' with the same parameter types

```<code>static void update(string name)
    {

    }
static void update(object name)
    {

    }

static void update(dynamic name)
    {

    }
</code>```

答:
When you use dynamic parameter type, i.e.

```<code>static void update(dynamic name)
{
}
</code>```

compiler changes the signature of your method to use object instead, i.e.

```<code>static void update(object name)
{
}
</code>```

and then inserts some "magic" in the body of your method in order to treat name as a dynamically-typed object. This, however, introduces an important limitation: you cannot have another method update that takes object, because you already have one.

Think about this overload from the perspective of language designer: when you see a call to an overload between object and dynamic, there would be no intuitively understood way to resolve the tie, because both object and dynamic could accommodate objects of any type. Hence, overloads like this should be disallowed anyway, regardless of the underlying implementation for dynamic.

Body:
Why compiler is restraining to overload method in below way, Compilation Error i get in update method with dynamic type parameter.

Error - Type 'Program' already defines a member called 'update' with the same parameter types

static void update(string name)
    {

    }
static void update(object name)
    {

    }

static void update(dynamic name)
    {

    }

Body:
When you use dynamic parameter type, i.e.

static void update(dynamic name)
{
}

compiler changes the signature of your method to use object instead, i.e.

static void update(object name)
{
}

and then inserts some "magic" in the body of your method in order to treat name as a dynamically-typed object. This, however, introduces an important limitation: you cannot have another method update that takes object, because you already have one.

Think about this overload from the perspective of language designer: when you see a call to an overload between object and dynamic, there would be no intuitively understood way to resolve the tie, because both object and dynamic could accommodate objects of any type. Hence, overloads like this should be disallowed anyway, regardless of the underlying implementation for dynamic.


问:
Can't change divs ID of first element from <tempate>
I have this HTML template:

```<code><template id="single_feed">

    <div class="ibox" id="FIRST_DIV">
        <div class="ibox-title">
            <h5 id="naslov"></h5>
         </div>
        <div class="ibox-content">
            <form method="get" _lpchecked="1">
                 <div class="form-group  row"><label class="col-sm-2 col-form-label">Naziv</label>
            </form>
        </div>
    </div>
</template>
</code>```

Now I want to clone and change first div ID (now set to: "FIRST_DIV"). But don't know how. I am able only to change 2nd,3rd.... divs.

My jquery code for cloning is:

```<code>    $(".btn-RSS-single").click(function(e) {
        var idClicked = e.target.id;

        const $template = $( $('#single_feed')[0].innerHTML );

        $template.find("div:first").attr("id", "NEW_ID_"+idClicked);

        $('#kolona_1').append($template);

});
</code>```

P.S:
I removed unnecessary parts to make code more readable.

答:
Try something like below</p>

```<code>   $(".btn-RSS-single").click(function(e) {
    var idClicked = e.target.id;

    const $template = $( $('#single_feed')[0].innerHTML );

    $template.find("div:first").attr("class", "template-new"+idClicked);

    $('#kolona_1').append($template);
    $('#kolona_1').find('.template-new' + idClicked).attr('id', 'NEW_ID_' + idClicked);
</code>```

<p>}); </p>

Body:
I have this HTML template:

<template id="single_feed">

            <form method="get" _lpchecked="1">

Naziv
            </form>

</template>

Now I want to clone and change first div ID (now set to: "FIRST_DIV"). But don't know how. I am able only to change 2nd,3rd.... divs.

My jquery code for cloning is:

    $(".btn-RSS-single").click(function(e) {
        var idClicked = e.target.id;

        const $template = $( $('#single_feed')[0].innerHTML );

        $template.find("div:first").attr("id", "NEW_ID_"+idClicked);

        $('#kolona_1').append($template);

});

P.S:
I removed unnecessary parts to make code more readable.

Body:
Try something like below

   $(".btn-RSS-single").click(function(e) {
    var idClicked = e.target.id;

    const $template = $( $('#single_feed')[0].innerHTML );

    $template.find("div:first").attr("class", "template-new"+idClicked);

    $('#kolona_1').append($template);
    $('#kolona_1').find('.template-new' + idClicked).attr('id', 'NEW_ID_' + idClicked);

});


问:
Which HTTP methods match up to which CRUD methods?
In RESTful style programming, we should use HTTP methods as our building blocks. I'm a little confused though which methods match up to the classic CRUD methods. GET/Read and DELETE/Delete are obvious enough.

However, what is the difference between PUT/POST? Do they match one to one with Create and Update?

答:
```<code>Create = PUT with a new URI
         POST to a base URI returning a newly created URI
Read   = GET
Update = PUT with an existing URI
Delete = DELETE
</code>```

PUT can map to both Create and Update depending on the existence of the URI used with the PUT.

POST maps to Create.

Correction: POST can also map to Update although it's typically used for Create.  POST can also be a partial update so we don't need the proposed PATCH method.

Body:
Create = PUT with a new URI
         POST to a base URI returning a newly created URI
Read   = GET
Update = PUT with an existing URI
Delete = DELETE

PUT can map to both Create and Update depending on the existence of the URI used with the PUT.

POST maps to Create.

Correction: POST can also map to Update although it's typically used for Create.  POST can also be a partial update so we don't need the proposed PATCH method.


问:
List of dec numbers to 2digit hex in python
I have a list of numbers between 0 and 255 in python 3, which looks like that:

```<code>numbers = [79, 104, 44, 32, 105, 116, 32, 119, 111, 114, 107, 115, 32, 102, 2, 2]
</code>```

I would like to convert it to a string with hex-numbers like:

```<code>4f682c20697420776f726b7320660202
</code>```

I do not want the "0x" to be included and very important: Numbers smaller than a should have a trailing zero.

答:
```<code> "".join(hex(num)[2:].zfill(2) for num in numbers)
 # '4f682c20697420776f726b7320660202'
</code>```

Use hex to get the hexadecimal representation,

use [2:] to get rid of the 0x part,

use str.zfill to ensure zeros as prefix for short ones e.g. 2,

and lastly join the generator expression by "" to get a string.

Body:
I have a list of numbers between 0 and 255 in python 3, which looks like that:

numbers = [79, 104, 44, 32, 105, 116, 32, 119, 111, 114, 107, 115, 32, 102, 2, 2]

I would like to convert it to a string with hex-numbers like:

4f682c20697420776f726b7320660202

I do not want the "0x" to be included and very important: Numbers smaller than a should have a trailing zero.

Body:
 "".join(hex(num)[2:].zfill(2) for num in numbers)
 # '4f682c20697420776f726b7320660202'

Use hex to get the hexadecimal representation,

use [2:] to get rid of the 0x part,

use str.zfill to ensure zeros as prefix for short ones e.g. 2,

and lastly join the generator expression by "" to get a string.


问:
Understanding the how Anki determines what’s considered as “finished studying a deck”
I’ve recently begun using Anki and was curious as to what’s considered “finishing a deck”. For example, if I have 40 cards in a deck, have I finished studying the deck once I’ve seen all 40 cards? How do I know I’ve seen all 40 cards? Does Anki have some sort of algorithm to inform the user that they’ve adequately finished studying a set, or is that judgement made by our best discretion?</p>

答:
You should have a look to the manual. The deck is "finished" when there is no more cards to see for a given day because you have seen the daily new cards, and reviewed the due cards.

The software decides when you have to review a specific card based on your previous answers with an algorithm. See that page of the manual. When it comes to new cards, you can choose how many new cards you want to learn each day, in the parameters of the deck.


问:
Unable to identify some C# syntax for translation to VB.NET
I'm translating some example code line by line from C# to VB.NET.

The lines which confuse me looks like this:

```<code>[Kernel(CustomFallbackMethod = "AddCpu")]
</code>```

I see in the code that these lines appear just before the method declaration:

```<code>private static void
</code>```

What kind of line appears before a method declaration? Or is it a continuation of the last? I hope this is obvious to a native C Sharper.

答:
It's an Attribute. It's a way to mark up code that can be used at runtime or compile time.

I would google VB.NET and Attributes. You can read some passages here on O'Reilly

Your example would be converted to:

```<code>       <Kernel(CustomFallbackMethod:="AddCpu")>
</code>```

Be sure to use _ if you decide to put it on the line before your method.

Body:
I'm translating some example code line by line from C# to VB.NET.

The lines which confuse me looks like this:

[Kernel(CustomFallbackMethod = "AddCpu")]

I see in the code that these lines appear just before the method declaration:

private static void

What kind of line appears before a method declaration? Or is it a continuation of the last? I hope this is obvious to a native C Sharper.

Body:
It's an Attribute. It's a way to mark up code that can be used at runtime or compile time.

I would google VB.NET and Attributes. You can read some passages here on O'Reilly

Your example would be converted to:

       <Kernel(CustomFallbackMethod:="AddCpu")>

Be sure to use _ if you decide to put it on the line before your method.


问:
How to send email notification when colab processing is complete
I have a Colab task for data processing.

I want to send a Gmail notification when this task is finished.

Can anyone help me?

答:
You can use smtplib to send an email. For more details goto this link.

```<code>import smtplib

sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('mail.your-domain.com', 25)
   smtpObj.sendmail(sender, receivers, message)
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"
</code>```

Body:
You can use smtplib to send an email. For more details goto this link.

import smtplib

sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('mail.your-domain.com', 25)
   smtpObj.sendmail(sender, receivers, message)
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"


问:
Windows Defender recognize output binary of C# desktop project release build with Visual Studio 2019 as Trojan
I use VS 2019 16.6.0 and build my project in Release configuration with these settings:

My result binary will recognized as Trojan:MSIL/Fareit.VM!MTB:

Get-MpComputerStatus executed in PowerShell:

```<code>AMEngineVersion                 : 1.1.17100.2
AMProductVersion                : 4.18.2004.6
AMServiceEnabled                : True
AMServiceVersion                : 4.18.2004.6
AntispywareEnabled              : True
AntispywareSignatureAge         : 0
AntispywareSignatureLastUpdated : 29.05.2020 16:06:44
AntispywareSignatureVersion     : 1.317.207.0
AntivirusEnabled                : True
AntivirusSignatureAge           : 0
AntivirusSignatureLastUpdated   : 29.05.2020 16:06:44
AntivirusSignatureVersion       : 1.317.207.0
BehaviorMonitorEnabled          : True
ComputerID                      : AFCC7D96-94CF-402C-BC3E-9ECE1640D1A0
ComputerState                   : 0
FullScanAge                     : 4294967295
FullScanEndTime                 :
FullScanStartTime               :
IoavProtectionEnabled           : True
IsTamperProtected               : True
IsVirtualMachine                : False
LastFullScanSource              : 0
LastQuickScanSource             : 2
NISEnabled                      : True
NISEngineVersion                : 1.1.17100.2
NISSignatureAge                 : 0
NISSignatureLastUpdated         : 29.05.2020 16:06:44
NISSignatureVersion             : 1.317.207.0
OnAccessProtectionEnabled       : True
QuickScanAge                    : 6
QuickScanEndTime                : 23.05.2020 14:27:29
QuickScanStartTime              : 23.05.2020 14:25:44
RealTimeProtectionEnabled       : True
RealTimeScanDirection           : 0
PSComputerName                  :
</code>```

答: Setting Debug info to Embedded resolves it

Body:
I use VS 2019 16.6.0 and build my project in Release configuration with these settings:

My result binary will recognized as Trojan:MSIL/Fareit.VM!MTB:

Get-MpComputerStatus executed in PowerShell:

AMEngineVersion                 : 1.1.17100.2
AMProductVersion                : 4.18.2004.6
AMServiceEnabled                : True
AMServiceVersion                : 4.18.2004.6
AntispywareEnabled              : True
AntispywareSignatureAge         : 0
AntispywareSignatureLastUpdated : 29.05.2020 16:06:44
AntispywareSignatureVersion     : 1.317.207.0
AntivirusEnabled                : True
AntivirusSignatureAge           : 0
AntivirusSignatureLastUpdated   : 29.05.2020 16:06:44
AntivirusSignatureVersion       : 1.317.207.0
BehaviorMonitorEnabled          : True
ComputerID                      : AFCC7D96-94CF-402C-BC3E-9ECE1640D1A0
ComputerState                   : 0
FullScanAge                     : 4294967295
FullScanEndTime                 :
FullScanStartTime               :
IoavProtectionEnabled           : True
IsTamperProtected               : True
IsVirtualMachine                : False
LastFullScanSource              : 0
LastQuickScanSource             : 2
NISEnabled                      : True
NISEngineVersion                : 1.1.17100.2
NISSignatureAge                 : 0
NISSignatureLastUpdated         : 29.05.2020 16:06:44
NISSignatureVersion             : 1.317.207.0
OnAccessProtectionEnabled       : True
QuickScanAge                    : 6
QuickScanEndTime                : 23.05.2020 14:27:29
QuickScanStartTime              : 23.05.2020 14:25:44
RealTimeProtectionEnabled       : True
RealTimeScanDirection           : 0
PSComputerName                  :


问:
Makefile problems
I want compile makefile in linux.
This Is my makefile

```<code>FFMPEG_LIBS=    libavdevice                        \
libavformat                        \
libavfilter                        \
libavcodec                         \
libswresample                      \
libswscale                         \
libavutil                          \

LDLIBS := $(shell pkg-config --libs $(FFMPEG_LIBS))
LIBS = -lstdc++fs
PROJECT_ROOT    =   $(shell pwd)

CXX        = g++
CXXFLAGS   = -c -Wall
STRIP      = strip
LDFLAGS    =
OBJS       = main.o chekfiletoconcat.o
DEPS       = chekfiletoconcat.h
EXECUTABLE = concat

.PHONY: all
all: $(EXECUTABLE) $(LIBS)

$(EXECUTABLE): $(OBJS)
    $(CXX) $(LDFLAGS) $^ -o $@ $(LDLIBS)
    $(STRIP) $(EXECUTABLE)

%.o: %.cpp $(DEPS)
    $(CXX) $(CXXFLAGS) $<

.PHONY: clean
clean:
    rm -f $(OBJS) $(EXECUTABLE)
</code>```

But I recive error ** make: * No rule to make target '-lstdc++fs', needed by 'all'.  Stop.

答:
I have done this</p>

```<code>LDLIBS := $(shell pkg-config --libs $(FFMPEG_LIBS)) -lstdc++fs
</code>```

```<code>all: $(EXECUTABLE)
</code>```

Title: Makefile problems

Body:
I want compile makefile in linux.
This Is my makefile

FFMPEG_LIBS=    libavdevice                        \
libavformat                        \
libavfilter                        \
libavcodec                         \
libswresample                      \
libswscale                         \
libavutil                          \

LDLIBS := $(shell pkg-config --libs $(FFMPEG_LIBS))
LIBS = -lstdc++fs
PROJECT_ROOT    =   $(shell pwd)

CXX        = g++
CXXFLAGS   = -c -Wall
STRIP      = strip
LDFLAGS    =
OBJS       = main.o chekfiletoconcat.o
DEPS       = chekfiletoconcat.h
EXECUTABLE = concat

.PHONY: all
all: $(EXECUTABLE) $(LIBS)

$(EXECUTABLE): $(OBJS)
    $(CXX) $(LDFLAGS) $^ -o $@ $(LDLIBS)
    $(STRIP) $(EXECUTABLE)

%.o: %.cpp $(DEPS)
    $(CXX) $(CXXFLAGS) $<

.PHONY: clean
clean:
    rm -f $(OBJS) $(EXECUTABLE)

But I recive error ** make: * No rule to make target '-lstdc++fs', needed by 'all'.  Stop.

Body:
I have done this

LDLIBS := $(shell pkg-config --libs $(FFMPEG_LIBS)) -lstdc++fs

all: $(EXECUTABLE)


问:
Change font style of searchFieldLabel in SearchDelegate Flutter
I implemented a SearchAppBar using SearchDelegate of Material and changed the hint text default of the Search Delegate using the responses from this question.

But, I'm having the problem of can't change the font style of the hint text at the search field, that is displayed as showed on the image below:

I already have the style I want implemented and am using this style in another fonts of my app, but I want to apply this style to this hint text too to don't break with the style guide of the application.

Code that I'm using for changing the default message of Search Delegate:

class SearchRoomAppBar extends SearchDelegate {

    SearchRoomAppBar() : super(
        searchFieldLabel: "Search user",
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.search,
    );
}
```

答:
The SearchDelegate app bar text is styled with whatever style is set to ThemeData.textTheme.headline6.

By default, SearchDelegate uses your app's ThemeData, but you can override the ThemeData appBarTheme(BuildContext context) method to return a custom version.

```<code>  @override
  ThemeData appBarTheme(BuildContext context) {
    // You can use Theme.of(context) directly too
    var superThemeData = super.appBarTheme(context);

    return superThemeData.copyWith(
      textTheme: superThemeData.textTheme.copyWith(
        headline6: /* Whatever style you want to apply to your text */,
      ),
    );
  }
</code>```

Body:
The SearchDelegate app bar text is styled with whatever style is set to ThemeData.textTheme.headline6.

By default, SearchDelegate uses your app's ThemeData, but you can override the ThemeData appBarTheme(BuildContext context) method to return a custom version.

  @override
  ThemeData appBarTheme(BuildContext context) {
    // You can use Theme.of(context) directly too
    var superThemeData = super.appBarTheme(context);

    return superThemeData.copyWith(
      textTheme: superThemeData.textTheme.copyWith(
        headline6: /* Whatever style you want to apply to your text */,
      ),
    );
  }


问:
Kubernetes - HTTP Probe failed with statuscode: 404
I`ve got a specyfic problem. When the container is running in Pods, the application contained in it works correctly, while in kubernetes the status is displayed - Error. In Events there are the following problems:

```<code>Readiness probe failed: HTTP Probe failed with statuscode: 404
Liveness probe failed: HTTP Probe failed with statuscode: 404
</code>```

The same errors are displayed in four containers with applications (Spring Boot). On the other hand, when I launch a container with a simple application (writing numbers from 0 to 10), in Kuberneres, the status is success. I'm just learning a Kubernetes, so I'd like to ask for help, which may be the cause of the problems?

答: check liveness probe and readiness probe in your deployment yml. Check the path is correct. if still not resolved increase the initialDelay seconds</p>

Body:
I`ve got a specyfic problem. When the container is running in Pods, the application contained in it works correctly, while in kubernetes the status is displayed - Error. In Events there are the following problems:

Readiness probe failed: HTTP Probe failed with statuscode: 404
Liveness probe failed: HTTP Probe failed with statuscode: 404

The same errors are displayed in four containers with applications (Spring Boot). On the other hand, when I launch a container with a simple application (writing numbers from 0 to 10), in Kuberneres, the status is success. I'm just learning a Kubernetes, so I'd like to ask for help, which may be the cause of the problems?


问:
How do you use flex inside a scrollView React Native
When I use the ScrollView with contents that have flex they don't show and flex doesn't seem to work. How do you get flex to work inside a ScrollView?

```<code>import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from 'react-native';

const App = (props) => {

  return (
      <ScrollView style={styles.body}>
        <View style={styles.box1} />
        <View style={styles.box2} />
        <View style={styles.box1} />
      </ScrollView>
  );
};

const styles = StyleSheet.create({
  body: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff',
    borderColor: 'red',
    borderWidth: 5
  },
  box1: {
    flex: 1,
    backgroundColor: 'blue',
  },
  box2: {
    flex: 2,
    backgroundColor: 'purple',
  }
});

export default App;
</code>```

I've created a snack. The inner views/boxes don't show.

答:
I managed to figure it out. You create another view inside the scrollView and fix the height. The only problem is that the size of the content views depends on the height of this view instead of the height of the scrollView.

```<code>import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from 'react-native';
// import { useHeaderHeight } from '@react-navigation/stack';

const App = (props) => {
  let screenHeight = Dimensions.get('window').height;
  // let headerHeight = useHeaderHeight();
  let headerHeight = 0
  let bodyHeight = screenHeight - headerHeight + 500;

  return (
      <ScrollView style={styles.body}>
        <View style={[styles.innerBody, { height: bodyHeight }]}>
          <View style={styles.box1} />
          <View style={styles.box2} />
          <View style={styles.box1} />
        </View>
      </ScrollView>
  );
};

const styles = StyleSheet.create({
  body: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff',
  },
  innerBody: {
    borderColor: 'red',
    borderWidth: 5
  },
  box1: {
    flex: 1,
    backgroundColor: 'blue',
  },
  box2: {
    flex: 2,
    backgroundColor: 'purple',
  }
});

export default App;
</code>```

Heres a snack showing it working.

Body:
When I use the ScrollView with contents that have flex they don't show and flex doesn't seem to work. How do you get flex to work inside a ScrollView?

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from 'react-native';

const App = (props) => {

  return (
      <ScrollView style={styles.body}>
        <View style={styles.box1} />
        <View style={styles.box2} />
        <View style={styles.box1} />
      </ScrollView>
  );
};

const styles = StyleSheet.create({
  body: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff',
    borderColor: 'red',
    borderWidth: 5
  },
  box1: {
    flex: 1,
    backgroundColor: 'blue',
  },
  box2: {
    flex: 2,
    backgroundColor: 'purple',
  }
});

export default App;

I've created a snack. The inner views/boxes don't show.

Body:
I managed to figure it out. You create another view inside the scrollView and fix the height. The only problem is that the size of the content views depends on the height of this view instead of the height of the scrollView.

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from 'react-native';
// import { useHeaderHeight } from '@react-navigation/stack';

const App = (props) => {
  let screenHeight = Dimensions.get('window').height;
  // let headerHeight = useHeaderHeight();
  let headerHeight = 0
  let bodyHeight = screenHeight - headerHeight + 500;

  return (
      <ScrollView style={styles.body}>
        <View style={[styles.innerBody, { height: bodyHeight }]}>
          <View style={styles.box1} />
          <View style={styles.box2} />
          <View style={styles.box1} />
        </View>
      </ScrollView>
  );
};

const styles = StyleSheet.create({
  body: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff',
  },
  innerBody: {
    borderColor: 'red',
    borderWidth: 5
  },
  box1: {
    flex: 1,
    backgroundColor: 'blue',
  },
  box2: {
    flex: 2,
    backgroundColor: 'purple',
  }
});

export default App;

Heres a snack showing it working.


问:
How to retrieve all rows from an SQL table into an array?
I am trying to retrieve 4 rows and I expected that It should display all 4 rows but it's only displaying the first row. This is the code I am using</p>

```<code>$coquery = "Select distinct coName from avgcarcompany";
$crun = mysqli_query($con,$coquery);

$arrey = mysqli_fetch_assoc($crun);

print_r($arrey);
</code>```

答:
If you want to get all rows from the result set then you need to fetch all. Right now you are fetching only one.

To fetch all rows use fetch_all()

```<code>$coquery = "Select distinct coName from avgcarcompany";
$crun = $con->query($coquery);

$arrey = $crun->fetch_all(MYSQLI_ASSOC)

print_r($arrey);
</code>```

Body:
I am trying to retrieve 4 rows and I expected that It should display all 4 rows but it's only displaying the first row. This is the code I am using

$coquery = "Select distinct coName from avgcarcompany";
$crun = mysqli_query($con,$coquery);

$arrey = mysqli_fetch_assoc($crun);

print_r($arrey);

Body:
If you want to get all rows from the result set then you need to fetch all. Right now you are fetching only one.

To fetch all rows use fetch_all()

$coquery = "Select distinct coName from avgcarcompany";
$crun = $con->query($coquery);

$arrey = $crun->fetch_all(MYSQLI_ASSOC)

print_r($arrey);


问:
Converting separate month, day and year values into a timestamp
I have a month value (1-12), day value (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.

How can I give this to strtotime() in a way it can convert it to a timestamp?

答:
Is strtotime the best tool for this job?  What about mktime()?

```<code>$time = mktime($hour, $minute, 0, $month, $day, $year);
</code>```

Body:
Is strtotime the best tool for this job?  What about mktime()?

$time = mktime($hour, $minute, 0, $month, $day, $year);


问:
Active font-weight with JS + CSS
I need to know how to activate font-weight on the page (I'm using JavaScript).

Example: If I'm on the teachers page, the  Teachers  font-weight should be bold like shown in image below.

<!DOCTYPE html>

       {% block head %}
           <title>Private Classes</title>
       {% endblock %}

       <link rel="stylesheet" href="/styles.css">

               Teachers
               Students

       {% block content %}
       {% endblock %}

```

答:
You are on teachers page and 'active' class is already there so no need to use javascript for it.
Simply adding font weight to the 'active' class is enough.</p>

```<code><style>
.active{
  font-weight: bold;
}
</style>
</code>```

Title: Active font-weight with JS + CSS

Body:
You are on teachers page and 'active' class is already there so no need to use javascript for it.
Simply adding font weight to the 'active' class is enough.

<style>
.active{
  font-weight: bold;
}
</style>


问:
Can assignment operator be used in if statements. As if statements are used Boolean expression
I was expecting an error in if(b=5), as the assignment operator is used in if statement.

```<code>Code:
#include <stdio.h>

int main() {

    int a=10, b=10;
    if(b=5)
        a--;
    printf("%d, %d", a, b--);
    return 0;
}
</code>```

答:
You expected it to raise an error because it seems a typo in the attempt to use the comparison operator ==, usually used in if-statements like this

```<code>if ( b == 5 )
</code>```

The expression in the if-statement

```<code>if ( b = 5 )
</code>```

is actually evaluated like every expression in C. In this case its evaluation is the value of the assignment 5, and since it is not zero it is equivalent to true in a boolean expression.

It is probably a subtle typo, so that the author probably performed a comparison instead of that assigment. Anyways it doesn't raise an error because it is valid C.

Fortunately, in many compilers a warning is raised. Make sure to enable all warnings in your compiler options, and to never ignore them. In this way you will avoid these subtle traps in the future.

Body:
I was expecting an error in if(b=5), as the assignment operator is used in if statement.

Code:
#include <stdio.h>

int main() {

    int a=10, b=10;
    if(b=5)
        a--;
    printf("%d, %d", a, b--);
    return 0;
}

Body:
You expected it to raise an error because it seems a typo in the attempt to use the comparison operator ==, usually used in if-statements like this

if ( b == 5 )

The expression in the if-statement

if ( b = 5 )

is actually evaluated like every expression in C. In this case its evaluation is the value of the assignment 5, and since it is not zero it is equivalent to true in a boolean expression.

It is probably a subtle typo, so that the author probably performed a comparison instead of that assigment. Anyways it doesn't raise an error because it is valid C.

Fortunately, in many compilers a warning is raised. Make sure to enable all warnings in your compiler options, and to never ignore them. In this way you will avoid these subtle traps in the future.


问:
matplotlib plots 2 line instead of 1
I have this python array:

when I use this code:

```<code>plt.plot(t, 10 * t)
</code>```

I get the following line:

But when I use this code:

```<code>plt.plot(t, t**2)
</code>```

I get 2 lines:

What am I doing wrong here, why is it plotting 2 lines instead of 1??

答:
I think the figure is simply preserving the first plotted line.
Try to add a plt.clf() before plotting the second line. This will clear the figure.

Title: matplotlib plots 2 line instead of 1

Body:
I have this python array:

when I use this code:

plt.plot(t, 10 * t)

I get the following line:

But when I use this code:

plt.plot(t, t**2)

I get 2 lines:

What am I doing wrong here, why is it plotting 2 lines instead of 1??


问:
How do you query text in a SQL Server XML column
I have a XML column in a SQL Server database table. It stores XML responses from a web service.

If that web service times out, it stores the actual text

Error: Timed out waiting for a reply

It's actually storing that text in the XML column - and I can't seem to query it because I cannot compare a string to an XML value. Any ideas?

答:
A non empty string without any tags will be treated as a standalone text node in SQL Server.

So you can use 'text()[1]' to get the first top level text node in the XML content and inspect that.

you can use exist if you want to exclude from consideration any content that is a mix of top level text nodes and elements.

```<code>SELECT *,
        your_col.value('text()[1]', 'varchar(8000)')
FROM t
WHERE your_col.exist('*') = 0 AND your_col.exist('text()') = 1
</code>```

Body:
A non empty string without any tags will be treated as a standalone text node in SQL Server.

So you can use 'text()[1]' to get the first top level text node in the XML content and inspect that.

you can use exist if you want to exclude from consideration any content that is a mix of top level text nodes and elements.

SELECT *,
        your_col.value('text()[1]', 'varchar(8000)')
FROM t
WHERE your_col.exist('*') = 0 AND your_col.exist('text()') = 1


问:
Prometheus Collector fails with "collected metric was collected before with the same name and label values"
I have a device that is exposing temperature measurements as a JSON in the following format:

```<code>[
  {
    "dataPointId": 123456,
    "values": [
      {
        "t": 1589236277000,
        "v": 14.999993896484398
      },
      {
        "t": 1589236877000,
        "v": 14.700006103515648
      },
      {
        "t": 1589237477000,
        "v": 14.999993896484398
      },
[..]
</code>```

As you can see, the values contain both a timestamp and the temperature measurement. I would like to expose these measurements via Prometheus metrics, so I am using prometheus/client_golang to build an exporter.

My expectation would be that the /metrics endpoint then exposes something like this from the data above:

```<code># HELP my_temperature_celsius Temperature
# TYPE my_temperature_celsius gauge
my_temperature_celsius{id="123456"} 14.999993896484398 1589236277000
my_temperature_celsius{id="123456"} 14.700006103515648 1589236877000
my_temperature_celsius{id="123456"} 14.999993896484398 1589237477000
</code>```

I implemented a simple prometheus.Collector and I am adding my static metrics without any issues. For the measurements above, NewMetricWithTimestamp seems to be the only way to add metrics with a timestamp, so I am iterating over these values using something like this:

```<code>for _, measurements := range dp.Values {
  ch <- prometheus.NewMetricWithTimestamp(
    time.Unix(measurements.T, 0),
    prometheus.MustNewConstMetric(
      collector.temperature,
      prometheus.GaugeValue,
      float64(measurements.V),
      device.DatapointID))
}
</code>```

However, this leads to the following error that I do not fully understand:

```<code>An error has occurred while serving metrics:

1135 error(s) occurred:
* collected metric "my_temperature_celsius" { label:<name:"id" value:"123456" > gauge:<value:14.999993896484398 > timestamp_ms:1589236877000000 } was collected before with the same name and label values
* collected metric "my_temperature_celsius" { label:<name:"id" value:"123456" > gauge:<value:14.700006103515648 > timestamp_ms:1589237477000000 } was collected before with the same name and label values
[..]
</code>```

I understand that the metric and label combination must be unique, but as I am also adding a timestamp, does that not count as a unique metric? Is my expectation above even possible?

How can I represent these measurements in a Prometheus exporter?

答:
Ref from Prometheus

```<code>A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.

A histogram samples observations (usually things like request durations or response sizes) and counts them in configurable buckets.
</code>```

Gauge used for one value that we care about, don't care about timestamp. Like Current temperature, not tempratures of last day.

Gauge is not the metric type you are looking for. Or, prometheus may not what you are looking for.

When we want to monitor temprature, we use histogram. which you can calc average temp, min temp or max in a short time. BUT, when you want to use your own timestamp, you need to implement A histogram collector yourself. You can check the file from prometheus/client_golang/histogram.go. Not simple AT ALL.

What you really need is A time series database, like influxdb. You can push you data into influxdb which accept custom timestamp, as simple as post json to http, and then monitor data with grafana.

Wish that would help you.

Body:
I have a device that is exposing temperature measurements as a JSON in the following format:

[
  {
    "dataPointId": 123456,
    "values": [
      {
        "t": 1589236277000,
        "v": 14.999993896484398
      },
      {
        "t": 1589236877000,
        "v": 14.700006103515648
      },
      {
        "t": 1589237477000,
        "v": 14.999993896484398
      },
[..]

As you can see, the values contain both a timestamp and the temperature measurement. I would like to expose these measurements via Prometheus metrics, so I am using prometheus/client_golang to build an exporter.

My expectation would be that the /metrics endpoint then exposes something like this from the data above:

# HELP my_temperature_celsius Temperature
# TYPE my_temperature_celsius gauge
my_temperature_celsius{id="123456"} 14.999993896484398 1589236277000
my_temperature_celsius{id="123456"} 14.700006103515648 1589236877000
my_temperature_celsius{id="123456"} 14.999993896484398 1589237477000

I implemented a simple prometheus.Collector and I am adding my static metrics without any issues. For the measurements above, NewMetricWithTimestamp seems to be the only way to add metrics with a timestamp, so I am iterating over these values using something like this:

for _, measurements := range dp.Values {
  ch <- prometheus.NewMetricWithTimestamp(
    time.Unix(measurements.T, 0),
    prometheus.MustNewConstMetric(
      collector.temperature,
      prometheus.GaugeValue,
      float64(measurements.V),
      device.DatapointID))
}

However, this leads to the following error that I do not fully understand:

An error has occurred while serving metrics:

1135 error(s) occurred:
* collected metric "my_temperature_celsius" { label:<name:"id" value:"123456" > gauge:<value:14.999993896484398 > timestamp_ms:1589236877000000 } was collected before with the same name and label values
* collected metric "my_temperature_celsius" { label:<name:"id" value:"123456" > gauge:<value:14.700006103515648 > timestamp_ms:1589237477000000 } was collected before with the same name and label values
[..]

I understand that the metric and label combination must be unique, but as I am also adding a timestamp, does that not count as a unique metric? Is my expectation above even possible?

How can I represent these measurements in a Prometheus exporter?

Body:
Ref from Prometheus

A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.

A histogram samples observations (usually things like request durations or response sizes) and counts them in configurable buckets.

Gauge used for one value that we care about, don't care about timestamp. Like Current temperature, not tempratures of last day.

Gauge is not the metric type you are looking for. Or, prometheus may not what you are looking for.

When we want to monitor temprature, we use histogram. which you can calc average temp, min temp or max in a short time. BUT, when you want to use your own timestamp, you need to implement A histogram collector yourself. You can check the file from prometheus/client_golang/histogram.go. Not simple AT ALL.

What you really need is A time series database, like influxdb. You can push you data into influxdb which accept custom timestamp, as simple as post json to http, and then monitor data with grafana.

Wish that would help you.


问:
UVA 369-Combinations | Modular Arithmetic | Binary Exponentiation
I am trying to solve uVa's 369(Combinations) problem using Modular Arthimetic and Binary Exponentiation instead of just using BigInteger class in java. I am able to pass the last two base test cases but not the first test case. Can anybody explain where my code is wrong ? </p>

```<code>public class Main {
    static long M = 1000000007;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while(true){
            String s = br.readLine();
            s = s.trim();
            s = s.replaceAll("\\s{2,}", " ");
            String[] str = s.split(" ");
            long n = Long.parseLong(str[0]);
            long m = Long.parseLong(str[1]);
            if(n == 0 && m == 0) break;
            long a = fact(n); long b = fact((n-m) % M); long c = fact(m);
            long d = (b*c) % M;
            long ans = divide(a,d);
            System.out.println(n + " things taken " + m + " at a time is " + ans + " exactly");
        }
    }
    public static long fact(long N){
        long ans = 1;
        for(int i=1; i<=N; ++i)
            ans = (ans * i) % M;
        return ans;
    }
    public static long divide(long a, long b){
        return a * pow(b,M-2) % M;
    }
    public static long pow(long a, long b){
        long res = 1;
        while(b > 0){
            if(b % 2 == 1) res = (res*a) % M;
            a = (a*a) % M;
            b /=2;
        }
        return res;
    }
}

</code>```

答:
M is too small. For example for the input 100 6, the correct result is 1192052400, but since your code works modulo 1000000007 the result will be 1192052400 mod 1000000007 = 192052393, which is much smaller (not just 7 smaller).

Using M = 0x7fffffff (also a prime) may work.

Body:
I am trying to solve uVa's 369(Combinations) problem using Modular Arthimetic and Binary Exponentiation instead of just using BigInteger class in java. I am able to pass the last two base test cases but not the first test case. Can anybody explain where my code is wrong ?

public class Main {
    static long M = 1000000007;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while(true){
            String s = br.readLine();
            s = s.trim();
            s = s.replaceAll("\\s{2,}", " ");
            String[] str = s.split(" ");
            long n = Long.parseLong(str[0]);
            long m = Long.parseLong(str[1]);
            if(n == 0 && m == 0) break;
            long a = fact(n); long b = fact((n-m) % M); long c = fact(m);
            long d = (b*c) % M;
            long ans = divide(a,d);
            System.out.println(n + " things taken " + m + " at a time is " + ans + " exactly");
        }
    }
    public static long fact(long N){
        long ans = 1;
        for(int i=1; i<=N; ++i)
            ans = (ans * i) % M;
        return ans;
    }
    public static long divide(long a, long b){
        return a * pow(b,M-2) % M;
    }
    public static long pow(long a, long b){
        long res = 1;
        while(b > 0){
            if(b % 2 == 1) res = (res*a) % M;
            a = (a*a) % M;
            b /=2;
        }
        return res;
    }
}


问:
Import Error on using pydoc
I have following files in same folder:
config.py, init.py, asc.py and mainfile.py

contents of init.py file:

from mainfile import *

config and asc files are imported in mainfile.py.

I am creating html using pydoc as:
  python -m pydoc -w mainfile.py

I am getting error as:
    <type 'exceptions.ImportError'>: No module named config

If i will remove config, it works fine and html gets created but does not work with config file.

What is the problem?

答:
In Python3

In some cases in python3.x such as in MacOS people are typing pydoc whereas it must be pydoc3 for Python3.x Versions. Thus, the Syntax in its most basic format is

Basic Syntax

```<code>$ pydoc3 -w <module_name> <path_to_module>
</code>```

This should create a .html file in the current directory in which you are using the terminal in.

///////////////////////////////////////////////////////////////////////////////\

;)

Title: Import Error on using pydoc

Body:
In Python3

In some cases in python3.x such as in MacOS people are typing pydoc whereas it must be pydoc3 for Python3.x Versions. Thus, the Syntax in its most basic format is

Basic Syntax

$ pydoc3 -w <module_name> <path_to_module>

This should create a .html file in the current directory in which you are using the terminal in.

///////////////////////////////////////////////////////////////////////////////\

;)


问:
Enable viewBinding by default for new projects
To enable viewBinding I add this to gradle:

```<code>viewBinding
{
   enabled = true
}
</code>```

Is there a way to have viewBinding enabled by default whenever I create a new project?

答: I'm pretty sure there is no way to enable it by default as there is no setting or plugin available for this, but I could be wrong.</p>

Body:
To enable viewBinding I add this to gradle:

viewBinding
{
   enabled = true
}

Is there a way to have viewBinding enabled by default whenever I create a new project?


答:
Inside the if statement there is a valid assignment. The result of such operation is the assigned value (5) which is valid inside an if statement and evaluates to true.

Actually, any number other than 0 will be interpreted as true.

Maybe you already know, but you are not making a comparison there. The comparison operation is ==.

Title: Can assignment operator be used in if statements. As if statements are used Boolean expression


问:
Method overloading with dynamic data types
Why compiler is restraining to overload method in below way, Compilation Error i get in update method with dynamic type parameter.

Error - Type 'Program' already defines a member called 'update' with the same parameter types

```<code>static void update(string name)
    {

    }
static void update(object name)
    {

    }

static void update(dynamic name)
    {

    }
</code>```

答:
Because dynamic is also a type of object. You can check the generated IL code. So its giving compilation error for

```<code>static void update(object name)
    {

    }

static void update(dynamic name)
    {

    }
</code>```

Body:
Why compiler is restraining to overload method in below way, Compilation Error i get in update method with dynamic type parameter.

Error - Type 'Program' already defines a member called 'update' with the same parameter types

static void update(string name)
    {

    }
static void update(object name)
    {

    }

static void update(dynamic name)
    {

    }

Body:
Because dynamic is also a type of object. You can check the generated IL code. So its giving compilation error for

static void update(object name)
    {

    }

static void update(dynamic name)
    {

    }