问:
How to force int to string in Laravel JSON?
I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...

I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.

Is there a way to somehow force response()->json() to return int's as string's?

答:
If you don't want to modify a lot of code you could run response data through a quick and dirty function. Instead of going directory to JSON you should instead grab the data as a nested array. Then put it through a function like this:

```<code>function convertIntToString ($myArray) {
    foreach ($myArray as $thisKey => $thisValue) {
        if (is_array($thisValue)) {
            // recurse to handle a nested array
            $myArray[$thisKey] = convertIntToString($thisValue);
        } elseif (is_integer($thisValue)) {
            // convert any integers to a string
            $myArray[$thisKey] = (string) $thisValue;
        }
    }
    return $myArray;
}
</code>```

The function will convert integers to strings and use recursion to handle nested arrays. Take the output from that and then convert it to JSON.

Body:
If you don't want to modify a lot of code you could run response data through a quick and dirty function. Instead of going directory to JSON you should instead grab the data as a nested array. Then put it through a function like this:

function convertIntToString ($myArray) {
    foreach ($myArray as $thisKey => $thisValue) {
        if (is_array($thisValue)) {
            // recurse to handle a nested array
            $myArray[$thisKey] = convertIntToString($thisValue);
        } elseif (is_integer($thisValue)) {
            // convert any integers to a string
            $myArray[$thisKey] = (string) $thisValue;
        }
    }
    return $myArray;
}

The function will convert integers to strings and use recursion to handle nested arrays. Take the output from that and then convert it to JSON.


来源: stackexchange

问:
Developing resolution independent flex web application
Well. I checked this link Flex Cross Resolution Applications and it did not help. Infact, the display varies from browser to browser, (for eg. chrome vs ie8) Chrome has bigger browser window. How to develop flex applications in this case ? I am using values in percentages. However, it doesnt help. A panel which displays properly in IE8, appears big in chrome with text and buttons having same size. How to solve this problem ? Giving fixed width is not a solution. Is there any other way ?</p>

答:
You can use the maxWidth & maxHeight properties of your buttons in concert with setting percentage based width & height.  That will ensure you're buttons (or other components) don't grow bigger than you want regardless of browser stage size.

Another option that could work is breaking your buttons up in Group tags.  Then make the spacing between your groups of buttons percentage-based.

ContentLicense: CC BY-SA 2.5


问:
Grails, executing a javascript by clicking on a column in a table row
I have a view consisting of two lists: products and offers. You can select several rows by checking checkboxes on them and then by clicking on a link, offer lines will be created for each selected product.
Every offer line has the id of the product which I will use to list all offers created for that product in a list below the list of products.

I tried to solve that by using a javascript which should be activated when you click on a link or field in the product list.
The script sends a message to the controller that creates the list of offers for this product and then render a template in this view.

I can just use a link and call the controller and the template will be rendered but of course not the rest of the view.

So I need to have line:

```<code><td><g:link action="listOffers" id="${pb.id}">${pb.volumeOffered}</g:link></td>
</code>```

replaced with something better that can call my javascript-function.
I read somewhere you could put an -onclick="javascript-function" in the g:link tag but it doesn't work.

Below is the most important part of controller and gsp in this case.

In the List.gsp:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```

In the template _AvailableProductData.gsp:

```<code>    <g:each in="${prodBuffer}" status="i" var="pb">
  <tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
                <td><a onclick="listOffers(${pb.id})">${pb.volumeOffered}</a></td>
</code>```

In the template _ListOffers.gsp:

```<code><div id="offerList">
    <g:set var="entityName" value='Offers' />
    <div id="list-offers" class="content scaffold-list" role="main">
        <h1><g:message code="default.list.label" args="[entityName]" /></h1>
        <table style="width:100%">
            <thead>
                <tr>
                    <g:sortableColumn property="product" title='Product' />
                    <g:sortableColumn property="volumeOffered" title='Volume' />
                </tr>
            </thead>
            <tbody>
                <g:each in="${offerDetails}" status="i" var="od">
                    <tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
                        <td><g:link class="edit" action="edit" resource="offerDetail" id="${od?.id}"> ${od.product?.encodeAsHTML()}</g:link></td>
                        <td>${od?.volumeOffered}</td>
                    </tr>
                </g:each>
            </tbody>
        </table>
        <div class="pagination">
            <g:paginate total="${offersCount ?: 0}" />
        </div>
    </div>
</div>
</code>```

In the controller:

```<code>def listOffers(){
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}
</code>```

Added a printout to see what params contains:

```<code>def listOffers(){
    System.out.println("#--#"+params)
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}
</code>```

The printout is:

```<code>#--#[undefined:, controller:ordersAndStore, format:null, action:listOffers]
</code>```

Following is the complete javascript section, the first one is working good but then comes the onclick version that responds and calls the controller but can not send the id. Then comes your version and another one simple but no one is working.

```<code>    <script type="text/javascript">
        function availableProducts(){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'availableProducts' )}',
                    data: [sawMill],
                    type: 'get'
            }).success( function ( data ) { $( '#divToUpdate' ).html( data ); });
        }

        function listOffers(){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

        $( document ).ready( function() {
            $( '.offers' ).click( function ( event ){
                alert('HEJ')
                $.ajax({
                    url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                    data: [this.id],
                    type: 'get'
                }).success( function ( data ) { $( '#offerList' ).html( data ); });
            });
        });
        $( document ).ready( function() {
            $('.test1').bind('click', function (){
            alert('KLICKED');
            });
        });

    </script>
</code>```

And the gsp-part in the template:

```<code>        <g:each in="${prodBuffer}" status="i" var="pb">
            <tr id="{$pb.id}" class="offers" class=" ${ (i % 2) == 0 ? 'even': 'odd'}">
                <td><g:checkBox name="toOffer" value="${pb.id}" checked="false"  /></td>
                <td><g:link action="edit_prodbuffer" id="${pb.id}">${pb.id}</g:link></td>
                <td>${pb.sawMill}</td>
                <td>${pb.product}</td>
                <td>${pb.length}</td>
                <td>${pb.volumeAvailable}</td>
                <td><a  onclick='listOffers()' > ${pb.volumeOffered}</a></td>
</code>```

==================================================

I have taken an old test project which I cleaned and modified to this simple example that still don't work:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>
        <script type="text/javascript">
            $( document ).ready( function() {
                $( '.off1' ).click( function ( event ){
                    alert('HEJ');
                });
            });
        </script>
    </head>
    <body>
        <a href="#list-author" class="skip" tabindex="-1"><g:message code="default.link.skip.label" default="Skip to content…"/></a>
        <div class="nav" role="navigation">
            <ul>
                <li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
                <li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
            </ul>
        </div>
        <div id="list-author" class="content scaffold-list" role="main">
            <h1><g:message code="default.list.label" args="[entityName]" /></h1>
            <g:if test="${flash.message}">
                <div class="message" role="status">${flash.message}</div>
            </g:if>
            <table>
                <th></th>
                <tbody
                    <g:each in="${authorList}" status='i' var='a'>
                        <tr id="${a.id}" class="off1">
                            <td><g:field  type="text" name="author" value="${a?.name}"/> </td>
                        </tr>
                    </g:each>
            <div class="pagination">
                <g:paginate total="${authorCount ?: 0}" />
            </div>
        </div>
    </body>
</html>
</code>```

I begin to be desperate, can't make this work but I must :(
I'll list the code again with some different settings and the output.
Sure something must be wrong with my code as others can make it work but what is wrong?

Part of the GSP-file where things start, there is two alternative lines one is commented here.

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```0

-- Controller:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```1

-- Script A:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```2

-- Script B:

```<code>        $( document ).ready( function() {
            $(".off1").click( function(event){
                alert('HEJ');
            });
        });
</code>```

Script B: never respond - WHY?

Output from controller using script A:

```<code>### --- HEJ --- ### [undefined:, controller:author, format:null, action:listOffers, id:null]
</code>```

Modified script A -- data is empty:

```<code>        function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
</code>```

Output from controller using modified version of script A:

```<code>### --- HEJ --- ### [controller:author, format:null, action:listOffers, id:null]
</code>```

The alert call works ok and I get the correct value of id there.
As yo can see from the controller printout id is null and if data contains id I also get 'undefined:' as a parameter.
If I remove id from data, now data[], this 'undefined:' disappear

答:
The problem was in 2 points.
First: In main.gsp I moved the string:

```<code><asset:javascript src="application.js"/>
</code>```

from the end of the file up to the head close to the css-loading.
This made the script to respond.

But then I couldn't get the data from "id" go in to params.
but by rewriting the row:

```<code>data:[this.id] to data:{id: this.id}
</code>```

it worked.

ContentLicense: CC BY-SA 3.0

Body:
I have a view consisting of two lists: products and offers. You can select several rows by checking checkboxes on them and then by clicking on a link, offer lines will be created for each selected product.
Every offer line has the id of the product which I will use to list all offers created for that product in a list below the list of products.

I tried to solve that by using a javascript which should be activated when you click on a link or field in the product list.
The script sends a message to the controller that creates the list of offers for this product and then render a template in this view.

I can just use a link and call the controller and the template will be rendered but of course not the rest of the view.

So I need to have line:

<g:link action="listOffers" id="${pb.id}">${pb.volumeOffered}</g:link>

replaced with something better that can call my javascript-function.
I read somewhere you could put an -onclick="javascript-function" in the g:link tag but it doesn't work.

Below is the most important part of controller and gsp in this case.

In the List.gsp:

.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>

In the template _AvailableProductData.gsp:

    <g:each in="${prodBuffer}" status="i" var="pb">

                ${pb.volumeOffered}

In the template _ListOffers.gsp:

    <g:set var="entityName" value='Offers' />

<g:message code="default.list.label" args="[entityName]" />

                    <g:sortableColumn property="product" title='Product' />
                    <g:sortableColumn property="volumeOffered" title='Volume' />

                <g:each in="${offerDetails}" status="i" var="od">

                        <g:link class="edit" action="edit" resource="offerDetail" id="${od?.id}"> ${od.product?.encodeAsHTML()}</g:link>
                        ${od?.volumeOffered}

                </g:each>

            <g:paginate total="${offersCount ?: 0}" />

In the controller:

def listOffers(){
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

Added a printout to see what params contains:

def listOffers(){
    System.out.println("#--#"+params)
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

The printout is:

#--#[undefined:, controller:ordersAndStore, format:null, action:listOffers]

Following is the complete javascript section, the first one is working good but then comes the onclick version that responds and calls the controller but can not send the id. Then comes your version and another one simple but no one is working.

And the gsp-part in the template:

        <g:each in="${prodBuffer}" status="i" var="pb">

                <g:checkBox name="toOffer" value="${pb.id}" checked="false"  />
                <g:link action="edit_prodbuffer" id="${pb.id}">${pb.id}</g:link>
                ${pb.sawMill}
                ${pb.product}
                ${pb.length}
                ${pb.volumeAvailable}
                 ${pb.volumeOffered}

==================================================

I have taken an old test project which I cleaned and modified to this simple example that still don't work:

<!DOCTYPE html>

        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>

        <g:message code="default.link.skip.label" default="Skip to content…"/>

<g:message code="default.home.label"/>

<g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link>

<g:message code="default.list.label" args="[entityName]" />

            <g:if test="${flash.message}">

${flash.message}

            </g:if>

                <tbody
                    <g:each in="${authorList}" status='i' var='a'>

                            <g:field  type="text" name="author" value="${a?.name}"/>

                    </g:each>

                <g:paginate total="${authorCount ?: 0}" />

I begin to be desperate, can't make this work but I must :(
I'll list the code again with some different settings and the output.
Sure something must be wrong with my code as others can make it work but what is wrong?

Part of the GSP-file where things start, there is two alternative lines one is commented here.

                <g:each in="${authorList}" status='i' var='a'>

                        <g:field  type="text" name="author" value="${a?.name}"/>

                </g:each>

-- Controller:

def listOffers() {
    System.out.println("### --- HEJ --- ### "+params)
}

-- Script A:

    function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [id],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

-- Script B:

        $( document ).ready( function() {
            $(".off1").click( function(event){
                alert('HEJ');
            });
        });

Script B: never respond - WHY?

Output from controller using script A:

### --- HEJ --- ### [undefined:, controller:author, format:null, action:listOffers, id:null]

Modified script A -- data is empty:

        function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

Output from controller using modified version of script A:

### --- HEJ --- ### [controller:author, format:null, action:listOffers, id:null]

The alert call works ok and I get the correct value of id there.
As yo can see from the controller printout id is null and if data contains id I also get 'undefined:' as a parameter.
If I remove id from data, now data[], this 'undefined:' disappear

Body:
The problem was in 2 points.
First: In main.gsp I moved the string:

<asset:javascript src="application.js"/>

from the end of the file up to the head close to the css-loading.
This made the script to respond.

But then I couldn't get the data from "id" go in to params.
but by rewriting the row:

data:[this.id] to data:{id: this.id}

it worked.


问:
Gson: How to exclude specific fields from Serialization without annotations
I'm trying to learn Gson and I'm struggling with field exclusion. Here are my classes

```<code>public class Student {
  private Long                id;
  private String              firstName        = "Philip";
  private String              middleName       = "J.";
  private String              initials         = "P.F";
  private String              lastName         = "Fry";
  private Country             country;
  private Country             countryOfBirth;
}

public class Country {
  private Long                id;
  private String              name;
  private Object              other;
}
</code>```

I can use the GsonBuilder and add an ExclusionStrategy for a field name like firstName or country but I can't seem to manage to exclude properties of certain fields like country.name.

Using the method public boolean shouldSkipField(FieldAttributes fa), FieldAttributes doesn't contain enough information to match the field with a filter like country.name.

P.S: I want to avoid annotations since I want to improve on this and use RegEx to filter fields out.

Edit: I'm trying to see if it's possible to emulate the behavior of Struts2 JSON plugin

using Gson

```<code><interceptor-ref name="json">
  <param name="enableSMD">true</param>
  <param name="excludeProperties">
    login.password,
    studentList.*\.sin
  </param>
</interceptor-ref>
</code>```

Edit:
    I reopened the question with the following addition:

I added a second field with the same type to futher clarify this problem. Basically I want to exclude country.name but not countrOfBirth.name. I also don't want to exclude Country as a type.
So the types are the same it's the actual place in the object graph that I want to pinpoint and exclude.

答:
I'm working just by putting the @Expose annotation, here my version that I use

```<code>compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
</code>```

In Model class:

```<code>@Expose
int number;

public class AdapterRestApi {
</code>```

In the Adapter class:

```<code>public EndPointsApi connectRestApi() {
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(90000, TimeUnit.SECONDS)
            .readTimeout(90000,TimeUnit.SECONDS).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ConstantRestApi.ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    return retrofit.create  (EndPointsApi.class);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn Gson and I'm struggling with field exclusion. Here are my classes

public class Student {
  private Long                id;
  private String              firstName        = "Philip";
  private String              middleName       = "J.";
  private String              initials         = "P.F";
  private String              lastName         = "Fry";
  private Country             country;
  private Country             countryOfBirth;
}

public class Country {
  private Long                id;
  private String              name;
  private Object              other;
}

I can use the GsonBuilder and add an ExclusionStrategy for a field name like firstName or country but I can't seem to manage to exclude properties of certain fields like country.name.

Using the method public boolean shouldSkipField(FieldAttributes fa), FieldAttributes doesn't contain enough information to match the field with a filter like country.name.

P.S: I want to avoid annotations since I want to improve on this and use RegEx to filter fields out.

Edit: I'm trying to see if it's possible to emulate the behavior of Struts2 JSON plugin

using Gson

<interceptor-ref name="json">
  <param name="enableSMD">true</param>
  <param name="excludeProperties">
    login.password,
    studentList.*\.sin
  </param>
</interceptor-ref>

Edit:
    I reopened the question with the following addition:

I added a second field with the same type to futher clarify this problem. Basically I want to exclude country.name but not countrOfBirth.name. I also don't want to exclude Country as a type.
So the types are the same it's the actual place in the object graph that I want to pinpoint and exclude.

Body:
I'm working just by putting the @Expose annotation, here my version that I use

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

In Model class:

@Expose
int number;

public class AdapterRestApi {

In the Adapter class:

public EndPointsApi connectRestApi() {
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(90000, TimeUnit.SECONDS)
            .readTimeout(90000,TimeUnit.SECONDS).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ConstantRestApi.ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    return retrofit.create  (EndPointsApi.class);
}


问:
QT how to emit a signal in this case
I need to develop a Sudoku game. After reading a text file containing the number values, I create 9*9 widgets.
If (the value is already set then I instantiate to a qlabel containing the number,
else I instantiate a combobox containing the possible values of each case).

Until here everything is OK.
The problem is that when a value is chosen from the combobox, I need to draw it in a square in my view (MVC).  The problem is how can I know which one was chosen?

The only signal can I use from combobox signals is currenttextchanged(QString), but I'll not know which combo made that signal.
The ideal for me would be something like this SIGNAL(curretextchanged(QString, int, int)), but I don't know if I can define a new signal?

Here is some code:

```<code>QWidget *tab[9][9];
SudModel *modele = ???;
QComboBox *combobox = new QComboBox();
combobox->setStyleSheet("border: 1px solid red");
int tmp = modele->valuesof(i, j).size();

for (int s = 0; s < tmp; s++) {
    combobox->addItem(QString::number(modele->valuesof(i, j)[s]));
}

connect(combobox, SIGNAL(currentTextChanged(QString)), this, SLOT(update()));
tab[i][j] = combobox;
</code>```

答:
You can ask the slot for a sender()

QObject *QObject::sender() const

Returns a pointer to the object that sent the signal, if called in a
slot     activated by a signal; otherwise it returns 0. The pointer is
valid only during     the execution of the slot that calls this
function from this object's thread context.

Title: QT how to emit a signal in this case

Body:
I need to develop a Sudoku game. After reading a text file containing the number values, I create 9*9 widgets.
If (the value is already set then I instantiate to a qlabel containing the number,
else I instantiate a combobox containing the possible values of each case).

Until here everything is OK.
The problem is that when a value is chosen from the combobox, I need to draw it in a square in my view (MVC).  The problem is how can I know which one was chosen?

The only signal can I use from combobox signals is currenttextchanged(QString), but I'll not know which combo made that signal.
The ideal for me would be something like this SIGNAL(curretextchanged(QString, int, int)), but I don't know if I can define a new signal?

Here is some code:

QWidget *tab[9][9];
SudModel *modele = ???;
QComboBox *combobox = new QComboBox();
combobox->setStyleSheet("border: 1px solid red");
int tmp = modele->valuesof(i, j).size();

for (int s = 0; s < tmp; s++) {
    combobox->addItem(QString::number(modele->valuesof(i, j)[s]));
}

connect(combobox, SIGNAL(currentTextChanged(QString)), this, SLOT(update()));
tab[i][j] = combobox;


问:
PHPMailer email sent successfully but not received (EC2)
I am using PHPMailer on EC2. My account is not in a sandbox and Im sending from verified email. Im getting no errors from PHPMailer and thats my log

```<code>2017-03-31 06:24:52 Connection: opening to email-smtp.us-west-2.amazonaws.com:587, timeout=300, options=array ( )
2017-03-31 06:24:52 Connection: opened
2017-03-31 06:24:53 SERVER -> CLIENT: 220 email-smtp.amazonaws.com ESMTP SimpleEmailService-2007935443 svKFRJ5M6s1rqbMTRdZu
2017-03-31 06:24:53 CLIENT -> SERVER: EHLO ***.domain
2017-03-31 06:24:53 SERVER -> CLIENT: 250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: STARTTLS
2017-03-31 06:24:53 SERVER -> CLIENT: 220 Ready to start TLS
2017-03-31 06:24:53 CLIENT -> SERVER: EHLO ***.domain
2017-03-31 06:24:53 SERVER -> CLIENT: 250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: AUTH LOGIN
2017-03-31 06:24:53 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2017-03-31 06:24:53 CLIENT -> SERVER: xxx=
2017-03-31 06:24:53 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2017-03-31 06:24:53 CLIENT -> SERVER: xxx=
2017-03-31 06:24:53 SERVER -> CLIENT: 235 Authentication successful.
2017-03-31 06:24:53 CLIENT -> SERVER: MAIL FROM:
2017-03-31 06:24:53 SERVER -> CLIENT: 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: RCPT TO:
2017-03-31 06:24:53 SERVER -> CLIENT: 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: DATA
2017-03-31 06:24:53 SERVER -> CLIENT: 354 End data with .
2017-03-31 06:24:53 CLIENT -> SERVER: Date: Fri, 31 Mar 2017 06:24:52 +0000
2017-03-31 06:24:53 CLIENT -> SERVER: To: NG
2017-03-31 06:24:53 CLIENT -> SERVER: From: Me
2017-03-31 06:24:53 CLIENT -> SERVER: Subject: New User Added
2017-03-31 06:24:53 CLIENT -> SERVER: Message-ID: <8ada86808c4dc38c21d7ff5d64051951@***.domain>
2017-03-31 06:24:53 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.21 (https://github.com/PHPMailer/PHPMailer)
2017-03-31 06:24:53 CLIENT -> SERVER: MIME-Version: 1.0
2017-03-31 06:24:53 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1
2017-03-31 06:24:53 CLIENT -> SERVER:
2017-03-31 06:24:53 CLIENT -> SERVER: 123
2017-03-31 06:24:53 CLIENT -> SERVER:
2017-03-31 06:24:53 CLIENT -> SERVER: .
2017-03-31 06:24:53 SERVER -> CLIENT: 250 Ok 0101015b2309bfbe-39a8cf31-ad57-4998-832d-94312b7ddfad-000000
2017-03-31 06:24:53 CLIENT -> SERVER: QUIT
2017-03-31 06:24:53 SERVER -> CLIENT: 221 Bye
2017-03-31 06:24:53 Connection: closed
</code>```

This is my PHPMailer settings

```<code>$this->SMTPDebug = 3;

$this->Host = 'email-smtp.us-west-2.amazonaws.com';
$this->Username = '***';
$this->Password = '***';
$this->SMTPAuth = true;
$this->SMTPSecure = 'tls';
$this->Port = 587;
$this->isHTML(true);
$this->isSMTP();

$this->From = '***';
$this->FromName = '***';
$this->ReturnPath = '***';
</code>```

I tried to send this to different email but it still not working. Here is actual code of sending

```<code>$mailer = new Mailer($API);
$mailer->Subject = 'New User Added';
$mailer->Body = '123';

$mailer->addAddress('***', '***');

if (!$mailer->send()) {
   throw new Exception($mailer->ErrorInfo);
} else {
    print_r('Sent');
}
</code>```

答: I would suggest that you go to https://www.mail-tester.com/ and then copy the email address you see. Update your code and then send an email using PHPMailer to the address you copied. Assuming that your code does actually send the email, and it looks like your code is correct, then Mail Tester will show you what problems your email has.</p>

Body:
I am using PHPMailer on EC2. My account is not in a sandbox and Im sending from verified email. Im getting no errors from PHPMailer and thats my log

2017-03-31 06:24:52 Connection: opening to email-smtp.us-west-2.amazonaws.com:587, timeout=300, options=array ( )
2017-03-31 06:24:52 Connection: opened
2017-03-31 06:24:53 SERVER -> CLIENT: 220 email-smtp.amazonaws.com ESMTP SimpleEmailService-2007935443 svKFRJ5M6s1rqbMTRdZu
2017-03-31 06:24:53 CLIENT -> SERVER: EHLO ***.domain
2017-03-31 06:24:53 SERVER -> CLIENT: 250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: STARTTLS
2017-03-31 06:24:53 SERVER -> CLIENT: 220 Ready to start TLS
2017-03-31 06:24:53 CLIENT -> SERVER: EHLO ***.domain
2017-03-31 06:24:53 SERVER -> CLIENT: 250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: AUTH LOGIN
2017-03-31 06:24:53 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2017-03-31 06:24:53 CLIENT -> SERVER: xxx=
2017-03-31 06:24:53 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2017-03-31 06:24:53 CLIENT -> SERVER: xxx=
2017-03-31 06:24:53 SERVER -> CLIENT: 235 Authentication successful.
2017-03-31 06:24:53 CLIENT -> SERVER: MAIL FROM:
2017-03-31 06:24:53 SERVER -> CLIENT: 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: RCPT TO:
2017-03-31 06:24:53 SERVER -> CLIENT: 250 Ok
2017-03-31 06:24:53 CLIENT -> SERVER: DATA
2017-03-31 06:24:53 SERVER -> CLIENT: 354 End data with .
2017-03-31 06:24:53 CLIENT -> SERVER: Date: Fri, 31 Mar 2017 06:24:52 +0000
2017-03-31 06:24:53 CLIENT -> SERVER: To: NG
2017-03-31 06:24:53 CLIENT -> SERVER: From: Me
2017-03-31 06:24:53 CLIENT -> SERVER: Subject: New User Added
2017-03-31 06:24:53 CLIENT -> SERVER: Message-ID: <8ada86808c4dc38c21d7ff5d64051951@***.domain>
2017-03-31 06:24:53 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.21 (https://github.com/PHPMailer/PHPMailer)
2017-03-31 06:24:53 CLIENT -> SERVER: MIME-Version: 1.0
2017-03-31 06:24:53 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1
2017-03-31 06:24:53 CLIENT -> SERVER:
2017-03-31 06:24:53 CLIENT -> SERVER: 123
2017-03-31 06:24:53 CLIENT -> SERVER:
2017-03-31 06:24:53 CLIENT -> SERVER: .
2017-03-31 06:24:53 SERVER -> CLIENT: 250 Ok 0101015b2309bfbe-39a8cf31-ad57-4998-832d-94312b7ddfad-000000
2017-03-31 06:24:53 CLIENT -> SERVER: QUIT
2017-03-31 06:24:53 SERVER -> CLIENT: 221 Bye
2017-03-31 06:24:53 Connection: closed

This is my PHPMailer settings

$this->SMTPDebug = 3;

$this->Host = 'email-smtp.us-west-2.amazonaws.com';
$this->Username = '***';
$this->Password = '***';
$this->SMTPAuth = true;
$this->SMTPSecure = 'tls';
$this->Port = 587;
$this->isHTML(true);
$this->isSMTP();

$this->From = '***';
$this->FromName = '***';
$this->ReturnPath = '***';

I tried to send this to different email but it still not working. Here is actual code of sending

$mailer = new Mailer($API);
$mailer->Subject = 'New User Added';
$mailer->Body = '123';

$mailer->addAddress('***', '***');

if (!$mailer->send()) {
   throw new Exception($mailer->ErrorInfo);
} else {
    print_r('Sent');
}


问:
What is correct media query for IPad Pro?
I have these two but they are not working. I'm simulating in Chrome

```<code>    /* Landscape*/

    @media only screen and (min-device-width: 1024px) and (max-device-width: 1366px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: landscape)  {}

    /* Portrait*/
    @media only screen and (min-device-width: 1024px) and (max-device-width: 1366px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: portrait)  {}
</code>```

If I remove   'and (orientation: landscape)' then the css in there works in the first media query.
What is the correct orientation, for both landscape and portrait ?

The HTML  meta is set as

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
</code>```

答:
```<code>/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen
  and (min-width: 1024px)
  and (max-height: 1366px)
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Portrait */
@media only screen
  and (min-width: 1024px)
  and (max-height: 1366px)
  and (orientation: portrait)
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Landscape */
@media only screen
  and (min-width: 1024px)
  and (max-height: 1366px)
  and (orientation: landscape)
  and (-webkit-min-device-pixel-ratio: 1.5) {

}
</code>```

I don't have an iPad Pro but this works for me in the Chrome simulator.

Body:
I have these two but they are not working. I'm simulating in Chrome

    /* Landscape*/

    @media only screen and (min-device-width: 1024px) and (max-device-width: 1366px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: landscape)  {}

    /* Portrait*/
    @media only screen and (min-device-width: 1024px) and (max-device-width: 1366px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: portrait)  {}

If I remove   'and (orientation: landscape)' then the css in there works in the first media query.
What is the correct orientation, for both landscape and portrait ?

The HTML  meta is set as

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

Body:
/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen
  and (min-width: 1024px)
  and (max-height: 1366px)
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Portrait */
@media only screen
  and (min-width: 1024px)
  and (max-height: 1366px)
  and (orientation: portrait)
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Landscape */
@media only screen
  and (min-width: 1024px)
  and (max-height: 1366px)
  and (orientation: landscape)
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

I don't have an iPad Pro but this works for me in the Chrome simulator.


问:
Rails - document.ready not working in specific JavaScript file
A piece of JavaScript I wrote (which lives in app/assets/javascripts/tenant_content.js) wasn't working so I boiled it down to the following in order to test it:

```<code>$(document).ready(function() {
  console.log("Test");
});
</code>```

When I refresh the page nothing is logged to the console.

If I remove the console.log from within the document.ready then it prints just fine. The strange thing is it also works if I move it to one of my other JavaScript files. It seems to be the combination of being in this particular file and being within the document.ready function that causes it not to work. Any ideas why?

Note: I'm not using Turbolinks.

Thanks

答:
This means that document.ready fired before this event was binded. So your DOM is ready before script is loaded.

If this tag is at the bottom of page, put it up. Or remove asynch and deferred attributes.

Body:
A piece of JavaScript I wrote (which lives in app/assets/javascripts/tenant_content.js) wasn't working so I boiled it down to the following in order to test it:

$(document).ready(function() {
  console.log("Test");
});

When I refresh the page nothing is logged to the console.

If I remove the console.log from within the document.ready then it prints just fine. The strange thing is it also works if I move it to one of my other JavaScript files. It seems to be the combination of being in this particular file and being within the document.ready function that causes it not to work. Any ideas why?

Note: I'm not using Turbolinks.

Thanks


问:
Cannot read property 'set' of undefined of a defined Map
I'm working with ES6 for the first time, and I read some stuff about maps. From what I understand, this should be well within the possibility of ES6:

```<code>export class Elements {

    constructor() {
        this.elements = new Map();
        this.attachListeners();
    }

    textElement () {
        this.elements.set((elements.length + 1), new TextElement());
    }

    attachListeners () {
        document.getElementById('addText').addEventListener('click', this.textElement);
    }
}
</code>```

However, when I click the addText element, I get the following in my console

Uncaught TypeError: Cannot read property 'set' of undefined at HTMLDivElement.textElement

I tried swapping the Map with a Set, an Array and an Object, however, that same error kept coming into my console.

How can it be that a simple operation like this isn't working?

答:
You need to bind your listener, like this:

```<code>document.getElementById('addText').addEventListener('click', this.textElement.bind(this));
</code>```

Otherwise, this refers to your 'addText' element in your textElement function.

Try console.log(this) in textElement with and without the .bind(this) and you'll understand what's happening.

Body:
I'm working with ES6 for the first time, and I read some stuff about maps. From what I understand, this should be well within the possibility of ES6:

export class Elements {

    constructor() {
        this.elements = new Map();
        this.attachListeners();
    }

    textElement () {
        this.elements.set((elements.length + 1), new TextElement());
    }

    attachListeners () {
        document.getElementById('addText').addEventListener('click', this.textElement);
    }
}

However, when I click the addText element, I get the following in my console

Uncaught TypeError: Cannot read property 'set' of undefined at HTMLDivElement.textElement

I tried swapping the Map with a Set, an Array and an Object, however, that same error kept coming into my console.

How can it be that a simple operation like this isn't working?

Body:
You need to bind your listener, like this:

document.getElementById('addText').addEventListener('click', this.textElement.bind(this));

Otherwise, this refers to your 'addText' element in your textElement function.

Try console.log(this) in textElement with and without the .bind(this) and you'll understand what's happening.


问:
Time Complexity while deleting last element from arraylist and linkedlist
1st Part :-

I was reading in the book - "Data Structure and Algorithms made easy in Java" that the time complexity for deleting the last element from Linkedlist and Arraylist is O(n). But the Linkedlist internally implements DoublyLinkedlist so the time complexity should be O(1) and similarly for Arraylist as it internally implement Array it should be O(1).

2nd Part :-

It also says that the insertion of an element at the ending of a linkedlist has a time complexity of O(n) but the linkedlist maintains pointers both at the end and at the front. So it this statement correct ? Moreover it says that the time complexity to insert an element in an arraylist at the end is O(1) if array is not full and O(n) if the array is full. Why O(n) if the array is full ?

Thanks for answering the 1st part . Can anyone please also explain the 2nd part. Thanks :)

答:
It depends on what methods you're calling.

A glance at the implementation shows that if you're calling LinkedList.removeLast(), that's O(1). The LinkedList maintains pointers both to the first and last node in the list. So it doesn't have to traverse the list to get to the last node.

Calling LinkedList.remove(index) with the index of the last element is also O(1), because it traverses the list from the closest end. [Noted by user @andreas in comment below.]

But if you're calling LinkedList.remove(Object), then there's an O(n) search for the first matching node.

Similarly, for ArrayList, if you're calling ArrayList.remove(index) with the index of the last element, then that's O(1). For all other indices, there's a System.arrayCopy() call that can be O(n) -- but that's skipped entirely for the last element.

But if you call ArrayList.remove(Object), then again there's an O(n) search for the first matching node.


问:
How to get values from input types using this.refs in reactjs?
Not able to get values of input type using this.refs...
how to get that values from input type</p>

```<code>   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }
</code>```

答:
I think the more idiomatic way is to use state instead of refs, although it's a little more code in this case since you only have a single input.

```<code>export class BusinessDetailsForm extends Component {

  constructor(props) {
    super(props);
    this.state = { googleInput: '' };
    this.defaultValue = 'someValue';
    this.handleChange = this.handleChange.bind(this);
    this.submitForm = this.submitForm.bind(this);
  }

  handleChange(e) {
    const { field, value } = e.target;
    this.setState({ [field]: value });
  }
  submitForm() {
    console.log(this.state.googleInput);
  }
  render() {
    return (
      <Formsy.Form onSubmit={this.submitForm} id="form_validation">
        <Field type="text"
          name="googleInput"
          onChange={this.handleChange}
          component={GoogleAutoComplete}
          floatingLabelText="location"
          hintText="location"
          id="addressSearchBoxField"
          defaultValue={this.defaultValue}
          onSelectPlace={this.handlePlaceChanged}
          validate={[ required ]}
        />
      </Formsy.Form>
    );
  }
}
</code>```

See https://facebook.github.io/react/docs/forms.html#controlled-components.

Body:
Not able to get values of input type using this.refs...
how to get that values from input type

   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }

Body:
I think the more idiomatic way is to use state instead of refs, although it's a little more code in this case since you only have a single input.

export class BusinessDetailsForm extends Component {

  constructor(props) {
    super(props);
    this.state = { googleInput: '' };
    this.defaultValue = 'someValue';
    this.handleChange = this.handleChange.bind(this);
    this.submitForm = this.submitForm.bind(this);
  }

  handleChange(e) {
    const { field, value } = e.target;
    this.setState({ [field]: value });
  }
  submitForm() {
    console.log(this.state.googleInput);
  }
  render() {
    return (
      <Formsy.Form onSubmit={this.submitForm} id="form_validation">
        <Field type="text"
          name="googleInput"
          onChange={this.handleChange}
          component={GoogleAutoComplete}
          floatingLabelText="location"
          hintText="location"
          id="addressSearchBoxField"
          defaultValue={this.defaultValue}
          onSelectPlace={this.handlePlaceChanged}
          validate={[ required ]}
        />
      </Formsy.Form>
    );
  }
}

See https://facebook.github.io/react/docs/forms.html#controlled-components.


问:
Swift 3.0 Passing data among view controller
I'm using Xcode Swift 3.0, I have 5 view controllers, each controller have several textField. Once the information finish filled, press nextButton to next view controller. For example, finish fill in all textField in view controller 1, click nextButton and I will segue it to view controller 2, and so on.....

I want to get view controller 1,2,3,4 entered textField information only from view controller 5.

How am I gonna to do that without using Segue to pass data from vc1 to vc2, and from vc2 to vc3 and so on?

Please advice.

答:
TempData can be used for passing value from Controller to View and also from Controller to Controller.
Find the example:</p>

```<code>public class FirstController : Controller
{
    // GET: First
    public ActionResult Index()
    {
        TempData["Message"] = "Hello MVC!";
        return new RedirectResult(@"~\Second\");
    }
}
public class SecondController : Controller
{
    // GET: Second
    public ActionResult Index()
    {
        return View();
    }
}
</code>```

Body:
TempData can be used for passing value from Controller to View and also from Controller to Controller.
Find the example:

public class FirstController : Controller
{
    // GET: First
    public ActionResult Index()
    {
        TempData["Message"] = "Hello MVC!";
        return new RedirectResult(@"~\Second\");
    }
}
public class SecondController : Controller
{
    // GET: Second
    public ActionResult Index()
    {
        return View();
    }
}


问:
Why gcc sometimes allocate extra space for local but sometimes not?
Here is my code

```<code>#include <stdio.h>

char func_with_ret()
{
    return 1;
}
void func_1()
{
    char buf[16];
    func_with_ret();
}
void func_2()
{
    char buf[16];
    getchar();
}
int main()
{
    func_1();
    func_2();
}
</code>```

I declare 16-byte local buffers to keep the stack pointer aligned(for x86).

I write two function "func_1", "func_2", they look almost the same - allocate 16-byte local buffer and call a function with char return value and no parameter, but one is self-defined and the other is getchar().

Compile with gcc parameter "-fno-stack-protector"(so there's no canary on stack) and "-O0" to avoid unexpected optimization behavior.

Here is the disassembly code by gdb for func_1 and func_2.

```<code>Dump of assembler code for function func_1:
   0x08048427 <+0>:     push   ebp
   0x08048428 <+1>:     mov    ebp,esp
   0x0804842a <+3>:     sub    esp,0x10
   0x0804842d <+6>:     call   0x804841d <func_with_ret>
   0x08048432 <+11>:    leave
   0x08048433 <+12>:    ret

Dump of assembler code for function func_2:
   0x08048434 <+0>:     push   ebp
   0x08048435 <+1>:     mov    ebp,esp
   0x08048437 <+3>:     sub    esp,0x18
   0x0804843a <+6>:     call   0x80482f0 <getchar@plt>
   0x0804843f <+11>:    leave
   0x08048440 <+12>:    ret
</code>```

In func_1, buffer is allocated for 0x10(16) bytes,
but in func_2 , it is allocated for 0x18(24) bytes, why?

Edit:
@Attie figure out that buffer size is actually the same for both, but there's
strange 8-byte stack spaces in func_2 don't know where it comes from.

答:
I have just tried to reproduce this, see below:

Compiling for x86-64 (no joy):

$ gcc p.c -g -o p -O0 -fno-stack-protector
$ objdump -d p

p:     file format elf64-x86-64

[...]

0000000000400538 <func_1>:
  400538:       55                      push   %rbp
  400539:       48 89 e5                mov    %rsp,%rbp
  40053c:       48 83 ec 10             sub    $0x10,%rsp
  400540:       b8 00 00 00 00          mov    $0x0,%eax
  400545:       e8 e3 ff ff ff          callq  40052d <func_with_ret>
  40054a:       c9                      leaveq
  40054b:       c3                      retq

000000000040054c <func_2>:
  40054c:       55                      push   %rbp
  40054d:       48 89 e5                mov    %rsp,%rbp
  400550:       48 83 ec 10             sub    $0x10,%rsp
  400554:       e8 c7 fe ff ff          callq  400420 <getchar@plt>
  400559:       c9                      leaveq
  40055a:       c3                      retq
```

<p>Compiling for <code>i386</code> (success):</p>

<pre class="lang-none prettyprint-override"><code>$ gcc p.c -g -o p -O0 -fno-stack-protector -m32
$ objdump -d p

p:     file format elf32-i386

[...]

08048427 <func_1>:
 8048427:       55                      push   %ebp
 8048428:       89 e5                   mov    %esp,%ebp
 804842a:       83 ec 10                sub    $0x10,%esp
 804842d:       e8 eb ff ff ff          call   804841d <func_with_ret>
 8048432:       c9                      leave
 8048433:       c3                      ret

08048434 <func_2>:
 8048434:       55                      push   %ebp
 8048435:       89 e5                   mov    %esp,%ebp
 8048437:       83 ec 18                sub    $0x18,%esp
 804843a:       e8 b1 fe ff ff          call   80482f0 <getchar@plt>
 804843f:       c9                      leave
 8048440:       c3                      ret
</code>```

This doesn't appear to be related to any of the following:

The fact that getchar() is a library function, and thus we are calling into the PLT (Procedure Linkage Table).

Related to the return type of the function

The order of the calls in main()

The order of the functions in the binary

Dynamic / static compliation

If you however increase the size of your buffer by one, to 17, then the stack usage increases to 32 and 40 bytes (from 16 and 24 bytes) respectively. The difference is 16 bytes, which is used for alignment, as answered here.

I can't answer why the stack alignment appears to be off by 8-bytes upon entering func_2() though.

If you update func_1() and func_2() to have a 15-byte buffer, and a single byte variable, and write data to them, then you can see where these items are in the stack frame:

```<code>void func_1(void) {
    char buf[15];
    char x;
    buf[0] = 0xaa;
    x = 0x55;
    func_with_ret();
}

void func_2(void) {
    char buf[15];
    char x;
    buf[0] = 0xaa;
    x = 0x55;
    getchar();
}
</code>```

08048434 <func_1>:
 8048434:       55                      push   %ebp
 8048435:       89 e5                   mov    %esp,%ebp
 8048437:       83 ec 10                sub    $0x10,%esp
 804843a:       c6 45 f0 aa             movb   $0xaa,-0x10(%ebp)
 804843e:       c6 45 ff 55             movb   $0x55,-0x1(%ebp)
 8048442:       e8 d6 ff ff ff          call   804841d <func_with_ret>
 8048447:       c9                      leave
 8048448:       c3                      ret

08048449 <func_2>:
 8048449:       55                      push   %ebp
 804844a:       89 e5                   mov    %esp,%ebp
 804844c:       83 ec 18                sub    $0x18,%esp
 804844f:       c6 45 e8 aa             movb   $0xaa,-0x18(%ebp)
 8048453:       c6 45 f7 55             movb   $0x55,-0x9(%ebp)
 8048457:       e8 94 fe ff ff          call   80482f0 <getchar@plt>
 804845c:       c9                      leave
 804845d:       c3                      ret
```

Body:
Here is my code

#include <stdio.h>

char func_with_ret()
{
    return 1;
}
void func_1()
{
    char buf[16];
    func_with_ret();
}
void func_2()
{
    char buf[16];
    getchar();
}
int main()
{
    func_1();
    func_2();
}

I declare 16-byte local buffers to keep the stack pointer aligned(for x86).

I write two function "func_1", "func_2", they look almost the same - allocate 16-byte local buffer and call a function with char return value and no parameter, but one is self-defined and the other is getchar().

Compile with gcc parameter "-fno-stack-protector"(so there's no canary on stack) and "-O0" to avoid unexpected optimization behavior.

Here is the disassembly code by gdb for func_1 and func_2.

Dump of assembler code for function func_1:
   0x08048427 <+0>:     push   ebp
   0x08048428 <+1>:     mov    ebp,esp
   0x0804842a <+3>:     sub    esp,0x10
   0x0804842d <+6>:     call   0x804841d <func_with_ret>
   0x08048432 <+11>:    leave
   0x08048433 <+12>:    ret

Dump of assembler code for function func_2:
   0x08048434 <+0>:     push   ebp
   0x08048435 <+1>:     mov    ebp,esp
   0x08048437 <+3>:     sub    esp,0x18
   0x0804843a <+6>:     call   0x80482f0 <getchar@plt>
   0x0804843f <+11>:    leave
   0x08048440 <+12>:    ret

In func_1, buffer is allocated for 0x10(16) bytes,
but in func_2 , it is allocated for 0x18(24) bytes, why?

Edit:
@Attie figure out that buffer size is actually the same for both, but there's
strange 8-byte stack spaces in func_2 don't know where it comes from.

Body:
I have just tried to reproduce this, see below:

Compiling for x86-64 (no joy):

$ gcc p.c -g -o p -O0 -fno-stack-protector
$ objdump -d p

p:     file format elf64-x86-64

[...]

0000000000400538 <func_1>:
  400538:       55                      push   %rbp
  400539:       48 89 e5                mov    %rsp,%rbp
  40053c:       48 83 ec 10             sub    $0x10,%rsp
  400540:       b8 00 00 00 00          mov    $0x0,%eax
  400545:       e8 e3 ff ff ff          callq  40052d <func_with_ret>
  40054a:       c9                      leaveq
  40054b:       c3                      retq

000000000040054c <func_2>:
  40054c:       55                      push   %rbp
  40054d:       48 89 e5                mov    %rsp,%rbp
  400550:       48 83 ec 10             sub    $0x10,%rsp
  400554:       e8 c7 fe ff ff          callq  400420 <getchar@plt>
  400559:       c9                      leaveq
  40055a:       c3                      retq

Compiling for i386 (success):

$ gcc p.c -g -o p -O0 -fno-stack-protector -m32
$ objdump -d p

p:     file format elf32-i386

[...]

08048427 <func_1>:
 8048427:       55                      push   %ebp
 8048428:       89 e5                   mov    %esp,%ebp
 804842a:       83 ec 10                sub    $0x10,%esp
 804842d:       e8 eb ff ff ff          call   804841d <func_with_ret>
 8048432:       c9                      leave
 8048433:       c3                      ret

08048434 <func_2>:
 8048434:       55                      push   %ebp
 8048435:       89 e5                   mov    %esp,%ebp
 8048437:       83 ec 18                sub    $0x18,%esp
 804843a:       e8 b1 fe ff ff          call   80482f0 <getchar@plt>
 804843f:       c9                      leave
 8048440:       c3                      ret

This doesn't appear to be related to any of the following:

The fact that getchar() is a library function, and thus we are calling into the PLT (Procedure Linkage Table).

Related to the return type of the function

The order of the calls in main()

The order of the functions in the binary

Dynamic / static compliation

If you however increase the size of your buffer by one, to 17, then the stack usage increases to 32 and 40 bytes (from 16 and 24 bytes) respectively. The difference is 16 bytes, which is used for alignment, as answered here.

I can't answer why the stack alignment appears to be off by 8-bytes upon entering func_2() though.

If you update func_1() and func_2() to have a 15-byte buffer, and a single byte variable, and write data to them, then you can see where these items are in the stack frame:

void func_1(void) {
    char buf[15];
    char x;
    buf[0] = 0xaa;
    x = 0x55;
    func_with_ret();
}

void func_2(void) {
    char buf[15];
    char x;
    buf[0] = 0xaa;
    x = 0x55;
    getchar();
}

08048434 <func_1>:
 8048434:       55                      push   %ebp
 8048435:       89 e5                   mov    %esp,%ebp
 8048437:       83 ec 10                sub    $0x10,%esp
 804843a:       c6 45 f0 aa             movb   $0xaa,-0x10(%ebp)
 804843e:       c6 45 ff 55             movb   $0x55,-0x1(%ebp)
 8048442:       e8 d6 ff ff ff          call   804841d <func_with_ret>
 8048447:       c9                      leave
 8048448:       c3                      ret

08048449 <func_2>:
 8048449:       55                      push   %ebp
 804844a:       89 e5                   mov    %esp,%ebp
 804844c:       83 ec 18                sub    $0x18,%esp
 804844f:       c6 45 e8 aa             movb   $0xaa,-0x18(%ebp)
 8048453:       c6 45 f7 55             movb   $0x55,-0x9(%ebp)
 8048457:       e8 94 fe ff ff          call   80482f0 <getchar@plt>
 804845c:       c9                      leave
 804845d:       c3                      ret


问:
Looking for a clean and efficient algorithm for checking on and off elements of a "tree" (actually a DAG)
This is not a homework.

Visually it looks like a tree, but all leafs are unique (have unique ids in database). The hierarchy above them is somewhat arbitrary. Each checkbox has 3 states: on, off, and partial. Leaves can be only checked or not checked. The state of the children should drive the state of the parents. Clicking on a checkbox should "toggle" it, and propagate the necessary changes up or down. If you click on a parent that is partially checked, it should become fully checked. Each child has a pointer to a list (I could change this to a set if I must) of parents. Each parent has a list of children sorted alphabetically. At the same time, for display purposes, this structure is a tree that I can expand and collapse, as you would see from the picture below.

I am sure this algorithm has been invented before. Since the number of leaves has been up to 20,000, I do care about the performance in practice. But, I would not try to squeeze every last drop of performance out of the algo at the expense of code being short and readable.

I figured that in principle I should walk down (if there is anywhere to go) and identify all leaves that should be changed. After that I should walk up. From the set of leaves I should figure out a set of parents that might be affected. Then filter it down to the set of parents that will need to change, and to which value. Then Add those to a set. Then I will need to walk up from those nodes and repeat. After I have a set of leaves and other nodes that need to change as well as their values, I will need to just do it ... or something like that. A matrix-based representation would be too expensive.

I am hacking this thing together in C++ using MFC, but my question is pretty much language-agnostic. I would prefer a concrete implementation to an algorithm, however. Some languages like Python, Perl, Scala might have too modern tricks up their sleeves. I would try to stick to something more conventional, like Java, C# (minus LINQ).

Code, links, references and questions are welcome.

答:
The "partial" state is an issue here.

If you are in a "partial" state, and a child pass "unchecked" should you go "unchecked" too or keep your "partial" state ? This requires querying all other children. I would suggest to modify the structure to keep 2 numbers instead of flags (for non-leaves):

the number of children (leaves not direct)

the number of checked children (leaves not direct)

You need to maintain them correct at each update, of course.

In order to update them correctly, it's a simple walk from the child to its parents. If you make sure that each child only has one reference to its parent (and the same goes for the parent...), then each time a child change its state, update each of its parents (and thus each of them).


问:
Null Pointer Exception in JDBCTemplateObject.query() in listFriends method in JDBCTemplate class
I'm trying the retrieve the data from Database and display it on the UI. There's a null pointer exception in FriendJDBCTemplate class. Can anyone please help me with this.

FriendJDBCTemplate.java:

```<code>package com.initial.hellocontroller;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class FriendJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;

    public void setDataSource(DataSource dataSource) {
       this.dataSource = dataSource;
       JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    public void create(String name, String Email) {
        String SQL = "insert into Friend (name, Email) values (?, ?)";
        jdbcTemplateObject.update( SQL, name, Email);
        System.out.println("Created Record Name = " + name + " Email = " + Email);
        return;
    }
    public Friend getFriend(String Telephone) {
        String SQL = "select * from Friend where Telephone = ?";
        Friend friend = jdbcTemplateObject.queryForObject(SQL, new Object[] {Telephone}, new FriendMapper());
        return friend;
    }
    public List<Friend> listFriends() {
        String SQL = "select * from Friend";
        List <Friend> friends = jdbcTemplateObject.query(SQL, new FriendMapper());
        return friends;
    }
    public void delete(String Telephone) {
        String SQL = "delete from Friend where Telephone = ?";
        jdbcTemplateObject.update(SQL, Telephone);
        System.out.println("Deleted Record with ID = " + Telephone);
        return;
    }
    public void update(String Telephone, String name){
        String SQL = "update Friend set name = ? where Telephone = ?";
        jdbcTemplateObject.update(SQL, name, Telephone);
        System.out.println("Updated Record with Telephone = " + Telephone );
        return;
    }
}
</code>```

FriendMapper.java

```<code>package com.initial.hellocontroller;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class FriendMapper implements RowMapper<Friend> {
    public Friend mapRow(ResultSet rs, int rowNum) throws SQLException{
        Friend friend = new Friend();
        friend.settelephone(rs.getString("Telephone"));
        friend.setname(rs.getString("name"));
        friend.setemail(rs.getString("Email"));
        return friend;
    }
}
</code>```

Friend.java

```<code>package com.initial.hellocontroller;
import java.util.List;

public class Friend implements Listall {
    private String name;
    private String Email;
    private String Telephone;

    public void setname(String name){
        this.name= name;
    }
    public String getname(){
        return name;
    }

    public void setemail(String Email){
        this.Email = Email;
    }
    public String getemail(){
        return Email;
    }
    public void settelephone(String Telephone){
        this.Telephone = Telephone;
    }
    public String gettelephone(){
        return Telephone;
    }

    public List<Friend> Listallfriends(){
        FriendJDBCTemplate listall = new FriendJDBCTemplate();
        return listall.listFriends();
    }
}
</code>```

HelloController.java

```<code>package com.initial.hellocontroller;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import org.springframework.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
/*
public class HelloController extends AbstractController
{

    @override
    protected ModelAndView handleRequestInternal(HttpServletRequest   request, HttpServletResponse response) throws Exception
    {
        ModelAndView modelandview = new ModelAndView("Hellopage");
        modelandview.addObject("welcomeMessage","Hi User, Welcome to the first  spring MVC tutorial");

        return modelandview;
    }
}

*/

@Controller
public class HelloController {

    List<Friend> templist = new ArrayList<Friend>();
    Friend temp = new Friend();
    @RequestMapping(value = "/admissionForm",method = RequestMethod.GET)
    public ModelAndView getAdmissionForm(){
        ModelAndView model = new ModelAndView("Portfolio");
        return model;
    }

    @RequestMapping(value="/submitAdmissionForm", method = RequestMethod.POST)
    public ModelAndView submitAdmissionForm(@RequestParam Map<String,String> reqPar){
        String name = reqPar.get("name");
        String email =reqPar.get("Email");
        String telephone =reqPar.get("Telephone");

        // taking the input from the form to update the data from database.
        Friend friend = new Friend();
        friend.setname(name);
        friend.setemail(email);
        friend.settelephone(telephone);

        ModelAndView model = new ModelAndView("HelloPage");
        templist = temp.Listallfriends();
        for (Friend items : templist){
            model.addObject("msg", "your total friends" +items);
        }
        return model;
    }
}
</code>```

Dispatch-servlet.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.initial.hellocontroller"/>
    <mvc:annotation-driven/>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="dataSource"
          class =  "org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name = "driverClassName" value = "oracle.jdbc.OracleDriver"/>
        <property name = "url" value = "jdbc:oracle:thin:@localhost:1521:ORCL"/>
        <property name = "username" value = "system"/>
        <property name = "password" value = "hello123"/>
    </bean>
</beans>
</code>```

error trace:

```<code>java.lang.NullPointerException
    com.initial.hellocontroller.FriendJDBCTemplate.listFriends(FriendJDBCTemplate.java:28)
    com.initial.hellocontroller.Friend.Listallfriends(Friend.java:37)
    com.initial.hellocontroller.HelloController.submitAdmissionForm(HelloController.java:63)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</code>```

答:
Do you have two jdbcTemplateObject with same name. How is it even compiling.

Change JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);

To

this.jdbcTemplateObject  = new JdbcTemplate(dataSource); in setDataSource.

You have your dataSource bean defined in your spring config, but you are not injecting it to FriendsJDBCTemplate anywhere. You need to either use annotation "@Autowired" or manually wire beans in your spring xml. Just declaring beans won't work. You have to tell Spring container where they should be injected.

```<code>@Autowired
private DataSource dataSource;
</code>```

Body:
I'm trying the retrieve the data from Database and display it on the UI. There's a null pointer exception in FriendJDBCTemplate class. Can anyone please help me with this.

FriendJDBCTemplate.java:

package com.initial.hellocontroller;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class FriendJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;

    public void setDataSource(DataSource dataSource) {
       this.dataSource = dataSource;
       JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    public void create(String name, String Email) {
        String SQL = "insert into Friend (name, Email) values (?, ?)";
        jdbcTemplateObject.update( SQL, name, Email);
        System.out.println("Created Record Name = " + name + " Email = " + Email);
        return;
    }
    public Friend getFriend(String Telephone) {
        String SQL = "select * from Friend where Telephone = ?";
        Friend friend = jdbcTemplateObject.queryForObject(SQL, new Object[] {Telephone}, new FriendMapper());
        return friend;
    }
    public List<Friend> listFriends() {
        String SQL = "select * from Friend";
        List <Friend> friends = jdbcTemplateObject.query(SQL, new FriendMapper());
        return friends;
    }
    public void delete(String Telephone) {
        String SQL = "delete from Friend where Telephone = ?";
        jdbcTemplateObject.update(SQL, Telephone);
        System.out.println("Deleted Record with ID = " + Telephone);
        return;
    }
    public void update(String Telephone, String name){
        String SQL = "update Friend set name = ? where Telephone = ?";
        jdbcTemplateObject.update(SQL, name, Telephone);
        System.out.println("Updated Record with Telephone = " + Telephone );
        return;
    }
}

FriendMapper.java

package com.initial.hellocontroller;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class FriendMapper implements RowMapper<Friend> {
    public Friend mapRow(ResultSet rs, int rowNum) throws SQLException{
        Friend friend = new Friend();
        friend.settelephone(rs.getString("Telephone"));
        friend.setname(rs.getString("name"));
        friend.setemail(rs.getString("Email"));
        return friend;
    }
}

Friend.java

package com.initial.hellocontroller;
import java.util.List;

public class Friend implements Listall {
    private String name;
    private String Email;
    private String Telephone;

    public void setname(String name){
        this.name= name;
    }
    public String getname(){
        return name;
    }

    public void setemail(String Email){
        this.Email = Email;
    }
    public String getemail(){
        return Email;
    }
    public void settelephone(String Telephone){
        this.Telephone = Telephone;
    }
    public String gettelephone(){
        return Telephone;
    }

    public List<Friend> Listallfriends(){
        FriendJDBCTemplate listall = new FriendJDBCTemplate();
        return listall.listFriends();
    }
}

HelloController.java

package com.initial.hellocontroller;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import org.springframework.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
/*
public class HelloController extends AbstractController
{

    @override
    protected ModelAndView handleRequestInternal(HttpServletRequest   request, HttpServletResponse response) throws Exception
    {
        ModelAndView modelandview = new ModelAndView("Hellopage");
        modelandview.addObject("welcomeMessage","Hi User, Welcome to the first  spring MVC tutorial");

        return modelandview;
    }
}

*/

@Controller
public class HelloController {

    List<Friend> templist = new ArrayList<Friend>();
    Friend temp = new Friend();
    @RequestMapping(value = "/admissionForm",method = RequestMethod.GET)
    public ModelAndView getAdmissionForm(){
        ModelAndView model = new ModelAndView("Portfolio");
        return model;
    }

    @RequestMapping(value="/submitAdmissionForm", method = RequestMethod.POST)
    public ModelAndView submitAdmissionForm(@RequestParam Map<String,String> reqPar){
        String name = reqPar.get("name");
        String email =reqPar.get("Email");
        String telephone =reqPar.get("Telephone");

        // taking the input from the form to update the data from database.
        Friend friend = new Friend();
        friend.setname(name);
        friend.setemail(email);
        friend.settelephone(telephone);

        ModelAndView model = new ModelAndView("HelloPage");
        templist = temp.Listallfriends();
        for (Friend items : templist){
            model.addObject("msg", "your total friends" +items);
        }
        return model;
    }
}

Dispatch-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.initial.hellocontroller"/>
    <mvc:annotation-driven/>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="dataSource"
          class =  "org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name = "driverClassName" value = "oracle.jdbc.OracleDriver"/>
        <property name = "url" value = "jdbc:oracle:thin:@localhost:1521:ORCL"/>
        <property name = "username" value = "system"/>
        <property name = "password" value = "hello123"/>
    </bean>
</beans>

error trace:

java.lang.NullPointerException
    com.initial.hellocontroller.FriendJDBCTemplate.listFriends(FriendJDBCTemplate.java:28)
    com.initial.hellocontroller.Friend.Listallfriends(Friend.java:37)
    com.initial.hellocontroller.HelloController.submitAdmissionForm(HelloController.java:63)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Body:
Do you have two jdbcTemplateObject with same name. How is it even compiling.

Change JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);

To

this.jdbcTemplateObject  = new JdbcTemplate(dataSource); in setDataSource.

You have your dataSource bean defined in your spring config, but you are not injecting it to FriendsJDBCTemplate anywhere. You need to either use annotation "@Autowired" or manually wire beans in your spring xml. Just declaring beans won't work. You have to tell Spring container where they should be injected.

@Autowired
private DataSource dataSource;


问:
Appending a line to a file only if it does not already exist
I need to add the following line to the end of a config file:

```<code>include "/configs/projectname.conf"
</code>```

to a file called lighttpd.conf

I am looking into using sed to do this, but I can't work out how.

How would I only insert it if the line doesn't already exist?

答:
If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>.  A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

```<code>LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"
</code>```

Body:
I need to add the following line to the end of a config file:

include "/configs/projectname.conf"

to a file called lighttpd.conf

I am looking into using sed to do this, but I can't work out how.

How would I only insert it if the line doesn't already exist?

Body:
If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>.  A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"


问:
Trouble with creating one-time calendar event from Google Sheets row
I'm having some trouble with my Google Apps Script code trying to have it take the information on one row of my sheet and create a single, Calendar event, with beginning and ending times.

```<code>    //push new events to calendar
function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();

  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
    if ((values[i][0].length == '<>') && (values[i][1].length == '<>') && (values[i][4].length == '<>') && (values[i][5].length == '<>') && (values[i][6].length == '<>') && (values[i][7].length == '<>')) {

      //check if it's been entered before
      if ((values[i][8] == '')||(values[i][8] == null)) {

        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = CalendarApp.getDefaultCalendar().createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();

        //mark as entered, enter ID
        sheet.getRange(i+2,8).setValue(newEventId);

      } //could edit here with an else statement
    }
    numValues++;
  }
}
</code>```

I have pertinent information (used in the event title) in the first three columns, and Start Date in column 4, Start Time in column 5, End Date in column 6, and End Time in column 7. The other columns contain information that I'll add to the description of the event.

The problem I'm mostly running into is filtering the data set into events that have not been pushed to the Calendar yet, as well as the script accurately recording once it does push an event over, such that it will be able to filter it on the next cycle of the script.

答:
I got it to work. I was referencing the wrong columns initially in the value check line. Silly me.

```<code>//push new events to calendar
function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();

  //calendar variables
  var defaultCalendar = CalendarApp.getDefaultCalendar()

  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
  if ((values[i][0]) && (values[i][1]) && (values[i][3]) && (values[i][4]) && (values[i][5]) && (values[i][6]))
  {

      //check if it's been entered before
      if (values[i][8] != 'y') {

        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = defaultCalendar.createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();

        //mark as entered, enter ID
        sheet.getRange(i+2,8).setValue('y');
        sheet.getRange(i+2,9).setValue(newEventId);

      } //could edit here with an else statement
    }

    numValues++;
  }
}
</code>```

Spreadsheet has header row

Column 1 (value[i][0]) is Event Title info

Column 2 (value[i][1]) is Event Title info

Column 3 (value[i][2]) is Event Title info

Column 4 (value[i][3]) is Start Date

Column 5 (value[i][4]) is Start Time

Column 6 (value[i][5]) is End Date

Column 7 (value[i][6]) is End Time

Column 8 (value[i][7]) contains 'y' if event has been pushed to
Calendar

Column 9 (value[i][8]) contains EventID of event created by script

Columns after that have pertinent event info that can be added to the
event description

Body:
I'm having some trouble with my Google Apps Script code trying to have it take the information on one row of my sheet and create a single, Calendar event, with beginning and ending times.

    //push new events to calendar
function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();

  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
    if ((values[i][0].length == '<>') && (values[i][1].length == '<>') && (values[i][4].length == '<>') && (values[i][5].length == '<>') && (values[i][6].length == '<>') && (values[i][7].length == '<>')) {

      //check if it's been entered before
      if ((values[i][8] == '')||(values[i][8] == null)) {

        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = CalendarApp.getDefaultCalendar().createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();

        //mark as entered, enter ID
        sheet.getRange(i+2,8).setValue(newEventId);

      } //could edit here with an else statement
    }
    numValues++;
  }
}

I have pertinent information (used in the event title) in the first three columns, and Start Date in column 4, Start Time in column 5, End Date in column 6, and End Time in column 7. The other columns contain information that I'll add to the description of the event.

The problem I'm mostly running into is filtering the data set into events that have not been pushed to the Calendar yet, as well as the script accurately recording once it does push an event over, such that it will be able to filter it on the next cycle of the script.

Body:
I got it to work. I was referencing the wrong columns initially in the value check line. Silly me.

//push new events to calendar
function pushToCalendar() {

  //spreadsheet variables
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange(2,1,lastRow,16);
  var values = range.getValues();

  //calendar variables
  var defaultCalendar = CalendarApp.getDefaultCalendar()

  var numValues = 0;
  for (var i = 0; i < values.length; i++) {
    //check to see if Age, Competition, Start Date, Start Time and End Date & Time are filled out
  if ((values[i][0]) && (values[i][1]) && (values[i][3]) && (values[i][4]) && (values[i][5]) && (values[i][6]))
  {

      //check if it's been entered before
      if (values[i][8] != 'y') {

        //create event https://developers.google.com/apps-script/class_calendarapp#createEvent
        var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
        var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
        var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
        var start = startDay + ' ' + startTime;
        var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
        var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
        var end = endDay+ ' ' + endTime;
        var newEvent = defaultCalendar.createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][12]});
        //get ID
        var newEventId = newEvent.getId();

        //mark as entered, enter ID
        sheet.getRange(i+2,8).setValue('y');
        sheet.getRange(i+2,9).setValue(newEventId);

      } //could edit here with an else statement
    }

    numValues++;
  }
}

Spreadsheet has header row

Column 1 (value[i][0]) is Event Title info

Column 2 (value[i][1]) is Event Title info

Column 3 (value[i][2]) is Event Title info

Column 4 (value[i][3]) is Start Date

Column 5 (value[i][4]) is Start Time

Column 6 (value[i][5]) is End Date

Column 7 (value[i][6]) is End Time

Column 8 (value[i][7]) contains 'y' if event has been pushed to
Calendar

Column 9 (value[i][8]) contains EventID of event created by script

Columns after that have pertinent event info that can be added to the
event description


问:
Android Studio - Could not resolve all dependencies for configuration ':app:_debugApkCopy'
I am trying to run an Android Studio project, but when I do, it fails:

This post suggests that I should reinstall the android support repository, and this guide suggests that I should look in the Extras folder in the SDK Manager window, but there is no such folder:

This post says I should use the Launch Standalone SDK Manager button, but that also does not exist for me.

I'd appreciate help, thank you.

答:
Think you are missing the support libraries you need. They are not part of android sdk.

build.gradle:

```<code>compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:appcompat-v7:25.2.0'
</code>```

just a copy paste, try out which one you really need at the end. Also the versions should be as your exception tells you

Body:
Think you are missing the support libraries you need. They are not part of android sdk.

build.gradle:

compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:appcompat-v7:25.2.0'

just a copy paste, try out which one you really need at the end. Also the versions should be as your exception tells you


问:
How do you wrap DynamicLayout text?
Hey there-  I'm creating a Live Wallpaper which includes text that is drawn directly to the canvas via a TextPaint and DynamicLayout object.  Within my DynamicLayout Object I set the width to the canvas width, and am now looking for a way to wrap the text that extends past the canvas.  Here is my text set up code:

```<code>    //token is my large text string
    TextPaint tp = new TextPaint();
    Layout sl = new DynamicLayout(token, tp, (int) canvasWidth, Layout.Alignment.ALIGN_NORMAL, 0, 0, true);
    canvas.translate(startPositionX , startPositionY);
    sl.draw(canvas);
</code>```

How do I wrap this text if it extends past the canvasWidth?  Any help is appreciated!

答:
Got this after a few hours... looking to StringTokenizer, finding the longest word from my string and wrapping the remaining text to that width.</p>

```<code>// Assume s contains a string of words
String longestWord = "";
StringTokenizer st = new StringTokenizer(s, " ,\t");
while (st.hasMoreTokens()) {
    String w = st.nextToken();
    if (w.length() > longestWord.length()) {
        longestWord = w;
    }
}

float textWidth = tp.measureText(longestWord+" ");
Layout sl = new DynamicLayout(token, tp, (int) textWidth, Layout.Alignment.ALIGN_CENTER, lineSpacing, 0, true);
</code>```

Title: How do you wrap DynamicLayout text?

Body:
Hey there-  I'm creating a Live Wallpaper which includes text that is drawn directly to the canvas via a TextPaint and DynamicLayout object.  Within my DynamicLayout Object I set the width to the canvas width, and am now looking for a way to wrap the text that extends past the canvas.  Here is my text set up code:

    //token is my large text string
    TextPaint tp = new TextPaint();
    Layout sl = new DynamicLayout(token, tp, (int) canvasWidth, Layout.Alignment.ALIGN_NORMAL, 0, 0, true);
    canvas.translate(startPositionX , startPositionY);
    sl.draw(canvas);

How do I wrap this text if it extends past the canvasWidth?  Any help is appreciated!

Body:
Got this after a few hours... looking to StringTokenizer, finding the longest word from my string and wrapping the remaining text to that width.

// Assume s contains a string of words
String longestWord = "";
StringTokenizer st = new StringTokenizer(s, " ,\t");
while (st.hasMoreTokens()) {
    String w = st.nextToken();
    if (w.length() > longestWord.length()) {
        longestWord = w;
    }
}

float textWidth = tp.measureText(longestWord+" ");
Layout sl = new DynamicLayout(token, tp, (int) textWidth, Layout.Alignment.ALIGN_CENTER, lineSpacing, 0, true);


问:
Why isn't my range regex syntax working?
I'm using Ruby 2.4.  I want to say match a string that contains between 3 and 4 consecutive numbers.  But my braces syntax isn't working

```<code>2.4.0 :034 > data = "1234"
 => "1234"
2.4.0 :035 > data =~ /\d{3, 4}/
 => nil
</code>```

What's the ocrrect way to say this?

答:
Your regex is interpreted as

```<code> \d{3,[ ]4}
</code>```

That's why it doesn't work.

Remove the space

Your regex is trying to match this

```<code> \d       # digit
 {        # literal
 3        # literal
 ,        # literal
 [ ]      # class
 4        # literal
 }        # literal
</code>```

Body:
I'm using Ruby 2.4.  I want to say match a string that contains between 3 and 4 consecutive numbers.  But my braces syntax isn't working

2.4.0 :034 > data = "1234"
 => "1234"
2.4.0 :035 > data =~ /\d{3, 4}/
 => nil

What's the ocrrect way to say this?

Body:
Your regex is interpreted as

 \d{3,[ ]4}

That's why it doesn't work.

Remove the space

Your regex is trying to match this

 \d       # digit
 {        # literal
 3        # literal
 ,        # literal
 [ ]      # class
 4        # literal
 }        # literal