问:
Embedding multiple instances of a flash component in a Flex application
I have a flash application (pure AS, no Flex framework) that I'd like to embed inside of a flex application using SWFLoader.

Embedding one instance works well. However, when I try to embed multiple instances (each with a separate SwfLoader), there is really strange behavior that seems to be caused by clashes among the class definitions of the multiple instances. This flash application is written with a lot of singleton classes, so my guess is that these singletons are overriding each other and causing the weird behavior.

I tried loading the flash application into a child applicationdomain, but that doesn't seem to help much either. Has anyone faced this problem?

答:
You would want to load the SWF into its own application domain (not a child) to avoid name clashing.

There are three types of application domains:

```<code>var swfLoader:Loader = new Loader();
var loaderContext:LoaderContext = new LoaderContext();

// child SWF adds its unique definitions to
// parent SWF; both SWFs share the same domain
// child SWFs definitions do not overwrite parents
loaderContext.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);

// child SWF uses parent domain definitions
// if defined there, otherwise its own
loaderContext.applicationDomain = ApplicationDomain.currentDomain;

// child SWF domain is completely separate and
// each SWF uses its own definitions
loaderContext.applicationDomain = new ApplicationDomain();

// Load the swf file
swfLoader.load(new URLRequest("file.swf"), loaderContext);
</code>```

I would suggest using the first method, as it will not overwrite definitions.

OwnerDisplayName: Michael Hoisie

ContentLicense: CC BY-SA 2.5

Body:
You would want to load the SWF into its own application domain (not a child) to avoid name clashing.

There are three types of application domains:

var swfLoader:Loader = new Loader();
var loaderContext:LoaderContext = new LoaderContext();

// child SWF adds its unique definitions to
// parent SWF; both SWFs share the same domain
// child SWFs definitions do not overwrite parents
loaderContext.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);

// child SWF uses parent domain definitions
// if defined there, otherwise its own
loaderContext.applicationDomain = ApplicationDomain.currentDomain;

// child SWF domain is completely separate and
// each SWF uses its own definitions
loaderContext.applicationDomain = new ApplicationDomain();

// Load the swf file
swfLoader.load(new URLRequest("file.swf"), loaderContext);

I would suggest using the first method, as it will not overwrite definitions.

OwnerDisplayName: LiraNuna


来源: stackexchange

问:
xcopy file and folder from a changing directory
I have been having 0 files copied message when attempting to Xcopy files.
Note that I managed to do it successfully by specifying an exact source path as shown below:

```<code>xcopy /y %USERPROFILE%\Desktop\WinXTweak\program1.exe %WINDIR%\
xcopy /y %USERPROFILE%\Desktop\WinXTweak\program2.exe %WINDIR%\
xcopy /y %USERPROFILE%\Desktop\WinXTweak\program3.exe %WINDIR%\
</code>```

Of course, this would only work if the WinXTweak folder is on the desktop. I would like to be able to copy it into a USB drive for instance or any location in my PC and run it. The location of the batch file is inside the WinXTweak folder too. I could not figure out what to do. I tried the ones below but it did fail.

```<code>xcopy /y program1.exe %WINDIR%\
xcopy /y program2.exe %WINDIR%\
xcopy /y program3.exe %WINDIR%\
</code>```

Thanks all in advance,

答:
Thanks all for your reply. After reading more stuff online, I was able to resolve the issue by using the following code. I am a newbie at this, and there might be a much simpler way this is what I used.

```<code>@echo off

set source=%~dp0*.exe
set target="%WINDIR%"
xcopy /y "%source%" "%target%"
</code>```

The suggested answers I will take note and learn so I can use it in the future.

Thank you for helping and best regards,

ContentLicense: CC BY-SA 4.0

Body:
I have been having 0 files copied message when attempting to Xcopy files.
Note that I managed to do it successfully by specifying an exact source path as shown below:

xcopy /y %USERPROFILE%\Desktop\WinXTweak\program1.exe %WINDIR%\
xcopy /y %USERPROFILE%\Desktop\WinXTweak\program2.exe %WINDIR%\
xcopy /y %USERPROFILE%\Desktop\WinXTweak\program3.exe %WINDIR%\

Of course, this would only work if the WinXTweak folder is on the desktop. I would like to be able to copy it into a USB drive for instance or any location in my PC and run it. The location of the batch file is inside the WinXTweak folder too. I could not figure out what to do. I tried the ones below but it did fail.

xcopy /y program1.exe %WINDIR%\
xcopy /y program2.exe %WINDIR%\
xcopy /y program3.exe %WINDIR%\

Thanks all in advance,

Body:
Thanks all for your reply. After reading more stuff online, I was able to resolve the issue by using the following code. I am a newbie at this, and there might be a much simpler way this is what I used.

@echo off

set source=%~dp0*.exe
set target="%WINDIR%"
xcopy /y "%source%" "%target%"

The suggested answers I will take note and learn so I can use it in the future.

Thank you for helping and best regards,


问:
Return all records in one query in Elasticsearch
I have a database in elastic search and want to get all records on my web site page. I wrote a bean, which connects to the elastic search node, searches records and returns some response. My simple java code, which does the searching, is

```<code>SearchResponse response = getClient().prepareSearch(indexName)
    .setTypes(typeName)
    .setQuery(queryString("\*:*"))
    .setExplain(true)
    .execute().actionGet();
</code>```

But Elasticsearch set default size to 10 and I have 10 hits in response. There are more than 10 records in my database. If I set size to Integer.MAX_VALUE my search becomes very slow and this not what I want.

How can I get all the records in one action in an acceptable amount of time without setting size of response?

答:
It has been long since you asked this question, and I would like to post my answer for future readers.

As mentioned above answers, it is better to load documents with size and start when you have thousands of documents in the index. In my project, the search loads 50 results as default size and starting from zero index, if a user wants to load more data, then the next 50 results will be loaded. Here what I have done in the code:

```<code>public List<CourseDto> searchAllCourses(int startDocument) {

    final int searchSize = 50;
    final SearchRequest searchRequest = new SearchRequest("course_index");
    final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());

    if (startDocument != 0) {
        startDocument += searchSize;
    }

    searchSourceBuilder.from(startDocument);
    searchSourceBuilder.size(searchSize);

    // sort the document
    searchSourceBuilder.sort(new FieldSortBuilder("publishedDate").order(SortOrder.ASC));
    searchRequest.source(searchSourceBuilder);

    List<CourseDto> courseList = new ArrayList<>();

    try {
        final SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        final SearchHits hits = searchResponse.getHits();

        // Do you want to know how many documents (results) are returned? here is you get:
        TotalHits totalHits = hits.getTotalHits();
        long numHits = totalHits.value;

        final SearchHit[] searchHits = hits.getHits();

        final ObjectMapper mapper = new ObjectMapper();

        for (SearchHit hit : searchHits) {
            // convert json object to CourseDto
            courseList.add(mapper.readValue(hit.getSourceAsString(), CourseDto.class));
        }
    } catch (IOException e) {
        logger.error("Cannot search by all mach. " + e);
    }
    return courseList;
}
</code>```

Info:
- Elasticsearch version 7.5.0
- Java High Level REST Client is used as client.

I Hope, this will be useful for someone.

Body:
I have a database in elastic search and want to get all records on my web site page. I wrote a bean, which connects to the elastic search node, searches records and returns some response. My simple java code, which does the searching, is

SearchResponse response = getClient().prepareSearch(indexName)
    .setTypes(typeName)
    .setQuery(queryString("\*:*"))
    .setExplain(true)
    .execute().actionGet();

But Elasticsearch set default size to 10 and I have 10 hits in response. There are more than 10 records in my database. If I set size to Integer.MAX_VALUE my search becomes very slow and this not what I want.

How can I get all the records in one action in an acceptable amount of time without setting size of response?

Body:
It has been long since you asked this question, and I would like to post my answer for future readers.

As mentioned above answers, it is better to load documents with size and start when you have thousands of documents in the index. In my project, the search loads 50 results as default size and starting from zero index, if a user wants to load more data, then the next 50 results will be loaded. Here what I have done in the code:

public List<CourseDto> searchAllCourses(int startDocument) {

    final int searchSize = 50;
    final SearchRequest searchRequest = new SearchRequest("course_index");
    final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());

    if (startDocument != 0) {
        startDocument += searchSize;
    }

    searchSourceBuilder.from(startDocument);
    searchSourceBuilder.size(searchSize);

    // sort the document
    searchSourceBuilder.sort(new FieldSortBuilder("publishedDate").order(SortOrder.ASC));
    searchRequest.source(searchSourceBuilder);

    List<CourseDto> courseList = new ArrayList<>();

    try {
        final SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        final SearchHits hits = searchResponse.getHits();

        // Do you want to know how many documents (results) are returned? here is you get:
        TotalHits totalHits = hits.getTotalHits();
        long numHits = totalHits.value;

        final SearchHit[] searchHits = hits.getHits();

        final ObjectMapper mapper = new ObjectMapper();

        for (SearchHit hit : searchHits) {
            // convert json object to CourseDto
            courseList.add(mapper.readValue(hit.getSourceAsString(), CourseDto.class));
        }
    } catch (IOException e) {
        logger.error("Cannot search by all mach. " + e);
    }
    return courseList;
}

Info:
- Elasticsearch version 7.5.0
- Java High Level REST Client is used as client.

I Hope, this will be useful for someone.


问:
Spring Boot Embedded Apache Derby
I know a Similar question has been asked and answered before. But i've tried the solutions from the previous answers and they are not working out. I've tried out as much as i could and hope someone can shed some lights over the problem i'm facing.

Configuring embedded Derby in Spring Boot app

Spring-boot error using Apache Derby as embedded database

Spring Boot non-embedded Derby database?

And a lot more from the web. But seriously, i don't see a solution yet for the probelm i'm facing.

Here is my code,

application.properties

```<code>spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.url=jdbc:derby:memory:mydb;create=true
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver
</code>```

ApacheDerbyExample.java

```<code>package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.CommandLineRunner;

@ComponentScan("com.app")
@SpringBootApplication
public class ApacheDerbyExample implements CommandLineRunner {

    public static void main(String[] args) {
        System.out.println("STARTING THE APPLICATION");
        SpringApplication.run(ApacheDerbyExample.class, args);
        System.out.println("APPLICATION FINISHED");
    }

    @Override
    public void run(String... args) {
        System.out.println("EXECUTING : command line runner");
        //org.apache.derby.jdbc.ClientDataSource ds = new org.apache.derby.jdbc.ClientDataSource();
        //ds.setDatabaseName("mydb");
    }
}
</code>```

And from my pom.xml,

        org.apache.derby
        derby
        10.15.2.0
        runtime

        org.apache.derby
        derbyclient
        10.15.2.0
        runtime

https://github.com/manikandaraj/practice-code/tree/master/java/spring-boot-apache-derby-embedded

I'm building the project using,

```<code>mvn clean package
</code>```

And when i run,

```<code>java -jar -Dspring.config.location=config/spring-conf/application.properties target/derby-101-0.0.1-SNAPSHOT.jar
</code>```

But i'm getting the following error,

```<code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-31 02:15:43.402 ERROR 8733 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Dbcp2.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.commons.dbcp2.BasicDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.apache.derby.jdbc.EmbeddedDriver
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656) ~[spring-beans-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636) ~[spring-beans-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
</code>```

I'm just trying to use the Apache Derby Embedded Database in my Application and with the dependencies defined in Maven, I don't know why i'm still getting the error.

I want to be able to use the Embedded Pooled Data Source(Derby) and run some query on CSV content I get from REST APIs.

答: I think ,Looks like you are missing the  jdbc driver in your classpath. </p>

Title: Spring Boot Embedded Apache Derby

Body:
I know a Similar question has been asked and answered before. But i've tried the solutions from the previous answers and they are not working out. I've tried out as much as i could and hope someone can shed some lights over the problem i'm facing.

Configuring embedded Derby in Spring Boot app

Spring-boot error using Apache Derby as embedded database

Spring Boot non-embedded Derby database?

And a lot more from the web. But seriously, i don't see a solution yet for the probelm i'm facing.

Here is my code,

application.properties

spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.url=jdbc:derby:memory:mydb;create=true
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver

ApacheDerbyExample.java

package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.CommandLineRunner;

@ComponentScan("com.app")
@SpringBootApplication
public class ApacheDerbyExample implements CommandLineRunner {

    public static void main(String[] args) {
        System.out.println("STARTING THE APPLICATION");
        SpringApplication.run(ApacheDerbyExample.class, args);
        System.out.println("APPLICATION FINISHED");
    }

    @Override
    public void run(String... args) {
        System.out.println("EXECUTING : command line runner");
        //org.apache.derby.jdbc.ClientDataSource ds = new org.apache.derby.jdbc.ClientDataSource();
        //ds.setDatabaseName("mydb");
    }
}

And from my pom.xml,

        org.apache.derby
        derby
        10.15.2.0
        runtime

        org.apache.derby
        derbyclient
        10.15.2.0
        runtime

https://github.com/manikandaraj/practice-code/tree/master/java/spring-boot-apache-derby-embedded

I'm building the project using,

mvn clean package

And when i run,

java -jar -Dspring.config.location=config/spring-conf/application.properties target/derby-101-0.0.1-SNAPSHOT.jar

But i'm getting the following error,

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-31 02:15:43.402 ERROR 8733 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Dbcp2.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.commons.dbcp2.BasicDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.apache.derby.jdbc.EmbeddedDriver
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656) ~[spring-beans-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636) ~[spring-beans-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]

I'm just trying to use the Apache Derby Embedded Database in my Application and with the dependencies defined in Maven, I don't know why i'm still getting the error.

I want to be able to use the Embedded Pooled Data Source(Derby) and run some query on CSV content I get from REST APIs.


问:
how to test a setter in c# ?and why?
I am getting started with c#. I am asked to do an assignement that contains writing a unit test for a setter and checking its output. I don't follow the meaning of testing something very trivial that does not contain any logic. here's the example (SetKeywords() is the method to be tested):</p>

```<code>public struct Keyword
{
    private string keyword;
    private KeywordTypes type;

    public Keyword(string keyword, KeywordTypes Type =
    KeywordTypes.String)
    {
        this.keyword = keyword;
        this.type = Type;
    }

    public string GetString()
    {
        return this.keyword;
    }

    public KeywordTypes WhichType()
    {
        return this.type;
    }
}

public class ShopParser
{
    private Keyword[] keywords = new Keyword[0];

    public void **SetKeywords**(Keyword[] tags)
    {
        keywords = tags;
    }
}
    public Keyword[] GetKeywords()
    {
            return this.keywords;
    }
    public static KeywordPair[] ExtractFromTaG(ShopParser parser, string
    serializedInput)
    {
            var findings = new KeywordPair[0];
            foreach (var keyword in parser.GetKeywords())
            {
                var start = serializedInput.IndexOf(keyword.GetStart());

                // Check if keyword is in input string, if not continue
                with next keyword.

                if (start <= -1) continue;

                var end = serializedInput.LastIndexOf(keyword.GetEnd());

                // Extract the thing between the tags. Tag excluded
                start += keyword.GetStart().Length;

                var substring = serializedInput.Substring(start, end -
                start);

                // Add substring to result list

                var tmp = new KeywordPair[findings.Length + 1];
                var i = 0;
                for (; i < findings.Length; ++i)
                {
                    tmp[i] = findings[i];
                }
                tmp[i] = new KeywordPair(keyword, substring);
                findings = tmp;
            }
            return findings;
    }

}
</code>```

答:
Lack of complex code does not mean there are no design decisions by the author of the class that should be verified and protected by unit tests. I.e. the fact you picked value type for items in the collection makes some behaviors impossible and some trivial - the test are there to clarify that class implements that design decision properly and protects the behavior of the class in case of future modifications.

Unit tests for setters for properties of a collection type (unlike value type int) are actually non trivial because one must verify that contract of the class is defined and properly supported - does setter make a copy of a collection or reference existing one, does it make deep or shallow copy? Testing each of the cases properly is definitely not a trivial task. (Same to lesser extent applies to all reference type properties, but in non-collection cases expectations of behavior are usually more aligned with default).

So what you want to do before writing the test is to decide the behavior of your collection property - does it make copy at the moment of setting or refers to the original live instance. If collection would be of reference type (not the case in the question) you also need to decide if it takes shallow or deep copy (deep copy is unusual).

After you made the decision it is somewhat trivial to write the test to verify. You add following tests:

is the collection exposed via getter has the same items in the same order as one used to call setter (applies to both copy and reference approaches)

use setter with a  collection and modify original collection (in case of an array change items in the collection). Verify that the collection exposed by the getter behaves properly (either matches updated one for live reference or stays the same for copied one)

if using collection of non-immutable reference types verify that modifying individual items behave as expected (either reflects modification for non-deep copy or stays the same)

if collection just refers to original one tests may be shortened to just checking for reference equality between the original and value returned by the getter, but doing so will not document expected behavior and limit ability to modify in the future.

One may need additional test to validate that collection returned as result of the getter behaves as designed by the class author - in particular if modification of the resulting collection are reflected in the class' state or not (getter returning shallow/deep copy of the state or just exposing internal state directly as shown in the question).

Please note that it is discouraged to have setters for collection properties - see CA2227: Collection properties should be read only. So code in the question sort of follows the recommendation but better name like "AddKeywords"/"ReplaceKeywords" would clarify behavior rather than general "set".

Title: how to test a setter in c# ?and why?

Body:
I am getting started with c#. I am asked to do an assignement that contains writing a unit test for a setter and checking its output. I don't follow the meaning of testing something very trivial that does not contain any logic. here's the example (SetKeywords() is the method to be tested):

public struct Keyword
{
    private string keyword;
    private KeywordTypes type;

    public Keyword(string keyword, KeywordTypes Type =
    KeywordTypes.String)
    {
        this.keyword = keyword;
        this.type = Type;
    }

    public string GetString()
    {
        return this.keyword;
    }

    public KeywordTypes WhichType()
    {
        return this.type;
    }
}

public class ShopParser
{
    private Keyword[] keywords = new Keyword[0];

    public void **SetKeywords**(Keyword[] tags)
    {
        keywords = tags;
    }
}
    public Keyword[] GetKeywords()
    {
            return this.keywords;
    }
    public static KeywordPair[] ExtractFromTaG(ShopParser parser, string
    serializedInput)
    {
            var findings = new KeywordPair[0];
            foreach (var keyword in parser.GetKeywords())
            {
                var start = serializedInput.IndexOf(keyword.GetStart());

                // Check if keyword is in input string, if not continue
                with next keyword.

                if (start <= -1) continue;

                var end = serializedInput.LastIndexOf(keyword.GetEnd());

                // Extract the thing between the tags. Tag excluded
                start += keyword.GetStart().Length;

                var substring = serializedInput.Substring(start, end -
                start);

                // Add substring to result list

                var tmp = new KeywordPair[findings.Length + 1];
                var i = 0;
                for (; i < findings.Length; ++i)
                {
                    tmp[i] = findings[i];
                }
                tmp[i] = new KeywordPair(keyword, substring);
                findings = tmp;
            }
            return findings;
    }

}


问:
Dialog in Wi-Fi Network Request API
I'm using the new API 29 for connecting the device to a wifi network in an Android 10 device:

```<code>    private val connectivityManager: ConnectivityManager by inject()

    override fun connectToNetwork(ssid: String, password: String) {
        val networkRequest = buildNetworkRequest(ssid, password)

        val networkCallback =
            object : NetworkCallback() {
                override fun onAvailable(network: Network) {
                    super.onAvailable(network)
                    Timber.d("Connected to network $ssid")
                }

                override fun onUnavailable() {
                    super.onUnavailable()
                    Timber.e("Unable to connect to network $ssid")
                }
            }

        connectivityManager.requestNetwork(networkRequest, networkCallback, CONNECTION_TIME_OUT)

    }

    private fun buildNetworkRequest(ssid: String, password: String) =
        NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .setNetworkSpecifier(buildWifiNetworkSpecifier(ssid, password))
            .build()

    private fun buildWifiNetworkSpecifier(ssid: String, password: String) =
        WifiNetworkSpecifier.Builder()
            .setSsid(ssid)
            .setWpa2Passphrase(password)
            .build()
</code>```

A dialog appears with a "Device to use with " with the specified wifi network listed. The dialog has two buttons for "cancel" and "connect". When I click "connect", the device connects to the wifi network (I can see that in the system settings) and the connect button is disabled.

But the dialog does not go away and none of the methods in the requestNetwork callback is invoked. Eventually I reach the specified timeout and another dialog comes with "Something came up. The application has cancelled the request to choose a device".

What is happening here? I want to connect to a network and have the 'onAvailable' or 'onUnavailable' methods in the callback invoked.

答:
I had the same problem. By trial and error, I found out that this is due to the fact that the request occurs earlier than the network is finally connected. If you send a request after network availability, then everything works. Here is an example of code that solved my problem:

```<code>override fun onAvailable(network: Network) {
            GlobalScope.launch(Dispatchers.IO) {
                while (!isNetworkAvailable(ctx)) {
                    delay(200)
                }
                launch(Dispatchers.Main) {
                    // begin request....
                }
            }
            cm.unregisterNetworkCallback(this)
        }
</code>```

and

```<code> private fun isNetworkAvailable(ctx: Context): Boolean {
    val connectivityManager = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val nw = connectivityManager.activeNetwork ?: return false
        val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
        return actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
    } else {
        val nwInfo = connectivityManager.activeNetworkInfo ?: return false
        return nwInfo.isConnected
    }
}
</code>```

Also, before connecting, you have to clear ssid for the correct connection:

```<code>private fun removeSsid(ctx : Context, ssid : String, pass : String){
    val suggestion = WifiNetworkSuggestion.Builder()
        .setSsid(ssid)
        .setWpa2Passphrase(pass)
        .build()
    val wifiManager = ctx.getSystemService(WIFI_SERVICE) as WifiManager
    val sList = ArrayList<WifiNetworkSuggestion>()
    sList.add(suggestion)
    wifiManager.removeNetworkSuggestions(sList)
}
</code>```

Title: Dialog in Wi-Fi Network Request API

Body:
I'm using the new API 29 for connecting the device to a wifi network in an Android 10 device:

    private val connectivityManager: ConnectivityManager by inject()

    override fun connectToNetwork(ssid: String, password: String) {
        val networkRequest = buildNetworkRequest(ssid, password)

        val networkCallback =
            object : NetworkCallback() {
                override fun onAvailable(network: Network) {
                    super.onAvailable(network)
                    Timber.d("Connected to network $ssid")
                }

                override fun onUnavailable() {
                    super.onUnavailable()
                    Timber.e("Unable to connect to network $ssid")
                }
            }

        connectivityManager.requestNetwork(networkRequest, networkCallback, CONNECTION_TIME_OUT)

    }

    private fun buildNetworkRequest(ssid: String, password: String) =
        NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .setNetworkSpecifier(buildWifiNetworkSpecifier(ssid, password))
            .build()

    private fun buildWifiNetworkSpecifier(ssid: String, password: String) =
        WifiNetworkSpecifier.Builder()
            .setSsid(ssid)
            .setWpa2Passphrase(password)
            .build()

A dialog appears with a "Device to use with " with the specified wifi network listed. The dialog has two buttons for "cancel" and "connect". When I click "connect", the device connects to the wifi network (I can see that in the system settings) and the connect button is disabled.

But the dialog does not go away and none of the methods in the requestNetwork callback is invoked. Eventually I reach the specified timeout and another dialog comes with "Something came up. The application has cancelled the request to choose a device".

What is happening here? I want to connect to a network and have the 'onAvailable' or 'onUnavailable' methods in the callback invoked.

Body:
I had the same problem. By trial and error, I found out that this is due to the fact that the request occurs earlier than the network is finally connected. If you send a request after network availability, then everything works. Here is an example of code that solved my problem:

override fun onAvailable(network: Network) {
            GlobalScope.launch(Dispatchers.IO) {
                while (!isNetworkAvailable(ctx)) {
                    delay(200)
                }
                launch(Dispatchers.Main) {
                    // begin request....
                }
            }
            cm.unregisterNetworkCallback(this)
        }

and

 private fun isNetworkAvailable(ctx: Context): Boolean {
    val connectivityManager = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val nw = connectivityManager.activeNetwork ?: return false
        val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
        return actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
    } else {
        val nwInfo = connectivityManager.activeNetworkInfo ?: return false
        return nwInfo.isConnected
    }
}

Also, before connecting, you have to clear ssid for the correct connection:

private fun removeSsid(ctx : Context, ssid : String, pass : String){
    val suggestion = WifiNetworkSuggestion.Builder()
        .setSsid(ssid)
        .setWpa2Passphrase(pass)
        .build()
    val wifiManager = ctx.getSystemService(WIFI_SERVICE) as WifiManager
    val sList = ArrayList<WifiNetworkSuggestion>()
    sList.add(suggestion)
    wifiManager.removeNetworkSuggestions(sList)
}


问:
Assistance writting function to list for api query in python
I wrote a simple application to generate a 64char hex, translate to a private address and then check the balance via Etherscan. It works without issue. the API also allows checking addresses in groups of 20, separated by commas. I know i need to write the output of accAddress 20x to a list, i just don't understand how. Any guidance is greatly appreciated.</p>

```<code>import os
from ethereum import utils
import time
import urllib.request
import json
import secrets

hex_number = secrets.token_hex(32)
rawAddress = utils.privtoaddr(hex_number)
accAddress = utils.checksum_encode(rawAddress)

url = "https://api.etherscan.io/api?module=account&action=balance&address=" + accAddress + "&tag=latest&apikey=YOURAPIKEY"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
print (hex_number + "\n" + accAddress + ": " + data['result'])
</code>```

答:
after much help, this is what works for me.</p>

```<code>import os
from ethereum import utils
import time
import urllib.request
import json
import secrets

# Initialize main variables
addressCount = 20 # Address number by request
allAddress = []
allHexNumber = {}

for i in range(addressCount):
    # Generate random eth address
    hex_number = secrets.token_hex(32)
    rawAddress = utils.privtoaddr(hex_number)
    accAddress = utils.checksum_encode(rawAddress)

# Add address to list with its hex number
allAddress.append(accAddress)
allHexNumber[accAddress] = hex_number

# Join all the addresses by a ","
allAddressStr = ",".join(allAddress)

# Make the request
url = "https://api.etherscan.io/api?module=account&action=balancemultiaddress=" + allAddressStr + "&tag=latest&apikey=YOURAPIKEY"
response = urllib.request.urlopen(url)
data = json.loads(response.read())

# Get and display the result for each balance with its hex number
allResults = data['result']

for result in allResults:
    address = result['account']
    hex_number = allHexNumber[address]
    balance = result['balance']
    print(hex_number + "\n" + address + ": " + balance)
</code>```

Body:
I wrote a simple application to generate a 64char hex, translate to a private address and then check the balance via Etherscan. It works without issue. the API also allows checking addresses in groups of 20, separated by commas. I know i need to write the output of accAddress 20x to a list, i just don't understand how. Any guidance is greatly appreciated.

import os
from ethereum import utils
import time
import urllib.request
import json
import secrets

hex_number = secrets.token_hex(32)
rawAddress = utils.privtoaddr(hex_number)
accAddress = utils.checksum_encode(rawAddress)

url = "https://api.etherscan.io/api?module=account&action=balance&address=" + accAddress + "&tag=latest&apikey=YOURAPIKEY"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
print (hex_number + "\n" + accAddress + ": " + data['result'])

Body:
after much help, this is what works for me.

import os
from ethereum import utils
import time
import urllib.request
import json
import secrets

# Initialize main variables
addressCount = 20 # Address number by request
allAddress = []
allHexNumber = {}

for i in range(addressCount):
    # Generate random eth address
    hex_number = secrets.token_hex(32)
    rawAddress = utils.privtoaddr(hex_number)
    accAddress = utils.checksum_encode(rawAddress)

# Add address to list with its hex number
allAddress.append(accAddress)
allHexNumber[accAddress] = hex_number

# Join all the addresses by a ","
allAddressStr = ",".join(allAddress)

# Make the request
url = "https://api.etherscan.io/api?module=account&action=balancemultiaddress=" + allAddressStr + "&tag=latest&apikey=YOURAPIKEY"
response = urllib.request.urlopen(url)
data = json.loads(response.read())

# Get and display the result for each balance with its hex number
allResults = data['result']

for result in allResults:
    address = result['account']
    hex_number = allHexNumber[address]
    balance = result['balance']
    print(hex_number + "\n" + address + ": " + balance)


问:
Scroll Listview to bottom after items loaded in flutter
I want to scroll the Listview to bottom after the Widget is rendered.
Tried the below code, but its being called before the Listview is rendered.

```<code>  ScrollController _lvScrollCtrl = new ScrollController();
  @override
  void initState() {
    getData();
    loadListviewData();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _lvScrollCtrl.animateTo(_lvScrollCtrl.position.maxScrollExtent,
          duration: const Duration(milliseconds: 500), curve: Curves.easeOut);
    });
    super.initState();
  }
</code>```

I have also tried setting the reverse property of Listview to true. But this brings all items to the bottom of Expanded widget.
I just wanted a normal Listview scrolled down to the end to show recent updates on Load. :/

答:
I moved the below code to the build function before return statement, and it's working perfect. Just realized addPostFrameCallback callback will be called only once after the current frame is finished. So I needed to set it again and again to keep it calling. </p>

```<code>  WidgetsBinding.instance.addPostFrameCallback((_) {
      _lvScrollCtrl.animateTo(_lvScrollCtrl.position.maxScrollExtent,
          duration: const Duration(milliseconds: 500), curve: Curves.easeOut);
    });
</code>```

Body:
I want to scroll the Listview to bottom after the Widget is rendered.
Tried the below code, but its being called before the Listview is rendered.

  ScrollController _lvScrollCtrl = new ScrollController();
  @override
  void initState() {
    getData();
    loadListviewData();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _lvScrollCtrl.animateTo(_lvScrollCtrl.position.maxScrollExtent,
          duration: const Duration(milliseconds: 500), curve: Curves.easeOut);
    });
    super.initState();
  }

I have also tried setting the reverse property of Listview to true. But this brings all items to the bottom of Expanded widget.
I just wanted a normal Listview scrolled down to the end to show recent updates on Load. :/

Body:
I moved the below code to the build function before return statement, and it's working perfect. Just realized addPostFrameCallback callback will be called only once after the current frame is finished. So I needed to set it again and again to keep it calling.

  WidgetsBinding.instance.addPostFrameCallback((_) {
      _lvScrollCtrl.animateTo(_lvScrollCtrl.position.maxScrollExtent,
          duration: const Duration(milliseconds: 500), curve: Curves.easeOut);
    });


问:
How to run these XSL templates in sequence
To preface this, I've only recently gotten into the more advances things we can do with XSL.

I'm currently trying to transform the data provided in the XML file and then convert the output of that into a JSON file.

I can do each of these things individually (using XSL I found online for the JSON) and I've tried to run this using apply-templates, call-template, mode="run2" etc. and cannot get them to behave. I can only ever get one or the other.

The XSL I'm using is:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   version="1.0">
  <xsl:output method="text" encoding="utf-8"/>

<!-- Extract required information-->
  <xsl:template match="/" name="xmlOutput">
    <jobDetails>
      <orderId>
        <xsl:value-of select="/Order/OrderId"/>
      </orderId>
      <xsl:variable name="jobId" select="/Order/OrderLines/OrderLine/OrderLineId" />
      <orderLine>
        <xsl:value-of select="substring-after($jobId,'d')"/>
      </orderLine>
      <xsl:for-each select="/Order/OrderLines/OrderLine">
        <name>
          <xsl:value-of select="ProductName"/>
        </name>
        <copies>
          <xsl:value-of select="Quantity"/>
        </copies>
        <url>
          <xsl:value-of select="AssetUrl"/>
        </url>
        <nestQueueName>smile_test</nestQueueName>
        <customer_info>
          <first_name>
            <xsl:value-of select="/Order/Customer/FirstName"/>
          </first_name>
          <last_name>
            <xsl:value-of select="/Order/Customer/LastName"/>
          </last_name>
          <street1>
            <xsl:value-of select="/Order/ShippingAddress/Address1"/>
          </street1>
          <street2>
            <xsl:value-of select="/Order/ShippingAddress/Address2"/>
          </street2>
          <city>
            <xsl:value-of select="/Order/ShippingAddress/Town"/>
          </city>
          <state>
            <xsl:value-of select="/Order/ShippingAddress/State"/>
          </state>
          <country>
            <xsl:value-of select="/Order/ShippingAddress/Country"/>
          </country>
          <phone>
            <xsl:value-of select="/Order/ShippingAddress/Phone"/>
          </phone>
          <email>
            <xsl:value-of select="/Order/ShippingAddress/Email"/>
          </email>

        </customer_info>
      </xsl:for-each>
    </jobDetails>
  </xsl:template>

<!--Convert XML to JSON-->
  <xsl:template match="/">
    <xsl:variable name="xmlOutputVar">
      <xsl:apply-templates select="/"/>
    </xsl:variable>

    <xsl:apply-templates select="$xmlOutputVar"/>
  </xsl:template>

  <!-- Object or Element Property-->
  <xsl:template match="*">
        "    <xsl:value-of select="name()"/>
" :    <xsl:call-template name="Properties"/>
  </xsl:template>

  <!-- Array Element -->
  <xsl:template match="*" mode="ArrayElement">
    <xsl:call-template name="Properties"/>
  </xsl:template>

  <!-- Object Properties -->
  <xsl:template name="Properties">
    <xsl:variable name="childName" select="name(*[1])"/>
    <xsl:choose>
      <xsl:when test="not(*|@*)">"        <xsl:value-of select="."/>
"</xsl:when>
      <xsl:when test="count(*[name()=$childName]) > 1">{ "        <xsl:value-of select="$childName"/>
" :[        <xsl:apply-templates select="*" mode="ArrayElement"/>
] }</xsl:when>
      <xsl:otherwise>{
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*"/>
    }</xsl:otherwise>
    </xsl:choose>
    <xsl:if test="following-sibling::*">,</xsl:if>
  </xsl:template>

  <!-- Attribute Property -->
  <xsl:template match="@*">"    <xsl:value-of select="name()"/>
" : "    <xsl:value-of select="."/>
",
  </xsl:template>

</xsl:stylesheet>

</code>```

The two aren't configured to run together at the moment since I've stripped it back to be simplified, but the pipeline should be Source XML -> Extract information template -> Convert to JSON templates.

I know these two template/template sets work as I've tried them individually on the source XML (see below), but when I try and link them up I cannot get the right output.

Can anyone help?

Source XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <OrderId>1234</OrderId>
    <StoreFrontId>00</StoreFrontId>
    <StoreFrontName>Example Store</StoreFrontName>
    <Amount>0.0000</Amount>
    <Taxes>0.0000</Taxes>
    <TotalDiscount>0.0000</TotalDiscount>
    <OrderStatusId>1</OrderStatusId>
    <OrderStatus>Confirmed</OrderStatus>
    <PaymentStatusId>2</PaymentStatusId>
    <PaymentStatus>Paid</PaymentStatus>
    <ShippingStatusId>1</ShippingStatusId>
    <ShippingStatus>Pending</ShippingStatus>
    <OrderDiscount>0.0000</OrderDiscount>
    <SubTotalDiscountInclTax>0.0000</SubTotalDiscountInclTax>
    <SubTotalDiscountExclTax>0.0000</SubTotalDiscountExclTax>
    <ShippingTax>0.0000</ShippingTax>
    <ShippingPrice>0.0000</ShippingPrice>
    <ShippingMethod>Test</ShippingMethod>
    <ShippingMethodSystemName>Test</ShippingMethodSystemName>
    <ShippingMethodCode>24</ShippingMethodCode>
    <PaymentMethod>Payments.PurchaseOrder</PaymentMethod>
    <VatNumber />
    <OrderWeight>1.0000</OrderWeight>
    <Currency>GBP</Currency>
    <PurchaseOrderNumber />
    <Customer>
        <CatfishId>50242</CatfishId>
        <ExternalId>External ID</ExternalId>
        <Email>test@email.com</Email>
        <FirstName>TestFirst</FirstName>
        <LastName>TestLast</LastName>
        <PhoneNumber>01234567890</PhoneNumber>
        <CompanyName>CompanyName</CompanyName>
        <AddressLine1>AddressLine1</AddressLine1>
        <AddressLine2>AddressLine2</AddressLine2>
        <Town>Town</Town>
        <County>County</County>
        <Country>United Kingdom</Country>
        <CountryCode>GB</CountryCode>
        <ZipPostalCode>AB01 1AB</ZipPostalCode>
    </Customer>
    <OrderNotes />
    <OrderDateUtc>2018-07-27</OrderDateUtc>
    <DispatchBy>2018-07-27</DispatchBy>
    <BillingAddress>
        <ExternalId />
        <FirstName>Billing</FirstName>
        <LastName>Address</LastName>
        <Address1>BALO</Address1>
        <Postcode>BA73 5ST</Postcode>
        <State>Aberdeenshire</State>
        <Town>BAT</Town>
        <Country>United Kingdom</Country>
        <CountryCode>GB</CountryCode>
        <Email>test@email.com</Email>
        <CompanyName>BillingAddressCompany</CompanyName>
    </BillingAddress>
    <ShippingAddress>
        <ExternalId />
        <FirstName>Billing</FirstName>
        <LastName>Address</LastName>
        <Address1>BALO</Address1>
        <Postcode>BA73 5ST</Postcode>
        <State>Aberdeenshire</State>
        <Town>BAT</Town>
        <Country>United Kingdom</Country>
        <CountryCode>GB</CountryCode>
        <Email>test@email.com</Email>
        <CompanyName>BillingAddressCompany</CompanyName>
    </ShippingAddress>
    <OrderLines>
        <OrderLine>
            <OrderLineId>v2604</OrderLineId>
            <ProductExternalId>External ID</ProductExternalId>
            <ProductVariantExternalId>Variant External ID</ProductVariantExternalId>
            <Sku>0000</Sku>
            <ProductName>ProductName</ProductName>
            <Quantity>1</Quantity>
            <TotalPrice>0.0000</TotalPrice>
            <TotalTax>0.0000</TotalTax>
            <Weight>1.0000</Weight>
            <DiscountAmountInclTax>0.0000</DiscountAmountInclTax>
            <DiscountAmountExclTax>0.0000</DiscountAmountExclTax>
            <AssetUrl>urlGoesHere</AssetUrl>
            <PrintParameters />
            <ProductAttributes>
                <ProductAttribute>
                    <Name>Attribute1</Name>
                    <Value>A</Value>
                    <Values>
                        <ProductAttributeValue>
                            <Value>A</Value>
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
                <ProductAttribute>
                    <Name>Attribute2</Name>
                    <Value />
                    <Values>
                        <ProductAttributeValue>
                            <Value />
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
                <ProductAttribute>
                    <Name>Attribute3</Name>
                    <Value />
                    <Values>
                        <ProductAttributeValue>
                            <Value />
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
                <ProductAttribute>
                    <Name>Attribute4</Name>
                    <Value />
                    <Values>
                        <ProductAttributeValue>
                            <Value />
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
            </ProductAttributes>
            <Totals>
                <UnitPrice>0.00000000</UnitPrice>
                <TotalPrice>0.00000000</TotalPrice>
                <TotalTax>0.00000000</TotalTax>
                <DiscountAmountInclTax>0.00000000</DiscountAmountInclTax>
                <DiscountAmountExclTax>0.00000000</DiscountAmountExclTax>
            </Totals>
        </OrderLine>
    </OrderLines>
    <CheckoutAttributes />
    <Totals>
        <CurrencyCode>GBP</CurrencyCode>
        <TotalPrice>0.00000000</TotalPrice>
        <TotalDiscount>0</TotalDiscount>
        <OrderDiscount>0.00000000</OrderDiscount>
        <SubTotalDiscountInclTax>0.00000000</SubTotalDiscountInclTax>
        <SubTotalDiscountExclTax>0.00000000</SubTotalDiscountExclTax>
        <TotalTax>0.00000000</TotalTax>
        <ShippingPrice>0.00000000</ShippingPrice>
        <ShippingTax>0.00000000</ShippingTax>
    </Totals>
</Order>
</code>```

P.S. It's not possible for me to run two separate XSL files on the XML, nor is it possible to use anything beyond XSL 1.0

EDIT:
I've amended the XSLT to be the following after listening to the advice given in a comment:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
   version="1.0">
  <xsl:output method="text" encoding="utf-8"/>

<!-- Extract required information-->
  <xsl:template match="/" name="xmlOutput">
    <jobDetails>
      <orderId>
        <xsl:value-of select="/Order/OrderId"/>
      </orderId>
      <xsl:variable name="jobId" select="/Order/OrderLines/OrderLine/OrderLineId" />
      <orderLine>
        <xsl:value-of select="substring-after($jobId,'d')"/>
      </orderLine>
      <xsl:for-each select="/Order/OrderLines/OrderLine">
        <name>
          <xsl:value-of select="ProductName"/>
        </name>
        <copies>
          <xsl:value-of select="Quantity"/>
        </copies>
        <url>
          <xsl:value-of select="AssetUrl"/>
        </url>
        <nestQueueName>smile_test</nestQueueName>
        <customer_info>
          <first_name>
            <xsl:value-of select="/Order/Customer/FirstName"/>
          </first_name>
          <last_name>
            <xsl:value-of select="/Order/Customer/LastName"/>
          </last_name>
          <street1>
            <xsl:value-of select="/Order/ShippingAddress/Address1"/>
          </street1>
          <street2>
            <xsl:value-of select="/Order/ShippingAddress/Address2"/>
          </street2>
          <city>
            <xsl:value-of select="/Order/ShippingAddress/Town"/>
          </city>
          <state>
            <xsl:value-of select="/Order/ShippingAddress/State"/>
          </state>
          <country>
            <xsl:value-of select="/Order/ShippingAddress/Country"/>
          </country>
          <phone>
            <xsl:value-of select="/Order/ShippingAddress/Phone"/>
          </phone>
          <email>
            <xsl:value-of select="/Order/ShippingAddress/Email"/>
          </email>

        </customer_info>
      </xsl:for-each>
    </jobDetails>
  </xsl:template>

<!--Convert XML to JSON-->
  <xsl:template match="/">
    <xsl:variable name="xmlOutputVar">
      <xsl:call-template name="xmlOutput"/>
    </xsl:variable>

    <xsl:apply-templates select="exsl:node-set($xmlOutputVar)/node()"/>
  </xsl:template>

  <!-- Object or Element Property-->
  <xsl:template match="*">
        "    <xsl:value-of select="name()"/>
" :    <xsl:call-template name="Properties"/>
  </xsl:template>

  <!-- Array Element -->
  <xsl:template match="*" mode="ArrayElement">
    <xsl:call-template name="Properties"/>
  </xsl:template>

  <!-- Object Properties -->
  <xsl:template name="Properties">
    <xsl:variable name="childName" select="name(*[1])"/>
    <xsl:choose>
      <xsl:when test="not(*|@*)">"        <xsl:value-of select="."/>
"</xsl:when>
      <xsl:when test="count(*[name()=$childName]) > 1">{ "        <xsl:value-of select="$childName"/>
" :[        <xsl:apply-templates select="*" mode="ArrayElement"/>
] }</xsl:when>
      <xsl:otherwise>{
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*"/>
    }</xsl:otherwise>
    </xsl:choose>
    <xsl:if test="following-sibling::*">,</xsl:if>
  </xsl:template>

  <!-- Attribute Property -->
  <xsl:template match="@*">"    <xsl:value-of select="name()"/>
" : "    <xsl:value-of select="."/>
",
  </xsl:template>

</xsl:stylesheet>

</code>```

But it's producing a different output to if I run the two transformations as separate XSL files.

If I run them separately, I end up with:

```<code>{

    "jobDetails" :{

    "orderId" :"1234",
    "orderLine" :"",
    "name" :"ProductName",
    "copies" :"1",
    "url" :"urlGoesHere",
    "nestQueueName" :"smile_test",
    "customer_info" :{

    "first_name" :"TestFirst",
    "last_name" :"TestLast",
    "street1" :"BALO",
    "street2" :"",
    "city" :"BAT",
    "state" :"Aberdeenshire",
    "country" :"United Kingdom",
    "phone" :"",
    "email" :"test@email.com"
            }
            }}
</code>```

However, if I run them in the same XSL file, I end up with:

```<code>
        "    jobDetails
" :    {

        "    orderId
" :    "        1234
",
        "    orderLine
" :    "
",
        "    name
" :    "        ProductName
",
        "    copies
" :    "        1
",
        "    url
" :    "        urlGoesHere
",
        "    nestQueueName
" :    "        smile_test
",
        "    customer_info
" :    {

        "    first_name
" :    "        TestFirst
",
        "    last_name
" :    "        TestLast
",
        "    street1
" :    "        BALO
",
        "    street2
" :    "
",
        "    city
" :    "        BAT
",
        "    state
" :    "        Aberdeenshire
",
        "    country
" :    "        United Kingdom
",
        "    phone
" :    "
",
        "    email
" :    "        test@email.com
"
    }
    }
</code>```

I can't see what would be causing the different outputs, can someone help with this as well please?

答:
Change

```<code><xsl:variable name="xmlOutputVar">
  <xsl:apply-templates select="/"/>
</xsl:variable>
</code>```

to

```<code><xsl:variable name="xmlOutputVar">
  <xsl:call-template name="xmlOutput"/>
</xsl:variable>
</code>```

then use the supported extension function like e.g. exsl:node-set and replace

```<code><xsl:apply-templates select="$xmlOutputVar"/>
</code>```

with

```<code><xsl:apply-templates select="exsl:node-set($xmlOutputVar)/node()" xmlns:exsl="http://exslt.org/common"/>
</code>```

Body:
To preface this, I've only recently gotten into the more advances things we can do with XSL.

I'm currently trying to transform the data provided in the XML file and then convert the output of that into a JSON file.

I can do each of these things individually (using XSL I found online for the JSON) and I've tried to run this using apply-templates, call-template, mode="run2" etc. and cannot get them to behave. I can only ever get one or the other.

The XSL I'm using is:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   version="1.0">
  <xsl:output method="text" encoding="utf-8"/>

  <xsl:template match="/" name="xmlOutput">
    <jobDetails>
      <orderId>
        <xsl:value-of select="/Order/OrderId"/>
      </orderId>
      <xsl:variable name="jobId" select="/Order/OrderLines/OrderLine/OrderLineId" />
      <orderLine>
        <xsl:value-of select="substring-after($jobId,'d')"/>
      </orderLine>
      <xsl:for-each select="/Order/OrderLines/OrderLine">
        <name>
          <xsl:value-of select="ProductName"/>
        </name>
        <copies>
          <xsl:value-of select="Quantity"/>
        </copies>
        <url>
          <xsl:value-of select="AssetUrl"/>
        </url>
        <nestQueueName>smile_test</nestQueueName>
        <customer_info>
          <first_name>
            <xsl:value-of select="/Order/Customer/FirstName"/>
          </first_name>
          <last_name>
            <xsl:value-of select="/Order/Customer/LastName"/>
          </last_name>
          <street1>
            <xsl:value-of select="/Order/ShippingAddress/Address1"/>
          </street1>
          <street2>
            <xsl:value-of select="/Order/ShippingAddress/Address2"/>
          </street2>
          <city>
            <xsl:value-of select="/Order/ShippingAddress/Town"/>
          </city>
          <state>
            <xsl:value-of select="/Order/ShippingAddress/State"/>
          </state>
          <country>
            <xsl:value-of select="/Order/ShippingAddress/Country"/>
          </country>
          <phone>
            <xsl:value-of select="/Order/ShippingAddress/Phone"/>
          </phone>
          <email>
            <xsl:value-of select="/Order/ShippingAddress/Email"/>
          </email>

        </customer_info>
      </xsl:for-each>
    </jobDetails>
  </xsl:template>

  <xsl:template match="/">
    <xsl:variable name="xmlOutputVar">
      <xsl:apply-templates select="/"/>
    </xsl:variable>

    <xsl:apply-templates select="$xmlOutputVar"/>
  </xsl:template>

  <xsl:template match="*">
        "    <xsl:value-of select="name()"/>
" :    <xsl:call-template name="Properties"/>
  </xsl:template>

  <xsl:template match="*" mode="ArrayElement">
    <xsl:call-template name="Properties"/>
  </xsl:template>

  <xsl:template name="Properties">
    <xsl:variable name="childName" select="name(*[1])"/>
    <xsl:choose>
      <xsl:when test="not(*|@*)">"        <xsl:value-of select="."/>
"</xsl:when>
      <xsl:when test="count(*[name()=$childName]) > 1">{ "        <xsl:value-of select="$childName"/>
" :[        <xsl:apply-templates select="*" mode="ArrayElement"/>
] }</xsl:when>
      <xsl:otherwise>{
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*"/>
    }</xsl:otherwise>
    </xsl:choose>
    <xsl:if test="following-sibling::*">,</xsl:if>
  </xsl:template>

  <xsl:template match="@*">"    <xsl:value-of select="name()"/>
" : "    <xsl:value-of select="."/>
",
  </xsl:template>

</xsl:stylesheet>

The two aren't configured to run together at the moment since I've stripped it back to be simplified, but the pipeline should be Source XML -> Extract information template -> Convert to JSON templates.

I know these two template/template sets work as I've tried them individually on the source XML (see below), but when I try and link them up I cannot get the right output.

Can anyone help?

Source XML:

<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <OrderId>1234</OrderId>
    <StoreFrontId>00</StoreFrontId>
    <StoreFrontName>Example Store</StoreFrontName>
    <Amount>0.0000</Amount>
    <Taxes>0.0000</Taxes>
    <TotalDiscount>0.0000</TotalDiscount>
    <OrderStatusId>1</OrderStatusId>
    <OrderStatus>Confirmed</OrderStatus>
    <PaymentStatusId>2</PaymentStatusId>
    <PaymentStatus>Paid</PaymentStatus>
    <ShippingStatusId>1</ShippingStatusId>
    <ShippingStatus>Pending</ShippingStatus>
    <OrderDiscount>0.0000</OrderDiscount>
    <SubTotalDiscountInclTax>0.0000</SubTotalDiscountInclTax>
    <SubTotalDiscountExclTax>0.0000</SubTotalDiscountExclTax>
    <ShippingTax>0.0000</ShippingTax>
    <ShippingPrice>0.0000</ShippingPrice>
    <ShippingMethod>Test</ShippingMethod>
    <ShippingMethodSystemName>Test</ShippingMethodSystemName>
    <ShippingMethodCode>24</ShippingMethodCode>
    <PaymentMethod>Payments.PurchaseOrder</PaymentMethod>
    <VatNumber />
    <OrderWeight>1.0000</OrderWeight>
    <Currency>GBP</Currency>
    <PurchaseOrderNumber />
    <Customer>
        <CatfishId>50242</CatfishId>
        <ExternalId>External ID</ExternalId>
        <Email>test@email.com</Email>
        <FirstName>TestFirst</FirstName>
        <LastName>TestLast</LastName>
        <PhoneNumber>01234567890</PhoneNumber>
        <CompanyName>CompanyName</CompanyName>
        <AddressLine1>AddressLine1</AddressLine1>
        <AddressLine2>AddressLine2</AddressLine2>
        <Town>Town</Town>
        <County>County</County>
        <Country>United Kingdom</Country>
        <CountryCode>GB</CountryCode>
        <ZipPostalCode>AB01 1AB</ZipPostalCode>
    </Customer>
    <OrderNotes />
    <OrderDateUtc>2018-07-27</OrderDateUtc>
    <DispatchBy>2018-07-27</DispatchBy>
    <BillingAddress>
        <ExternalId />
        <FirstName>Billing</FirstName>
        <LastName>Address</LastName>
        <Address1>BALO</Address1>
        <Postcode>BA73 5ST</Postcode>
        <State>Aberdeenshire</State>
        <Town>BAT</Town>
        <Country>United Kingdom</Country>
        <CountryCode>GB</CountryCode>
        <Email>test@email.com</Email>
        <CompanyName>BillingAddressCompany</CompanyName>
    </BillingAddress>
    <ShippingAddress>
        <ExternalId />
        <FirstName>Billing</FirstName>
        <LastName>Address</LastName>
        <Address1>BALO</Address1>
        <Postcode>BA73 5ST</Postcode>
        <State>Aberdeenshire</State>
        <Town>BAT</Town>
        <Country>United Kingdom</Country>
        <CountryCode>GB</CountryCode>
        <Email>test@email.com</Email>
        <CompanyName>BillingAddressCompany</CompanyName>
    </ShippingAddress>
    <OrderLines>
        <OrderLine>
            <OrderLineId>v2604</OrderLineId>
            <ProductExternalId>External ID</ProductExternalId>
            <ProductVariantExternalId>Variant External ID</ProductVariantExternalId>
            <Sku>0000</Sku>
            <ProductName>ProductName</ProductName>
            <Quantity>1</Quantity>
            <TotalPrice>0.0000</TotalPrice>
            <TotalTax>0.0000</TotalTax>
            <Weight>1.0000</Weight>
            <DiscountAmountInclTax>0.0000</DiscountAmountInclTax>
            <DiscountAmountExclTax>0.0000</DiscountAmountExclTax>
            <AssetUrl>urlGoesHere</AssetUrl>
            <PrintParameters />
            <ProductAttributes>
                <ProductAttribute>
                    <Name>Attribute1</Name>
                    <Value>A</Value>
                    <Values>
                        <ProductAttributeValue>
                            <Value>A</Value>
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
                <ProductAttribute>
                    <Name>Attribute2</Name>
                    <Value />
                    <Values>
                        <ProductAttributeValue>
                            <Value />
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
                <ProductAttribute>
                    <Name>Attribute3</Name>
                    <Value />
                    <Values>
                        <ProductAttributeValue>
                            <Value />
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
                <ProductAttribute>
                    <Name>Attribute4</Name>
                    <Value />
                    <Values>
                        <ProductAttributeValue>
                            <Value />
                        </ProductAttributeValue>
                    </Values>
                </ProductAttribute>
            </ProductAttributes>
            <Totals>
                <UnitPrice>0.00000000</UnitPrice>
                <TotalPrice>0.00000000</TotalPrice>
                <TotalTax>0.00000000</TotalTax>
                <DiscountAmountInclTax>0.00000000</DiscountAmountInclTax>
                <DiscountAmountExclTax>0.00000000</DiscountAmountExclTax>
            </Totals>
        </OrderLine>
    </OrderLines>
    <CheckoutAttributes />
    <Totals>
        <CurrencyCode>GBP</CurrencyCode>
        <TotalPrice>0.00000000</TotalPrice>
        <TotalDiscount>0</TotalDiscount>
        <OrderDiscount>0.00000000</OrderDiscount>
        <SubTotalDiscountInclTax>0.00000000</SubTotalDiscountInclTax>
        <SubTotalDiscountExclTax>0.00000000</SubTotalDiscountExclTax>
        <TotalTax>0.00000000</TotalTax>
        <ShippingPrice>0.00000000</ShippingPrice>
        <ShippingTax>0.00000000</ShippingTax>
    </Totals>
</Order>

P.S. It's not possible for me to run two separate XSL files on the XML, nor is it possible to use anything beyond XSL 1.0

EDIT:
I've amended the XSLT to be the following after listening to the advice given in a comment:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
   version="1.0">
  <xsl:output method="text" encoding="utf-8"/>

  <xsl:template match="/" name="xmlOutput">
    <jobDetails>
      <orderId>
        <xsl:value-of select="/Order/OrderId"/>
      </orderId>
      <xsl:variable name="jobId" select="/Order/OrderLines/OrderLine/OrderLineId" />
      <orderLine>
        <xsl:value-of select="substring-after($jobId,'d')"/>
      </orderLine>
      <xsl:for-each select="/Order/OrderLines/OrderLine">
        <name>
          <xsl:value-of select="ProductName"/>
        </name>
        <copies>
          <xsl:value-of select="Quantity"/>
        </copies>
        <url>
          <xsl:value-of select="AssetUrl"/>
        </url>
        <nestQueueName>smile_test</nestQueueName>
        <customer_info>
          <first_name>
            <xsl:value-of select="/Order/Customer/FirstName"/>
          </first_name>
          <last_name>
            <xsl:value-of select="/Order/Customer/LastName"/>
          </last_name>
          <street1>
            <xsl:value-of select="/Order/ShippingAddress/Address1"/>
          </street1>
          <street2>
            <xsl:value-of select="/Order/ShippingAddress/Address2"/>
          </street2>
          <city>
            <xsl:value-of select="/Order/ShippingAddress/Town"/>
          </city>
          <state>
            <xsl:value-of select="/Order/ShippingAddress/State"/>
          </state>
          <country>
            <xsl:value-of select="/Order/ShippingAddress/Country"/>
          </country>
          <phone>
            <xsl:value-of select="/Order/ShippingAddress/Phone"/>
          </phone>
          <email>
            <xsl:value-of select="/Order/ShippingAddress/Email"/>
          </email>

        </customer_info>
      </xsl:for-each>
    </jobDetails>
  </xsl:template>

  <xsl:template match="/">
    <xsl:variable name="xmlOutputVar">
      <xsl:call-template name="xmlOutput"/>
    </xsl:variable>

    <xsl:apply-templates select="exsl:node-set($xmlOutputVar)/node()"/>
  </xsl:template>

  <xsl:template match="*">
        "    <xsl:value-of select="name()"/>
" :    <xsl:call-template name="Properties"/>
  </xsl:template>

  <xsl:template match="*" mode="ArrayElement">
    <xsl:call-template name="Properties"/>
  </xsl:template>

  <xsl:template name="Properties">
    <xsl:variable name="childName" select="name(*[1])"/>
    <xsl:choose>
      <xsl:when test="not(*|@*)">"        <xsl:value-of select="."/>
"</xsl:when>
      <xsl:when test="count(*[name()=$childName]) > 1">{ "        <xsl:value-of select="$childName"/>
" :[        <xsl:apply-templates select="*" mode="ArrayElement"/>
] }</xsl:when>
      <xsl:otherwise>{
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*"/>
    }</xsl:otherwise>
    </xsl:choose>
    <xsl:if test="following-sibling::*">,</xsl:if>
  </xsl:template>

  <xsl:template match="@*">"    <xsl:value-of select="name()"/>
" : "    <xsl:value-of select="."/>
",
  </xsl:template>

</xsl:stylesheet>

But it's producing a different output to if I run the two transformations as separate XSL files.

If I run them separately, I end up with:

{

    "jobDetails" :{

    "orderId" :"1234",
    "orderLine" :"",
    "name" :"ProductName",
    "copies" :"1",
    "url" :"urlGoesHere",
    "nestQueueName" :"smile_test",
    "customer_info" :{

    "first_name" :"TestFirst",
    "last_name" :"TestLast",
    "street1" :"BALO",
    "street2" :"",
    "city" :"BAT",
    "state" :"Aberdeenshire",
    "country" :"United Kingdom",
    "phone" :"",
    "email" :"test@email.com"
            }
            }}

However, if I run them in the same XSL file, I end up with:

        "    jobDetails
" :    {

        "    orderId
" :    "        1234
",
        "    orderLine
" :    "
",
        "    name
" :    "        ProductName
",
        "    copies
" :    "        1
",
        "    url
" :    "        urlGoesHere
",
        "    nestQueueName
" :    "        smile_test
",
        "    customer_info
" :    {

        "    first_name
" :    "        TestFirst
",
        "    last_name
" :    "        TestLast
",
        "    street1
" :    "        BALO
",
        "    street2
" :    "
",
        "    city
" :    "        BAT
",
        "    state
" :    "        Aberdeenshire
",
        "    country
" :    "        United Kingdom
",
        "    phone
" :    "
",
        "    email
" :    "        test@email.com
"
    }
    }

I can't see what would be causing the different outputs, can someone help with this as well please?

Body:
Change

<xsl:variable name="xmlOutputVar">
  <xsl:apply-templates select="/"/>
</xsl:variable>

to

<xsl:variable name="xmlOutputVar">
  <xsl:call-template name="xmlOutput"/>
</xsl:variable>

then use the supported extension function like e.g. exsl:node-set and replace

<xsl:apply-templates select="$xmlOutputVar"/>

with

<xsl:apply-templates select="exsl:node-set($xmlOutputVar)/node()" xmlns:exsl="http://exslt.org/common"/>


问:
How can I dynamically work with FetchRequest data in SwiftUI view
I am trying to create a calorie counter view using SwiftUI where workout data is fetched from Core Data and besides writing all of the data out I want to get total number of burnt calories for today. I was thinking of going through the fetched data, check whether its createdAt attribute equals current Date() and if so add it up to sum of self.totalCaloriesBurntToday.

I got an error that ForEach of this type does not conform to certain protocols:

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

Here is my code:

```<code>import SwiftUI

struct ProgressBar: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(
        entity: WorkoutInputData.entity(),
        sortDescriptors: []
    ) var workoutData: FetchedResults<WorkoutInputData>

    @State private var totalCaloriesBurntToday : Int

    var body: some View {
        ForEach(workoutData) { singleWorkout in
            if singleWorkout.createdAt == Date(){
                self.totalCaloriesBurntToday += Int(singleWorkout.caloriesBurnt)!
            }
        }
        return Text("\(self.totalCaloriesBurntToday)")
    }
}
</code>```

I want to output the sum later and want it to change dynamically. Everytime some data object is added or deleted the sum would automatically adjust.

I have tried to go around this using UserDefaults to save the calories there, but there is the problem that the change of data in UserDefaults does not automatically push for changes in the view and hence it is not dynamic.

答:
The SwiftUI's ForEach you used has a return type of Content, which means for every item in the loop it has to return some View. It's not the same as a simple foreach loop.

You can use reduce to calculate totalCaloriesBurnt and filter to choose only today's workouts.

For comparing dates it's better to use Calendar.compare:

```<code>Calendar.current.compare(singleWorkout.createdAt, to: Date(), toGranularity: .day) == .orderedSame
</code>```

Summing up your code can look like this:

```<code>workoutData
  .filter { Calendar.current.compare($0.createdAt, to: Date(), toGranularity: .day) == .orderedSame }
  .reduce(0) { $0 + Int($1.caloriesBurnt)! }
</code>```

Body:
I am trying to create a calorie counter view using SwiftUI where workout data is fetched from Core Data and besides writing all of the data out I want to get total number of burnt calories for today. I was thinking of going through the fetched data, check whether its createdAt attribute equals current Date() and if so add it up to sum of self.totalCaloriesBurntToday.

I got an error that ForEach of this type does not conform to certain protocols:

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

Here is my code:

import SwiftUI

struct ProgressBar: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(
        entity: WorkoutInputData.entity(),
        sortDescriptors: []
    ) var workoutData: FetchedResults<WorkoutInputData>

    @State private var totalCaloriesBurntToday : Int

    var body: some View {
        ForEach(workoutData) { singleWorkout in
            if singleWorkout.createdAt == Date(){
                self.totalCaloriesBurntToday += Int(singleWorkout.caloriesBurnt)!
            }
        }
        return Text("\(self.totalCaloriesBurntToday)")
    }
}

I want to output the sum later and want it to change dynamically. Everytime some data object is added or deleted the sum would automatically adjust.

I have tried to go around this using UserDefaults to save the calories there, but there is the problem that the change of data in UserDefaults does not automatically push for changes in the view and hence it is not dynamic.

Body:
The SwiftUI's ForEach you used has a return type of Content, which means for every item in the loop it has to return some View. It's not the same as a simple foreach loop.

You can use reduce to calculate totalCaloriesBurnt and filter to choose only today's workouts.

For comparing dates it's better to use Calendar.compare:

Calendar.current.compare(singleWorkout.createdAt, to: Date(), toGranularity: .day) == .orderedSame

Summing up your code can look like this:

workoutData
  .filter { Calendar.current.compare($0.createdAt, to: Date(), toGranularity: .day) == .orderedSame }
  .reduce(0) { $0 + Int($1.caloriesBurnt)! }


问:
When add data into Access Database show the error below
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class net.ucanaccess.jdbc.UcanaccessPreparedStatement cannot be cast to class com.mysql.jdbc.PreparedStatement (net.ucanaccess.jdbc.UcanaccessPreparedStatement and com.mysql.jdbc.PreparedStatement are in unnamed module of loader 'app')
    at hamody.NewJFrame.jButton1ActionPerformed(NewJFrame.java:115)
    at hamody.NewJFrame$1.actionPerformed(NewJFrame.java:66)</p>

```<code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   String   usernames  ;
   usernames = jTextField1.getText();

   try {
      Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

      String dbURL = "jdbc:ucanaccess://E:/Database410.mdb" ;

      connection = DriverManager.getConnection(dbURL);

        // Step 2.B: Creating JDBC Statement
        statement = connection.createStatement();

     pst =  (PreparedStatement) connection.prepareStatement("insert into user ( username ,password ) values( ?,? )") ;
     pst.setString(1,usernames);
     int b=Integer.parseInt(jTextField2.getText());

     pst.executeUpdate();

     JOptionPane.showMessageDialog(this,"تم الاضافة");

 } catch (ClassNotFoundException ex){
    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    JOptionPane.showMessageDialog(this,ex);
 }  catch (SQLException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this,ex);
    }

}
</code>```

答:
This line seems to be an offender:

```<code>pst =  (PreparedStatement) connection.prepareStatement("insert into user ( username ,password ) values( ?,? )") ;
</code>```

Why are you casting this to (PreparedStatement)? connection.prepareStetement should give you a PreparedStatement already, without need of casting. Look into your imports. My guess is you will find a line there looking like import com.mysql.jdbc.PreparedStatement or import com.mysql.jdbc.*. Delete it, and also delete the unnecessary cast.

Body:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class net.ucanaccess.jdbc.UcanaccessPreparedStatement cannot be cast to class com.mysql.jdbc.PreparedStatement (net.ucanaccess.jdbc.UcanaccessPreparedStatement and com.mysql.jdbc.PreparedStatement are in unnamed module of loader 'app')
    at hamody.NewJFrame.jButton1ActionPerformed(NewJFrame.java:115)
    at hamody.NewJFrame$1.actionPerformed(NewJFrame.java:66)

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   String   usernames  ;
   usernames = jTextField1.getText();

   try {
      Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

      String dbURL = "jdbc:ucanaccess://E:/Database410.mdb" ;

      connection = DriverManager.getConnection(dbURL);

        // Step 2.B: Creating JDBC Statement
        statement = connection.createStatement();

     pst =  (PreparedStatement) connection.prepareStatement("insert into user ( username ,password ) values( ?,? )") ;
     pst.setString(1,usernames);
     int b=Integer.parseInt(jTextField2.getText());

     pst.executeUpdate();

     JOptionPane.showMessageDialog(this,"تم الاضافة");

 } catch (ClassNotFoundException ex){
    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    JOptionPane.showMessageDialog(this,ex);
 }  catch (SQLException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this,ex);
    }

}

Body:
This line seems to be an offender:

pst =  (PreparedStatement) connection.prepareStatement("insert into user ( username ,password ) values( ?,? )") ;

Why are you casting this to (PreparedStatement)? connection.prepareStetement should give you a PreparedStatement already, without need of casting. Look into your imports. My guess is you will find a line there looking like import com.mysql.jdbc.PreparedStatement or import com.mysql.jdbc.*. Delete it, and also delete the unnecessary cast.


问:
Unhandle Promise sequelize hooks and encrypt password
I'm tryng to register a user in my database.

```<code>const sequelize = require('sequelize')
const { Model, DataTypes } = sequelize
const bcrypt = require('bcrypt')

class User extends Model {

  isPasswordValid(encondedPassword, password) {
   return bcrypt.compareSync(password, encondedPassword)
  }

  static init(sequelize) {
    super.init({
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      }
    }, {
      hooks: {
          beforeCreate:  (user, options) => {
            const salt =  bcrypt.genSaltSync()
            user.setAttributes('password', bcrypt.hashSync(user.password, salt))
          }
      },
      sequelize
    })
  }
}

module.exports = User
</code>```

But when I call User.create({email, password}) it gives me and error:

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: null value in column "password" violates not-null constraint .

If a delete my hook the code works fine but the password will not be encrypted.

答:
setAttributes receive 3 arguments or an object

Try this

```<code>user.setAttributes('setAttributes', 'password', bcrypt.hashSync(user.password, salt))
//OR
user.setAttributes({password: bcrypt.hashSync(user.password, salt)})
</code>```

Simpler use setDataValue

```<code>user.setDataValue('password', bcrypt.hashSync(user.password, salt))
</code>```

Body:
I'm tryng to register a user in my database.

const sequelize = require('sequelize')
const { Model, DataTypes } = sequelize
const bcrypt = require('bcrypt')

class User extends Model {

  isPasswordValid(encondedPassword, password) {
   return bcrypt.compareSync(password, encondedPassword)
  }

  static init(sequelize) {
    super.init({
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      }
    }, {
      hooks: {
          beforeCreate:  (user, options) => {
            const salt =  bcrypt.genSaltSync()
            user.setAttributes('password', bcrypt.hashSync(user.password, salt))
          }
      },
      sequelize
    })
  }
}

module.exports = User

But when I call User.create({email, password}) it gives me and error:

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: null value in column "password" violates not-null constraint .

If a delete my hook the code works fine but the password will not be encrypted.

Body:
setAttributes receive 3 arguments or an object

Try this

user.setAttributes('setAttributes', 'password', bcrypt.hashSync(user.password, salt))
//OR
user.setAttributes({password: bcrypt.hashSync(user.password, salt)})

Simpler use setDataValue

user.setDataValue('password', bcrypt.hashSync(user.password, salt))


问:
I need to count both vowels and consonants but i am stumped on the consonants
I can't figure out how to have both vowels and consonants. The vowels part of the code works fine. I have no idea how to add the consonants.

```<code>import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter some text: ");
      String str = in.nextLine();
      System.out.println(str);

System.out.print("your input has " + count_Vowels(str) + "vowels");
    }
 public static int count_Vowels(String str)
    {
        int vcount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            {
              vcount++;
            }
        }
        return vcount;
    }
public static int count_Consanants(String str)
    {
      int ccount = 0;
      for (int i = 0; i < str.length(); i++)
    {
      char ch = str.charAt(i);
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
      {
        vcount++;
      }
      else
      {
        consonants++;
      }
    }
  }
}
</code>```

I cannot seem to figure out the consonant part of the code

答:
Your code will also count other characters that are not consonants. Here is a simple way to count vowels and consonants:

```<code>for (int i = 0; i < str.length(); i++) {
    //Checks whether a character is a vowel
    if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
        vCount++;
    }
    //Checks whether a character is a consonant
    else if (str.charAt(i) >= 'a' && str.charAt(i)<='z') {
        cCount++;
    }
}
</code>```

Similarly, you can also modify the code for upper case characters.

Slightly elegant:

```<code>Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));

for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    if (vowels.contains(c)) {
        vCount++;
    } else if (c >= 'a' && c <= 'z') {
        cCount++;
    }
}
</code>```

Body:
I can't figure out how to have both vowels and consonants. The vowels part of the code works fine. I have no idea how to add the consonants.

import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter some text: ");
      String str = in.nextLine();
      System.out.println(str);

System.out.print("your input has " + count_Vowels(str) + "vowels");
    }
 public static int count_Vowels(String str)
    {
        int vcount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            {
              vcount++;
            }
        }
        return vcount;
    }
public static int count_Consanants(String str)
    {
      int ccount = 0;
      for (int i = 0; i < str.length(); i++)
    {
      char ch = str.charAt(i);
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
      {
        vcount++;
      }
      else
      {
        consonants++;
      }
    }
  }
}

I cannot seem to figure out the consonant part of the code

Body:
Your code will also count other characters that are not consonants. Here is a simple way to count vowels and consonants:

for (int i = 0; i < str.length(); i++) {
    //Checks whether a character is a vowel
    if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
        vCount++;
    }
    //Checks whether a character is a consonant
    else if (str.charAt(i) >= 'a' && str.charAt(i)<='z') {
        cCount++;
    }
}

Similarly, you can also modify the code for upper case characters.

Slightly elegant:

Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));

for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    if (vowels.contains(c)) {
        vCount++;
    } else if (c >= 'a' && c <= 'z') {
        cCount++;
    }
}


问:
Toggle class on buttons in Svelte
Consider this Svelte code

```<code>{#each filters as filters, i}
   <div class='filter-container'>
      <div class='button filter' on:click={ () => setFilter(filters.name, filterContext)}>{filters.name}</div>
   </div>
{/each}
</code>```

The above filter buttons are made depending on how many filters there are in some js object. How can I create a class that is toggled for all filter buttons when the one button is clicked.

eg. when one is active all the others are not?

答:
Class are just strings - in svelte you can bind them to an expression as any other attribute.

For example:

```

when activefilter === filters.name is true, then the button class will became 'button filter isactive'

A special short syntax to toggle classes is provided too. Find more here

Title: Toggle class on buttons in Svelte

Body:
Consider this Svelte code

{#each filters as filters, i}

 setFilter(filters.name, filterContext)}>{filters.name}

{/each}

The above filter buttons are made depending on how many filters there are in some js object. How can I create a class that is toggled for all filter buttons when the one button is clicked.

eg. when one is active all the others are not?

Body:
Class are just strings - in svelte you can bind them to an expression as any other attribute.

For example:

<div class={'button filter ' + (activefilter === filters.name ? 'isactive' : '')}/>

when activefilter === filters.name is true, then the button class will became 'button filter isactive'

A special short syntax to toggle classes is provided too. Find more here


问:
Adding and removing select value in text area using jquery

i have a textarea, a select list and two buttons:- add and remove

on clicking the add button i want to add the select list value to the textarea and on
remove button click i want to remove the text selected from the textarea.
and on a single click in the text area i want the corresponding added select item to be selected(so that i can click on remove button to remove it)
Please help me with this.

```<code><table cellpadding="0" cellspacing="0">
<tr>
<td colspan="3">
    <select>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    <select>
</td>
</tr>
<tr>
<td><input type="button" value="Remove" style="width:110px" class="btn" id="remove"/></td>
<td  style="width:110px"></td>
<td><input type="button" value="Add" style="width:110px" class="btn" id="add"/></td>
</tr>
<tr>
    <td colspan="3">
        <textarea cols="45" rows="5" id="textarea"  readonly="true" ></textarea>
    </td>
</tr>
</table>
</code>```

Thanks,

Devan

答:
Using jQuery you can get this approach by doing this (easily):

Have two arrays - selected / final

All selected values should go inside "selected" array

Don't use textarea but a div section.

Populate these selected item as ul/li list inside div section (using for loop)

$("#divId").append("

..

")

Now, with the help of js/css whenever user click, apply the css (highlight) + add this selected item inside "final" array

$("#divId #someuniqueId1").css("highlight")

final[someuniqueId1] = $("#divId #someuniqueId1").children("li").html()

Point 5 should continue until user select the list.

To unselect, use ".toggle" and reverse the action - have another css called normal & apply this if the list goes from select to deselect + remove this item from the "final" arry.

$("#divId #someuniqueId1").css("unhighlight")

delete(final['someuniqueId1']) - make sure this works

"Final" array has all the selected items.

ContentLicense: CC BY-SA 3.0

Body:
i have a textarea, a select list and two buttons:- add and remove

on clicking the add button i want to add the select list value to the textarea and on
remove button click i want to remove the text selected from the textarea.
and on a single click in the text area i want the corresponding added select item to be selected(so that i can click on remove button to remove it)
Please help me with this.

    <select>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    <select>

<input type="button" value="Remove" style="width:110px" class="btn" id="remove"/>

<input type="button" value="Add" style="width:110px" class="btn" id="add"/>

        <textarea cols="45" rows="5" id="textarea"  readonly="true" ></textarea>

Thanks,

Devan

Body:
Using jQuery you can get this approach by doing this (easily):

Have two arrays - selected / final

All selected values should go inside "selected" array

Don't use textarea but a div section.

Populate these selected item as ul/li list inside div section (using for loop)

$("#divId").append("<ul id='someuniqueId1'><li>..</li></ul>")

Now, with the help of js/css whenever user click, apply the css (highlight) + add this selected item inside "final" array

$("#divId #someuniqueId1").css("highlight")

final[someuniqueId1] = $("#divId #someuniqueId1").children("li").html()

Point 5 should continue until user select the list.

To unselect, use ".toggle" and reverse the action - have another css called normal & apply this if the list goes from select to deselect + remove this item from the "final" arry.

$("#divId #someuniqueId1").css("unhighlight")

delete(final['someuniqueId1']) - make sure this works

"Final" array has all the selected items.


问:
React Mobx edit observable array
I'm learning Mobx and I'm trying to build a form application which displays some fields of an array and you should be able to edit them.

I have an array @observable myArray, how can I edit a certain field of that array?

I tried making the function:

@action setMyArray(id, value) => {
   myArray.map(field => {
      if (field.id === id) {
          field.text = value
      }
   }
}
```

When I use this as a callback method for a text field, it only adds 1 letter to the current value of field and does not rerender in the textfield.

答:
First of all, you don't have to store data in a array
If you want to store all form fields in one observable field, you should use for example object or Map, like that:

class SomeStore {
  @observable formData = new Map();

  @action
  setValue = (name, value) => {
    this.formData.set(name, value)
  }
}
```

<p>and then you can use such code for react component</p>

<pre class="lang-js prettyprint-override"><code>const onChange = (event) => {
  SomeStore.setValue(event.target.name, event.target.value);
}

return (
  ...
    <input name="firstName" onChange={onChange} value={SomeStore.formData.get('firstName')} />
    <input name="lastName" onChange={onChange} value={SomeStore.formData.get('lastName')} />
  ...
)
</code>```

Title: React Mobx edit observable array

Body:
I'm learning Mobx and I'm trying to build a form application which displays some fields of an array and you should be able to edit them.

I have an array @observable myArray, how can I edit a certain field of that array?

I tried making the function:

@action setMyArray(id, value) => {
   myArray.map(field => {
      if (field.id === id) {
          field.text = value
      }
   }
}

When I use this as a callback method for a text field, it only adds 1 letter to the current value of field and does not rerender in the textfield.

Body:
First of all, you don't have to store data in a array
If you want to store all form fields in one observable field, you should use for example object or Map, like that:

class SomeStore {
  @observable formData = new Map();

  @action
  setValue = (name, value) => {
    this.formData.set(name, value)
  }
}

and then you can use such code for react component

const onChange = (event) => {
  SomeStore.setValue(event.target.name, event.target.value);
}

return (
  ...
    <input name="firstName" onChange={onChange} value={SomeStore.formData.get('firstName')} />
    <input name="lastName" onChange={onChange} value={SomeStore.formData.get('lastName')} />
  ...
)


问:
How do I pass these Integers to another activity?
I have three Integers that are the index values of drawables in another file. Now that I have them in a bundle, how to I retrieve them from another activity? Below is code from the sending activity.</p>

```<code> Bundle b = new Bundle();
    b.putInt("headIndex", headIndex);
    b.putInt("bodyIndex", bodyIndex);
    b.putInt("legIndex", legIndex);

    final Intent intent = new Intent(this, AndroidMeActivity.class);
    intent.putExtras(b);

    Button btnNext = (Button) findViewById(R.id.btnNext);
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){
            startActivity(intent);
        }
    });
</code>```

答:
You can do this in the receiving activity

```<code>Intent intent = getIntent();
if (null != intent) {
    int headIndex = intent.getIntExtra("headIndex");
    // Do this for remaining
}
</code>```

Reference

Body:
I have three Integers that are the index values of drawables in another file. Now that I have them in a bundle, how to I retrieve them from another activity? Below is code from the sending activity.

 Bundle b = new Bundle();
    b.putInt("headIndex", headIndex);
    b.putInt("bodyIndex", bodyIndex);
    b.putInt("legIndex", legIndex);

    final Intent intent = new Intent(this, AndroidMeActivity.class);
    intent.putExtras(b);

    Button btnNext = (Button) findViewById(R.id.btnNext);
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){
            startActivity(intent);
        }
    });

Body:
You can do this in the receiving activity

Intent intent = getIntent();
if (null != intent) {
    int headIndex = intent.getIntExtra("headIndex");
    // Do this for remaining
}

Reference


问:
Javascript Class: getter value when instantiating the class
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

```<code>class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2
</code>```

Just curious to know how we can implement this?

答:
Okey here is another class extending one:

class HeyNumber extends (class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}) {
  constructor() {
    return super().numbers.reverse()
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2```

Is this cheating? I have not touched the class at all, I'm still printing the reverse order of numbers in the class you provided :P

Body:
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2

Just curious to know how we can implement this?

Body:
Okey here is another class extending one:

class HeyNumber extends (class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}) {
  constructor() {
    return super().numbers.reverse()
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2

Is this cheating? I have not touched the class at all, I'm still printing the reverse order of numbers in the class you provided :P