问:
How to download maven dependency as *.jar file?
I attempt to implement the example from here, but upon the Maven dependencies installation I can't find jar file amongst downloaded dependencies.

My pom.xml looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- This is often your domain name (reversed.)  -->
    <groupId>com.abc</groupId>
    <!-- The name of this project (actually, the name of the artifact, which is the thing that this project produces. A jar in this case.) -->
    <artifactId>javaparser-maven-sample</artifactId>
    <!-- The version of this project. SNAPSHOT means "we're still working on it" -->
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- Tell Maven we want to use Java 8 -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <!-- Tell Maven to treat all source files as UTF-8 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <geotools.version>2.5.7</geotools.version>
    </properties>
   <repositories>
    <repository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net repository</name>
        <url>http://download.java.net/maven/2</url>
    </repository>
    <repository>
        <id>osgeo</id>
        <name>Open Source Geospatial Foundation Repository</name>
        <url>http://download.osgeo.org/webdav/geotools/</url>
    </repository>
    <repository> <!--Add the snapshot repository here-->
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
        <id>opengeo</id>
        <name>OpenGeo Maven Repository</name>
        <url>http://repo.opengeo.org</url>
    </repository>
</repositories>

    <dependencies>
        <!-- Here are all your dependencies. Currently only one. These are automatically downloaded from https://mvnrepository.com/ -->
        <dependency>
            <groupId>com.github.javaparser</groupId>
            <artifactId>javaparser-core</artifactId>
            <version>3.15.21</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mil.nga.geopackage/geopackage -->
        <dependency>
            <groupId>mil.nga.geopackage</groupId>
            <artifactId>geopackage</artifactId>
            <version>3.5.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.geotools/gt-api -->
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-api</artifactId>
            <version>20.5</version>
        </dependency>

    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-epsg-hsql</artifactId>
        <version>${geotools.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.geotools/gt-geometry -->
    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-geometry</artifactId>
        <version>2.5-M2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.geotools/gt-referencing -->
    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-referencing</artifactId>
        <version>17.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.locationtech.jts.io/jts-io-common -->
    <dependency>
        <groupId>org.locationtech.jts.io</groupId>
        <artifactId>jts-io-common</artifactId>
        <version>1.16.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.opengis/geoapi -->
    <dependency>
        <groupId>org.opengis</groupId>
        <artifactId>geoapi</artifactId>
        <version>3.0.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.geotools/gt-jts-wrapper -->
<dependency>
    <groupId>org.geotools</groupId>
    <artifactId>gt-jts-wrapper</artifactId>
    <version>17.0</version>
    <scope>test</scope>
</dependency>
    <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>17.0</version>
        </dependency>

    </dependencies>

    <!-- This blob of configuration tells Maven to make the jar executable. You can run it with:
    mvn clean package
    java -jar target/javaparser-maven-sample-1.0-SNAPSHOT-shaded.jar
    -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <shadedArtifactAttached>true</shadedArtifactAttached>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.abc.conversion.LogicPositivizer</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

I am able to download all the jars except geotools related jars. When I clean and run the project, in the .m2 folder I am not able to see the geotool related jars. Even in the maven repository I am not able to download the jar file.

Maven repo

Is there any alternative way to proceed?

答:
If you paste the Open Source Geospatial Foundation Repository URL in your web browser and hit enter it will return 404 Not Found error. This happens when Maven attempts to connect to that resource to fetch dependency for you but it's no longer available. However, if you pay close attention to Maven Repo link, there is a note:

Note: this artefact is located at Boundless repository (https://repo.boundlessgeo.com/main/)

Try to replace http://download.osgeo.org/webdav/geotools/ with a given in the note URL and run mvn clean install

Please let me know if that worked for you.

Body:
I attempt to implement the example from here, but upon the Maven dependencies installation I can't find jar file amongst downloaded dependencies.

My pom.xml looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.abc</groupId>

    <artifactId>javaparser-maven-sample</artifactId>

    <version>1.0-SNAPSHOT</version>

    <properties>

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <geotools.version>2.5.7</geotools.version>
    </properties>
   <repositories>
    <repository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net repository</name>
        <url>http://download.java.net/maven/2</url>
    </repository>
    <repository>
        <id>osgeo</id>
        <name>Open Source Geospatial Foundation Repository</name>
        <url>http://download.osgeo.org/webdav/geotools/</url>
    </repository>
    <repository>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
        <id>opengeo</id>
        <name>OpenGeo Maven Repository</name>
        <url>http://repo.opengeo.org</url>
    </repository>
</repositories>

    <dependencies>

        <dependency>
            <groupId>com.github.javaparser</groupId>
            <artifactId>javaparser-core</artifactId>
            <version>3.15.21</version>
        </dependency>

        <dependency>
            <groupId>mil.nga.geopackage</groupId>
            <artifactId>geopackage</artifactId>
            <version>3.5.0</version>
        </dependency>

        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-api</artifactId>
            <version>20.5</version>
        </dependency>

    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-epsg-hsql</artifactId>
        <version>${geotools.version}</version>
    </dependency>

    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-geometry</artifactId>
        <version>2.5-M2</version>
    </dependency>

    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-referencing</artifactId>
        <version>17.1</version>
    </dependency>

    <dependency>
        <groupId>org.locationtech.jts.io</groupId>
        <artifactId>jts-io-common</artifactId>
        <version>1.16.1</version>
    </dependency>

    <dependency>
        <groupId>org.opengis</groupId>
        <artifactId>geoapi</artifactId>
        <version>3.0.0</version>
    </dependency>

<dependency>
    <groupId>org.geotools</groupId>
    <artifactId>gt-jts-wrapper</artifactId>
    <version>17.0</version>
    <scope>test</scope>
</dependency>
    <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>17.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <shadedArtifactAttached>true</shadedArtifactAttached>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.abc.conversion.LogicPositivizer</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

I am able to download all the jars except geotools related jars. When I clean and run the project, in the .m2 folder I am not able to see the geotool related jars. Even in the maven repository I am not able to download the jar file.

Maven repo

Is there any alternative way to proceed?


来源: stackexchange

问:
Math symbols not rendered correctly in R notebook format from KableExtra table objects
UPDATE: KableExtra creator haozhu233 added mathjax support to the package. See my original issue and his comments on Github: https://github.com/haozhu233/kableExtra/issues/473#issuecomment-668224096

When I try and create a table using kable and kableExtra I cannot get math symbols to display correctly. I am able to produce math characters in normal kable tables like expected. I've tried different variations of the options escape = FALSE and protect_latex = T without any luck. The math symbols display correctly if I knit to PDF or HTML, it's just the inline display (and preview) and notebook display that show the raw characters.

As far as I can see from the HTML output, the only difference between the kable table and the kableExtra table is that the latter contains some extra info on the class and style. The R objects are also of a different class, which makes me wonder if the problem might be that mathjax is not called to render kableExtra objects? If so, is there a way I can tell Rstudio to call on mathjax when rendering HTML from kableExtra objects?

I've reproduced this problem on two different computers and using the RStudio Cloud.

Note: i filed a Github Issue but realized that it might be more appropriate to ask here. I've also posted on the Rstudio community without getting a response so I thought I'd try my luck here.

Reprex:

```<code>---
title: "Kable Extra Math Symbols"
output: html_notebook
---

```{r}

math_symb <- c(1,2,3,4)

kable_table <- knitr::kable(math_symb, col.names = "$R^{2}$")
styled_kable_table <- kableExtra::kable_styling(kable_table)

kable_table
styled_kable_table
```{}
</code>```

From the example the object kable_table is rendered with the column name "R2", which is what I want to achieve whereas the styled_kable_table object is displayed with the the undesired column name "$R^2$"

Session Info:

R version 3.6.3 (2020-02-29)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
2 LC_COLLATE=Norwegian Bokmål_Norway.1252 LC_CTYPE=Norwegian Bokmål_Norway.1252
[3] LC_MONETARY=Norwegian Bokmål_Norway.1252 LC_NUMERIC=C
[5] LC_TIME=Norwegian Bokmål_Norway.1252

attached base packages:
2 stats graphics grDevices utils datasets methods base

loaded via a namespace (and not attached):
2 Rcpp_1.0.4.6 rstudioapi_0.11 xml2_1.3.2 knitr_1.28 magrittr_1.5 hms_0.5.3
[7] munsell_0.5.0 rvest_0.3.5 viridisLite_0.3.0 colorspace_1.4-1 R6_2.4.1 rlang_0.4.6
[13] stringr_1.4.0 httr_1.4.1 highr_0.8 tools_3.6.3 webshot_0.5.2 xfun_0.14
[19] htmltools_0.4.0 ellipsis_0.3.0 yaml_2.2.1 digest_0.6.25 tibble_3.0.1 lifecycle_0.2.0
[25] crayon_1.3.4 kableExtra_1.1.0 readr_1.3.1 vctrs_0.3.0 glue_1.4.1 evaluate_0.14
[31] rmarkdown_2.1 stringi_1.4.6 compiler_3.6.3 pillar_1.4.4 scales_1.1.1 pkgconfig_2.0.3

答:
You're producing an HTML document, so you need to format your header using HTML:

```<code>math_symb <- c(1,2,3,4)
math_symb %>%  kable(col.names = "R<sup>2</sup>")
</code>```

Gives

ContentLicense: CC BY-SA 4.0

Body:
UPDATE: KableExtra creator haozhu233 added mathjax support to the package. See my original issue and his comments on Github: https://github.com/haozhu233/kableExtra/issues/473#issuecomment-668224096

When I try and create a table using kable and kableExtra I cannot get math symbols to display correctly. I am able to produce math characters in normal kable tables like expected. I've tried different variations of the options escape = FALSE and protect_latex = T without any luck. The math symbols display correctly if I knit to PDF or HTML, it's just the inline display (and preview) and notebook display that show the raw characters.

As far as I can see from the HTML output, the only difference between the kable table and the kableExtra table is that the latter contains some extra info on the class and style. The R objects are also of a different class, which makes me wonder if the problem might be that mathjax is not called to render kableExtra objects? If so, is there a way I can tell Rstudio to call on mathjax when rendering HTML from kableExtra objects?

I've reproduced this problem on two different computers and using the RStudio Cloud.

Note: i filed a Github Issue but realized that it might be more appropriate to ask here. I've also posted on the Rstudio community without getting a response so I thought I'd try my luck here.

Reprex:

---
title: "Kable Extra Math Symbols"
output: html_notebook
---

```{r}

math_symb <- c(1,2,3,4)

kable_table <- knitr::kable(math_symb, col.names = "$R^{2}$")
styled_kable_table <- kableExtra::kable_styling(kable_table)

kable_table
styled_kable_table
```{}

From the example the object kable_table is rendered with the column name "R2", which is what I want to achieve whereas the styled_kable_table object is displayed with the the undesired column name "$R^2$"

Session Info:

R version 3.6.3 (2020-02-29)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
2 LC_COLLATE=Norwegian Bokmål_Norway.1252 LC_CTYPE=Norwegian Bokmål_Norway.1252
[3] LC_MONETARY=Norwegian Bokmål_Norway.1252 LC_NUMERIC=C
[5] LC_TIME=Norwegian Bokmål_Norway.1252

attached base packages:
2 stats graphics grDevices utils datasets methods base

loaded via a namespace (and not attached):
2 Rcpp_1.0.4.6 rstudioapi_0.11 xml2_1.3.2 knitr_1.28 magrittr_1.5 hms_0.5.3
[7] munsell_0.5.0 rvest_0.3.5 viridisLite_0.3.0 colorspace_1.4-1 R6_2.4.1 rlang_0.4.6
[13] stringr_1.4.0 httr_1.4.1 highr_0.8 tools_3.6.3 webshot_0.5.2 xfun_0.14
[19] htmltools_0.4.0 ellipsis_0.3.0 yaml_2.2.1 digest_0.6.25 tibble_3.0.1 lifecycle_0.2.0
[25] crayon_1.3.4 kableExtra_1.1.0 readr_1.3.1 vctrs_0.3.0 glue_1.4.1 evaluate_0.14
[31] rmarkdown_2.1 stringi_1.4.6 compiler_3.6.3 pillar_1.4.4 scales_1.1.1 pkgconfig_2.0.3

Body:
You're producing an HTML document, so you need to format your header using HTML:

math_symb <- c(1,2,3,4)
math_symb %>%  kable(col.names = "R<sup>2</sup>")

Gives


问:
Firebase Cloud Messaging - "success" and "failure" in response JSON
I use Firebase Cloud Messaging to deliver notifications to my Android client apps, each notification should be sent to a single device according to its registration token.

Each time I send a notification via https://fcm.googleapis.com/fcm/send, I receive a JSON response like this one:

```<code>{
  "multicast_id": 108,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    { "message_id": "1:08" }
  ]
}
</code>```

I find success and failure redundant - don't they mean the same thing? Should I check both of them to be sure everything is fine? Is it always true that success != failure?

答:
Add the notification parameter along with data and registration_ids.

```<code>{"notification":{"title":"","body":""},"data":{},"registration_ids":["acaxdYt5464262hghdsd*****"]
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use Firebase Cloud Messaging to deliver notifications to my Android client apps, each notification should be sent to a single device according to its registration token.

Each time I send a notification via https://fcm.googleapis.com/fcm/send, I receive a JSON response like this one:

{
  "multicast_id": 108,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    { "message_id": "1:08" }
  ]
}

I find success and failure redundant - don't they mean the same thing? Should I check both of them to be sure everything is fine? Is it always true that success != failure?

Body:
Add the notification parameter along with data and registration_ids.

{"notification":{"title":"","body":""},"data":{},"registration_ids":["acaxdYt5464262hghdsd*****"]
}


问:
R - Merging city name to approximate lat-long coordinates
I want to merge city names to approximate coordinates.

I have two datasets.

lat-long for cities, called cities.

lat-long for observed events, called events.

Most of the events occur just out-side the lat-longs of the city.

I want to merge in the city from cities if the lat-long are max 1 lat and lon different from those listed in events.

The nearest function in data.table seems to be too crude.

What would you do? Use maptools?

Example:

```<code>cities <- data.table(city = c("A", "B", "C"),
                 lat = c(23.4, 43.5, 21.3),
                 lon = c(100, 98.4, -78.2))

events <- data.table(event = c("X1", "Y1", "B1"),
                 lat = c(24.4, 42.5, 23.3),
                 lon = c(101, 100.4, -78.2)))

result <- data.table(event = c("X1", "Y1", "B1"),
                 lat = c(23.4, 43.5, 21.3),
                 lon = c(100, 98.4, -78.2),
                 city = c("A", NA, NA))

> result
   event  lat   lon city
1:    X1 23.4 100.0    A
2:    Y1 43.5  98.4 <NA>
3:    B1 21.3 -78.2 <NA>
</code>```

答:
method 1: non-equi join

This non-equi update join do the trick... But this only will work since you put on a hard 1-degree limit. Problem is dat the distance bewteen 2 degrees will vary around the globe...

```<code>events[ cities[, `:=`(lat_min = lat - 1, lat_max = lat+1,
                      lon_min = lon - 1, lon_max = lon + 1) ],
        city := i.city,
        on = .(lat >= lat_min, lat <= lat_max, lon >= lon_min, lon <= lon_max ) ][]

#    event  lat   lon city
# 1:    X1 24.4 101.0    A
# 2:    Y1 42.5 100.4 <NA>
# 3:    B1 23.3 -78.2 <NA>
</code>```

method 2: based on  absolute distance

If you want to set a maximum distance bwetween events and cities, you'll need a spatial solution like this:

```<code>#maximum distance between event and city (in metres)
max_dist = 180000

library( sf )
#create simple (point) features of events and cities
cities.sf <- st_as_sf( cities, coords = c("lon", "lat"), crs = 4326 )
events.sf <- st_as_sf( events, coords = c("lon", "lat"), crs = 4326 )

#spatial join
st_join( events.sf, cities.sf, join = st_is_within_distance, dist = max_dist )

# Simple feature collection with 3 features and 2 fields
# geometry type:  POINT
# dimension:      XY
# bbox:           xmin: -78.2 ymin: 23.3 xmax: 101 ymax: 42.5
# CRS:            EPSG:4326
#   event city           geometry
# 1    X1    A   POINT (101 24.4)
# 2    Y1 <NA> POINT (100.4 42.5)
# 3    B1 <NA> POINT (-78.2 23.3)
</code>```

Body:
I want to merge city names to approximate coordinates.

I have two datasets.

lat-long for cities, called cities.

lat-long for observed events, called events.

Most of the events occur just out-side the lat-longs of the city.

I want to merge in the city from cities if the lat-long are max 1 lat and lon different from those listed in events.

The nearest function in data.table seems to be too crude.

What would you do? Use maptools?

Example:

cities <- data.table(city = c("A", "B", "C"),
                 lat = c(23.4, 43.5, 21.3),
                 lon = c(100, 98.4, -78.2))

events <- data.table(event = c("X1", "Y1", "B1"),
                 lat = c(24.4, 42.5, 23.3),
                 lon = c(101, 100.4, -78.2)))

result <- data.table(event = c("X1", "Y1", "B1"),
                 lat = c(23.4, 43.5, 21.3),
                 lon = c(100, 98.4, -78.2),
                 city = c("A", NA, NA))

> result
   event  lat   lon city
1:    X1 23.4 100.0    A
2:    Y1 43.5  98.4 <NA>
3:    B1 21.3 -78.2 <NA>

Body:
method 1: non-equi join

This non-equi update join do the trick... But this only will work since you put on a hard 1-degree limit. Problem is dat the distance bewteen 2 degrees will vary around the globe...

events[ cities[, `:=`(lat_min = lat - 1, lat_max = lat+1,
                      lon_min = lon - 1, lon_max = lon + 1) ],
        city := i.city,
        on = .(lat >= lat_min, lat <= lat_max, lon >= lon_min, lon <= lon_max ) ][]

#    event  lat   lon city
# 1:    X1 24.4 101.0    A
# 2:    Y1 42.5 100.4 <NA>
# 3:    B1 23.3 -78.2 <NA>

method 2: based on  absolute distance

If you want to set a maximum distance bwetween events and cities, you'll need a spatial solution like this:

#maximum distance between event and city (in metres)
max_dist = 180000

library( sf )
#create simple (point) features of events and cities
cities.sf <- st_as_sf( cities, coords = c("lon", "lat"), crs = 4326 )
events.sf <- st_as_sf( events, coords = c("lon", "lat"), crs = 4326 )

#spatial join
st_join( events.sf, cities.sf, join = st_is_within_distance, dist = max_dist )

# Simple feature collection with 3 features and 2 fields
# geometry type:  POINT
# dimension:      XY
# bbox:           xmin: -78.2 ymin: 23.3 xmax: 101 ymax: 42.5
# CRS:            EPSG:4326
#   event city           geometry
# 1    X1    A   POINT (101 24.4)
# 2    Y1 <NA> POINT (100.4 42.5)
# 3    B1 <NA> POINT (-78.2 23.3)


问:
How to rate limit a for each request
I'm calling the Webflow CMS API which has a rate limit of 60 requests per minute. As I have 300 items to update/create I am wondering how I can slow down my forEach to meet the rate limit:

```<code>static update(collectionData, country, res) {

        return collectionData.get()
            .then(docs => {
                return docs.forEach(doc => {
                setTimeout(() => {
                    let country = doc.data();

                    return axios.request({
                        url: country.webflowId ? (webflowCollection + '/' + country.webflowId) : webflowCollection,
                        method: country.webflowId ? 'patch' : 'post',
                        headers: webflowHeaders,
                        data: {
                            "fields": {
                                "name": country.country,
                                "slug": country.country.replace(/\s+/g, '-').replace("'", "-").toLowerCase(),
                                "country-code": country.countryCode,
                                "_archived": false,
                                "_draft": false
                            }
                        }
                    })
                        .then(function (response) {
                            console.log('Updated ' + country.country + " (id: " + response.data._id + ")");
                            return doc.ref.set({
                                webflowId: response.data._id
                            }, {merge: true});
                        })
                        .catch(function (response) {
                            console.log(JSON.stringify(response));
                            return res.send(JSON.stringify(response));
                        });
                });
            })
            .then(() => {
                return res.status(200).send('Update complete!');
            })
            .catch(err => {
                return res.status(404).send('Error listing countries: ' + err);
            });
            },2000);
    }
</code>```

I've tried await functions and setTimeout but nothing seems to work. The code powers through and hits the limit which then returns a 429 error.

答:
You should maybe have a look at the axios-rate-limit module

https://github.com/aishek/axios-rate-limit

Title: How to rate limit a for each request

Body:
I'm calling the Webflow CMS API which has a rate limit of 60 requests per minute. As I have 300 items to update/create I am wondering how I can slow down my forEach to meet the rate limit:

static update(collectionData, country, res) {

        return collectionData.get()
            .then(docs => {
                return docs.forEach(doc => {
                setTimeout(() => {
                    let country = doc.data();

                    return axios.request({
                        url: country.webflowId ? (webflowCollection + '/' + country.webflowId) : webflowCollection,
                        method: country.webflowId ? 'patch' : 'post',
                        headers: webflowHeaders,
                        data: {
                            "fields": {
                                "name": country.country,
                                "slug": country.country.replace(/\s+/g, '-').replace("'", "-").toLowerCase(),
                                "country-code": country.countryCode,
                                "_archived": false,
                                "_draft": false
                            }
                        }
                    })
                        .then(function (response) {
                            console.log('Updated ' + country.country + " (id: " + response.data._id + ")");
                            return doc.ref.set({
                                webflowId: response.data._id
                            }, {merge: true});
                        })
                        .catch(function (response) {
                            console.log(JSON.stringify(response));
                            return res.send(JSON.stringify(response));
                        });
                });
            })
            .then(() => {
                return res.status(200).send('Update complete!');
            })
            .catch(err => {
                return res.status(404).send('Error listing countries: ' + err);
            });
            },2000);
    }

I've tried await functions and setTimeout but nothing seems to work. The code powers through and hits the limit which then returns a 429 error.


问:
Im working on a python problem to optimize the script

to make the row values of option_labels column into column headers

if the option_labels is present for a particular user_id, I would apply the value of option_values in the created new columns, else it would be 0.

sample data is: (data.csv)

```<code> user_id       country        option_values        option_labels

 abc456         Germany        256gb                  SSD
 abc123         Brazil         i5                    intel
 xyz456         France         128gb                  SSD
 xyz123         Turkey         i7                    intel
 abc123         Brazil         2gb                   nvidia
 abc456         Germany        32gb                   RAM
 xyz123         Turkey         4gb                   nvidia
 xyz456         France         16gb                   RAM
</code>```

sample output would be:

```<code> user_id       country        option_values     option_labels     intel         nvidia       SSD        RAM

 abc456         Germany        256gb             SSD                0              0        256gb        0
 abc123         Brazil         i5                intel              i5             0          0          0
 xyz456         France         256gb             SSD                0              0        128gb        0
 xyz123         Turkey         i7                intel              i7             0          0          0
 abc123         Brazil         2gb               nvidia             0              2gb        0          0
 abc456         Germany        32gb              RAM                0              0          0          32gb
 xyz123         Turkey         4gb               nvidia             0              4gb        0          0
 xyz456         France         16gb              RAM                0              0          0          16gb
</code>```

I have done this process with the below sample code,

```<code> import pandas as pd
 import numpy as np

 data_sample = pd.read_csv("data.csv")
 feature_list = data_sample["option_label"].unique().tolist()
 user_list = data_sample["user_id"].unique().tolist()
 country_list = data_sample["country"].unique().tolist()
 opt_val_list = data_sample["opt_val"].unique().tolist()

 def filterd_id(check_id):
     single_id_data= data_sample[data_sample['user_id'] == check_id]
     return single_id_data

 def finding_features(single_id_data):
     user_features = single_id_data["option_labels"].unique().tolist()
     return user_features

 def check_feature(feature_list, user_features):
     feature_prs_not = []
     for i in feature_list:
         if(i in user_features):
             result = opt_val_list
         else:
             result = 0
         feature_prs_not.append(result)
     return feature_prs_not

 user_id = []
 country = []

 for i in user_list:
     check_id = i
     user_id.append(i)
     single_id_data = filterd_id(check_id)
     c = single_id_data["country"].unique().tolist()
     country.append(c)
     user_features = finding_features(single_id_data)
     feature_prst_not = check_feature(feature_list,user_features)
     df = pd.DataFrame([feature_prst_not], columns = feature_list)
     df_feature = df_feature.append(df)
 df_user_id = pd.DataFrame(user_id, columns=['all_user_id'])
 df_country = pd.DataFrame(country, columns=['country_name'])
</code>```

its taking much more time to run (for eg.. 8-9 hours) for my original data of nearly 100k ids.
I'm still in the learning phase in Python, Im trying to optimize now to reduce the run time of the script.

答:
If you want it faster you need to vectorize. I believe this code produces the same output as yours

```<code>import numpy as np

for val in df['option_labels'].unique():
    df[val] = np.where(df['option_labels']==val, df['option_values'], 0)
</code>```

That's how I reproduced your data

```<code>from io import StringIO

df = pd.read_csv(StringIO('''
"user_id","country","option_values","option_labels"
"abc456","Germany","256gb","SSD"
"abc123","Brazil","i5","intel"
"xyz456","France","128gb","SSD"
"xyz123","Turkey","i7","intel"
"abc123","Brazil","2gb","nvidia"
"abc456","Germany","32gb","RAM"
"xyz123","Turkey","4gb","nvidia"
"xyz456","France","16gb","RAM"'''))
</code>```

Body:
to make the row values of option_labels column into column headers

if the option_labels is present for a particular user_id, I would apply the value of option_values in the created new columns, else it would be 0.

sample data is: (data.csv)

 user_id       country        option_values        option_labels

 abc456         Germany        256gb                  SSD
 abc123         Brazil         i5                    intel
 xyz456         France         128gb                  SSD
 xyz123         Turkey         i7                    intel
 abc123         Brazil         2gb                   nvidia
 abc456         Germany        32gb                   RAM
 xyz123         Turkey         4gb                   nvidia
 xyz456         France         16gb                   RAM

sample output would be:

 user_id       country        option_values     option_labels     intel         nvidia       SSD        RAM

 abc456         Germany        256gb             SSD                0              0        256gb        0
 abc123         Brazil         i5                intel              i5             0          0          0
 xyz456         France         256gb             SSD                0              0        128gb        0
 xyz123         Turkey         i7                intel              i7             0          0          0
 abc123         Brazil         2gb               nvidia             0              2gb        0          0
 abc456         Germany        32gb              RAM                0              0          0          32gb
 xyz123         Turkey         4gb               nvidia             0              4gb        0          0
 xyz456         France         16gb              RAM                0              0          0          16gb

I have done this process with the below sample code,

 import pandas as pd
 import numpy as np

 data_sample = pd.read_csv("data.csv")
 feature_list = data_sample["option_label"].unique().tolist()
 user_list = data_sample["user_id"].unique().tolist()
 country_list = data_sample["country"].unique().tolist()
 opt_val_list = data_sample["opt_val"].unique().tolist()

 def filterd_id(check_id):
     single_id_data= data_sample[data_sample['user_id'] == check_id]
     return single_id_data

 def finding_features(single_id_data):
     user_features = single_id_data["option_labels"].unique().tolist()
     return user_features

 def check_feature(feature_list, user_features):
     feature_prs_not = []
     for i in feature_list:
         if(i in user_features):
             result = opt_val_list
         else:
             result = 0
         feature_prs_not.append(result)
     return feature_prs_not

 user_id = []
 country = []

 for i in user_list:
     check_id = i
     user_id.append(i)
     single_id_data = filterd_id(check_id)
     c = single_id_data["country"].unique().tolist()
     country.append(c)
     user_features = finding_features(single_id_data)
     feature_prst_not = check_feature(feature_list,user_features)
     df = pd.DataFrame([feature_prst_not], columns = feature_list)
     df_feature = df_feature.append(df)
 df_user_id = pd.DataFrame(user_id, columns=['all_user_id'])
 df_country = pd.DataFrame(country, columns=['country_name'])

its taking much more time to run (for eg.. 8-9 hours) for my original data of nearly 100k ids.
I'm still in the learning phase in Python, Im trying to optimize now to reduce the run time of the script.

Body:
If you want it faster you need to vectorize. I believe this code produces the same output as yours

import numpy as np

for val in df['option_labels'].unique():
    df[val] = np.where(df['option_labels']==val, df['option_values'], 0)

That's how I reproduced your data

from io import StringIO

df = pd.read_csv(StringIO('''
"user_id","country","option_values","option_labels"
"abc456","Germany","256gb","SSD"
"abc123","Brazil","i5","intel"
"xyz456","France","128gb","SSD"
"xyz123","Turkey","i7","intel"
"abc123","Brazil","2gb","nvidia"
"abc456","Germany","32gb","RAM"
"xyz123","Turkey","4gb","nvidia"
"xyz456","France","16gb","RAM"'''))


问:
How is an int data stored on the memory in terms of bits? Is it not right-aligned?
I got really confused while I was trying some things out with fwrite function in C.

I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/

It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to 4 characters.

I thought that a bit representation of a value is right-aligned on memory. That is, 98(ascii of 'b') would be stored as

00000000 00000000 00000000 01100010

on the memory. So I expected the fwrite function to write ' ', ' ', ' ', 'b' in the txt file. Instead, it wrote 'b', ' ', ' ', ' '.

I got confused so I tested it again with pointer, hoping my knowledge about memory storage was not wrong and it was only about fwrite function. I made an integer array arr, and put (1<<8)+2, 98 in it.

I used char pointer to split each integer into four bytes. Here's the code.

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

int main()
{
    int arr[5]={(1<<8)+2, 98, 'c', 'd', 'e'};
    char *p = (char*)&(arr[0]);

    printf("%d %d %d %d %d %d", arr[0], (int)(*p), (int)(*(p+1)), (int)(*(p+2)), (int)(*(p+3)), (int)(*(p+4)));

    FILE *fp;

    fp = fopen("TestFile2.txt", "a");
    fwrite(arr, sizeof(char), 5, fp);
    fclose(fp);
}
</code>```

The program printed "258 2 1 0 0 98" on the console, and "  b" was written in TestFile2 (exlcluding "s).

In my knowledge, (1<<8)+2 representation in terms of bits is

00000000 00000000 00000001 00000010 so the program should've printed 258 0 0 1 2 0.

The weird thing is that the result is not even left-aligned bit representation of the value either.

How is a value store on the memory bitwise? Is it not like what I thought it is? Or, am I missing something else here?

Any helps would be really appreciated.

答:
There's no such concept as "right alignment" in memory storage.  Only big endian (meaning most significant byte is stored in the lower addressed memory while the least significant byte is stored in the higher addressed memory) and little endian (least significant byte stored in the lower addressed memory and the most significant byt stored in the highest addressed memory)

The order of bits in a byte is a different thing.  I've seen books where bits are number from 1 to 8, from higher to lower weight in the byte, and others where the bits are number from 0 to 7 by their weights in the word.  Another issue is how are the individual bits in a word transferred when they are serialized to go on the net.  some protocols transmit least significant bit firs (mainly rs-232c and ethernet) while others transmit most significant bit first (I think, but I'm not sure, USB and CAN BUS)

if you are using fwrite(2) to write a multibyte int it depends on the machine architecture, to see the order of the bytes actually transferred over the file descriptor.  As fwrite() always writes the bytes from lower addressed byte cells to higher, the bytes of the integer will be writen as you write in the paper (most weighted first, then least weighted bytes of the number) only if you are in a big endian machine (sparc, motorolas, and some arms --- in arms, the endiannes is user selectable) but if you are in a little endian machine, then you'll get the bytes with lesser weight first, then the most weighted bytes (e.g. Intel, etc.)

Body:
I got really confused while I was trying some things out with fwrite function in C.

I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/

It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to 4 characters.

I thought that a bit representation of a value is right-aligned on memory. That is, 98(ascii of 'b') would be stored as

00000000 00000000 00000000 01100010

on the memory. So I expected the fwrite function to write ' ', ' ', ' ', 'b' in the txt file. Instead, it wrote 'b', ' ', ' ', ' '.

I got confused so I tested it again with pointer, hoping my knowledge about memory storage was not wrong and it was only about fwrite function. I made an integer array arr, and put (1<<8)+2, 98 in it.

I used char pointer to split each integer into four bytes. Here's the code.

#include <stdio.h>

int main()
{
    int arr[5]={(1<<8)+2, 98, 'c', 'd', 'e'};
    char *p = (char*)&(arr[0]);

    printf("%d %d %d %d %d %d", arr[0], (int)(*p), (int)(*(p+1)), (int)(*(p+2)), (int)(*(p+3)), (int)(*(p+4)));

    FILE *fp;

    fp = fopen("TestFile2.txt", "a");
    fwrite(arr, sizeof(char), 5, fp);
    fclose(fp);
}

The program printed "258 2 1 0 0 98" on the console, and "  b" was written in TestFile2 (exlcluding "s).

In my knowledge, (1<<8)+2 representation in terms of bits is

00000000 00000000 00000001 00000010 so the program should've printed 258 0 0 1 2 0.

The weird thing is that the result is not even left-aligned bit representation of the value either.

How is a value store on the memory bitwise? Is it not like what I thought it is? Or, am I missing something else here?

Any helps would be really appreciated.


问:
How can i use angular interpolation as index in an array?
I am trying to make an exam type true or false simulator with angular 9, but when i try to correct each question i cant interpolate the index of the correction. I have this error:

```<code>ERROR in Template parse errors:
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
</code>```

The issue is about the way of interpolate the index of the correccion array
Here is my ts code:

```<code>    import { Component, OnInit } from '@angular/core';
import { PreguntaService } from '../../services/pregunta.service';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-examen',
  templateUrl: './examen.component.html',
  styleUrls: ['./examen.component.css'],
  providers: [PreguntaService]
})
export class ExamenComponent implements OnInit {

  public numeroPreguntas: any;
  public preguntas: any;
  public status: boolean;
  public timeLeft: number;
  public interval;
  public subscribeTimer: any;
  public timerStatus: boolean;
  public correccion: any;
  public iteracion: number;
  public respuesta: boolean;

  constructor(private _preguntaService: PreguntaService) {
    this.numeroPreguntas = 10;
    this.status = false;
    this.timeLeft = this.numeroPreguntas * 40;
    this.correccion = new Array;
  }

  ngOnInit(): void {
    this.status = false;
    console.log(this.preguntas);

  }

  generateExam() {
    this.preguntas = new Array;
    for (let i = 0; i < this.numeroPreguntas; i++) {
    this._preguntaService.getRandomPregunta().subscribe(response=>{
        this.preguntas.push(response.pregunta);
      },
      error=>{
        console.log(<any>error);

      }
    );

    }

    console.log(this.preguntas);

    this.status = true;
  }
  changeNumber($event) {
    this.numeroPreguntas = $event;
    this.preguntas = new Array(this.numeroPreguntas);
    this.timeLeft = this.numeroPreguntas * 40;
  }

  changeRadio($event){
    this.respuesta = $event;
  }
  onSubmit(responseForm: NgForm) {
      this.respuesta=responseForm.controls['respuesta'].value;
      this.iteracion = responseForm.controls['iteracion2'].value;

    console.log('hola');
    console.log(this.iteracion);
    console.log(this.respuesta);

    if (this.preguntas[this.iteracion].response == this.respuesta ) {
      this.correccion = true;
    }else{
      this.correccion[this.iteracion] = false;
    }
  }
  startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timerStatus = false;
      }
    },1000)
  }

  pauseTimer() {
      clearInterval(this.interval);
    }
  }
</code>```

And my template:

```<code><div class="">
  <label>Introduce el numero de preguntas</label>
  <input type="number" [ngModel]="numeroPreguntas" (ngModelChange)="changeNumber($event)" min="1" max="40">
</div>

<div class="">
  <button type="button" (click)="generateExam()">Generar examen</button>
</div>
<div class="sticky-top container bg-warning d-flex flex-row justify-content-around">
  <div class="botones">
    <button (click)='startTimer()' class="btn">Start Timer</button>
    <button (click)='pauseTimer()' class="btn">Pause</button>
  </div>
  <div class="timer">
    <p>{{timeLeft}} Seconds Left....</p>
  </div>
</div>

<div class="" *ngIf="status == true">
  <div class="jumbotron" *ngFor="let pregunta of preguntas; index as i">
    <h3>{{pregunta.title}}</h3>
    <p>{{pregunta.text}}</p>
    <form #responseForm="ngForm" (ngSubmit)="onSubmit(responseForm)">
      <select class="" ngModel name="respuesta" #respuesta="ngModel">
        <option value="true">True</option>
        <option value="false">False</option>
      </select>
      <label>No cambiar uwu</label>
      <input type="text" name="iteracion2" ngModel #iteracion2="ngModel" value="{{i}}">
      <p>
        <input type="submit" value="Corregir">
      </p>
    </form>
    <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
    <span *ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
  </div>
</div>
</code>```

Sorry for the mix of spanish and english at my code.

答:
Please use it like this</p>

```<code>  <span *ngIf="correccion[iteracion] === true">Correcto</span>
    <span *ngIf="correccion[iteracion] === false">Incorrecto</span>
</code>```

Body:
I am trying to make an exam type true or false simulator with angular 9, but when i try to correct each question i cant interpolate the index of the correction. I have this error:

ERROR in Template parse errors:
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

The issue is about the way of interpolate the index of the correccion array
Here is my ts code:

    import { Component, OnInit } from '@angular/core';
import { PreguntaService } from '../../services/pregunta.service';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-examen',
  templateUrl: './examen.component.html',
  styleUrls: ['./examen.component.css'],
  providers: [PreguntaService]
})
export class ExamenComponent implements OnInit {

  public numeroPreguntas: any;
  public preguntas: any;
  public status: boolean;
  public timeLeft: number;
  public interval;
  public subscribeTimer: any;
  public timerStatus: boolean;
  public correccion: any;
  public iteracion: number;
  public respuesta: boolean;

  constructor(private _preguntaService: PreguntaService) {
    this.numeroPreguntas = 10;
    this.status = false;
    this.timeLeft = this.numeroPreguntas * 40;
    this.correccion = new Array;
  }

  ngOnInit(): void {
    this.status = false;
    console.log(this.preguntas);

  }

  generateExam() {
    this.preguntas = new Array;
    for (let i = 0; i < this.numeroPreguntas; i++) {
    this._preguntaService.getRandomPregunta().subscribe(response=>{
        this.preguntas.push(response.pregunta);
      },
      error=>{
        console.log(<any>error);

      }
    );

    }

    console.log(this.preguntas);

    this.status = true;
  }
  changeNumber($event) {
    this.numeroPreguntas = $event;
    this.preguntas = new Array(this.numeroPreguntas);
    this.timeLeft = this.numeroPreguntas * 40;
  }

  changeRadio($event){
    this.respuesta = $event;
  }
  onSubmit(responseForm: NgForm) {
      this.respuesta=responseForm.controls['respuesta'].value;
      this.iteracion = responseForm.controls['iteracion2'].value;

    console.log('hola');
    console.log(this.iteracion);
    console.log(this.respuesta);

    if (this.preguntas[this.iteracion].response == this.respuesta ) {
      this.correccion = true;
    }else{
      this.correccion[this.iteracion] = false;
    }
  }
  startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timerStatus = false;
      }
    },1000)
  }

  pauseTimer() {
      clearInterval(this.interval);
    }
  }

And my template:

  Introduce el numero de preguntas
  <input type="number" [ngModel]="numeroPreguntas" (ngModelChange)="changeNumber($event)" min="1" max="40">

  <button type="button" (click)="generateExam()">Generar examen</button>

    <button (click)='startTimer()' class="btn">Start Timer</button>
    <button (click)='pauseTimer()' class="btn">Pause</button>

{{timeLeft}} Seconds Left....

{{pregunta.title}}

{{pregunta.text}}

    <form #responseForm="ngForm" (ngSubmit)="onSubmit(responseForm)">
      <select class="" ngModel name="respuesta" #respuesta="ngModel">
        <option value="true">True</option>
        <option value="false">False</option>
      </select>
      No cambiar uwu
      <input type="text" name="iteracion2" ngModel #iteracion2="ngModel" value="{{i}}">

        <input type="submit" value="Corregir">

    </form>
    Correcto
    Incorrecto

Sorry for the mix of spanish and english at my code.

Body:
Please use it like this

  <span *ngIf="correccion[iteracion] === true">Correcto</span>
    <span *ngIf="correccion[iteracion] === false">Incorrecto</span>


问:
Variadic generic function accepting generic types as input arguments
Suppose we have some concrete types A, B, C, etc. Also we have a wrapper type: Wrapper<T> where T could be any types e.g. A, B.

I need a variadic function that takes some Wrapper<T>s and returns the wrapped values as a tuple: [].

```<code>let wa: Wrapper<A>;
let wb: Wrapper<B>;
let wc: Wrapper<C>;
let result = myFunction(wa, wb, wc);
</code>```

In this example result should be of type [A, B, C]. I don't know how to write the type of myFunction. Can you help?

答:
If you have a rough idea of how many wrapped arguments you want to pass to your functions, the simples option is to use a set of overloads. Something like this

type Wrapper<T> = {
    type: T
}

type A = number
type B = boolean
type C = string

function f(w1: Wrapper, w2: Wrapper, w3: Wrapper<C>): [A, B, C]
function f(w1: Wrapper, w2: Wrapper): [A, B]
function f(w1: Wrapper): [A]
function f(...ws: Wrapper<any>[]): any[] {
    return ws.map(w => w.type)
}

declare const a: Wrapper
declare const b: Wrapper
declare const c: Wrapper<C>

const foo = f(a, b, c) // [A, B, C]
```

Body:
Suppose we have some concrete types A, B, C, etc. Also we have a wrapper type: Wrapper<T> where T could be any types e.g. A, B.

I need a variadic function that takes some Wrapper<T>s and returns the wrapped values as a tuple: [].

let wa: Wrapper;
let wb: Wrapper;
let wc: Wrapper<C>;
let result = myFunction(wa, wb, wc);

In this example result should be of type [A, B, C]. I don't know how to write the type of myFunction. Can you help?

Body:
If you have a rough idea of how many wrapped arguments you want to pass to your functions, the simples option is to use a set of overloads. Something like this

type Wrapper<T> = {
    type: T
}

type A = number
type B = boolean
type C = string

function f<A, B, C>(w1: Wrapper<A>, w2: Wrapper<B>, w3: Wrapper<C>): [A, B, C]
function f<A, B>(w1: Wrapper<A>, w2: Wrapper<B>): [A, B]
function f<A>(w1: Wrapper<A>): [A]
function f(...ws: Wrapper<any>[]): any[] {
    return ws.map(w => w.type)
}

declare const a: Wrapper<A>
declare const b: Wrapper<B>
declare const c: Wrapper<C>

const foo = f(a, b, c) // [A, B, C]


问:
React onMouseEnter is blocking onClick
I have a button that sends a prefetch request using graphQL Apollo Client when a user hovers it.

The issue is the onClick event is blocked for a few ms. Can someone please explain why seperate events are clashing like this. I can't think of any reason why my onclick event is not firing while the request is in flight as its asynchronous.

```<code><div
   role="button"
   key={shortId()}
   onMouseEnter={prefetch(value.value)}
   onClick={onToggle(id, value.value)}
   className="FilterGroup__item"
>
   {renderWidget({value, selected})}
    <span className="FilterGroup__item__count">{value.count}</span>
</div>
</code>```

The function returned by prefetch is:

```<code>    const [searchPrefetch] = useLazyQuery(searchQuery, {
        returnPartialData: true
    });

    const sendSearchPrefetch = (additionalParameters?: IAdditionalSearchParameters) => {
        searchPrefetch({
            variables: getRequestParameters(additionalParameters)
        });
    };

const handlePrefetch = useCallback(
        debounce(async (additionalFacets?: IAdditionalSearchParameters) => {
            sendSearchPrefetch(additionalFacets);
        }, SEARCH_DEBOUNCE_TIMER_MS),
        []
    );

  const prefetch = (filter: string) => (value: string) => () => {
        handlePrefetch({filters: {[filter]: value}});
    };
</code>```

答:
Your click is fired on load

Your click and prefetch functions are fired when the component is loaded. If these functions do not return functions to be fired on click and mouse enter you need to wrap them in another function.

```<code><div
   role="button"
   key={shortId()}
   onMouseEnter={() => prefetch(value.value)}
   onClick={() => onToggle(id, value.value)}
   className="FilterGroup__item"
>
   {renderWidget({value, selected})}
    <span className="FilterGroup__item__count">{value.count}</span>
</div>
</code>```

Title: React onMouseEnter is blocking onClick

Body:
I have a button that sends a prefetch request using graphQL Apollo Client when a user hovers it.

The issue is the onClick event is blocked for a few ms. Can someone please explain why seperate events are clashing like this. I can't think of any reason why my onclick event is not firing while the request is in flight as its asynchronous.

   {renderWidget({value, selected})}
    {value.count}

The function returned by prefetch is:

    const [searchPrefetch] = useLazyQuery(searchQuery, {
        returnPartialData: true
    });

    const sendSearchPrefetch = (additionalParameters?: IAdditionalSearchParameters) => {
        searchPrefetch({
            variables: getRequestParameters(additionalParameters)
        });
    };

const handlePrefetch = useCallback(
        debounce(async (additionalFacets?: IAdditionalSearchParameters) => {
            sendSearchPrefetch(additionalFacets);
        }, SEARCH_DEBOUNCE_TIMER_MS),
        []
    );

  const prefetch = (filter: string) => (value: string) => () => {
        handlePrefetch({filters: {[filter]: value}});
    };

Body:
Your click is fired on load

Your click and prefetch functions are fired when the component is loaded. If these functions do not return functions to be fired on click and mouse enter you need to wrap them in another function.

<div
   role="button"
   key={shortId()}
   onMouseEnter={() => prefetch(value.value)}
   onClick={() => onToggle(id, value.value)}
   className="FilterGroup__item"
>
   {renderWidget({value, selected})}
    <span className="FilterGroup__item__count">{value.count}</span>
</div>


问:
Is un-initialized integer always default to 0 in c?
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

```<code>#if 0
    ngx_last_process = 0;
#endif
</code>```

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

```<code>    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }
</code>```

Is it guranteed that un-initialized variable will have 0 value in c at all?

答: It depends on how the variable is allocated. Statically allocated variables are initialized to zero, whereas variables allocated on the stack or with malloc() are not.

Body:
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

#if 0
    ngx_last_process = 0;
#endif

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }

Is it guranteed that un-initialized variable will have 0 value in c at all?


问:
Why my multiprocess queue might be "losing" items?
I've got some code where I want to share objects between processes using queues. I've got a parent:

```<code>processing_manager = mp.Manager()
to_cacher = processing_manager.Queue()
fetchers = get_fetchers()
fetcher_process = mp.Process(target=fetch_news, args=(to_cacher, fetchers))
fetcher_process.start()
while 1:
    print(to_cacher.get())
</code>```

And a child:

```<code>def fetch_news(pass_to: Queue, fetchers: List[Fetcher]):
    def put_news_to_query(pass_to: Queue, fetchers: List[Fetcher]):
        for fet in fetchers:
            for news in fet.latest_news():
                print(news)
                pass_to.put(news)
        print("----------------")

    put_news_to_query(pass_to, fetchers)
</code>```

I'm expecting to see N objects printed in put_news_to_query, then a line, and then the same objects printed in while loop in a parent. Problem is, objects appear to miss: if I get, say, 8 objects printed in put_news_to_query I get only 2-3 objects printed in while loop. What am I doing wrong here?

答:
So, apparently, it was something related to in which order put and get statements were executed. Basically, some of the objects from parent's print were printed before the line. If you struggle with something like this, I'd recommend adding something to distinguish prints, like this:</p>

```<code>print(f"Worker: {news}")
print(f"Main: {to_cacher.get()}")
</code>```

Body:
I've got some code where I want to share objects between processes using queues. I've got a parent:

processing_manager = mp.Manager()
to_cacher = processing_manager.Queue()
fetchers = get_fetchers()
fetcher_process = mp.Process(target=fetch_news, args=(to_cacher, fetchers))
fetcher_process.start()
while 1:
    print(to_cacher.get())

And a child:

def fetch_news(pass_to: Queue, fetchers: List[Fetcher]):
    def put_news_to_query(pass_to: Queue, fetchers: List[Fetcher]):
        for fet in fetchers:
            for news in fet.latest_news():
                print(news)
                pass_to.put(news)
        print("----------------")

    put_news_to_query(pass_to, fetchers)

I'm expecting to see N objects printed in put_news_to_query, then a line, and then the same objects printed in while loop in a parent. Problem is, objects appear to miss: if I get, say, 8 objects printed in put_news_to_query I get only 2-3 objects printed in while loop. What am I doing wrong here?

Body:
So, apparently, it was something related to in which order put and get statements were executed. Basically, some of the objects from parent's print were printed before the line. If you struggle with something like this, I'd recommend adding something to distinguish prints, like this:

print(f"Worker: {news}")
print(f"Main: {to_cacher.get()}")


问:
How can I add additional PHP versions to MAMP
The current version of MAMP that I have only has php 5.2.17 and 5.4.4. I need 5.3.X. Is there a way to add additional versions that can be selected in the MAMP interfaces php preferences? This is for the free version of MAMP, not MAMP PRO.

Thanks

答:
The easiest solution I found is to just rename the php folder version as such:

Shut down the servers

Rename the folder containing the php version that you don't need in /Applications/MAMP/bin/php. php7.3.9 --> _php7.3.9

That way only two of them will be read by MAMP. Done!


问:
/usr/bin/time: No such file or directory
I'm trying to run the time command for a file on a virtual machine running Fedora 19 64-bit and I get the message "/usr/bin/time: No such file or directory". I tried googling, but it appears it's something that I should already have. How do I get this on my computer?</p>

答:
bash/zsh/modern shells usually implement a basic time command as a builtin. So it won't exist on the filesystem, but time mycommand should work.

If you want the "proper" time command (with more options eg: -l/-v), then you'll need to install it via apt/yum/etc. You'll need to run it as /usr/bin/time mycommand so the shell-builtin doesn't get invoked.


问:
link ocilib using mingw g++ on windows
i'm trying to use ocilib.h that i downloaded from the internet. It work just find went i using visual studio 2017. But because of my machine i have to use mingw.

Windows 10   - OS
VSCode       - Text Editor
Mingw        - Compiler
Language     - C/C++
External Lib - ocilib

I use to the g++ -g *.cpp -o main.exe only, never tried the complex command to link library

my current directory is : C:\Users----\Desktop\Testing

the code that i copy from the developer

the header location is :  C:\ocilib\include (for all the *.h and *.cpp)
what inside this directory

the link location is :  C:\ocilib\lib32 (for all the *.dll and *.lib)
what inside this last dir

i have try the -l -L -I command but bunch of error still come out

Please help me...Thank you in advance

答: You could try the ocilib driver from http://vrogier.github.io/ocilib/ and build it with gcc. I had no issues building it under MSYS2 with MinGW-w64 from http://winlibs.com/</p>

Title: link ocilib using mingw g++ on windows


问:
Serverless - Referencing api gateway address in CloudFront origin definition
Using Serverless Framework,
i am creating an api gateway in my template :

```<code>functions
   test:
     handler: test.handler
     events:
      - http:
        path: save-subscription
        method: post
        cors: false
</code>```

later on i want to use this api address xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/
as a domain name of an oigin of my cloudfront origins

```<code>DomainName: xxxxxxx.execute-api.us-east-1.amazonaws.com
OriginPath: dev
</code>```

Is there a way to reference the api address dynamically/programmatically before it even exist, and do I need to use depends on?

Thanks

答:
```<code>  -   DomainName:
         Fn::Join:
          - ""
          -   -   "Ref": "ApiGatewayRestApi"
              - ".execute-api.${self:custom.region}.amazonaws.com"
</code>```

worked for me.
Found the answer here : https://www.richdevelops.dev/blog/how-do-i-get-my-api-gateway-url

Body:
Using Serverless Framework,
i am creating an api gateway in my template :

functions
   test:
     handler: test.handler
     events:
      - http:
        path: save-subscription
        method: post
        cors: false

later on i want to use this api address xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/
as a domain name of an oigin of my cloudfront origins

DomainName: xxxxxxx.execute-api.us-east-1.amazonaws.com
OriginPath: dev

Is there a way to reference the api address dynamically/programmatically before it even exist, and do I need to use depends on?

Thanks

Body:
  -   DomainName:
         Fn::Join:
          - ""
          -   -   "Ref": "ApiGatewayRestApi"
              - ".execute-api.${self:custom.region}.amazonaws.com"

worked for me.
Found the answer here : https://www.richdevelops.dev/blog/how-do-i-get-my-api-gateway-url


问:
SQL Efficiency - Query using dateAdd Function twice; or SubQuery and DateAdd Function once; on Date BETWEEN
The expense is using the DateAdd function not only in the SELECT, but also in the WHERE;
Or using the Sub Query which initially returns more data than I need, but then can be filtered without using the DateAdd function again on the database.

Execution Plan seems to imply that they are identical as far as it is concerned.
I'm wondering which would be more efficient?

```<code>    DECLARE @DateFrom DateTime
    SET @DateFrom = '2011-05-27'
    DECLARE @DateTo DateTime
    SET @DateTo = '2011-06-27'

    SELECT id, name,
    dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
    FROM tablename
    WHERE dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM'))
            BETWEEN @DateFrom AND @DateTo

    ORDER BY itsm_requiredbyx desc

    ---------------------------------------------------------------------------------------------

    SELECT *
    FROM
        (
        select id, name,
        dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
                dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
        from tablename
        ) RR
    WHERE itsm_requiredbyx BETWEEN @DateFrom AND @DateTo
    ORDER BY itsm_requiredbyx desc
</code>```

答:
This article might help you choose. If your date columns are indexed, there might be a big difference between the methods used, particularly in the WHERE clause.

As it says,

If you are searching large tables with lots of records, you will most likely index some of the date columns that are commonly used to constrain queries. When a date column is used in a WHERE clause, the query optimizer will not use an index if the date column is wrapped in a function.

This is also explained in Ten Common SQL Programming Mistakes, particularly under #2 Functions on indexed columns in predicates:

The problem arises from the fact that
  the index columns are being passed to
  a function, which the query engine
  must then evaluate for every single
  row in the table. In cases such as
  these, the WHERE clause predicate is
  deemed "non-SARGable" and the best
  that the query optimizer can do is
  perform a full index or table scan.

To make sure the indexes get used, we
  need to avoid the use of functions on
  the indexed columns.

Body:
The expense is using the DateAdd function not only in the SELECT, but also in the WHERE;
Or using the Sub Query which initially returns more data than I need, but then can be filtered without using the DateAdd function again on the database.

Execution Plan seems to imply that they are identical as far as it is concerned.
I'm wondering which would be more efficient?

    DECLARE @DateFrom DateTime
    SET @DateFrom = '2011-05-27'
    DECLARE @DateTo DateTime
    SET @DateTo = '2011-06-27'

    SELECT id, name,
    dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
    FROM tablename
    WHERE dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
            dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM'))
            BETWEEN @DateFrom AND @DateTo

    ORDER BY itsm_requiredbyx desc

    ---------------------------------------------------------------------------------------------

    SELECT *
    FROM
        (
        select id, name,
        dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
                dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
        from tablename
        ) RR
    WHERE itsm_requiredbyx BETWEEN @DateFrom AND @DateTo
    ORDER BY itsm_requiredbyx desc


问:
What is the exact use of Run continuous integration triggers for committed changes and other features in TFS 2017 Gated Build?
I am bit confused with the options that are provided in the TFS 2017 Build under the Triggers section. I have a two separate build definitions one is used for code check-in i.e. called Gated Build and other is Manual build which we used for code drop\deployment on our CI servers after the Gated build is completed.

Recently, we thought of using the Gated build definitions directly for code drop which will save time in triggering the manual builds separately. However, while doing this POC I am confused with use of different features that are available in the Triggers section, especially the Run continuous integration triggers for committed changes

I have linked Gated Build with the Release Definition directly which deploys the code once the gated build is completed. I have selected both the options in the build i.e.  Use workspace mapping for filters and the Run continuous integration triggers for committed changes.
With this whenever I check-in the code the build once completed triggers the Release definition and deploys the code on the server but when I deselect the Run continuous integration triggers for committed changes and check-in an code it still deploys the code just because it is linked with the Release definition.

I searched on google and tried to understand the use of it and other feature but didn't understood much, I went through the link as well just got to know it won't display the NO CI in the change-set.

Can anyone please explain the exact use of each features\option present under the triggers except the Scheduled one or please let me know if there are any other links, blogs, video's tutorial any one aware of where all the features present under trigger options are explained in depth with examples?

Enabled the Continuous integration option in CI build due to which it gets automatically triggered after the gated build is completed.

答:
Just as literal meaning, it is used for Continuous integration.

For normal CI build, it will build whenever someone checks in code,
it happens after the changes have been checked in to TFS.

If you select Gated check-in, it will accept check-ins only if the
submitted changes merge and build successfully, which means only the
build succeeded the changes can be checked in.

By default, CI builds are not run after the gated check-in process is complete and the changes are checked in. However, if you do want CI builds to run after a gated check-in, select the Run continuous integration triggers for committed changes check box.

More detailed information about all triggers you can refer to our official link below:

https://learn.microsoft.com/en-us/azure/devops/pipelines/build/triggers?view=azure-devops

To conclude, uncheck that option to prevent triggering the continuous integration build.

As for why check-in an code it still deploys the code just because it is linked with the Release definition. This trigger only control your build definition/pipeline, not affect release pipeline.

There is also corresponding Release Trigger. You should double check it in your environment.

For a sample about the usage of Gated Build in Azure DevOps, you could refer this blog-- Gated Check-ins in Visual Studio Team Services using TFSVC and Git


问:
How can I unit test a form containing ng-select?
I have created an Angular form component that uses <ng-select> as a replacement for HTML <select> elements.  Now I want to unit test my component.  To test the component logic I have methods that find HTML elements in the DOM and examine or modify their value.  This works fine with native HTML elements.  But <ng-select> is difficult.

I can find the current value with something like this, but it feels like a very brittle solution.

```<code>document.querySelector("ng-select[formControlName=country] .ng-value .ng-value-label").innerText
</code>```

And how do I change the selection?  With a standard input component you can set the value, then fire an input event. There's an <input type="text" role="combobox"> inside <ng-select/>, but changing its value doesn't seem to affect the FormControl value.

I'm not trying to test ng-select, but I do need to verify that my component reacts appropriately to selection changes.  It will also be necessary to make selections in the UI when running automated integration tests.

答:
You can use a Harness (MatselectHarness) to interact with an Angular Material component. This will make the tests more robust:

```<code> it('should have 20 countries in the select box', async () => {
    ...
    const select = await loader.getHarness(MatSelectHarness.with(MatSelectHarness);
    //Click the select element host
    (await selectHarness.host()).click();
    const actual = (await selectHarness.getOptions()).length;
    expect(actual).toBe(20);
  });
</code>```

Select a value (example code from angular doc):

```<code>it('should switch to bug report template', async () => {
    expect(fixture.debugElement.query('bug-report-form')).toBeNull();
    const select = await loader.getHarness(MatSelect);
    await select.open();
    const bugOption = await select.getOption({text: 'Bug'});
    await bugOption.click();
    expect(fixture.debugElement.query('bug-report-form')).not.toBeNull();
  });
</code>```

See: using-component-harnesses

An other way is to move the logic into a service. A service can be unit tested easily.

Body:
I have created an Angular form component that uses <ng-select> as a replacement for HTML <select> elements.  Now I want to unit test my component.  To test the component logic I have methods that find HTML elements in the DOM and examine or modify their value.  This works fine with native HTML elements.  But <ng-select> is difficult.

I can find the current value with something like this, but it feels like a very brittle solution.

document.querySelector("ng-select[formControlName=country] .ng-value .ng-value-label").innerText

And how do I change the selection?  With a standard input component you can set the value, then fire an input event. There's an <input type="text" role="combobox"> inside <ng-select/>, but changing its value doesn't seem to affect the FormControl value.

I'm not trying to test ng-select, but I do need to verify that my component reacts appropriately to selection changes.  It will also be necessary to make selections in the UI when running automated integration tests.

Body:
You can use a Harness (MatselectHarness) to interact with an Angular Material component. This will make the tests more robust:

 it('should have 20 countries in the select box', async () => {
    ...
    const select = await loader.getHarness(MatSelectHarness.with(MatSelectHarness);
    //Click the select element host
    (await selectHarness.host()).click();
    const actual = (await selectHarness.getOptions()).length;
    expect(actual).toBe(20);
  });

Select a value (example code from angular doc):

it('should switch to bug report template', async () => {
    expect(fixture.debugElement.query('bug-report-form')).toBeNull();
    const select = await loader.getHarness(MatSelect);
    await select.open();
    const bugOption = await select.getOption({text: 'Bug'});
    await bugOption.click();
    expect(fixture.debugElement.query('bug-report-form')).not.toBeNull();
  });

See: using-component-harnesses

An other way is to move the logic into a service. A service can be unit tested easily.


问:
Laravel Pivot Table Insert Array
I am not sure on the relationship for the tasks_assigned_too_groups table,
my database is like the following:

```<code>tasks
id | task_name | task_description

groups
id | group_name | user_id

tasks_assigned_too_groups
id | tasks_id | group_name
</code>```

in the form you create a task and specify it to groups, then I want to to create like the following:

```<code> public function store() {

        $data = request()->validate([
           'task_title' => '',
           'task_description' => '',
           'start_date' => '',
            'due_date' => '',
            'group_name' => '',
        ]);

// insert in to tasks database table...
        $task = request()->user()->tasks()->create([
            'task_title' => $data['task_title'],
            'task_description' => $data['task_description'],
            'start_date' => $data['start_date'],
            'due_date' => $data['due_date'],
        ]);

// insert into tasks_assigned_too_groups database table...
        $task->setforgroups()->attach($data['group_name']);

        return new TasksResource($task);
    }
</code>```

$data['group_name'] is an array like following:

```<code>[
  {
    "group_name": "9x/En3"
  },
  {
    "group_name": "10x/En3"
  }
]
</code>```

How do I insert the task_id and group_name its been assigned too into  tasks_assigned_too_groups table?

答:
Try to change this

```<code> tasks
 id | task_name | task_description

 groups
 id | group_name | user_id

 tasks_assigned_too_groups
 id | tasks_id | group_name
</code>```

to this:

```<code> tasks
 id | task_name | task_description

 groups
 id | group_name | user_id

 tasks_assigned_too_groups
 id | tasks_id | group_id
</code>```

Because this is ManyToMany Relationship and the intermediary(pivot) table needs to have a foreign key of both connected tables.

Task model

```<code>public function groups()
{
    return $this->belongsToMany('App\Group');
}
</code>```

Group model

```<code>public function tasks()
{
    return $this->belongsToMany('App\Task');
}
</code>```

Here is the documentation for more info.
laravel.com

Title: Laravel Pivot Table Insert Array

Body:
I am not sure on the relationship for the tasks_assigned_too_groups table,
my database is like the following:

tasks
id | task_name | task_description

groups
id | group_name | user_id

tasks_assigned_too_groups
id | tasks_id | group_name

in the form you create a task and specify it to groups, then I want to to create like the following:

 public function store() {

        $data = request()->validate([
           'task_title' => '',
           'task_description' => '',
           'start_date' => '',
            'due_date' => '',
            'group_name' => '',
        ]);

// insert in to tasks database table...
        $task = request()->user()->tasks()->create([
            'task_title' => $data['task_title'],
            'task_description' => $data['task_description'],
            'start_date' => $data['start_date'],
            'due_date' => $data['due_date'],
        ]);

// insert into tasks_assigned_too_groups database table...
        $task->setforgroups()->attach($data['group_name']);

        return new TasksResource($task);
    }

$data['group_name'] is an array like following:

[
  {
    "group_name": "9x/En3"
  },
  {
    "group_name": "10x/En3"
  }
]

How do I insert the task_id and group_name its been assigned too into  tasks_assigned_too_groups table?

Body:
Try to change this

 tasks
 id | task_name | task_description

 groups
 id | group_name | user_id

 tasks_assigned_too_groups
 id | tasks_id | group_name

to this:

 tasks
 id | task_name | task_description

 groups
 id | group_name | user_id

 tasks_assigned_too_groups
 id | tasks_id | group_id

Because this is ManyToMany Relationship and the intermediary(pivot) table needs to have a foreign key of both connected tables.

Task model

public function groups()
{
    return $this->belongsToMany('App\Group');
}

Group model

public function tasks()
{
    return $this->belongsToMany('App\Task');
}

Here is the documentation for more info.
laravel.com


问:
How do I get All actors that haven't appeared in R rated films

I want to get All actors  that haven't appeared in R rated films

It was easy to do with sub-queries

```<code>select *
from actor
where actor_id not in
  (select actor_id
   from actor
     inner join film_actor using (actor_id)
     inner join film using (film_id)
   where rating = 'R');
</code>```

I am unable to do it with joins -

I have done this till now -

```<code>select distinct(a.actor_id), a.first_name, a.last_name
from actor as a
  left join
    (film_actor as fa
       inner join film as f
         on fa.film_id = f.film_id)
  on a.actor_id = fa.actor_id
  where f.rating = 'R'
  order by actor_id
</code>```

In the above query I get all the actors who have worked in R rated films, but now I am not sure how to get the non R rated films

Can someone help me do this with joins?

答:
WHERE clauses are applied after joins.

The implact here is that your LEFT JOIN has effectively been turned back in to an INNER JOIN:

- The LEFT JOIN returns some records with NULLs

- The WHERE clause excludes the NULLs

Instead, you must filter to the R rated films before the JOIN on to the actors table.

```<code>select distinct(a.actor_id), a.first_name, a.last_name
from actor as a
  left join
    (film_actor as fa
       inner join film as f
         on fa.film_id = f.film_id
         and f.rating = 'R')         -- R Rating filter here
  on a.actor_id = fa.actor_id
  where f.film_id IS NULL            -- where the actor does NOT map to such films
  order by actor_id
</code>```

The DISTINCT shouldn't be required either, the join is 1 actor to 0 films, so no duplication.

Also, I find your style very hard to read.  Try spacing things out a bit more, and making the level of indentation wore consistent?

```<code>SELECT
    a.actor_id,
    a.first_name,
    a.last_name
FROM
  actor   AS a
LEFT JOIN
(
        film_actor   AS fa
    INNER JOIN
        film         AS f
            ON  fa.film_id = f.film_id
            AND f.rating   = 'R'
)
    ON  a.actor_id = fa.actor_id
WHERE
    f.film_id IS NULL
ORDER BY
    a.actor_id
</code>```

Finally, NOT EXISTS is often much faster than NOT IN for these cases (anti-semi-joins).

```<code>SELECT
    *
FROM
    actor
WHERE
    NOT EXISTS
    (
        SELECT
            *
        FROM
            film_actor
        INNER JOIN
            film
                USING (film_id)
        WHERE
                film.rating         = 'R'
            AND film_actor.actor_id = actor.id
    )
</code>```

Body:
I want to get All actors  that haven't appeared in R rated films

It was easy to do with sub-queries

select *
from actor
where actor_id not in
  (select actor_id
   from actor
     inner join film_actor using (actor_id)
     inner join film using (film_id)
   where rating = 'R');

I am unable to do it with joins -

I have done this till now -

select distinct(a.actor_id), a.first_name, a.last_name
from actor as a
  left join
    (film_actor as fa
       inner join film as f
         on fa.film_id = f.film_id)
  on a.actor_id = fa.actor_id
  where f.rating = 'R'
  order by actor_id

In the above query I get all the actors who have worked in R rated films, but now I am not sure how to get the non R rated films

Can someone help me do this with joins?

Body:
WHERE clauses are applied after joins.

The implact here is that your LEFT JOIN has effectively been turned back in to an INNER JOIN:

- The LEFT JOIN returns some records with NULLs

- The WHERE clause excludes the NULLs

Instead, you must filter to the R rated films before the JOIN on to the actors table.

select distinct(a.actor_id), a.first_name, a.last_name
from actor as a
  left join
    (film_actor as fa
       inner join film as f
         on fa.film_id = f.film_id
         and f.rating = 'R')         -- R Rating filter here
  on a.actor_id = fa.actor_id
  where f.film_id IS NULL            -- where the actor does NOT map to such films
  order by actor_id

The DISTINCT shouldn't be required either, the join is 1 actor to 0 films, so no duplication.

Also, I find your style very hard to read.  Try spacing things out a bit more, and making the level of indentation wore consistent?

SELECT
    a.actor_id,
    a.first_name,
    a.last_name
FROM
  actor   AS a
LEFT JOIN
(
        film_actor   AS fa
    INNER JOIN
        film         AS f
            ON  fa.film_id = f.film_id
            AND f.rating   = 'R'
)
    ON  a.actor_id = fa.actor_id
WHERE
    f.film_id IS NULL
ORDER BY
    a.actor_id

Finally, NOT EXISTS is often much faster than NOT IN for these cases (anti-semi-joins).

SELECT
    *
FROM
    actor
WHERE
    NOT EXISTS
    (
        SELECT
            *
        FROM
            film_actor
        INNER JOIN
            film
                USING (film_id)
        WHERE
                film.rating         = 'R'
            AND film_actor.actor_id = actor.id
    )