问:
How to send cookies when connecting to socket.io via WebSockets?
Is there a way to easily pass an authentication cookie when handshaking a WebSocket connection to socket.io? I currently have to do it separately, like so:</p>

```<code>socket = new io.Socket(document.location.hostname);
socket.addEvent("connect", function()
{
    // Send PHP session ID, which will be used to authenticate
    var sessid = readCookie("PHPSESSID");
    this.send("{'action':'authenticate','sessionid':'"+sessid+"'}");
});
</code>```

答:
WebSockets do have support for cookies since they are based on HTTP, but a quick browse through the source of Socket.IO revealed that there is no support for this built in.

So using cookies directly is not a feasible solution in this case, also, since you're using Socket.IO, it's not guaranteed that users will actually connect via a WebSocket.

In the case that a connection uses a flash socket, it's really hard to make Flash send the Browser's cookies instead of it's own set, so even if you would send a cookie directly, it wouldn't get set in the Browser in case of a flask socket connection.

Currently there's no support for this built into Socket.IO, so flash sockets will just fail.

You can read about that in this issue, and here's a question about the flash cookie problem.

Best solution is still to make it part of your own protocol.

Body:
Is there a way to easily pass an authentication cookie when handshaking a WebSocket connection to socket.io? I currently have to do it separately, like so:

socket = new io.Socket(document.location.hostname);
socket.addEvent("connect", function()
{
    // Send PHP session ID, which will be used to authenticate
    var sessid = readCookie("PHPSESSID");
    this.send("{'action':'authenticate','sessionid':'"+sessid+"'}");
});


来源: stackexchange

问:
Sql - order by number of conditions satisfied
Suppose I have a query with multiple conditions that are in the OR relation like this:

```<code>SELECT * FROM TABLE WHERE (c1) OR (c2) OR (c3) OR ...
</code>```

I do not want results to be ordered based on the number of condition they satisfied .this means records that satisfied c1 and c2 and c3 showed first(3 conditions),then the  records that satisfy c1 and c2,or c1 and c3 ,or c2 and c3(2 conditions) and at the end records that satisfy c1 or c2 or c3

答:
Make an expression that looks like this:

```<code>( CASE WHEN c1 THEN 1 ELSE 0 END
+ CASE WHEN c2 THEN 1 ELSE 0 END
+ CASE WHEN c3 THEN 1 ELSE 0 END)
</code>```

It will provide you the number of conditions satisfied by the current record.

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a query with multiple conditions that are in the OR relation like this:

SELECT * FROM TABLE WHERE (c1) OR (c2) OR (c3) OR ...

I do not want results to be ordered based on the number of condition they satisfied .this means records that satisfied c1 and c2 and c3 showed first(3 conditions),then the  records that satisfy c1 and c2,or c1 and c3 ,or c2 and c3(2 conditions) and at the end records that satisfy c1 or c2 or c3

Body:
Make an expression that looks like this:

( CASE WHEN c1 THEN 1 ELSE 0 END
+ CASE WHEN c2 THEN 1 ELSE 0 END
+ CASE WHEN c3 THEN 1 ELSE 0 END)

It will provide you the number of conditions satisfied by the current record.


问:
Link to corresponding path in other locale (rails)
I have a multi-lingual application in Ruby on Rails 4. For that I use the following  domains:

Swedish: exempel.se

English: example.com

French:  fr.example.com

Spanish: es.example.com

I want to be able to link to the corresponding path in another corresponding locale. For example if I am at www.exempel.se/denna-bloggpost I want to be able to easily link to (English/Spanish/French) to e.g. www.example.com/this-here-blog-post and es.example.com/este-posto-de-bloggo (sorry, can't speak Spanish :)).

I understand this is done with link_to 'Spanish', locale => :es but this gives me the url www.exempel.se/denna-bloggpost?locale=es which is not what I want. I expect to access es.example.com/esto-posto-de-bloggo

It seems like default_url_options has something to do with this but I can't make it work.

How do I solve this?

Edit (2017-03-30): I will also need this solution for hreflang in the  section.

I am using the route_translator gem.

I have seen several solutions for this but they all include solutions with ?locale=en or are just to simplified (like, only working for one single controller). What I am hoping for is a solution that would do something like this:

```<code><% I18n.available_locales.each |locale| do %>
 <% I18n.t(this route e.g. /denna-bloggpost) #=> /este-posto-de-bloggo, /this-blog-post, /le-post-du-blog %>
<% end %>
</code>```

答:
You can use the locale-specific routes that route_translator generates for you. Run rake routes to see what these are. And then:

```<code># Create links for every other locale
<% (I18n.available_locales - I18n.locale).each |locale| do %>
  # Example URL helper here - replace with your own!
  <%= Rails.application.routes.url_helpers.send("posts_#{locale}_url",
 'denna-bloggpost') %>
<% end %>
</code>```

Body:
I have a multi-lingual application in Ruby on Rails 4. For that I use the following  domains:

Swedish: exempel.se

English: example.com

French:  fr.example.com

Spanish: es.example.com

I want to be able to link to the corresponding path in another corresponding locale. For example if I am at www.exempel.se/denna-bloggpost I want to be able to easily link to (English/Spanish/French) to e.g. www.example.com/this-here-blog-post and es.example.com/este-posto-de-bloggo (sorry, can't speak Spanish :)).

I understand this is done with link_to 'Spanish', locale => :es but this gives me the url www.exempel.se/denna-bloggpost?locale=es which is not what I want. I expect to access es.example.com/esto-posto-de-bloggo

It seems like default_url_options has something to do with this but I can't make it work.

How do I solve this?

Edit (2017-03-30): I will also need this solution for hreflang in the  section.

I am using the route_translator gem.

I have seen several solutions for this but they all include solutions with ?locale=en or are just to simplified (like, only working for one single controller). What I am hoping for is a solution that would do something like this:

<% I18n.available_locales.each |locale| do %>
 <% I18n.t(this route e.g. /denna-bloggpost) #=> /este-posto-de-bloggo, /this-blog-post, /le-post-du-blog %>
<% end %>

Body:
You can use the locale-specific routes that route_translator generates for you. Run rake routes to see what these are. And then:

# Create links for every other locale
<% (I18n.available_locales - I18n.locale).each |locale| do %>
  # Example URL helper here - replace with your own!
  <%= Rails.application.routes.url_helpers.send("posts_#{locale}_url",
 'denna-bloggpost') %>
<% end %>


问:
jsf selectOneMenu value does not change
I have a selectOneMenu that have the correct values (a list of string) however when I select a value it does not trigger the setSelectedValue from the bean.

```<code><h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}">
    <f:selectItems value="#{Bean.values}"/>
</h:selectOneMenu>
</code>```

Bean:

```<code>private String selectedValue = "";
private List<String> values = new LinkedList<String>();

...

public String getSelectedValue() {
    return this.selectedValue;
}

public void setSelectedValue(String selectedValue) {
    LOGGER.debug("Try to set selected value" + selectedValue);
    if (!selectedValue.isEmpty()){
        this.selectedValue = selectedValue ;
    }
}
</code>```

There is nothing in the logs.

I've tried to add a listener:

```<code><h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}" valueChangeListener="#{dwrBean.statusChanged}" >
    <f:selectItems value="#{dwrBean.values}"/>
</h:selectOneMenu>
</code>```

Here the statusChanged is triggered but the newValue is null, the oldValue is correct, but it is always the same.

```<code>public void statusChanged(ValueChangeEvent event) {
    LOGGER.debug("new" + event.getNewValue());
    LOGGER.debug("old" + event.getOldValue());

    if (event.getNewValue() != null &&
            !((String) event.getNewValue()).isEmpty()) {

            LOGGER.debug("OK");
        }
}
</code>```

I really don't understand.

Actually the selectOneMenu is within a popup.

I've moved the selectOneMenu outside of the popup and it works. Do I have to change the scope of the Bean ?

Non-working configuration:

```<code><h:form>
     <rich:popupPanel>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>
<h:form>
</code>```

Working configuration:

```<code><h:form>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>

     <rich:popupPanel>
<h:form>
</code>```

答:
below method invoke when you subbmit form</p>

```<code>public void setSelectedValue(String selectedValue) {
    LOGGER.debug("Try to set selected value" + selectedValue);
    if (!selectedValue.isEmpty()){
        this.selectedValue = selectedValue ;
    }
}
</code>```

Title: jsf selectOneMenu value does not change

Body:
I have a selectOneMenu that have the correct values (a list of string) however when I select a value it does not trigger the setSelectedValue from the bean.

<h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}">
    <f:selectItems value="#{Bean.values}"/>
</h:selectOneMenu>

Bean:

private String selectedValue = "";
private List<String> values = new LinkedList<String>();

...

public String getSelectedValue() {
    return this.selectedValue;
}

public void setSelectedValue(String selectedValue) {
    LOGGER.debug("Try to set selected value" + selectedValue);
    if (!selectedValue.isEmpty()){
        this.selectedValue = selectedValue ;
    }
}

There is nothing in the logs.

I've tried to add a listener:

<h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}" valueChangeListener="#{dwrBean.statusChanged}" >
    <f:selectItems value="#{dwrBean.values}"/>
</h:selectOneMenu>

Here the statusChanged is triggered but the newValue is null, the oldValue is correct, but it is always the same.

public void statusChanged(ValueChangeEvent event) {
    LOGGER.debug("new" + event.getNewValue());
    LOGGER.debug("old" + event.getOldValue());

    if (event.getNewValue() != null &&
            !((String) event.getNewValue()).isEmpty()) {

            LOGGER.debug("OK");
        }
}

I really don't understand.

Actually the selectOneMenu is within a popup.

I've moved the selectOneMenu outside of the popup and it works. Do I have to change the scope of the Bean ?

Non-working configuration:

<h:form>
     <rich:popupPanel>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>
<h:form>

Working configuration:

<h:form>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>

     <rich:popupPanel>
<h:form>

Body:
below method invoke when you subbmit form

public void setSelectedValue(String selectedValue) {
    LOGGER.debug("Try to set selected value" + selectedValue);
    if (!selectedValue.isEmpty()){
        this.selectedValue = selectedValue ;
    }
}


问:
Understanding mpreferred-stack-boundary=number
I'm trying to visualize and understand how to utilize mpreferred-stack-boundary(more like build code to exploit it for school). From reading the gcc manual, it states that it aligns the stack according to mpreferred-stack-boundary=number, where number is the exponent to base 2. By default, number=4 so the alignment of the stack is 2^4= 16 bytes. I don't know if it's the caffeine messing with my brain, but all the shell code injections I've seen in class demand that we use mpreferred-stack-boundary=2 when compiling, which would align the stack by 4 bytes. So does that mean I have that the variables placed on the stack try to fill the stack 16 bytes at a time by default? Also, why does shellcode that I place in the buffer work when the boundary when it is set to 2 yet does not work when run it in default mode?</p>

答: The size of the whole stack frame will be rounded up to 16 bytes, not each individual local variable. Shellcode would work either way, but code is written for one particular layout so you need to use different shellcode for different layout. – Jester</p>


问:
Error: Inline Babel script: Adjacent JSX elements must be wrapped in an enclosing tag
I am using ReactJS, i am getting this error:

Inline Babel script: Adjacent JSX elements must be wrapped in an
  enclosing tag.

One more thing: Can I use multiple state in my component, how?

Here is my code:

```<code>class App extends React.Component (
    constructor(props) {
        super(props);

        this.state = {
            header: "Header from state...",
            data:[]
        }

        this.setStateHandler = this.setStateHandler.bind(this);
    }
    setStateHandler() {
        var item = "ReactJs :)"
        var myArray = this.state.data;
        myArray.push(item)
        this.setState({data: myArray})
    };
    render(){
        return(
            <p>{this.state.header}</p>
            <button onClick = {this.setStateHandler}>SET STATE</button>
            <p>State Array: {this.state.data}</p>
        )
    }
}
export default App;
</code>```

答:
Issue is in return, you are returning more than one html element, wrap them in a div it will work.

Reason: A React component can't return multiple elements, but a single JSX expression can have multiple children, so if you want a component to render multiple things you can wrap them in a div.

Don't forget that the render() is basically a function, Function always take in number of parameters and always return exactly one value.

Use this:

```<code>render(){
   return(
     <div>
        <p>{this.state.header}</p>
        <button onClick = {this.setStateHandler}>SET STATE</button>
        <p>State Array: {this.state.data}</p>
     </div>
   )
}
</code>```

You need to change the way you are updating the state variable. Never mutate state variable directly. Instead of pushing the values directly into State variable array, first create a copy of that then update the value and push the data back into state. Like this:

```<code>let a = this.state.data.slice();
a.push('React');
this.setState({data: a});
</code>```

multiple State using in single component...?

You can declare many variable inside state object, but declaring state object multiple times doesn't make any sense.

Check the working example:

class App extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            header: "Header from state...",
            data:[]
        };

        this.setStateHandler = this.setStateHandler.bind(this);
    }
    setStateHandler() {
        var item = "ReactJs :)"
        var myArray = this.state.data.slice();
        myArray.push(item);
        this.setState({data: myArray})
    };
    render(){
        return(

{this.state.header}

               <button onClick = {this.setStateHandler}>SET STATE</button>

State Array: {this.state.data}

        )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I am using ReactJS, i am getting this error:

Inline Babel script: Adjacent JSX elements must be wrapped in an
  enclosing tag.

One more thing: Can I use multiple state in my component, how?

Here is my code:

class App extends React.Component (
    constructor(props) {
        super(props);

        this.state = {
            header: "Header from state...",
            data:[]
        }

        this.setStateHandler = this.setStateHandler.bind(this);
    }
    setStateHandler() {
        var item = "ReactJs :)"
        var myArray = this.state.data;
        myArray.push(item)
        this.setState({data: myArray})
    };
    render(){
        return(

{this.state.header}

            <button onClick = {this.setStateHandler}>SET STATE</button>

State Array: {this.state.data}

        )
    }
}
export default App;

Body:
Issue is in return, you are returning more than one html element, wrap them in a div it will work.

Reason: A React component can't return multiple elements, but a single JSX expression can have multiple children, so if you want a component to render multiple things you can wrap them in a div.

Don't forget that the render() is basically a function, Function always take in number of parameters and always return exactly one value.

Use this:

render(){
   return(
     <div>
        <p>{this.state.header}</p>
        <button onClick = {this.setStateHandler}>SET STATE</button>
        <p>State Array: {this.state.data}</p>
     </div>
   )
}

You need to change the way you are updating the state variable. Never mutate state variable directly. Instead of pushing the values directly into State variable array, first create a copy of that then update the value and push the data back into state. Like this:

let a = this.state.data.slice();
a.push('React');
this.setState({data: a});

multiple State using in single component...?

You can declare many variable inside state object, but declaring state object multiple times doesn't make any sense.

Check the working example:

class App extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            header: "Header from state...",
            data:[]
        };

        this.setStateHandler = this.setStateHandler.bind(this);
    }
    setStateHandler() {
        var item = "ReactJs :)"
        var myArray = this.state.data.slice();
        myArray.push(item);
        this.setState({data: myArray})
    };
    render(){
        return(
            <div>
               <p>{this.state.header}</p>
               <button onClick = {this.setStateHandler}>SET STATE</button>
               <p>State Array: {this.state.data}</p>
            </div>
        )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
What is the best method of handling currency/money?
I'm working on a very basic shopping cart system.

I have a table items that has a column price of type integer.

I'm having trouble displaying the price value in my views for prices that include both Euros and cents. Am I missing something obvious as far as handling currency in the Rails framework is concerned?

Body:
Simple code for Ruby & Rails

<%= number_to_currency(1234567890.50) %>

OUT PUT => $1,234,567,890.50


问:
Writing to event log in C# - do I need to use EventLog.CreateEventSource when writing to Application log?
When I use the following code to write to Application Event log, everything works fine:

```<code>EventLog log = new EventLog();
log.Source = "Application";
log.WriteEntry("test message", EventLogEntryType.Error);
</code>```

When I use the code that is from MSDN and all other blogs, I get the security error (I am guessing because CreateEventSource raises it).

```<code>string sSource = "MyWebService";
string sLog = "myApplication";
string sMsg = errorMessage;

if (!EventLog.SourceExists(sSource))
   EventLog.CreateEventSource(sSource, sLog);

 EventLog.WriteEntry(sSource, sMsg, EventLogEntryType.Error);
</code>```

So, do I need to check whether the source exists if all I need is to write to Application log which is there by default?

What is the proper way to write to EventViewer?

答:
You need admin rights to run your application.

Either you can run your application by
Going into the debug folder of your application and right click on your .exe file and run as admin

or

You run Visual studio as admin

Body:
When I use the following code to write to Application Event log, everything works fine:

EventLog log = new EventLog();
log.Source = "Application";
log.WriteEntry("test message", EventLogEntryType.Error);

When I use the code that is from MSDN and all other blogs, I get the security error (I am guessing because CreateEventSource raises it).

string sSource = "MyWebService";
string sLog = "myApplication";
string sMsg = errorMessage;

if (!EventLog.SourceExists(sSource))
   EventLog.CreateEventSource(sSource, sLog);

 EventLog.WriteEntry(sSource, sMsg, EventLogEntryType.Error);

So, do I need to check whether the source exists if all I need is to write to Application log which is there by default?

What is the proper way to write to EventViewer?


问:
Rounded corners in GroupBox control
How can I get rounded corners in a GroupBox in my form? Is there any option in the property tab?</p>

答:
When visual styles are enabled for your application and the FlatStyle property is set to "System", the group boxes look like they have slightly rounded corners, but it's probably no more than 3 to 5 degrees. So I suppose this is not what you're looking for.

Unfortunately, there's no built-in way to customize its degree of roundedness. The only real solution is to use a custom control. You can either inherit off of the existing GroupBox control and override its Paint event to draw the borders yourself, or you can use one of these existing controls:

http://roundedgroupbox.codeplex.com/

http://weblogs.asp.net/andrewrea/archive/2008/02/18/my-own-version-of-a-winforms-rounded-groupbox-with-transparency.aspx

http://www.codeproject.com/KB/miscctrl/grouper.aspx

ContentLicense: CC BY-SA 2.5

Title: Rounded corners in GroupBox control


问:
Can't ssh to vagrant + virtualbox (from vmware)
I now my setup is redundant but it's only for testing purposes.
I'm running VMware fusion 8.5.5 on my laptop. Inside my VMware I've installed Centos 7:

```<code>$ uname -r
3.10.0-514.10.2.el7.x86_64
</code>```

After that I've installed vagrant

```<code>vagrant --version
Vagrant 1.9.3
</code>```

And also virtualbox version 5.1.18 r114002

But when I start a vagrant box I'm unable to ssh. Never. The OS of the box doesn't matter:

```<code>$ vagrant init bento/centos-7.2
$ vagrant up
</code>```

I'm facing this error when I try to check the virtual box GUI but I would think it's not problem in my case. I just try to ssh.

```<code>==> default: Importing base box 'bento/centos-7.2'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'bento/centos-7.2' is up to date...
==> default: Setting the name of the VM: test_default_1490853341673_52433
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

VT-x/AMD-V hardware acceleration is not available on your system.
</code>```

答: I had the same problem, this is a bug in the virtual box version you're using. try downloading virtualbox 5.1.4 </p>

Body:
I now my setup is redundant but it's only for testing purposes.
I'm running VMware fusion 8.5.5 on my laptop. Inside my VMware I've installed Centos 7:

$ uname -r
3.10.0-514.10.2.el7.x86_64

After that I've installed vagrant

vagrant --version
Vagrant 1.9.3

And also virtualbox version 5.1.18 r114002

But when I start a vagrant box I'm unable to ssh. Never. The OS of the box doesn't matter:

$ vagrant init bento/centos-7.2
$ vagrant up

I'm facing this error when I try to check the virtual box GUI but I would think it's not problem in my case. I just try to ssh.

==> default: Importing base box 'bento/centos-7.2'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'bento/centos-7.2' is up to date...
==> default: Setting the name of the VM: test_default_1490853341673_52433
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

VT-x/AMD-V hardware acceleration is not available on your system.


问:
How to use variable defined inside setOnAction outside it?
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

```<code>//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
</code>```

答:
Just make that variable a class field.

```<code>public class MyClass
{
    private int poeni;

    public MyClass()
    {
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                MyClass.this.poeni = 0;

                if(odgovor1_1.isSelected()) MyClass.this.poeni++;
                if(odgovor2_3.isSelected()) MyClass.this.poeni++;
                if(odgovor3_2.isSelected()) MyClass.this.poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + this.poeni);
    }
}
</code>```

Update:

This should be the correct way to do it the JavaFX style:

```<code>public class MyClass
{
    private final IntegerProperty poeni = new SimpleIntegerProperty(0);
    public IntegerProperty poeniProperty()
    {
        return this.poeni;
    }
    public int getPoeni()
    {
        this.poeniProperty().get();
    }
    public void setPoeni(int value)
    {
        this.poeniProperty().set(value);
    }

    public MyClass()
    {
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int count = 0;

                if(odgovor1_1.isSelected()) count++;
                if(odgovor2_3.isSelected()) count++;
                if(odgovor3_2.isSelected()) count++;
                MyClass.this.setPoeni(count);
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label();
        lbl_rezultat.textProperty.bind(Bindings.createStringBinding(() ->
            "Vas rezultat je: " + Integer.toString(MyClass.this.getPoeni()),
            MyClass.this.poeniProperty()));
    }
}
</code>```

Body:
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);

Body:
Just make that variable a class field.

public class MyClass
{
    private int poeni;

    public MyClass()
    {
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                MyClass.this.poeni = 0;

                if(odgovor1_1.isSelected()) MyClass.this.poeni++;
                if(odgovor2_3.isSelected()) MyClass.this.poeni++;
                if(odgovor3_2.isSelected()) MyClass.this.poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + this.poeni);
    }
}

Update:

This should be the correct way to do it the JavaFX style:

public class MyClass
{
    private final IntegerProperty poeni = new SimpleIntegerProperty(0);
    public IntegerProperty poeniProperty()
    {
        return this.poeni;
    }
    public int getPoeni()
    {
        this.poeniProperty().get();
    }
    public void setPoeni(int value)
    {
        this.poeniProperty().set(value);
    }

    public MyClass()
    {
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int count = 0;

                if(odgovor1_1.isSelected()) count++;
                if(odgovor2_3.isSelected()) count++;
                if(odgovor3_2.isSelected()) count++;
                MyClass.this.setPoeni(count);
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label();
        lbl_rezultat.textProperty.bind(Bindings.createStringBinding(() ->
            "Vas rezultat je: " + Integer.toString(MyClass.this.getPoeni()),
            MyClass.this.poeniProperty()));
    }
}


问:
Xamrin android app project not getting build
I am new at xamrin android app development. I have made basic menu drawer app in xamrin. But when I try to run this project it show following warning

Severity   Code    Description Project File    Line    Suppression State
  Warning     An unexpected error occurred trying to initialize Android Designer. Please verify the Android SDK path and the  Java Development Kit path on Tools->Options->Xamarin->Android Settings menu. Please see the logs for more details.          0

Severity   Code    Description Project File    Line    Suppression State
  Warning IDE0006 Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.   menu_drawer     1   Active

JDK path
C:\Program Files (x86)\Java\jdk1.6.0_21

And Android SDK Path
C:\Users\Suraj\AppData\Local\Xamarin\MonoForAndroid\AndroidSDK

答:
Open Tools > Option > Xamarin > Android. Are the Android SDK and JDK available?

If yes, try updating your Android SDK and JDK.

If no, download and install Android SDK and JDK to your computer.

Hope it could help.


问:
Is is possible to change a UISearchBar placeholder's alignment?
I am going to need to show the UISearchBar in different alignments because of different input languages.

I saw this answer, but I can't find where is it that you actually align the text to the right on a UISearchBar.

Any ideas?

Thanks!

答:
To set attributed placeholder text to achieve left aligned placeholder, try this code...  </p>

```<code>//Step1 : Make blank attributed string
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:@""];

//Step2 : Append placeholder to blank attributed string
NSString *strSearchHere = @"Search here...";
NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subString = [[NSAttributedString alloc] initWithString:strSearchHere attributes:attributes];
[attributedString appendAttributedString:subString];

//Step3 : Append dummy text to blank attributed string
NSString *strLongText = @"LongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongText";
NSDictionary * attributesLong = [NSDictionary dictionaryWithObject:[UIColor clearColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subStringLong = [[NSAttributedString alloc] initWithString:strLongText attributes:attributesLong];
[attributedString appendAttributedString:subStringLong];

//Step4 : Set attributed placeholder string to searchBar textfield
UITextField *searchTextField = [searchBarr valueForKey:@"_searchField"];
searchTextField.attributedPlaceholder = attributedString;
searchTextField.leftView = nil; //To Remove Search icon
searchTextField.textAlignment = NSTextAlignmentLeft;
</code>```

Body:
To set attributed placeholder text to achieve left aligned placeholder, try this code...

//Step1 : Make blank attributed string
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:@""];

//Step2 : Append placeholder to blank attributed string
NSString *strSearchHere = @"Search here...";
NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subString = [[NSAttributedString alloc] initWithString:strSearchHere attributes:attributes];
[attributedString appendAttributedString:subString];

//Step3 : Append dummy text to blank attributed string
NSString *strLongText = @"LongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongText";
NSDictionary * attributesLong = [NSDictionary dictionaryWithObject:[UIColor clearColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subStringLong = [[NSAttributedString alloc] initWithString:strLongText attributes:attributesLong];
[attributedString appendAttributedString:subStringLong];

//Step4 : Set attributed placeholder string to searchBar textfield
UITextField *searchTextField = [searchBarr valueForKey:@"_searchField"];
searchTextField.attributedPlaceholder = attributedString;
searchTextField.leftView = nil; //To Remove Search icon
searchTextField.textAlignment = NSTextAlignmentLeft;

ContentLicense: CC BY-SA 4.0


问:
goBack.focus() not working in win 10
I am using IE 11 and here I am opening the popup window. There is a point from where I can turn my focus to the parent window.

The code is like this-

```<code>var goBack = window.open('', 'parent');
                goBack.focus();
</code>```

Now, this works fine in all the IE 11 which I tested but fails in Win 10 pro version IE. And I not understanding why. Could anyone point me in right direction?

This is IE version which is not working

Update:I have tried something window.opener.focus(); it works but same fails in chrome

答:
I'm not sure if this applicable for IE11 but from the https://msdn.microsoft.com/ru-ru/library/ms536651(v=vs.85).aspx

Internet Explorer 7 on Windows Vista: Opening a new window from an application (other than the Internet Explorer process) may result in a null return value. This restriction occurs because Internet Explorer runs in protected mode, by default. One facet of protected mode prevents applications from having privileged access to Internet Explorer when that access spans process boundaries. Opening a new window by using this method generates a new process. For more information about protected mode, see Understanding and Working in Protected Mode Internet Explorer. This commonly occurs for applications that host the WebBrowser control.

Title: goBack.focus() not working in win 10

Body:
I am using IE 11 and here I am opening the popup window. There is a point from where I can turn my focus to the parent window.

The code is like this-

var goBack = window.open('', 'parent');
                goBack.focus();

Now, this works fine in all the IE 11 which I tested but fails in Win 10 pro version IE. And I not understanding why. Could anyone point me in right direction?

This is IE version which is not working

Update:I have tried something window.opener.focus(); it works but same fails in chrome


问:
Stock PrestaShop
I'm totally new in PrestaShop. I'm stuck with an issue, can't find in code where PrestaShop subtracts items from stock.

When customer create an order and choose payment, item is subtract from stock, but if customer doesn't pay and go back, item doesn't return to stock. So I need to understand where it's happening in code, for to write function which does it automatically.

答:
In the PaymentModule::validateOrder there is a call to the OrderDetail->createList with:

```<code>// Insert new Order detail list using cart for the current order
$order_detail = new OrderDetail(null, null, $this->context);
$order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
$order_detail_list[] = $order_detail;
</code>```

In OrderDetail->createList we have a call to $this->create foreach product in the list. This is where that order detail data is "calculated", and there is a $this->checkProductStock($product, $id_order_state); that checks if the order is not canceled and not an error and if that product depends on stock:

```<code>protected function checkProductStock($product, $id_order_state)
{
    if ($id_order_state != Configuration::get('PS_OS_CANCELED') && $id_order_state != Configuration::get('PS_OS_ERROR')) {
        $update_quantity = true;
        if (!StockAvailable::dependsOnStock($product['id_product'])) {
            $update_quantity = StockAvailable::updateQuantity($product['id_product'], $product['id_product_attribute'], -(int)$product['cart_quantity']);
        }

        if ($update_quantity) {
            $product['stock_quantity'] -= $product['cart_quantity'];
        }

        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
            $this->outOfStock = true;
        }
        Product::updateDefaultAttribute($product['id_product']);
    }
}
</code>```

Btw, if you cancel an order, the stock is reset with that order amount.

But if you want to only decrease stock after payment, in your case I would add a config PS_WAITING_PAYMENT with the value the orders have if not confirmed, then override this last function to add the state awaiting payment

```<code>protected function checkProductStock($product, $id_order_state)
{
    if ($id_order_state != Configuration::get('PS_OS_CANCELED') && $id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_WAITING_PAYMENT')) {
        $update_quantity = true;
        if (!StockAvailable::dependsOnStock($product['id_product'])) {
            $update_quantity = StockAvailable::updateQuantity($product['id_product'], $product['id_product_attribute'], -(int)$product['cart_quantity']);
        }

        if ($update_quantity) {
            $product['stock_quantity'] -= $product['cart_quantity'];
        }

        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
            $this->outOfStock = true;
        }
        Product::updateDefaultAttribute($product['id_product']);
    }
}
</code>```

If you set the Waiting payment order state to not logable, and the new state is logable, when you change the state to confirmed payment it should decrease stock, because in OrderHistory->changeIdOrderState there is:

```<code>...
foreach ($order->getProductsDetail() as $product) {
    if (Validate::isLoadedObject($old_os)) {
        // if becoming logable => adds sale
        if ($new_os->logable && !$old_os->logable) {
            ProductSale::addProductSale($product['product_id'], $product['product_quantity']);
            // @since 1.5.0 - Stock Management
            if (!Pack::isPack($product['product_id']) &&
                in_array($old_os->id, $error_or_canceled_statuses) &&
                !StockAvailable::dependsOnStock($product['id_product'], (int)$order->id_shop)) {
                StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], -(int)$product['product_quantity'], $order->id_shop);
            }
        }
    ...
</code>```

Title: Stock PrestaShop

Body:
In the PaymentModule::validateOrder there is a call to the OrderDetail->createList with:

// Insert new Order detail list using cart for the current order
$order_detail = new OrderDetail(null, null, $this->context);
$order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
$order_detail_list[] = $order_detail;

In OrderDetail->createList we have a call to $this->create foreach product in the list. This is where that order detail data is "calculated", and there is a $this->checkProductStock($product, $id_order_state); that checks if the order is not canceled and not an error and if that product depends on stock:

protected function checkProductStock($product, $id_order_state)
{
    if ($id_order_state != Configuration::get('PS_OS_CANCELED') && $id_order_state != Configuration::get('PS_OS_ERROR')) {
        $update_quantity = true;
        if (!StockAvailable::dependsOnStock($product['id_product'])) {
            $update_quantity = StockAvailable::updateQuantity($product['id_product'], $product['id_product_attribute'], -(int)$product['cart_quantity']);
        }

        if ($update_quantity) {
            $product['stock_quantity'] -= $product['cart_quantity'];
        }

        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
            $this->outOfStock = true;
        }
        Product::updateDefaultAttribute($product['id_product']);
    }
}

Btw, if you cancel an order, the stock is reset with that order amount.

But if you want to only decrease stock after payment, in your case I would add a config PS_WAITING_PAYMENT with the value the orders have if not confirmed, then override this last function to add the state awaiting payment

protected function checkProductStock($product, $id_order_state)
{
    if ($id_order_state != Configuration::get('PS_OS_CANCELED') && $id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_WAITING_PAYMENT')) {
        $update_quantity = true;
        if (!StockAvailable::dependsOnStock($product['id_product'])) {
            $update_quantity = StockAvailable::updateQuantity($product['id_product'], $product['id_product_attribute'], -(int)$product['cart_quantity']);
        }

        if ($update_quantity) {
            $product['stock_quantity'] -= $product['cart_quantity'];
        }

        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
            $this->outOfStock = true;
        }
        Product::updateDefaultAttribute($product['id_product']);
    }
}

If you set the Waiting payment order state to not logable, and the new state is logable, when you change the state to confirmed payment it should decrease stock, because in OrderHistory->changeIdOrderState there is:

...
foreach ($order->getProductsDetail() as $product) {
    if (Validate::isLoadedObject($old_os)) {
        // if becoming logable => adds sale
        if ($new_os->logable && !$old_os->logable) {
            ProductSale::addProductSale($product['product_id'], $product['product_quantity']);
            // @since 1.5.0 - Stock Management
            if (!Pack::isPack($product['product_id']) &&
                in_array($old_os->id, $error_or_canceled_statuses) &&
                !StockAvailable::dependsOnStock($product['id_product'], (int)$order->id_shop)) {
                StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], -(int)$product['product_quantity'], $order->id_shop);
            }
        }
    ...


问:
Can you test the latest version of Firefox (52 as of now) using Webdriver.io?
I can see that Webdriver.io only supports Selenium 2, and the latest FF is using Selenium 3, so is there any work around to use Webdriver.io for the latest FF? Is Webdriver.io planning to support Selenium 3 anytime soon?</p>

答:
Latest version of firefox needed gecko driver to launch, for this you have to download geckodriver.exe

```<code>System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
</code>```

Body:
Latest version of firefox needed gecko driver to launch, for this you have to download geckodriver.exe

System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


问:
Get Google Map Marker and data from web service
I am stuck at this a point where I have to call Google Map Marker from the web service how can I do this is my web service. What I try is below code which is not working. What I want to do is to use Picasso library to load an icon from the web service.

I don't have too much knowledge about google maps.If any one help me it would be great for me so please.

```<code>public class Frnt_mapActivity extends Activity {

    public String Shop_title;
    public String Shop_address;
    public String Shop_icons;
    ProgressDialog mDialog;
    JSONObject jsonobject3;
    JSONArray jsonarray3;
    // Google Map
    private static GoogleMap googlemap;

    public static ArrayList<SearchBeams> searchdata_list;
    public static ArrayList<NormalSearchBeams> normlSearchList;

    ArrayList<All_products_lat_long> venueList;

    private int i;
    private Intent intent;
    HashMap<Marker, Integer> hashMap=new HashMap<Marker, Integer>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frnt_map_activity);

        googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
        googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googlemap.setMyLocationEnabled(true);
        googlemap.getUiSettings().setZoomControlsEnabled(true);
        googlemap.getUiSettings().setMyLocationButtonEnabled(true);
        googlemap.getUiSettings().setCompassEnabled(true);
        googlemap.getUiSettings().setRotateGesturesEnabled(true);
        googlemap.getUiSettings().setZoomGesturesEnabled(true);
        googlemap.setMyLocationEnabled(true);
        intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
        googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                i=hashMap.get(arg0);
                intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
                startActivity(intent);
                //overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
            }
        });

        new Frnt_mIcons_Activity().execute();

    }
    private void addMarkers() {

        for(int k=0; k<venueList.size(); k += 1){

            //nirmal
            try{
                Log.e("pj",venueList.get(k).getMap_icon());

                //new AddMarkerAsyncTask(venueList.get(k),k).execute();

                double ln = Double.parseDouble(venueList.get(k).getLongitude());
                double la = Double.parseDouble(venueList.get(k).getLatitude());
                String title=venueList.get(k).getPost_title()==null?"":venueList.get(k).getPost_title();
                URL url = new URL(venueList.get(k).getMap_icon());
                Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                BitmapDescriptor bd=BitmapDescriptorFactory.fromBitmap(image);

                Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(la, ln))
                        .title(title)
                        .icon(bd));
                hashMap.put(marker, k);

            }catch (Exception e){
                Log.e("addMarkers",k+"");
                e.printStackTrace();
            }

        }
    }

    /******************FOR MAP******************/
    class Frnt_mIcons_Activity extends AsyncTask<String, String, String> {

        public ArrayList<All_products_lat_long> maplist;

        @Override
        protected void onPreExecute() {
            mDialog = new ProgressDialog(Frnt_mapActivity.this);
            mDialog.setMessage("Loading...");
            mDialog.setCancelable(false);
            mDialog.show();
            super.onPreExecute();
        }

        // Slow Implementation
        private String inputStreamToString(InputStream is) {
            String s = "";
            String line = "";
            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            // Read response until the end
            try {
                while ((line = rd.readLine()) != null) {
                    s += line;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // Return full string
            return s;
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            maplist = new ArrayList<All_products_lat_long>();

            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("http", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

            HttpPost httpPost = new HttpPost("http://towncitycards.com/webservice_action.php?action=all_products");

            try{

                HttpResponse response = httpClient.execute(httpPost);
                String data = inputStreamToString(response.getEntity().getContent());
                jsonobject3 = new JSONObject(data);
                jsonarray3 = new JSONArray(jsonobject3.getString("all_products"));
                venueList =new ArrayList<All_products_lat_long>();
                for(int j=0; j<jsonarray3.length();j++){
                    JSONObject itemobj = jsonarray3.getJSONObject(j);
                    //SHOW SEARCH RESULT
                    All_products_lat_long searchItems = new All_products_lat_long();

                    searchItems.setId(itemobj.getString("ID"));
                    searchItems.setPost_title(itemobj.getString("post_title"));
                    searchItems.setMap_icon(itemobj.getString("map_icon"));
                    searchItems.setLongitude(itemobj.getString("longitude"));
                    searchItems.setLatitude(itemobj.getString("latitude"));
                    //          System.out.println("######Ashish is object >>"+itemobj);
                    venueList.add(searchItems);
                    //      System.out.println("SEARCHLISTSS@@@@@@@"+venueList.get(j).getLongitude());
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public void onPostExecute(String result) {
            super.onPostExecute(result);

            //System.out.println("SEARCHLISTSS@@@@@@@"+venueList);
            //System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAA"+venueList);
            try{
                if(venueList.size()>0)
                {
                    addMarkers();
                    //Toast.makeText(Frnt_mapActivity.this,"Search for the venue11.",Toast.LENGTH_SHORT).show();

                }
                else
                    Toast.makeText(Frnt_mapActivity.this,"Search for the venue.",Toast.LENGTH_SHORT).show();
                //LatLng coordinate = new LatLng(22.75852160, 75.8911550);
                LatLng coordinate = new LatLng(50.85514, 0.58382);
                CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 18);
                googlemap.animateCamera(yourLocation);
                for (int i = 0; i < jsonarray3.length(); i++) {

                    jsonobject3 = jsonarray3.getJSONObject(i);

                    Shop_title = jsonobject3.optString("post_title");
                    Shop_address = jsonobject3.optString("map_icon");
                    Shop_icons = jsonobject3.optString("map_icon");
                    //}
                }

            }catch(Exception e){
                e.printStackTrace();
            }

            if(mDialog!=null && mDialog.isShowing()){
                mDialog.dismiss();
            }
        }
    }

}
</code>```

Log :

```<code>03-30 14:47:19.467 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/5percent.png
03-30 14:47:20.798 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save£2.png
03-30 14:47:20.798 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.799 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.800 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.800 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.801 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/freedrink.png
03-30 14:47:20.801 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.802 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.802 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.803 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.803 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.804 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/freedrink.png
03-30 14:47:20.804 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/freedessert.png
03-30 14:47:20.837 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save£2.png
03-30 14:47:20.837 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
</code>```

It is get all url but not showing icon
Here is a emulator image:

答:
Try this code:

import :

```<code>import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
</code>```

`
create a class:

```<code> public class PicassoMarker implements Target {
        Marker mMarker;

        PicassoMarker(Marker marker) {
            mMarker = marker;
        }

        @Override
        public int hashCode() {
            return mMarker.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof PicassoMarker) {
                Marker marker = ((PicassoMarker) o).mMarker;
                return mMarker.equals(marker);
            } else {
                return false;
            }
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    }
</code>```

Now modify your addMarkers() method to:

```<code> private void addMarkers() {
    for (int k = 0; k < venueList.size(); k += 1) {
        try {
            Log.e("pj", venueList.get(k).getMap_icon());

            //new AddMarkerAsyncTask(venueList.get(k),k).execute();

            double ln = Double.parseDouble(venueList.get(k).getLongitude());
            double la = Double.parseDouble(venueList.get(k).getLatitude());
            String title = venueList.get(k).getPost_title() == null ? "" : venueList.get(k).getPost_title();

            Marker marker = googlemap.addMarker(new MarkerOptions()
                    .position(new LatLng(la, ln))
                    .title(title));

            PicassoMarker pmarker = new PicassoMarker(marker);
            Picasso.with(MainActivity.this).setLoggingEnabled(true).fit().load(venueList.get(k).getMap_icon()).into(pmarker);
            hashMap.put(marker, k);

        } catch (Exception e) {
            Log.e("addMarkers", k + "");
            e.printStackTrace();
        }
    }
}
</code>```

the PicassoMarker class is inspired from this Answer

i added some modification in your addMarkers() method

Body:
I am stuck at this a point where I have to call Google Map Marker from the web service how can I do this is my web service. What I try is below code which is not working. What I want to do is to use Picasso library to load an icon from the web service.

I don't have too much knowledge about google maps.If any one help me it would be great for me so please.

public class Frnt_mapActivity extends Activity {

    public String Shop_title;
    public String Shop_address;
    public String Shop_icons;
    ProgressDialog mDialog;
    JSONObject jsonobject3;
    JSONArray jsonarray3;
    // Google Map
    private static GoogleMap googlemap;

    public static ArrayList<SearchBeams> searchdata_list;
    public static ArrayList<NormalSearchBeams> normlSearchList;

    ArrayList<All_products_lat_long> venueList;

    private int i;
    private Intent intent;
    HashMap<Marker, Integer> hashMap=new HashMap<Marker, Integer>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frnt_map_activity);

        googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
        googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googlemap.setMyLocationEnabled(true);
        googlemap.getUiSettings().setZoomControlsEnabled(true);
        googlemap.getUiSettings().setMyLocationButtonEnabled(true);
        googlemap.getUiSettings().setCompassEnabled(true);
        googlemap.getUiSettings().setRotateGesturesEnabled(true);
        googlemap.getUiSettings().setZoomGesturesEnabled(true);
        googlemap.setMyLocationEnabled(true);
        intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
        googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                i=hashMap.get(arg0);
                intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
                startActivity(intent);
                //overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
            }
        });

        new Frnt_mIcons_Activity().execute();

    }
    private void addMarkers() {

        for(int k=0; k<venueList.size(); k += 1){

            //nirmal
            try{
                Log.e("pj",venueList.get(k).getMap_icon());

                //new AddMarkerAsyncTask(venueList.get(k),k).execute();

                double ln = Double.parseDouble(venueList.get(k).getLongitude());
                double la = Double.parseDouble(venueList.get(k).getLatitude());
                String title=venueList.get(k).getPost_title()==null?"":venueList.get(k).getPost_title();
                URL url = new URL(venueList.get(k).getMap_icon());
                Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                BitmapDescriptor bd=BitmapDescriptorFactory.fromBitmap(image);

                Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(la, ln))
                        .title(title)
                        .icon(bd));
                hashMap.put(marker, k);

            }catch (Exception e){
                Log.e("addMarkers",k+"");
                e.printStackTrace();
            }

        }
    }

    /******************FOR MAP******************/
    class Frnt_mIcons_Activity extends AsyncTask<String, String, String> {

        public ArrayList<All_products_lat_long> maplist;

        @Override
        protected void onPreExecute() {
            mDialog = new ProgressDialog(Frnt_mapActivity.this);
            mDialog.setMessage("Loading...");
            mDialog.setCancelable(false);
            mDialog.show();
            super.onPreExecute();
        }

        // Slow Implementation
        private String inputStreamToString(InputStream is) {
            String s = "";
            String line = "";
            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            // Read response until the end
            try {
                while ((line = rd.readLine()) != null) {
                    s += line;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // Return full string
            return s;
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            maplist = new ArrayList<All_products_lat_long>();

            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("http", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

            HttpPost httpPost = new HttpPost("http://towncitycards.com/webservice_action.php?action=all_products");

            try{

                HttpResponse response = httpClient.execute(httpPost);
                String data = inputStreamToString(response.getEntity().getContent());
                jsonobject3 = new JSONObject(data);
                jsonarray3 = new JSONArray(jsonobject3.getString("all_products"));
                venueList =new ArrayList<All_products_lat_long>();
                for(int j=0; j<jsonarray3.length();j++){
                    JSONObject itemobj = jsonarray3.getJSONObject(j);
                    //SHOW SEARCH RESULT
                    All_products_lat_long searchItems = new All_products_lat_long();

                    searchItems.setId(itemobj.getString("ID"));
                    searchItems.setPost_title(itemobj.getString("post_title"));
                    searchItems.setMap_icon(itemobj.getString("map_icon"));
                    searchItems.setLongitude(itemobj.getString("longitude"));
                    searchItems.setLatitude(itemobj.getString("latitude"));
                    //          System.out.println("######Ashish is object >>"+itemobj);
                    venueList.add(searchItems);
                    //      System.out.println("SEARCHLISTSS@@@@@@@"+venueList.get(j).getLongitude());
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public void onPostExecute(String result) {
            super.onPostExecute(result);

            //System.out.println("SEARCHLISTSS@@@@@@@"+venueList);
            //System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAA"+venueList);
            try{
                if(venueList.size()>0)
                {
                    addMarkers();
                    //Toast.makeText(Frnt_mapActivity.this,"Search for the venue11.",Toast.LENGTH_SHORT).show();

                }
                else
                    Toast.makeText(Frnt_mapActivity.this,"Search for the venue.",Toast.LENGTH_SHORT).show();
                //LatLng coordinate = new LatLng(22.75852160, 75.8911550);
                LatLng coordinate = new LatLng(50.85514, 0.58382);
                CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 18);
                googlemap.animateCamera(yourLocation);
                for (int i = 0; i < jsonarray3.length(); i++) {

                    jsonobject3 = jsonarray3.getJSONObject(i);

                    Shop_title = jsonobject3.optString("post_title");
                    Shop_address = jsonobject3.optString("map_icon");
                    Shop_icons = jsonobject3.optString("map_icon");
                    //}
                }

            }catch(Exception e){
                e.printStackTrace();
            }

            if(mDialog!=null && mDialog.isShowing()){
                mDialog.dismiss();
            }
        }
    }

}

Log :

03-30 14:47:19.467 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/5percent.png
03-30 14:47:20.798 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save£2.png
03-30 14:47:20.798 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.799 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.800 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.800 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.801 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/freedrink.png
03-30 14:47:20.801 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.802 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.802 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.803 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.803 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png
03-30 14:47:20.804 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/freedrink.png
03-30 14:47:20.804 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/freedessert.png
03-30 14:47:20.837 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save£2.png
03-30 14:47:20.837 2895-2895/com.towncitycards E/pj: http://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/10percent.png

It is get all url but not showing icon
Here is a emulator image:

Body:
Try this code:

import :

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

`
create a class:

 public class PicassoMarker implements Target {
        Marker mMarker;

        PicassoMarker(Marker marker) {
            mMarker = marker;
        }

        @Override
        public int hashCode() {
            return mMarker.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof PicassoMarker) {
                Marker marker = ((PicassoMarker) o).mMarker;
                return mMarker.equals(marker);
            } else {
                return false;
            }
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    }

Now modify your addMarkers() method to:

 private void addMarkers() {
    for (int k = 0; k < venueList.size(); k += 1) {
        try {
            Log.e("pj", venueList.get(k).getMap_icon());

            //new AddMarkerAsyncTask(venueList.get(k),k).execute();

            double ln = Double.parseDouble(venueList.get(k).getLongitude());
            double la = Double.parseDouble(venueList.get(k).getLatitude());
            String title = venueList.get(k).getPost_title() == null ? "" : venueList.get(k).getPost_title();

            Marker marker = googlemap.addMarker(new MarkerOptions()
                    .position(new LatLng(la, ln))
                    .title(title));

            PicassoMarker pmarker = new PicassoMarker(marker);
            Picasso.with(MainActivity.this).setLoggingEnabled(true).fit().load(venueList.get(k).getMap_icon()).into(pmarker);
            hashMap.put(marker, k);

        } catch (Exception e) {
            Log.e("addMarkers", k + "");
            e.printStackTrace();
        }
    }
}

the PicassoMarker class is inspired from this Answer

i added some modification in your addMarkers() method


问:
PHP key value pair array to strings
Let's say I have an array that looks like this:

```<code>$args = array(
  'format' => 'file',
  'type' => 'page',
  'name' => 'Projects',
  'template' => 'default'
);
</code>```

To get the values from the array keys I need to do this:

```<code>echo $args['format'];
echo $args['type'];
echo $args['name'];
echo $args['template'];
</code>```

While it works, it feels more messy than needed. Is there a proper way to somehow convert it to this?

```<code>echo $format;
echo $type;
echo $name;
echo $template;
</code>```

I'm aware of list but that only uses values and not keys.

答:
We can easily print the array value using foreach() loop if we don't use to list() as you mention then use extract() method like below:

```<code>$args = array(
        'format' => 'file',
        'type' => 'page',
        'name' => 'Projects',
        'template' => 'default'
    );
     extract($args);

    echo $format."<br/>".$type."<br/>".$name."<br/>".$template;
</code>```

Title: PHP key value pair array to strings

Body:
Let's say I have an array that looks like this:

$args = array(
  'format' => 'file',
  'type' => 'page',
  'name' => 'Projects',
  'template' => 'default'
);

To get the values from the array keys I need to do this:

echo $args['format'];
echo $args['type'];
echo $args['name'];
echo $args['template'];

While it works, it feels more messy than needed. Is there a proper way to somehow convert it to this?

echo $format;
echo $type;
echo $name;
echo $template;

I'm aware of list but that only uses values and not keys.

Body:
We can easily print the array value using foreach() loop if we don't use to list() as you mention then use extract() method like below:

$args = array(
        'format' => 'file',
        'type' => 'page',
        'name' => 'Projects',
        'template' => 'default'
    );
     extract($args);

    echo $format."<br/>".$type."<br/>".$name."<br/>".$template;


问:
Convert wav to mp3 and back to wav
I'm using an NAudio wrapper for LAME to convert my wav file to mp3.  However, when I use NAudio to convert my mp3 back to wav, the wav file is a bit larger than the original wav file.  Is there a way I can get it so that the original and decoded wav files are exactly the same size?   Aside from this everything else works and I'm able to play the wav and mp3 files without issue.   Thanks and I have included my conversion functions below:</p>

```<code>private void ConvertWavMP3(string wavFile)
    {
        try
        {
            using (var wavRdr = new WaveFileReader(wavFile))
            using (var mp3Writer = new LameMP3FileWriter(wavFile.Replace(".wav", ".mp3"), wavRdr.WaveFormat, 128))
            {
                wavRdr.CopyTo(mp3Writer);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error converting wav to mp3.", "CONVERSION ERROR");
        }
    }

    private static void ConvertMp3ToWav(string mp3File)
    {
        try
        {
            using (Mp3FileReader reader = new Mp3FileReader(mp3File))
            {
                //using (WaveStream pcmStream = new WaveFormatConversionStream(new WaveFormat(8000, 16, 1), reader))
                using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
                {
                    WaveFileWriter.CreateWaveFile(mp3File.Replace(".mp3", ".wav"), pcmStream);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error converting mp3 to wav.", "CONVERSION ERROR");
        }
    }
</code>```

答: MP3 is a lossy codec so it doesn't decompress to the exact same audio that you encoded. It also works by creating a series of encoded "frames", each of which has a fixed length, so the decoded MP3 will usually not be exactly the same duration as the input, but a few milliseconds longer. </p>

Title: Convert wav to mp3 and back to wav

Body:
I'm using an NAudio wrapper for LAME to convert my wav file to mp3.  However, when I use NAudio to convert my mp3 back to wav, the wav file is a bit larger than the original wav file.  Is there a way I can get it so that the original and decoded wav files are exactly the same size?   Aside from this everything else works and I'm able to play the wav and mp3 files without issue.   Thanks and I have included my conversion functions below:

private void ConvertWavMP3(string wavFile)
    {
        try
        {
            using (var wavRdr = new WaveFileReader(wavFile))
            using (var mp3Writer = new LameMP3FileWriter(wavFile.Replace(".wav", ".mp3"), wavRdr.WaveFormat, 128))
            {
                wavRdr.CopyTo(mp3Writer);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error converting wav to mp3.", "CONVERSION ERROR");
        }
    }

    private static void ConvertMp3ToWav(string mp3File)
    {
        try
        {
            using (Mp3FileReader reader = new Mp3FileReader(mp3File))
            {
                //using (WaveStream pcmStream = new WaveFormatConversionStream(new WaveFormat(8000, 16, 1), reader))
                using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
                {
                    WaveFileWriter.CreateWaveFile(mp3File.Replace(".mp3", ".wav"), pcmStream);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error converting mp3 to wav.", "CONVERSION ERROR");
        }
    }


问:
Got an error while running vagrant ssh
I have install VM, docker-engine following a book. All command work correctly, no error found there.

But when i run this in terminal

```<code>vagrant ssh
</code>```

I got this error

```<code>==> dev: The container is not currently running.
</code>```

I google this and follow several answer from github issue and stackoverflow but can't overcome this error.

N.B: I am fairly new to Vagrant and Docker both

答:
Problem solved.

I fixed it by patching host_machine_port_checker.rb and adding an extra argument I discard in port_check:

```<code>def port_check(discard_this, port)
    host_machine = @machine.provider.host_vm
    host_machine.guest.capability(:port_open_check, port)
end
</code>```

Thanks Dimitrios Kouzis-Loukas.

Title: Got an error while running vagrant ssh

Body:
I have install VM, docker-engine following a book. All command work correctly, no error found there.

But when i run this in terminal

vagrant ssh

I got this error

==> dev: The container is not currently running.

I google this and follow several answer from github issue and stackoverflow but can't overcome this error.

N.B: I am fairly new to Vagrant and Docker both

Body:
Problem solved.

I fixed it by patching host_machine_port_checker.rb and adding an extra argument I discard in port_check:

def port_check(discard_this, port)
    host_machine = @machine.provider.host_vm
    host_machine.guest.capability(:port_open_check, port)
end

Thanks Dimitrios Kouzis-Loukas.


问:
Spring Boot Thymeleaf th:include dynamic templates
I am using Spring Boot v1.5.2.RELEASE and Thymeleaf.

I use

.
It works fine, but now I have a special requirement that I want to include a path in the controller like this:

```<code><div th:include="praxis/header"></div>

@Controller
@RequestMapping(path = "/praxis")
public class UserController extends BaseController {
@GetMapping(value = "/header")
    public ModelAndView praxisHeader(HttpServletRequest request) {
        //do sth
        return new ModelAndView("some other templates", "user", user);
    }
}
</code>```

It does not work because th:include can only include templates from the "resource" folder.

How can I include a template from the controller?

答:
th:include can only include fragments from other templates, it cannot include data from the controller.

If you want to send data from the controller to the template you should create a map, set the content you want to send as the value of some key in this map, and send this map as model using this API:

```<code>public ModelAndView(String viewName, Map<String,?> model)
</code>```

Now, you have it in the template and you can use it in any way you want.

Body:
I am using Spring Boot v1.5.2.RELEASE and Thymeleaf.

I use

.
It works fine, but now I have a special requirement that I want to include a path in the controller like this:

@Controller
@RequestMapping(path = "/praxis")
public class UserController extends BaseController {
@GetMapping(value = "/header")
    public ModelAndView praxisHeader(HttpServletRequest request) {
        //do sth
        return new ModelAndView("some other templates", "user", user);
    }
}

It does not work because th:include can only include templates from the "resource" folder.

How can I include a template from the controller?

Body:
th:include can only include fragments from other templates, it cannot include data from the controller.

If you want to send data from the controller to the template you should create a map, set the content you want to send as the value of some key in this map, and send this map as model using this API:

public ModelAndView(String viewName, Map<String,?> model)

Now, you have it in the template and you can use it in any way you want.


问:
Low memory image resizing
I am looking for some advice on how to construct a very low memory image resizing program that will be run as a child process of my nodejs application in linux.

The solution I am looking for is a linux executable that will take a base64 string image (uploaded from a client) using stdin, resizing the photo to a specified size and then pumping the resulting image data back through stdout.

I've looked into image magick and it might be what I end up using, but I figured I would ask and see if anyone had a suggestion.

Suggestions of libraries or examples of pre compiled executables in C/C++ would be greatly appreciated. Also a helpful answer would include general strategies for low memory image resizing.

Thank you

答:
if anything this is just a sample following what he described:

```<code>import sys
from PIL import Image
import binascii
import cStringIO
x,y = sys.stdin.readline().strip().split(' ')
x,y = int(x), int(y)
img = Image.open(cStringIO.StringIO(binascii.b2a_base64(sys.stdin.read())).resize(x,y)
img.save(sys.stdout, format="png")
</code>```

as that has to read the input, decode it, resize, and encode, and write it out there is no way to reduce the size of the memory used to less then the size of the input image

Title: Low memory image resizing

Body:
if anything this is just a sample following what he described:

import sys
from PIL import Image
import binascii
import cStringIO
x,y = sys.stdin.readline().strip().split(' ')
x,y = int(x), int(y)
img = Image.open(cStringIO.StringIO(binascii.b2a_base64(sys.stdin.read())).resize(x,y)
img.save(sys.stdout, format="png")

as that has to read the input, decode it, resize, and encode, and write it out there is no way to reduce the size of the memory used to less then the size of the input image


问:
Bash - Why doesn't sfdisk work in this script?
UPDATE: As per suggestions, I have asked this question of the Superuser community. I told them you say hi ;)

https://superuser.com/questions/1193808/why-doesnt-this-sfdisk-script-work

This has been a painful process. Perhaps there's something simple I'm missing..?

I'm trying to create a script to automatically partition a disk with a gpt table and 1 partition that takes up all the space. Should be super simple and straight forward..

I found the sfdisk command which is the (supposedly) script-friendly version of fdisk.

The best I've got so far is:

```<code>sfdisk --color=always --wipe always --no-reread --no-act --label gpt /dev/sdc
</code>```

There's the matter of the partition type, which is to be Linux Filesystem (is that a good choice for a data drive?). The GUID for that is 0FC63DAF-8483-4772-8E79-3D69D8477DE4

When I run the above command, I get an interactive prompt. This is a bit of a problem for my script ;)

What of the input/output format described in the man pages?

<name>: <value>, <name>: <value>, ...

It seems to be suggesting I do something like:

echo 'label: gpt' | --color=always --wipe always --no-reread --no-act /dev/sdc

but, alas, that fails harder than the above. :(

```<code>Partitioning /dev/sdc...

Disk /dev/sdc: 2.7 TiB, 3000592982016 bytes, 5860533168 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 4096 bytes I/O size (minimum/optimal): 4096 bytes / 4096 bytes

>>> line 1: unsupported command

New situation: Leaving.
</code>```

Then there's the dumpfile I caught wind of in the depths of the man pages. It seems to suggest that I can create these cursed things, cat them, and pipe to sfdisk. (Un?)fortunately, I can't hardcode most of this so the solution won't work for me:

```<code>label: gpt
label-id: 236AEC41-D407-4FE5-94FA-8550C2CA10B5
device: /dev/sdc
unit: sectors
first-lba: 2048
last-lba: 5860533134

/dev/sdc1 : start=        2048, size=  5860531087, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4,uuid=8D7D48B0-8BF5-4383-B0EC-615C0E8AF4B4
</code>```

What am I doing wrong!?
Thanks :)

答:
I found a better way: sgdisk

```<code>sgdisk --clear $blkdev
sgdisk --new=0:0:0 --typecode=0:0FC63DAF-8483-4772-8E79-3D69D8477DE4 $blkdev
</code>```

Body:
UPDATE: As per suggestions, I have asked this question of the Superuser community. I told them you say hi ;)

https://superuser.com/questions/1193808/why-doesnt-this-sfdisk-script-work

This has been a painful process. Perhaps there's something simple I'm missing..?

I'm trying to create a script to automatically partition a disk with a gpt table and 1 partition that takes up all the space. Should be super simple and straight forward..

I found the sfdisk command which is the (supposedly) script-friendly version of fdisk.

The best I've got so far is:

sfdisk --color=always --wipe always --no-reread --no-act --label gpt /dev/sdc

There's the matter of the partition type, which is to be Linux Filesystem (is that a good choice for a data drive?). The GUID for that is 0FC63DAF-8483-4772-8E79-3D69D8477DE4

When I run the above command, I get an interactive prompt. This is a bit of a problem for my script ;)

What of the input/output format described in the man pages?

<name>: <value>, <name>: <value>, ...

It seems to be suggesting I do something like:

echo 'label: gpt' | --color=always --wipe always --no-reread --no-act /dev/sdc

but, alas, that fails harder than the above. :(

Partitioning /dev/sdc...

Disk /dev/sdc: 2.7 TiB, 3000592982016 bytes, 5860533168 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 4096 bytes I/O size (minimum/optimal): 4096 bytes / 4096 bytes

>>> line 1: unsupported command

New situation: Leaving.

Then there's the dumpfile I caught wind of in the depths of the man pages. It seems to suggest that I can create these cursed things, cat them, and pipe to sfdisk. (Un?)fortunately, I can't hardcode most of this so the solution won't work for me:

label: gpt
label-id: 236AEC41-D407-4FE5-94FA-8550C2CA10B5
device: /dev/sdc
unit: sectors
first-lba: 2048
last-lba: 5860533134

/dev/sdc1 : start=        2048, size=  5860531087, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4,uuid=8D7D48B0-8BF5-4383-B0EC-615C0E8AF4B4

What am I doing wrong!?
Thanks :)

Body:
I found a better way: sgdisk

sgdisk --clear $blkdev
sgdisk --new=0:0:0 --typecode=0:0FC63DAF-8483-4772-8E79-3D69D8477DE4 $blkdev


问:
CakePHP 3 - Comparing and modifying dates
In the CakePHP 3 Cookbook on Date/Time, you can compare time intervals with future/past days/weeks using IsWithinNext/WasWithinNext. You can also modify dates/times by doing a ->modify('extra time') - eg. if $date = 2016-01-01, $date->modify('+1 week') would mean $date = 2016-01-08.

These features require the use of Cake\i18n\Time. However, when I attempted to use these features, I received a Cake error:

Call to a member function isWithinNext() on string.

This is the code I used:

```<code>$date_start = \Cake\Database\Type::build('date')->marshal($data['session']['date_start'])->i18nFormat(); //before hand my dates were in the form of an array comprised of Year, Month and Day. This changes them into date format.
if($date_start->isWithinNext('1 week')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+48 hours');
} elseif ($date_start->isWithinNext('2 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} elseif ($date_start->isWithinNext('3 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} else {
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+2 weeks');
}
</code>```

答:
Calling i18nFormat() returns a formatted string as you can look up in the API: https://api.cakephp.org/3.4/class-Cake.I18n.DateFormatTrait.html#_i18nFormat

This, for example, should work:

```<code>$date_start = new \Cake\I18n\Time($data['session']['date_start']);
debug($date_start->isWithinNext('2 weeks'));
</code>```

Body:
In the CakePHP 3 Cookbook on Date/Time, you can compare time intervals with future/past days/weeks using IsWithinNext/WasWithinNext. You can also modify dates/times by doing a ->modify('extra time') - eg. if $date = 2016-01-01, $date->modify('+1 week') would mean $date = 2016-01-08.

These features require the use of Cake\i18n\Time. However, when I attempted to use these features, I received a Cake error:

Call to a member function isWithinNext() on string.

This is the code I used:

$date_start = \Cake\Database\Type::build('date')->marshal($data['session']['date_start'])->i18nFormat(); //before hand my dates were in the form of an array comprised of Year, Month and Day. This changes them into date format.
if($date_start->isWithinNext('1 week')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+48 hours');
} elseif ($date_start->isWithinNext('2 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} elseif ($date_start->isWithinNext('3 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} else {
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+2 weeks');
}

Body:
Calling i18nFormat() returns a formatted string as you can look up in the API: https://api.cakephp.org/3.4/class-Cake.I18n.DateFormatTrait.html#_i18nFormat

This, for example, should work:

$date_start = new \Cake\I18n\Time($data['session']['date_start']);
debug($date_start->isWithinNext('2 weeks'));


问:
select row under condition of points distance
I have two data set crime and camera.(first pic is crime- Lon is Longitude , Lat is Latitude; second is camera- X is Longitude , Y is Latitude)

My purpose is select all the crimes whose distance are smaller than 200 feet within camera 89('OBJECTID'=89). In sql, it should be like

```<code>select*
from crime
where "distance with camera89" < 200feet
</code>```

```<code>import pandas as pd
from geopy.distance import vincenty

crime = pd.read_csv('/Users/xccxken/Desktop/crime.csv',low_memory=False)
camera = pd.read_csv('/Users/xccxken/Desktop/camera.csv')

def xycamera(id):
    row=camera[camera['OBJECTID'] == id]
    x = row[['X']]
    y = row[['Y']]
    return x,y

print (xycamera(89))

c200 = crime[vincenty((crime['Lon'],crime['Lat']),xycamera(89)).feet>200]
</code>```

I have a ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). in
c200=crime[vincenty((crime['Lon'],crime['Lat']),xycamera(89)).feet>200]

I hope some one can tell me how to fix it.

And it would be better if there's a better method to achieve my goal. Thanks!

Here is a example of how to use vincenty()
and https://pypi.python.org/pypi/geopy if you need

```<code>>>> from geopy.distance import vincenty
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(vincenty(newport_ri, cleveland_oh).miles)
538.3904451566326
</code>```

答:
I don't know how vincenty() expects your coordinates (tuples or whatnot), but for sure you are missing an opening parenthesis on your last line. (or you have an extra closing one). Based on your example, probably the parenthesis after .feet is the extra one

Try this one:

```<code>cameraCoords = xycamera(89)
vincenty((11,11),(12,12)).feet
crime[vincenty((crime['Lon'],crime['Lat']),cameraCoords ).feet>200]
</code>```

run this one, paste your whole code and paste here the WHOLE traceback

Body:
I have two data set crime and camera.(first pic is crime- Lon is Longitude , Lat is Latitude; second is camera- X is Longitude , Y is Latitude)

My purpose is select all the crimes whose distance are smaller than 200 feet within camera 89('OBJECTID'=89). In sql, it should be like

select*
from crime
where "distance with camera89" < 200feet

import pandas as pd
from geopy.distance import vincenty

crime = pd.read_csv('/Users/xccxken/Desktop/crime.csv',low_memory=False)
camera = pd.read_csv('/Users/xccxken/Desktop/camera.csv')

def xycamera(id):
    row=camera[camera['OBJECTID'] == id]
    x = row[['X']]
    y = row[['Y']]
    return x,y

print (xycamera(89))

c200 = crime[vincenty((crime['Lon'],crime['Lat']),xycamera(89)).feet>200]

I have a ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). in
c200=crime[vincenty((crime['Lon'],crime['Lat']),xycamera(89)).feet>200]

I hope some one can tell me how to fix it.

And it would be better if there's a better method to achieve my goal. Thanks!

Here is a example of how to use vincenty()
and https://pypi.python.org/pypi/geopy if you need

>>> from geopy.distance import vincenty
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(vincenty(newport_ri, cleveland_oh).miles)
538.3904451566326

Body:
I don't know how vincenty() expects your coordinates (tuples or whatnot), but for sure you are missing an opening parenthesis on your last line. (or you have an extra closing one). Based on your example, probably the parenthesis after .feet is the extra one

Try this one:

cameraCoords = xycamera(89)
vincenty((11,11),(12,12)).feet
crime[vincenty((crime['Lon'],crime['Lat']),cameraCoords ).feet>200]

run this one, paste your whole code and paste here the WHOLE traceback


问:
Javascript OnClick toggle scroll
This code disables scrolling once a button is clicked, but I can't figure out how to reactivate the scroll. I think the problem might have something to do with:

```<code>window.removeEventListener('scroll', noscroll);
</code>```

I have tested the if/else statement and that seems to work if I, for example, change the background color of the body.

```<code>var isScrollEnabled = true;

document.querySelector('.mobile-button').addEventListener('click', function(event) {
    event.preventDefault();
    document.querySelector('body').classList.toggle("mobile-menu");

    function noscroll() {
        window.scrollTo(0, 0);
    }

    if (isScrollEnabled = true;) {
        window.addEventListener('scroll', noscroll);
        var isScrollEnabled = false;
    } else {
        window.removeEventListener('scroll', noscroll);
        var isScrollEnabled = true;
    }
});
</code>```

答:
Easy fix is to use a global variable:</p>

```<code>var isScrollEnabled = true;
document.querySelector('.mobile-button').addEventListener('click', function(event) {
  event.preventDefault();
  document.querySelector('body').classList.toggle("mobile-menu");

  function noscroll() {
    window.scrollTo(0, 0);
  }

  if ( isScrollEnabled ) {
    window.addEventListener('scroll', noscroll);
    isScrollEnabled = false;
  } else {
    window.removeEventListener('scroll', noscroll);
    isScrollEnabled = true;
  }
});
</code>```

Title: Javascript OnClick toggle scroll

Body:
This code disables scrolling once a button is clicked, but I can't figure out how to reactivate the scroll. I think the problem might have something to do with:

window.removeEventListener('scroll', noscroll);

I have tested the if/else statement and that seems to work if I, for example, change the background color of the body.

var isScrollEnabled = true;

document.querySelector('.mobile-button').addEventListener('click', function(event) {
    event.preventDefault();
    document.querySelector('body').classList.toggle("mobile-menu");

    function noscroll() {
        window.scrollTo(0, 0);
    }

    if (isScrollEnabled = true;) {
        window.addEventListener('scroll', noscroll);
        var isScrollEnabled = false;
    } else {
        window.removeEventListener('scroll', noscroll);
        var isScrollEnabled = true;
    }
});

Body:
Easy fix is to use a global variable:

var isScrollEnabled = true;
document.querySelector('.mobile-button').addEventListener('click', function(event) {
  event.preventDefault();
  document.querySelector('body').classList.toggle("mobile-menu");

  function noscroll() {
    window.scrollTo(0, 0);
  }

  if ( isScrollEnabled ) {
    window.addEventListener('scroll', noscroll);
    isScrollEnabled = false;
  } else {
    window.removeEventListener('scroll', noscroll);
    isScrollEnabled = true;
  }
});