问:
Exporting JTable to txt file
Interesting little error here, hopefully someone can point out what's happening to me.

My program is able to write to a text file if there's approximately 4 or less entries in the JTable.  Once there's more than that it fails and throws an exception that pops up my catch block.  Not sure what's happening.

```<code>public void actionPerformed(ActionEvent e)
    {
        try
        {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("payrollData.txt"));
            PrintWriter fileWriter = new PrintWriter(bufferedWriter);

            for(int i = 0; i < outputTable.getRowCount()+1; i++)
            {
                String headers = String.valueOf(outputTable.getColumnName(i));
                fileWriter.print(headers);
                fileWriter.print("\t");
            }

            fileWriter.println("");
            for(int i=0; i<model.getRowCount(); ++i)
            {
                for(int j=0; j<model.getColumnCount(); ++j)
                {
                    String s = model.getValueAt(i,j).toString();
                    fileWriter.print(s);
                    fileWriter.print("\t\t");
                }
                fileWriter.println("");
            }
            fileWriter.close();
            JOptionPane.showMessageDialog(null, "Success. File saved to payrollData.txt");
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Failure");
        }
</code>```

edit: added ex.printStackTrace(); and it shows an array index out of bounds exception

答:
So, having a look at this...

```<code>for(int i = 0; i < outputTable.getRowCount()+1; i++)
{
    String headers = String.valueOf(outputTable.getColumnName(i));
    fileWriter.print(headers);
    fileWriter.print("\t");
}
</code>```

I'm left wondering what getRowCount has to do with the number of columns ... pherhaps you meant getColumnCount ... which would means you could also get rid of the +1

Observations...

Having spent some time running over the code, there are a couple of other minor observations I can make.

First, I'd highly encourage the use of The try-with-resources Statement, this will allow you to better manage your resources.

I'd also suggest using StringJoiner to generate each line, it's simpler then trying to check if you're writing out the last column or not and allows you supply what ever delimiter you want to use

As an example...

```<code>DefaultTableModel model = new DefaultTableModel();
model.addColumn("Purpose");
model.addColumn("Name");
model.addColumn("Composition");
model.addColumn("Expiry");
model.addColumn("Stock");
model.addColumn("Cost");
model.addColumn("Type");
model.addColumn("Supplier");
model.addColumn("Supplier Number");
model.addColumn("Rack");

for (int index = 0; index < 10; index++) {

    Vector vector = new Vector();
    vector.add("p" + index);
    vector.add("n" + index);
    vector.add("c" + index);
    vector.add("e" + index);
    vector.add("s" + index);
    vector.add("c" + index);
    vector.add("t" + index);
    vector.add("s" + index);
    vector.add("s" + index);
    vector.add("r" + index);

    model.addRow(vector);

}

JTable table = new JTable(model);

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Test.txt")))) {
    StringJoiner joiner = new StringJoiner(",");
    for (int col = 0; col < table.getColumnCount(); col++) {
        joiner.add(table.getColumnName(col));
    }
    System.out.println(joiner.toString());
    bw.write(joiner.toString());
    bw.newLine();
    for (int row = 0; row < table.getRowCount(); row++) {
        joiner = new StringJoiner(",");
        for (int col = 0; col < table.getColumnCount(); col++) {
            Object obj = table.getValueAt(row, col);
            String value = obj == null ? "null" : obj.toString();
            joiner.add(value);
        }
        System.out.println(joiner.toString());
        bw.write(joiner.toString());
        bw.newLine();
    }
} catch (IOException exp) {
    exp.printStackTrace();
}
</code>```

Title: Exporting JTable to txt file

Body:
Interesting little error here, hopefully someone can point out what's happening to me.

My program is able to write to a text file if there's approximately 4 or less entries in the JTable.  Once there's more than that it fails and throws an exception that pops up my catch block.  Not sure what's happening.

public void actionPerformed(ActionEvent e)
    {
        try
        {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("payrollData.txt"));
            PrintWriter fileWriter = new PrintWriter(bufferedWriter);

            for(int i = 0; i < outputTable.getRowCount()+1; i++)
            {
                String headers = String.valueOf(outputTable.getColumnName(i));
                fileWriter.print(headers);
                fileWriter.print("\t");
            }

            fileWriter.println("");
            for(int i=0; i<model.getRowCount(); ++i)
            {
                for(int j=0; j<model.getColumnCount(); ++j)
                {
                    String s = model.getValueAt(i,j).toString();
                    fileWriter.print(s);
                    fileWriter.print("\t\t");
                }
                fileWriter.println("");
            }
            fileWriter.close();
            JOptionPane.showMessageDialog(null, "Success. File saved to payrollData.txt");
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Failure");
        }

edit: added ex.printStackTrace(); and it shows an array index out of bounds exception

Body:
So, having a look at this...

for(int i = 0; i < outputTable.getRowCount()+1; i++)
{
    String headers = String.valueOf(outputTable.getColumnName(i));
    fileWriter.print(headers);
    fileWriter.print("\t");
}

I'm left wondering what getRowCount has to do with the number of columns ... pherhaps you meant getColumnCount ... which would means you could also get rid of the +1

Observations...

Having spent some time running over the code, there are a couple of other minor observations I can make.

First, I'd highly encourage the use of The try-with-resources Statement, this will allow you to better manage your resources.

I'd also suggest using StringJoiner to generate each line, it's simpler then trying to check if you're writing out the last column or not and allows you supply what ever delimiter you want to use

As an example...

DefaultTableModel model = new DefaultTableModel();
model.addColumn("Purpose");
model.addColumn("Name");
model.addColumn("Composition");
model.addColumn("Expiry");
model.addColumn("Stock");
model.addColumn("Cost");
model.addColumn("Type");
model.addColumn("Supplier");
model.addColumn("Supplier Number");
model.addColumn("Rack");

for (int index = 0; index < 10; index++) {

    Vector vector = new Vector();
    vector.add("p" + index);
    vector.add("n" + index);
    vector.add("c" + index);
    vector.add("e" + index);
    vector.add("s" + index);
    vector.add("c" + index);
    vector.add("t" + index);
    vector.add("s" + index);
    vector.add("s" + index);
    vector.add("r" + index);

    model.addRow(vector);

}

JTable table = new JTable(model);

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Test.txt")))) {
    StringJoiner joiner = new StringJoiner(",");
    for (int col = 0; col < table.getColumnCount(); col++) {
        joiner.add(table.getColumnName(col));
    }
    System.out.println(joiner.toString());
    bw.write(joiner.toString());
    bw.newLine();
    for (int row = 0; row < table.getRowCount(); row++) {
        joiner = new StringJoiner(",");
        for (int col = 0; col < table.getColumnCount(); col++) {
            Object obj = table.getValueAt(row, col);
            String value = obj == null ? "null" : obj.toString();
            joiner.add(value);
        }
        System.out.println(joiner.toString());
        bw.write(joiner.toString());
        bw.newLine();
    }
} catch (IOException exp) {
    exp.printStackTrace();
}


来源: stackexchange

问:
Firebase 3.0 + Ember 2.0: The Torii adapter must implement `open` for a session to be opened
I'm having an issue with facebook authentication with the torii adapter, the error being: 'The Torii adapter must implement open for a session to be opened'.

I've visited many tutorials, and tried all presented methods, but most of them are usually old ember code and none of them seem to actually work.

Current state: I am able to login, I get the facebook popup and I can authorize.

Using fiddler, I can also see the response from the API containing a JSON response with all credentials from the user I authenticated with.
In the firebase console, I can see the authorized user, reset its password, deny access,...

All this leads me to believe that it's 'merely' a front-end issue where I can't seem to establish a proper 'session' to work with.

My end goal would be to pick up the relevant user data and transfer it to my firebase backend as a 'user' entry, allowing for quick registration for site visitors, but I'll be more than glad to have an active session so I can work out the rest on my own.

As a front-end rookie (I normally code C#), Ember may not have been the best choice to get the hang it, but I'm this far now, I'm not about to let it all slide and pick up a different framework.

My code:

config/environment.js

```<code>firebase: {
    apiKey: 'xxxxxxx',
    authDomain: 'myappname.firebaseapp.com',
    databaseURL: 'https://myappname.firebaseio.com',
    storageBucket: 'myappname.appspot.com',
    messagingSenderId: '1234567890'
  },

    torii: {
      sessionServiceName: 'session'
    }
</code>```

torii-adapters/application.js (I've changed this so much, I can't even remember what the original code was, because none of what I change/add/delete here seems to do anything at all.)

```<code>import Ember from 'ember';
import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';

export default ToriiFirebaseAdapter.extend({
  firebase: Ember.inject.service(),
});
</code>```

routes/application.js

```<code>import Ember from 'ember';

export default Ember.Route.extend({
    beforeModel: function() {
    return this.get('session').fetch().catch(function() {
    });
  },

  actions:{

    login: function(provider) {
      this.get('session').open('firebase', {
        provider: provider,
      }).then(function(data) {
        console.log(data.currentUser);
      });
    },

    logout: function() {
      this.get('session').close().then(function() {
        this.transitionTo('application');
      }.bind(this));
    }
  }
});
</code>```

application.hbs

```<code><div class="container">
  {{partial 'navbar'}}
<a {{action "signIn" "facebook"}} class="btn">{{fa-icon "facebook"}}</a>
<a {{action "signIn" "twitter"}} class="btn">{{fa-icon "twitter"}}</a>
<a {{action "signIn" "github"}} class="btn">{{fa-icon "github"}}</a>
<a {{action "signIn" "google"}} class="btn">{{fa-icon "google"}}</a>
  {{outlet}}
</div>
</code>```

EDIT 1

Above code is giving me alot more errors after restarting ember server. Is this the cause of my troubles ? All the changes that seemingly didn't change a thing, weren't registered until after a server restart ? If that's the case, I may have passed the correct solution about a hundred times already...

EDIT 2

Changed the code to reflect the actual issue. The previous code was screwed beyond measure, but I never realized it because it didn't pick up until after a server restart.

EDIT 3
Found and tried this, to no avail: https://stackoverflow.com/a/32079863/4309050

答:
NOTE: for Ember 3.16+ apps, here is the same code, but with updated syntax / patterns: https://stackoverflow.com/a/62500685/356849

The below is for Ember < 3.16, even though the code would work as 3.16+ as fully backwards compatible, but it's not always fun to write older code.

Try to inject service inside your application route and move the beforeModel outside of the actions hash,

```<code>// Inside routes/application.js

export default Ember.Route.extend({
  session: Ember.inject.service(), // (1)

  beforeModel: function() {
    return this.get('session').fetch().catch(function() {});
  },

  actions:{
    login: function(provider) {
      this.get('session').open('firebase', {
        provider: provider,
      }).then(function(data) {
        console.log(data.currentUser);
      });
    },

    logout: function() {
      this.get('session').close().then(function() {
        this.transitionTo('application');
      }.bind(this));
    }
  }
});
</code>```

I have completed the same thing (Firebase Torii Auth) yesterday, try to follow the guide carefully. The only thing missing from the guide is to inject session service manually.

Still remember the session you declared inside environment.js file? You have to inject it to make it available

```<code>session: Ember.inject.service(), // (1)
</code>```

https://github.com/firebase/emberfire/blob/master/docs/guide/authentication.md

Inside my ToriiFirebaesAdapter,

```<code>import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';

export default ToriiFirebaseAdapter.extend({
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having an issue with facebook authentication with the torii adapter, the error being: 'The Torii adapter must implement open for a session to be opened'.

I've visited many tutorials, and tried all presented methods, but most of them are usually old ember code and none of them seem to actually work.

Current state: I am able to login, I get the facebook popup and I can authorize.

Using fiddler, I can also see the response from the API containing a JSON response with all credentials from the user I authenticated with.
In the firebase console, I can see the authorized user, reset its password, deny access,...

All this leads me to believe that it's 'merely' a front-end issue where I can't seem to establish a proper 'session' to work with.

My end goal would be to pick up the relevant user data and transfer it to my firebase backend as a 'user' entry, allowing for quick registration for site visitors, but I'll be more than glad to have an active session so I can work out the rest on my own.

As a front-end rookie (I normally code C#), Ember may not have been the best choice to get the hang it, but I'm this far now, I'm not about to let it all slide and pick up a different framework.

My code:

config/environment.js

firebase: {
    apiKey: 'xxxxxxx',
    authDomain: 'myappname.firebaseapp.com',
    databaseURL: 'https://myappname.firebaseio.com',
    storageBucket: 'myappname.appspot.com',
    messagingSenderId: '1234567890'
  },

    torii: {
      sessionServiceName: 'session'
    }

torii-adapters/application.js (I've changed this so much, I can't even remember what the original code was, because none of what I change/add/delete here seems to do anything at all.)

import Ember from 'ember';
import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';

export default ToriiFirebaseAdapter.extend({
  firebase: Ember.inject.service(),
});

routes/application.js

import Ember from 'ember';

export default Ember.Route.extend({
    beforeModel: function() {
    return this.get('session').fetch().catch(function() {
    });
  },

  actions:{

    login: function(provider) {
      this.get('session').open('firebase', {
        provider: provider,
      }).then(function(data) {
        console.log(data.currentUser);
      });
    },

    logout: function() {
      this.get('session').close().then(function() {
        this.transitionTo('application');
      }.bind(this));
    }
  }
});

application.hbs

  {{partial 'navbar'}}
{{fa-icon "facebook"}}
{{fa-icon "twitter"}}
{{fa-icon "github"}}
{{fa-icon "google"}}
  {{outlet}}

EDIT 1

Above code is giving me alot more errors after restarting ember server. Is this the cause of my troubles ? All the changes that seemingly didn't change a thing, weren't registered until after a server restart ? If that's the case, I may have passed the correct solution about a hundred times already...

EDIT 2

Changed the code to reflect the actual issue. The previous code was screwed beyond measure, but I never realized it because it didn't pick up until after a server restart.

EDIT 3
Found and tried this, to no avail: https://stackoverflow.com/a/32079863/4309050

Body:
NOTE: for Ember 3.16+ apps, here is the same code, but with updated syntax / patterns: https://stackoverflow.com/a/62500685/356849

The below is for Ember < 3.16, even though the code would work as 3.16+ as fully backwards compatible, but it's not always fun to write older code.

Try to inject service inside your application route and move the beforeModel outside of the actions hash,

// Inside routes/application.js

export default Ember.Route.extend({
  session: Ember.inject.service(), // (1)

  beforeModel: function() {
    return this.get('session').fetch().catch(function() {});
  },

  actions:{
    login: function(provider) {
      this.get('session').open('firebase', {
        provider: provider,
      }).then(function(data) {
        console.log(data.currentUser);
      });
    },

    logout: function() {
      this.get('session').close().then(function() {
        this.transitionTo('application');
      }.bind(this));
    }
  }
});

I have completed the same thing (Firebase Torii Auth) yesterday, try to follow the guide carefully. The only thing missing from the guide is to inject session service manually.

Still remember the session you declared inside environment.js file? You have to inject it to make it available

session: Ember.inject.service(), // (1)

https://github.com/firebase/emberfire/blob/master/docs/guide/authentication.md

Inside my ToriiFirebaesAdapter,

import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';

export default ToriiFirebaseAdapter.extend({
});

ContentLicense: CC BY-SA 4.0


问:
Arquillian test under security manager throws NoSuchElementException
I have a WildFly 10.1 environment where I am starting the container using the following config:

```<code><container qualifier="container.active-1" mode="suite" default="true">
    <configuration>
        <property name="jbossHome">${wildFlyInstallDir}</property>
        <property name="jbossArguments">-secmgr</property>
        <property name="javaVmArguments">
            -Djava.net.preferIPv4Stack=true
            -Djgroups.bind_addr=127.0.0.1
            -Djboss.socket.binding.port-offset=137
            -Djava.security.policy=./arquillian.policy
        </property>
    </configuration>
</container>
</code>```

When I do not specify the -secmgr argument, the instance starts and the test is executed just fine; however when I use the security management argument to trigger using the security manager, I get the following exception:

```
java.util.NoSuchElementException
    at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:713)
    at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:734)
    at org.jboss.arquillian.container.test.spi.util.TestRunners.getTestRunner(TestRunners.java:60)
    at org.jboss.arquillian.container.test.spi.util.TestRunners.getTestRunner(TestRunners.java:44)
    at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.executeTest(ServletTestRunner.java:169)
    at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.execute(ServletTestRunner.java:135)
    at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.doGet(ServletTestRunner.java:98)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1$1.run(ServletInitialHandler.java:110)
    at java.security.AccessController.doPrivileged(Native Method)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:107)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
```

I need to execute my Arquillian test case using the security manager and I'm not clear what I could have missed as a part of my configuration.

The pertinent gradle libraries are:

```<code>org.jboss.arquillian.junit:arquillian-junit-container:1.1.12.Final
org.jboss.arquillian.protocol:arquillian-protocol-servlet:1.1.12.Final
org.wildfly.arquillian:wildfly-arquillian-container-managed:2.0.0.Final
</code>```

答: The problem is because the ShrinkWrap deployment was not including a permissions.xml file and thus the exception was being thrown.   Once I added that file, things worked.

Body:
I have a WildFly 10.1 environment where I am starting the container using the following config:

<container qualifier="container.active-1" mode="suite" default="true">
    <configuration>
        <property name="jbossHome">${wildFlyInstallDir}</property>
        <property name="jbossArguments">-secmgr</property>
        <property name="javaVmArguments">
            -Djava.net.preferIPv4Stack=true
            -Djgroups.bind_addr=127.0.0.1
            -Djboss.socket.binding.port-offset=137
            -Djava.security.policy=./arquillian.policy
        </property>
    </configuration>
</container>

When I do not specify the -secmgr argument, the instance starts and the test is executed just fine; however when I use the security management argument to trigger using the security manager, I get the following exception:

java.util.NoSuchElementException
    at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:713)
    at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:734)
    at org.jboss.arquillian.container.test.spi.util.TestRunners.getTestRunner(TestRunners.java:60)
    at org.jboss.arquillian.container.test.spi.util.TestRunners.getTestRunner(TestRunners.java:44)
    at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.executeTest(ServletTestRunner.java:169)
    at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.execute(ServletTestRunner.java:135)
    at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.doGet(ServletTestRunner.java:98)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1$1.run(ServletInitialHandler.java:110)
    at java.security.AccessController.doPrivileged(Native Method)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:107)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I need to execute my Arquillian test case using the security manager and I'm not clear what I could have missed as a part of my configuration.

The pertinent gradle libraries are:

org.jboss.arquillian.junit:arquillian-junit-container:1.1.12.Final
org.jboss.arquillian.protocol:arquillian-protocol-servlet:1.1.12.Final
org.wildfly.arquillian:wildfly-arquillian-container-managed:2.0.0.Final


问:
Node.js Lambda function returns "The response is invalid" back to Alexa Service Simulator from REST call
Having issues making a REST call to an API between a node.js Lambda function and Alexa. I'm using the request library to make the calls with an account linked skill. I've only set one sample utterance for the intent, and the simulator see this fine.

Also, the cloudwatch logs show a 200 response code from the api endpoint and any of the returned data from the API from console.logs to CW.

```<code>'use strict';
var http = require('http');
var request = require('request');
var Alexa = require('alexa-sdk');
var APP_ID = "amzn1.ask.skill.XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX";

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
   'LaunchRequest': function () {
        this.emit(':tell', 'Hi!');
   },

   'ApiWelcomeIntent': function () {
        request('https://some.web/api', function (error, response, body) {
            if (!error && response.statusCode == 200) {
            // from within the callback, write data to response, essentially returning it.
                var speechOutput = JSON.stringify(body);
                console.log(body + " :Raw output?");
                console.log(speechOutput + ' :JSON stringified');
                console.log(response.statusCode);
                this.emit(':tell', speechOutput);
            } else {
                console.log(error + ' : ' + response.statusCode);
                this.emit(':tell', 'There was an error');
            }
        });
    },

    'AMAZON.HelpIntent': function () {} //.........And other built in intents.

    }
};
</code>```

I'm guessing its something to do with the format of speechOutput that I'm asking Alexa to "emit/tell"?

答:
No, it has nothing to do with the format of speechOutput. The issue is that when the callback of the request method is executed, the reference to this is lost. To solve that, keep a reference to this before you call request (e.g. assign this to a variable called self):

```<code>'use strict';
var http = require('http');
var request = require('request');
var Alexa = require('alexa-sdk');
var APP_ID = "amzn1.ask.skill.XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX";

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
   'LaunchRequest': function () {
        this.emit(':tell', 'Hi!');
   },

   'ApiWelcomeIntent': function () {
        self = this

        request('https://some.web/api', function (error, response, body) {
            if (!error && response.statusCode == 200) {
            // from within the callback, write data to response, essentially returning it.
                var speechOutput = JSON.stringify(body);
                console.log(body + " :Raw output?");
                console.log(speechOutput + ' :JSON stringified');
                console.log(response.statusCode);
                self.emit(':tell', speechOutput); // USE SELF HERE
            } else {
                console.log(error + ' : ' + response.statusCode);
                self.emit(':tell', 'There was an error'); // AND HERE AS WELL
            }
        });
    },

    'AMAZON.HelpIntent': function () {} //.........And other built in intents.

    }
};
</code>```

Body:
Having issues making a REST call to an API between a node.js Lambda function and Alexa. I'm using the request library to make the calls with an account linked skill. I've only set one sample utterance for the intent, and the simulator see this fine.

Also, the cloudwatch logs show a 200 response code from the api endpoint and any of the returned data from the API from console.logs to CW.

'use strict';
var http = require('http');
var request = require('request');
var Alexa = require('alexa-sdk');
var APP_ID = "amzn1.ask.skill.XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX";

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
   'LaunchRequest': function () {
        this.emit(':tell', 'Hi!');
   },

   'ApiWelcomeIntent': function () {
        request('https://some.web/api', function (error, response, body) {
            if (!error && response.statusCode == 200) {
            // from within the callback, write data to response, essentially returning it.
                var speechOutput = JSON.stringify(body);
                console.log(body + " :Raw output?");
                console.log(speechOutput + ' :JSON stringified');
                console.log(response.statusCode);
                this.emit(':tell', speechOutput);
            } else {
                console.log(error + ' : ' + response.statusCode);
                this.emit(':tell', 'There was an error');
            }
        });
    },

    'AMAZON.HelpIntent': function () {} //.........And other built in intents.

    }
};

I'm guessing its something to do with the format of speechOutput that I'm asking Alexa to "emit/tell"?

Body:
No, it has nothing to do with the format of speechOutput. The issue is that when the callback of the request method is executed, the reference to this is lost. To solve that, keep a reference to this before you call request (e.g. assign this to a variable called self):

'use strict';
var http = require('http');
var request = require('request');
var Alexa = require('alexa-sdk');
var APP_ID = "amzn1.ask.skill.XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX";

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
   'LaunchRequest': function () {
        this.emit(':tell', 'Hi!');
   },

   'ApiWelcomeIntent': function () {
        self = this

        request('https://some.web/api', function (error, response, body) {
            if (!error && response.statusCode == 200) {
            // from within the callback, write data to response, essentially returning it.
                var speechOutput = JSON.stringify(body);
                console.log(body + " :Raw output?");
                console.log(speechOutput + ' :JSON stringified');
                console.log(response.statusCode);
                self.emit(':tell', speechOutput); // USE SELF HERE
            } else {
                console.log(error + ' : ' + response.statusCode);
                self.emit(':tell', 'There was an error'); // AND HERE AS WELL
            }
        });
    },

    'AMAZON.HelpIntent': function () {} //.........And other built in intents.

    }
};


问:
How best to compare to 0 in PHP?
In one bit of code I'm working on, I need to pull a value from the database and check if it is 0. Originally, I had written this as:

```<code>if ($myVal == 0) { ...
</code>```

But when I looked at it again today, I realised a bug there:

```<code>var_dump("foo" == 0);  // bool(true)

// and while we're here...
var_dump(intval("foo")); // int(0)
</code>```

Since this value is coming from the database, that usually means it will be a string, so I suppose I could do this:

```<code>if ($myVal === "0")
</code>```

but it seems counter-intuitive since I actually want to be dealing with an integer, and this would appear to show that we're working with strings. (I hope that makes sense to you.) Also, it shouldn't be unexpected that any given DB accessor would cast values to their appropriate type, given the field type.

What method do you use to check for a value of 0 when it could be a string or an int?

答:
```<code>if( ('integer' === gettype($is_anonymous) && $is_anonymous === 0 )
    ||
    ('string' === gettype($is_anonymous) && $is_anonymous === '0')
 ) {
    echo 'matches';
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How best to compare to 0 in PHP?

Body:
In one bit of code I'm working on, I need to pull a value from the database and check if it is 0. Originally, I had written this as:

if ($myVal == 0) { ...

But when I looked at it again today, I realised a bug there:

var_dump("foo" == 0);  // bool(true)

// and while we're here...
var_dump(intval("foo")); // int(0)

Since this value is coming from the database, that usually means it will be a string, so I suppose I could do this:

if ($myVal === "0")

but it seems counter-intuitive since I actually want to be dealing with an integer, and this would appear to show that we're working with strings. (I hope that makes sense to you.) Also, it shouldn't be unexpected that any given DB accessor would cast values to their appropriate type, given the field type.

What method do you use to check for a value of 0 when it could be a string or an int?


问:
Error while trying to self reference a model in ember.js
I'm trying to create a self-referenced property in a model, but I'm getting the following error:

Error while processing route: index No model was found for 'menu' Error

Here is my model (menus.js):

```<code>import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  link: DS.attr('string'),
  isActive: DS.attr('boolean'),
  children: DS.hasMany('menus', { inverse: null }),
});
</code>```

I'm trying to returning a list from a Web API. Here is my API JSON return:

```<code>[
  {
    "id": 1,
    "title": "Test",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 4,
        "title": "Test 2",
        "link": "index",
        "isActive": false
      }
    ]
  },
  {
    "id": 2,
    "title": "Test 2",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 5,
        "title": "Test 4 ",
        "link": "index",
        "isActive": false
      }
    ]
  },
  {
    "id": 3,
    "title": "Test 5",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 6,
        "title": "Test 6",
        "link": "index",
        "isActive": false
      },
      {
        "id": 7,
        "title": "Test 7",
        "link": "index",
        "isActive": false
      }
    ]
  }
]
</code>```

答: You should call your models in singular form. So rename model/menus.js to model/menu.js and DS.hasMany('menus', { inverse: null }), with DS.hasMany('menu', { inverse: null }),.

Body:
I'm trying to create a self-referenced property in a model, but I'm getting the following error:

Error while processing route: index No model was found for 'menu' Error

Here is my model (menus.js):

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  link: DS.attr('string'),
  isActive: DS.attr('boolean'),
  children: DS.hasMany('menus', { inverse: null }),
});

I'm trying to returning a list from a Web API. Here is my API JSON return:

[
  {
    "id": 1,
    "title": "Test",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 4,
        "title": "Test 2",
        "link": "index",
        "isActive": false
      }
    ]
  },
  {
    "id": 2,
    "title": "Test 2",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 5,
        "title": "Test 4 ",
        "link": "index",
        "isActive": false
      }
    ]
  },
  {
    "id": 3,
    "title": "Test 5",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 6,
        "title": "Test 6",
        "link": "index",
        "isActive": false
      },
      {
        "id": 7,
        "title": "Test 7",
        "link": "index",
        "isActive": false
      }
    ]
  }
]


问:
How to make a reverse string using a for loop?
I need to have my code output the String in reverse order. For example, the output should have "code" return as "edoc". This is what I have done so far.</p>

```<code>public String reverseString(String str) {
 String res = "";

for (int i = 0; i <= str.length()-1; i++) {
   res = res + str.charAt(i);
 }
  return res;
}
</code>```

答:
You have your concatenation backwards. Try:

```<code>public String reverseString(String str) {
    String res = "";
    for (int i = 0; i < str.length(); i++) {
       res = str.charAt(i) + res;            // Add each char to the *front*
    }
    return res;
}
</code>```

Note also the simpler, canonical, loop termination condition.

Body:
I need to have my code output the String in reverse order. For example, the output should have "code" return as "edoc". This is what I have done so far.

public String reverseString(String str) {
 String res = "";

for (int i = 0; i <= str.length()-1; i++) {
   res = res + str.charAt(i);
 }
  return res;
}

Body:
You have your concatenation backwards. Try:

public String reverseString(String str) {
    String res = "";
    for (int i = 0; i < str.length(); i++) {
       res = str.charAt(i) + res;            // Add each char to the *front*
    }
    return res;
}

Note also the simpler, canonical, loop termination condition.


问:
How can I embed YouTube videos as a custom playlist and make them play in a loop?
I'm trying to embed some YouTube videos in a website in a form of a playlist. I want them to play as a playlist, looping all the videos without waiting time in between.

So far I have this:

```<code><iframe src="https://www.youtube.com/embed/WTybilbbFqw?autoplay=1&loop=1&playlist=PMIhuOOMLXs,yV8qytGjsFc,WTybilbbFqw"></iframe>
</code>```

答:
You need to include rel=0 into the line.

Like this

```<code><iframe src="https://www.youtube.com/embed/WTybilbbFqw?autoplay=1&loop=1&rel=0&playlist=PMIhuOOMLXs,yV8qytGjsFc,WTybilbbFqw"></iframe>
</code>```

As a standard thing, the video will reset. If rel = 1 which is default, then the video is stopped/paused to display the related video list..

Body:
You need to include rel=0 into the line.

Like this

<iframe src="https://www.youtube.com/embed/WTybilbbFqw?autoplay=1&loop=1&rel=0&playlist=PMIhuOOMLXs,yV8qytGjsFc,WTybilbbFqw"></iframe>

As a standard thing, the video will reset. If rel = 1 which is default, then the video is stopped/paused to display the related video list..


问:
Smarty : evaluate a template stored in a PHP variable
i have a php variable which has html/smarty code in it

```<code>$x='<a href="{$link}" >{$title}</a>';
</code>```

This data is fetched from database , i want to evaluate it using smarty and put the output into a php variable (to print it out or to save it to the database again) .

Thanks

Edit :

i want the content of X to be evaluated using smarty , as if the content of x is stored in a file.tpl then $y=$smarty->fetch('file.tpl'); ... want to do it without the need to save the content of x into a file

答:
See "Example 15.9. Using custom resources" here:
http://www.smarty.net/docsv2/en/template.resources</p>

Body:
i have a php variable which has html/smarty code in it

$x='{$title}';

This data is fetched from database , i want to evaluate it using smarty and put the output into a php variable (to print it out or to save it to the database again) .

Thanks

Edit :

i want the content of X to be evaluated using smarty , as if the content of x is stored in a file.tpl then $y=$smarty->fetch('file.tpl'); ... want to do it without the need to save the content of x into a file


问:
Cache (potentially) changing values from the database in java
What is the current recommended approach for storing cached data in Java

I am looking for a particular approach that will update the cache when an insert or an update happens to particular table(s).

Ideally this should happen as quickly as possible so as to avoid any issues when cross referencing data.

Is there a technology that provides this (such as ehcache) or an advised programming standard which i could follow.

Thanks

答:
I will talk about Ehcache but there should be similar features in other caching framework.

It really depends on how transactional you need to be. Two features in Ehcache might help you.

XA to have Ehcache committing to the cache in the same transaction as your DB

Loader-writer. This will load the data from the database when the case is queried and write to the cache when writing to the database. So they both stay in sync

Of course, both can be used under Spring-Cache if needed.


问:
r Error: Don't know how to add o to a plot
I am trying to add arrow heads to a line created by geom_line() in ggplot.
Example:

```<code>library(grid)
library(ggplot2)
df <- data.frame(x=(1:2),y=(2:1))
ggplot(df,aes(x,y)) +
    geom_line() +
    arrow()
</code>```

The error I get is "Error: Don't know how to add o to a plot".

I found a variety of posts with this error, but they had a complex scenario and the answers called for making what looked like subtle changes in the code.

If instead I run:

```<code>ggplot(data=cinterval,aes(x=x,y=y))+
    geom_line()
</code>```

I get the expected line.
When I run the expanded code, with a more elaborate plot, I get the error
"Error in as.vector(y) : attempt to apply non-function"

答:
Do this instead</p>

```<code> library(grid)
library(ggplot2)
df <- data.frame(x=(1:2),y=(2:1))
ggplot(df,aes(x,y)) +
 geom_line(arrow = arrow(length=unit(0.30,"cm"), ends="first", type ="closed"))
</code>```

Body:
I am trying to add arrow heads to a line created by geom_line() in ggplot.
Example:

library(grid)
library(ggplot2)
df <- data.frame(x=(1:2),y=(2:1))
ggplot(df,aes(x,y)) +
    geom_line() +
    arrow()

The error I get is "Error: Don't know how to add o to a plot".

I found a variety of posts with this error, but they had a complex scenario and the answers called for making what looked like subtle changes in the code.

If instead I run:

ggplot(data=cinterval,aes(x=x,y=y))+
    geom_line()

I get the expected line.
When I run the expanded code, with a more elaborate plot, I get the error
"Error in as.vector(y) : attempt to apply non-function"

Body:
Do this instead

 library(grid)
library(ggplot2)
df <- data.frame(x=(1:2),y=(2:1))
ggplot(df,aes(x,y)) +
 geom_line(arrow = arrow(length=unit(0.30,"cm"), ends="first", type ="closed"))


问:
Kotlin - Function's Invoke Operator Overloading
I am currently studying Kotlin - Operator Overloading

I am trying to understand (with an example) how does operator overloading work for a function's invoke() function

The pre-test

Kotlin's Extension Functions

```<code>fun exampleOfExtensionFunction() {
    fun Int.randomize(): Int {
        return Random(this.toLong()).nextInt()
    }

    val randomizedFive = 5.randomize()
    println("$randomizedFive")
}
</code>```

Prints :

-1157408321

In Kotlin, functions can be declared as variables with types

```<code>fun exampleOfFunctionType() {
    val printNumber: (number: Int) -> Unit
    printNumber = { number ->
        println("[$number = ${number.toString(16).toUpperCase()} = ${number.toString(2)}]")
    }

    printNumber(1023)
}
</code>```

Prints :

[1023 = 3FF = 1111111111]

Kotlin allows operator overloading with both extension and member functions

```<code>fun exampleOfOperatorOverloadingUsingExtensionFunction() {
    class MyType() {
        val strings: ArrayList<String> = ArrayList<String>()
        override fun toString(): String {
            val joiner: StringJoiner = StringJoiner(" , ", "{ ", " }")
            for (string in strings) {
                joiner.add("\"$string\"")
            }
            return joiner.toString()
        }
    }

    operator fun MyType.contains(stringToCheck: String): Boolean {
        for (stringElement in strings) {
            if (stringElement == stringToCheck) return true
        }
        return false
    }

    val myType = MyType()
    myType.strings.add("one")
    myType.strings.add("two")
    myType.strings.add("three")
    println("$myType")
    println("(myType.contains(\"four\")) = ${myType.contains("four")} , (\"three\" in myType) = ${"three" in myType}")
}
</code>```

Prints :

{ "one" , "two" , "three" }

  (myType.contains("four")) = false , ("three" in myType) = true

Test Attempt

Based on the above. I tried to create an example of a function's invoke() operator overloading using the type (Boolean, Boolean, Boolean) -> Boolean as a receiver type for an extension function invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean). This however did not work as expected.

```<code>    fun attemptFunctionInvokeOperatorOverloading() {
        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }

        var func1: ((Boolean, Boolean, Boolean) -> Boolean) = { flag1, flag2, flag3 ->
            println("func1 body")
            flag1 && flag2 && flag3
        }

        fun func2(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("func2 body")
            return flag1 && flag2 && flag3
        }

        func1(true, true, false)
        func2(true, true, true)
    }
</code>```

Prints :

func1 body

  func2 body

Expected :

Overloaded invoke operator

  Overloaded invoke operator

Another question :

What exactly is this? (If it isn't operator overloading)

```<code>        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }
</code>```

答:
As said in another answer, invoke is defined on the function object itself, so you can't override it with an extension method.

I think the deeper problem here, though, is a slight misunderstanding of the purpose of this feature. Let's look at plus for the + operator instead.

I think you'll agree that attempting to define operator fun Int.plus(b: Int): Int { /* ... */} makes no sense, because overriding the default + operator for ints is a pretty dangerous thing to do, yes?

However, if you define a complex number class:

```<code>data class Complex(real: Double, img: Double)
</code>```

Then it's perfectly reasonable to define this to sum complex numbers:

```<code>operator fun Complex.plus(other: Complex): Complex {
  val real = this.real + other.real
  val img  = this.img + other.img
  return Complex(real, img)
}
</code>```

So, same thing with invoke and (): The meaning of () is that it's whatever is analogous to invoking a function for your type, and overriding invoke on something that's already a function is just asking for trouble. What you want to use it for instead is to provide function-like syntax for your own objects.

For example, imagine you define an interface like so:

```<code>interface MyCallback {
  fun call(ctx: MyContext)
}
</code>```

Which you use the usual way:

```<code>callback.call(ctx)
</code>```

But with an implementation of the invoke operator overload, you get to use it as a function:

```<code>operator fun MyCallback.invoke(ctx: Context) = this.call(ctx)

/* Elsewhere... */
callback(ctx)
</code>```

Hope that clarifies how you use invoke/()

Body:
I am currently studying Kotlin - Operator Overloading

I am trying to understand (with an example) how does operator overloading work for a function's invoke() function

The pre-test

Kotlin's Extension Functions

fun exampleOfExtensionFunction() {
    fun Int.randomize(): Int {
        return Random(this.toLong()).nextInt()
    }

    val randomizedFive = 5.randomize()
    println("$randomizedFive")
}

Prints :

-1157408321

In Kotlin, functions can be declared as variables with types

fun exampleOfFunctionType() {
    val printNumber: (number: Int) -> Unit
    printNumber = { number ->
        println("[$number = ${number.toString(16).toUpperCase()} = ${number.toString(2)}]")
    }

    printNumber(1023)
}

Prints :

[1023 = 3FF = 1111111111]

Kotlin allows operator overloading with both extension and member functions

fun exampleOfOperatorOverloadingUsingExtensionFunction() {
    class MyType() {
        val strings: ArrayList<String> = ArrayList<String>()
        override fun toString(): String {
            val joiner: StringJoiner = StringJoiner(" , ", "{ ", " }")
            for (string in strings) {
                joiner.add("\"$string\"")
            }
            return joiner.toString()
        }
    }

    operator fun MyType.contains(stringToCheck: String): Boolean {
        for (stringElement in strings) {
            if (stringElement == stringToCheck) return true
        }
        return false
    }

    val myType = MyType()
    myType.strings.add("one")
    myType.strings.add("two")
    myType.strings.add("three")
    println("$myType")
    println("(myType.contains(\"four\")) = ${myType.contains("four")} , (\"three\" in myType) = ${"three" in myType}")
}

Prints :

{ "one" , "two" , "three" }

  (myType.contains("four")) = false , ("three" in myType) = true

Test Attempt

Based on the above. I tried to create an example of a function's invoke() operator overloading using the type (Boolean, Boolean, Boolean) -> Boolean as a receiver type for an extension function invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean). This however did not work as expected.

    fun attemptFunctionInvokeOperatorOverloading() {
        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }

        var func1: ((Boolean, Boolean, Boolean) -> Boolean) = { flag1, flag2, flag3 ->
            println("func1 body")
            flag1 && flag2 && flag3
        }

        fun func2(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("func2 body")
            return flag1 && flag2 && flag3
        }

        func1(true, true, false)
        func2(true, true, true)
    }

Prints :

func1 body

  func2 body

Expected :

Overloaded invoke operator

  Overloaded invoke operator

Another question :

What exactly is this? (If it isn't operator overloading)

        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }

Body:
As said in another answer, invoke is defined on the function object itself, so you can't override it with an extension method.

I think the deeper problem here, though, is a slight misunderstanding of the purpose of this feature. Let's look at plus for the + operator instead.

I think you'll agree that attempting to define operator fun Int.plus(b: Int): Int { /* ... */} makes no sense, because overriding the default + operator for ints is a pretty dangerous thing to do, yes?

However, if you define a complex number class:

data class Complex(real: Double, img: Double)

Then it's perfectly reasonable to define this to sum complex numbers:

operator fun Complex.plus(other: Complex): Complex {
  val real = this.real + other.real
  val img  = this.img + other.img
  return Complex(real, img)
}

So, same thing with invoke and (): The meaning of () is that it's whatever is analogous to invoking a function for your type, and overriding invoke on something that's already a function is just asking for trouble. What you want to use it for instead is to provide function-like syntax for your own objects.

For example, imagine you define an interface like so:

interface MyCallback {
  fun call(ctx: MyContext)
}

Which you use the usual way:

callback.call(ctx)

But with an implementation of the invoke operator overload, you get to use it as a function:

operator fun MyCallback.invoke(ctx: Context) = this.call(ctx)

/* Elsewhere... */
callback(ctx)

Hope that clarifies how you use invoke/()


问:
Find out the parent view of a clicked button in swift
I have some code where I have 3 buttons and I would like to find out the parent view of those buttons when clicked

```<code> @IBAction func resizeButtonClicked(sender: UIButton) {
    if(sender.isEqual(resizeButton)) {
        //This is to convert to small square
    } else if(sender.isEqual(maximizeButton)) {
        //This is to convert to maximized view
    } else if(sender.isEqual(closeButton)) {
        //This is to close the view completely

    }
}
</code>```

Now I can identify the sender button but how do I identify the view this button is sitting in?

Thank you

Nikhil

答:
I you don't want to create a custom class and also don't want to use accessibilityHin:</p>

```<code>    func performAction(_ sender : AnyObject?)
{
    let cell = sender?.superview??.superviewOfClassType(UITableViewCell.self) as! UITableViewCell
    let tbl = cell.superviewOfClassType(UITableView.self) as! UITableView
    let indexPath = tbl.indexPath(for: cell)
    let myData = myDataArray[indexPath.row]
    ...
}
</code>```

Body:
I have some code where I have 3 buttons and I would like to find out the parent view of those buttons when clicked

 @IBAction func resizeButtonClicked(sender: UIButton) {
    if(sender.isEqual(resizeButton)) {
        //This is to convert to small square
    } else if(sender.isEqual(maximizeButton)) {
        //This is to convert to maximized view
    } else if(sender.isEqual(closeButton)) {
        //This is to close the view completely

    }
}

Now I can identify the sender button but how do I identify the view this button is sitting in?

Thank you

Nikhil

Body:
I you don't want to create a custom class and also don't want to use accessibilityHin:

    func performAction(_ sender : AnyObject?)
{
    let cell = sender?.superview??.superviewOfClassType(UITableViewCell.self) as! UITableViewCell
    let tbl = cell.superviewOfClassType(UITableView.self) as! UITableView
    let indexPath = tbl.indexPath(for: cell)
    let myData = myDataArray[indexPath.row]
    ...
}


问:
Knp\Snappy\Pdf generateFromHTML not generating the PDF with correct filename
I have PDF download functionality in my Laravel application.

It works perfectly when the PDF filename is English, the problem is with other languages.

```<code>$pdf = new Pdf();
...
$pdf->generateFromHtml(View::make('invoices.download'.$preferences->invoice_template, $data), $pdf_file_loc);
return Response::download($pdf_file_loc);
</code>```

In the above code, $pdf_file_loc has a full path of PDF file as well as the PDF filename. Currently, for instance, when the filename is "Förderverein_für.pdf" (it is German), the real name of created PDF file is "Frderverein_fr.pdf".

In other words, the generateFromHtml function is not creating the PDF file with correct German filename.

But after that, as $pdf_file_loc is containing the correct German name, it is trying to download the "Förderverein_für.pdf" file which isn't exist (in the return Response::download($pdf_file_loc)).

So it is showing an error page when I try to download the PDF file

This is causing a serious problem in my live application as the PDF filename contains our customer's company name and it is often written by foreign languages (not English).

答:
As the generateFromHtml function is not creating the file with other languages (not English), I didn't include other languages in the filename but tried to reset the filename with other language while downloading the file.

So, now the $pdf_file_loc doesn't include other language and it is stored with only English in the app store but convert it to other language while downloading.

```<code>return Response::download($pdf_file_loc, $filename);
</code>```

I don't think this is best answer but as long as the purpose is to get the PDF filename with other language, this solves my problem.

Body:
I have PDF download functionality in my Laravel application.

It works perfectly when the PDF filename is English, the problem is with other languages.

$pdf = new Pdf();
...
$pdf->generateFromHtml(View::make('invoices.download'.$preferences->invoice_template, $data), $pdf_file_loc);
return Response::download($pdf_file_loc);

In the above code, $pdf_file_loc has a full path of PDF file as well as the PDF filename. Currently, for instance, when the filename is "Förderverein_für.pdf" (it is German), the real name of created PDF file is "Frderverein_fr.pdf".

In other words, the generateFromHtml function is not creating the PDF file with correct German filename.

But after that, as $pdf_file_loc is containing the correct German name, it is trying to download the "Förderverein_für.pdf" file which isn't exist (in the return Response::download($pdf_file_loc)).

So it is showing an error page when I try to download the PDF file

This is causing a serious problem in my live application as the PDF filename contains our customer's company name and it is often written by foreign languages (not English).

Body:
As the generateFromHtml function is not creating the file with other languages (not English), I didn't include other languages in the filename but tried to reset the filename with other language while downloading the file.

So, now the $pdf_file_loc doesn't include other language and it is stored with only English in the app store but convert it to other language while downloading.

return Response::download($pdf_file_loc, $filename);

I don't think this is best answer but as long as the purpose is to get the PDF filename with other language, this solves my problem.


问:
Xamarin Label losing text alignment when page returned to
I have a label inside of a stack layout. It has its HorizontalTextAlignment set to TextAlignment.Center. It works correctly on the initial loading of the page, and when a new value is selected - however when the page is left and then returned to, it loses its alignment. This is only a problem on Android and not on iOS. I hope the image below can help illustrate my point. This is the only code that affects the Label's alignment, other than that it's just changing it's text through a binding, but I don't see how that would change it's alignment. Any ideas? Thanks.

StackLayout durationLayout = new StackLayout {
    Orientation = StackOrientation.Vertical,
    WidthRequest = (App.ScreenDpWidth / 3) - (GMStyle.Margin.PageMargin.Left * 2),
    VerticalOptions = LayoutOptions.Center,
    Margin = new Thickness(0, 5, 0, 0),
    HorizontalOptions = LayoutOptions.Start
};
durationLabel = new Label {
    Style = (Style)Application.Current.Resources["DurationLabelStyle"],
    HorizontalTextAlignment = TextAlignment.Center,
    //VerticalTextAlignment = TextAlignment.Center,
};
durationLabel.SetBinding(Label.TextProperty, "DurationDisplay");
durationLayout.Children.Add(timeSpanPicker);
durationLayout.Children.Add(durationLabel);
durationLayout.GestureRecognizers.Add(timeSpanTap);
```

答:
This is a bug in Xamarin Forms, that I believe appeared in 2.3.3 or 2.3.4, it works fine in 2.3.2. I don't know of any bug report lodged against it just yet, this is the closest I could find, that may be related.

https://bugzilla.xamarin.com/show_bug.cgi?id=49311

As a workaround, you can use HorizontalOptions=LayoutOptions.CenterAndExpand instead of HorizontalTextAlignment.


问:
Trigger event when user scroll to specific element - with jQuery
I have an h1 that is far down a page..

```<code><h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>
</code>```

and I want to trigger an alert when the user scrolls to the h1, or has it in it's browser's view.

```<code>$('#scroll-to').scroll(function() {
     alert('you have scrolled to the h1!');
});
</code>```

how do I do this?

答:
Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

```<code>function elementInView(el) {
  // The vertical distance between the top of the page and the top of the element.
  var elementOffset = $(el).offset().top;
  // The height of the element, including padding and borders.
  var elementOuterHeight = $(el).outerHeight();
  // Height of the window without margins, padding, borders.
  var windowHeight = $(window).height();
  // The vertical distance between the top of the page and the top of the viewport.
  var scrollOffset = $(this).scrollTop();

  if (elementOuterHeight < windowHeight) {
    // Element is smaller than viewport.
    if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
      // Element is completely inside viewport, reveal the element!
      return true;
    }
  } else {
    // Element is larger than the viewport, handle visibility differently.
    // Consider it visible as soon as it's top half has filled the viewport.
    if (scrollOffset > elementOffset) {
      // The top of the viewport has touched the top of the element, reveal the element!
      return true;
    }
  }
  return false;
}
</code>```

Body:
I have an h1 that is far down a page..

TRIGGER EVENT WHEN SCROLLED TO.

and I want to trigger an alert when the user scrolls to the h1, or has it in it's browser's view.

$('#scroll-to').scroll(function() {
     alert('you have scrolled to the h1!');
});

how do I do this?

Body:
Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

function elementInView(el) {
  // The vertical distance between the top of the page and the top of the element.
  var elementOffset = $(el).offset().top;
  // The height of the element, including padding and borders.
  var elementOuterHeight = $(el).outerHeight();
  // Height of the window without margins, padding, borders.
  var windowHeight = $(window).height();
  // The vertical distance between the top of the page and the top of the viewport.
  var scrollOffset = $(this).scrollTop();

  if (elementOuterHeight < windowHeight) {
    // Element is smaller than viewport.
    if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
      // Element is completely inside viewport, reveal the element!
      return true;
    }
  } else {
    // Element is larger than the viewport, handle visibility differently.
    // Consider it visible as soon as it's top half has filled the viewport.
    if (scrollOffset > elementOffset) {
      // The top of the viewport has touched the top of the element, reveal the element!
      return true;
    }
  }
  return false;
}


问:
Php session needs to be refresh to get the latest session value from angularjs
I created a session in php and the value of that session is from angularjs. I created a function that has a parameter. And every time I click on a button, the function will execute and the parameter of the function will send to php.  What my problem is when I click the first button my php page will display the value of 18 and it is correct. Now when I go back to the buttons and click another then redirect to php page it doesn't echo the new value which is 20 and it still echo the last value which is 18.

```<code>$scope.sendval = function(id){
    $http.post('page',{
        'param': id
     }).then(function(response){
         //some codes...
     });
};
</code>```

page.php

```<code>session_start();
$data = json_decode(file_get_contents("php://input"));
$_SESSION['param'] = $data->param;
</code>```

Display session

```<code>session_start();

echo $_SESSION['param'];
</code>```

My problem is the value of the session remains the same. But when I refresh page, it updates. How to do it without page refresh? TIA!

What I've already tried and still not working:

```<code>session_destroy($_SESSION['param']);
// and
unset($_SESSION['param']);
$_SESSION['param'];
</code>```

答:
You must have placed the unset in the wrong place.</p>

```<code><?php
session_start();
$data = json_decode(file_get_contents("php://input"));
if (isset($_SESSION['param'])) {
    unset($_SESSION['param']);
    $_SESSION['param'] = $data->param;
}
else{
    $_SESSION['param'] = $data->param;
}
?>
</code>```

Body:
I created a session in php and the value of that session is from angularjs. I created a function that has a parameter. And every time I click on a button, the function will execute and the parameter of the function will send to php.  What my problem is when I click the first button my php page will display the value of 18 and it is correct. Now when I go back to the buttons and click another then redirect to php page it doesn't echo the new value which is 20 and it still echo the last value which is 18.

$scope.sendval = function(id){
    $http.post('page',{
        'param': id
     }).then(function(response){
         //some codes...
     });
};

page.php

session_start();
$data = json_decode(file_get_contents("php://input"));
$_SESSION['param'] = $data->param;

Display session

session_start();

echo $_SESSION['param'];

My problem is the value of the session remains the same. But when I refresh page, it updates. How to do it without page refresh? TIA!

What I've already tried and still not working:

session_destroy($_SESSION['param']);
// and
unset($_SESSION['param']);
$_SESSION['param'];

Body:
You must have placed the unset in the wrong place.

<?php
session_start();
$data = json_decode(file_get_contents("php://input"));
if (isset($_SESSION['param'])) {
    unset($_SESSION['param']);
    $_SESSION['param'] = $data->param;
}
else{
    $_SESSION['param'] = $data->param;
}
?>


问:
How to set value in bean using use c:set with jsf?
I have another problem to solve. I have a code on my xhtml page:

```<code><t:dataList id="myDataList" value="#{myBean.myList}" var="element" first="0" `rows="10" dir="LTR" frame="hsides" rules="all">`
<c:set target="#{myBean}" property="fid" value="#{element[0]}"/>
...
</t:dataList>
</code>```

The problem is that value of 'fid' in a bean is null when I`m checking it. When I wrote:

```<code><c:set target="#{myBean}" property="fid" value="8"/>
</code>```

everything works fine and value is set to '8'. How should i fix this? Thanks for replies.

答:
JSTL tags runs during view build time. JSF tags runs during view render time. You can visualize it as follows: JSTL runs from top to bottom first when the JSF component tree is to be populated, then hands over the component tree to JSF and finally JSF runs from top to bottom to render the HTML.

The element[0] is not there when JSTL is creating the view. It's only there when JSF is rendering the HTML. However, 8 is hardcoded and it is always there.

There are several ways to achieve it the proper way, but since the functional requirement is unclear, I can't suggest a proper approach. Maybe you need f:setPropetyActionListener. Maybe you need DataModel#getRowData() or UIData#getRowData(). Or maybe you don't need it at all.

Body:
I have another problem to solve. I have a code on my xhtml page:

<t:dataList id="myDataList" value="#{myBean.myList}" var="element" first="0" `rows="10" dir="LTR" frame="hsides" rules="all">`
<c:set target="#{myBean}" property="fid" value="#{element[0]}"/>
...
</t:dataList>

The problem is that value of 'fid' in a bean is null when I`m checking it. When I wrote:

<c:set target="#{myBean}" property="fid" value="8"/>

everything works fine and value is set to '8'. How should i fix this? Thanks for replies.


问:
Slow spatial comparison when using cross join
I'm using U-SQL to select all objects which are inside one or more of the shapes. The code works but is really slow. Is there some way to make it more performant?

```<code>@rs1 =
    SELECT DISTINCT aisdata.imo,
                    portshape.unlocode
    FROM @lsaisdata AS aisdata
         CROSS JOIN
             @portsshape AS portshape
    WHERE Geometry.STMPolyFromText(new SqlChars(portshape.shape.Replace("Z", "").ToCharArray()), 0).STContains(Geometry.Point(aisdata.lon, aisdata.lat, 0)).IsTrue;
</code>```

Added more information about my issue:

I've registered Microsoft.SqlServer.Types.dll and SqlServerSpatial130.dll to be able to use spatial functions in U-SQL

I'm running my job in Data Lake Analytics using two AUs. Initially I used 10 AUs, but the Diagnostics tab stated that the job was 8 AUs over-allocated and max useful AUs was 2.

The job takes about 27 minutes to run with the UDT code below and the cross join takes almost all of this time

The input is one csv file (66 Mb) and one wkt file (2.4 Mb)

I'm using Visual Studio 2015 with Azure Data Lake Tools v2.2.5000.0

I tried encapsulating some of the spatial code in UDTs and that improved the performance to 27 minutes:

@rs1 =

    SELECT DISTINCT aisdata.imo,

    portshape.unlocode

    FROM @lsaisdata AS aisdata

    CROSS JOIN

    @portsshape AS portshape
    WHERE portshape.geoShape.GeoObject.STContains(SpatialUSQLApp.CustomFunctions.GetGeoPoint(aisdata.lon, aisdata.lat).GeoObject).IsTrue;

答:
First, a CROSS JOIN will always explode your data to an NxM matrix. Depending on the number of rows this may either make it very expensive and possibly hard to estimate correct degree of parallelism.

Secondly, I assume that the Spatial join you do is an expensive operation. For example, if you use SQL Server 2012's spatial capabilities (2016 has native implementations of the type that may be a bit faster), I assume you probably get similar performance behavior. Most of the time you need a spatial index to get better performance. Now U-SQL does not support spatial indices, but you probably could approximate the same behavior by using an abstraction (like tessellation of the objects and determining if they overlap), to provide a faster pre-filter/join before you then test the condition to weed out the false positives.

Body:
I'm using U-SQL to select all objects which are inside one or more of the shapes. The code works but is really slow. Is there some way to make it more performant?

@rs1 =
    SELECT DISTINCT aisdata.imo,
                    portshape.unlocode
    FROM @lsaisdata AS aisdata
         CROSS JOIN
             @portsshape AS portshape
    WHERE Geometry.STMPolyFromText(new SqlChars(portshape.shape.Replace("Z", "").ToCharArray()), 0).STContains(Geometry.Point(aisdata.lon, aisdata.lat, 0)).IsTrue;

Added more information about my issue:

I've registered Microsoft.SqlServer.Types.dll and SqlServerSpatial130.dll to be able to use spatial functions in U-SQL

I'm running my job in Data Lake Analytics using two AUs. Initially I used 10 AUs, but the Diagnostics tab stated that the job was 8 AUs over-allocated and max useful AUs was 2.

The job takes about 27 minutes to run with the UDT code below and the cross join takes almost all of this time

The input is one csv file (66 Mb) and one wkt file (2.4 Mb)

I'm using Visual Studio 2015 with Azure Data Lake Tools v2.2.5000.0

I tried encapsulating some of the spatial code in UDTs and that improved the performance to 27 minutes:

@rs1 =

    SELECT DISTINCT aisdata.imo,

    portshape.unlocode

    FROM @lsaisdata AS aisdata

    CROSS JOIN

    @portsshape AS portshape
    WHERE portshape.geoShape.GeoObject.STContains(SpatialUSQLApp.CustomFunctions.GetGeoPoint(aisdata.lon, aisdata.lat).GeoObject).IsTrue;


问:
Stack overflow in recursive method
I'm writing a program that allows a user to input a set of integers into an array and characteristics of those numbers will be displayed once a zero is entered. I am having an issue with one method:findMaxOfLessThanFirst. Which, of course, finds the maximum number in the array that is also less than the first number entered. Here is the full code:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];

        InputStreamReader inRead = new InputStreamReader(System.in);
        BufferedReader buffRead = new BufferedReader(inRead);
        String line = buffRead.readLine();

        try {
            while (!line.equals("0") && index < 100) {
                numbers[index] = Integer.parseInt(line);
                index++;
                line = buffRead.readLine();
            }
        } catch (IOException exception) {
            System.out.println("Array index out of bound");
        }
        int min = findMin(numbers, 0);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        int maxLessThanFirst = findMaxOfLessThanFirst(numbers, 1, numbers.length - 1, numbers[0]);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println(
                "The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
    }

    public static int findMin(int[] numbers, int index) {
        if (index == numbers.length - 1) {
            return numbers[index];
        } else {
            return Math.min(numbers[index], findMin(numbers, index + 1));
        }
    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else
                return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return +2;
            } else {
                return 1;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

    private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
        if (startIndex == endIndex) {
            if (numbers[endIndex] <= firstNumber)
                return numbers[startIndex];
        }
        int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
        if (max >= numbers[endIndex] && max <= firstNumber) {
            return max;
        }
        return numbers[endIndex];
    }
}
</code>```

I am sure I'm missing something really elementary here. I just started learning the concept of recursion. So, please be gentle.

答:
You are missing the else branch. Where you have if, there must a else, I use this as a rule for programming. In some cases else maybe useless, in such cases I put some log info in else.

```<code> private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    if (startIndex == endIndex) {
        if (numbers[endIndex] <= firstNumber)
            return numbers[startIndex];
        else return Integer.MIN_VALUE;
    }
    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
    if (max >= numbers[endIndex] && max<=firstNumber) {
        return max;
    }
    return numbers[endIndex];
}
</code>```

Title: Stack overflow in recursive method

Body:
I'm writing a program that allows a user to input a set of integers into an array and characteristics of those numbers will be displayed once a zero is entered. I am having an issue with one method:findMaxOfLessThanFirst. Which, of course, finds the maximum number in the array that is also less than the first number entered. Here is the full code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];

        InputStreamReader inRead = new InputStreamReader(System.in);
        BufferedReader buffRead = new BufferedReader(inRead);
        String line = buffRead.readLine();

        try {
            while (!line.equals("0") && index < 100) {
                numbers[index] = Integer.parseInt(line);
                index++;
                line = buffRead.readLine();
            }
        } catch (IOException exception) {
            System.out.println("Array index out of bound");
        }
        int min = findMin(numbers, 0);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        int maxLessThanFirst = findMaxOfLessThanFirst(numbers, 1, numbers.length - 1, numbers[0]);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println(
                "The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
    }

    public static int findMin(int[] numbers, int index) {
        if (index == numbers.length - 1) {
            return numbers[index];
        } else {
            return Math.min(numbers[index], findMin(numbers, index + 1));
        }
    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else
                return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return +2;
            } else {
                return 1;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

    private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
        if (startIndex == endIndex) {
            if (numbers[endIndex] <= firstNumber)
                return numbers[startIndex];
        }
        int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
        if (max >= numbers[endIndex] && max <= firstNumber) {
            return max;
        }
        return numbers[endIndex];
    }
}

I am sure I'm missing something really elementary here. I just started learning the concept of recursion. So, please be gentle.

Body:
You are missing the else branch. Where you have if, there must a else, I use this as a rule for programming. In some cases else maybe useless, in such cases I put some log info in else.

 private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    if (startIndex == endIndex) {
        if (numbers[endIndex] <= firstNumber)
            return numbers[startIndex];
        else return Integer.MIN_VALUE;
    }
    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
    if (max >= numbers[endIndex] && max<=firstNumber) {
        return max;
    }
    return numbers[endIndex];
}


问:
jQuery: How to get first value and last value on input text
I have no idea how to get last value on input text. I already get the first value, when input type is empty did not get value. Here's my code:

HTML

```<code><input type="text" name="date[]" class="date" id="date" value="6/17"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
</code>```

JS/jQuery

```<code>$(document).ready(function(){
    var $set = $('.date');
    var len = $set.length;
    $set.each(function(index, element) {
        if (index === 0) {
            alert (this.value);
        }
    });
});
</code>```

答:
You can use [value!=''] to select only inputs with values.
Then use first() and last() to get values from the first item and last item from the selected list.

var $values = $(".date[value!='']");
$("#firstValue").html($values.first().val());
$("#lastValue").html($values.last().val());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="date[]" class="date" id="date" value="6/17"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<div>First value: <span id="firstValue"></span></div>
<div>Last value: <span id="lastValue"></span></div></code>```

Body:
I have no idea how to get last value on input text. I already get the first value, when input type is empty did not get value. Here's my code:

HTML

<input type="text" name="date[]" class="date" id="date" value="6/17">

<input type="text" name="date[]" class="date" id="date" value="6/18">

<input type="text" name="date[]" class="date" id="date" value="6/18">

<input type="text" name="date[]" class="date" id="date" value="6/19">

<input type="text" name="date[]" class="date" id="date" value="6/19">

<input type="text" name="date[]" class="date" id="date" value="">

<input type="text" name="date[]" class="date" id="date" value="">

JS/jQuery

$(document).ready(function(){
    var $set = $('.date');
    var len = $set.length;
    $set.each(function(index, element) {
        if (index === 0) {
            alert (this.value);
        }
    });
});

Body:
You can use [value!=''] to select only inputs with values.
Then use first() and last() to get values from the first item and last item from the selected list.

var $values = $(".date[value!='']");
$("#firstValue").html($values.first().val());
$("#lastValue").html($values.last().val());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="date[]" class="date" id="date" value="6/17"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<div>First value: <span id="firstValue"></span></div>
<div>Last value: <span id="lastValue"></span></div>


问:
Get full response of Websocket connect
My code:

```<code><script>
// Create WebSocket connection.
const socket = new WebSocket('wss://echo.websocket.org:443');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server', event.data);
});
</script>
</code>```

Output:

```<code>Message from server Hello Server!
</code>```

My qustion is, does it possible to get the full response that include the HTTP Header and the TLS certificate?

Thank you.

答:
My question is, is it possible to get the full response that includes the HTTP Header and the TLS certificate?

No, it is not.  The WebSocket interface in the browser does not expose that info.  HTTP is used to establish the initial WebSocket connection, but after that, the protocol is changed to the WebSocket protocol and HTTP is no longer used.  The browser interface to WebSockets does not expose custom headers.  You can request an URL (with protocol, port, domain, path, query string, etc...) and you can send zero or more sub-protocol strings.  That's it.

From MDN, this is the interface for establishing the WebSocket connection:

```<code>WebSocket WebSocket(
  in DOMString url,
  in optional DOMString protocols
);
</code>```

Once the connection is upgraded from HTTP to the WebSocket protocol, then there are no HTTP headers any more.  That data is sent in WebSocket frames as you can see here on MDN.  In that data frame format, you will get all of the payload data from that frame other than the housekeeping bytes used for delineating the frame and managing security.  There are no headers there to get.

If the connection is TLS, that is completely transparent to you and none of that information is made available either.

Title: Get full response of Websocket connect

Body:
My code:

Output:

Message from server Hello Server!

My qustion is, does it possible to get the full response that include the HTTP Header and the TLS certificate?

Thank you.

Body:
My question is, is it possible to get the full response that includes the HTTP Header and the TLS certificate?

No, it is not.  The WebSocket interface in the browser does not expose that info.  HTTP is used to establish the initial WebSocket connection, but after that, the protocol is changed to the WebSocket protocol and HTTP is no longer used.  The browser interface to WebSockets does not expose custom headers.  You can request an URL (with protocol, port, domain, path, query string, etc...) and you can send zero or more sub-protocol strings.  That's it.

From MDN, this is the interface for establishing the WebSocket connection:

WebSocket WebSocket(
  in DOMString url,
  in optional DOMString protocols
);

Once the connection is upgraded from HTTP to the WebSocket protocol, then there are no HTTP headers any more.  That data is sent in WebSocket frames as you can see here on MDN.  In that data frame format, you will get all of the payload data from that frame other than the housekeeping bytes used for delineating the frame and managing security.  There are no headers there to get.

If the connection is TLS, that is completely transparent to you and none of that information is made available either.