问:
Camel Karaf (OSGI Blueprint) SQL datasource
Hi Guys I'm having some issues with my datasource in Karaf 4.3.6 (recent upgrade) I'm hoping someone could shed some light on what I'm doing wrong here.

Before the upgrade

Karaf had the below services (org.osgi.service.jdbc.DataSourceFactory):

```<code>[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = com.microsoft.sqlserver.mssql-jdbc-native
 osgi.jdbc.driver.version = 6.2.2.jre8
 service.bundleid = 46
 service.id = 219
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (46)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = Microsoft JDBC Driver for SQL Server
 osgi.jdbc.driver.version = 7.4
 service.bundleid = 47
 service.id = 223
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (47)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = mssql
 service.bundleid = 157
 service.id = 252
 service.scope = singleton
Provided by :
 OPS4J Pax JDBC MSSQL Driver Adapter (157)
Used by:
 example-project(173)
 OPS4J Pax JDBC Config (38)
</code>```

My project blueprint contained the below:

```<code>    <bean id="sqlComponent" class="org.apache.camel.component.sql.SqlComponent">
    <property name="dataSource" ref="exampleSQLServerDataSource"/>
</bean>

<service id="c1SQLDataSource" interface="javax.sql.DataSource" ref="exampleSQLServerDataSource">
    <service-properties>
        <entry key="osgi.jndi.service.name" value="exSQLDataSource"/>
    </service-properties>
</service>

<bean id="exampleSQLServerDataSource" factory-ref="sqlServerDataSourceFactory" factory-method="createDataSource">
  <argument>
    <props>
      <prop key="databaseName">${ex.db.dbname}</prop>
      <prop key="user">${ex.db.user}</prop>
      <prop key="password">${ex.db.password}</prop>
      <prop key="portNumber">${ex.db.port}</prop>
      <prop key="serverName">${ex.db.host}</prop>
    </props>
  </argument>
</bean>

<reference id="sqlServerDataSourceFactory" interface="org.osgi.service.jdbc.DataSourceFactory" filter="(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.name=mssql)"/>
</code>```

With this configuration my project worked fine on install / i could use the camel-sql component with my datasource.

After the upgrade

Changes to karaf depensancys meant that the mssql factory was no longer available (even when starting the feature for pax-jdbc-mssql)

Karaf had the below services (org.osgi.service.jdbc.DataSourceFactory):

```<code>[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = com.microsoft.sqlserver.mssql-jdbc-native
 osgi.jdbc.driver.version = 6.2.2.jre8
 service.bundleid = 54
 service.id = 214
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (54)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = Microsoft JDBC Driver for SQL Server
 osgi.jdbc.driver.version = 9.2
 service.bundleid = 55
 service.id = 371
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (55)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = Microsoft JDBC Driver for SQL Server
 osgi.jdbc.driver.version = 9.4
 service.bundleid = 282
 service.id = 370
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (282)
</code>```

My project blueprint containes the below:

I modified my blueprint.xml to use one of the other connections available in jdbc:ds-factories but i am seeing the below error complaining of missing requirements on install

```<code><bean id="sqlComponent" class="org.apache.camel.component.sql.SqlComponent">
    <property name="dataSource" ref="exampleSQLServerDataSource"/>
</bean>

<service id="c1SQLDataSource" interface="javax.sql.DataSource" ref="exampleSQLServerDataSource">
    <service-properties>
        <entry key="osgi.jndi.service.name" value="exSQLDataSource"/>
    </service-properties>
</service>

<bean id="exampleSQLServerDataSource" factory-ref="sqlServerDataSourceFactory" factory-method="createDataSource">
  <argument>
    <props>
      <prop key="databaseName">${ex.db.dbname}</prop>
      <prop key="user">${ex.db.user}</prop>
      <prop key="password">${ex.db.password}</prop>
      <prop key="portNumber">${ex.db.port}</prop>
      <prop key="serverName">${ex.db.host}</prop>
    </props>
  </argument>
</bean>

<reference id="sqlServerDataSourceFactory" interface="org.osgi.service.jdbc.DataSourceFactory" filter="(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4)"/>
</code>```

Seeing this error on install

```<code>karaf@root()> feature:install example-project
org.apache.felix.resolver.reason.ReasonException: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=example-project; type=karaf.feature; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; filter:="(&(osgi.identity=example-project)(type=karaf.feature)(version>=0.1.4.SNAPSHOT)(version<=0.1.4.SNAPSHOT))" [caused by: Unable to resolve example-project/0.1.4.SNAPSHOT: missing requirement [example-project/0.1.4.SNAPSHOT] osgi.identity; osgi.identity=com.example.example.project; type=osgi.bundle; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; resolution:=mandatory [caused by: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"]]
        at org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1341)
        at org.apache.felix.resolver.ResolverImpl.doResolve(ResolverImpl.java:433)
        at org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:420)
        at org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:374)
        at org.apache.karaf.features.internal.region.SubsystemResolver.resolve(SubsystemResolver.java:257)
        at org.apache.karaf.features.internal.service.Deployer.deploy(Deployer.java:399)
        at org.apache.karaf.features.internal.service.FeaturesServiceImpl.doProvision(FeaturesServiceImpl.java:1069)
        at org.apache.karaf.features.internal.service.FeaturesServiceImpl.lambda$doProvisionInThread$13(FeaturesServiceImpl.java:1004)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.felix.resolver.reason.ReasonException: Unable to resolve example-project/0.1.4.SNAPSHOT: missing requirement [example-project/0.1.4.SNAPSHOT] osgi.identity; osgi.identity=com.example.example.project; type=osgi.bundle; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; resolution:=mandatory [caused by: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"]
        at org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1341)
        ... 12 more
Caused by: org.apache.felix.resolver.reason.ReasonException: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"
        at org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1341)
        ... 13 more
Error executing command: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=example-project; type=karaf.feature; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; filter:="(&(osgi.identity=example-project)(type=karaf.feature)(version>=0.1.4.SNAPSHOT)(version<=0.1.4.SNAPSHOT))" [caused by: Unable to resolve example-project/0.1.4.SNAPSHOT: missing requirement [example-project/0.1.4.SNAPSHOT] osgi.identity; osgi.identity=com.example.example.project; type=osgi.bundle; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; resolution:=mandatory [caused by: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"]]
</code>```

POM

The maven-bundle-plugin definition from my pom.xml file

```<code>    <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
            <instructions>
                <Import-Package>
                    javax.jms;version="[2.0,3)",
                    org.xmlsoap.schemas.soap.envelope,
                    com.example.example.services.amqp.*,
                    *
                </Import-Package>
            </instructions>
        </configuration>
    </plugin>
</code>```

答:
If I am reading the error message correctly, your Karaf is for some reason missing SQLServerDataSourceFactory service that should be provided by sqlserver activator when the bundle starts.

If you're upgrading from Apache Karaf version 4.2.x to 4.3.6 it could be that the version of the mssql-jdbc/9.4.0.jre8 bundle which the pax-jdbc-mssql feature installs could be incompatible with Java 11.

Apache Karaf 4.3.x supports JDK 11+ where as 4.2.x is for JDK 8, 9 and 10. There's handy table on Apache karafs downloads page that shows which version supports what. Mail about JDK 8 support with 4.3.x

Since the feature pax-jdbc-mssql only contains mssql-jdbc bundle and pax-jdbc-spec feature you could try to install them separately using jre11 version of mssql-jdbc bundle.

Example:

feature:install pax-jdbc-spec
bundle:install mvn:com.microsoft.sqlserver/mssql-jdbc/9.4.1.jre11
```

Since the version 9.4.1 has some vulnerabilities you could also try to upgrade to the newer 10.2.0.jre11 version if possible.

Body:
Hi Guys I'm having some issues with my datasource in Karaf 4.3.6 (recent upgrade) I'm hoping someone could shed some light on what I'm doing wrong here.

Before the upgrade

Karaf had the below services (org.osgi.service.jdbc.DataSourceFactory):

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = com.microsoft.sqlserver.mssql-jdbc-native
 osgi.jdbc.driver.version = 6.2.2.jre8
 service.bundleid = 46
 service.id = 219
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (46)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = Microsoft JDBC Driver for SQL Server
 osgi.jdbc.driver.version = 7.4
 service.bundleid = 47
 service.id = 223
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (47)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = mssql
 service.bundleid = 157
 service.id = 252
 service.scope = singleton
Provided by :
 OPS4J Pax JDBC MSSQL Driver Adapter (157)
Used by:
 example-project(173)
 OPS4J Pax JDBC Config (38)

My project blueprint contained the below:

    <bean id="sqlComponent" class="org.apache.camel.component.sql.SqlComponent">
    <property name="dataSource" ref="exampleSQLServerDataSource"/>
</bean>

<service id="c1SQLDataSource" interface="javax.sql.DataSource" ref="exampleSQLServerDataSource">
    <service-properties>
        <entry key="osgi.jndi.service.name" value="exSQLDataSource"/>
    </service-properties>
</service>

<bean id="exampleSQLServerDataSource" factory-ref="sqlServerDataSourceFactory" factory-method="createDataSource">
  <argument>
    <props>
      <prop key="databaseName">${ex.db.dbname}</prop>
      <prop key="user">${ex.db.user}</prop>
      <prop key="password">${ex.db.password}</prop>
      <prop key="portNumber">${ex.db.port}</prop>
      <prop key="serverName">${ex.db.host}</prop>
    </props>
  </argument>
</bean>

<reference id="sqlServerDataSourceFactory" interface="org.osgi.service.jdbc.DataSourceFactory" filter="(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.name=mssql)"/>

With this configuration my project worked fine on install / i could use the camel-sql component with my datasource.

After the upgrade

Changes to karaf depensancys meant that the mssql factory was no longer available (even when starting the feature for pax-jdbc-mssql)

Karaf had the below services (org.osgi.service.jdbc.DataSourceFactory):

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = com.microsoft.sqlserver.mssql-jdbc-native
 osgi.jdbc.driver.version = 6.2.2.jre8
 service.bundleid = 54
 service.id = 214
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (54)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = Microsoft JDBC Driver for SQL Server
 osgi.jdbc.driver.version = 9.2
 service.bundleid = 55
 service.id = 371
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (55)

[org.osgi.service.jdbc.DataSourceFactory]
-----------------------------------------
 osgi.jdbc.driver.class = com.microsoft.sqlserver.jdbc.SQLServerDriver
 osgi.jdbc.driver.name = Microsoft JDBC Driver for SQL Server
 osgi.jdbc.driver.version = 9.4
 service.bundleid = 282
 service.id = 370
 service.scope = singleton
Provided by :
 Microsoft JDBC Driver for SQL Server (282)

My project blueprint containes the below:

I modified my blueprint.xml to use one of the other connections available in jdbc:ds-factories but i am seeing the below error complaining of missing requirements on install

<bean id="sqlComponent" class="org.apache.camel.component.sql.SqlComponent">
    <property name="dataSource" ref="exampleSQLServerDataSource"/>
</bean>

<service id="c1SQLDataSource" interface="javax.sql.DataSource" ref="exampleSQLServerDataSource">
    <service-properties>
        <entry key="osgi.jndi.service.name" value="exSQLDataSource"/>
    </service-properties>
</service>

<bean id="exampleSQLServerDataSource" factory-ref="sqlServerDataSourceFactory" factory-method="createDataSource">
  <argument>
    <props>
      <prop key="databaseName">${ex.db.dbname}</prop>
      <prop key="user">${ex.db.user}</prop>
      <prop key="password">${ex.db.password}</prop>
      <prop key="portNumber">${ex.db.port}</prop>
      <prop key="serverName">${ex.db.host}</prop>
    </props>
  </argument>
</bean>

<reference id="sqlServerDataSourceFactory" interface="org.osgi.service.jdbc.DataSourceFactory" filter="(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4)"/>

Seeing this error on install

karaf@root()> feature:install example-project
org.apache.felix.resolver.reason.ReasonException: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=example-project; type=karaf.feature; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; filter:="(&(osgi.identity=example-project)(type=karaf.feature)(version>=0.1.4.SNAPSHOT)(version<=0.1.4.SNAPSHOT))" [caused by: Unable to resolve example-project/0.1.4.SNAPSHOT: missing requirement [example-project/0.1.4.SNAPSHOT] osgi.identity; osgi.identity=com.example.example.project; type=osgi.bundle; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; resolution:=mandatory [caused by: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"]]
        at org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1341)
        at org.apache.felix.resolver.ResolverImpl.doResolve(ResolverImpl.java:433)
        at org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:420)
        at org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:374)
        at org.apache.karaf.features.internal.region.SubsystemResolver.resolve(SubsystemResolver.java:257)
        at org.apache.karaf.features.internal.service.Deployer.deploy(Deployer.java:399)
        at org.apache.karaf.features.internal.service.FeaturesServiceImpl.doProvision(FeaturesServiceImpl.java:1069)
        at org.apache.karaf.features.internal.service.FeaturesServiceImpl.lambda$doProvisionInThread$13(FeaturesServiceImpl.java:1004)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.felix.resolver.reason.ReasonException: Unable to resolve example-project/0.1.4.SNAPSHOT: missing requirement [example-project/0.1.4.SNAPSHOT] osgi.identity; osgi.identity=com.example.example.project; type=osgi.bundle; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; resolution:=mandatory [caused by: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"]
        at org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1341)
        ... 12 more
Caused by: org.apache.felix.resolver.reason.ReasonException: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"
        at org.apache.felix.resolver.Candidates$MissingRequirementError.toException(Candidates.java:1341)
        ... 13 more
Error executing command: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=example-project; type=karaf.feature; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; filter:="(&(osgi.identity=example-project)(type=karaf.feature)(version>=0.1.4.SNAPSHOT)(version<=0.1.4.SNAPSHOT))" [caused by: Unable to resolve example-project/0.1.4.SNAPSHOT: missing requirement [example-project/0.1.4.SNAPSHOT] osgi.identity; osgi.identity=com.example.example.project; type=osgi.bundle; version="[0.1.4.SNAPSHOT,0.1.4.SNAPSHOT]"; resolution:=mandatory [caused by: Unable to resolve com.example.example.project/0.1.4.SNAPSHOT: missing requirement [com.example.example.project/0.1.4.SNAPSHOT] osgi.service; effective:=active; filter:="(&(objectClass=org.osgi.service.jdbc.DataSourceFactory)(osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver)(osgi.jdbc.driver.name=Microsoft JDBC Driver for SQL Server)(osgi.jdbc.driver.version=9.4))"]]

POM

The maven-bundle-plugin definition from my pom.xml file

    <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
            <instructions>
                <Import-Package>
                    javax.jms;version="[2.0,3)",
                    org.xmlsoap.schemas.soap.envelope,
                    com.example.example.services.amqp.*,
                    *
                </Import-Package>
            </instructions>
        </configuration>
    </plugin>

Body:
If I am reading the error message correctly, your Karaf is for some reason missing SQLServerDataSourceFactory service that should be provided by sqlserver activator when the bundle starts.

If you're upgrading from Apache Karaf version 4.2.x to 4.3.6 it could be that the version of the mssql-jdbc/9.4.0.jre8 bundle which the pax-jdbc-mssql feature installs could be incompatible with Java 11.

Apache Karaf 4.3.x supports JDK 11+ where as 4.2.x is for JDK 8, 9 and 10. There's handy table on Apache karafs downloads page that shows which version supports what. Mail about JDK 8 support with 4.3.x

Since the feature pax-jdbc-mssql only contains mssql-jdbc bundle and pax-jdbc-spec feature you could try to install them separately using jre11 version of mssql-jdbc bundle.

Example:

feature:install pax-jdbc-spec
bundle:install mvn:com.microsoft.sqlserver/mssql-jdbc/9.4.1.jre11

Since the version 9.4.1 has some vulnerabilities you could also try to upgrade to the newer 10.2.0.jre11 version if possible.


来源: stackexchange

问:
using multiple api calls, after first api others return undefined
Everyone does a weather app for api practice so I decided to do something different I'm using Pokeapi to make a small app. I have to call a few different apis to make it work how I want which is being done like this

```<code>const api = "https://pokeapi.co/api/v2/pokemon";
const apiMoves = "https://pokeapi.co/api/v2/move";
const apiSpecies = "https://pokeapi.co/api/v2/pokemon-species"

const searchBox = document.querySelector(".search-box");
searchBox.addEventListener("keypress", setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value);
    searchBox.value = "";
  }
}
function getResults(query) {
  const pokemonData = fetch(`${api}/${query}`)
  .then((data) => {
     return data.json();
  });
  pokemonData.then(displayResults)

  pokemonData.then(data => {
      return fetch(`${apiMoves}/${data.moves[0].move.name}`)
      .then(data => data.json())
      .then(move => {
          console.log(move)
      })
  })
  pokemonData.then(data => {
      return fetch(`${apiSpecies}/${query}`)
      .then(data => data.json())
      .then(species => {
          console.log(species)
      })
  })
}

</code>```

all 3 of the end points are being logged in the console so I can see them. However looking at api call 2 I'm passing info from the first api call to get more info and that logs fine. When I'm trying to display the info from that 2nd api call it just returns undefined but in the console I can see all the endpoints.

the display results looks something like this.

```<code>function displayResults(pokemon) {
  let name = document.querySelector('h2')
name.innerText = pokemon.name <-- this works.
  let dmg1 = document.querySelector('.dmg1')
dmg1.innerText = pokemon.power <-- this is returning undefined but in the console "power" shows a number.
}

</code>```

I've tried to replace the pokemon.power with move.power but that gives an error saying "move" is not defined.

I'm thinking that I'm simply calling the 2nd and 3rd api wrong? I'm not sure and trying to search for this issue is a bit rough.

any help is appreciated!

答:
const pokeApiPrefix = 'https://pokeapi.co/api/v2/';
const apiPokemon = `${pokeApiPrefix}pokemon`;
const apiMoves = `${pokeApiPrefix}move`;
const apiSpecies = `${pokeApiPrefix}pokemon-species`;

const searchBox = document.querySelector('.search-box');
searchBox.addEventListener('keypress', setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value.toLowerCase());
    searchBox.value = '';
  }
}
getResults('Dragonite'.toLowerCase());
function getResults(pokemon) {
   let dmg1 = document.querySelector('.dmg1');
  dmg1.innerText = `Getting results. Please wait...`;
  const pokemonData = fetch(`${apiPokemon}/${pokemon}`)
    .then((data) => data.json())
    .then((data) => {
      console.log(`pokemon data:`, data);
      displayPokemonName(data);
      const moveName = data.moves[0].move.name;
      return fetch(`${apiMoves}/${moveName}`);
    })
    .then((data) => {
      return data.json();
    })
    .then((data) => {
      displayMovePower(data);
      console.log(`move data:`, data);
      return fetch(`${apiSpecies}/${pokemon}`);
    })
    .then((data) => data.json())
    .then((data) => {
      console.log(`species data:`, data);
    });
}

// function displayResults(pokemon) {
//   let name = document.querySelector('h2');
//   name.innerText = pokemon.name;
//   let dmg1 = document.querySelector('.dmg1');
//   // I couldn't find 'power' attribute on api results, used id instead
//   // https://pokeapi.co/docs/v2#pokemon
//   dmg1.innerText = `#${pokemon.id}`;
// }

function displayPokemonName(pokemon) {
  let name = document.querySelector('h2');
  name.innerText = `Pokemon name: ${pokemon.name}`;
}

function displayMovePower(move) {
  let dmg1 = document.querySelector('.dmg1');
  dmg1.innerText = `Move power: ${move.id}`;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class="search-box" />

<h2></h2>
<div class="dmg1"></div></code>```

I've created a snippet, chaining multiple promises and logging every result on the console.
As stated, it seems you are trying to use an attribute 'power', which is not present in the first pokemon api call

ContentLicense: CC BY-SA 4.0

Body:
Everyone does a weather app for api practice so I decided to do something different I'm using Pokeapi to make a small app. I have to call a few different apis to make it work how I want which is being done like this

const api = "https://pokeapi.co/api/v2/pokemon";
const apiMoves = "https://pokeapi.co/api/v2/move";
const apiSpecies = "https://pokeapi.co/api/v2/pokemon-species"

const searchBox = document.querySelector(".search-box");
searchBox.addEventListener("keypress", setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value);
    searchBox.value = "";
  }
}
function getResults(query) {
  const pokemonData = fetch(`${api}/${query}`)
  .then((data) => {
     return data.json();
  });
  pokemonData.then(displayResults)

  pokemonData.then(data => {
      return fetch(`${apiMoves}/${data.moves[0].move.name}`)
      .then(data => data.json())
      .then(move => {
          console.log(move)
      })
  })
  pokemonData.then(data => {
      return fetch(`${apiSpecies}/${query}`)
      .then(data => data.json())
      .then(species => {
          console.log(species)
      })
  })
}

all 3 of the end points are being logged in the console so I can see them. However looking at api call 2 I'm passing info from the first api call to get more info and that logs fine. When I'm trying to display the info from that 2nd api call it just returns undefined but in the console I can see all the endpoints.

the display results looks something like this.

function displayResults(pokemon) {
  let name = document.querySelector('h2')
name.innerText = pokemon.name <-- this works.
  let dmg1 = document.querySelector('.dmg1')
dmg1.innerText = pokemon.power <-- this is returning undefined but in the console "power" shows a number.
}

I've tried to replace the pokemon.power with move.power but that gives an error saying "move" is not defined.

I'm thinking that I'm simply calling the 2nd and 3rd api wrong? I'm not sure and trying to search for this issue is a bit rough.

any help is appreciated!

Body:
const pokeApiPrefix = 'https://pokeapi.co/api/v2/';
const apiPokemon = `${pokeApiPrefix}pokemon`;
const apiMoves = `${pokeApiPrefix}move`;
const apiSpecies = `${pokeApiPrefix}pokemon-species`;

const searchBox = document.querySelector('.search-box');
searchBox.addEventListener('keypress', setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value.toLowerCase());
    searchBox.value = '';
  }
}
getResults('Dragonite'.toLowerCase());
function getResults(pokemon) {
   let dmg1 = document.querySelector('.dmg1');
  dmg1.innerText = `Getting results. Please wait...`;
  const pokemonData = fetch(`${apiPokemon}/${pokemon}`)
    .then((data) => data.json())
    .then((data) => {
      console.log(`pokemon data:`, data);
      displayPokemonName(data);
      const moveName = data.moves[0].move.name;
      return fetch(`${apiMoves}/${moveName}`);
    })
    .then((data) => {
      return data.json();
    })
    .then((data) => {
      displayMovePower(data);
      console.log(`move data:`, data);
      return fetch(`${apiSpecies}/${pokemon}`);
    })
    .then((data) => data.json())
    .then((data) => {
      console.log(`species data:`, data);
    });
}

// function displayResults(pokemon) {
//   let name = document.querySelector('h2');
//   name.innerText = pokemon.name;
//   let dmg1 = document.querySelector('.dmg1');
//   // I couldn't find 'power' attribute on api results, used id instead
//   // https://pokeapi.co/docs/v2#pokemon
//   dmg1.innerText = `#${pokemon.id}`;
// }

function displayPokemonName(pokemon) {
  let name = document.querySelector('h2');
  name.innerText = `Pokemon name: ${pokemon.name}`;
}

function displayMovePower(move) {
  let dmg1 = document.querySelector('.dmg1');
  dmg1.innerText = `Move power: ${move.id}`;
}

<input type="text" class="search-box" />

<h2></h2>
<div class="dmg1"></div>

I've created a snippet, chaining multiple promises and logging every result on the console.
As stated, it seems you are trying to use an attribute 'power', which is not present in the first pokemon api call


问:
Spring-webflux / Netty service won't handle any requests
Attempting to update a Spring-webflux java service to use BouncyCastle for FIPS compliant cryptography would startup, however every request to the service would end up failing with a stack trace like this:</p>
```<code>[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server ignored SNI (no matchers specified)
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server specified new session: 3897681a0667834f4be0c7c579976c84863b65c3cb5b572ab2064488b89069e7
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server (1.2) selected credentials for signature scheme 'ecdsa_secp521r1_sha512(0x603)' (keyType 'ECDHE_ECDSA'), with private key algorithm 'RSA'
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server selected cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server raised fatal(2) internal_error(80) alert: Failed to process record
java.lang.IllegalStateException: Invalid algorithm: {sha512(6),ecdsa(3)} at org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsRSASigner.generateRawSignature(JcaTlsRSASigner.java:59)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.DefaultTlsCredentialedSigner.generateRawSignature(DefaultTlsCredentialedSigner.java:53)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsUtils.generateServerKeyExchangeSignature(TlsUtils.java:2587)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsECDHEKeyExchange.generateServerKeyExchange(TlsECDHEKeyExchange.java:79)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsServerProtocol.handleHandshakeMessage(TlsServerProtocol.java:1082)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.processHandshakeQueue(TlsProtocol.java:695)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.processRecord(TlsProtocol.java:584)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.RecordStream.readFullRecord(RecordStream.java:207)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.safeReadFullRecord(TlsProtocol.java:890)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.offerInput(TlsProtocol.java:1282)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.offerInput(TlsProtocol.java:1250)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.jsse.provider.ProvSSLEngine.unwrap(ProvSSLEngine.java:464)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at java.base/javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:637)
~[na:na] at io.netty.handler.ssl.SslHandler$SslEngineType$3.unwrap(SslHandler.java:298)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1344)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1237)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1286)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507)
~[netty-codec-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446)
~[netty-codec-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
~[netty-codec-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
~[netty-common-4.1.66.Final.jar:4.1.66.Final] at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
~[netty-common-4.1.66.Final.jar:4.1.66.Final] at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
~[netty-common-4.1.66.Final.jar:4.1.66.Final] at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
</code>```

答: If a server.ssl.keyAlias is configured spring boot will use a KeyManagerFactory wrapper that causes problems like this.  Deleting that configuration item resolved the issue for us.

Body:
Attempting to update a Spring-webflux java service to use BouncyCastle for FIPS compliant cryptography would startup, however every request to the service would end up failing with a stack trace like this:

[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server ignored SNI (no matchers specified)
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server specified new session: 3897681a0667834f4be0c7c579976c84863b65c3cb5b572ab2064488b89069e7
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server (1.2) selected credentials for signature scheme 'ecdsa_secp521r1_sha512(0x603)' (keyType 'ECDHE_ECDSA'), with private key algorithm 'RSA'
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server selected cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
[ctor-http-nio-5] o.b.jsse.provider.ProvTlsServer : Server raised fatal(2) internal_error(80) alert: Failed to process record
java.lang.IllegalStateException: Invalid algorithm: {sha512(6),ecdsa(3)} at org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsRSASigner.generateRawSignature(JcaTlsRSASigner.java:59)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.DefaultTlsCredentialedSigner.generateRawSignature(DefaultTlsCredentialedSigner.java:53)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsUtils.generateServerKeyExchangeSignature(TlsUtils.java:2587)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsECDHEKeyExchange.generateServerKeyExchange(TlsECDHEKeyExchange.java:79)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsServerProtocol.handleHandshakeMessage(TlsServerProtocol.java:1082)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.processHandshakeQueue(TlsProtocol.java:695)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.processRecord(TlsProtocol.java:584)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.RecordStream.readFullRecord(RecordStream.java:207)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.safeReadFullRecord(TlsProtocol.java:890)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.offerInput(TlsProtocol.java:1282)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.tls.TlsProtocol.offerInput(TlsProtocol.java:1250)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at org.bouncycastle.jsse.provider.ProvSSLEngine.unwrap(ProvSSLEngine.java:464)
~[bctls-fips-1.0.12.2.jar:1.0.12.2] at java.base/javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:637)
~[na:na] at io.netty.handler.ssl.SslHandler$SslEngineType$3.unwrap(SslHandler.java:298)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1344)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1237)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1286)
~[netty-handler-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507)
~[netty-codec-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446)
~[netty-codec-4.1.66.Final.jar:4.1.66.Final] at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
~[netty-codec-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
~[netty-transport-4.1.66.Final.jar:4.1.66.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
~[netty-common-4.1.66.Final.jar:4.1.66.Final] at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
~[netty-common-4.1.66.Final.jar:4.1.66.Final] at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
~[netty-common-4.1.66.Final.jar:4.1.66.Final] at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]


问:
New line character in text file (C#)
I'm exporting text to a file in C# using System.IO.File.AppendAllText, and passing in the text file, and then the text I want to export with \n added to the end. When I view the text document, they are not on different lines, although that pesky return-line character is there between the lines. So the system may think it's two line, but a user sees it as one. How can this be fixed automatically without doing a find-replace every time I generate a file?

```<code>System.IO.File.AppendAllText(@"./WarningsLog.txt", line + "\n");
</code>```

答:
You could try building this with some file specific characters checks , like
new line, tab , etc....
Here is an example code which checks for new line and tabs :

```<code> public static string Replace()
        {
             string rLower =   words.ToLower().Replace(Environment.NewLine, "<replaced_newLine>");
            rLower = rLower.Replace("\t", "<replaced_Tabulation>");
            return rLower;
        }
</code>```

Of course you might have a lot of different combinations , where an item that needs to be changed is followed by " " or "\n" or "\r\n" or "\t"

ContentLicense: CC BY-SA 3.0

Title: New line character in text file (C#)

Body:
I'm exporting text to a file in C# using System.IO.File.AppendAllText, and passing in the text file, and then the text I want to export with \n added to the end. When I view the text document, they are not on different lines, although that pesky return-line character is there between the lines. So the system may think it's two line, but a user sees it as one. How can this be fixed automatically without doing a find-replace every time I generate a file?

System.IO.File.AppendAllText(@"./WarningsLog.txt", line + "\n");

Body:
You could try building this with some file specific characters checks , like
new line, tab , etc....
Here is an example code which checks for new line and tabs :

 public static string Replace()
        {
             string rLower =   words.ToLower().Replace(Environment.NewLine, "<replaced_newLine>");
            rLower = rLower.Replace("\t", "<replaced_Tabulation>");
            return rLower;
        }

Of course you might have a lot of different combinations , where an item that needs to be changed is followed by " " or "\n" or "\r\n" or "\t"


问:
how to loop over the videos and write the information in sepreate folders?
I have a main folder which has multiple folders, including input with multiple sub-folders each sub-folder has a video in it. I loop over input (its sub-folders) and process them. I wish to write the processed information into the output file. Currently everything is written in only one output folder. But I would like to have an output folder like this where I can have multiple sub folders to write processed info related to each video.

What I am currently doing:

```<code>mainfolder
    ├── input
    │   │
    │   ├── sub-folder1/ video1.mp4
    │   ├── sub-folder2/ video2.mp4
    │   └── sub-folder3/ video3.mp4
    |
    ├── output/ everything get over written here
    │
    │
    │
    ├── main_code.py
</code>```

What I wish to do:

```<code>mainfolder
├── input
│   │
│   ├── sub-folder1/ video1.mp4
│   ├── sub-folder2/ video2.mp4
│   └── sub-folder3/ video3.mp4
├── output
│   ├── sub-folder1/ processed-info(video1)
│   ├── sub-folder2/ processed-info(video2)
│   └── sub-folder3/ processed-info(video3)
│
│
├── main_code.py
</code>```

After doing some process for each video under sub-folder, I want to write frames into the same locations as of each sub-folder.

Here is the loop over sub-folders, each has a video in it:

```<code> mainFolder= 'input'
myFolders= os.listdir(mainFolder)

for folder in myFolders:
    path=mainFolder+ '/'+ folder
    print(path)
    vidoes=[]
    myList=os.listdir(path)

    for vidN in myList:
        vs=cv2.VideoCapture(f'{path}/{vidN}')
        vidoes.append(vs)
</code>```

After processing each video, I write the out put of the frames, .txt file and processed video into an output folder. This causes an overwriting issue. How do I create folders with the same name as the videos inside the output folder to prevent overwriting?

```<code>directory_name1 = os.path.join(os.getcwd(),'output','frames1')
                        if not os.path.exists(directory_name1):
                            os.makedirs(directory_name1)

                        frame_path1= os.path.join(directory_name1,f"frame1-{frameIndex}.png")
                        cv2.imwrite(frame_path1,frame)

output_string=f"{ID}, {count} \n"
                            print(output_string)
                            with open(outputFilename, 'a') as file_writer:
                                file_writer.write(output_string)

# check if the video writer is None
        if writer is None:
            # initialize our video writer
            fourcc = cv2.VideoWriter_fourcc(*"MJPG")

            directory_out= 'output'

            if not os.path.exists(directory_out):
                os.makedirs(directory_out)

            writer = cv2.VideoWriter(os.path.join(directory_out,'out.avi'), fourcc, 120,
                                     (frame.shape[1], frame.shape[0]), True)
</code>```

I can loop over video files, but when I try to write the output it overwrites. My question is how do I direct output for each videos into a separate sub folder?

答:
Here is a little program to demonstrate modifying the filename.We have to double escape the . as separateur.Of course you could seperate on "/" or "" depending on the OS and reconstruct the filename with a new subfolder, that you would have to create.It could be done but would be much more complicated.</p>
```<code>class FileName {
        public static void main(String[] args) {
                String fileName = "/path/to/my/file/video.mp4";
                String[] parts = fileName.split("\\.");
                String newFileName = parts[0] + ".proc." + parts[1];
                System.out.println(newFileName);
                }
}
</code>```

Body:
I have a main folder which has multiple folders, including input with multiple sub-folders each sub-folder has a video in it. I loop over input (its sub-folders) and process them. I wish to write the processed information into the output file. Currently everything is written in only one output folder. But I would like to have an output folder like this where I can have multiple sub folders to write processed info related to each video.

What I am currently doing:

mainfolder
    ├── input
    │   │
    │   ├── sub-folder1/ video1.mp4
    │   ├── sub-folder2/ video2.mp4
    │   └── sub-folder3/ video3.mp4
    |
    ├── output/ everything get over written here
    │
    │
    │
    ├── main_code.py

What I wish to do:

mainfolder
├── input
│   │
│   ├── sub-folder1/ video1.mp4
│   ├── sub-folder2/ video2.mp4
│   └── sub-folder3/ video3.mp4
├── output
│   ├── sub-folder1/ processed-info(video1)
│   ├── sub-folder2/ processed-info(video2)
│   └── sub-folder3/ processed-info(video3)
│
│
├── main_code.py

After doing some process for each video under sub-folder, I want to write frames into the same locations as of each sub-folder.

Here is the loop over sub-folders, each has a video in it:

 mainFolder= 'input'
myFolders= os.listdir(mainFolder)

for folder in myFolders:
    path=mainFolder+ '/'+ folder
    print(path)
    vidoes=[]
    myList=os.listdir(path)

    for vidN in myList:
        vs=cv2.VideoCapture(f'{path}/{vidN}')
        vidoes.append(vs)

After processing each video, I write the out put of the frames, .txt file and processed video into an output folder. This causes an overwriting issue. How do I create folders with the same name as the videos inside the output folder to prevent overwriting?

directory_name1 = os.path.join(os.getcwd(),'output','frames1')
                        if not os.path.exists(directory_name1):
                            os.makedirs(directory_name1)

                        frame_path1= os.path.join(directory_name1,f"frame1-{frameIndex}.png")
                        cv2.imwrite(frame_path1,frame)

output_string=f"{ID}, {count} \n"
                            print(output_string)
                            with open(outputFilename, 'a') as file_writer:
                                file_writer.write(output_string)

# check if the video writer is None
        if writer is None:
            # initialize our video writer
            fourcc = cv2.VideoWriter_fourcc(*"MJPG")

            directory_out= 'output'

            if not os.path.exists(directory_out):
                os.makedirs(directory_out)

            writer = cv2.VideoWriter(os.path.join(directory_out,'out.avi'), fourcc, 120,
                                     (frame.shape[1], frame.shape[0]), True)

I can loop over video files, but when I try to write the output it overwrites. My question is how do I direct output for each videos into a separate sub folder?

Body:
Here is a little program to demonstrate modifying the filename.We have to double escape the . as separateur.Of course you could seperate on "/" or "" depending on the OS and reconstruct the filename with a new subfolder, that you would have to create.It could be done but would be much more complicated.

class FileName {
        public static void main(String[] args) {
                String fileName = "/path/to/my/file/video.mp4";
                String[] parts = fileName.split("\\.");
                String newFileName = parts[0] + ".proc." + parts[1];
                System.out.println(newFileName);
                }
}


问:
React Typescript - Types problem | One component that renders sub component
Parent Component: Font

Sub Component: FontHeading, FontText, FontSubTitle.

```<code>  return (
    <>
      {type === "title" && <FontTitle as={as} variant={variant as HeadingVariants}>{children}</FontTitle>}
      {type === "subtitle" && <FontSubtitle>{children}</FontSubtitle>}
      {type === "iperlink" && <FontIperLink>{children}</FontIperLink>}
    </>
  );

export type IFont = {
  type: 'title' | 'subtitle' | 'link',
  children: React.ReactNode,
  variant: HeadingVariants | TextVariants | LinkVariants;
  setRef?: React.Ref<HTMLDivElement>;
}

export type IFontTitle = {
  as?: "h1" | "h2" | "h3" | "h4" | "h5";
  variant: HeadingVariants
}

export type IFontSubTitle = {
  variant: TextVariants
}

export type IFontLink = {
  href: string;
  variant: LinkVariants;
}
</code>```

How can I tell that if <Field type="title" .... /> then it needs to accept props that are of IFontTitle ? Viceversa with type="variant" or type="link".
Also would be great if it's auto select the correct variant, any help is appreciated..

Thanks

答:
I suppose, generic will be more suitable in your case (read from bottom to top).

```<code>interface Link extends BaseFont<'link', LinkVariants, HTMLLinkElement> {
  href: string;
}

interface Subtitle extends BaseFont<'subtitle', TextVariants, HTMLDivElement> {}

type TitleTag = "h1" | "h2" | "h3" | "h4" | "h5";

interface Title extends BaseFont<'title', HeadingVariants, HTMLHeadingElement> {
  tag?: TitleTag;
}

interface BaseFont<T, V, R> {
  type: T;
  variant: V;
  children: ReactNode;
  ref?: Ref<R>;
}
</code>```

And don't use verb, if you name an instance but not some function.

Body:
Parent Component: Font

Sub Component: FontHeading, FontText, FontSubTitle.

  return (
    <>
      {type === "title" && <FontTitle as={as} variant={variant as HeadingVariants}>{children}</FontTitle>}
      {type === "subtitle" && <FontSubtitle>{children}</FontSubtitle>}
      {type === "iperlink" && <FontIperLink>{children}</FontIperLink>}
    </>
  );

export type IFont = {
  type: 'title' | 'subtitle' | 'link',
  children: React.ReactNode,
  variant: HeadingVariants | TextVariants | LinkVariants;
  setRef?: React.Ref<HTMLDivElement>;
}

export type IFontTitle = {
  as?: "h1" | "h2" | "h3" | "h4" | "h5";
  variant: HeadingVariants
}

export type IFontSubTitle = {
  variant: TextVariants
}

export type IFontLink = {
  href: string;
  variant: LinkVariants;
}

How can I tell that if <Field type="title" .... /> then it needs to accept props that are of IFontTitle ? Viceversa with type="variant" or type="link".
Also would be great if it's auto select the correct variant, any help is appreciated..

Thanks

Body:
I suppose, generic will be more suitable in your case (read from bottom to top).

interface Link extends BaseFont<'link', LinkVariants, HTMLLinkElement> {
  href: string;
}

interface Subtitle extends BaseFont<'subtitle', TextVariants, HTMLDivElement> {}

type TitleTag = "h1" | "h2" | "h3" | "h4" | "h5";

interface Title extends BaseFont<'title', HeadingVariants, HTMLHeadingElement> {
  tag?: TitleTag;
}

interface BaseFont<T, V, R> {
  type: T;
  variant: V;
  children: ReactNode;
  ref?: Ref<R>;
}

And don't use verb, if you name an instance but not some function.


问:
MVC3-ValidationFailure-RetainValues
I am using MVC3 in ASP.NET. In the Post Action,
I have an View, In which it should let me edit the values. Some fields are read-only and some fields are editable. If there is a validation failure then it should retain the values and display the same View, if there are no error then it should let me to submit the form.

Control1:
Name I have to display as label as It has to be read-only

```<code>@Html.DisplayFor(Model => Model.Absentee.Name)
</code>```

Control2:

I have to display this one as textbox so that it can be edited. This  is a required Field.

```<code>  @Html.TextBoxFor(Model => Model.AbsStart)
     @Html.ValidationMessageFor(Model => Model.AbsStart) (This Makes it as a required Field)
</code>```

Control 3:

This is also a textbox but not required field.

```<code>@Html.DisplayFor(Model => Model.AbsEnteredAt)
</code>```

When there are no validation errors, things works great, but when there is a validation error, then I will be in the same view(Which is what I want) but the value in First control is not retained.

So Basically, when the validation failure, the value is not retained in the DisplayFor Control

What do I do to sort this?
Thank you

答:
When there is an error, what is the viewModel you are returning?  DisplayFor does not get sent back to the server ... add this under the displayfor:

```<code>@Html.HiddenFor(Model => Model.Absentee.Name)
</code>```

Title: MVC3-ValidationFailure-RetainValues

Body:
I am using MVC3 in ASP.NET. In the Post Action,
I have an View, In which it should let me edit the values. Some fields are read-only and some fields are editable. If there is a validation failure then it should retain the values and display the same View, if there are no error then it should let me to submit the form.

Control1:
Name I have to display as label as It has to be read-only

@Html.DisplayFor(Model => Model.Absentee.Name)

Control2:

I have to display this one as textbox so that it can be edited. This  is a required Field.

  @Html.TextBoxFor(Model => Model.AbsStart)
     @Html.ValidationMessageFor(Model => Model.AbsStart) (This Makes it as a required Field)

Control 3:

This is also a textbox but not required field.

@Html.DisplayFor(Model => Model.AbsEnteredAt)

When there are no validation errors, things works great, but when there is a validation error, then I will be in the same view(Which is what I want) but the value in First control is not retained.

So Basically, when the validation failure, the value is not retained in the DisplayFor Control

What do I do to sort this?
Thank you

Body:
When there is an error, what is the viewModel you are returning?  DisplayFor does not get sent back to the server ... add this under the displayfor:

@Html.HiddenFor(Model => Model.Absentee.Name)


问:
Is it possible to remove embed value?
I have been trying to remobe the value of an embed because I don't like it there but I cant find a way to "bypass" it.

Does anyone have a solution?

https://i.stack.imgur.com/eQxrG.png

答: Put a whitespace character, like \u0020

Title: Is it possible to remove embed value?

Body: Put a whitespace character, like \u0020


问:
How to select a graph vertex with igraph in R?
In Python you can simply use graph.select() (atleast when reading the documentation: https://igraph.org/python/doc/api/igraph.VertexSeq.html) to select a vertex based on a value. I have a huge graph connecting movies that share an actor. However I would simply like to select one vertex from that graph and then plot it with its direct neighbors. I'm running into issues when I want to select just that single vertex.

I had hoped something like worked

```<code>graph.movies.select('Snatch (2000)')
</code>```

But no luck.

Another approach I took was grabbing the single Snatch vertex by filtering all others out and then adding the edges.

```<code>snatch.graph <- induced.subgraph(g.movies, vids=V(g.movies)$name == 'Snatch (2000)')
snatch.edges <- edges(g.movies, "Snatch (2000)")
add_edges(snatch.graph, snatch.edges$edges)
</code>```

However this returns an empty graph with only the snatch vertex.

My goal is to grab the Snatch vertex and plot this vertex, its DIRECT neighbors and the edges amomng them. Any suggestions? Thanks alot :D Been stuck o nthis for a quite a while -.-

答:
You can use ?ego to grab the neighbours or ?make_ego_graph to form the graph. (Depending on whether your graph is directed or not, you may need to use the mode argument).

An example:

library(igraph)

# create some data
set.seed(71085002)
n = 10
g = random.graph.game(n, 0.25)
V(g)$name = seq_len(n)

# grab neighbours of node "1"
# set mindist = 0 to include node itself
# set order for the stepsize of the neigbourhood;
nb_g = make_ego_graph(g, order=1, node="1", mindist=0)[[1]]

# plot
# you could use the `layout` argument to
# keep nodes in the same position
op = par(mfrow=c(1,2), oma=rep(0,4))
  plot(g, vertex.size=0, vertex.label.cex=3, main="Full graph")
  plot(nb_g, vertex.size=0, vertex.label.cex=3, main="Sub graph")
par(op) # reset
```
<p><img src="https://i.stack.imgur.com/oUKgU.png" alt="enter image description here" /></p>
<p>If you just need a list of the neighbouring nodes:</p>
<pre class="lang-r prettyprint-override"><code>ego(g, order=1, node="1", mindist=0)
# [[1]]
# + 4/10 vertices, named, from 00cfa70:
# [1] 1 4 6 9
</code>```

Body:
In Python you can simply use graph.select() (atleast when reading the documentation: https://igraph.org/python/doc/api/igraph.VertexSeq.html) to select a vertex based on a value. I have a huge graph connecting movies that share an actor. However I would simply like to select one vertex from that graph and then plot it with its direct neighbors. I'm running into issues when I want to select just that single vertex.

I had hoped something like worked

graph.movies.select('Snatch (2000)')

But no luck.

Another approach I took was grabbing the single Snatch vertex by filtering all others out and then adding the edges.

snatch.graph <- induced.subgraph(g.movies, vids=V(g.movies)$name == 'Snatch (2000)')
snatch.edges <- edges(g.movies, "Snatch (2000)")
add_edges(snatch.graph, snatch.edges$edges)

However this returns an empty graph with only the snatch vertex.

My goal is to grab the Snatch vertex and plot this vertex, its DIRECT neighbors and the edges amomng them. Any suggestions? Thanks alot :D Been stuck o nthis for a quite a while -.-

Body:
You can use ?ego to grab the neighbours or ?make_ego_graph to form the graph. (Depending on whether your graph is directed or not, you may need to use the mode argument).

An example:

library(igraph)

# create some data
set.seed(71085002)
n = 10
g = random.graph.game(n, 0.25)
V(g)$name = seq_len(n)

# grab neighbours of node "1"
# set mindist = 0 to include node itself
# set order for the stepsize of the neigbourhood;
nb_g = make_ego_graph(g, order=1, node="1", mindist=0)[[1]]

# plot
# you could use the `layout` argument to
# keep nodes in the same position
op = par(mfrow=c(1,2), oma=rep(0,4))
  plot(g, vertex.size=0, vertex.label.cex=3, main="Full graph")
  plot(nb_g, vertex.size=0, vertex.label.cex=3, main="Sub graph")
par(op) # reset

If you just need a list of the neighbouring nodes:

ego(g, order=1, node="1", mindist=0)
# [[1]]
# + 4/10 vertices, named, from 00cfa70:
# [1] 1 4 6 9


问:
How to display json Image collected from Flickr API in HTML
I've been tasked to build an API that will get data from Flickrs public photo.search API and then feed these pictures to my website. I've used a lot of YouTube videos to try and create my API because I'm totally new to this, I've only written HTML, CSS and basic Java.

But now when I've started my http-server with npm no picture is showing and I'm getting an error in the console in Chrome. Could someone help me get this going? Thanks

```<code>let pagenr=1;
let query ="";

async function Photos(pagenr) {
    const data = await fetch(
        `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=f594577bccc78a7056049a0aaa2d1cc2&per_page=10&format=json&nojsoncallback=1&text=MarvelUniverse`,
        {
            method:"GET",
            headers : {
            Accept: "application/json",

            },
        }
    );
    const result=await data.json();
    console.log(result);
    const pic=document.createElement("div");
        document.querySelector(".gallery").appendChild(pic);
    };
Photos(pagenr);

</code>```

EDIT: I've tried to change the .json to .text and the error is gone but I'm now getting the raw json string from the Flickr API. I want that json to be converted to an object to display as an image in the HTML with http-server. Any help is appreciated!

EDIT 2: Changed the API URL and back to .json and all seems good but can't get anything to be displayed in my HTML.

答:
The issue is because inside the URL you have jsoncallback=FlickrPhotoSearch which is designed to help invoke a function after an API call. This actually means the response type is no longer valid JSON which is causing the error you are seeing. You want to get the raw JSON, for the Flickr API you need to add nojsoncallback=1 and remove jsoncallback=FlickrPhotoSearch from the API URL.

You seemed to have posted the URL with your API key included inside too, this meant I was able to access the link using your API credentials and anyone else can do the same. You should change this key as soon as possible.

Body:
I've been tasked to build an API that will get data from Flickrs public photo.search API and then feed these pictures to my website. I've used a lot of YouTube videos to try and create my API because I'm totally new to this, I've only written HTML, CSS and basic Java.

But now when I've started my http-server with npm no picture is showing and I'm getting an error in the console in Chrome. Could someone help me get this going? Thanks

let pagenr=1;
let query ="";

async function Photos(pagenr) {
    const data = await fetch(
        `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=f594577bccc78a7056049a0aaa2d1cc2&per_page=10&format=json&nojsoncallback=1&text=MarvelUniverse`,
        {
            method:"GET",
            headers : {
            Accept: "application/json",

            },
        }
    );
    const result=await data.json();
    console.log(result);
    const pic=document.createElement("div");
        document.querySelector(".gallery").appendChild(pic);
    };
Photos(pagenr);

EDIT: I've tried to change the .json to .text and the error is gone but I'm now getting the raw json string from the Flickr API. I want that json to be converted to an object to display as an image in the HTML with http-server. Any help is appreciated!

EDIT 2: Changed the API URL and back to .json and all seems good but can't get anything to be displayed in my HTML.


问:
Need help determining why docker compose attempts to launch dependent containers before building dependencies
I am hoping that someone can help me understand an error that I have encountered while building a multi-container environment using Docker Desktop for Windows using WSL2 (Don't think these details matter, but you never know)

I have a docker-compose.yml script that builds a number of containers that are all linked together.  I can get it to work in a very janky way by commenting and uncommenting specific containers, but this seems counter productive to how docker compose is supposed to work from my understanding.

Before anyone comments something about using something like docker-compose-wait or docker-wait the problem with those solutions is that they are run during the build process, the error I am getting is happening before that build process ever gets a chance to process.

This is my docker-compose.yml file:

```<code>version: "3.4"

services:
  # Redis Service
  redis:
    build:
      context: .
      dockerfile: docker/redis/Dockerfile
    image: star/redis
    container_name: star_redis
    restart: unless-stopped
    tty: true
    ports:
      - "16379:6379"
    volumes:
      - redis_data:/data

  db:
    build:
      context: .
      dockerfile: docker/mysql/Dockerfile
    image: star/mysql
    container_name: star_db
    restart: unless-stopped
    tty: true
    environment:
      RUN_INIT_FILES: ${DOCKER_RUN_MYSQL_INIT}
      SERVICE_TAGS: dev
      SERVICE_NAME: MySQL
    ports:
      - "3306:3306"
    volumes:
      - ${WEB_APP_PATH}${WEB_APP_PROJECT_PATH}/docker/mysql/init:/docker-entrypoint- initdb.d
      - star_mysql_db:/var/lib/mysql

  app:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    image: star/php
    container_name: star_app
    restart: unless-stopped
    tty: true
    environment:
      RUNNING_IN_DOCKER: 'true'
      SERVICE_NAME: app
      SERVICE_TAGS: dev
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    depends_on:
      - redis
      - db

  nginx:
    build:
      context: .
      dockerfile: docker/nginx/Dockerfile
    image: star/nginx
    container_name: star_webserver
    restart: unless-stopped
    tty: true
    environment:
      RUNNING_IN_DOCKER: 'true'
    ports:
      - '80:80'
      - '443:443'
      - '8888:80'
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    depends_on:
      - db
      - app

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: star_phpmyadmin
    environment:
      PMA_PORT: 3306
      PMA_HOST: db
      PMA_USER: ####
      PMA_PASSWORD: ######
    links:
       - db:MySQL
    ports:
       - "8090:80"
    restart: unless-stopped
    depends_on:
      - db
      - app
      - nginx

  package-installer:
    image: star/php:latest
    container_name: star_installer
    restart: on-failure
    depends_on:
      - db
      - app
      - nginx
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    environment:
      APP_ENV: local
      CONTAINER_ROLE: installer
      CACHE_DRIVER: redis
      SESSION_DRIVER: redis
      QUEUE_DRIVER: redis
      REDIS_HOST: redis

# Scheduler Service
 scheduler:
   image: star/php:latest
   container_name: star_scheduler
   restart: on-failure
   depends_on:
     - db
     - app
     - nginx
     - package-installer
   volumes:
     - star_laravel_data:${WEB_DESTINATION_PATH}
   environment:
     APP_ENV: local
     CONTAINER_ROLE: scheduler
     CACHE_DRIVER: redis
     SESSION_DRIVER: redis
     QUEUE_DRIVER: redis
     REDIS_HOST: redis

  # Queue Service
  queue:
    image: star/php:latest
    container_name: star_queue
    restart: on-failure
    logging:
      driver: local
    depends_on:
      - db
      - app
      - nginx
      - package-installer
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    environment:
      APP_ENV: local
      CONTAINER_ROLE: queue
      CACHE_DRIVER: redis
      SESSION_DRIVER: redis
      QUEUE_DRIVER: redis
      REDIS_HOST: redis

  volumes:
    star_laravel_data:
      driver: local
      driver_opts:
        type: none
        o: bind
        device: ${WEB_APP_PATH}${WEB_APP_PROJECT_PATH}
    star_mysql_db:
    portainer_data:
    redis_data:
      driver: local
</code>```

So here is the crux of the problem, if I run this, as a fresh install I get this response from docker compose:

```<code>[+] Running 0/3
 - package-installer Error
 - scheduler Error
 - queue Error
Error response from daemon: pull access denied for star/php, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
</code>```

These containers which all have a depends_on field to tell them other containers at least need to be started first are the first ones that docker compose attempts to build.  To me that makes no sense.  These have a depends_on for a reason, they are using the custom image created by the app container to build their own containers.  So why, if they are told they depend on other containers, and they are at the bottom of the script, are they the first ones that docker compose tries to build?

My only working solutions thus far has been:

Comment out the package-installer, scheduler, and queue containers in the docker-compose.yml file

Build the environment

Shut down the environment

Un-comment the package-installer container

Re-build the environment (because now the custom star/php image exists)

Shut down the environment

Un-comment the scheduler and queue containers

Re-build the environment...again (because now the files added by running the package-installer Dockerfile have been added)

Now I can use the environment

If this was just my own environment this wouldn't be an issue, but this docker stack was designed for our development team to be able to use it.  With this strategy to get it installed, I would have to explain the process to each person on how to comment and un-comment the various packages to get it to work.  That would be a nightmare.

Based on the docker documentation, the depends_on field is supposed to build the containers in order of their dependence, which means the containers should be built in this order:

redis

db

app

nginx

phpmyadmin

package-installer

queue / scheduler

Again, I'm not concerned if the container that it is depending on is running, it simply needs to be built, but it doesn't seem to be doing that, it seems (at least for the three affected containers) to skip right to the running stage, without building the dependencies).

Any useful insight or tips would be welcomed.

答: depends_on does not wait for other containers to be “ready” before starting only until they have been started. If you need to wait for a service to be ready, see https://docs.docker.com/compose/startup-order/ for solving it.</p>

Body:
I am hoping that someone can help me understand an error that I have encountered while building a multi-container environment using Docker Desktop for Windows using WSL2 (Don't think these details matter, but you never know)

I have a docker-compose.yml script that builds a number of containers that are all linked together.  I can get it to work in a very janky way by commenting and uncommenting specific containers, but this seems counter productive to how docker compose is supposed to work from my understanding.

Before anyone comments something about using something like docker-compose-wait or docker-wait the problem with those solutions is that they are run during the build process, the error I am getting is happening before that build process ever gets a chance to process.

This is my docker-compose.yml file:

version: "3.4"

services:
  # Redis Service
  redis:
    build:
      context: .
      dockerfile: docker/redis/Dockerfile
    image: star/redis
    container_name: star_redis
    restart: unless-stopped
    tty: true
    ports:
      - "16379:6379"
    volumes:
      - redis_data:/data

  db:
    build:
      context: .
      dockerfile: docker/mysql/Dockerfile
    image: star/mysql
    container_name: star_db
    restart: unless-stopped
    tty: true
    environment:
      RUN_INIT_FILES: ${DOCKER_RUN_MYSQL_INIT}
      SERVICE_TAGS: dev
      SERVICE_NAME: MySQL
    ports:
      - "3306:3306"
    volumes:
      - ${WEB_APP_PATH}${WEB_APP_PROJECT_PATH}/docker/mysql/init:/docker-entrypoint- initdb.d
      - star_mysql_db:/var/lib/mysql

  app:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    image: star/php
    container_name: star_app
    restart: unless-stopped
    tty: true
    environment:
      RUNNING_IN_DOCKER: 'true'
      SERVICE_NAME: app
      SERVICE_TAGS: dev
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    depends_on:
      - redis
      - db

  nginx:
    build:
      context: .
      dockerfile: docker/nginx/Dockerfile
    image: star/nginx
    container_name: star_webserver
    restart: unless-stopped
    tty: true
    environment:
      RUNNING_IN_DOCKER: 'true'
    ports:
      - '80:80'
      - '443:443'
      - '8888:80'
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    depends_on:
      - db
      - app

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: star_phpmyadmin
    environment:
      PMA_PORT: 3306
      PMA_HOST: db
      PMA_USER: ####
      PMA_PASSWORD: ######
    links:
       - db:MySQL
    ports:
       - "8090:80"
    restart: unless-stopped
    depends_on:
      - db
      - app
      - nginx

  package-installer:
    image: star/php:latest
    container_name: star_installer
    restart: on-failure
    depends_on:
      - db
      - app
      - nginx
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    environment:
      APP_ENV: local
      CONTAINER_ROLE: installer
      CACHE_DRIVER: redis
      SESSION_DRIVER: redis
      QUEUE_DRIVER: redis
      REDIS_HOST: redis

# Scheduler Service
 scheduler:
   image: star/php:latest
   container_name: star_scheduler
   restart: on-failure
   depends_on:
     - db
     - app
     - nginx
     - package-installer
   volumes:
     - star_laravel_data:${WEB_DESTINATION_PATH}
   environment:
     APP_ENV: local
     CONTAINER_ROLE: scheduler
     CACHE_DRIVER: redis
     SESSION_DRIVER: redis
     QUEUE_DRIVER: redis
     REDIS_HOST: redis

  # Queue Service
  queue:
    image: star/php:latest
    container_name: star_queue
    restart: on-failure
    logging:
      driver: local
    depends_on:
      - db
      - app
      - nginx
      - package-installer
    volumes:
      - star_laravel_data:${WEB_DESTINATION_PATH}
    environment:
      APP_ENV: local
      CONTAINER_ROLE: queue
      CACHE_DRIVER: redis
      SESSION_DRIVER: redis
      QUEUE_DRIVER: redis
      REDIS_HOST: redis

  volumes:
    star_laravel_data:
      driver: local
      driver_opts:
        type: none
        o: bind
        device: ${WEB_APP_PATH}${WEB_APP_PROJECT_PATH}
    star_mysql_db:
    portainer_data:
    redis_data:
      driver: local

So here is the crux of the problem, if I run this, as a fresh install I get this response from docker compose:

[+] Running 0/3
 - package-installer Error
 - scheduler Error
 - queue Error
Error response from daemon: pull access denied for star/php, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

These containers which all have a depends_on field to tell them other containers at least need to be started first are the first ones that docker compose attempts to build.  To me that makes no sense.  These have a depends_on for a reason, they are using the custom image created by the app container to build their own containers.  So why, if they are told they depend on other containers, and they are at the bottom of the script, are they the first ones that docker compose tries to build?

My only working solutions thus far has been:

Comment out the package-installer, scheduler, and queue containers in the docker-compose.yml file

Build the environment

Shut down the environment

Un-comment the package-installer container

Re-build the environment (because now the custom star/php image exists)

Shut down the environment

Un-comment the scheduler and queue containers

Re-build the environment...again (because now the files added by running the package-installer Dockerfile have been added)

Now I can use the environment

If this was just my own environment this wouldn't be an issue, but this docker stack was designed for our development team to be able to use it.  With this strategy to get it installed, I would have to explain the process to each person on how to comment and un-comment the various packages to get it to work.  That would be a nightmare.

Based on the docker documentation, the depends_on field is supposed to build the containers in order of their dependence, which means the containers should be built in this order:

redis

db

app

nginx

phpmyadmin

package-installer

queue / scheduler

Again, I'm not concerned if the container that it is depending on is running, it simply needs to be built, but it doesn't seem to be doing that, it seems (at least for the three affected containers) to skip right to the running stage, without building the dependencies).

Any useful insight or tips would be welcomed.


问:
Count strings in Series Python
I have the following dataframe:

```<code>import pandas as pd

df = pd.DataFrame({'X': ['Ciao, I would like to count the number of occurrences in this text considering negations that can change the meaning of the sentence',
                    "Hello, not number of negations, in this case we need to take care of the negation.",
                    "Hello world, don't number is another case in which where we need to consider negations."]})

</code>```

I would like to count how many times a string appears in those senteces. So I simply do:

```<code>d = pd.DataFrame(['need'], columns = ['D'])
df['X'].str.count('|'.join(d.append({'D': 'number'}, ignore_index = True).D))

0    1
1    2
2    2
Name: X, dtype: int64

</code>```

However, in the application I am doing, I need to loop over each element of df which means:

```<code>res=[]
for i in range(len(df)):
    f = df['X'][i].count('|'.join(d.append({'D': 'number'}, ignore_index = True).D))
    res.append(f)

[0,0,0]

</code>```

I get two different results. The first one is obviously correct.

How can I fix it?

Thanks!

答:
Use iterrows:

```<code>import re

words = ['need', 'number']

res = {}
for idx, row in df.iterrows():
    count = len(re.findall('|'.join(words), row['X']))
    res[idx] = count
df['count'] = pd.Series(res)
</code>```

Output:

```<code>>>> df
                                                   X  count
0  Ciao, I would like to count the number of occu...      1
1  Hello, not number of negations, in this case w...      2
2  Hello world, don't number is another case in w...      2
</code>```

Title: Count strings in Series Python

Body:
I have the following dataframe:

import pandas as pd

df = pd.DataFrame({'X': ['Ciao, I would like to count the number of occurrences in this text considering negations that can change the meaning of the sentence',
                    "Hello, not number of negations, in this case we need to take care of the negation.",
                    "Hello world, don't number is another case in which where we need to consider negations."]})

I would like to count how many times a string appears in those senteces. So I simply do:

d = pd.DataFrame(['need'], columns = ['D'])
df['X'].str.count('|'.join(d.append({'D': 'number'}, ignore_index = True).D))

0    1
1    2
2    2
Name: X, dtype: int64

However, in the application I am doing, I need to loop over each element of df which means:

res=[]
for i in range(len(df)):
    f = df['X'][i].count('|'.join(d.append({'D': 'number'}, ignore_index = True).D))
    res.append(f)

[0,0,0]

I get two different results. The first one is obviously correct.

How can I fix it?

Thanks!

Body:
Use iterrows:

import re

words = ['need', 'number']

res = {}
for idx, row in df.iterrows():
    count = len(re.findall('|'.join(words), row['X']))
    res[idx] = count
df['count'] = pd.Series(res)

Output:

>>> df
                                                   X  count
0  Ciao, I would like to count the number of occu...      1
1  Hello, not number of negations, in this case w...      2
2  Hello world, don't number is another case in w...      2


问:
Extracting value from an array of formArray elements gives error
I have a form array in a form group defined as follows:

```<code>  agreementForm: FormGroup;
  agrArr: any[] = [];

  constructor() {
    this.agreementForm = new FormGroup({
      serviceArr: new FormArray([])
    });
  }

  submitAgreement() {
    const data = this.agreementForm.value;
    this.agrArr.push(data);
  }

  submitForm() {
    console.log(this.agrArr);
    for(i=0;i<this.agrArr.length;i++) {
      for(j=0;j<this.agrArr[i].serviceArr.length;j++){
        console.log(this.agrArr[i].serviceArr[j]);
      }
    }
  }
</code>```

Here, I am trying to have a form array within an array for master detail use. I am able to log the agrArr onto the console before the for loop, however when I get to the second for loop, I get the following error:

ERROR TypeError: Cannot read properties of undefined (reading 'serviceArr')

And when I try to log in individual elements of agrArr onto the console I get undefined as the result. How can this be when I get the complete array at first? Where am I going wrong and how do I access individual elements of my two arrays?

答:
What happens is that to use find you first need to verify that the array is not undefined and also has a size greater than zero.

Try this:

```<code>submitForm() {
    console.log(this.agrArr);
    for(i=0;i<this.agrArr.length;i++) {
      if (this.agrArr[i].serviceArr && this.agrArr[i].serviceArr.length > 0) {
        for(j=0;j<this.agrArr[i].serviceArr.length;j++){
          console.log(this.agrArr[i].serviceArr[j]);
        }
      }

    }
}
</code>```

Body:
I have a form array in a form group defined as follows:

  agreementForm: FormGroup;
  agrArr: any[] = [];

  constructor() {
    this.agreementForm = new FormGroup({
      serviceArr: new FormArray([])
    });
  }

  submitAgreement() {
    const data = this.agreementForm.value;
    this.agrArr.push(data);
  }

  submitForm() {
    console.log(this.agrArr);
    for(i=0;i<this.agrArr.length;i++) {
      for(j=0;j<this.agrArr[i].serviceArr.length;j++){
        console.log(this.agrArr[i].serviceArr[j]);
      }
    }
  }

Here, I am trying to have a form array within an array for master detail use. I am able to log the agrArr onto the console before the for loop, however when I get to the second for loop, I get the following error:

ERROR TypeError: Cannot read properties of undefined (reading 'serviceArr')

And when I try to log in individual elements of agrArr onto the console I get undefined as the result. How can this be when I get the complete array at first? Where am I going wrong and how do I access individual elements of my two arrays?

Body:
What happens is that to use find you first need to verify that the array is not undefined and also has a size greater than zero.

Try this:

submitForm() {
    console.log(this.agrArr);
    for(i=0;i<this.agrArr.length;i++) {
      if (this.agrArr[i].serviceArr && this.agrArr[i].serviceArr.length > 0) {
        for(j=0;j<this.agrArr[i].serviceArr.length;j++){
          console.log(this.agrArr[i].serviceArr[j]);
        }
      }

    }
}


问:
How to read a JSON file content from GitHub public repository using RestTemplate?
I need to read the content of a JSON file on a public GitHub repository using RestTemplate. The content of this JSON file keeps changing quite often, so I need to pull the data from this file once a week. I just need to get the content as String object. Is there anyway to do that?

An example of a JSON file on a public GitHub repository: JSON_File

答:
Using RestTemplate, you can achieve it in this way.

```<code>String fortune500String = restTemplate.getForEntity
   ("https://raw.githubusercontent.com/dariusk/corpora/master/data/corporations/fortune500.json", String.class);
</code>```

That will return a ResponseEntity of type String, of which you can invoke getBody() to get the String.

That's what you've asked for, but I think there's a better approach.  I assume that the data itself is the only thing that changes, and not the structure.  Given this assumption, create a model that represents the data, like this:

```<code>@Data
public class Fortune500 {
  private String description;
  private List<String> companies;
}
</code>```

Then configure RestTemplate to be able to convert from the content type of text/plain

```<code>RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(List.of(MediaType.TEXT_PLAIN));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
</code>```

Then you can have RestTemplate return an instance of the model, which will be much easier for you to work with.

```<code>Fortune500 fortune500 = restTemplate.getForEntity
    ("https://raw.githubusercontent.com/dariusk/corpora/master/data/corporations/fortune500.json", Fortune500.class).getBody();
</code>```

Body:
Using RestTemplate, you can achieve it in this way.

String fortune500String = restTemplate.getForEntity
   ("https://raw.githubusercontent.com/dariusk/corpora/master/data/corporations/fortune500.json", String.class);

That will return a ResponseEntity of type String, of which you can invoke getBody() to get the String.

That's what you've asked for, but I think there's a better approach.  I assume that the data itself is the only thing that changes, and not the structure.  Given this assumption, create a model that represents the data, like this:

@Data
public class Fortune500 {
  private String description;
  private List<String> companies;
}

Then configure RestTemplate to be able to convert from the content type of text/plain

RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(List.of(MediaType.TEXT_PLAIN));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);

Then you can have RestTemplate return an instance of the model, which will be much easier for you to work with.

Fortune500 fortune500 = restTemplate.getForEntity
    ("https://raw.githubusercontent.com/dariusk/corpora/master/data/corporations/fortune500.json", Fortune500.class).getBody();


问:
Access aws elastic search role based using python elastic search package
I am using deepset/haystack and communicating with elastic search. Using OpenDistroElasticsearchDocumentStore method works fine with username,pasword access to aws elastic search. Doesnt seem to work with role based access when deployed in ec2. Please suggest me a solution to access aws elastic search using python elastic search package given a role access</p>

答:
```<code>from requests_aws4auth import AWS4Auth
from botocore.session import Session
credentials = Session().get_credentials()
auth = AWS4Auth(region='eu-west-1', service='es', refreshable_credentials=credentials)
</code>```

This example shows how to construct an AWS4Auth instance with automatically refreshing credentials, suitable for long-running applications using AWS IAM assume-role. The RefreshableCredentials instance is used to generate valid static credentials per-request, eliminating the need to recreate the AWS4Auth instance when temporary credentials expire.

Source: https://github.com/tedder/requests-aws4auth#dynamic-sts-credentials-using-botocore-refreshablecredentials

This was merged into AWS4Auth in May 2021.

Body:
from requests_aws4auth import AWS4Auth
from botocore.session import Session
credentials = Session().get_credentials()
auth = AWS4Auth(region='eu-west-1', service='es', refreshable_credentials=credentials)

This example shows how to construct an AWS4Auth instance with automatically refreshing credentials, suitable for long-running applications using AWS IAM assume-role. The RefreshableCredentials instance is used to generate valid static credentials per-request, eliminating the need to recreate the AWS4Auth instance when temporary credentials expire.

Source: https://github.com/tedder/requests-aws4auth#dynamic-sts-credentials-using-botocore-refreshablecredentials

This was merged into AWS4Auth in May 2021.


问:
How to give a .tf file as input in Terraform Apply command?
I'm a beginner in Terraform.

I have a directory which contains 2 .tf files.

Now I want to run Terraform Apply on a selected .tf file & neglect the other one.

Can I do that? If yes, how? If no, why & what is the best practice?

答:
```<code>terraform apply -target nginx-docker.tf
</code>```

Body: terraform apply -target nginx-docker.tf


答:
I think the fastest way is to use another function to count number of occurrences in a regex. You can try something like that:

import re
res=[]
for i in range(len(df)):
    pattern = '|'.join(d.append({'D': 'number'}, ignore_index = True).D)
    text = df['X'][I]
    count = len(re.findall(pattern, text))
    res.append(count)
```

Title: Count strings in Series Python


问:
Connect Timeout with Alarm()
Since it seems that I can't find a solution to my original problem, I tried to do a little workaround. I'm simply trying to set a timeout to the connect() call of my TCP Socket.

I want the connect() to be blocking but not until the usual 75 seconds timeout, I want to define my own.

I have already tried select() which worked for the timeout but I couldn't get a connection (that was my initial problem as described here ).

So now I found another way to deal with it: just do a blocking connect() call but interrupt it with an alarm like this :

```<code>    signal(SIGALRM, connect_alarm);
    int secs = 5;
    alarm(secs);
    if (connect(m_Socket, (struct sockaddr *)&addr, sizeof(addr)) < 0 )
    {
        if ( errno == EINTR )
        {
            debug_printf("Timeout");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_TIMEOUT;
        }
        else
        {
            debug_printf("Other Err");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_NET_SOCKET;
        }
    }
</code>```

with

```<code>static void connect_alarm(int signo)
{
     debug_printf("SignalHandler");
     return;
}
</code>```

This is the solution I found on the Internet in a thread here on stackoverflow. If I use this code the program starts the timer and then goes into the connect() call. After the 5 seconds the signal handler is fired (as seen on the console with the printf()), but after that the program still remains within the connect() function for 75 seconds. Actually every description says that the connect_alarm() should interrupt the connect() function but it seems it doesn't in my case. Is there any way to get the desired result for my problem?

答:
signal is a massively under-specified interface and should be avoided in new code.  On some versions of Linux, I believe it provides "BSD semantics", which means (among other things) that providing SA_RESTART by default.

Use sigaction instead, do not specify SA_RESTART, and you should be good to go.

...

Well, except for the general fragility and unavoidable race conditions, that is.  connect will return EINTR for any signal, not just SIGALARM.  More troublesome, if the system happens to be under heavy load, it could take more than 5 seconds between the call to alarm and the call to connect, in which case you will miss the signal and block in connect forever.

Your earlier attempt, using non-blocking sockets with connect and select, was a much better idea.  I would suggest debugging that.

Title: Connect Timeout with Alarm()

Body:
Since it seems that I can't find a solution to my original problem, I tried to do a little workaround. I'm simply trying to set a timeout to the connect() call of my TCP Socket.

I want the connect() to be blocking but not until the usual 75 seconds timeout, I want to define my own.

I have already tried select() which worked for the timeout but I couldn't get a connection (that was my initial problem as described here ).

So now I found another way to deal with it: just do a blocking connect() call but interrupt it with an alarm like this :

    signal(SIGALRM, connect_alarm);
    int secs = 5;
    alarm(secs);
    if (connect(m_Socket, (struct sockaddr *)&addr, sizeof(addr)) < 0 )
    {
        if ( errno == EINTR )
        {
            debug_printf("Timeout");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_TIMEOUT;
        }
        else
        {
            debug_printf("Other Err");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_NET_SOCKET;
        }
    }

with

static void connect_alarm(int signo)
{
     debug_printf("SignalHandler");
     return;
}

This is the solution I found on the Internet in a thread here on stackoverflow. If I use this code the program starts the timer and then goes into the connect() call. After the 5 seconds the signal handler is fired (as seen on the console with the printf()), but after that the program still remains within the connect() function for 75 seconds. Actually every description says that the connect_alarm() should interrupt the connect() function but it seems it doesn't in my case. Is there any way to get the desired result for my problem?


问:
Azure DevOps Portfolio plans (beta) too slow and lacks significant features
Portfolio Plans (Beta) roadmapping tool in ADO is not a full-featured tool and lacks significant features that are needed to effectively create and manage product roadmaps. Are there any alternative extensions?</p>

答: I would use Portfolio++.  It provides cross-project roadmaps, Epic/Feature Timeline - as well as Boards work-item quality assurance (Epic status), and the Pro version offers dependencies, milestones, and the ability to sort the order of the epics in the Roadmap.</p>


问:
Autocomplete - Free solo — Why does the close button is not accessible by keyboard?
In Material UI Autocomplete Free Solo, I noticed that the "Clear input" button is clickable, but not accessible by keyboard.

I went into the codebase to understand the reasoning behind this decision but didn't find anything. I also checked the A11Y docs but without success either... Could anyone give a little more detail about this? Was it a decision based on user testing?

Code that adds the tabindex="-1"

Testing the tabindex="-1"

Thanks :)

答:
As far as why it's behaving the way it is, you already discovered that.  tabindex="-1" means the element should be removed from the normal tabbing order but still allows the elmenet to be focused programmatically (if you call obj.focus() from javascript).

If you're asking why Material decided to not have that button focusable, @rafael is correct that that's not a stackoverflow question.  Someone working for Material that happens to be on stackoverflow might see this question and try to answer it but you're more likely to get an answer if you ask them directly.

Note that WCAG 2.1.1 is often misunderstood that every interactive element on the page must be accessible via the keyboard.  That's not true.  What that checkpoint says is that all "functionality" of the page must be accessible through the keyboard.  In the case of the X-clear button, that functionality is also available via the keyboard because when you TAB to the input field, all the text gets selected so you can either press DELETE or BACKSPACE to erase it or just start typing new text.  Or you can press Ctrl (or CMD) + A to select all the text and delete it.

So all the functionality of the X-clear button is available to the keyboard user without the actual button being accessible.

Now having said that, I rarely, if ever, make a button that is clickable with the mouse not available to the keyboard user.


问:
What to prevent multiple toplevels from appearing in Tkinter?
What can I do to prevent toplevels from appearing in Tkinter?

```<code>from tkinter import *
import os

root = Tk()

def top_level():
    a=Toplevel()
    l=Label(a,text="yeni")
    l.pack()

    def yeni():
        root.destroy()
        os.startfile("a.pyw")

        top_level()

    bt1= Button(a,  text="Top Level",command= yeni)
    bt1.pack()
    a.mainloop()

bt= Button(root,  text="Top Level",command= top_level)
bt.pack()

root.mainloop()
</code>```

It outputs like this:

答: a is the Toplevel so a.destroy()

Body:
What can I do to prevent toplevels from appearing in Tkinter?

from tkinter import *
import os

root = Tk()

def top_level():
    a=Toplevel()
    l=Label(a,text="yeni")
    l.pack()

    def yeni():
        root.destroy()
        os.startfile("a.pyw")

        top_level()

    bt1= Button(a,  text="Top Level",command= yeni)
    bt1.pack()
    a.mainloop()

bt= Button(root,  text="Top Level",command= top_level)
bt.pack()

root.mainloop()

It outputs like this:

Body: a is the Toplevel so a.destroy()