问:
Convert opacity with var scss sass
I have some property like this

::root {
  --light-grey: #EFEFEF;
}

.content-wrapper {
  background-color: rgba(#EFEFEF, .4);
  border-radius: 8px;
  padding: 25px 33px;
}
```
<p>But when I try</p>
<pre class="lang-css prettyprint-override"><code>.content-wrapper {
  background-color: rgba(var(--light-grey), .4);
  border-radius: 8px;
  padding: 25px 33px;
}
</code>```

This does not works, grey background color is not shown?

答:
Unfortunately, you can't use HEX variables with alpha. But you can convert HEX color into RGB-version of this color and use it like CSS variable with alpha transparency you want.

--color-primary: #ff6347;
--color-primary-rgb: 255, 99, 71;
...
```
<p>This code won't work:</p>
<pre class="lang-css prettyprint-override"><code>color: rgba(var(--color-primary), .5);
</code>```

but this will:

color: rgba(var(--color-primary-rgb), .5);
```
<p>So, let say we have SCSS map of colors, we can generate CSS variables for HEX and RGB, generate classes with backgrounds:</p>
<pre class="lang-scss prettyprint-override"><code>$colors: (
  "primary": #ff6347,
  "secondary": #962ba2
);

// generating root variables
:root {
  @each $color, $value in $colors {
    --color-#{$color}: #{$value};
    --color-#{$color}-rgb: #{red($value)}, #{green($value)}, #{blue($value)};
  }
}

// generate backgrounds HEX, RGB variants
@mixin background {
  @each $color, $value in $colors {
    &-#{$color} {
      background: var(--color-#{$color});
    }

    &-#{$color}-rgb {
      --opacity: .5;
      background: rgba(var(--color-#{$color}-rgb), var(--opacity));
    }
  }
}

.bg {
  @include background;
}
</code>```

Output of this SCSS code will be:

:root {
  --color-primary: #ff6347;
  --color-primary-rgb: 255, 99, 71;
  --color-secondary: #962ba2;
  --color-secondary-rgb: 150, 43, 162;
}

.bg-primary {
  background: var(--color-primary);
}
.bg-primary-rgb {
  --opacity: .5;
  background: rgba(var(--color-primary-rgb), var(--opacity));
}
.bg-secondary {
  background: var(--color-secondary);
}
.bg-secondary-rgb {
  --opacity: .5;
  background: rgba(var(--color-secondary-rgb), var(--opacity));
}
```
<p>Here is Code Snippet demo, and link to CodePen with this code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --color-primary: #ff6347;
  --color-primary-rgb: 255, 99, 71;
  --color-secondary: #962ba2;
  --color-secondary-rgb: 150, 43, 162;
}

.bg-primary {
  background: var(--color-primary);
}

.bg-primary-rgb {
  --opacity: .5;
  background: rgba(var(--color-primary-rgb), var(--opacity));
}

.bg-secondary {
  background: var(--color-secondary);
}

.bg-secondary-rgb {
  --opacity: .5;
  background: rgba(var(--color-secondary-rgb), var(--opacity));
}

body {
  background: #1d1e22;
}

.row {
  display: flex;
  column-gap: 0.25rem;
  margin-bottom: 1rem;
}

.sq {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-weight: bold;
  width: 10rem;
  aspect-ratio: 1/1;
}</code>```

    primary

    primary
 opacity 0.5

    primary
 opacity 0.3

    secondary

    secondary
 opacity 0.5

    secondary
 opacity 0.7

```

Title: Convert opacity with var scss sass

Body:
I have some property like this

::root {
  --light-grey: #EFEFEF;
}

.content-wrapper {
  background-color: rgba(#EFEFEF, .4);
  border-radius: 8px;
  padding: 25px 33px;
}

But when I try

.content-wrapper {
  background-color: rgba(var(--light-grey), .4);
  border-radius: 8px;
  padding: 25px 33px;
}

This does not works, grey background color is not shown?

Body:
Unfortunately, you can't use HEX variables with alpha. But you can convert HEX color into RGB-version of this color and use it like CSS variable with alpha transparency you want.

--color-primary: #ff6347;
--color-primary-rgb: 255, 99, 71;
...

This code won't work:

color: rgba(var(--color-primary), .5);

but this will:

color: rgba(var(--color-primary-rgb), .5);

So, let say we have SCSS map of colors, we can generate CSS variables for HEX and RGB, generate classes with backgrounds:

$colors: (
  "primary": #ff6347,
  "secondary": #962ba2
);

// generating root variables
:root {
  @each $color, $value in $colors {
    --color-#{$color}: #{$value};
    --color-#{$color}-rgb: #{red($value)}, #{green($value)}, #{blue($value)};
  }
}

// generate backgrounds HEX, RGB variants
@mixin background {
  @each $color, $value in $colors {
    &-#{$color} {
      background: var(--color-#{$color});
    }

    &-#{$color}-rgb {
      --opacity: .5;
      background: rgba(var(--color-#{$color}-rgb), var(--opacity));
    }
  }
}

.bg {
  @include background;
}

Output of this SCSS code will be:

:root {
  --color-primary: #ff6347;
  --color-primary-rgb: 255, 99, 71;
  --color-secondary: #962ba2;
  --color-secondary-rgb: 150, 43, 162;
}

.bg-primary {
  background: var(--color-primary);
}
.bg-primary-rgb {
  --opacity: .5;
  background: rgba(var(--color-primary-rgb), var(--opacity));
}
.bg-secondary {
  background: var(--color-secondary);
}
.bg-secondary-rgb {
  --opacity: .5;
  background: rgba(var(--color-secondary-rgb), var(--opacity));
}

Here is Code Snippet demo, and link to CodePen with this code:

:root {
  --color-primary: #ff6347;
  --color-primary-rgb: 255, 99, 71;
  --color-secondary: #962ba2;
  --color-secondary-rgb: 150, 43, 162;
}

.bg-primary {
  background: var(--color-primary);
}

.bg-primary-rgb {
  --opacity: .5;
  background: rgba(var(--color-primary-rgb), var(--opacity));
}

.bg-secondary {
  background: var(--color-secondary);
}

.bg-secondary-rgb {
  --opacity: .5;
  background: rgba(var(--color-secondary-rgb), var(--opacity));
}

body {
  background: #1d1e22;
}

.row {
  display: flex;
  column-gap: 0.25rem;
  margin-bottom: 1rem;
}

.sq {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-weight: bold;
  width: 10rem;
  aspect-ratio: 1/1;
}

<div class="row">
  <div class="sq bg-primary">
    primary
  </div>
  <div class="sq bg-primary-rgb">
    primary <br /> opacity 0.5
  </div>

  <div class="sq bg-primary-rgb" style="--opacity: .3">
    primary <br /> opacity 0.3
  </div>
</div>

<div class="row">
  <div class="sq bg-secondary">
    secondary
  </div>
  <div class="sq bg-secondary-rgb">
    secondary <br /> opacity 0.5
  </div>

  <div class="sq bg-secondary-rgb" style="--opacity: .7">
    secondary <br /> opacity 0.7
  </div>
</div>


来源: stackexchange

问:
Read an excel file using Apache Camel
I am trying to read an Excel file using Apache Camel. For that I have found that we can use the CSV component:

```<code>https://camel.apache.org/components/3.14.x/dataformats/csv-dataformat.html
</code>```

For that I have created a simple route which reads a XLSX file from a folder. Then I am trying to print the content of of that Excel file and write to another folder, but the contents of the file are not getting printed. The route is as below:

```<code>import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.csv.CsvDataFormat;
import org.apache.commons.csv.CSVFormat;
import org.springframework.stereotype.Component;

@Component
public class MyRoute extends RouteBuilder {

    public void configure() {

        CsvDataFormat csv = new CsvDataFormat();
        csv.setFormat(CSVFormat.EXCEL);

        from("file://C://work//ei01//source")
            .unmarshal(csv)
            .log("Reached ${body}")
            .marshal(csv)
            .to("file://C://work//ei01//destination?fileName=test.xlsx");
    }
}
</code>```

The pom.xml is as below:

```<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sprng-boot-camel-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprng-boot-camel-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-spring-boot-starter</artifactId>
            <version>3.14.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-csv-starter</artifactId>
            <version>3.14.1</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Can you please suggest me what I am doing wrong here?

答:
I suppose you try to read a real Excel file (.xlsx). That does not work with the CSV data format.

The CSVFormat.EXCEL format is to read CSV files (.csv) exported from Excel. Because the CSV format is done quite different from product to product, Camel supports multiple "well-known" CSV formats. One of them is CSVFormat.EXCEL.

To read the native Excel format (I think it is a ZIP file that contains XML files), you need a library like Apache POI.

ContentLicense: CC BY-SA 4.0

Title: Read an excel file using Apache Camel

Body:
I am trying to read an Excel file using Apache Camel. For that I have found that we can use the CSV component:

https://camel.apache.org/components/3.14.x/dataformats/csv-dataformat.html

For that I have created a simple route which reads a XLSX file from a folder. Then I am trying to print the content of of that Excel file and write to another folder, but the contents of the file are not getting printed. The route is as below:

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.csv.CsvDataFormat;
import org.apache.commons.csv.CSVFormat;
import org.springframework.stereotype.Component;

@Component
public class MyRoute extends RouteBuilder {

    public void configure() {

        CsvDataFormat csv = new CsvDataFormat();
        csv.setFormat(CSVFormat.EXCEL);

        from("file://C://work//ei01//source")
            .unmarshal(csv)
            .log("Reached ${body}")
            .marshal(csv)
            .to("file://C://work//ei01//destination?fileName=test.xlsx");
    }
}

The pom.xml is as below:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sprng-boot-camel-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprng-boot-camel-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-spring-boot-starter</artifactId>
            <version>3.14.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-csv-starter</artifactId>
            <version>3.14.1</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Can you please suggest me what I am doing wrong here?


问:
How do I get the key from Map in a List and do a get rest request in Java
I want to do a get request and want to get all the jobs who have the "teacher" in it. In this case the map value 2 and 3.

How do I get there if I execute the code below then I only get the value from the Map 2. The best way is over a List? But how do I do it?

I have this method.

```<code>@GET
@Path("jobs")
public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
            System.out.println("I DID IT");
            System.out.println(entry.getKey());
            return berufe.get(entry.getKey());
        }

    }
    return berufe.get(id);
}
</code>```

and this Map:

```<code>jobs.put(1, new jobs(1, 1337, "student"));
jobs.put(2, new jobs(2, 420, "teacher"));
jobs.put(3, new jobs(3, 69, "schoolteacher"));
</code>```

---------------------------------EDIT----------------------------------

If I do this:

```<code>@GET
@Path("jobs")
public Collection<Job> getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    final Set<Beruf> result = new HashSet<>();

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()) == true) {

            result.add(jobs.get(entry.getKey()));
        } else {
          return jobs.values();
        }

    }
    return result;
}
</code>```

I get with a discription all Map values back and without I get an Error.

What do I do wrong here?

答:
First of all, you should do is design the API correctly, for example:

```<code>@GET
@Path("jobs")
public List<Integer> searchJobsIdByDescription(@QueryParam("description") String description) {
    ...
}
</code>```

Important: you must give a suitable name to the method (f.e: searchJobsIdByDescription), your method should only do one thing, so you declare only the parameters needed to do that thing (f.e: (@QueryParam("description") String description)) and return the expected type (List<Integer>).

Pay attention to the annotation @Path("jobs"), you have to avoid matching the previous ones

Next, you should carefully read @frIV's answer

Body:
I want to do a get request and want to get all the jobs who have the "teacher" in it. In this case the map value 2 and 3.

How do I get there if I execute the code below then I only get the value from the Map 2. The best way is over a List? But how do I do it?

I have this method.

@GET
@Path("jobs")
public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
            System.out.println("I DID IT");
            System.out.println(entry.getKey());
            return berufe.get(entry.getKey());
        }

    }
    return berufe.get(id);
}

and this Map:

jobs.put(1, new jobs(1, 1337, "student"));
jobs.put(2, new jobs(2, 420, "teacher"));
jobs.put(3, new jobs(3, 69, "schoolteacher"));

---------------------------------EDIT----------------------------------

If I do this:

@GET
@Path("jobs")
public Collection<Job> getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    final Set<Beruf> result = new HashSet<>();

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()) == true) {

            result.add(jobs.get(entry.getKey()));
        } else {
          return jobs.values();
        }

    }
    return result;
}

I get with a discription all Map values back and without I get an Error.

What do I do wrong here?

Body:
First of all, you should do is design the API correctly, for example:

@GET
@Path("jobs")
public List<Integer> searchJobsIdByDescription(@QueryParam("description") String description) {
    ...
}

Important: you must give a suitable name to the method (f.e: searchJobsIdByDescription), your method should only do one thing, so you declare only the parameters needed to do that thing (f.e: (@QueryParam("description") String description)) and return the expected type (List<Integer>).

Pay attention to the annotation @Path("jobs"), you have to avoid matching the previous ones

Next, you should carefully read @frIV's answer


问:
java.lang.UnsatisfiedLinkError: No implementation found for void org.libsdl.app.SDLActivity.nativeSetenv
I'm trying to run an APK that I generated using buildozer. After trying to run on several devices both physical and virtual, I always get the same error:

```<code>2022-02-08 18:05:17.702 10070-10070/org.test.butterfly E/AndroidRuntime: FATAL EXCEPTION: main
        Process: org.test.butterfly, PID: 10070
        java.lang.UnsatisfiedLinkError: No implementation found for void org.libsdl.app.SDLActivity.nativeSetenv(java.lang.String, java.lang.String) (tried Java_org_libsdl_app_SDLActivity_nativeSetenv and Java_org_libsdl_app_SDLActivity_nativeSetenv__Ljava_lang_String_2Ljava_lang_String_2)
            at org.libsdl.app.SDLActivity.nativeSetenv(Native Method)
            at org.kivy.android.PythonActivity$UnpackFilesTask.onPostExecute(PythonActivity.java:157)
            at org.kivy.android.PythonActivity$UnpackFilesTask.onPostExecute(PythonActivity.java:102)
            at android.os.AsyncTask.finish(AsyncTask.java:771)
            at android.os.AsyncTask.access$900(AsyncTask.java:199)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:223)
            at android.app.ActivityThread.main(ActivityThread.java:7656)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
</code>```

This is my first time using Android Studio, and until now I didn't find a proper solution for this error. I would appreciate any help.

You can download the APK in the link below:

```<code>https://drive.google.com/file/d/1B8D2fbUg5-3nlkJHFDJHrwAciKPtftkF/view?usp=sharing
</code>```

答:
The error message No implementation found for void org.libsdl.app.SDLActivity.nativeSetenv(java.lang.String, java.lang.String) (tried Java_org_libsdl_app_SDLActivity_nativeSetenv and Java_org_libsdl_app_SDLActivity_nativeSetenv__Ljava_lang_String_2Ljava_lang_String_2) means that non of the loaded .so libraries of your app provides a matching method that implements the native method org.libsdl.app.SDLActivity.nativeSetenv.

So one library of your app has to export a method named Java_org_libsdl_app_SDLActivity_nativeSetenv respectively Java_org_libsdl_app_SDLActivity_nativeSetenv__Ljava_lang_String_2Ljava_lang_String_2 and this library has to be loaded using System.loadLibrary before you can call a native method.

Comparing the libs sub-folders it is obvious that something is wrong with the APK:

```<code>lib\arm64-v8a\libtensorflowlite_jni.so
lib\armeabi-v7a\libcrypto1.1.so
lib\armeabi-v7a\libffi.so
lib\armeabi-v7a\libhidapi.so
lib\armeabi-v7a\libmain.so
lib\armeabi-v7a\libpython3.8.so
lib\armeabi-v7a\libSDL2.so
lib\armeabi-v7a\libSDL2_image.so
lib\armeabi-v7a\libSDL2_mixer.so
lib\armeabi-v7a\libSDL2_ttf.so
lib\armeabi-v7a\libsqlite3.so
lib\armeabi-v7a\libssl1.1.so
lib\armeabi-v7a\libtensorflowlite_jni.so
lib\x86\libtensorflowlite_jni.so
lib\x86_64\libtensorflowlite_jni.so
</code>```

As you can see in the armeabi-v7a folders are way more libraries than in the folder for the other architectures. This means that for all architectures except armv7 your app misses a large set of libraries. So you need a libsdl version that has support for other architectures than armv7.

Body:
I'm trying to run an APK that I generated using buildozer. After trying to run on several devices both physical and virtual, I always get the same error:

2022-02-08 18:05:17.702 10070-10070/org.test.butterfly E/AndroidRuntime: FATAL EXCEPTION: main
        Process: org.test.butterfly, PID: 10070
        java.lang.UnsatisfiedLinkError: No implementation found for void org.libsdl.app.SDLActivity.nativeSetenv(java.lang.String, java.lang.String) (tried Java_org_libsdl_app_SDLActivity_nativeSetenv and Java_org_libsdl_app_SDLActivity_nativeSetenv__Ljava_lang_String_2Ljava_lang_String_2)
            at org.libsdl.app.SDLActivity.nativeSetenv(Native Method)
            at org.kivy.android.PythonActivity$UnpackFilesTask.onPostExecute(PythonActivity.java:157)
            at org.kivy.android.PythonActivity$UnpackFilesTask.onPostExecute(PythonActivity.java:102)
            at android.os.AsyncTask.finish(AsyncTask.java:771)
            at android.os.AsyncTask.access$900(AsyncTask.java:199)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:223)
            at android.app.ActivityThread.main(ActivityThread.java:7656)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

This is my first time using Android Studio, and until now I didn't find a proper solution for this error. I would appreciate any help.

You can download the APK in the link below:

https://drive.google.com/file/d/1B8D2fbUg5-3nlkJHFDJHrwAciKPtftkF/view?usp=sharing

Body:
The error message No implementation found for void org.libsdl.app.SDLActivity.nativeSetenv(java.lang.String, java.lang.String) (tried Java_org_libsdl_app_SDLActivity_nativeSetenv and Java_org_libsdl_app_SDLActivity_nativeSetenv__Ljava_lang_String_2Ljava_lang_String_2) means that non of the loaded .so libraries of your app provides a matching method that implements the native method org.libsdl.app.SDLActivity.nativeSetenv.

So one library of your app has to export a method named Java_org_libsdl_app_SDLActivity_nativeSetenv respectively Java_org_libsdl_app_SDLActivity_nativeSetenv__Ljava_lang_String_2Ljava_lang_String_2 and this library has to be loaded using System.loadLibrary before you can call a native method.

Comparing the libs sub-folders it is obvious that something is wrong with the APK:

lib\arm64-v8a\libtensorflowlite_jni.so
lib\armeabi-v7a\libcrypto1.1.so
lib\armeabi-v7a\libffi.so
lib\armeabi-v7a\libhidapi.so
lib\armeabi-v7a\libmain.so
lib\armeabi-v7a\libpython3.8.so
lib\armeabi-v7a\libSDL2.so
lib\armeabi-v7a\libSDL2_image.so
lib\armeabi-v7a\libSDL2_mixer.so
lib\armeabi-v7a\libSDL2_ttf.so
lib\armeabi-v7a\libsqlite3.so
lib\armeabi-v7a\libssl1.1.so
lib\armeabi-v7a\libtensorflowlite_jni.so
lib\x86\libtensorflowlite_jni.so
lib\x86_64\libtensorflowlite_jni.so

As you can see in the armeabi-v7a folders are way more libraries than in the folder for the other architectures. This means that for all architectures except armv7 your app misses a large set of libraries. So you need a libsdl version that has support for other architectures than armv7.


问:
How to parse tree using lxml iterparse
This is part of my xml starting from some part:

```<code><bigchapter>
     <chapter id="a" name="x">
      <valueimportant v="valuetoget1"/>
      <TimeSeries>
        <TimeSeriesIdentification v="1"/>
        <type v="a1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="26"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="26"/>
          </Interval>
        </Period>
      </TimeSeries>
      <TimeSeries>
        <type v="b1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="26"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="26"/>
          </Interval>
        </Period>
      </TimeSeries>
     </chapter>
     <chapter id="a" name="x">
      <valueimportant v="valuetoget2"/>
      <TimeSeries>
        <TimeSeriesIdentification v="1"/>
        <type v="a1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="154"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="126"/>
          </Interval>
        </Period>
      </TimeSeries>
      <TimeSeries>
        <type v="b1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="137"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="148"/>
          </Interval>
        </Period>
      </TimeSeries>
     </chapter>
</bigchapter>
</code>```

What I want is to create a dictionary with valueimportant as a key and as a value another dictionary with types as keys and dictionary with keys as Pos and Qty as values.

In return I will be getting:

```<code>{valuetoget1: {a1:{1: 26, 2:26}, b1: {1:26, 2:26}}, valuetoget2: {a1:{1:154, 2:126}, b1:{1:137,2:148}}
</code>```

I also have some xml before this part of xml, which is irrelevant, I tried this way I am getting the first part of my dictionary, which is keys, but I do not know how to proceed I would be grateful to use lxml etree

```<code>result={}
context = etree.iterparse(file_obj,
                          events=("end",))
for event, elem in context:
    try:
        if elem.tag == 'chapter':
            valueimportant = elem.find('valueimportant')
            if valueimportant.attrib['v'] not in result.keys():
                result[valueimportant.attrib['v']] = {}

    except IndexError or KeyError or ValueError:
        print('error')
</code>```

答:
I'm not sure that you need lxml there, built-in ElementTree functionality should be enough. The main task is to collect data, so just iterate over root node processing each <chapter> separately, find <valueimportant> node with v attribute, then iterate over <Period> node and find <Pos> and <Qty> nodes with v attributes.

Code:

import xml.etree.ElementTree as ET

xml = ET.parse("file.xml")
root = xml.getroot()

result = {}
for chapter in root:  # root.iterfind(".//chapter")
    valueimportant = chapter.find("./valueimportant[@v]")
    if valueimportant is not None:
        period = chapter.find("./TimeSeries/Period")  # chapter.find(".//Period")
        if period is not None:
            values = {}
            for interval in period:  # period.iterfind(".//Interval")
                pos = interval.find("./Pos[@v]")
                qty = interval.find("./Qty[@v]")
                if pos is not None and qty is not None:
                    values[pos.attrib["v"]] = qty.attrib["v"]
            result[valueimportant.attrib["v"]] = values
```

Title: How to parse tree using lxml iterparse

Body:
This is part of my xml starting from some part:

<bigchapter>
     <chapter id="a" name="x">
      <valueimportant v="valuetoget1"/>
      <TimeSeries>
        <TimeSeriesIdentification v="1"/>
        <type v="a1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="26"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="26"/>
          </Interval>
        </Period>
      </TimeSeries>
      <TimeSeries>
        <type v="b1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="26"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="26"/>
          </Interval>
        </Period>
      </TimeSeries>
     </chapter>
     <chapter id="a" name="x">
      <valueimportant v="valuetoget2"/>
      <TimeSeries>
        <TimeSeriesIdentification v="1"/>
        <type v="a1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="154"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="126"/>
          </Interval>
        </Period>
      </TimeSeries>
      <TimeSeries>
        <type v="b1"/>
        <Period>
          <Interval>
            <Pos v="1"/>
            <Qty v="137"/>
          </Interval>
          <Interval>
            <Pos v="2"/>
            <Qty v="148"/>
          </Interval>
        </Period>
      </TimeSeries>
     </chapter>
</bigchapter>

What I want is to create a dictionary with valueimportant as a key and as a value another dictionary with types as keys and dictionary with keys as Pos and Qty as values.

In return I will be getting:

{valuetoget1: {a1:{1: 26, 2:26}, b1: {1:26, 2:26}}, valuetoget2: {a1:{1:154, 2:126}, b1:{1:137,2:148}}

I also have some xml before this part of xml, which is irrelevant, I tried this way I am getting the first part of my dictionary, which is keys, but I do not know how to proceed I would be grateful to use lxml etree

result={}
context = etree.iterparse(file_obj,
                          events=("end",))
for event, elem in context:
    try:
        if elem.tag == 'chapter':
            valueimportant = elem.find('valueimportant')
            if valueimportant.attrib['v'] not in result.keys():
                result[valueimportant.attrib['v']] = {}

    except IndexError or KeyError or ValueError:
        print('error')


问:
How to build sources JAR with Gradle?
I am working with an open source project that is built with Gradle. I would like to generate a (project)-sources.jar file that I can load into my IDE (IntelliJ IDEA) and debug through the project. I know how to load the file if I can generate it.

I have looked through the available Gradle tasks for the project and there isn't one that generates a sources jar file.

What is the easiest way to generate a sources jar file for this project?

Adding the source into the jar file that contains the compiled class files would be fine as well.

答:
Android:

```<code>  task androidSourcesJar(type: Jar) {
        getArchiveClassifier().set('sources')
        from android.sourceSets.main.java.srcDirs//full sources
  }
</code>```

Java:

```<code> task sourcesJar(type: Jar, dependsOn: classes) {
        getArchiveClassifier().set('sources')
        from sourceSets.main.allSource
    }
</code>```

Title: How to build sources JAR with Gradle?

Body:
Android:

  task androidSourcesJar(type: Jar) {
        getArchiveClassifier().set('sources')
        from android.sourceSets.main.java.srcDirs//full sources
  }

Java:

 task sourcesJar(type: Jar, dependsOn: classes) {
        getArchiveClassifier().set('sources')
        from sourceSets.main.allSource
    }


问:
How to use the IEqualityComparer
I have some bells in my database with the same number. I want to get all of them without duplication. I created a compare class to do this work, but the execution of the function causes a big delay from the function without distinct, from 0.6 sec to 3.2 sec!

Am I doing it right or do I have to use another method?

```<code>reg.AddRange(
    (from a in this.dataContext.reglements
     join b in this.dataContext.Clients on a.Id_client equals b.Id
     where a.date_v <= datefin && a.date_v >= datedeb
     where a.Id_client == b.Id
     orderby a.date_v descending
     select new Class_reglement
     {
         nom  = b.Nom,
         code = b.code,
         Numf = a.Numf,
     })
    .AsEnumerable()
    .Distinct(new Compare())
    .ToList());

class Compare : IEqualityComparer<Class_reglement>
{
    public bool Equals(Class_reglement x, Class_reglement y)
    {
        if (x.Numf == y.Numf)
        {
            return true;
        }
        else { return false; }
    }
    public int GetHashCode(Class_reglement codeh)
    {
        return 0;
    }
}
</code>```

答:
The purpose of this answer is to improve on previous answers by:

making the lambda expression optional in the constructor so that full object equality can be checked by default, not just on one of the properties.

operating on different types of classes, even complex types including sub-objects or nested lists. And not only on simple classes comprising only primitive type properties.

Not taking into account possible list container differences.

Here, you'll find a first simple code sample that works only on simple types (the ones composed only by primitif properties), and a second one that is complete (for a wider range of classes and complex types).

Here is my 2 pennies try:

```<code>public class GenericEqualityComparer<T> : IEqualityComparer<T> where T : class
{
    private Func<T, object> _expr { get; set; }

    public GenericEqualityComparer() => _expr = null;

    public GenericEqualityComparer(Func<T, object> expr) => _expr = expr;

    public bool Equals(T x, T y)
    {
        var first = _expr?.Invoke(x) ?? x;
        var sec = _expr?.Invoke(y) ?? y;

        if (first == null && sec == null)
            return true;

        if (first != null && first.Equals(sec))
            return true;

        var typeProperties = typeof(T).GetProperties();

        foreach (var prop in typeProperties)
        {
            var firstPropVal = prop.GetValue(first, null);
            var secPropVal = prop.GetValue(sec, null);

            if (firstPropVal != null && !firstPropVal.Equals(secPropVal))
                return false;
        }

        return true;
    }

    public int GetHashCode(T obj) =>
        _expr?.Invoke(obj).GetHashCode() ?? obj.GetHashCode();
}
</code>```

I know we can still optimize it (and maybe use a recursive?)..
But that is working like a charm without this much complexity and on a wide range of classes. ;)

Edit: After a day, here is my $10 attempt:
First, in a separate static extension class, you'll need:

```<code>public static class CollectionExtensions
{
    public static bool HasSameLengthThan<T>(this IEnumerable<T> list, IEnumerable<T> expected)
    {
        if (list.IsNullOrEmptyCollection() && expected.IsNullOrEmptyCollection())
            return true;

        if ((list.IsNullOrEmptyCollection() && !expected.IsNullOrEmptyCollection()) || (!list.IsNullOrEmptyCollection() && expected.IsNullOrEmptyCollection()))
            return false;

        return list.Count() == expected.Count();
    }

    /// <summary>
    /// Used to find out if a collection is empty or if it contains no elements.
    /// </summary>
    /// <typeparam name="T">Type of the collection's items.</typeparam>
    /// <param name="list">Collection of items to test.</param>
    /// <returns><c>true</c> if the collection is <c>null</c> or empty (without items), <c>false</c> otherwise.</returns>
    public static bool IsNullOrEmptyCollection<T>(this IEnumerable<T> list) => list == null || !list.Any();
}
</code>```

Then, here is the updated class that works on a wider range of classes:

```<code>public class GenericComparer<T> : IEqualityComparer<T> where T : class
{
    private Func<T, object> _expr { get; set; }

    public GenericComparer() => _expr = null;

    public GenericComparer(Func<T, object> expr) => _expr = expr;

    public bool Equals(T x, T y)
    {
        var first = _expr?.Invoke(x) ?? x;
        var sec = _expr?.Invoke(y) ?? y;

        if (ObjEquals(first, sec))
            return true;

        var typeProperties = typeof(T).GetProperties();

        foreach (var prop in typeProperties)
        {
            var firstPropVal = prop.GetValue(first, null);
            var secPropVal = prop.GetValue(sec, null);

            if (!ObjEquals(firstPropVal, secPropVal))
            {
                var propType = prop.PropertyType;

                if (IsEnumerableType(propType) && firstPropVal is IEnumerable && !ArrayEquals(firstPropVal, secPropVal))
                    return false;

                if (propType.IsClass)
                {
                    if (!DeepEqualsFromObj(firstPropVal, secPropVal, propType))
                        return false;

                    if (!DeepObjEquals(firstPropVal, secPropVal))
                        return false;
                }
            }
        }

        return true;
    }

    public int GetHashCode(T obj) =>
        _expr?.Invoke(obj).GetHashCode() ?? obj.GetHashCode();

    #region Private Helpers

    private bool DeepObjEquals(object x, object y) =>
        new GenericComparer<object>().Equals(x, y);

    private bool DeepEquals<U>(U x, U y) where U : class =>
        new GenericComparer<U>().Equals(x, y);

    private bool DeepEqualsFromObj(object x, object y, Type type)
    {
        dynamic a = Convert.ChangeType(x, type);
        dynamic b = Convert.ChangeType(y, type);
        return DeepEquals(a, b);
    }

    private bool IsEnumerableType(Type type) =>
        type.GetInterface(nameof(IEnumerable)) != null;

    private bool ObjEquals(object x, object y)
    {
        if (x == null && y == null) return true;
        return x != null && x.Equals(y);
    }

    private bool ArrayEquals(object x, object y)
    {
        var firstList = new List<object>((IEnumerable<object>)x);
        var secList = new List<object>((IEnumerable<object>)y);

        if (!firstList.HasSameLengthThan(secList))
            return false;

        var elementType = firstList?.FirstOrDefault()?.GetType();
        int cpt = 0;
        foreach (var e in firstList)
        {
            if (!DeepEqualsFromObj(e, secList[cpt++], elementType))
                return false;
        }

        return true;
    }

    #endregion Private Helpers
</code>```

We can still optimize it but it worth give it a try ^^.

Title: How to use the IEqualityComparer

Body:
I have some bells in my database with the same number. I want to get all of them without duplication. I created a compare class to do this work, but the execution of the function causes a big delay from the function without distinct, from 0.6 sec to 3.2 sec!

Am I doing it right or do I have to use another method?

reg.AddRange(
    (from a in this.dataContext.reglements
     join b in this.dataContext.Clients on a.Id_client equals b.Id
     where a.date_v <= datefin && a.date_v >= datedeb
     where a.Id_client == b.Id
     orderby a.date_v descending
     select new Class_reglement
     {
         nom  = b.Nom,
         code = b.code,
         Numf = a.Numf,
     })
    .AsEnumerable()
    .Distinct(new Compare())
    .ToList());

class Compare : IEqualityComparer<Class_reglement>
{
    public bool Equals(Class_reglement x, Class_reglement y)
    {
        if (x.Numf == y.Numf)
        {
            return true;
        }
        else { return false; }
    }
    public int GetHashCode(Class_reglement codeh)
    {
        return 0;
    }
}

Body:
The purpose of this answer is to improve on previous answers by:

making the lambda expression optional in the constructor so that full object equality can be checked by default, not just on one of the properties.

operating on different types of classes, even complex types including sub-objects or nested lists. And not only on simple classes comprising only primitive type properties.

Not taking into account possible list container differences.

Here, you'll find a first simple code sample that works only on simple types (the ones composed only by primitif properties), and a second one that is complete (for a wider range of classes and complex types).

Here is my 2 pennies try:

public class GenericEqualityComparer<T> : IEqualityComparer<T> where T : class
{
    private Func<T, object> _expr { get; set; }

    public GenericEqualityComparer() => _expr = null;

    public GenericEqualityComparer(Func<T, object> expr) => _expr = expr;

    public bool Equals(T x, T y)
    {
        var first = _expr?.Invoke(x) ?? x;
        var sec = _expr?.Invoke(y) ?? y;

        if (first == null && sec == null)
            return true;

        if (first != null && first.Equals(sec))
            return true;

        var typeProperties = typeof(T).GetProperties();

        foreach (var prop in typeProperties)
        {
            var firstPropVal = prop.GetValue(first, null);
            var secPropVal = prop.GetValue(sec, null);

            if (firstPropVal != null && !firstPropVal.Equals(secPropVal))
                return false;
        }

        return true;
    }

    public int GetHashCode(T obj) =>
        _expr?.Invoke(obj).GetHashCode() ?? obj.GetHashCode();
}

I know we can still optimize it (and maybe use a recursive?)..
But that is working like a charm without this much complexity and on a wide range of classes. ;)

Edit: After a day, here is my $10 attempt:
First, in a separate static extension class, you'll need:

public static class CollectionExtensions
{
    public static bool HasSameLengthThan<T>(this IEnumerable<T> list, IEnumerable<T> expected)
    {
        if (list.IsNullOrEmptyCollection() && expected.IsNullOrEmptyCollection())
            return true;

        if ((list.IsNullOrEmptyCollection() && !expected.IsNullOrEmptyCollection()) || (!list.IsNullOrEmptyCollection() && expected.IsNullOrEmptyCollection()))
            return false;

        return list.Count() == expected.Count();
    }

    /// <summary>
    /// Used to find out if a collection is empty or if it contains no elements.
    /// </summary>
    /// <typeparam name="T">Type of the collection's items.</typeparam>
    /// <param name="list">Collection of items to test.</param>
    /// <returns><c>true</c> if the collection is <c>null</c> or empty (without items), <c>false</c> otherwise.</returns>
    public static bool IsNullOrEmptyCollection<T>(this IEnumerable<T> list) => list == null || !list.Any();
}

Then, here is the updated class that works on a wider range of classes:

public class GenericComparer<T> : IEqualityComparer<T> where T : class
{
    private Func<T, object> _expr { get; set; }

    public GenericComparer() => _expr = null;

    public GenericComparer(Func<T, object> expr) => _expr = expr;

    public bool Equals(T x, T y)
    {
        var first = _expr?.Invoke(x) ?? x;
        var sec = _expr?.Invoke(y) ?? y;

        if (ObjEquals(first, sec))
            return true;

        var typeProperties = typeof(T).GetProperties();

        foreach (var prop in typeProperties)
        {
            var firstPropVal = prop.GetValue(first, null);
            var secPropVal = prop.GetValue(sec, null);

            if (!ObjEquals(firstPropVal, secPropVal))
            {
                var propType = prop.PropertyType;

                if (IsEnumerableType(propType) && firstPropVal is IEnumerable && !ArrayEquals(firstPropVal, secPropVal))
                    return false;

                if (propType.IsClass)
                {
                    if (!DeepEqualsFromObj(firstPropVal, secPropVal, propType))
                        return false;

                    if (!DeepObjEquals(firstPropVal, secPropVal))
                        return false;
                }
            }
        }

        return true;
    }

    public int GetHashCode(T obj) =>
        _expr?.Invoke(obj).GetHashCode() ?? obj.GetHashCode();

    #region Private Helpers

    private bool DeepObjEquals(object x, object y) =>
        new GenericComparer<object>().Equals(x, y);

    private bool DeepEquals<U>(U x, U y) where U : class =>
        new GenericComparer<U>().Equals(x, y);

    private bool DeepEqualsFromObj(object x, object y, Type type)
    {
        dynamic a = Convert.ChangeType(x, type);
        dynamic b = Convert.ChangeType(y, type);
        return DeepEquals(a, b);
    }

    private bool IsEnumerableType(Type type) =>
        type.GetInterface(nameof(IEnumerable)) != null;

    private bool ObjEquals(object x, object y)
    {
        if (x == null && y == null) return true;
        return x != null && x.Equals(y);
    }

    private bool ArrayEquals(object x, object y)
    {
        var firstList = new List<object>((IEnumerable<object>)x);
        var secList = new List<object>((IEnumerable<object>)y);

        if (!firstList.HasSameLengthThan(secList))
            return false;

        var elementType = firstList?.FirstOrDefault()?.GetType();
        int cpt = 0;
        foreach (var e in firstList)
        {
            if (!DeepEqualsFromObj(e, secList[cpt++], elementType))
                return false;
        }

        return true;
    }

    #endregion Private Helpers

We can still optimize it but it worth give it a try ^^.


问:
Call different constructors from different structs based on input parameter value
recently I'm working on an problem like that

```<code>struct A {
    A() {/* Constructor A */ }
    void method() { /* method A */ }
};

struct B {
    B() {/* Constructor B */ }
    void method() { /* method B */ }
};

struct C : public A, public B {
    C(int which) :A() {}
    C() :B() {}

    static C ConstructIt(int which) {
        if (which == 1) {
            return C(which);
        }
        else {
            return C();
        }
    }
};
int main(int argc, char** argv) {
    const int a = 1, b = 0;
    C examp_A = C::ConstructIt(a);
    C examp_B = C::ConstructIt(b);
    examp_A.method(); //use method A
    examp_B.method(); //use method B
}
</code>```

I need to create a interface to call different method struct A or B based on dynamic input parameter value, since it's determined in runtime I do not want to use template partial specialization. I try to use multiple inherit to see struct A and B as bases, and conditionally select the constructors A or B, it failed caused by multiple inheritance construct the base and derived classes automatically.

With my current knowledge of C++ I don't know how to realize it (maybe it's a stupid question), thanks for help in advance.

EDIT:
Thanks the solution provided by Jarod42. It seems ok for me if I can modify the struct A which is fully developed. Is there a way that I could realize the above feature without modify the existed struct A? Struct B is free to change.

答:
It seems you want polymorphism. There are several ways.

One common way is with interface and virtual functions:

struct C
{
    virtual ~C() = default;
    virtual void method() = 0;
};

struct A : C {
    A() {/* Constructor A */ }
    void method() override { /* method A */ }
};

struct B  : C {
    B() {/* Constructor B */ }
    void method() override { /* method B */ }
};

std::unique_ptr<C> ConstructC(int which) {
    switch (which) {
        case 1: return std::make_unique();
        case 2: return std::make_unique();
        // ...
    }
    return nullptr;
}
```
<p>And then</p>
<pre class="lang-cpp prettyprint-override"><code>int main() {
    const int a = 1, b = 0;
    auto examp_A = ConstructC(a);
    auto examp_B = ConstructC(b);
    examp_A->method(); //use method A
    examp_B->method(); //use method B
}
</code>```

Body:
recently I'm working on an problem like that

struct A {
    A() {/* Constructor A */ }
    void method() { /* method A */ }
};

struct B {
    B() {/* Constructor B */ }
    void method() { /* method B */ }
};

struct C : public A, public B {
    C(int which) :A() {}
    C() :B() {}

    static C ConstructIt(int which) {
        if (which == 1) {
            return C(which);
        }
        else {
            return C();
        }
    }
};
int main(int argc, char** argv) {
    const int a = 1, b = 0;
    C examp_A = C::ConstructIt(a);
    C examp_B = C::ConstructIt(b);
    examp_A.method(); //use method A
    examp_B.method(); //use method B
}

I need to create a interface to call different method struct A or B based on dynamic input parameter value, since it's determined in runtime I do not want to use template partial specialization. I try to use multiple inherit to see struct A and B as bases, and conditionally select the constructors A or B, it failed caused by multiple inheritance construct the base and derived classes automatically.

With my current knowledge of C++ I don't know how to realize it (maybe it's a stupid question), thanks for help in advance.

EDIT:
Thanks the solution provided by Jarod42. It seems ok for me if I can modify the struct A which is fully developed. Is there a way that I could realize the above feature without modify the existed struct A? Struct B is free to change.

Body:
It seems you want polymorphism. There are several ways.

One common way is with interface and virtual functions:

struct C
{
    virtual ~C() = default;
    virtual void method() = 0;
};

struct A : C {
    A() {/* Constructor A */ }
    void method() override { /* method A */ }
};

struct B  : C {
    B() {/* Constructor B */ }
    void method() override { /* method B */ }
};

std::unique_ptr<C> ConstructC(int which) {
    switch (which) {
        case 1: return std::make_unique<A>();
        case 2: return std::make_unique<B>();
        // ...
    }
    return nullptr;
}

And then

int main() {
    const int a = 1, b = 0;
    auto examp_A = ConstructC(a);
    auto examp_B = ConstructC(b);
    examp_A->method(); //use method A
    examp_B->method(); //use method B
}


问:
Cannot resolve an error" Error reading the C:\Users\acer\AppData\Local\Temp\iisexpress\ directory." while executing ASP.NET Core web app
I am working on an ASP.NET Core web application. The project is built successfully but I keep getting this unhandled exception

Error reading the C:\Users\acer\AppData\Local\Temp\iisexpress\ directory.

The app runs alright but this error pops up every time I run the application. How to solve this issue?

答:
I have this same problem. I went to the iisexppress folder in Temp and it tells me that "You don't current have permission to access this folder".

I then ran Visual Studio as administrator and the error doesn't appear. So it's a permissions problem for me, and I don't know why it happens...!

I then went to my Temp folder and renamed iisexpress to issexpress.bak. Then reloaded visual studio (not as admin) and ran and it didn't show this error message, as it recreated the iisexpress folder with the right permissions this time.


问:
Async python script just returning in console (works in IDE / debugger)
The script is running fine in thonny on the rasperry zero and does its job to measure and interact with the mqtt server. This is intended to be a script that runs in the background and I added it to /etc/rc.local between the lines fi and exit 0: python3 /home/pi/pisensor/scripts/dht22_mqtt.py &
After rebooting the expected messages on the mqtt server did not appear, so I tried running the script on the console. I called it with python3 dht22_mqtt.py in the directory and after some seconds it just looked like it was finished (new line in in console), but had done nothing (no messages to mqtt server and no print messages). No errors were shown that a library is missing or something was wrong.
Could it be there is a problem with running an async script like this from console?

Is there a possibility to debug the script when run from console? I tried the -d parameter of python3, but with the same result.
I tried pip3 with the dht and the paho-mqtt lib, but it was already installed.

You can have a look at the script here:

```<code>from time import sleep
import asyncio
from paho.mqtt import subscribe, publish
from random import randint
from typing import Awaitable, Any

async def run_sequence(*functions: Awaitable[Any]) -> None:
    for function in functions:
        await function

async def run_parallel(*functions: Awaitable[Any]) -> None:
    await asyncio.gather(*functions)

class IOTSensorDHT22:

    def __init__(self,
                 mqtt_server="localhost",
                 mqtt_port=1883,
                 sensor_pin=4,
                 sensor_values_topic_prefix="/sensor/raw/bedroom/",
                 sensor_interval=60,
                 sensor_interval_topic="/setting/sensor/inside/power/interval"):
        self.messages = None
        self.values = None
        self.mqtt_server = mqtt_server
        self.mqtt_port = mqtt_port
        self.sensor_pin = sensor_pin
        self.sensor_values_topic_prefix = sensor_values_topic_prefix
        self.sensor_interval = sensor_interval
        self.sensor_interval_topic = sensor_interval_topic
        self.mqtt_client_id = f"mqtt_client_{randint(0, 1000)}"

    async def query_interval(self):
        new_interval = int(subscribe.simple(self.sensor_interval_topic, hostname=self.mqtt_server).payload)
        if new_interval != self.sensor_interval:
            print(
                f"new interval {new_interval} - old: {self.sensor_interval} - assigning new value: {new_interval != self.sensor_interval}")
            self.sensor_interval = new_interval

    async def publish_values(self):
        print(f"publishing messages: {self.messages}")
        publish.multiple(self.messages, hostname=self.mqtt_server)

    async def measure(self):
        self.values = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, self.sensor_pin)

    async def build_messages(self):
        messages = (self.build_message("hum", self.values[0]), self.build_message("temp", self.values[1]))
        print(messages)
        self.messages = messages

    def build_message(self, topic_appendix, value):
        return self.sensor_values_topic_prefix + topic_appendix, round(value, 1)

    def sleep(self):
        print(f"going to sleep for {self.sensor_interval}")
        sleep(self.sensor_interval)

    async def run(self):
        while True:
            await run_parallel(
                run_sequence(self.measure(), self.build_messages(), self.publish_values()),
                self.query_interval()
            )
            self.sleep()

if __name__ is "__main__":
    asyncio.run(
        IOTSensorDHT22(
            mqtt_server="192.168.188.37",  #
            sensor_pin=12,
            sensor_values_topic_prefix="/sensor/raw/bedroom/",
            sensor_interval=60,
            sensor_interval_topic="/setting/sensor/inside/power/interval/").run())
</code>```

edit: thanks for the edit help :)

UPDATE - SOLVED:

I wrote if __name__ is "__main__":

while it should have been

if __name__ == "__main__":

My mistake for sure, but it was misleading for me that it worked fine in the IDE (Thonny), but did nothing when run from console.

答:
You can use ipdb for debugging in the console.

```<code>pip install ipdb
</code>```

then put this in your code at the point you want to debug:

```<code>import ipdb
ipdb.set_trace()
</code>```

then you can just step through your code, like with a debugger from an IDE. for more instructions how to use ipdb see this tutorial.

Body:
The script is running fine in thonny on the rasperry zero and does its job to measure and interact with the mqtt server. This is intended to be a script that runs in the background and I added it to /etc/rc.local between the lines fi and exit 0: python3 /home/pi/pisensor/scripts/dht22_mqtt.py &
After rebooting the expected messages on the mqtt server did not appear, so I tried running the script on the console. I called it with python3 dht22_mqtt.py in the directory and after some seconds it just looked like it was finished (new line in in console), but had done nothing (no messages to mqtt server and no print messages). No errors were shown that a library is missing or something was wrong.
Could it be there is a problem with running an async script like this from console?

Is there a possibility to debug the script when run from console? I tried the -d parameter of python3, but with the same result.
I tried pip3 with the dht and the paho-mqtt lib, but it was already installed.

You can have a look at the script here:

from time import sleep
import asyncio
from paho.mqtt import subscribe, publish
from random import randint
from typing import Awaitable, Any

async def run_sequence(*functions: Awaitable[Any]) -> None:
    for function in functions:
        await function

async def run_parallel(*functions: Awaitable[Any]) -> None:
    await asyncio.gather(*functions)

class IOTSensorDHT22:

    def __init__(self,
                 mqtt_server="localhost",
                 mqtt_port=1883,
                 sensor_pin=4,
                 sensor_values_topic_prefix="/sensor/raw/bedroom/",
                 sensor_interval=60,
                 sensor_interval_topic="/setting/sensor/inside/power/interval"):
        self.messages = None
        self.values = None
        self.mqtt_server = mqtt_server
        self.mqtt_port = mqtt_port
        self.sensor_pin = sensor_pin
        self.sensor_values_topic_prefix = sensor_values_topic_prefix
        self.sensor_interval = sensor_interval
        self.sensor_interval_topic = sensor_interval_topic
        self.mqtt_client_id = f"mqtt_client_{randint(0, 1000)}"

    async def query_interval(self):
        new_interval = int(subscribe.simple(self.sensor_interval_topic, hostname=self.mqtt_server).payload)
        if new_interval != self.sensor_interval:
            print(
                f"new interval {new_interval} - old: {self.sensor_interval} - assigning new value: {new_interval != self.sensor_interval}")
            self.sensor_interval = new_interval

    async def publish_values(self):
        print(f"publishing messages: {self.messages}")
        publish.multiple(self.messages, hostname=self.mqtt_server)

    async def measure(self):
        self.values = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, self.sensor_pin)

    async def build_messages(self):
        messages = (self.build_message("hum", self.values[0]), self.build_message("temp", self.values[1]))
        print(messages)
        self.messages = messages

    def build_message(self, topic_appendix, value):
        return self.sensor_values_topic_prefix + topic_appendix, round(value, 1)

    def sleep(self):
        print(f"going to sleep for {self.sensor_interval}")
        sleep(self.sensor_interval)

    async def run(self):
        while True:
            await run_parallel(
                run_sequence(self.measure(), self.build_messages(), self.publish_values()),
                self.query_interval()
            )
            self.sleep()

if __name__ is "__main__":
    asyncio.run(
        IOTSensorDHT22(
            mqtt_server="192.168.188.37",  #
            sensor_pin=12,
            sensor_values_topic_prefix="/sensor/raw/bedroom/",
            sensor_interval=60,
            sensor_interval_topic="/setting/sensor/inside/power/interval/").run())

edit: thanks for the edit help :)

UPDATE - SOLVED:

I wrote if __name__ is "__main__":

while it should have been

if __name__ == "__main__":

My mistake for sure, but it was misleading for me that it worked fine in the IDE (Thonny), but did nothing when run from console.

Body:
You can use ipdb for debugging in the console.

pip install ipdb

then put this in your code at the point you want to debug:

import ipdb
ipdb.set_trace()

then you can just step through your code, like with a debugger from an IDE. for more instructions how to use ipdb see this tutorial.


问:
How should I structure this code to break out of multiple nested loops at once?
I'm learning image detection and python writing a bot for a 2d game. There are certain targets we want to attack and certain targets we want to avoid. One target is displayed on the screen at a time out of a pool of 100 and you click next or attack depending on what you want to do. In doing this you're able to cycle through targets until you find one you want to attack. My code currently checks to see if it finds one of 24 different targets we want to avoid, if it does it avoids that target. Otherwise, it attacks that target.

At the moment my code:

```<code>1. Loads 24 different images of things we want to avoid into a NumPy array and checks with `py.locateCenterOnScreen`
   if we are on the correct screen to start the video loop
2. Uses cv2.imshow to display a real-time view of what is happening for use later with cv2.rectangles
3. Continuously loops through the NumPy array to determine if any of the loaded images have been found
4. If anything has been found it will either print "avoid" or "attack" to the terminal.
</code>```

There's also additional logging that I've not added to the below code as it isn't relevant. It simply logs the attack/avoid to a .txt file with time stamps.

```<code>My issue:
</code>```

At the moment my object detection loop for i in image_list: never stops when it finds one of the 24 images, it loops over them again and again swapping away from the found image.

```<code>My question:
</code>```

When one of the 24 images is detected, how do I stop my detection loop without stopping my cv2.imshow loop. For example, if image 5 is found. I want to keep image 5 highlighted with cv2.rectangle rather than only having it highlight for a fraction of a second when it comes up in the detection loop.

```<code># Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append((img, i))
    return image_list

def objectDetection(image_list, threshold_value):
    # Video Loop
    while True:
        # Listener to check if attack! button displaying
        if py.locateCenterOnScreen('!attack.jpg', region = (1282, 931, 1585-1282, 1032-931), grayscale=True) != None:
            # Set attack_loop to false as haven't found anything yet, only set to true when something has been attacked
            attack_loop = False
            while attack_loop is False:
                # Grab PSS Window and find size
                window = pygetwindow.getWindowsWithTitle('App')[0]
                x1 = window.left
                y1 = window.top
                height = window.height
                width = window.width
                x2 = x1 + width
                y2 = y1 + height
                # Actual Video Loop, cropped down to the specific window,
                # resized to 1/2 size, and converted to BGR for OpenCV
                haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
                (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
                haystack_img_resized = haystack_img.resize((width, height))
                crop = haystack_img_resized.crop((360,22,600,65))
                haystack_img_np = np.array(crop)
                haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
                cv.imshow("Screen", haystack)

                # Object Detection
                for i in image_list:
                    needle_img = i[0]
                    needle_name = i[1]
                    result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

                    # Get the best match position
                    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

                    # Define top left and bottom right and threshold
                    (H, W) = i[0].shape[:2]
                    top_left = max_loc
                    bottom_right = (top_left[0] + W, top_left[1] + H)
                    threshold = threshold_value

                    # If something has been detected click keep looking code
                    if max_val >= threshold:
                        cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                        print("avoid")
                    else:
                        print("attack")
                        if max_val >= threshold:print(max_val)

### Main Script ###

# load images to detect
ships_to_avoid = loadImages(defeat)
# Run actual image detection
objectDetection(ships_to_avoid, 0.92)
</code>```

答:
The full working code.</p>
```<code>import pyautogui as py
import glob
import cv2 as cv
import os
import numpy as np
import pygetwindow
import time
from PIL import ImageGrab

os.chdir(r'C:\test')
avoid = glob.glob(r"C:\test\*.png")

# Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append((img, i))
    return image_list

def videoLoop():
    # Grab Window and find size
    window = pygetwindow.getWindowsWithTitle('App')[0]
    x1 = window.left
    y1 = window.top
    height = window.height
    width = window.width
    x2 = x1 + width
    y2 = y1 + height
    # Actual Video Loop, cropped down to the specific window,
    # resized to 1/2 size, and converted to BGR for OpenCV
    haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
    (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
    haystack_img_resized = haystack_img.resize((width, height))
    crop = haystack_img_resized.crop((360,22,600,65))
    haystack_img_np = np.array(crop)
    haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
    cv.imshow("Screen", haystack)
    return haystack

def objectDetection(image_list, threshold, haystack, a):
    # Object Detection
    for x in range (0, a):
        for i in image_list:
            needle_img = i[0]
            needle_name = i[1]
            sliced_name = needle_name.split("\\")[-1]
            result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

            # Get the best match position
            min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

            # Define top left and bottom right and threshold
            (H, W) = i[0].shape[:2]
            top_left = max_loc
            bottom_right = (top_left[0] + W, top_left[1] + H)

            # If something has been detected click keep looking code
            if max_val >= threshold:
                cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                cv.imshow("Screen", haystack)
                keep_looking()

            if cv.waitKey(1) == ord('q'):
                cv.destroyAllWindows()
                break

def keep_looking():
    py.moveTo(1715,1000,0.1)
    py.sleep(0.01)
    py.click()

# load images to detect
ships_to_avoid = loadImages(avoid)

while True:
    window = videoLoop()
    objectDetection(ships_to_avoid, 0.92, window, 10)
</code>```

Body:
I'm learning image detection and python writing a bot for a 2d game. There are certain targets we want to attack and certain targets we want to avoid. One target is displayed on the screen at a time out of a pool of 100 and you click next or attack depending on what you want to do. In doing this you're able to cycle through targets until you find one you want to attack. My code currently checks to see if it finds one of 24 different targets we want to avoid, if it does it avoids that target. Otherwise, it attacks that target.

At the moment my code:

1. Loads 24 different images of things we want to avoid into a NumPy array and checks with `py.locateCenterOnScreen`
   if we are on the correct screen to start the video loop
2. Uses cv2.imshow to display a real-time view of what is happening for use later with cv2.rectangles
3. Continuously loops through the NumPy array to determine if any of the loaded images have been found
4. If anything has been found it will either print "avoid" or "attack" to the terminal.

There's also additional logging that I've not added to the below code as it isn't relevant. It simply logs the attack/avoid to a .txt file with time stamps.

My issue:

At the moment my object detection loop for i in image_list: never stops when it finds one of the 24 images, it loops over them again and again swapping away from the found image.

My question:

When one of the 24 images is detected, how do I stop my detection loop without stopping my cv2.imshow loop. For example, if image 5 is found. I want to keep image 5 highlighted with cv2.rectangle rather than only having it highlight for a fraction of a second when it comes up in the detection loop.

# Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append((img, i))
    return image_list

def objectDetection(image_list, threshold_value):
    # Video Loop
    while True:
        # Listener to check if attack! button displaying
        if py.locateCenterOnScreen('!attack.jpg', region = (1282, 931, 1585-1282, 1032-931), grayscale=True) != None:
            # Set attack_loop to false as haven't found anything yet, only set to true when something has been attacked
            attack_loop = False
            while attack_loop is False:
                # Grab PSS Window and find size
                window = pygetwindow.getWindowsWithTitle('App')[0]
                x1 = window.left
                y1 = window.top
                height = window.height
                width = window.width
                x2 = x1 + width
                y2 = y1 + height
                # Actual Video Loop, cropped down to the specific window,
                # resized to 1/2 size, and converted to BGR for OpenCV
                haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
                (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
                haystack_img_resized = haystack_img.resize((width, height))
                crop = haystack_img_resized.crop((360,22,600,65))
                haystack_img_np = np.array(crop)
                haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
                cv.imshow("Screen", haystack)

                # Object Detection
                for i in image_list:
                    needle_img = i[0]
                    needle_name = i[1]
                    result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

                    # Get the best match position
                    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

                    # Define top left and bottom right and threshold
                    (H, W) = i[0].shape[:2]
                    top_left = max_loc
                    bottom_right = (top_left[0] + W, top_left[1] + H)
                    threshold = threshold_value

                    # If something has been detected click keep looking code
                    if max_val >= threshold:
                        cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                        print("avoid")
                    else:
                        print("attack")
                        if max_val >= threshold:print(max_val)

### Main Script ###

# load images to detect
ships_to_avoid = loadImages(defeat)
# Run actual image detection
objectDetection(ships_to_avoid, 0.92)

Body:
The full working code.

import pyautogui as py
import glob
import cv2 as cv
import os
import numpy as np
import pygetwindow
import time
from PIL import ImageGrab

os.chdir(r'C:\test')
avoid = glob.glob(r"C:\test\*.png")

# Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append((img, i))
    return image_list

def videoLoop():
    # Grab Window and find size
    window = pygetwindow.getWindowsWithTitle('App')[0]
    x1 = window.left
    y1 = window.top
    height = window.height
    width = window.width
    x2 = x1 + width
    y2 = y1 + height
    # Actual Video Loop, cropped down to the specific window,
    # resized to 1/2 size, and converted to BGR for OpenCV
    haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
    (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
    haystack_img_resized = haystack_img.resize((width, height))
    crop = haystack_img_resized.crop((360,22,600,65))
    haystack_img_np = np.array(crop)
    haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
    cv.imshow("Screen", haystack)
    return haystack

def objectDetection(image_list, threshold, haystack, a):
    # Object Detection
    for x in range (0, a):
        for i in image_list:
            needle_img = i[0]
            needle_name = i[1]
            sliced_name = needle_name.split("\\")[-1]
            result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

            # Get the best match position
            min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

            # Define top left and bottom right and threshold
            (H, W) = i[0].shape[:2]
            top_left = max_loc
            bottom_right = (top_left[0] + W, top_left[1] + H)

            # If something has been detected click keep looking code
            if max_val >= threshold:
                cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                cv.imshow("Screen", haystack)
                keep_looking()

            if cv.waitKey(1) == ord('q'):
                cv.destroyAllWindows()
                break

def keep_looking():
    py.moveTo(1715,1000,0.1)
    py.sleep(0.01)
    py.click()

# load images to detect
ships_to_avoid = loadImages(avoid)

while True:
    window = videoLoop()
    objectDetection(ships_to_avoid, 0.92, window, 10)


问:
How to switch tab programmatically in react-navigation showing the animation?
I'm using the MaterialTopTabNavigationProp, and need to change the selected tab programmatically.

I just tried using navigation.navigate or navigation.jumpTo, everything works fine, but the changing is instant with no animation, is there a way to show the classic tab switching animation?

Thanks everyone

答:
If you want animation when you change the tab, you can use the following library.

react-native-animated-tabbar


问:
Big Query Table not being partitioned with firestore Export Collections to BigQuery extension

I am using Export Collections to BigQuery extension with firestore to export data to the bigquery.I can export data to the big query but the table is not getting partitioned even I have enabled the table partitioned with extension while configuring extension at the creation time.

答:
I had the same issue today when exporting data from Firestore to BigQuery and doing a historical load with npx firebaseextensions/fs-bq-import-collection command.

These are my findings.
If you configure the extension to have partitioning based on the ingestion time, you have to wait for a first new record that will trigger that streaming extension and create a partitioned table.

If you just create an extension and immediately execute a historical load, the table created won't be partitioned. I tested this 3 times today.

A question for you -- did you execute a historical load or imported only new records?


问:
Component attributes do not support complex content (mixed C# and markup) error message
I am working on validation on a form in a blazor server application.
I created the component below that I am using

```<code>    @* Inherits from the original InputText component *@
    @inherits InputText
    @* Bind the oninput event *@
    <input @attributes="AdditionalAttributes"
           class="@CssClass"
           value="@CurrentValue"
           @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />

    @code {

    }
</code>```

I am using the inputTextOnInput in this form

```<code>     <EditForm EditContext="@EditContext">
                <DataAnnotationsValidator />
                <div class="mb-5">
                    <label for="projectnameinput" class="form-label">Name your project*</label>
                    <InputTextOnInput  class="form-control form-control-lg cust @pNameValidation" id="projectnameinput" @bind-value="projectModel.ProjectName" @onkeyup=KeyboardEventHandler />
                </div>
     </EditForm>
</code>```

since I created this I started getting the error message below

Component attributes do not support complex content (mixed C# and markup). Attribute: 'class', text: 'form-controlform-control-lgcustpNameValidation

Do you have an idea of what this implies?

答:
For some reason Blazor/Razor don't let you mix text literals and variables within an attribute value. So when you try and do

```<code><InputTextOnInput  class="form-control form-control-lg cust @pNameValidation" id="projectnameinput" @bind-value="projectModel.ProjectName" @onkeyup=KeyboardEventHandler />
</code>```

the class statement is invalid because it contains literals "form-control", "form-control-lg" and "cust" and also a variable "@pNameValidation".

My solution to this problem was to create a little method on a component base class which allows mixing the two things.

```<code>    public string Class(string classStr, params string[] objStrs)
    {
        var output = new StringBuilder();
        output.Append(classStr);
        output.Append(' ');
        output.AppendJoin(' ', objStrs);
        return output.ToString();
    }
</code>```

now all I have to do is to write my line like this

```<code><InputTextOnInput  class="@Class("form-control form-control-lg cust", pNameValidation)" id="projectnameinput" @bind-value="projectModel.ProjectName" @onkeyup=KeyboardEventHandler />
</code>```

and by using params, you can also just add as many string variables as you want.

Body:
I am working on validation on a form in a blazor server application.
I created the component below that I am using

    @* Inherits from the original InputText component *@
    @inherits InputText
    @* Bind the oninput event *@
    <input @attributes="AdditionalAttributes"
           class="@CssClass"
           value="@CurrentValue"
           @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />

    @code {

    }

I am using the inputTextOnInput in this form

     <EditForm EditContext="@EditContext">
                <DataAnnotationsValidator />

                    Name your project*
                    <InputTextOnInput  class="form-control form-control-lg cust @pNameValidation" id="projectnameinput" @bind-value="projectModel.ProjectName" @onkeyup=KeyboardEventHandler />

     </EditForm>

since I created this I started getting the error message below

Component attributes do not support complex content (mixed C# and markup). Attribute: 'class', text: 'form-controlform-control-lgcustpNameValidation

Do you have an idea of what this implies?

Body:
For some reason Blazor/Razor don't let you mix text literals and variables within an attribute value. So when you try and do

<InputTextOnInput  class="form-control form-control-lg cust @pNameValidation" id="projectnameinput" @bind-value="projectModel.ProjectName" @onkeyup=KeyboardEventHandler />

the class statement is invalid because it contains literals "form-control", "form-control-lg" and "cust" and also a variable "@pNameValidation".

My solution to this problem was to create a little method on a component base class which allows mixing the two things.

    public string Class(string classStr, params string[] objStrs)
    {
        var output = new StringBuilder();
        output.Append(classStr);
        output.Append(' ');
        output.AppendJoin(' ', objStrs);
        return output.ToString();
    }

now all I have to do is to write my line like this

<InputTextOnInput  class="@Class("form-control form-control-lg cust", pNameValidation)" id="projectnameinput" @bind-value="projectModel.ProjectName" @onkeyup=KeyboardEventHandler />

and by using params, you can also just add as many string variables as you want.


问:
Message from a telegram bot without a command(python)
I want to send a Message(call a function) every day at a given Time. Sadly this is not possible with message.reply_text('Test'). Is there any way i can do this? I could not find anything.

This is my current code:

```<code>import telegram.ext
from telegram.ext import CommandHandler, MessageHandler, Filters
import schedule
import time

API_KEY = 'XXXXXXXXXXX'
updater = telegram.ext.Updater(API_KEY)
dispatcher = updater.dispatcher

def start(update, context):
    update.message.reply_text('Welcome!')

# problem:
def Test(update, context):
    update.message.reply_text('Works!!!')

# running special functions every Day at a given Time
schedule.every().day.at("10:00").do(Test)

while True:
    schedule.run_pending()
    time.sleep(1)

def main():
    # add handlers for start and help commands
    dispatcher.add_handler(CommandHandler("start", start))

    # start your bot
    updater.start_polling()
    # run the bot until Ctrl-C
    updater.idle()
</code>```

The schedule part works, I just don`t know how to send this Message.
Thanks for your help!

答:
Update object, inside of the message field, has the from field which is a User Telegram object containing the user's ID.

Once you have the user's ID, you can use the sendMessage method in order to reply him easily.

To conclude, instead of:

```<code>update.message.reply_text('Welcome!')
</code>```

You could do like so:

```<code>user_id = update.message.from.id
updater.sendmessage(chat_id=user_id, text="Welcome!")
</code>```

Body:
I want to send a Message(call a function) every day at a given Time. Sadly this is not possible with message.reply_text('Test'). Is there any way i can do this? I could not find anything.

This is my current code:

import telegram.ext
from telegram.ext import CommandHandler, MessageHandler, Filters
import schedule
import time

API_KEY = 'XXXXXXXXXXX'
updater = telegram.ext.Updater(API_KEY)
dispatcher = updater.dispatcher

def start(update, context):
    update.message.reply_text('Welcome!')

# problem:
def Test(update, context):
    update.message.reply_text('Works!!!')

# running special functions every Day at a given Time
schedule.every().day.at("10:00").do(Test)

while True:
    schedule.run_pending()
    time.sleep(1)

def main():
    # add handlers for start and help commands
    dispatcher.add_handler(CommandHandler("start", start))

    # start your bot
    updater.start_polling()
    # run the bot until Ctrl-C
    updater.idle()

The schedule part works, I just don`t know how to send this Message.
Thanks for your help!

Body:
Update object, inside of the message field, has the from field which is a User Telegram object containing the user's ID.

Once you have the user's ID, you can use the sendMessage method in order to reply him easily.

To conclude, instead of:

update.message.reply_text('Welcome!')

You could do like so:

user_id = update.message.from.id
updater.sendmessage(chat_id=user_id, text="Welcome!")


问:
GLTF Loader Trial Returning TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../"
Im fairly new at three.js and am trying to load a model into my canvas. as soon as I import the GLTFLoader, I get the above reading in the console. What is going on? The syntax and relative paths looks fine. I dont really understand whats going on. I added another folder to put the master three.js folder into but it is not working.

import * as THREE from '../master/three.js-master/build/three.module.js'
import {GLTFLoader} from '../master/three.js-master/examples/jsm/loaders/GLTFLoader.js'
const canvas = document.querySelector('.webgl')
const scene = new THREE.Scene()

const loader = new GLTFLoader()
loader.load('../assets/scene.gltf', function(gltf){
  console.log(gltf);
  const root = gltf.scene;
  scene.add(root);
}, function(xhr){
  console.log((xhr.loaded/xhr.total * 100) + "% loaded")
}, function(error){
  console.log('error');
})

// const geometry = new THREE.BoxGeometry(1,1,1)
// const material = new THREE.MeshBasicMaterial({
//   color: 'green'
// })

const boxMesh = new THREE.Mesh(geometry,material)
scene.add(boxMesh)

//Boiler Plate

const sizes = {
  width: window.innerWidth,
  height: window.innerHeight,
}

const camera = new THREE.PerspectiveCamera(75, sizes.width/sizes.height, 0.1, 100)
camera.position.set(0,1,2)
scene.add(camera)

const renderer = new THREE.WebGLRenderer({
  canvas: canvas
})

renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
renderer.shadowMap.enabled = true
// renderer.outputEncoding = true
renderer.render(scene, camera)

console.log('working')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Landing Page</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas class="webgl"></canvas>
    <script type = "module" src="scripts.js"></script>
    <script>

    </script>
</body>
</html></code>```

答:
Since r137 using ES6 modules like GLTFLoader in the browser requires an import map. Add the following section right below you canvas.

```<code><!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

<script type="importmap">
    {
        "imports": {
            "three": "../master/three.js-master/build/three.module.js"
        }
    }
</script>
</code>```

The three.js import statement in your scripts.js looks like so then:

import * as THREE from 'three'
```

Body:
Im fairly new at three.js and am trying to load a model into my canvas. as soon as I import the GLTFLoader, I get the above reading in the console. What is going on? The syntax and relative paths looks fine. I dont really understand whats going on. I added another folder to put the master three.js folder into but it is not working.

import * as THREE from '../master/three.js-master/build/three.module.js'
import {GLTFLoader} from '../master/three.js-master/examples/jsm/loaders/GLTFLoader.js'
const canvas = document.querySelector('.webgl')
const scene = new THREE.Scene()

const loader = new GLTFLoader()
loader.load('../assets/scene.gltf', function(gltf){
  console.log(gltf);
  const root = gltf.scene;
  scene.add(root);
}, function(xhr){
  console.log((xhr.loaded/xhr.total * 100) + "% loaded")
}, function(error){
  console.log('error');
})

// const geometry = new THREE.BoxGeometry(1,1,1)
// const material = new THREE.MeshBasicMaterial({
//   color: 'green'
// })

const boxMesh = new THREE.Mesh(geometry,material)
scene.add(boxMesh)

//Boiler Plate

const sizes = {
  width: window.innerWidth,
  height: window.innerHeight,
}

const camera = new THREE.PerspectiveCamera(75, sizes.width/sizes.height, 0.1, 100)
camera.position.set(0,1,2)
scene.add(camera)

const renderer = new THREE.WebGLRenderer({
  canvas: canvas
})

renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
renderer.shadowMap.enabled = true
// renderer.outputEncoding = true
renderer.render(scene, camera)

console.log('working')

<!DOCTYPE html>

    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Landing Page</title>
    <link rel="stylesheet" href="style.css">

    <canvas class="webgl"></canvas>

Body:
Since r137 using ES6 modules like GLTFLoader in the browser requires an import map. Add the following section right below you canvas.

<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

<script type="importmap">
    {
        "imports": {
            "three": "../master/three.js-master/build/three.module.js"
        }
    }
</script>

The three.js import statement in your scripts.js looks like so then:

import * as THREE from 'three'


问:
Program closing down when clicking on the screen
I'm a beginner trying to code a Tic Tac Toe program (using Python in VSC) with this video tutorial: https://www.youtube.com/watch?v=yniQ15A7MLk. But when I try to make the circle show up when clicked, the program closes down when I click on the screen and the terminal prints this error message:

```<code>TypeError: function missing required argument 'radius' (pos 4)
</code>```

I don't think it's the clicking function, since I get the results printed in text in the VSC terminal. But it doesn't show up in the program window. And I don't think it's something in the draw function, since I tried with an image instead and the same thing happened (program closing down when I clicked on the screen).

```<code>import pygame
import numpy

pygame.init()

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

height = 700
width = 700
line_thickness = 20

display = pygame.display.set_mode((height, width))
display.fill(black)

board = numpy.zeros((3, 3))

def lines():
    pygame.draw.line(display, white, (50, 250), (650, 250), line_thickness)
    pygame.draw.line(display, white, (50, 450), (650, 450), line_thickness)
    pygame.draw.line(display, white, (250, 50), (250, 650), line_thickness)
    pygame.draw.line(display, white, (450, 50), (450, 650), line_thickness)

lines()

square_size = 200
o_radius = 60
o_width = 15

def draw_figures():
    for row in range(3):
        for col in range(3):
            if board[row, col] == 1:
                pygame.draw.circle(display, red, ((int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width))

def marked_square(row, col, player):
    board[row, col] = player

def available_square(row, col):
    return board[row, col] == 0

player = 1

pygame.display.update()

running = True
while running:
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x = event.pos[0]
            mouse_y = event.pos[1]

            clicked_row = int(mouse_y // 200)
            clicked_col = int(mouse_x // 200)

            if available_square(clicked_row, clicked_col):
                if player == 1:
                    marked_square(clicked_row, clicked_row, 1)
                    player = 2

                elif player == 2:
                    marked_square(clicked_row, clicked_row, 2)
                    player = 1

                draw_figures()

                print(board)
</code>```

答:
in:

```<code>pygame.draw.circle(display, red, ((int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width))
</code>```

Your brackets are incorrect, so you only have 3 parameters

```<code>pygame.draw.circle(
    display,
    red,
    ((int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width)
    )
</code>```

I assume you mean

```<code>pygame.draw.circle(display, red, (int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width)
</code>```

It would probably be cleaner to have some helper variables

```<code>x = int(row * square_size + square_size // 2)
y = int(col * square_size + square_size // 2)
pygame.draw.circle(display, red, (x, y), o_radius, o_width)
</code>```

Body:
I'm a beginner trying to code a Tic Tac Toe program (using Python in VSC) with this video tutorial: https://www.youtube.com/watch?v=yniQ15A7MLk. But when I try to make the circle show up when clicked, the program closes down when I click on the screen and the terminal prints this error message:

TypeError: function missing required argument 'radius' (pos 4)

I don't think it's the clicking function, since I get the results printed in text in the VSC terminal. But it doesn't show up in the program window. And I don't think it's something in the draw function, since I tried with an image instead and the same thing happened (program closing down when I clicked on the screen).

import pygame
import numpy

pygame.init()

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

height = 700
width = 700
line_thickness = 20

display = pygame.display.set_mode((height, width))
display.fill(black)

board = numpy.zeros((3, 3))

def lines():
    pygame.draw.line(display, white, (50, 250), (650, 250), line_thickness)
    pygame.draw.line(display, white, (50, 450), (650, 450), line_thickness)
    pygame.draw.line(display, white, (250, 50), (250, 650), line_thickness)
    pygame.draw.line(display, white, (450, 50), (450, 650), line_thickness)

lines()

square_size = 200
o_radius = 60
o_width = 15

def draw_figures():
    for row in range(3):
        for col in range(3):
            if board[row, col] == 1:
                pygame.draw.circle(display, red, ((int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width))

def marked_square(row, col, player):
    board[row, col] = player

def available_square(row, col):
    return board[row, col] == 0

player = 1

pygame.display.update()

running = True
while running:
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x = event.pos[0]
            mouse_y = event.pos[1]

            clicked_row = int(mouse_y // 200)
            clicked_col = int(mouse_x // 200)

            if available_square(clicked_row, clicked_col):
                if player == 1:
                    marked_square(clicked_row, clicked_row, 1)
                    player = 2

                elif player == 2:
                    marked_square(clicked_row, clicked_row, 2)
                    player = 1

                draw_figures()

                print(board)

Body:
in:

pygame.draw.circle(display, red, ((int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width))

Your brackets are incorrect, so you only have 3 parameters

pygame.draw.circle(
    display,
    red,
    ((int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width)
    )

I assume you mean

pygame.draw.circle(display, red, (int(row * square_size + square_size // 2), int(col * square_size + square_size // 2)), o_radius, o_width)

It would probably be cleaner to have some helper variables

x = int(row * square_size + square_size // 2)
y = int(col * square_size + square_size // 2)
pygame.draw.circle(display, red, (x, y), o_radius, o_width)


问:
types of facebook application and their differences
I try to understand the difference betweeen a facebook canvaas application and a facebook enabled website. For me the only difference is that Canvas integrates into Facebook with an iFrame and Websites are stand allone.

But in terms of policy and functionality these two types look the same. Is this true or am I wrong?

答:
I have read the Platform Policies and there was an interesting definition:
By "Application" we mean canvas page application, Platform integration, or any other technical integration we have assigned an application identification number

I assume in terms of policy they are all treated the same way. One exeption: Games on canvas pages are obligated to use Facebook Credits.

In terms of functionality it seems that canvas pages have the advantage of sending requests and using bookmarks. Now for games there are additonal stories during playing.

ContentLicense: CC BY-SA 3.0


问:
Is there a way to have several yml file for one project?
I want to sperate some security fields such as usernames or passwords from my main application.yml file . in fact I want 2 yml file in my project , one for main configs and other for security fields.
Is there any way to do that ?

smaple:

Main yml file:

```<code>spring:
     application:
      name: My project
  datasource:
    driverClassName:  com.ibm.db2.jcc.DB2Driver
    username: username
    password: password
    url: url
.....
</code>```

security.yml

```<code>username: "username"
password: "password"
....
</code>```

答:
One option is to specify profile specific .yml files. These are then activated by activating the corresponding profile.

So you can create application-security.yml

And in your main yml file add:

```<code>spring:
  profiles:
    include:
      security
</code>```

Body:
I want to sperate some security fields such as usernames or passwords from my main application.yml file . in fact I want 2 yml file in my project , one for main configs and other for security fields.
Is there any way to do that ?

smaple:

Main yml file:

spring:
     application:
      name: My project
  datasource:
    driverClassName:  com.ibm.db2.jcc.DB2Driver
    username: username
    password: password
    url: url
.....

security.yml

username: "username"
password: "password"
....

Body:
One option is to specify profile specific .yml files. These are then activated by activating the corresponding profile.

So you can create application-security.yml

And in your main yml file add:

spring:
  profiles:
    include:
      security