问:
Java project does not compile after switching from Maven to Gradle with "cannot find symbol" errors
I had a Maven project, which I then switched to Gradle. I am now attempting to compile the Gradle project, but it isn't compiling, even if it was building and compiling successfully when I used Maven.

I ran gradle init to convert my project to Gradle and it stopped compiling and gave me the "cannot find symbol" errors. It seems as though Gradle cannot find many classes, including the Main class.

I have effectively read through the post: What does a "Cannot find symbol" or "Cannot resolve symbol" error mean? and I was unable to fix my issue. I know it's a compilation error, but I don't know what's causing it. I didn't change the code when I switched from Maven to Gradle, only the build files.

Here is an example of one of the errors:

```<code>        Main instance = Main.getInstance();
                            ^
  symbol:   method getInstance()
  location: class Main
</code>```

Note: the build is a multi-project build. It has several subprojects. Here is the mother build.gradle file:

plugins {
    id "java"
    id "com.github.johnrengelman.shadow" version "7.1.2"
    id "war"
}

group "net.pixlies"
version "1.0-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

subprojects {
    compileJava.options.encoding = "UTF-8"

    apply plugin: "java"
    apply plugin: "war"
    apply plugin: "com.github.johnrengelman.shadow"

    compileJava {
        sourceCompatibility = 17
        targetCompatibility = 17
    }
}

repositories {
    mavenCentral()
    maven { url "https://repo.purpurmc.org/snapshots/" }
    maven { url "https://repo.extendedclip.com/content/repositories/placeholderapi/" }
    maven { url "https://repo.aikar.co/content/groups/aikar/" }
    maven { url "https://repo.dmulloy2.net/repository/public/" }
}

dependencies {
    implementation "org.mongodb:mongo-java-driver:3.12.11"
    implementation "commons-io:commons-io:2.11.0"
    implementation "co.aikar:acf-paper:0.5.1-SNAPSHOT"
    implementation "org.ocpsoft.prettytime:prettytime:5.0.3.Final"
    implementation "commons-lang:commons-lang:2.6"
}
```
<p>Here is the settings.gradle file:</p>
```pluginManagement {
    repositories {
        gradlePluginPortal()
        maven { url "https://papermc.io/repo/repository/maven-public/" }
    }
}

rootProject.name = 'version-two'

include(':PixliesCore')
include(':LobbyModule')
include(':MiniMick')
include(':ProtoBusiness')
include(':PixliesFun')
include(':Nations')
include(':DiploMaurice')
include(':PixliesProxyCore')
```
<p>The PixliesCore project is having these issues with the "Cannot find symbol" error. Here is the <code>PixliesCore</code> subproject build.gradle file:</p>
<pre class="lang-clj prettyprint-override"><code>plugins {
    id 'net.pixlies.java-conventions'
}

dependencies {
    implementation 'com.github.stefvanschie.inventoryframework:IF:0.10.7'
    implementation 'org.projectlombok:lombok:1.18.24'
    implementation 'redis.clients:jedis:4.2.3'
    implementation 'joda-time:joda-time:2.11.1'
    compileOnly 'org.purpurmc.purpur:purpur-api:1.19-R0.1-SNAPSHOT'
    compileOnly 'com.comphenix.protocol:ProtocolLib:4.7.0'
    compileOnly 'me.clip:placeholderapi:2.11.2'
    compileOnly 'net.luckperms:api:5.4'
}

description = 'PixliesCore'
</code>```

I also ran ./gradlew assemble in the mother project's directory. Here is the output:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':PixliesCore:compileJava'.
> invalid source release: 17
</code>```

Perhaps this "invalid source release" is the cause, but I do not know what it means or how to fix it. I'm using the Java 17 SDK for everything.

Oh, also, here is the original POM.xml for the mother project:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <modules>
        <module>PixliesCore</module>
        <module>Nations</module>
        <module>MiniMick</module>
        <module>LobbyModule</module>
        <module>PixliesFun</module>
        <module>PixliesProxyCore</module>
        <module>DiploMaurice</module>
        <module>ProtoBusiness</module>
    </modules>

    <groupId>net.pixlies</groupId>
    <artifactId>version-two</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.11</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>co.aikar</groupId>
            <artifactId>acf-paper</artifactId>
            <version>0.5.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.ocpsoft.prettytime</groupId>
            <artifactId>prettytime</artifactId>
            <version>5.0.3.Final</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>purpur</id>
            <url>https://repo.purpurmc.org/snapshots</url>
        </repository>
        <repository>
            <id>aikar</id>
            <url>https://repo.aikar.co/content/groups/aikar/</url>
        </repository>
            <repository>
                <id>placeholderapi</id>
                <url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
            </repository>
        <repository>
            <id>dmulloy2-repo</id>
            <url>https://repo.dmulloy2.net/repository/public/</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>16</source>
                    <target>16</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

And the POM.xml for the PixliesCore subproject:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>version-two</artifactId>
        <groupId>net.pixlies</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>PixliesCore</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>aikar</id>
            <url>https://repo.aikar.co/content/groups/aikar/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.github.stefvanschie.inventoryframework</groupId>
            <artifactId>IF</artifactId>
            <version>0.10.7</version>
        </dependency>
        <dependency>
            <groupId>org.purpurmc.purpur</groupId>
            <artifactId>purpur-api</artifactId>
            <version>1.19-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>com.comphenix.protocol</groupId>
            <artifactId>ProtocolLib</artifactId>
            <version>4.7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>me.clip</groupId>
            <artifactId>placeholderapi</artifactId>
            <version>2.11.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.12.2</version>
        </dependency>
        <dependency>
            <groupId>net.luckperms</groupId>
            <artifactId>api</artifactId>
            <version>5.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <pluginRepositories>
        <pluginRepository>
            <id>maven-snapshots</id>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <build>
        <defaultGoal>clean package</defaultGoal>
        <finalName>PixliesCore</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.3.1-SNAPSHOT</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Body:
I had a Maven project, which I then switched to Gradle. I am now attempting to compile the Gradle project, but it isn't compiling, even if it was building and compiling successfully when I used Maven.

I ran gradle init to convert my project to Gradle and it stopped compiling and gave me the "cannot find symbol" errors. It seems as though Gradle cannot find many classes, including the Main class.

I have effectively read through the post: What does a "Cannot find symbol" or "Cannot resolve symbol" error mean? and I was unable to fix my issue. I know it's a compilation error, but I don't know what's causing it. I didn't change the code when I switched from Maven to Gradle, only the build files.

Here is an example of one of the errors:

        Main instance = Main.getInstance();
                            ^
  symbol:   method getInstance()
  location: class Main

Note: the build is a multi-project build. It has several subprojects. Here is the mother build.gradle file:

plugins {
    id "java"
    id "com.github.johnrengelman.shadow" version "7.1.2"
    id "war"
}

group "net.pixlies"
version "1.0-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

subprojects {
    compileJava.options.encoding = "UTF-8"

    apply plugin: "java"
    apply plugin: "war"
    apply plugin: "com.github.johnrengelman.shadow"

    compileJava {
        sourceCompatibility = 17
        targetCompatibility = 17
    }
}

repositories {
    mavenCentral()
    maven { url "https://repo.purpurmc.org/snapshots/" }
    maven { url "https://repo.extendedclip.com/content/repositories/placeholderapi/" }
    maven { url "https://repo.aikar.co/content/groups/aikar/" }
    maven { url "https://repo.dmulloy2.net/repository/public/" }
}

dependencies {
    implementation "org.mongodb:mongo-java-driver:3.12.11"
    implementation "commons-io:commons-io:2.11.0"
    implementation "co.aikar:acf-paper:0.5.1-SNAPSHOT"
    implementation "org.ocpsoft.prettytime:prettytime:5.0.3.Final"
    implementation "commons-lang:commons-lang:2.6"
}

Here is the settings.gradle file:

pluginManagement {
    repositories {
        gradlePluginPortal()
        maven { url "https://papermc.io/repo/repository/maven-public/" }
    }
}

rootProject.name = 'version-two'

include(':PixliesCore')
include(':LobbyModule')
include(':MiniMick')
include(':ProtoBusiness')
include(':PixliesFun')
include(':Nations')
include(':DiploMaurice')
include(':PixliesProxyCore')

The PixliesCore project is having these issues with the "Cannot find symbol" error. Here is the PixliesCore subproject build.gradle file:

plugins {
    id 'net.pixlies.java-conventions'
}

dependencies {
    implementation 'com.github.stefvanschie.inventoryframework:IF:0.10.7'
    implementation 'org.projectlombok:lombok:1.18.24'
    implementation 'redis.clients:jedis:4.2.3'
    implementation 'joda-time:joda-time:2.11.1'
    compileOnly 'org.purpurmc.purpur:purpur-api:1.19-R0.1-SNAPSHOT'
    compileOnly 'com.comphenix.protocol:ProtocolLib:4.7.0'
    compileOnly 'me.clip:placeholderapi:2.11.2'
    compileOnly 'net.luckperms:api:5.4'
}

description = 'PixliesCore'

I also ran ./gradlew assemble in the mother project's directory. Here is the output:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':PixliesCore:compileJava'.
> invalid source release: 17

Perhaps this "invalid source release" is the cause, but I do not know what it means or how to fix it. I'm using the Java 17 SDK for everything.

Oh, also, here is the original POM.xml for the mother project:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <modules>
        <module>PixliesCore</module>
        <module>Nations</module>
        <module>MiniMick</module>
        <module>LobbyModule</module>
        <module>PixliesFun</module>
        <module>PixliesProxyCore</module>
        <module>DiploMaurice</module>
        <module>ProtoBusiness</module>
    </modules>

    <groupId>net.pixlies</groupId>
    <artifactId>version-two</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.11</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>co.aikar</groupId>
            <artifactId>acf-paper</artifactId>
            <version>0.5.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.ocpsoft.prettytime</groupId>
            <artifactId>prettytime</artifactId>
            <version>5.0.3.Final</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>purpur</id>
            <url>https://repo.purpurmc.org/snapshots</url>
        </repository>
        <repository>
            <id>aikar</id>
            <url>https://repo.aikar.co/content/groups/aikar/</url>
        </repository>
            <repository>
                <id>placeholderapi</id>
                <url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
            </repository>
        <repository>
            <id>dmulloy2-repo</id>
            <url>https://repo.dmulloy2.net/repository/public/</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>16</source>
                    <target>16</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

And the POM.xml for the PixliesCore subproject:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>version-two</artifactId>
        <groupId>net.pixlies</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>PixliesCore</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>aikar</id>
            <url>https://repo.aikar.co/content/groups/aikar/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.github.stefvanschie.inventoryframework</groupId>
            <artifactId>IF</artifactId>
            <version>0.10.7</version>
        </dependency>
        <dependency>
            <groupId>org.purpurmc.purpur</groupId>
            <artifactId>purpur-api</artifactId>
            <version>1.19-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>com.comphenix.protocol</groupId>
            <artifactId>ProtocolLib</artifactId>
            <version>4.7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>me.clip</groupId>
            <artifactId>placeholderapi</artifactId>
            <version>2.11.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.12.2</version>
        </dependency>
        <dependency>
            <groupId>net.luckperms</groupId>
            <artifactId>api</artifactId>
            <version>5.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <pluginRepositories>
        <pluginRepository>
            <id>maven-snapshots</id>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <build>
        <defaultGoal>clean package</defaultGoal>
        <finalName>PixliesCore</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.3.1-SNAPSHOT</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


来源: stackexchange

问:
Error in IPv6 increment script (bash) - can't find the mistake
per my last question, I managed to increment a given IPv6 Address by 1 to have the next possible address - hooray it works :)

But only until I hit the :ffff IP - the next would obviously be :1:0000 but my script is not "behaving" in a sane way - and I cannot figure out why :(

```<code>#!/bin/bash

initialipv6address="2001:0000:0000:0000:0000:0000:0000:ffff"
echo $initialipv6address

function ipv6_increment {
  IFS=':' read -r -a fields <<< "$initialipv6address"

  carry=1

  for ((i=${#fields[@]}-1; i>=0; i--)); do
    fields[$i]=$((16#${fields[i]}+carry))

    if [[ ${fields[$i]} -ge 65536 ]]; then
      carry=1
      fields[$i]=$((16#${fields[i]}-65536))
    else
      carry=0
    fi
  done

  printf "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n" "${fields[@]}"
}

newipv6address=$(ipv6_increment "$initialipv6address")
echo "$newipv6address"
</code>```

Output expected:

```<code>2001:0000:0000:0000:0000:0000:0000:ffff
2001:0000:0000:0000:0000:0000:0001:0000
</code>```

Output is in reality:

```<code>2001:0000:0000:0000:0000:0000:0000:ffff
2001:0000:0000:0000:0000:0000:0001:55536 <-- WTF?????
</code>```

It seems like it correctly sets the value to 1 but I cannot figure out where the 55536 is coming from :(

ContentLicense: CC BY-SA 4.0

Body:
per my last question, I managed to increment a given IPv6 Address by 1 to have the next possible address - hooray it works :)

But only until I hit the :ffff IP - the next would obviously be :1:0000 but my script is not "behaving" in a sane way - and I cannot figure out why :(

#!/bin/bash

initialipv6address="2001:0000:0000:0000:0000:0000:0000:ffff"
echo $initialipv6address

function ipv6_increment {
  IFS=':' read -r -a fields <<< "$initialipv6address"

  carry=1

  for ((i=${#fields[@]}-1; i>=0; i--)); do
    fields[$i]=$((16#${fields[i]}+carry))

    if [[ ${fields[$i]} -ge 65536 ]]; then
      carry=1
      fields[$i]=$((16#${fields[i]}-65536))
    else
      carry=0
    fi
  done

  printf "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n" "${fields[@]}"
}

newipv6address=$(ipv6_increment "$initialipv6address")
echo "$newipv6address"

Output expected:

2001:0000:0000:0000:0000:0000:0000:ffff
2001:0000:0000:0000:0000:0000:0001:0000

Output is in reality:

2001:0000:0000:0000:0000:0000:0000:ffff
2001:0000:0000:0000:0000:0000:0001:55536 <-- WTF?????

It seems like it correctly sets the value to 1 but I cannot figure out where the 55536 is coming from :(


问:
ot-ctl connect session failed: No such file or directory
otbr-agent.service is not running when checking status.

Please suggest how to fix.

I have only tried to browse other forms to find a solution, however it is still not clear to me how to fix this. I'm new to this so please be explicit in your answer.


问:
I keep getting the error unkown option -style trying to change background color of gui with tkinter in python
Firstly im a complete beginner in coding in general. Currently im trying to code a gui which allows to download yt videos.

Im trying to change the background color of this gui to blue but I keep getting the error "unkown option "-style""


问:
why localhost is not loading after building with docker compose
I have a basic app without a database

```<code>client
 src
  scripts
   app.js
 dockerfile
 package.json

server
 app.js
 dockerfile
 package.json
</code>```

client dockerfile

```<code>FROM node
WORKDIR /client
RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm
COPY package.json .
RUN pnpm install
COPY . .
EXPOSE 3000
CMD ["pnpm", "start"]
</code>```

server dockerfile

```<code>FROM node
WORKDIR /app
RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm
COPY ./package.json .
RUN pnpm install
COPY . .
EXPOSE 80
CMD ["pnpm", "start"]
</code>```

root folder docker-compose.yaml

```<code>version: "3.8"
services:
  server:
    build: ./server
    restart: always
    ports:
      - "80:80"
    volumes:
      - logs:/app/logs
      - ./server:/app
      - /app/node_modules
  client:
    build: ./client
    restart: always
    ports:
      - "3000:3000"
    volumes:
      - ./client/src:/app/src
    stdin_open: true
    tty: true

volumes:
  data:
  logs:
</code>```

on the terminal I ran docker compose build which was successful
then docker compose up which seems to be working
but when I go to localhost:3000 or 8080 nothing is working

any suggestions ?

Body:
I have a basic app without a database

client
 src
  scripts
   app.js
 dockerfile
 package.json

server
 app.js
 dockerfile
 package.json

client dockerfile

FROM node
WORKDIR /client
RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm
COPY package.json .
RUN pnpm install
COPY . .
EXPOSE 3000
CMD ["pnpm", "start"]

server dockerfile

FROM node
WORKDIR /app
RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm
COPY ./package.json .
RUN pnpm install
COPY . .
EXPOSE 80
CMD ["pnpm", "start"]

root folder docker-compose.yaml

version: "3.8"
services:
  server:
    build: ./server
    restart: always
    ports:
      - "80:80"
    volumes:
      - logs:/app/logs
      - ./server:/app
      - /app/node_modules
  client:
    build: ./client
    restart: always
    ports:
      - "3000:3000"
    volumes:
      - ./client/src:/app/src
    stdin_open: true
    tty: true

volumes:
  data:
  logs:

on the terminal I ran docker compose build which was successful
then docker compose up which seems to be working
but when I go to localhost:3000 or 8080 nothing is working

any suggestions ?


问:
Create volumes only from docker-compose file without downloading images
I've asked a similar question here, missed some details which changes the question a bit.

The infrastructure is described in multiple ´docker-compose` files split in multiple projects. Within each project, volumes are created as part of the compose file.

In addition to that, there is a separate project for backup and restore, which mount the volumes as external volumes. Considering the restore options, I'm facing the problem that I need to create the volumes from aforementioned docker-compose projects, such that the restore container can mount them and restore the data to it.

The previous answer mentioned docker-compose up --no-start --no-deps, which does create the volumes, but also downloads the images and creates the containers. In a restore situation, the docker registry storing the images is not available yet, as it's a service running in the same infrastructure.

So the question: how can I create only the volumes out of a docker-compose environment, without the need that the referenced images can be downloaded?


问:
Extracting the relevant text from an email stored in pandas column
I have a situation in which there are several emails that are stored in a pandas column, some emails are lengthy and some are precise. I wanted to understand how to extract the actual body of that email, even if there are multiple responses on the same email. For example:

df:

```<code> email                                                                        clean_email
                                                                              Query Hello Please can someone advise?
<xx@gmail.com> Sent: 10 January 2021 13:12 To: yy@gmail.com>
Query Hello Please can someone advise?
</code>```

I want to achieve the output as shown in the clean_email column. Is there a method to achieve this sort of transformation? There are around 10k emails in this email column with probably different email structures. The ask is to extract the actual body from these emails

Body:
I have a situation in which there are several emails that are stored in a pandas column, some emails are lengthy and some are precise. I wanted to understand how to extract the actual body of that email, even if there are multiple responses on the same email. For example:

df:

 email                                                                        clean_email
                                                                              Query Hello Please can someone advise?
<xx@gmail.com> Sent: 10 January 2021 13:12 To: yy@gmail.com>
Query Hello Please can someone advise?

I want to achieve the output as shown in the clean_email column. Is there a method to achieve this sort of transformation? There are around 10k emails in this email column with probably different email structures. The ask is to extract the actual body from these emails


问:
Gradient Colors with ngStyle in ion-card
I have an ion-card repeated in page each time it display take different color base on array from classlist.page.ts so instead of using normal colors I want to use this gradient color

```<code>background-image: linear-gradient(to right top, #ff8008, #ff930d, #ffa619, #ffb727, #ffc837);
background-image: linear-gradient(to right top, #1d976c, #40af7f, #5cc792, #78e0a5, #93f9b9);
background-image: linear-gradient(to right top, #eb3349, #ee3f47, #f04946, #f25344, #f45c43);
</code>```

classlist.page.html

```<code><ion-card
*ngFor="let course of classes"
class="cards-description"
[ngStyle]="{'background': course.backgroundColor}"
(click)="openClassStudents(course)"
>
</ion-card>
</code>```

classlist.page.ts

```<code>@member classBackgroundColor used for background color of class

classBackgroundColor = [
    "#ff7043",
    "#2962ff",
    "#43a047",
    "#6d4c41",
    "#ffab00",
    "#00b0ff",
    "#651fff",
    "#2962ff",
    "#d81b60",
    "#6a1b9a",
  ];

if (courses && courses.length > 0) {
            let i = 0;
            this.classes = courses;
            this.reorderList = [];
            this.classes.forEach((course) => {
              course.backgroundColor = this.classBackgroundColor[i];
              i++;
              if (i == 9) i = 0;
            });
          } else {
            this.noDataFound = this.lang.no_class_found;
            this.classes = [];
            this.reorderList = [];
          }
</code>```

Body:
I have an ion-card repeated in page each time it display take different color base on array from classlist.page.ts so instead of using normal colors I want to use this gradient color

background-image: linear-gradient(to right top, #ff8008, #ff930d, #ffa619, #ffb727, #ffc837);
background-image: linear-gradient(to right top, #1d976c, #40af7f, #5cc792, #78e0a5, #93f9b9);
background-image: linear-gradient(to right top, #eb3349, #ee3f47, #f04946, #f25344, #f45c43);

classlist.page.html

<ion-card
*ngFor="let course of classes"
class="cards-description"
[ngStyle]="{'background': course.backgroundColor}"
(click)="openClassStudents(course)"
>
</ion-card>

classlist.page.ts

@member classBackgroundColor used for background color of class

classBackgroundColor = [
    "#ff7043",
    "#2962ff",
    "#43a047",
    "#6d4c41",
    "#ffab00",
    "#00b0ff",
    "#651fff",
    "#2962ff",
    "#d81b60",
    "#6a1b9a",
  ];

if (courses && courses.length > 0) {
            let i = 0;
            this.classes = courses;
            this.reorderList = [];
            this.classes.forEach((course) => {
              course.backgroundColor = this.classBackgroundColor[i];
              i++;
              if (i == 9) i = 0;
            });
          } else {
            this.noDataFound = this.lang.no_class_found;
            this.classes = [];
            this.reorderList = [];
          }


问:
Git works in cmd , but not in powersehll
I'm trying to use git --version in powershell but it doesn't execute the command, instead it opens a window asking how I want to open this file.

If I try to run it in cmd it works

Already tried to uninstall git, installed, and not functional.
I've also tried changing the environment variables, but to no avail.


问:
copyNextSampleBuffer hanging for AVAssetReaderTrackOutput
I am trying to create a video compression tool which simply takes in a video file URL, compresses it, and returns the new URL in swift 5 for ios 16.

I have been following a few tutorials online, but they all use functions which have since been deprecated, so I have put together this code here which is a refactoring from various sources:

```<code>import Foundation
import AVFoundation

class VideoCompressorModel: ObservableObject {
    let bitrate = 2_500_000 // MBPs

    func compressFile(urlToCompress: URL, outputURL: URL, completionHandler:@escaping (URL?)->Void) async {
        let asset = AVAsset(url: urlToCompress);
        //create asset reader

        var assetReader: AVAssetReader?
        do{
            assetReader = try AVAssetReader(asset: asset)
        } catch{
            assetReader = nil
        }

        guard let reader = assetReader else{
            completionHandler(nil)
            return
        }
        var videoTrack: AVAssetTrack?
        var audioTrack: AVAssetTrack?

        do {
            videoTrack = try await asset.loadTracks(withMediaType: AVMediaType.video).first
            audioTrack = try await asset.loadTracks(withMediaType: AVMediaType.audio).first
        } catch {
            completionHandler(nil)
            return
        }

        guard let videoTrack, let audioTrack else {
            completionHandler(nil)
            return
        }

        let videoReaderSettings: [String:Any] =  [kCVPixelBufferPixelFormatTypeKey as String:kCVPixelFormatType_32ARGB ]

        // ADJUST BIT RATE OF VIDEO HERE
        var videoSettings: [String:Any]?
        do {
           videoSettings = await [
                AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey:self.bitrate],
                AVVideoCodecKey: AVVideoCodecType.h264,
                AVVideoHeightKey: try videoTrack.load(.naturalSize).height,
                AVVideoWidthKey: try videoTrack.load(.naturalSize).width
            ]
        } catch {
            completionHandler(nil)
            return
        }
        guard let videoSettings else {
            completionHandler(nil)
            return
        }

        let audioSettings = [
            AVSampleRateKey: 44100,
            AVFormatIDKey: kAudioFormatLinearPCM
        ]

        let assetReaderVideoOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoReaderSettings)
        let assetReaderAudioOutput = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: audioSettings)

        if reader.canAdd(assetReaderVideoOutput){
            reader.add(assetReaderVideoOutput)
        }else{
            completionHandler(nil)
            return
        }

        if reader.canAdd(assetReaderAudioOutput){
            reader.add(assetReaderAudioOutput)
        } else{
            completionHandler(nil)
            return
        }

        let audioInput = AVAssetWriterInput(mediaType: AVMediaType.audio, outputSettings: nil)
        let videoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
        do {
            videoInput.transform = try await videoTrack.load(.preferredTransform)
        } catch{
            completionHandler(nil)
            return
        }
        //we need to add samples to the video input

        let videoInputQueue = DispatchQueue(label: "videoQueue")
        let audioInputQueue = DispatchQueue(label: "audioQueue")

        var assetWriter: AVAssetWriter?
        do{
            assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.mov)
        } catch {
            assetWriter = nil
        }

        guard let assetWriter else{
            completionHandler(nil)
            return
        }

        assetWriter.shouldOptimizeForNetworkUse = true
        assetWriter.add(videoInput)
        assetWriter.add(audioInput)

        assetWriter.startWriting()
        reader.startReading()
        assetWriter.startSession(atSourceTime: CMTime.zero)

        let closeWriterBothDone:()->Void = {
            assetWriter.finishWriting(completionHandler: {
                completionHandler((assetWriter.outputURL))
            })
            reader.cancelReading()
        }

        print("STARTING ")

        let closeWriterAudioDone:()->Void = {
            print("FINISHED AUDIO")
            videoInput.requestMediaDataWhenReady(on: videoInputQueue) {
                while(videoInput.isReadyForMoreMediaData){
                    let sample = assetReaderVideoOutput.copyNextSampleBuffer()
                    if (sample != nil){
                        videoInput.append(sample!)
                    } else{
                        videoInput.markAsFinished()
                        DispatchQueue.main.async {
                            closeWriterBothDone()
                        }
                        break;
                    }
                }

            }
        }

        audioInput.requestMediaDataWhenReady(on: audioInputQueue) {
            while(audioInput.isReadyForMoreMediaData){
                let sample = assetReaderAudioOutput.copyNextSampleBuffer()
                print("hi")
                if (sample != nil){
                    audioInput.append(sample!)
                } else{
                    audioInput.markAsFinished()
                    DispatchQueue.main.async {
                        closeWriterAudioDone()
                    }
                    break;
                }
            }
        }
    }
}

</code>```

The issue that occurs is that copyNextSampleBuffer for the audio track output hangs after a few calls. I test this simply by having a print("hi") which only gets called a handful of times before the code blocks.

I have tried changing the audio options provided to AVAssetReaderTrackOutput, which I originally had simply as nil, and this only had the effect of increasing the number of times copyNextSampleBuffer gets called before it freezes.

Perhaps there is a better way overall to compress video in newer versions of swift, as this seems somewhat unelegant? If not, is there any bugs in my code that is causing it to hang?

Body:
I am trying to create a video compression tool which simply takes in a video file URL, compresses it, and returns the new URL in swift 5 for ios 16.

I have been following a few tutorials online, but they all use functions which have since been deprecated, so I have put together this code here which is a refactoring from various sources:

import Foundation
import AVFoundation

class VideoCompressorModel: ObservableObject {
    let bitrate = 2_500_000 // MBPs

    func compressFile(urlToCompress: URL, outputURL: URL, completionHandler:@escaping (URL?)->Void) async {
        let asset = AVAsset(url: urlToCompress);
        //create asset reader

        var assetReader: AVAssetReader?
        do{
            assetReader = try AVAssetReader(asset: asset)
        } catch{
            assetReader = nil
        }

        guard let reader = assetReader else{
            completionHandler(nil)
            return
        }
        var videoTrack: AVAssetTrack?
        var audioTrack: AVAssetTrack?

        do {
            videoTrack = try await asset.loadTracks(withMediaType: AVMediaType.video).first
            audioTrack = try await asset.loadTracks(withMediaType: AVMediaType.audio).first
        } catch {
            completionHandler(nil)
            return
        }

        guard let videoTrack, let audioTrack else {
            completionHandler(nil)
            return
        }

        let videoReaderSettings: [String:Any] =  [kCVPixelBufferPixelFormatTypeKey as String:kCVPixelFormatType_32ARGB ]

        // ADJUST BIT RATE OF VIDEO HERE
        var videoSettings: [String:Any]?
        do {
           videoSettings = await [
                AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey:self.bitrate],
                AVVideoCodecKey: AVVideoCodecType.h264,
                AVVideoHeightKey: try videoTrack.load(.naturalSize).height,
                AVVideoWidthKey: try videoTrack.load(.naturalSize).width
            ]
        } catch {
            completionHandler(nil)
            return
        }
        guard let videoSettings else {
            completionHandler(nil)
            return
        }

        let audioSettings = [
            AVSampleRateKey: 44100,
            AVFormatIDKey: kAudioFormatLinearPCM
        ]

        let assetReaderVideoOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoReaderSettings)
        let assetReaderAudioOutput = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: audioSettings)

        if reader.canAdd(assetReaderVideoOutput){
            reader.add(assetReaderVideoOutput)
        }else{
            completionHandler(nil)
            return
        }

        if reader.canAdd(assetReaderAudioOutput){
            reader.add(assetReaderAudioOutput)
        } else{
            completionHandler(nil)
            return
        }

        let audioInput = AVAssetWriterInput(mediaType: AVMediaType.audio, outputSettings: nil)
        let videoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
        do {
            videoInput.transform = try await videoTrack.load(.preferredTransform)
        } catch{
            completionHandler(nil)
            return
        }
        //we need to add samples to the video input

        let videoInputQueue = DispatchQueue(label: "videoQueue")
        let audioInputQueue = DispatchQueue(label: "audioQueue")

        var assetWriter: AVAssetWriter?
        do{
            assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.mov)
        } catch {
            assetWriter = nil
        }

        guard let assetWriter else{
            completionHandler(nil)
            return
        }

        assetWriter.shouldOptimizeForNetworkUse = true
        assetWriter.add(videoInput)
        assetWriter.add(audioInput)

        assetWriter.startWriting()
        reader.startReading()
        assetWriter.startSession(atSourceTime: CMTime.zero)

        let closeWriterBothDone:()->Void = {
            assetWriter.finishWriting(completionHandler: {
                completionHandler((assetWriter.outputURL))
            })
            reader.cancelReading()
        }

        print("STARTING ")

        let closeWriterAudioDone:()->Void = {
            print("FINISHED AUDIO")
            videoInput.requestMediaDataWhenReady(on: videoInputQueue) {
                while(videoInput.isReadyForMoreMediaData){
                    let sample = assetReaderVideoOutput.copyNextSampleBuffer()
                    if (sample != nil){
                        videoInput.append(sample!)
                    } else{
                        videoInput.markAsFinished()
                        DispatchQueue.main.async {
                            closeWriterBothDone()
                        }
                        break;
                    }
                }

            }
        }

        audioInput.requestMediaDataWhenReady(on: audioInputQueue) {
            while(audioInput.isReadyForMoreMediaData){
                let sample = assetReaderAudioOutput.copyNextSampleBuffer()
                print("hi")
                if (sample != nil){
                    audioInput.append(sample!)
                } else{
                    audioInput.markAsFinished()
                    DispatchQueue.main.async {
                        closeWriterAudioDone()
                    }
                    break;
                }
            }
        }
    }
}

The issue that occurs is that copyNextSampleBuffer for the audio track output hangs after a few calls. I test this simply by having a print("hi") which only gets called a handful of times before the code blocks.

I have tried changing the audio options provided to AVAssetReaderTrackOutput, which I originally had simply as nil, and this only had the effect of increasing the number of times copyNextSampleBuffer gets called before it freezes.

Perhaps there is a better way overall to compress video in newer versions of swift, as this seems somewhat unelegant? If not, is there any bugs in my code that is causing it to hang?


问:
AWS Cognito Auth Role
I saw in the AWS docs that for your web app to get credentials from AWS via JS in a way that doesn't involve hardcoding, AWS Cognito is the way to go. However, when I create a cognito identity pool, an Auth and UnAuth role get created in IAM. However, my web app uses firebase to help handle login and authentication of users. When I tried using Cognito to get the credentials within a page in the web app that's only accessible by auth users, AWS is assuming the "UnAuth role" and because of that, I'm not able to run a task on ECS due to scope down. How do you force cognito identity pool to assume the Auth Cognito IAM role in the AWS Javascript V3 SDK. Can someone please help me out? It'd be a nice holiday miracle and you'd be doing a good deed to the developer community :)</p>

Title: AWS Cognito Auth Role


问:
keras Sequence generator with named inputs and batching merges batches and first dimension together
Given a keras Sequence with a __getitem__ method that returns a x, y batch in the following format:

```<code>x = [
 { 'input_1': [ 4123, 123, ... ], .... }, # item 1 x
 { 'input_1': [ 1123, 4123, ... ], .... } # item 2 x
]
y = [
 { 'output_1': 4123, .... }, # item 1 y
 { 'output_1': 4123, .... } # item 2 y
]
</code>```

Each named input is a column in a time series.

I am using the functional API configuration and I have configured the inputs that I am passing to Model(inputs=..., outputs=...) in the following way:

```<code>inputs = [ Input(batch_size=128, shape=timeseries_length, name='input_1'), .... ]

# features_length = len(inputs) for reference
</code>```

To test something I concatenated them together in the following way:

```<code>x = Concatenate(axis = -2)([ tensorflow.expand_dims(_input, -2) for _input in inputs ])
print(x.shape) # (batch_size, features_length, timeseries_length)
</code>```

When I run model.fit with the Sequence passed as it's data generator and batch_size specified I received the following:

```<code>ValueError: Layer "model" expects [num_input_columns] input(s), but it received [features_length * batch_size] input tensors.
</code>```

The batch_size and features_length dimensions got merged into one dimension for some reason.

Is the format the Sequence is supposed to return for batched named inputs different?

Should the generator give a dictionary of batches instead of batches of dictionaries?

Body:
Given a keras Sequence with a __getitem__ method that returns a x, y batch in the following format:

x = [
 { 'input_1': [ 4123, 123, ... ], .... }, # item 1 x
 { 'input_1': [ 1123, 4123, ... ], .... } # item 2 x
]
y = [
 { 'output_1': 4123, .... }, # item 1 y
 { 'output_1': 4123, .... } # item 2 y
]

Each named input is a column in a time series.

I am using the functional API configuration and I have configured the inputs that I am passing to Model(inputs=..., outputs=...) in the following way:

inputs = [ Input(batch_size=128, shape=timeseries_length, name='input_1'), .... ]

# features_length = len(inputs) for reference

To test something I concatenated them together in the following way:

x = Concatenate(axis = -2)([ tensorflow.expand_dims(_input, -2) for _input in inputs ])
print(x.shape) # (batch_size, features_length, timeseries_length)

When I run model.fit with the Sequence passed as it's data generator and batch_size specified I received the following:

ValueError: Layer "model" expects [num_input_columns] input(s), but it received [features_length * batch_size] input tensors.

The batch_size and features_length dimensions got merged into one dimension for some reason.

Is the format the Sequence is supposed to return for batched named inputs different?

Should the generator give a dictionary of batches instead of batches of dictionaries?


问:
link to react route redirects to root url
I have a react app that's deployed that has multiple routes for different purposes. If I want to send a link to someone with a route (domain.com/route) it just redirects to the root url of domain.com.

I think it's something to do with SPAs in general, but I can't figure out what to add or where to add. Is it an issue with DNS? My site is deployed on Digital Ocean, but my domain is from google and it redirects from a subdomain (app.domain.com) so maybe that's the issue.

I had a similar issue with a different react app and I was able to fix it by adding this to my index.html:

```<code><!-- Start Single Page Apps for GitHub Pages -->
<script type="text/javascript">
  // Single Page Apps for GitHub Pages
  // MIT License
  // https://github.com/rafgraph/spa-github-pages
  // This script checks to see if a redirect is present in the query string,
  // converts it back into the correct url and adds it to the
  // browser's history using window.history.replaceState(...),
  // which won't cause the browser to attempt to load the new url.
  // When the single page app is loaded further down in this file,
  // the correct url will be waiting in the browser's history for
  // the single page app to route accordingly.
  (function (l) {
    if (l.search[1] === "/") {
      var decoded = l.search
        .slice(1)
        .split("&")
        .map(function (s) {
          return s.replace(/~and~/g, "&");
        })
        .join("?");
      window.history.replaceState(
        null,
        null,
        l.pathname.slice(0, -1) + decoded + l.hash
      );
    }
  })(window.location);
</script>
<!-- End Single Page Apps for GitHub Pages -->
</code>```

But it still redirects from domain.com/route to app.domain.com without the route, which makes me think it's because of the app..

EDIT: However when I do app.domain.com/route it works, so I think the issue is with domain.com always redirecting to app.domain.com because of the way I set up my DNS. Which sort of changes the question, but I still don't know why that happens.

Body:
I have a react app that's deployed that has multiple routes for different purposes. If I want to send a link to someone with a route (domain.com/route) it just redirects to the root url of domain.com.

I think it's something to do with SPAs in general, but I can't figure out what to add or where to add. Is it an issue with DNS? My site is deployed on Digital Ocean, but my domain is from google and it redirects from a subdomain (app.domain.com) so maybe that's the issue.

I had a similar issue with a different react app and I was able to fix it by adding this to my index.html:

But it still redirects from domain.com/route to app.domain.com without the route, which makes me think it's because of the app..

EDIT: However when I do app.domain.com/route it works, so I think the issue is with domain.com always redirecting to app.domain.com because of the way I set up my DNS. Which sort of changes the question, but I still don't know why that happens.


问:
I want to Join two tables each related (by a ForeignKey) to a third one (but not each other)
The three models relevant to this question are:

```<code>class MaterialList(models.Model):
    org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
    Material = models.CharField(max_length=100)
    Description = models.CharField(max_length=250, blank=True)
    PartType = models.ForeignKey(WhsePartTypes, null=True, on_delete=models.RESTRICT)
    Price = models.FloatField(null=True, blank=True)
    PriceUnit = models.PositiveIntegerField(null=True, blank=True)
    TypicalContainerQty = models.IntegerField(null=True, blank=True)
    TypicalPalletQty = models.IntegerField(null=True, blank=True)
    Notes = models.CharField(max_length=250, blank=True)

    UniqueConstraint('org', 'Material')

    class Meta:
        ordering = ['org','Material']

class CountSchedule(models.Model):
    org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
    CountDate = models.DateField(null=False)
    Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
    Counter = models.CharField(max_length=250, blank=True)
    Priority = models.CharField(max_length=50, blank=True)
    ReasonScheduled = models.CharField(max_length=250, blank=True)
    Notes = models.CharField(max_length=250, blank=True)

    UniqueConstraint('org', 'CountDate', 'Material')

    class Meta:
        ordering = ['org','CountDate', 'Material']

class ActualCounts(models.Model):
    org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=False)
    CountDate = models.DateField(null=False)
    CycCtID = models.CharField(max_length=100, blank=True)
    Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
    Counter = models.CharField(max_length=250, blank=False, null=False)
    LocationOnly = models.BooleanField(blank=True, default=False)
    CTD_QTY_Expr = models.CharField(max_length=500, blank=False)
    BLDG = models.CharField(max_length=100, blank=True)
    LOCATION = models.CharField(max_length=250, blank=True)
    PKGID_Desc = models.CharField(max_length=250, blank=True)
    TAGQTY = models.CharField(max_length=250, blank=True)
    FLAG_PossiblyNotRecieved = models.BooleanField(blank=True, default=False)
    FLAG_MovementDuringCount = models.BooleanField(blank=True, default=False)
    Notes = models.CharField(max_length = 250, blank=True)

    class Meta:
        ordering = ['org', 'CountDate', 'Material']
</code>```

These models arise from a migration from a non-Python system to a Python-Django driven system.  Most of the time, I only need the forward relations CountSchedule.Material and ActualCounts.Material.  There is one report my bosses L_O_V_E, however.  This report joins ActualCounts and CountSchedule where ActualCounts.CountDate=CountSchedule.CountDate and ActualCounts.Material=CountSchedule.Material.  (Actually, the report has 3 sections, which boil down to a LEFT JOIN, a RIGHT JOIN and an INNER JOIN.  For now, I just need help with any of these as a start).

For the moment, I'm going with raw SQL, but I'd like to know if the ORM has a solution.

Any advice?

I've already tried

```<code>    M = MaterialList.objects.select_related('actualcounts_set', 'countschedule_set').filter(org=_userorg, actualcounts__CountDate=datestr, countschedule__CountDate=datestr)

</code>```

which resulted in

Invalid field name(s) given in select_related: 'countschedule_set', 'actualcounts_set'. Choices are: org, PartType

```<code></code>```

Body:
The three models relevant to this question are:

class MaterialList(models.Model):
    org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
    Material = models.CharField(max_length=100)
    Description = models.CharField(max_length=250, blank=True)
    PartType = models.ForeignKey(WhsePartTypes, null=True, on_delete=models.RESTRICT)
    Price = models.FloatField(null=True, blank=True)
    PriceUnit = models.PositiveIntegerField(null=True, blank=True)
    TypicalContainerQty = models.IntegerField(null=True, blank=True)
    TypicalPalletQty = models.IntegerField(null=True, blank=True)
    Notes = models.CharField(max_length=250, blank=True)

    UniqueConstraint('org', 'Material')

    class Meta:
        ordering = ['org','Material']

class CountSchedule(models.Model):
    org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
    CountDate = models.DateField(null=False)
    Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
    Counter = models.CharField(max_length=250, blank=True)
    Priority = models.CharField(max_length=50, blank=True)
    ReasonScheduled = models.CharField(max_length=250, blank=True)
    Notes = models.CharField(max_length=250, blank=True)

    UniqueConstraint('org', 'CountDate', 'Material')

    class Meta:
        ordering = ['org','CountDate', 'Material']

class ActualCounts(models.Model):
    org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=False)
    CountDate = models.DateField(null=False)
    CycCtID = models.CharField(max_length=100, blank=True)
    Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
    Counter = models.CharField(max_length=250, blank=False, null=False)
    LocationOnly = models.BooleanField(blank=True, default=False)
    CTD_QTY_Expr = models.CharField(max_length=500, blank=False)
    BLDG = models.CharField(max_length=100, blank=True)
    LOCATION = models.CharField(max_length=250, blank=True)
    PKGID_Desc = models.CharField(max_length=250, blank=True)
    TAGQTY = models.CharField(max_length=250, blank=True)
    FLAG_PossiblyNotRecieved = models.BooleanField(blank=True, default=False)
    FLAG_MovementDuringCount = models.BooleanField(blank=True, default=False)
    Notes = models.CharField(max_length = 250, blank=True)

    class Meta:
        ordering = ['org', 'CountDate', 'Material']

These models arise from a migration from a non-Python system to a Python-Django driven system.  Most of the time, I only need the forward relations CountSchedule.Material and ActualCounts.Material.  There is one report my bosses L_O_V_E, however.  This report joins ActualCounts and CountSchedule where ActualCounts.CountDate=CountSchedule.CountDate and ActualCounts.Material=CountSchedule.Material.  (Actually, the report has 3 sections, which boil down to a LEFT JOIN, a RIGHT JOIN and an INNER JOIN.  For now, I just need help with any of these as a start).

For the moment, I'm going with raw SQL, but I'd like to know if the ORM has a solution.

Any advice?

I've already tried

    M = MaterialList.objects.select_related('actualcounts_set', 'countschedule_set').filter(org=_userorg, actualcounts__CountDate=datestr, countschedule__CountDate=datestr)

which resulted in

Invalid field name(s) given in select_related: 'countschedule_set', 'actualcounts_set'. Choices are: org, PartType


问:
Socket.IO ping for room data isn't working
Merry Christmas folks,

I'm trying send an array of rooms from my backend to frontend on every new socket connection to bypass that socket's state having an empty array for the rooms state. I'm basically storing the rooms in my backend and I'm trying to send it to my frontend whenever a new user/socket connects but it isn't working and I have no idea why.

This is my code for sending the rooms array after every new connection:

```<code>socket.on("connect", () => {
  const roomsCopy = [...rooms];
  socket.emit("connection", roomsCopy);
});
</code>```

It uses the stored rooms array:

```<code>var rooms = <
  { roomID: string; color: string; font: string; users: string[] }[]
>[];
</code>```

And I'm catching it in my frontend with this code:

```<code>  socket.on("connection", (roomsCopy) => {
    setRooms([roomsCopy]);
  });
</code>```

But I keep getting an empty array on the frontend when I try to print it out using components:

```<code>  {showRooms &&
    rooms.map((room, index) => {
      console.log("hi" + room);
      return <RoomsDisplay key={index} room={room} />;
    })}
</code>```

I know the backend is for sure not empty because I'm logging it's data after every new connection and it's showing that it gets updated whenever I add a room.

Any ideas?

Body:
Merry Christmas folks,

I'm trying send an array of rooms from my backend to frontend on every new socket connection to bypass that socket's state having an empty array for the rooms state. I'm basically storing the rooms in my backend and I'm trying to send it to my frontend whenever a new user/socket connects but it isn't working and I have no idea why.

This is my code for sending the rooms array after every new connection:

socket.on("connect", () => {
  const roomsCopy = [...rooms];
  socket.emit("connection", roomsCopy);
});

It uses the stored rooms array:

var rooms = <
  { roomID: string; color: string; font: string; users: string[] }[]
>[];

And I'm catching it in my frontend with this code:

  socket.on("connection", (roomsCopy) => {
    setRooms([roomsCopy]);
  });

But I keep getting an empty array on the frontend when I try to print it out using components:

  {showRooms &&
    rooms.map((room, index) => {
      console.log("hi" + room);
      return <RoomsDisplay key={index} room={room} />;
    })}

I know the backend is for sure not empty because I'm logging it's data after every new connection and it's showing that it gets updated whenever I add a room.

Any ideas?


问:
How can I replace one or multiple lines in the code editor with a WebView, File Preview or an Image?
I'm trying to develop an extension that needs to render text, images and the preview of an external file in the code as a decoration. The problem is that I only can find text decoration and nothing that allows me to for example show a PNG between two lines of code without modifying the file.

Is this possible or I need to create a Custom Editor using the API? The problem of this solution is the need to integrate all the extension on the language I'm working what will take too much time.

I have seen the Comments API allows to show the reference of a text file but I can't find where is the API to generate this type of views:

The closest thing I can find is the Comments API with this sample. However, I need to add more than just text and the idea is to only show the content, nothing more.

Any guide, information or reference is highly appreciated.


问:
Create multiple providers for same SQS class using Google Guice
I have two SQS queues from which I want to listen to messages using two different message handlers. I am using Guice to bind and initialise the different consumers and message handlers. However, I am unable to bind the respective consumer to corresponding handler.

Consumer - TransactionQueue, Handler - TransactionMessageHandler

Consumer - RetryQueue, Handler- RetryMessageHandler

```<code>com.google.inject.CreationException: Unable to create injector, see the following errors:

1) No implementation for com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler was bound.
  Did you mean?
    * com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler annotated with
@com.google.inject.name.Named(value="TransactionMessageHandler")
    * com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler annotated with
@com.google.inject.name.Named(value="RetryMessageHandler")
 while locating com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler
for the 1st parameter of com.config.providers.ListenerProvider.<init>(TransactionConsumerProvider.java:23)
  at com.config.ListenerModule.configure(ListenerModule.java:26) (via modules: com.service.ServiceModule -> com.config.ListenerModule)

</code>```

I have used @Named annotation to differentiate the consumers and handlers. Here is how my bindings look like:

```<code>@Override
  protected void configure() {

        bind(SqsConsumer.class).annotatedWith(Names.named("TransactionQueue"))
            .toProvider(TransactionConsumerProvider.class)
            .asEagerSingleton();

bind(SqsMessageHandler.class).annotatedWith(Names.named("TransactionMessageHandler"))
            .toProvider(TransactionMessageHandlerProvider.class)
            .asEagerSingleton();

        bind(SqsConsumer.class).annotatedWith(Names.named("RetryQueue"))
            .toProvider(RetryConsumerProvider.class)
            .asEagerSingleton();

        bind(SqsMessageHandler.class).annotatedWith(Names.named("RetryMessageHandler"))
            .toProvider(RetryMessageHandlerProvider.class)
            .asEagerSingleton();
    }
</code>```

Here are the classes for the consumers and the handlers:

TransactionConsumerProvider.class

```<code>@AllArgsConstructor(onConstructor = @__(@Inject))
public final class TransactionConsumerProvider implements Provider<SqsConsumer> {

    @Named("TransactionMessageHandler")
    private final SqsMessageHandler sqsMessageHandler;

    @Override
    public SqsConsumer get() {
        // initializing transaction SQS queue
        final SqsConsumer consumer = new SqsConsumer(
            "TransactionQueue",
            sqsClientBuilder,
            sqsMessageHandler,
            new SimpleMessageProcessingFailureHandler()
        );
    }
</code>```

TransactionMessageHandlerProvider.class

```<code>@AllArgsConstructor(onConstructor = @__(@Inject))
public final class TransactionMessageHandlerProvider implements Provider<SqsMessageHandler> {

    @Override
    public SqsMessageHandler get() {
       // Initialising TransactionMessageHandler
    }
</code>```

RetryConsumerProvider.class

```<code>@AllArgsConstructor(onConstructor = @__(@Inject))
public final class RetryConsumerProvider implements Provider<SqsConsumer> {

    @Named("RetryMessageHandler")
    private final SqsMessageHandler sqsMessageHandler;

    @Override
    public SqsConsumer get() {
       // initializing retry SQS queue
    }
</code>```

RetryMessageHandlerProvider.class

```<code>@AllArgsConstructor(onConstructor = @__(@Inject))
public final class RetryMessageHandlerProvider implements Provider<SqsMessageHandler> {

    @Override
    public SqsMessageHandler get() {
       // Initialising RetryMessageHandlerProvider
    }
</code>```

I think I have used com.google.inject.name.Names import correctly, but I am willing to try any new suggestions to make this work.

Thanks

Body:
I have two SQS queues from which I want to listen to messages using two different message handlers. I am using Guice to bind and initialise the different consumers and message handlers. However, I am unable to bind the respective consumer to corresponding handler.

Consumer - TransactionQueue, Handler - TransactionMessageHandler

Consumer - RetryQueue, Handler- RetryMessageHandler

com.google.inject.CreationException: Unable to create injector, see the following errors:

1) No implementation for com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler was bound.
  Did you mean?
    * com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler annotated with
@com.google.inject.name.Named(value="TransactionMessageHandler")
    * com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler annotated with
@com.google.inject.name.Named(value="RetryMessageHandler")
 while locating com.amazon.aft.sqsmessageconsumer.messaging.sqs.SqsMessageHandler
for the 1st parameter of com.config.providers.ListenerProvider.<init>(TransactionConsumerProvider.java:23)
  at com.config.ListenerModule.configure(ListenerModule.java:26) (via modules: com.service.ServiceModule -> com.config.ListenerModule)

I have used @Named annotation to differentiate the consumers and handlers. Here is how my bindings look like:

@Override
  protected void configure() {

        bind(SqsConsumer.class).annotatedWith(Names.named("TransactionQueue"))
            .toProvider(TransactionConsumerProvider.class)
            .asEagerSingleton();

bind(SqsMessageHandler.class).annotatedWith(Names.named("TransactionMessageHandler"))
            .toProvider(TransactionMessageHandlerProvider.class)
            .asEagerSingleton();

        bind(SqsConsumer.class).annotatedWith(Names.named("RetryQueue"))
            .toProvider(RetryConsumerProvider.class)
            .asEagerSingleton();

        bind(SqsMessageHandler.class).annotatedWith(Names.named("RetryMessageHandler"))
            .toProvider(RetryMessageHandlerProvider.class)
            .asEagerSingleton();
    }

Here are the classes for the consumers and the handlers:

TransactionConsumerProvider.class

@AllArgsConstructor(onConstructor = @__(@Inject))
public final class TransactionConsumerProvider implements Provider<SqsConsumer> {

    @Named("TransactionMessageHandler")
    private final SqsMessageHandler sqsMessageHandler;

    @Override
    public SqsConsumer get() {
        // initializing transaction SQS queue
        final SqsConsumer consumer = new SqsConsumer(
            "TransactionQueue",
            sqsClientBuilder,
            sqsMessageHandler,
            new SimpleMessageProcessingFailureHandler()
        );
    }

TransactionMessageHandlerProvider.class

@AllArgsConstructor(onConstructor = @__(@Inject))
public final class TransactionMessageHandlerProvider implements Provider<SqsMessageHandler> {

    @Override
    public SqsMessageHandler get() {
       // Initialising TransactionMessageHandler
    }

RetryConsumerProvider.class

@AllArgsConstructor(onConstructor = @__(@Inject))
public final class RetryConsumerProvider implements Provider<SqsConsumer> {

    @Named("RetryMessageHandler")
    private final SqsMessageHandler sqsMessageHandler;

    @Override
    public SqsConsumer get() {
       // initializing retry SQS queue
    }

RetryMessageHandlerProvider.class

@AllArgsConstructor(onConstructor = @__(@Inject))
public final class RetryMessageHandlerProvider implements Provider<SqsMessageHandler> {

    @Override
    public SqsMessageHandler get() {
       // Initialising RetryMessageHandlerProvider
    }

I think I have used com.google.inject.name.Names import correctly, but I am willing to try any new suggestions to make this work.

Thanks


问:
Pandas SettingWithCopy Warning
Bear with me, yesterday was my first day using Pandas.

I'm trying to make a backtesting framework for an algorithmic investor, and I'm running into a 'SettingWithCopy' warning. The dataframe I'm working with isn't being edited either, so I think somewhere I'm editing a copy of the dataframe and it's getting thrown out. It gives me a warning at all of the 'df.at' commands.

Additionally to (and I expect related to) the SettingWithCopy warning, the changes I make to the dataframe within the method do not end up appearing in the dataframe that eventually gets returned. As far as I understand the 'df.at' commands I have should be changing the 'transactions' column, but in the output frame that column is just full of NaNs.

How do I fix these issues, and what is the cause so I can avoid this next time? I read the documentation on the warning and I didn't wholly understand it.

Here is the code:

#%%
import pandas as pd
import numpy as np
import matplotlib as mpl
import random

def backtest(df):
    # Set wallet properties
    wallet = 1000 # dollas

    #iterate through day by day
    for i in range(len(df)):
        today = df.iloc[i,:]
        print(f"i = {str(i)}")

        signal = random.randint(-1,1)
        print('Signal: ' + str(signal))

        # hold signal
        if signal == 0:
            pass
        # buy signal
        elif signal == 1:
            print('Buying on: ' + str(today['timestamp']) + ' for ' + str(today['close']))
            df.at[i,'transactions'] = 1
            wallet -= today['close']
        # sell signal
        elif signal == -1:
            print('Selling on: ' + str(today['timestamp']) + ' for ' + str(today['close']))
            wallet += today['close']
            df.at[i,'transactions'] = -1
            print(df.at[i,'transactions'])
            print(f"Wallet at ${str(wallet)}")
        df.at[i,'wallet'] = wallet
        print()

    return df

# Import the dataset and get it ready to work with
df = pd.read_csv('Data/S&P500_2015-2018.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'])

# Choose which stock(s) you're using
stock = df[df['symbol'] == 'AMD']

out = backtest(stock)
print('All done backtesting')
out.plot(x = 'timestamp', y = 'transactions')
#%%
```
<p>And here is the output:</p>
```i = 0
Signal: 1
Buying on: 2015-12-01 05:00:00+00:00 for 2.34

i = 1
Signal: -1
Selling on: 2015-12-02 05:00:00+00:00 for 2.27
-1.0
Wallet at $999.93

i = 2
Signal: 0

i = 3
Signal: 1
Buying on: 2015-12-04 05:00:00+00:00 for 2.28

i = 4
Signal: -1
Selling on: 2015-12-07 05:00:00+00:00 for 2.355
-1.0
Wallet at $1000.005

i = 5
Signal: 1
...

i = 398
Signal: -1
Selling on: 2017-06-30 04:00:00+00:00 for 12.48
<ipython-input-10-c0810f02fee9>:25: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df.loc[i,'transactions'] = 1
```

Edit: clarified my question

Title: Pandas SettingWithCopy Warning

Body:
Bear with me, yesterday was my first day using Pandas.

I'm trying to make a backtesting framework for an algorithmic investor, and I'm running into a 'SettingWithCopy' warning. The dataframe I'm working with isn't being edited either, so I think somewhere I'm editing a copy of the dataframe and it's getting thrown out. It gives me a warning at all of the 'df.at' commands.

Additionally to (and I expect related to) the SettingWithCopy warning, the changes I make to the dataframe within the method do not end up appearing in the dataframe that eventually gets returned. As far as I understand the 'df.at' commands I have should be changing the 'transactions' column, but in the output frame that column is just full of NaNs.

How do I fix these issues, and what is the cause so I can avoid this next time? I read the documentation on the warning and I didn't wholly understand it.

Here is the code:

#%%
import pandas as pd
import numpy as np
import matplotlib as mpl
import random

def backtest(df):
    # Set wallet properties
    wallet = 1000 # dollas

    #iterate through day by day
    for i in range(len(df)):
        today = df.iloc[i,:]
        print(f"i = {str(i)}")

        signal = random.randint(-1,1)
        print('Signal: ' + str(signal))

        # hold signal
        if signal == 0:
            pass
        # buy signal
        elif signal == 1:
            print('Buying on: ' + str(today['timestamp']) + ' for ' + str(today['close']))
            df.at[i,'transactions'] = 1
            wallet -= today['close']
        # sell signal
        elif signal == -1:
            print('Selling on: ' + str(today['timestamp']) + ' for ' + str(today['close']))
            wallet += today['close']
            df.at[i,'transactions'] = -1
            print(df.at[i,'transactions'])
            print(f"Wallet at ${str(wallet)}")
        df.at[i,'wallet'] = wallet
        print()

    return df

# Import the dataset and get it ready to work with
df = pd.read_csv('Data/S&P500_2015-2018.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'])

# Choose which stock(s) you're using
stock = df[df['symbol'] == 'AMD']

out = backtest(stock)
print('All done backtesting')
out.plot(x = 'timestamp', y = 'transactions')
#%%

And here is the output:

i = 0
Signal: 1
Buying on: 2015-12-01 05:00:00+00:00 for 2.34

i = 1
Signal: -1
Selling on: 2015-12-02 05:00:00+00:00 for 2.27
-1.0
Wallet at $999.93

i = 2
Signal: 0

i = 3
Signal: 1
Buying on: 2015-12-04 05:00:00+00:00 for 2.28

i = 4
Signal: -1
Selling on: 2015-12-07 05:00:00+00:00 for 2.355
-1.0
Wallet at $1000.005

i = 5
Signal: 1
...

i = 398
Signal: -1
Selling on: 2017-06-30 04:00:00+00:00 for 12.48
<ipython-input-10-c0810f02fee9>:25: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df.loc[i,'transactions'] = 1

Edit: clarified my question


问:
How to use routes from submodule in NextJS
I have this project where I would like to use the routes/pages of a dashboard as defined in a git submodule. So, somehow I need to 'merge' the pages (or app folder in Nextjs13) folder with the one in the submodule.
Symlinks don't seem to be respected by NextJS, as it will simply throw a 404 page.
Are there any other methods that I am not aware of?

So in short: How to expose routes from a submodule to NextJS?

So the desired file structure is:

```<code>- pages (the nextjs file-based routes)
  - index.tsx
  - about.tsx
  - dashboard (should come from submodules/dashboard/pages)
    - index.tsx
    - stats.tsx
    - login.tsx
- public
- submodules
  - dashboard
    - pages
      - index.tsx
      - stats.tsx
      - login.tsx
</code>```

Body:
I have this project where I would like to use the routes/pages of a dashboard as defined in a git submodule. So, somehow I need to 'merge' the pages (or app folder in Nextjs13) folder with the one in the submodule.
Symlinks don't seem to be respected by NextJS, as it will simply throw a 404 page.
Are there any other methods that I am not aware of?

So in short: How to expose routes from a submodule to NextJS?

So the desired file structure is:

- pages (the nextjs file-based routes)
  - index.tsx
  - about.tsx
  - dashboard (should come from submodules/dashboard/pages)
    - index.tsx
    - stats.tsx
    - login.tsx
- public
- submodules
  - dashboard
    - pages
      - index.tsx
      - stats.tsx
      - login.tsx


问:
variable error referenced before assignment
```<code>import pygame
import os
import random
import time
import sys

pygame.init()
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game Window")
white = (255, 255, 255)
black = (0, 0, 0)
FPS = 60
vel = 5
fireball_speed = 10
background = pygame.image.load(os.path.join('Assets', 'background.jpg'))
bird = pygame.image.load(os.path.join('Assets', 'bird.png'))
fireball_size = (45, 30)
fireball = pygame.image.load(os.path.join('Assets', 'fireball.png'))
fireball = pygame.transform.scale(fireball, fireball_size)
fireball = pygame.transform.rotate(fireball, -90)
bird_image = pygame.transform.scale(bird, (70, 45))
directionx = random.randrange(0, 255)
directiony = random.randrange(0, 255)
choice = random.randrange(1, 10)
border = pygame.Rect(WIDTH, HEIGHT, 1, 1)
fireballentity = pygame.Rect(directionx, directiony, 35, 30)
fireball_y = 0
fireball_x = 0
lives = 5
pygame.mixer.init()
pygame.mixer.music.load("gamemusic.mp3")
font = pygame.font.SysFont('Comic Sans MS', 30)

def draw_window(bird):
    WIN.blit(background, (0,0))
    pygame.draw.rect(WIN, black, border)
    WIN.blit(bird_image, (bird.x, bird.y))
    WIN.blit(fireball, (fireballentity.x, fireballentity.y))
    pygame.display.update()

def main():
    pygame.mixer.music.play(10)
    while pygame.mixer.music.get_busy():

        bird = pygame.Rect(450, 250, 70, 45)

        clock = pygame.time.Clock()
        run = True
        while run:
            draw_window(bird)
            text = font.render("Lives: 5", False, (255, 255, 255))
            WIN.blit(text, (25, 100))
            pygame.display.update()
            clock.tick(FPS)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    try:
                        pygame.mixer.Channel.pause()
                        run = False
                    except Exception:
                        return
            if bird.colliderect(fireballentity):
                lives -= 1
            keys_pressed = pygame.key.get_pressed()
            if keys_pressed[pygame.K_a] or keys_pressed[pygame.K_LEFT] and bird.x - vel > 0: #left
                bird.x -= vel
            if keys_pressed[pygame.K_d] or keys_pressed[pygame.K_RIGHT] and bird.x + vel + bird.width < border.x: #right
                bird.x += vel
            if keys_pressed[pygame.K_w] or keys_pressed[pygame.K_UP] and bird.y - vel > 0: #up
                bird.y -= vel
            if keys_pressed[pygame.K_s] or keys_pressed[pygame.K_DOWN] and bird.y + vel + bird.height < HEIGHT: #down
                bird.y += vel

def event_handler(bird, fireballsprite):
    if bird.colliderect(fireballsprite):
        lives -=1
        text = font.render(f"Lives: {lives}", False, (255, 255, 255))
    if lives == 0:
        WIN.fill(white)
        gameover = font.render("Game Over", False, (0, 0, 0))
        WIN.blit(gameover, (450, 250))

if __name__ == "__main__":
    main()
</code>```

I'm trying to set a variable lives as 5 and when the bird sprite collides with the fireball, the player loses lives, However I'm getting an error "lives" referenced before assignment

I was trying to make lives a global variable or even use pygame events but I still got the error
I also tried to add the lives variable in the main game function loop but the text will flicker or I will get this error

```<code>Traceback (most recent call last):
  File "/Users/username/Desktop/Code/main.py", line 98, in <module>
    main()
  File "/Users/username/Desktop/Code/main.py", line 52, in main
    if bird.colliderect(fireballrect):
TypeError: Argument must be rect style object
</code>```

Body:
import pygame
import os
import random
import time
import sys

pygame.init()
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game Window")
white = (255, 255, 255)
black = (0, 0, 0)
FPS = 60
vel = 5
fireball_speed = 10
background = pygame.image.load(os.path.join('Assets', 'background.jpg'))
bird = pygame.image.load(os.path.join('Assets', 'bird.png'))
fireball_size = (45, 30)
fireball = pygame.image.load(os.path.join('Assets', 'fireball.png'))
fireball = pygame.transform.scale(fireball, fireball_size)
fireball = pygame.transform.rotate(fireball, -90)
bird_image = pygame.transform.scale(bird, (70, 45))
directionx = random.randrange(0, 255)
directiony = random.randrange(0, 255)
choice = random.randrange(1, 10)
border = pygame.Rect(WIDTH, HEIGHT, 1, 1)
fireballentity = pygame.Rect(directionx, directiony, 35, 30)
fireball_y = 0
fireball_x = 0
lives = 5
pygame.mixer.init()
pygame.mixer.music.load("gamemusic.mp3")
font = pygame.font.SysFont('Comic Sans MS', 30)

def draw_window(bird):
    WIN.blit(background, (0,0))
    pygame.draw.rect(WIN, black, border)
    WIN.blit(bird_image, (bird.x, bird.y))
    WIN.blit(fireball, (fireballentity.x, fireballentity.y))
    pygame.display.update()

def main():
    pygame.mixer.music.play(10)
    while pygame.mixer.music.get_busy():

        bird = pygame.Rect(450, 250, 70, 45)

        clock = pygame.time.Clock()
        run = True
        while run:
            draw_window(bird)
            text = font.render("Lives: 5", False, (255, 255, 255))
            WIN.blit(text, (25, 100))
            pygame.display.update()
            clock.tick(FPS)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    try:
                        pygame.mixer.Channel.pause()
                        run = False
                    except Exception:
                        return
            if bird.colliderect(fireballentity):
                lives -= 1
            keys_pressed = pygame.key.get_pressed()
            if keys_pressed[pygame.K_a] or keys_pressed[pygame.K_LEFT] and bird.x - vel > 0: #left
                bird.x -= vel
            if keys_pressed[pygame.K_d] or keys_pressed[pygame.K_RIGHT] and bird.x + vel + bird.width < border.x: #right
                bird.x += vel
            if keys_pressed[pygame.K_w] or keys_pressed[pygame.K_UP] and bird.y - vel > 0: #up
                bird.y -= vel
            if keys_pressed[pygame.K_s] or keys_pressed[pygame.K_DOWN] and bird.y + vel + bird.height < HEIGHT: #down
                bird.y += vel

def event_handler(bird, fireballsprite):
    if bird.colliderect(fireballsprite):
        lives -=1
        text = font.render(f"Lives: {lives}", False, (255, 255, 255))
    if lives == 0:
        WIN.fill(white)
        gameover = font.render("Game Over", False, (0, 0, 0))
        WIN.blit(gameover, (450, 250))

if __name__ == "__main__":
    main()

I'm trying to set a variable lives as 5 and when the bird sprite collides with the fireball, the player loses lives, However I'm getting an error "lives" referenced before assignment

I was trying to make lives a global variable or even use pygame events but I still got the error
I also tried to add the lives variable in the main game function loop but the text will flicker or I will get this error

Traceback (most recent call last):
  File "/Users/username/Desktop/Code/main.py", line 98, in <module>
    main()
  File "/Users/username/Desktop/Code/main.py", line 52, in main
    if bird.colliderect(fireballrect):
TypeError: Argument must be rect style object


问:
How to find the shortest path
In the function of find_shortest_func, i think if now position isn't "T" which is also known as the terminal or exit, then i will try to find for direction and see if it is "T", if not, check if it is space and i can go there. Besides, tell the next state function now output and dic to tell the place where i visited. But some errors occur and I don't know why.

I think the problem may occur where I tried to deepcopy the output list

```<code>import copy

def set_symbol(symbol_name):
    def set_symbol_decorator(func):
        def wrapper(self, symbol):
            setattr(self, symbol_name, symbol)
        return wrapper
    return set_symbol_decorator

class Maze:
    space_symbol = " "
    obstacle_symbol = "X"
    path_symbol = "•"
    output = []
    dis = 0

    def __init__(self, input_string):
        self.maze = []
        if input_string.endswith("txt"):
            with open(input_string) as f:
                count = 0
                for line in f.readlines():
                    self.maze.append([])
                    for j in line:
                        if j != '\n':
                            self.maze[count].append(j)
                    count += 1
        else:
            count = 0
            for i in input_string.split("\n"):
                self.maze.append([])
                for j in i:
                    self.maze[count].append(j)
                count += 1

    def __str__(self):
        output_string = ""
        for i in range(20):
            for j in range(20):
                output_string += self.maze[i][j]
            output_string += "\n"
        return output_string

    @set_symbol("space_symbol")
    def set_space_symbol(self, change):
        pass

    @set_symbol("obstacle_symbol")
    def set_obstacle_symbol(self, change):
        pass

    @set_symbol("path_symbol")
    def set_path_symbol(self, change):
        pass

    def find_shortest_func(self, position: tuple, d: dict, out: list, dis: int):
        dic = copy.deepcopy(d)
        output = copy.deepcopy(out)
        dic[(position[0], position[1])] = 1
        output.append((position[0], (position[1])))
        dis += 1

        if self.maze[position[0]][position[1]] != "T":
            if position[0]+1 < 20 and self.maze[position[0]+1][position[1]] == self.space_symbol and (position[0]+1, position[1]) not in dic:

                self.find_shortest_func(
                    (position[0]+1, position[1]), dic, output, dis)
            if position[1]+1 < 20 and self.maze[position[0]][position[1]+1] == self.space_symbol and (position[0], position[1]+1) not in dic:

                self.find_shortest_func(
                    (position[0], position[1]+1), dic, output, dis)
            if position[0]-1 >= 0 and self.maze[position[0]-1][position[1]] == self.space_symbol and (position[0]-1, position[1]) not in dic:

                self.find_shortest_func(
                    (position[0]-1, position[1]), dic, output, dis)
            if position[1]-1 >= 0 and self.maze[position[0]][position[1]-1] == self.space_symbol and (position[0], position[1]-1) not in dic:

                self.find_shortest_func(
                    (position[0], position[1]-1), dic, output, dis)
        if self.maze[position[0]][position[1]] == "T":
            if dis < self.dis:
                self.output = copy.deepcopy(output)
                self.dis = dis
        return

    def find_shortest_path(self):
        d = dict()
        output = []
        dis = -1
        self.find_shortest_func((1, 0), d, output, dis)
        return self.output, self.dis
</code>```

Title: How to find the shortest path

Body:
In the function of find_shortest_func, i think if now position isn't "T" which is also known as the terminal or exit, then i will try to find for direction and see if it is "T", if not, check if it is space and i can go there. Besides, tell the next state function now output and dic to tell the place where i visited. But some errors occur and I don't know why.

I think the problem may occur where I tried to deepcopy the output list

import copy

def set_symbol(symbol_name):
    def set_symbol_decorator(func):
        def wrapper(self, symbol):
            setattr(self, symbol_name, symbol)
        return wrapper
    return set_symbol_decorator

class Maze:
    space_symbol = " "
    obstacle_symbol = "X"
    path_symbol = "•"
    output = []
    dis = 0

    def __init__(self, input_string):
        self.maze = []
        if input_string.endswith("txt"):
            with open(input_string) as f:
                count = 0
                for line in f.readlines():
                    self.maze.append([])
                    for j in line:
                        if j != '\n':
                            self.maze[count].append(j)
                    count += 1
        else:
            count = 0
            for i in input_string.split("\n"):
                self.maze.append([])
                for j in i:
                    self.maze[count].append(j)
                count += 1

    def __str__(self):
        output_string = ""
        for i in range(20):
            for j in range(20):
                output_string += self.maze[i][j]
            output_string += "\n"
        return output_string

    @set_symbol("space_symbol")
    def set_space_symbol(self, change):
        pass

    @set_symbol("obstacle_symbol")
    def set_obstacle_symbol(self, change):
        pass

    @set_symbol("path_symbol")
    def set_path_symbol(self, change):
        pass

    def find_shortest_func(self, position: tuple, d: dict, out: list, dis: int):
        dic = copy.deepcopy(d)
        output = copy.deepcopy(out)
        dic[(position[0], position[1])] = 1
        output.append((position[0], (position[1])))
        dis += 1

        if self.maze[position[0]][position[1]] != "T":
            if position[0]+1 < 20 and self.maze[position[0]+1][position[1]] == self.space_symbol and (position[0]+1, position[1]) not in dic:

                self.find_shortest_func(
                    (position[0]+1, position[1]), dic, output, dis)
            if position[1]+1 < 20 and self.maze[position[0]][position[1]+1] == self.space_symbol and (position[0], position[1]+1) not in dic:

                self.find_shortest_func(
                    (position[0], position[1]+1), dic, output, dis)
            if position[0]-1 >= 0 and self.maze[position[0]-1][position[1]] == self.space_symbol and (position[0]-1, position[1]) not in dic:

                self.find_shortest_func(
                    (position[0]-1, position[1]), dic, output, dis)
            if position[1]-1 >= 0 and self.maze[position[0]][position[1]-1] == self.space_symbol and (position[0], position[1]-1) not in dic:

                self.find_shortest_func(
                    (position[0], position[1]-1), dic, output, dis)
        if self.maze[position[0]][position[1]] == "T":
            if dis < self.dis:
                self.output = copy.deepcopy(output)
                self.dis = dis
        return

    def find_shortest_path(self):
        d = dict()
        output = []
        dis = -1
        self.find_shortest_func((1, 0), d, output, dis)
        return self.output, self.dis


问:
Function composed by the derivative of a function
I have a function (being an array of functions) and I would like to calculate its derivative defining via def. In other words, I have

```<code>import sympy as sym
from sympy import *
import numpy as np
import math
def g(r,theta):
 return np.array([[1+r+theta,0],[0,1-r+theta]])

def Drg(r,theta):
 r=symbols('r')
 theta=symbols('theta')
 f=np.array([[1+r+theta,0],[0,1-r+theta]])
 Df=diff(f, r)
 return lambdify((r,theta),Df,"numpy")

print(Drg(1,np.pi))
</code>```

It is not working the function Drg, how can I solve this issue?

Body:
I have a function (being an array of functions) and I would like to calculate its derivative defining via def. In other words, I have

import sympy as sym
from sympy import *
import numpy as np
import math
def g(r,theta):
 return np.array([[1+r+theta,0],[0,1-r+theta]])

def Drg(r,theta):
 r=symbols('r')
 theta=symbols('theta')
 f=np.array([[1+r+theta,0],[0,1-r+theta]])
 Df=diff(f, r)
 return lambdify((r,theta),Df,"numpy")

print(Drg(1,np.pi))

It is not working the function Drg, how can I solve this issue?


问:
How do you remove the white border on context menu items more than two submenus deep
I'm trying to add some custom context menu items to the Windows Explorer context menu, but for some reason, menu items deeper than two use the background for light-mode explorer.

Screenshot

Is there any way to fix this?

My registry is laid out as follows:

```<code>HKEY_CLASSES_ROOT
    *
        shell
            botw
            MUIVerb = "Botw"
            SubCommands = ""
                shell
                    aamp
                    MUIVerb = "Aamp"
                    SubCommands = ""
                        shell
                            convert_yaml_to_aamp
                            (Default) = "Convert Aamp to Yaml"
                                command
                            convert_aamp_to_yaml
                            (Default) = "Convert Yaml to Aamp"
                                command
</code>```

The expected behaviour would be to have the background match the rest of the menu.

Body:
I'm trying to add some custom context menu items to the Windows Explorer context menu, but for some reason, menu items deeper than two use the background for light-mode explorer.

Screenshot

Is there any way to fix this?

My registry is laid out as follows:

HKEY_CLASSES_ROOT
    *
        shell
            botw
            MUIVerb = "Botw"
            SubCommands = ""
                shell
                    aamp
                    MUIVerb = "Aamp"
                    SubCommands = ""
                        shell
                            convert_yaml_to_aamp
                            (Default) = "Convert Aamp to Yaml"
                                command
                            convert_aamp_to_yaml
                            (Default) = "Convert Yaml to Aamp"
                                command

The expected behaviour would be to have the background match the rest of the menu.


问:
Prometheus how to sum the number of lable
If I have a metric with the following labels:

```<code>my_metric{group="group a"}  100
my_metric{group="group b"}  100
my_metric{group="group c"}  100
next
my_metric{group="group a"}  100
my_metric{group="group b"}  50

</code>```

how to sum lable not vaules and show in grafana ,i want to get 3 2 ...

Body:
If I have a metric with the following labels:

my_metric{group="group a"}  100
my_metric{group="group b"}  100
my_metric{group="group c"}  100
next
my_metric{group="group a"}  100
my_metric{group="group b"}  50

how to sum lable not vaules and show in grafana ,i want to get 3 2 ...


问:
Kotlin built-in regex: Escape all regex metacharacters in a string with backslash
As you probably all know, regular expressions have some metacharacters, such as \, |, ., ?, +, *,….  If you want to search for a substring including one of these characters without actually using the regex behaviour, you can escape it with a backslash.

So if you want to search for "Is it true?" in a string you would use the pattern
"Is it true\?".

I am using Kotlin and its built-in regular expressions. Is there a way in Kotlin (a function or something) to get a string from another string in which all of the special characters in the input string are escaped?

So if the input to such a function were "This is good." the output would be "This is good\.", and for "? a [+" it would be "\? a \[\+".  → every regex special character in the output is escaped with a backslash.