问:
Contains with a predicate (/find/search) for a java.util.concurrent.BlockingQueue?
The java.util.concurrent.BlockingQueue has a convenient contains method:

```<code>/**
 * Returns {@code true} if this queue contains the specified element.
 * More formally, returns {@code true} if and only if this queue contains
 * at least one element {@code e} such that {@code o.equals(e)}.
 *
 * @param o object to be checked for containment in this queue
 * @return {@code true} if this queue contains the specified element
 * @throws ClassCastException if the class of the specified element
 *         is incompatible with this queue
 *         (<a href="../Collection.html#optional-restrictions">optional</a>)
 * @throws NullPointerException if the specified element is null
 *         (<a href="../Collection.html#optional-restrictions">optional</a>)
 */
public boolean contains(Object o);
</code>```

My need is a bit more specific: to apply a predicate / search criteria. Is there any way to do this short of

```<code>  Using a ArrayBlockQueue
  Invoking toArray
</code>```

That will work .. but what if the queue were large? This could cause memory allocation issues.

答:
I don't know whether you should be doing this, but it seems like you could do it:

```<code>public static class Matcher<T> {

    Predicate<T> predicate;
    Class<T> clazz;

    public Matcher(Predicate<T> t, Class<T> clazz) {
        this.predicate = t;
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    public boolean equals(Object o) {
        if (o != null && this.clazz.isInstance(o)) {
            System.out.println("Checking item " + o + " against predicate " + this.predicate);
            return this.predicate.test((T) o);
        }
        return false;
    }
}

public static void main(String args[]) {

    ArrayBlockingQueue<Integer> oddsOnly = new ArrayBlockingQueue<>(10);
    oddsOnly.addAll(Arrays.asList(1, 3, 5, 7, 9, 11, 13));

    ArrayBlockingQueue<Integer> oddsAndEves = new ArrayBlockingQueue<>(10);
    oddsAndEves.addAll(Arrays.asList(1, 2, 3, 4, 5));

    Predicate<Integer> evenPredicate = (i) -> i % 2 == 0;
    System.out.println(oddsOnly.contains(new Matcher<>(evenPredicate, Integer.class))); // prints false

    System.out.println(oddsAndEves.contains(new Matcher<>(evenPredicate, Integer.class))); // prints true
}
</code>```

Output:

```<code>Checking item 1 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 3 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 5 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 7 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 9 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 11 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 13 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
false
Checking item 1 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 2 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
true
</code>```

It does make me want to take a shower though.... Plus, as pvg points out correctly - this isn't guaranteed to work. BlockingQueue implementations might call hashCode() before calling equals() and then we'd be screwed.

A saner option would be to just iterate over the blocking queue, and run the predicate against each element. The BlockingQueue interface doesn't have an iterator, but many blocking queue implementation, such as ArrayBlockingQueue, and LinkedBlockingQueue do.

Body:
The java.util.concurrent.BlockingQueue has a convenient contains method:

/**
 * Returns {@code true} if this queue contains the specified element.
 * More formally, returns {@code true} if and only if this queue contains
 * at least one element {@code e} such that {@code o.equals(e)}.
 *
 * @param o object to be checked for containment in this queue
 * @return {@code true} if this queue contains the specified element
 * @throws ClassCastException if the class of the specified element
 *         is incompatible with this queue
 *         (optional)
 * @throws NullPointerException if the specified element is null
 *         (optional)
 */
public boolean contains(Object o);

My need is a bit more specific: to apply a predicate / search criteria. Is there any way to do this short of

  Using a ArrayBlockQueue
  Invoking toArray

That will work .. but what if the queue were large? This could cause memory allocation issues.

Body:
I don't know whether you should be doing this, but it seems like you could do it:

public static class Matcher<T> {

    Predicate<T> predicate;
    Class<T> clazz;

    public Matcher(Predicate<T> t, Class<T> clazz) {
        this.predicate = t;
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    public boolean equals(Object o) {
        if (o != null && this.clazz.isInstance(o)) {
            System.out.println("Checking item " + o + " against predicate " + this.predicate);
            return this.predicate.test((T) o);
        }
        return false;
    }
}

public static void main(String args[]) {

    ArrayBlockingQueue<Integer> oddsOnly = new ArrayBlockingQueue<>(10);
    oddsOnly.addAll(Arrays.asList(1, 3, 5, 7, 9, 11, 13));

    ArrayBlockingQueue<Integer> oddsAndEves = new ArrayBlockingQueue<>(10);
    oddsAndEves.addAll(Arrays.asList(1, 2, 3, 4, 5));

    Predicate<Integer> evenPredicate = (i) -> i % 2 == 0;
    System.out.println(oddsOnly.contains(new Matcher<>(evenPredicate, Integer.class))); // prints false

    System.out.println(oddsAndEves.contains(new Matcher<>(evenPredicate, Integer.class))); // prints true
}

Output:

Checking item 1 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 3 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 5 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 7 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 9 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 11 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 13 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
false
Checking item 1 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
Checking item 2 against predicate QueueEquals$Matcher$$Lambda$1/531885035@816f27d
true

It does make me want to take a shower though.... Plus, as pvg points out correctly - this isn't guaranteed to work. BlockingQueue implementations might call hashCode() before calling equals() and then we'd be screwed.

A saner option would be to just iterate over the blocking queue, and run the predicate against each element. The BlockingQueue interface doesn't have an iterator, but many blocking queue implementation, such as ArrayBlockingQueue, and LinkedBlockingQueue do.


来源: stackexchange

问:
How to Convert FXML to JAVA
I created a .fxml file using javafx scene builder in NetBeans.

How can I convert .fxml file in NetBeans to .java?
Is that any program to convert it?

I am not very good in fxml so I want to use .java file to code my javafx app.

答:
Is that any program to convert it?

Yes. Netbeans FXML 2 JAVA Converter via Archive.org 2021.03.04 capture.

ContentLicense: CC BY-SA 4.0

Title: How to Convert FXML to JAVA


问:
'dotnet restore' is failing when mixing a private NuGet feed and NEST
dotnet restore fails unexpectedly on certain packages for me and I can't figure out why.

I have a private NuGet repository hosted through the VSTS Packages extension, and my NuGet.Config looks like (as described here https://www.visualstudio.com/en-us/docs/package/nuget/auth#dotnet-core)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="MyPackages" value="https://{myaccount}.pkgs.visualstudio.com/_packaging/{myfeed}/nuget/v3/index.json"` />
  </packageSources>
  <packageCredentials>
    <MyPackages>
        <add key="Username" value="vsts" />
        <add key="ClearTextPassword" value="{my PAT}" />
    </MyPackages>
  </packageCredentials>
</configuration>
```
<p>If I create a new project using <code>dotnet new console</code> and add a reference to a package hosted on my feed, restoring works fine.</p>
<pre class="lang-xml prettyprint-override"><code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="My.Lib" Version="1.0.0"></PackageReference>
  </ItemGroup>
</Project>
</code>```

However, if I also include a package reference to NEST version 2.5.0 (or any version really), dotnet restore fails with

C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Unable to load the service index for source https://{myaccount}.pkgs.visualstudio.com/_packaging/{myfeed}/nuget/v3/index.json.\r `[C:\Users\test\dotnet\dotnet.csproj]
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Response status code does not indicate success: 401 (Unauthorized). [C:\Users\test\dotnet\dotnet.csproj]
```
<p>What's very odd though is that replacing NEST with anything else, restoring will work. For example, adding ElasticSearch.Net 2.5.0 will work fine.</p>
<p>If I remove my package credentials and private NuGet feed from my nuget.config and only reference NEST, then it works - but then I can't access my private feed.</p>
<p>And finally what's most strange is that restoring worked fine yesterday, but now for me and my coworkers we can't restore.</p>
<p>Is this a VSTS Packages issue? What could be different about NEST?</p>
<h2>Steps to reproduce</h2>
<h2>Expected behavior</h2>
<p><code>dotnet restore</code> should not fail restoring</p>
<h2>Actual behavior</h2>
<pre class="lang-none prettyprint-override"><code>dotnet restore fails - citing a 401 unauthorized response from the private nuget feed
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Unable to load the service index for source https://{account}.pkgs.visualstudio.com/_packaging/{feed}/nuget/v3/index.json.\r [C:\Users\davidf\temp\dotnet\dotnet.csproj]
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Response status code does not indicate success: 401 (Unauthorized). [C:\Users\davidf\temp\dotnet\dotnet.csproj]
</code>```

Environment data

dotnet --info output:

dotnet --info
.NET Command Line Tools (1.0.0)

Product Information:
    Version:            1.0.0
    Commit SHA-1 hash:  e53429feb4

Runtime Environment:
    OS Name:     Windows
    OS Version:  10.0.14393
    OS Platform: Windows
    RID:         win10-x64
    Base Path:   C:\Program Files\dotnet\sdk\1.0.0
```
<h3>Full console output</h3>
<pre class="lang-none prettyprint-override"><code>C:\Users\davidf\temp\dotnet>dotnet restore -v diag
C:\Program Files\dotnet\sdk\1.0.0\MSBuild.dll /NoLogo /ConsoleLoggerParameters:Verbosity=Minimal /Logger:Microsoft.DotNet.Tools.MSBuild.MSBuildLogger,C:\Program Files\dotnet\sdk\1.0.0\dotnet.dll /m /t:Restore /v:m /verbosity:diag .\dotnet.csproj
  Restoring packages for C:\Users\davidf\temp\dotnet\dotnet.csproj...
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Unable to load the service index for source https://{account}.pkgs.visualstudio.com/_packaging/{feed}/nuget/v3/index.json.\r [C:\Users\davidf\temp\dotnet\dotnet.csproj]
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error :   Response status code does not indicate success: 401 (Unauthorized). [C:\Users\davidf\temp\dotnet\dotnet.csproj]
</code>```

Some more information -

It seems that when I only use the official nuget.org source, NEST will work as will any other NuGet package as expected. And if there is a typo in the package name, you get an error like error : Unable to resolve NestOops

But when I have my NuGet source as an additional package source, any typo to a package name results in a 401 from my feed. I still don't know why NEST has the same error though.

答:
It looks like a false alarm!

The NuGet configuration was not quite correct - the <packageCredentials> should have been a <packageSourceCredentials>.

My guess is that some of the packages from the VSTS feed were cached (a separate project had its own configuration with the correct element, to put them in the cache to begin with) which is why they appeared to resolve correctly even though they weren't authenticating correctly. Then whenever a package was being looked up, that wasn't in the cache, it would hit our feed with wrong credentials and fail.

Body:
dotnet restore fails unexpectedly on certain packages for me and I can't figure out why.

I have a private NuGet repository hosted through the VSTS Packages extension, and my NuGet.Config looks like (as described here https://www.visualstudio.com/en-us/docs/package/nuget/auth#dotnet-core)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="MyPackages" value="https://{myaccount}.pkgs.visualstudio.com/_packaging/{myfeed}/nuget/v3/index.json"` />
  </packageSources>
  <packageCredentials>
    <MyPackages>
        <add key="Username" value="vsts" />
        <add key="ClearTextPassword" value="{my PAT}" />
    </MyPackages>
  </packageCredentials>
</configuration>

If I create a new project using dotnet new console and add a reference to a package hosted on my feed, restoring works fine.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="My.Lib" Version="1.0.0"></PackageReference>
  </ItemGroup>
</Project>

However, if I also include a package reference to NEST version 2.5.0 (or any version really), dotnet restore fails with

C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Unable to load the service index for source https://{myaccount}.pkgs.visualstudio.com/_packaging/{myfeed}/nuget/v3/index.json.\r `[C:\Users\test\dotnet\dotnet.csproj]
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Response status code does not indicate success: 401 (Unauthorized). [C:\Users\test\dotnet\dotnet.csproj]

What's very odd though is that replacing NEST with anything else, restoring will work. For example, adding ElasticSearch.Net 2.5.0 will work fine.

If I remove my package credentials and private NuGet feed from my nuget.config and only reference NEST, then it works - but then I can't access my private feed.

And finally what's most strange is that restoring worked fine yesterday, but now for me and my coworkers we can't restore.

Is this a VSTS Packages issue? What could be different about NEST?

Steps to reproduce

Expected behavior

dotnet restore should not fail restoring

Actual behavior

dotnet restore fails - citing a 401 unauthorized response from the private nuget feed
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Unable to load the service index for source https://{account}.pkgs.visualstudio.com/_packaging/{feed}/nuget/v3/index.json.\r [C:\Users\davidf\temp\dotnet\dotnet.csproj]
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Response status code does not indicate success: 401 (Unauthorized). [C:\Users\davidf\temp\dotnet\dotnet.csproj]

Environment data

dotnet --info output:

dotnet --info
.NET Command Line Tools (1.0.0)

Product Information:
    Version:            1.0.0
    Commit SHA-1 hash:  e53429feb4

Runtime Environment:
    OS Name:     Windows
    OS Version:  10.0.14393
    OS Platform: Windows
    RID:         win10-x64
    Base Path:   C:\Program Files\dotnet\sdk\1.0.0

Full console output

C:\Users\davidf\temp\dotnet>dotnet restore -v diag
C:\Program Files\dotnet\sdk\1.0.0\MSBuild.dll /NoLogo /ConsoleLoggerParameters:Verbosity=Minimal /Logger:Microsoft.DotNet.Tools.MSBuild.MSBuildLogger,C:\Program Files\dotnet\sdk\1.0.0\dotnet.dll /m /t:Restore /v:m /verbosity:diag .\dotnet.csproj
  Restoring packages for C:\Users\davidf\temp\dotnet\dotnet.csproj...
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Unable to load the service index for source https://{account}.pkgs.visualstudio.com/_packaging/{feed}/nuget/v3/index.json.\r [C:\Users\davidf\temp\dotnet\dotnet.csproj]
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error :   Response status code does not indicate success: 401 (Unauthorized). [C:\Users\davidf\temp\dotnet\dotnet.csproj]

Some more information -

It seems that when I only use the official nuget.org source, NEST will work as will any other NuGet package as expected. And if there is a typo in the package name, you get an error like error : Unable to resolve NestOops

But when I have my NuGet source as an additional package source, any typo to a package name results in a 401 from my feed. I still don't know why NEST has the same error though.


问:
How to send base64 encoded image string into JSON object in javascript?
I wanted to convert a image file into JSON object in javascript.
So I have converted image into a string using base64 encoding.
How to convert this string to JSON object?</p>

答:
Simple, set value to an keyObj.</p>

```<code>    var base64String = 'data:image/png;base64....'
    var imgObj = {
      url: base64String
    }

    <img src=''+ imgObj.url +''/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Simple, set value to an keyObj.

    var base64String = 'data:image/png;base64....'
    var imgObj = {
      url: base64String
    }

    <img src=''+ imgObj.url +''/>


问:
Components required in Sybase unwired platform
I have an requirement to gather the components required to build an application in Sybase unwired platform, I am completely clueless as I suppose that it's a new platform introduced.

Please assist.

答: It's a complex platform too.  In order to best determine what components you need you should provide more detail on what you are trying to do.  What devices are you targeting, and what do you want to accomplish with them?</p>

ContentLicense: CC BY-SA 2.5


问:
What is the proper way to iterate through a list with one item in python?
I have a list that only has one item. I know this list only has one item because it is the output of a MySQL query that will always have just one result.

MySQL Query:

```<code>SELECT MAX(date) FROM db.table;
</code>```

List result:

```<code>['20170307']
</code>```

Now I must access the item in this list. I have two options:

1) By position

```<code>max_date = list[0]
print(max_date)
</code>```

2) By iterating through item(s)

```<code>for item in list:
    max_date = item
print(max_date)
</code>```

Can someone please explain which approach is more appropriate in terms performance, readability, and overall best practice? My IDE raises a red flag when I use approach #2 but is it safe to ignore if I'm confident my list will always have one item?

答: Ideally, using the by position style works since all you need is the first element of the list. Just by reading the code, the for loop gives me an impression of more than 1 element in the list</p>

Body:
I have a list that only has one item. I know this list only has one item because it is the output of a MySQL query that will always have just one result.

MySQL Query:

SELECT MAX(date) FROM db.table;

List result:

['20170307']

Now I must access the item in this list. I have two options:

1) By position

max_date = list[0]
print(max_date)

2) By iterating through item(s)

for item in list:
    max_date = item
print(max_date)

Can someone please explain which approach is more appropriate in terms performance, readability, and overall best practice? My IDE raises a red flag when I use approach #2 but is it safe to ignore if I'm confident my list will always have one item?


问:
Why variable doesn't work inside for /F command?
If you have a variable inside this for /f command, it doesn't get printed out to file.

```<code>setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo %duration% > file.txt
)
</code>```

Contents of file.txt: Echo is ON.

If you move set duration=asdf out of for /f wrap and put it below setlocal line it works correct and prints asdf into file.txt

Why? How do I do this with the set variable inside the for command?

答:
This is due to delayed expansion, which stops variables from being set and used, in the same command.

You are getting Echo is ON. in file.txt, because to the command interpreter it's reading the echo command as:

```<code>echo > file.txt
</code>```

Which as documented by echo /?

Type ECHO without parameters to display the current echo setting.

The simplest fix is to replace the % with !

Updated script:

```<code>setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo !duration! > file.txt
)
</code>```

Body:
If you have a variable inside this for /f command, it doesn't get printed out to file.

setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo %duration% > file.txt
)

Contents of file.txt: Echo is ON.

If you move set duration=asdf out of for /f wrap and put it below setlocal line it works correct and prints asdf into file.txt

Why? How do I do this with the set variable inside the for command?

Body:
This is due to delayed expansion, which stops variables from being set and used, in the same command.

You are getting Echo is ON. in file.txt, because to the command interpreter it's reading the echo command as:

echo > file.txt

Which as documented by echo /?

Type ECHO without parameters to display the current echo setting.

The simplest fix is to replace the % with !

Updated script:

setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo !duration! > file.txt
)


问:
Java Sockets. Server-Client communication
I am trying to connect a client with gui with a server withoout gui. Connection is being done, but i cant see any messages between these two apps.
(i should get SERVER HERE in client, and CLIENT HERE in server)

Client Connection Code:

```<code>@Override
public void ClientRunning(){
    try {
       connectToServer();
        setStreams();
        ClientRun();

    }catch(EOFException oefException){
        showMessage("\n Client terminated the connection\n");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        close();
    }
}

public void connectToServer() throws IOException{
    showMessage("Attempting Connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);
    showMessage("Connected to: "+ connection.getInetAddress().getHostName());
}

public void setStreams() throws IOException{
   output = new PrintWriter(connection.getOutputStream(),true);
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}

public void close(){
    showMessage("\n closing...");
    try{
      output.close();
      input.close();
      connection.close();

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void showMessage(final String text){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            cwindow.append(text);
        }
    });
}

public void sendMessage(String message){
    output.write("CLIENT - "+message);
    output.flush();
    showMessage("\nCLIENT - "+message);
}

private void ClientRun() throws IOException{
    String message="CLIENT HERE!";
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }
</code>```

(input and output are defined in GUI class in which this Client class is extended to. Defined as "protected BufferedReader input;
protected PrintWriter output;")

Also, servers code:

```<code>public class ServerClass {

private ServerSocket server;
private Socket connection;
private BufferedReader input;
private BufferedWriter output;

public void startServer(){
    try{
        server=new ServerSocket(6789,100);
        while(true){
            try{
                waitForConnection();
                setStreams();
                ServerRunning();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");

            }finally{
            close();

        }
        }

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

private void waitForConnection() throws IOException{
    showMessage("Waiting for someone to connect... \n");
    connection=server.accept();
    showMessage("Now connected to "+ connection.getInetAddress().getHostName());
}

private void setStreams() throws IOException{
   output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}
public void ServerRunning() throws IOException{
    String message="SERVER HERE!";
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

  }
private void close(){
    showMessage("\n Closing connections... \n");
    try{
        output.close();
        input.close();
        connection.close();

}catch(IOException ioException){
    ioException.printStackTrace();
}
}
private void showMessage(String text){
    System.out.println(text);
}

private void sendMessage(String message){
    try{
       output.write("SERVER - "+message);
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}
</code>```

Connection seems to be ok, so i don't get whats wrong. Any help would be appreciated.

PS: i also tried PrintWriter in server as well and also tried a try catch in stream statement, the problem remains.

答:
[SOLVED]
As TedTrippin and Alfie mentioned readline(), messed my code. After adding "\n" in each message, everything seems to work smooth! I also changed printwriter to bufferwritter in client code, and i also added a try-catch function in sendMessage, cause printwritter seems to cause some problem as well for some reason.
Anyway, everything is set and done! Thanks guys!

UPDATED CLIENT CODE:

```<code>private void ClientRun() throws IOException{
    String message="CLIENT HERE! \n"; <----added \n here.
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

public void sendMessage(String message){
    try{                                 <-----added try-catch statement
       output.write("CLIENT - "+message+"\n"); <----adding "\n" here is super userful, instead of having to add \n in each message.
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

protected BufferedReader input;
protected BufferedWriter output; <----changed printwriter to BufferWriter
</code>```

UPDATED SERVER CODE:

```<code>public void ServerRunning() throws IOException{
    String message="SERVER HERE! \n";    <--- added \n here as well.
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
</code>```

}

Thanks guys!

Body:
I am trying to connect a client with gui with a server withoout gui. Connection is being done, but i cant see any messages between these two apps.
(i should get SERVER HERE in client, and CLIENT HERE in server)

Client Connection Code:

@Override
public void ClientRunning(){
    try {
       connectToServer();
        setStreams();
        ClientRun();

    }catch(EOFException oefException){
        showMessage("\n Client terminated the connection\n");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        close();
    }
}

public void connectToServer() throws IOException{
    showMessage("Attempting Connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);
    showMessage("Connected to: "+ connection.getInetAddress().getHostName());
}

public void setStreams() throws IOException{
   output = new PrintWriter(connection.getOutputStream(),true);
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}

public void close(){
    showMessage("\n closing...");
    try{
      output.close();
      input.close();
      connection.close();

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void showMessage(final String text){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            cwindow.append(text);
        }
    });
}

public void sendMessage(String message){
    output.write("CLIENT - "+message);
    output.flush();
    showMessage("\nCLIENT - "+message);
}

private void ClientRun() throws IOException{
    String message="CLIENT HERE!";
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

(input and output are defined in GUI class in which this Client class is extended to. Defined as "protected BufferedReader input;
protected PrintWriter output;")

Also, servers code:

public class ServerClass {

private ServerSocket server;
private Socket connection;
private BufferedReader input;
private BufferedWriter output;

public void startServer(){
    try{
        server=new ServerSocket(6789,100);
        while(true){
            try{
                waitForConnection();
                setStreams();
                ServerRunning();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");

            }finally{
            close();

        }
        }

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

private void waitForConnection() throws IOException{
    showMessage("Waiting for someone to connect... \n");
    connection=server.accept();
    showMessage("Now connected to "+ connection.getInetAddress().getHostName());
}

private void setStreams() throws IOException{
   output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}
public void ServerRunning() throws IOException{
    String message="SERVER HERE!";
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

  }
private void close(){
    showMessage("\n Closing connections... \n");
    try{
        output.close();
        input.close();
        connection.close();

}catch(IOException ioException){
    ioException.printStackTrace();
}
}
private void showMessage(String text){
    System.out.println(text);
}

private void sendMessage(String message){
    try{
       output.write("SERVER - "+message);
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

Connection seems to be ok, so i don't get whats wrong. Any help would be appreciated.

PS: i also tried PrintWriter in server as well and also tried a try catch in stream statement, the problem remains.

Body:
[SOLVED]
As TedTrippin and Alfie mentioned readline(), messed my code. After adding "\n" in each message, everything seems to work smooth! I also changed printwriter to bufferwritter in client code, and i also added a try-catch function in sendMessage, cause printwritter seems to cause some problem as well for some reason.
Anyway, everything is set and done! Thanks guys!

UPDATED CLIENT CODE:

private void ClientRun() throws IOException{
    String message="CLIENT HERE! \n"; <----added \n here.
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

public void sendMessage(String message){
    try{                                 <-----added try-catch statement
       output.write("CLIENT - "+message+"\n"); <----adding "\n" here is super userful, instead of having to add \n in each message.
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

protected BufferedReader input;
protected BufferedWriter output; <----changed printwriter to BufferWriter

UPDATED SERVER CODE:

public void ServerRunning() throws IOException{
    String message="SERVER HERE! \n";    <--- added \n here as well.
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

}

Thanks guys!


问:
ASP.Net MVC vs. Ruby on Rails
If you were starting a new web development project would you use ASP.Net MVC 2 or Ruby on Rails?

I have recently invested some time in to learning Ruby on Rails because I wanted to learn a solid web development framework.  Then I took a new job where I will be using ASP.Net MVC 2.

I know this question is very subjective, but I am planning to write some websites on my own, outside of work, and I would like to get some opinions from others.

答:
The .NET skills you'll acquire working with ASP.NET are applicable across the entire development spectrum; not just web development. Want to write desktop apps? XBOX games? Parallel processing services? Linux or Android apps? You can do all of that with C#/.NET.

I've heard good things about Ruby. I use a variety of languages for different tasks -physicists seem to love SCHEME which has been causing my therapist nightmares as of late - but my web projects are exclusively in .NET.

The best way to become proficient with a new language is to immerse yourself in it, and write something FUN. If you want to get up to speed on the new job as quickly as possible, write something you're interested in using the tools they prefer. ASP.NET MVC is more complex than Ruby, but it's also incredibly powerful once you pass that "Ah ha!" bump in the learning curve.

Title: ASP.Net MVC vs. Ruby on Rails


问:
resteasy javax.ws.rs.NotFoundException: Could not find resource for full path

Condition

1.resteasy 3.0.4.Final

2.eclipse

3.maven

Action

I got war package into tomcat7(window x64) webapps and server run normally.

Visit http://localhost:8080/test-resteasy/rest/message/hello, and browser print "Restful example : hello".

But when I maven build tomcat7:run tomcat7-maven-plugin in eclipse,visit the same url throws:

```<code> javax.ws.rs.NotFoundException: Could not find resource for full path
</code>```

Source (web.xml)

```<code><!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>Archetype Created Web Application</display-name>

  <!-- Auto scan REST service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <!-- this need same with resteasy servlet url-pattern -->
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

(pom.xml)

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>top.crowley.rest</groupId>
    <artifactId>resteasy</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>resteasy Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
                <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-servlet-initializer</artifactId>
            <version>3.0.4.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>3.0.4.Final</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>test-resteasy</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>8080</port>
                    <path>/test-resteasy</path>
                    <uriEncoding>UTF-8</uriEncoding>
                    <finalName>test resteasy</finalName>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

MessageRestService

```<code>package top.crowley.resteasy;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/message")
public class MessageRestService {
    @GET
    @Path("/{param}")
    public Response printMessage(@PathParam("param") String msg) {

        String result = "Restful example : " + msg;

        return Response.status(200).entity(result).build();

    }

}
</code>```

Conjecture

I think of source code is correct, because of run war package in single tomcat 7 server successful. Maybe lack of some dependencies in pom.xml.

Thanks!

答:
Really long post to analyze each POM dependency....but why don't you give a try to compile maven in this way, suggested by official resteasy team?

mvn clean install
mvn jetty:run

https://github.com/resteasy/resteasy-examples/tree/3.1.1.Final/resteasy-springMVC

Body:
Condition

1.resteasy 3.0.4.Final

2.eclipse

3.maven

Action

I got war package into tomcat7(window x64) webapps and server run normally.

Visit http://localhost:8080/test-resteasy/rest/message/hello, and browser print "Restful example : hello".

But when I maven build tomcat7:run tomcat7-maven-plugin in eclipse,visit the same url throws:

 javax.ws.rs.NotFoundException: Could not find resource for full path

Source (web.xml)

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>Archetype Created Web Application</display-name>

    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

(pom.xml)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>top.crowley.rest</groupId>
    <artifactId>resteasy</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>resteasy Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
                <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-servlet-initializer</artifactId>
            <version>3.0.4.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>3.0.4.Final</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>test-resteasy</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>8080</port>
                    <path>/test-resteasy</path>
                    <uriEncoding>UTF-8</uriEncoding>
                    <finalName>test resteasy</finalName>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

MessageRestService

package top.crowley.resteasy;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/message")
public class MessageRestService {
    @GET
    @Path("/{param}")
    public Response printMessage(@PathParam("param") String msg) {

        String result = "Restful example : " + msg;

        return Response.status(200).entity(result).build();

    }

}

Conjecture

I think of source code is correct, because of run war package in single tomcat 7 server successful. Maybe lack of some dependencies in pom.xml.

Thanks!


问:
Phonegap Camera Plugin Lock Orientation
Phonegap camera plugin https://github.com/apache/cordova-plugin-camera not respecting the orientation set on the config.xml file. My app is lock in landscape, when camera opens it respect the config and it sets landscape, but when rotating the device(while the camera is open) the camera rotates to portrait. I want to prevent this from happening.

I wouldn't question this if only the rotation bug on webview(where the webview gets cut off) is not there.

答:
I'm assuming you are the person that reported this bug: https://issues.apache.org/jira/browse/CB-11887.

I also have struggled with this issue, but supposedly there is a fix in the latest version of cordova-plugin-camera. I haven't figured out how to actually use it (as the usage is still undocumented), but here's the link to the PR that added the functionality: https://github.com/apache/cordova-plugin-camera/pull/167.

If anyone figures out the best way to use this new feature, please comment here or add a better answer.

Title: Phonegap Camera Plugin Lock Orientation


问:
Result: [OPERATION FAILED]: MyFirstVFPage: The page you have tried to delete is currently being referenced by a page, custom link, button
I am facing the below error in my salesforce.org.

```<code>Operation: Deleting Selected Metadata
Timestamp: Wed, 29 Mar 2017 19:47:33
   Result: [OPERATION FAILED]: MyFirstVFPage: The page you have tried to delete is currently being referenced by a page, custom link, button, web tab, dashboard, SoftPhone layout or custom sidebar component. Please delete the reference before deleting the page.
</code>```

I am not sure whats going wrong and where to check it ?

答:
The message says that your Visualforce page is referenced from a button, page layout, etc. You cannot delete a page if it is used anywhere.

To find out what refers to your page, go to Setup/Build/Develop/Visualforce Pages and click on the field label for your page (MyFirstVFPage). At the top of the detail page, click the button "Where is this used?". This will display a list of all places that refer to your page.

You will need to remove the Visualforce page from anything in the list.

Body:
I am facing the below error in my salesforce.org.

Operation: Deleting Selected Metadata
Timestamp: Wed, 29 Mar 2017 19:47:33
   Result: [OPERATION FAILED]: MyFirstVFPage: The page you have tried to delete is currently being referenced by a page, custom link, button, web tab, dashboard, SoftPhone layout or custom sidebar component. Please delete the reference before deleting the page.

I am not sure whats going wrong and where to check it ?


问:
I think my code is all correct but it does not work
I coded this to show me this:

1  + (1/2!) + (1/3!) + … + (1/n!)

  if ( n < 10 )

```<code>#include <iostream>
using namespace std;
int main() {
int n;
float factn=1,m,sum;
cout<<"enter n\n";
cin>>n;
if(n<10&&n>=0){
do{
        factn=factn*n;
        m=1/factn;
        sum=sum+m;
        n--;
    }while(n>=1);
        cout<<sum;
}
else{
    cout<<"error!\n";
}
return 0;

}
</code>```

This code must show this:

( n < 10 )      1  + (1/2!) + (1/3!) + … + (1/n!)

What is the problem?

It returns wrong values :(

答: You have not initialized sum=0 in the beginning. The variable sum, has a random value, that is stored in Ram at that location in memory where sum should be.</p>

Body:
I coded this to show me this:

1  + (1/2!) + (1/3!) + … + (1/n!)

  if ( n < 10 )

#include <iostream>
using namespace std;
int main() {
int n;
float factn=1,m,sum;
cout<<"enter n\n";
cin>>n;
if(n<10&&n>=0){
do{
        factn=factn*n;
        m=1/factn;
        sum=sum+m;
        n--;
    }while(n>=1);
        cout<<sum;
}
else{
    cout<<"error!\n";
}
return 0;

}

This code must show this:

( n < 10 )      1  + (1/2!) + (1/3!) + … + (1/n!)

What is the problem?

It returns wrong values :(


问:
german date format for the datepicker of ng-bootstrap
I need your help using NgbDateParserFormatter for the datepicker of ng-bootstrap. I need the german format dd.MM.yyyy (for example 31.03.2017).

I have got a plunker, but it does not work correctly:

selecting some dates work (selecting for example 17.03.2017 leads to 17.03.2017)

selecting some dates do not work (selecting 02.09.1937 gets to 01.09.1937)

typing a date swaps day and month (01.03.2017 gets to 03.01.2017 and 14.03.2017 gets to an empty input due to there is no 03.14.2017)

Here is the code:

```<code>import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';

export class CustomNgbDateParserFormatter extends NgbDateParserFormatter {
    datePipe = new DatePipe('de-AT');
    constructor(
        private dateFormatString: string) {
        super();
    }
    format(date: NgbDateStruct): string {
        if (date === null) {
            return '';
        }
        try {
            return this.datePipe.transform(new Date(date.year, date.month - 1, date.day), this.dateFormatString);
        } catch (e) {
            return '';
        }
    }
    parse(value: string): NgbDateStruct {
        let returnVal: NgbDateStruct;
        if (!value) {
            returnVal = null;
        } else {
            try {
                let dateParts = this.datePipe.transform(value, 'M-d-y').split('-');
                returnVal = { year: parseInt(dateParts[2]), month: parseInt(dateParts[0]), day: parseInt(dateParts[1]) };
            } catch (e) {
                returnVal = null;
            }
        }
        return returnVal;
    }
}
</code>```

Could you help me, please?

Thank you very much for your help.

答:
You are making your life harder for yourself by using JS Date objects and the DatePipe. Those are problematic for the following reasons:

Date JS objects carry time and time-zone information so without being careful you can easily get into time-zone conversion related issues - this is precisely why ng-bootstrap is using dedicated data structures

DataPipe uses Intl API under the hood and it is quite buggy, unfortunately.

The good news is that you can easily implement desired functionality by following the ISO parser / formatter as seen here: https://github.com/ng-bootstrap/ng-bootstrap/blob/088363551b5d5ecd602a82aedfc97d43a75a080f/src/datepicker/ngb-date-parser-formatter.ts#L25-L45

If I'm reading your intention correctly, your code could look like follows:

```<code>export class CustomNgbDateParserFormatter extends NgbDateParserFormatter {

    format(date: NgbDateStruct): string {
      return date ? `${padNumber(date.month)}.${padNumber(date.day)}.${date.year}` : '';
    }

    parse(value: string): NgbDateStruct {
        if (value) {
      const dateParts = value.trim().split('.');
      if (dateParts.length === 1 && isNumber(dateParts[0])) {
        return {year: null, month: toInteger(dateParts[0]), day: null};
      } else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
        return {year: null, month: toInteger(dateParts[0]), day: toInteger(dateParts[1])};
      } else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
        return {year: toInteger(dateParts[2]), month: toInteger(dateParts[0]), day: toInteger(dateParts[1])};
      }
    }
    return null;
    }
}
</code>```

Here is a plunker showing this in action: https://plnkr.co/edit/JdX0eHcl7QddOWxM9aT0?p=preview

Body:
I need your help using NgbDateParserFormatter for the datepicker of ng-bootstrap. I need the german format dd.MM.yyyy (for example 31.03.2017).

I have got a plunker, but it does not work correctly:

selecting some dates work (selecting for example 17.03.2017 leads to 17.03.2017)

selecting some dates do not work (selecting 02.09.1937 gets to 01.09.1937)

typing a date swaps day and month (01.03.2017 gets to 03.01.2017 and 14.03.2017 gets to an empty input due to there is no 03.14.2017)

Here is the code:

import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';

export class CustomNgbDateParserFormatter extends NgbDateParserFormatter {
    datePipe = new DatePipe('de-AT');
    constructor(
        private dateFormatString: string) {
        super();
    }
    format(date: NgbDateStruct): string {
        if (date === null) {
            return '';
        }
        try {
            return this.datePipe.transform(new Date(date.year, date.month - 1, date.day), this.dateFormatString);
        } catch (e) {
            return '';
        }
    }
    parse(value: string): NgbDateStruct {
        let returnVal: NgbDateStruct;
        if (!value) {
            returnVal = null;
        } else {
            try {
                let dateParts = this.datePipe.transform(value, 'M-d-y').split('-');
                returnVal = { year: parseInt(dateParts[2]), month: parseInt(dateParts[0]), day: parseInt(dateParts[1]) };
            } catch (e) {
                returnVal = null;
            }
        }
        return returnVal;
    }
}

Could you help me, please?

Thank you very much for your help.

Body:
You are making your life harder for yourself by using JS Date objects and the DatePipe. Those are problematic for the following reasons:

Date JS objects carry time and time-zone information so without being careful you can easily get into time-zone conversion related issues - this is precisely why ng-bootstrap is using dedicated data structures

DataPipe uses Intl API under the hood and it is quite buggy, unfortunately.

The good news is that you can easily implement desired functionality by following the ISO parser / formatter as seen here: https://github.com/ng-bootstrap/ng-bootstrap/blob/088363551b5d5ecd602a82aedfc97d43a75a080f/src/datepicker/ngb-date-parser-formatter.ts#L25-L45

If I'm reading your intention correctly, your code could look like follows:

export class CustomNgbDateParserFormatter extends NgbDateParserFormatter {

    format(date: NgbDateStruct): string {
      return date ? `${padNumber(date.month)}.${padNumber(date.day)}.${date.year}` : '';
    }

    parse(value: string): NgbDateStruct {
        if (value) {
      const dateParts = value.trim().split('.');
      if (dateParts.length === 1 && isNumber(dateParts[0])) {
        return {year: null, month: toInteger(dateParts[0]), day: null};
      } else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
        return {year: null, month: toInteger(dateParts[0]), day: toInteger(dateParts[1])};
      } else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
        return {year: toInteger(dateParts[2]), month: toInteger(dateParts[0]), day: toInteger(dateParts[1])};
      }
    }
    return null;
    }
}

Here is a plunker showing this in action: https://plnkr.co/edit/JdX0eHcl7QddOWxM9aT0?p=preview


问:
How to print a string and integer variable together?
I have written the following script:

```<code>string="My name"
age=19
print(string +str(age))
</code>```

But this gives an error stating:

```<code>"str object is not callable".
</code>```

Help me to typecast and print.

答:
String.format can help here.

```<code>print ("{0} {1}".format(string, age) )
</code>```

this results is the following being printed.

```<code>My name 19
</code>```

You can use this method to improve the readability of the output as well.

```<code>print ("Name: {0} age: {1}".format(string, age)
</code>```

This would result in the following output.

```<code>Name: My Name age: 19
</code>```

Body:
I have written the following script:

string="My name"
age=19
print(string +str(age))

But this gives an error stating:

"str object is not callable".

Help me to typecast and print.

Body:
String.format can help here.

print ("{0} {1}".format(string, age) )

this results is the following being printed.

My name 19

You can use this method to improve the readability of the output as well.

print ("Name: {0} age: {1}".format(string, age)

This would result in the following output.

Name: My Name age: 19


问:
Spring ActiveMQ Connection Error Handling in a Loop
Part of my application requires a constant loop to check our ActiveMQ Messaging queue for "work".  I have setup this using a dedicated thread that starts after Spring initializes everything, so I have all my DI items I need.  The thread handles everything in a while(true) loop for now to just keep looking for messages.

I am setting up a single ActiveMQConnectionFactory and injecting it.  Using that AMQCF, in the loop I create a new Connection, setup a Session from the connection, set a Destination, and finally look at a MessageConsumer to receive(5000).  If that detects a Message, I handle it and everything is fine.

My issue is connectivity issues between my application and the broker.  If the connection dies (AMQ goes down, etc) then an Exception is thrown and everything just kinda blows up.

```<code>javax.jms.JMSException: java.io.EOFException
at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:72)
at org.apache.activemq.ActiveMQMessageConsumer.dequeue(ActiveMQMessageConsumer.java:492)
at org.apache.activemq.ActiveMQMessageConsumer.receive(ActiveMQMessageConsumer.java:650)
at [AMQThreadClass]
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at org.apache.activemq.openwire.OpenWireFormat.unmarshal(OpenWireFormat.java:268)
at org.apache.activemq.transport.tcp.TcpTransport.readCommand(TcpTransport.java:240)
at org.apache.activemq.transport.tcp.TcpTransport.doRun(TcpTransport.java:232)
at org.apache.activemq.transport.tcp.TcpTransport.run(TcpTransport.java:215)
... 1 more
</code>```

When my connection factory is setup I use a location containing a failover jms.location=failover:(tcp://localhost:61616)?reconnectDelayExponent=2.0&useExponentialBackOff=true&initialReconnectDelay=30&maxReconnectAttempts=0 which I thought would work.  I think there is something else maybe missing, either from the loop or how I am handling the idea of Connect/Session/Destination/Consumer loop.

Does anyone have any idea what could be the proper way to safely handle connection issues which are bound to happen?

答:
It seems having the reconnect string in the URI is very helpful.  This helps try and keep the connection alive.  I ended up using a DefaultMessageListenerContainer and MessageListenerAdapter in Spring with a TaskExecutor to handle the "watching" of the queue.  This makes it monitored with Spring and eliminated the need of a higher thread to handle the looping over the queue.

A needed step was making sure this was set to autoStartup(false).  If the queue is down when Spring tries to initialize the Bean it will just wait and wait and never start.  To handle starting the connection (which initiates the monitoring set in place), I added a Startup Housekeeper kind of thread that implements ApplicationListener<ContextRefreshedEvent> for Spring.  This way on application start, after Beans are initialized and everything is "stable", I can then try and call the ListenerContainer to start up.

Starting the container up was moved into its own thread so it could be done asynchronously from the app and not block if the connection wasn't ready.  This allows the app to start just fine (queue up or down) and then connect when it can, adding in a Listener to handle any messages coming in.

No nasty while loop needed :)

Body:
Part of my application requires a constant loop to check our ActiveMQ Messaging queue for "work".  I have setup this using a dedicated thread that starts after Spring initializes everything, so I have all my DI items I need.  The thread handles everything in a while(true) loop for now to just keep looking for messages.

I am setting up a single ActiveMQConnectionFactory and injecting it.  Using that AMQCF, in the loop I create a new Connection, setup a Session from the connection, set a Destination, and finally look at a MessageConsumer to receive(5000).  If that detects a Message, I handle it and everything is fine.

My issue is connectivity issues between my application and the broker.  If the connection dies (AMQ goes down, etc) then an Exception is thrown and everything just kinda blows up.

javax.jms.JMSException: java.io.EOFException
at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:72)
at org.apache.activemq.ActiveMQMessageConsumer.dequeue(ActiveMQMessageConsumer.java:492)
at org.apache.activemq.ActiveMQMessageConsumer.receive(ActiveMQMessageConsumer.java:650)
at [AMQThreadClass]
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at org.apache.activemq.openwire.OpenWireFormat.unmarshal(OpenWireFormat.java:268)
at org.apache.activemq.transport.tcp.TcpTransport.readCommand(TcpTransport.java:240)
at org.apache.activemq.transport.tcp.TcpTransport.doRun(TcpTransport.java:232)
at org.apache.activemq.transport.tcp.TcpTransport.run(TcpTransport.java:215)
... 1 more

When my connection factory is setup I use a location containing a failover jms.location=failover:(tcp://localhost:61616)?reconnectDelayExponent=2.0&useExponentialBackOff=true&initialReconnectDelay=30&maxReconnectAttempts=0 which I thought would work.  I think there is something else maybe missing, either from the loop or how I am handling the idea of Connect/Session/Destination/Consumer loop.

Does anyone have any idea what could be the proper way to safely handle connection issues which are bound to happen?


问:
Spread Syntax with Map and Filter
I found this interesting problem and wanted to share with you guys.
The question is :

```<code>[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]
</code>```

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the  console gave me [1,1,2,7]. I couldn't quite understand 2 things.

why were the 0's left out of filter

what's the 7 doing there

答:
The first operation here is Array#map [-1, 0, 1].map(x => x + 1) which basically adds 1 to each element, returning [0, 1, 2] array.

Next one is Array#filter operation, [0, 1, ...[0, 1, 2]].filter(x => x) which actually returns a new array, without every falsy value (false, 0, undefined, null, "") out of the array.

The last operation looks like [...[1, 1, 2], 7] and gets rid of the nested array with the spread operator returning [1, 1, 2, 7].

Title: Spread Syntax with Map and Filter

Body:
I found this interesting problem and wanted to share with you guys.
The question is :

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the  console gave me [1,1,2,7]. I couldn't quite understand 2 things.

why were the 0's left out of filter

what's the 7 doing there


问:
Auto close InfoWindow Google Maps API when click another marker
I have problem with my Google Maps API v3 script. I am using CodeIgniter framework.
The problem is when I clicked a marker, and then click another marker, InfoWindow Google Maps on previous marker didn't close. This is my code:

```<code><script type="text/javascript">
      var peta;
      var gambar_kantor = new Array();
      var nama     = new Array();
      var kategori = new Array();
      var alamat   = new Array();
      var telpon   = new Array();
      var x        = new Array();
      var y        = new Array();
      var i;
      var url;
      var gambar_marker;
      var gambar_kantor;
      var baseurl  = "<?php echo base_url() ?>";

      function map_init() {
          var map = new google.maps.LatLng(-6.990411, 110.422542);

          var myStyles =[
          {
              featureType: "poi",
              elementType: "labels",
              stylers: [
                    { visibility: "off" }
              ]
          }
          ];

          var petaoption = {
              zoom: 12,
              center: map,
              mapTypeId: google.maps.MapTypeId.ROADMAP,
              styles: myStyles
              };

          peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);

          getdatabase();
      }

      function getdatabase(){
          var markers = [];
          var info= [];

          <?php
        $query = $this->db->query("SELECT l.id, l.nama, l.gambar, l.alamat, l.telp, l.latittude, l.longitude, k.nama_kategori, k.ikon
                                    FROM lokasi as l, kategori as k
                                    WHERE l.kategori=k.id");
          $i = 0;
          $js = "";

          foreach ($query->result() as $value) {

          $js .= 'nama['.$i.'] = "'.$value->nama.'";
                  alamat['.$i.'] = "'.$value->alamat.'";
                  telpon['.$i.'] = "'.$value->telp.'";
                  x['.$i.'] = "'.$value->latittude.'";
                  y['.$i.'] = "'.$value->longitude.'";
                  set_icon("'.$value->ikon.'");

                  var point = new google.maps.LatLng(parseFloat(x['.$i.']),parseFloat(y['.$i.']));

                  var contentString = "<table>"+
                                              "<tr>"+
                                                  "<td align=center><br><b>" + nama['.$i.'] + "</b></td>"+
                                              "</tr>"+
                                              "<tr>"+
                                                  "<td align=center width=300px>" + alamat['.$i.'] + "</td>"+
                                              "</tr>"+
                                              "<tr>"+
                                                  "<td align=center> Telp: " + telpon['.$i.'] + "</td>"+
                                              "</tr>"+
                                          "</table>";

                  var currentInfoWindow = null;

                  var infowindow = new google.maps.InfoWindow({
                      content: contentString

                  });

                  var marker = new google.maps.Marker({
                          position: point,
                          map: peta,
                          icon: gambar_marker,
                          clickable: true
                      });

                  markers.push(marker);
                  info.push(infowindow);

                  google.maps.event.addListener(markers['.$i.'], "click", function() {
                    info['.$i.'].open(peta,markers['.$i.']);
                  });
               ';
            $i++;
      }

      // echo JS
      echo $js;
      ?>
  }
</code>```

Any solution to make InfoWindow auto close when another marker clicked?
I have tried several solutions on Stackoverflow and Google but didn't worked. Thanks for your kindly help :)

答:
You could declare just one infowindow, outside of your loop. Then each marker, when clicked, opens that infowindow on itself, filling it with the proper contents.

In the following example I set the contentString property on the marker itself.

```<code>var infowindow = new google.maps.InfoWindow();

<?php
foreach ($query->result() as $value) {
....
?>

    var marker = new google.maps.Marker({
                   position: point,
                   map: peta,
                   icon: gambar_marker,
                   clickable: true,
                   content: contentString
                 });

    markers.push(marker);

    google.maps.event.addListener(marker, "click", function() {
        infowindow.setContent(marker.content);
        infowindow.open(peta,marker);
    });

<?php
  }
?>
</code>```

Body:
You could declare just one infowindow, outside of your loop. Then each marker, when clicked, opens that infowindow on itself, filling it with the proper contents.

In the following example I set the contentString property on the marker itself.

var infowindow = new google.maps.InfoWindow();

<?php
foreach ($query->result() as $value) {
....
?>

    var marker = new google.maps.Marker({
                   position: point,
                   map: peta,
                   icon: gambar_marker,
                   clickable: true,
                   content: contentString
                 });

    markers.push(marker);

    google.maps.event.addListener(marker, "click", function() {
        infowindow.setContent(marker.content);
        infowindow.open(peta,marker);
    });

<?php
  }
?>


问:
Check for ascending order of a list in Racket
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

```<code>(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))
</code>```

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."

答:
This Scheme solution uses an explicitly recursive named let and memoization:

(define (ascending? xs)
   (if (null? xs) #t                    ; Edge case: empty list
      (let asc? ((x (car xs))           ; Named `let`
                 (xs' (cdr xs)) )
         (if (null? xs') #t
            (let ((x' (car xs')))       ; Memoization of `(car xs)`
               (if (< x x')
                  (asc? x' (cdr xs'))   ; Tail recursion
                  #f))))))              ; Short-circuit termination

(display
   (ascending?
      (list 1 1 2) ))                   ; `#f`
```

Body:
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."


答:
I'd use a third option, sequence-unpacking syntax:

```<code>max_date, = list
</code>```

Note the comma.  This has the benefit of raising an exception if list is not in fact a sequence of length 1.

In terms of speed, list[0] almost certainly runs fastest.

Title: What is the proper way to iterate through a list with one item in python?

Body:
I'd use a third option, sequence-unpacking syntax:

max_date, = list

Note the comma.  This has the benefit of raising an exception if list is not in fact a sequence of length 1.

In terms of speed, list[0] almost certainly runs fastest.


问:
detect if input value selected via Enter press not onclick
I have an input tag

```<code><input type="text" name="cOperator"  class="form-control scale-input operator"  placeholder="Enter your ID" autocomplete="off"  onkeyup="ajax_showOptions(this,'getEmp',event)" required>
</code>```

So when I start typing in, it shows employee list. And I have a jQuery function that handles click event.

```<code>$( document ).on( "click",".optionDivSelected, .optionDiv",  function() {
     if($('.operator').val().length > 0){
        $('.operator-li').next().addClass('active');
        $( '.operator-li' ).find('span').addClass('hidden');
        $('.operator-value').show();
        $('.operator-value h1 span').html($('.operator').val());
        $('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
     }
});
</code>```

function checks the value of input, hides an input, shows selected value in a div and brings to next step automatically(I don't have a next button).
This part works perfect.
Problem is: User can just navigate with tab, choose with down or up arrows and select with Enter keypress. I have a selected value in input but it doesn't bring me to next step because Click event wasn't fired. I tried to do something like below:

```<code>$( document ).on( "click, keypress",".optionDivSelected, .optionDiv",  function() {console.log('someone used keyboard')});
</code>```

but no luck. (I don't know if it's even possible to have multiple event handler)

How do I detect if user inserted value using Enter keypress and do my staff after.
it also creates me a problem when I validate input onchange. input wants to be typed not just inserted via click or enter keypress.

Please help me with this.

I can't show whole code. because it has a lot of backend staff mixed.
I'll include steps I am trying to achieve.

I start typing and I see a list:

I click one of option and I move to next step:

But when I select by hitting ENTER(or return) I just see input tag with selected option, no div with selected operator no next step. Just like below:

Update:

Below is my workaround and is not a question:
in combination of Aswin Ramesh's comment, alpeshandya and Vikash Mishra's answer I came up with this code and it does what I was expecting. and Most alpeshandya's answer helped me. Thank you guys.
And BTW If you see that I am somehow spagettiing the code, PLS let me know.:-)

```<code>     var ajaxHandler = function(){
    // $( document ).on( "click",".optionDivSelected, .optionDiv",  function() {
         if($('.operator').val().length > 0){
            $('.operator-li').next().addClass('active');
            $( '.operator-li' ).find('span').addClass('hidden');
            $('.operator-value').show();
            $('.operator-value h1 span').html($('.operator').val());
            $('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
         }
    // });
    console.log('ajaxhandler')
 };

 $( document ).on( "click",".optionDivSelected, .optionDiv",  ajaxHandler)
 $('.operator').on('keyup', function(event) {
    if(event.which == 13) {
          console.log("enter");
          event.preventDefault();
          ajaxHandler();
      }
});
</code>```

答:
You will need to create a generic event handler function which can be used as handler for click as well as for key press. This should work for your usecase:

var eventHandler=function(){
 if($('.operator').val().length > 0){
        $('.operator-li').next().addClass('active');
        $( '.operator-li' ).find('span').addClass('hidden');
        $('.operator-value').show();
        $('.operator-value h1 span').html($('.operator').val());
        $('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
     }
}

$( document ).on( "click",".optionDivSelected, .optionDiv",  eventHandler)
$( document ).on( "keypress",".optionDivSelected, .optionDiv",  function(event){
 if(event.which == 13) {
          eventHandler();
      }
})```

Here is plunker for demo:
demo

Body:
I have an input tag

<input type="text" name="cOperator"  class="form-control scale-input operator"  placeholder="Enter your ID" autocomplete="off"  onkeyup="ajax_showOptions(this,'getEmp',event)" required>

So when I start typing in, it shows employee list. And I have a jQuery function that handles click event.

$( document ).on( "click",".optionDivSelected, .optionDiv",  function() {
     if($('.operator').val().length > 0){
        $('.operator-li').next().addClass('active');
        $( '.operator-li' ).find('span').addClass('hidden');
        $('.operator-value').show();
        $('.operator-value h1 span').html($('.operator').val());
        $('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
     }
});

function checks the value of input, hides an input, shows selected value in a div and brings to next step automatically(I don't have a next button).
This part works perfect.
Problem is: User can just navigate with tab, choose with down or up arrows and select with Enter keypress. I have a selected value in input but it doesn't bring me to next step because Click event wasn't fired. I tried to do something like below:

$( document ).on( "click, keypress",".optionDivSelected, .optionDiv",  function() {console.log('someone used keyboard')});

but no luck. (I don't know if it's even possible to have multiple event handler)

How do I detect if user inserted value using Enter keypress and do my staff after.
it also creates me a problem when I validate input onchange. input wants to be typed not just inserted via click or enter keypress.

Please help me with this.

I can't show whole code. because it has a lot of backend staff mixed.
I'll include steps I am trying to achieve.

I start typing and I see a list:

I click one of option and I move to next step:

But when I select by hitting ENTER(or return) I just see input tag with selected option, no div with selected operator no next step. Just like below:

Update:

Below is my workaround and is not a question:
in combination of Aswin Ramesh's comment, alpeshandya and Vikash Mishra's answer I came up with this code and it does what I was expecting. and Most alpeshandya's answer helped me. Thank you guys.
And BTW If you see that I am somehow spagettiing the code, PLS let me know.:-)

     var ajaxHandler = function(){
    // $( document ).on( "click",".optionDivSelected, .optionDiv",  function() {
         if($('.operator').val().length > 0){
            $('.operator-li').next().addClass('active');
            $( '.operator-li' ).find('span').addClass('hidden');
            $('.operator-value').show();
            $('.operator-value h1 span').html($('.operator').val());
            $('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
         }
    // });
    console.log('ajaxhandler')
 };

 $( document ).on( "click",".optionDivSelected, .optionDiv",  ajaxHandler)
 $('.operator').on('keyup', function(event) {
    if(event.which == 13) {
          console.log("enter");
          event.preventDefault();
          ajaxHandler();
      }
});

Body:
You will need to create a generic event handler function which can be used as handler for click as well as for key press. This should work for your usecase:

var eventHandler=function(){
 if($('.operator').val().length > 0){
        $('.operator-li').next().addClass('active');
        $( '.operator-li' ).find('span').addClass('hidden');
        $('.operator-value').show();
        $('.operator-value h1 span').html($('.operator').val());
        $('.operator').parents('label').hide().parents('.fieldset').next().fadeIn();
     }
}

$( document ).on( "click",".optionDivSelected, .optionDiv",  eventHandler)
$( document ).on( "keypress",".optionDivSelected, .optionDiv",  function(event){
 if(event.which == 13) {
          eventHandler();
      }
})

Here is plunker for demo:
demo


问:
Issues with variables with html checkbox
I've got this code:

```<code><HTML>
<BODY>

<FORM action = "respuestas.php" METHOD "post">
1. ¿Cuál es la capital de México?<br>
<INPUT TYPE = "radio" VALUE="nayarit" CHECKED NAME = "capital">Nayarit<br>
<INPUT TYPE = "radio" VALUE="cdmx" NAME = "capital" >Ciudad de México<br>
<INPUT TYPE = "radio" VALUE="yucatan" NAME = "capital">Yucatán<br>

2. ¿Cuánto es 9 x 5?<br>
<INPUT TYPE = "radio" VALUE="catorce" CHECKED NAME = "operacion">14<br>
<INPUT TYPE = "radio" VALUE="setenta" NAME = "operacion">70<br>
<INPUT TYPE = "radio" VALUE="cuarentacinco" NAME = "operacion">45<br>

3. ¿Cuántos colores tiene un arcoiris?<br>
<INPUT TYPE = "radio" VALUE="siete" CHECKED NAME = "color">7<br>
<INPUT TYPE = "radio" VALUE="nueve" NAME = "color">9<br>
<INPUT TYPE = "radio" VALUE="ocho" NAME = "color">8<br>

<INPUT TYPE = "submit" VALUE = "Aceptar" NAME= "aceptar"/>
</FORM>

</BODY>
</HTML>
</code>```

And this PHP code:

```<code><?php

$capital= "";
$operacion = "";
$color = "";
   if($capital == "cdmx") {
       echo"Respuesta 1: Correcto!<br>";
   } else{
       echo"Respuesta 1: Incorrecto!<br>";
   }
   if($operacion == "cuarentacinco"){
       echo"Respuesta 2: Correcto!<br>";
   } else{
       echo"Respuesta 2: Incorrecto!<br>";
   }
       if($color == "siete"){
       echo"Respuesta 3: Correcto!<br>";
   } else{
       echo"Respuesta 3: Incorrecto!<br>";
   }

?>
</code>```

It is supposed to print "Respuesta 1: Correcto!" when you check te correct answer, but for the 3 echo's it writes the false way that is "Respuesta 1: Correcto!", I think that html isn't sending the variables that are checked to the php code, i assure myself that the PHP file is called "respuestas.php", so I don't know how to fix it.

Thanks.

答:
You have to get post values from $_POST array.</p>

```<code>$capital= $_POST['capital'];
$operacion = $_POST['operacion'];
$color = $_POST['color'];
</code>```

Body:
I've got this code:

<FORM action = "respuestas.php" METHOD "post">
1. ¿Cuál es la capital de México?

<INPUT TYPE = "radio" VALUE="nayarit" CHECKED NAME = "capital">Nayarit

<INPUT TYPE = "radio" VALUE="cdmx" NAME = "capital" >Ciudad de México

<INPUT TYPE = "radio" VALUE="yucatan" NAME = "capital">Yucatán

2. ¿Cuánto es 9 x 5?

<INPUT TYPE = "radio" VALUE="catorce" CHECKED NAME = "operacion">14

<INPUT TYPE = "radio" VALUE="setenta" NAME = "operacion">70

<INPUT TYPE = "radio" VALUE="cuarentacinco" NAME = "operacion">45

3. ¿Cuántos colores tiene un arcoiris?

<INPUT TYPE = "radio" VALUE="siete" CHECKED NAME = "color">7

<INPUT TYPE = "radio" VALUE="nueve" NAME = "color">9

<INPUT TYPE = "radio" VALUE="ocho" NAME = "color">8

<INPUT TYPE = "submit" VALUE = "Aceptar" NAME= "aceptar"/>
</FORM>

And this PHP code:

<?php

$capital= "";
$operacion = "";
$color = "";
   if($capital == "cdmx") {
       echo"Respuesta 1: Correcto!
";
   } else{
       echo"Respuesta 1: Incorrecto!
";
   }
   if($operacion == "cuarentacinco"){
       echo"Respuesta 2: Correcto!
";
   } else{
       echo"Respuesta 2: Incorrecto!
";
   }
       if($color == "siete"){
       echo"Respuesta 3: Correcto!
";
   } else{
       echo"Respuesta 3: Incorrecto!
";
   }

?>

It is supposed to print "Respuesta 1: Correcto!" when you check te correct answer, but for the 3 echo's it writes the false way that is "Respuesta 1: Correcto!", I think that html isn't sending the variables that are checked to the php code, i assure myself that the PHP file is called "respuestas.php", so I don't know how to fix it.

Thanks.

Body:
You have to get post values from $_POST array.

$capital= $_POST['capital'];
$operacion = $_POST['operacion'];
$color = $_POST['color'];


答:
"list" is a reserved keyword. DO NOT use it as a variable name, it will lead to erractic behavior.If you really want to be safe, you can do:</p>

```<code>if len(list1) == 1:
    max_item = list1[0]
print(max_item)
</code>```

Body:
I have a list that only has one item. I know this list only has one item because it is the output of a MySQL query that will always have just one result.

MySQL Query:

SELECT MAX(date) FROM db.table;

List result:

['20170307']

Now I must access the item in this list. I have two options:

1) By position

max_date = list[0]
print(max_date)

2) By iterating through item(s)

for item in list:
    max_date = item
print(max_date)

Can someone please explain which approach is more appropriate in terms performance, readability, and overall best practice? My IDE raises a red flag when I use approach #2 but is it safe to ignore if I'm confident my list will always have one item?

Body:
"list" is a reserved keyword. DO NOT use it as a variable name, it will lead to erractic behavior.If you really want to be safe, you can do:

if len(list1) == 1:
    max_item = list1[0]
print(max_item)


问:
appending array to FormData and send via AJAX
I'm using ajax to submit a multipart form with array, text fields and files.

I append each VAR to the main data as so

```<code>var attachments = document.getElementById('files');
var data= new FormData();

for (i=0; i< attachments.files.length; i++){
    data.append('file', attachments.files[i]);
    console.log(attachments.files[i]);

    data.append ('headline', headline);
    data.append ('article', article);
    data.append ('arr', arr);
    data.append ('tag', tag);
</code>```

then I use the ajax function to send it to a PHP file to store inside sql DB.

```<code>$.ajax({
    type: "post",
    url: 'php/submittionform.php',
    cache: false,
    processData: false,
    contentType: false,
    data: data,
    success: function(request) {$('#box').html(request); }
})
</code>```

But on the PHP side, the arr variable, which is an array appears as a string.

When I don't send it with ajax as Form data but use the simple $.POST option I do get it as an array on the PHP side, but then I can't send the files as well.

any solutions?

答:
This is an old question but I ran into this problem with posting objects along with files recently.  I needed to be able to post an object, with child properties that were objects and arrays as well.

The function below will walk through an object and create the correct formData object.

```<code>// formData - instance of FormData object
// data - object to post
function getFormData(formData, data, previousKey) {
  if (data instanceof Object) {
    Object.keys(data).forEach(key => {
      const value = data[key];
      if (value instanceof Object && !Array.isArray(value)) {
        return this.getFormData(formData, value, key);
      }
      if (previousKey) {
        key = `${previousKey}[${key}]`;
      }
      if (Array.isArray(value)) {
        value.forEach(val => {
          formData.append(`${key}[]`, val);
        });
      } else {
        formData.append(key, value);
      }
    });
  }
}
</code>```

This will convert the following json -

```<code>{
  name: 'starwars',
  year: 1977,
  characters: {
    good: ['luke', 'leia'],
    bad: ['vader'],
  },
}
</code>```

into the following FormData

```<code> name, starwars
 year, 1977
 characters[good][], luke
 characters[good][], leia
 characters[bad][], vader
</code>```

Body:
I'm using ajax to submit a multipart form with array, text fields and files.

I append each VAR to the main data as so

var attachments = document.getElementById('files');
var data= new FormData();

for (i=0; i< attachments.files.length; i++){
    data.append('file', attachments.files[i]);
    console.log(attachments.files[i]);

    data.append ('headline', headline);
    data.append ('article', article);
    data.append ('arr', arr);
    data.append ('tag', tag);

then I use the ajax function to send it to a PHP file to store inside sql DB.

$.ajax({
    type: "post",
    url: 'php/submittionform.php',
    cache: false,
    processData: false,
    contentType: false,
    data: data,
    success: function(request) {$('#box').html(request); }
})

But on the PHP side, the arr variable, which is an array appears as a string.

When I don't send it with ajax as Form data but use the simple $.POST option I do get it as an array on the PHP side, but then I can't send the files as well.

any solutions?

Body:
This is an old question but I ran into this problem with posting objects along with files recently.  I needed to be able to post an object, with child properties that were objects and arrays as well.

The function below will walk through an object and create the correct formData object.

// formData - instance of FormData object
// data - object to post
function getFormData(formData, data, previousKey) {
  if (data instanceof Object) {
    Object.keys(data).forEach(key => {
      const value = data[key];
      if (value instanceof Object && !Array.isArray(value)) {
        return this.getFormData(formData, value, key);
      }
      if (previousKey) {
        key = `${previousKey}[${key}]`;
      }
      if (Array.isArray(value)) {
        value.forEach(val => {
          formData.append(`${key}[]`, val);
        });
      } else {
        formData.append(key, value);
      }
    });
  }
}

This will convert the following json -

{
  name: 'starwars',
  year: 1977,
  characters: {
    good: ['luke', 'leia'],
    bad: ['vader'],
  },
}

into the following FormData

 name, starwars
 year, 1977
 characters[good][], luke
 characters[good][], leia
 characters[bad][], vader


问:
Reliable File.renameTo() alternative on Windows?
Java's File.renameTo() is problematic, especially on Windows, it seems.
As the API documentation says,

Many aspects of the behavior of this
  method are inherently
  platform-dependent: The rename
  operation might not be able to move a
  file from one filesystem to another,
  it might not be atomic, and it might
  not succeed if a file with the
  destination abstract pathname already
  exists. The return value should always
  be checked to make sure that the
  rename operation was successful.

In my case, as part of an upgrade procedure, I need to move (rename) a directory that may contain gigabytes of data (lots of subdirectories and files of varying sizes). The move is always done within the same partition/drive, so there's no real need to physically move all the files on disk.

There shouldn't be any file locks to the contents of the dir to be moved, but still, quite often, renameTo() fails to do its job and returns false. (I'm just guessing that perhaps some file locks expire somewhat arbitrarily on Windows.)

Currently I have a fallback method that uses copying & deleting, but this sucks because it may take a lot of time, depending on the size of the folder. I'm also considering simply documenting the fact that the user can move the folder manually to avoid waiting for hours, potentially. But the Right Way would obviously be something automatic and quick.

So my question is, do you know an alternative, reliable approach to do a quick move/rename with Java on Windows, either with plain JDK or some external library. Or if you know an easy way to detect and release any file locks for a given folder and all of its contents (possibly thousands of individual files), that would be fine too.

Edit: In this particular case, it seems we got away using just renameTo() by taking a few more things into account; see this answer.

答:
I know this seems a little hacky, but for what I've been needing it for, it seems buffered readers and writers have no issue making the files.

```<code>void renameFiles(String oldName, String newName)
{
    String sCurrentLine = "";

    try
    {
        BufferedReader br = new BufferedReader(new FileReader(oldName));
        BufferedWriter bw = new BufferedWriter(new FileWriter(newName));

        while ((sCurrentLine = br.readLine()) != null)
        {
            bw.write(sCurrentLine);
            bw.newLine();
        }

        br.close();
        bw.close();

        File org = new File(oldName);
        org.delete();

    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

}
</code>```

Works well for small text files as part of a parser, just make sure oldName and newName are full paths to the file locations.

Cheers
Kactus

Body:
I know this seems a little hacky, but for what I've been needing it for, it seems buffered readers and writers have no issue making the files.

void renameFiles(String oldName, String newName)
{
    String sCurrentLine = "";

    try
    {
        BufferedReader br = new BufferedReader(new FileReader(oldName));
        BufferedWriter bw = new BufferedWriter(new FileWriter(newName));

        while ((sCurrentLine = br.readLine()) != null)
        {
            bw.write(sCurrentLine);
            bw.newLine();
        }

        br.close();
        bw.close();

        File org = new File(oldName);
        org.delete();

    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

}

Works well for small text files as part of a parser, just make sure oldName and newName are full paths to the file locations.

Cheers
Kactus


问:
Bind on C++/CLI delegate in Javascript (WinJS)
I am building a Cordova application for all major operating systems (iOS, macOS, Android and Windows).

I wrote a native Plugin (WinRT) in C++/CLI to call some native functions, this Plugin uses delegates to asynchronously give back results.

I also wrote a test application in C# that allows me to easily test the C++/CLI code without having to compile the whole Cordova project.
I am able to bind to the C++/CLI delegate without any issue in C#, but I am not able to do so in Javascript.

C# Way (Works like a charm):

```<code>myCppClass.log += (string logString) =>
                    {
                        Debug.WriteLine(logString);
                    };
</code>```

Javascript Way (Does not work at all):

```<code>myCppClass.addEventListener("log", function (msg) {
                console.log(msg);
            });
</code>```

I got the Javascript way from: https://msdn.microsoft.com/en-us/library/hh779077.aspx

Does anyone know how to bind to C++/CLI delegates in Javascript?

Thanks

答:
Take a look once again on the https://msdn.microsoft.com/en-us/library/hh779077.aspx#Anchor_4 sample.

Have you tried this way?

```<code>var instance = new MyCppClass();
instance.addEventListener("log", function (e) {
   console.log(e.msg);
});
</code>```

Body:
I am building a Cordova application for all major operating systems (iOS, macOS, Android and Windows).

I wrote a native Plugin (WinRT) in C++/CLI to call some native functions, this Plugin uses delegates to asynchronously give back results.

I also wrote a test application in C# that allows me to easily test the C++/CLI code without having to compile the whole Cordova project.
I am able to bind to the C++/CLI delegate without any issue in C#, but I am not able to do so in Javascript.

C# Way (Works like a charm):

myCppClass.log += (string logString) =>
                    {
                        Debug.WriteLine(logString);
                    };

Javascript Way (Does not work at all):

myCppClass.addEventListener("log", function (msg) {
                console.log(msg);
            });

I got the Javascript way from: https://msdn.microsoft.com/en-us/library/hh779077.aspx

Does anyone know how to bind to C++/CLI delegates in Javascript?

Thanks

Body:
Take a look once again on the https://msdn.microsoft.com/en-us/library/hh779077.aspx#Anchor_4 sample.

Have you tried this way?

var instance = new MyCppClass();
instance.addEventListener("log", function (e) {
   console.log(e.msg);
});


问:
Element 'script' cannot be nested inside element html
I'm making a flask application and just stuffed it all into a Visual Studio pyproj file and am just reviewing all the edit suggestions the IDE is proposing. One of them is where I put the

答: It should be inside body tag. So move one line up.


问:
Making a visual grid on a Frame in tkinter
I'm tring to create 3 Frames (right, center, left) in the root in tkinter 8.6
and then making a visual grid ( using "-") in each frame. I get the following error message when I try to make the grid on the first panel.

TypeError: grid_configure() takes at least 1 argument (0 given).

Here is my code:

```<code>from tkinter import *

root = Tk()
root.geometry("1366x768")

frame_right = Frame(root,width = 1366/4,height = 768bg = "powder blue")
frame_right.pack(side = LEFT)

frame_center = Frame(root,width = 1366/2,height = 768,bg = "red")
frame_center.pack(side = LEFT)

frame_left = Frame(root,width = 1366/4,height = 768,bg = "steel blue")
frame_center.pack(side = LEFT)

for i in range(0,10):
    for j in range(0,20):

        Label(frame_left,text = "-",width = 10,height = 1)
        Label.grid(row = i,column = j)

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

答:
With Label(parent, {some arguments}), you create an instance on the first line, on the second you create an instance with no parent.

Must be change:

```<code>Label(frame_left,text = "-",width = 10,height = 1)
Label.grid(row = i,column = j)
</code>```

to:

```<code>label = Label(frame_left,text = "-",width = 10,height = 1)
label.grid(row = i,column = j)
</code>```

or:

```<code>Label(frame_left,text = "-",width = 10,height = 1).grid(row = i,column = j)
</code>```

Body:
I'm tring to create 3 Frames (right, center, left) in the root in tkinter 8.6
and then making a visual grid ( using "-") in each frame. I get the following error message when I try to make the grid on the first panel.

TypeError: grid_configure() takes at least 1 argument (0 given).

Here is my code:

from tkinter import *

root = Tk()
root.geometry("1366x768")

frame_right = Frame(root,width = 1366/4,height = 768bg = "powder blue")
frame_right.pack(side = LEFT)

frame_center = Frame(root,width = 1366/2,height = 768,bg = "red")
frame_center.pack(side = LEFT)

frame_left = Frame(root,width = 1366/4,height = 768,bg = "steel blue")
frame_center.pack(side = LEFT)

for i in range(0,10):
    for j in range(0,20):

        Label(frame_left,text = "-",width = 10,height = 1)
        Label.grid(row = i,column = j)

root.mainloop()

Body:
With Label(parent, {some arguments}), you create an instance on the first line, on the second you create an instance with no parent.

Must be change:

Label(frame_left,text = "-",width = 10,height = 1)
Label.grid(row = i,column = j)

to:

label = Label(frame_left,text = "-",width = 10,height = 1)
label.grid(row = i,column = j)

or:

Label(frame_left,text = "-",width = 10,height = 1).grid(row = i,column = j)