问:
Calculations in childs using pipes
My task is

a. A parent and two childs

b. Parent take data from the user

c. Send to a child for addition and subtraction.

d. Again take input from user and send to another child for multiplication and division.

e. First child process creates another child C3.

f. Both the childs send result to the child process C3 to show output.

g. Parent process after completion of each child process task kill the process.

I've write the following code but i don't know where I'm doing wrong, I tried to debug it but I do not know what is wrong with it, it not showing the multiplication and division result.

Here is my code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include <stdlib.h>

int main()
{
    int status = 0;
    int pfds[2];
    int pfds2[2];
    int pfds3[2];
    int pfds4[2];
    int val = 0;
    int val2 = 0;
    pipe(pfds);
    pipe(pfds2);
    pipe(pfds3);
    pipe(pfds4);
    printf("Enter FIRST Number:  ");
    scanf("%i", &val);
    printf("Enter SECOND Number:  ");
    scanf("%i", &val2);
    if (fork() == 0)
    {
//Child
        printf("I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers\n");
        read(pfds[0], &val, sizeof(val));
        read(pfds2[0], &val2, sizeof(val));
        int sum = val + val2;
        int sub = val - val2;
        write(pfds3[1], &sum, sizeof(val));
        write(pfds4[1], &sub, sizeof(val));
        if (fork() == 0)
        {
            read(pfds3[0], &val, sizeof(val));
            printf("Sum Of Numbers Is : %i\n", val);
            read(pfds4[0], &val, sizeof(val));
            printf("Sub Of Numbers Is : %i\n", val);
            read(pfds[0], &val, sizeof(val));
            printf("Mul Of Numbers Is : %i\n", val);
            read(pfds2[0], &val, sizeof(val));
            printf("Div Of Numbers Is : %i\n", val);
            exit(1);
        }
        else
        {
            wait(&status);
        }
        exit(1);
    }
    else
    {
        if (fork() == 0)
        {
//Child2
            printf("I'm Child 2 and I'm Calculating Multiplication and Division Of Number\n");
            read(pfds[0], &val, sizeof(val));
            read(pfds2[0], &val2, sizeof(val));
            int mul = val * val2;
            int div = val / val2;
            write(pfds[1], &mul, sizeof(val));
            write(pfds2[1], &div, sizeof(val));
            exit(0);
        }
        else
        {
//wait(&status);
            write(pfds[1], &val, sizeof(val));
            write(pfds2[1], &val2, sizeof(val));
            wait(&status);
        } //else1
    } //else2
} //main
</code>```

It's giving me the following output:

```<code>Enter FIRST Number:  4
Enter SECOND Number:  2
I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers
I'm Child 2 and I'm Calculating Multiplication and Division Of Number
Sum Of Numbers Is : 6
Sub Of Numbers Is : 2
</code>```

If someone can help thankyou very much.

答:
The problem is likely that the grandchild consumes one of the data meant to be read by child 2 as its input.  Child 2 then hangs trying to read from the pipe, because it itself is the only processes left to write anything to that pipe, and it cannot do so until it has finished its read.  This can happen because all three children read inputs from the same two pipes, without any (other) synchronization between processes.

Overall, your strategy is dubious.  It is much safer and more robust to designate each pipe end for use by exactly one process, and thus to designate each whole pipe for communication between exactly one pair of processes.  Switching to this strategy would require the same number of pipes, but a different pattern of usage:

on pipe 0, the parent sends the two inputs to child 1, one after the other

on pipe 1, the parent sends the two inputs to child 2, one after the other

on pipe 2, child 1 sends its results to the grandchild / child 3, one after the other

on pipe 3, child 2 sends its results to the grandchild / child 3, one after the other

That way, there is no possibility of one of the processes mistakenly consuming data meant for a different one, or to mistake the source and therefore the meaning of any of the data sent to it.

Title: Calculations in childs using pipes

Body:
My task is

a. A parent and two childs

b. Parent take data from the user

c. Send to a child for addition and subtraction.

d. Again take input from user and send to another child for multiplication and division.

e. First child process creates another child C3.

f. Both the childs send result to the child process C3 to show output.

g. Parent process after completion of each child process task kill the process.

I've write the following code but i don't know where I'm doing wrong, I tried to debug it but I do not know what is wrong with it, it not showing the multiplication and division result.

Here is my code:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include <stdlib.h>

int main()
{
    int status = 0;
    int pfds[2];
    int pfds2[2];
    int pfds3[2];
    int pfds4[2];
    int val = 0;
    int val2 = 0;
    pipe(pfds);
    pipe(pfds2);
    pipe(pfds3);
    pipe(pfds4);
    printf("Enter FIRST Number:  ");
    scanf("%i", &val);
    printf("Enter SECOND Number:  ");
    scanf("%i", &val2);
    if (fork() == 0)
    {
//Child
        printf("I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers\n");
        read(pfds[0], &val, sizeof(val));
        read(pfds2[0], &val2, sizeof(val));
        int sum = val + val2;
        int sub = val - val2;
        write(pfds3[1], &sum, sizeof(val));
        write(pfds4[1], &sub, sizeof(val));
        if (fork() == 0)
        {
            read(pfds3[0], &val, sizeof(val));
            printf("Sum Of Numbers Is : %i\n", val);
            read(pfds4[0], &val, sizeof(val));
            printf("Sub Of Numbers Is : %i\n", val);
            read(pfds[0], &val, sizeof(val));
            printf("Mul Of Numbers Is : %i\n", val);
            read(pfds2[0], &val, sizeof(val));
            printf("Div Of Numbers Is : %i\n", val);
            exit(1);
        }
        else
        {
            wait(&status);
        }
        exit(1);
    }
    else
    {
        if (fork() == 0)
        {
//Child2
            printf("I'm Child 2 and I'm Calculating Multiplication and Division Of Number\n");
            read(pfds[0], &val, sizeof(val));
            read(pfds2[0], &val2, sizeof(val));
            int mul = val * val2;
            int div = val / val2;
            write(pfds[1], &mul, sizeof(val));
            write(pfds2[1], &div, sizeof(val));
            exit(0);
        }
        else
        {
//wait(&status);
            write(pfds[1], &val, sizeof(val));
            write(pfds2[1], &val2, sizeof(val));
            wait(&status);
        } //else1
    } //else2
} //main

It's giving me the following output:

Enter FIRST Number:  4
Enter SECOND Number:  2
I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers
I'm Child 2 and I'm Calculating Multiplication and Division Of Number
Sum Of Numbers Is : 6
Sub Of Numbers Is : 2

If someone can help thankyou very much.


来源: stackexchange

问:
Which browsers support page break manipulation using CSS and the page-break-inside element?
I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).

I've tried all the tutorials that supposedly describe exactly how to do this, but nothing works. Is this an issue of browser support or has anyone actually gotten this working, the exact bit of CSS looks like this:

```<code>@media print {

  .noPageBreak {
     page-break-inside : avoid;
  }
}
</code>```

答:
Firefox does not support this as of 2010-11-30, and thus won't in Firefox 4.

IE8 does support page-break-inside: avoid - but when I tried this on IE9, it's not very successful at avoiding page-breaks (this may be a regression, or perhaps IE8 is also only capable of avoiding page breaks in very simple cases).

AFAIK it doesn't work in any webkit browser; certainly not in chrome.

It actually works in Opera, even on real sites.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).

I've tried all the tutorials that supposedly describe exactly how to do this, but nothing works. Is this an issue of browser support or has anyone actually gotten this working, the exact bit of CSS looks like this:

@media print {

  .noPageBreak {
     page-break-inside : avoid;
  }
}

LastEditorDisplayName: Xian

ContentLicense: CC BY-SA 2.5


问:
read txt file line by line java using eclipe
Code:

```<code>    try {
    FileReader reader = new FileReader("rn.txt");
    BufferedReader bufferedReader = new BufferedReader(reader);

    String line;

    while ((line = bufferedReader.readLine()) != null) {
     System.out.println(line);
    }
    reader.close();

   } catch (IOException e) {
    e.printStackTrace();
   }
</code>```

rn.txt file contents:

```<code>12
45
78
23
45
</code>```

Console output:

```<code>0
/
N
K
M
^

.
:
P
/
G
0

?

8
W
3
</code>```

Question:
How can I read the actual data in the .txt file? Is there an issue with the code I have written?

EDIT:

this my console output and where i put my txt file

答:
```<code>  try {
                FileReader reader = new FileReader("F://angular pdf/rn.txt");
                BufferedReader bufferedReader = new BufferedReader(reader);

                String line =bufferedReader.readLine();

                while (line != null) {
                    System.out.println(line);
                   line= bufferedReader.readLine();
                }
                reader.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
</code>```

Body:
Code:

    try {
    FileReader reader = new FileReader("rn.txt");
    BufferedReader bufferedReader = new BufferedReader(reader);

    String line;

    while ((line = bufferedReader.readLine()) != null) {
     System.out.println(line);
    }
    reader.close();

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

rn.txt file contents:

12
45
78
23
45

Console output:

0
/
N
K
M
^

.
:
P
/
G
0

?

8
W
3

Question:
How can I read the actual data in the .txt file? Is there an issue with the code I have written?

EDIT:

this my console output and where i put my txt file


问:
UrlGenerationError in rspec test
I've been tasked with creating custom error pages that fall in line with our application. I found https://wearestac.com/blog/dynamic-error-pages-in-rails which works perfectly fine. I don't get any routing errors and manually testing shows that each page renders correctly.

However, when creating controller specs for the controller used to delegate the routes to the views, I am running into an issue. My views are named 404.html.erb, 500.html.erb, 422.html.erb. They are located in app/views. My code is almost exactly the same as what is listed in the link above, however for posterity and clarity, the relevant code is shown below as well as the error message is shown below:

Error message: ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"errors", :params=>{:code=>"404"}}

app/controllers/errors_controller.rb:

```<code># frozen_string_literal: true
class ErrorsController < ApplicationController
  def show
    render status_code.to_s, status: status_code
  end

  protected

  # get status code from params, default 500 in cases where no error code
  def status_code
    params[:code] || 500
  end
end
</code>```

spec/controllers/errors_controller_spec.rb:

```<code>require 'rails_helper'

describe ErrorsController, type: :controller do

    describe '#show' do
      it 'renders the 404 error page when it receives a 404 status code' do
      get :show, params: { code: '404' }
      # ive also tried changing the param passed to redirect_to to error_404 to no effect
      expect(response).to redirect_to(error_404_path)
    end

    it 'renders the 422 error page when it receives a 422 status code' do
      get :show, params: { code: '422' }
      expect(response).to redirect_to(error_422_path)
    end

    it 'renders the 500 error page when it receives a 500 status code' do
      get :show, params: { code: '500' }
      expect(response).to redirect_to(error_500_path)
    end
  end
end
</code>```

config/routes.rb (only the relevant route, our full routes file is gigantic)

```<code>%w(404 422 500).each do |code|
  get code, to: "errors#show", code: code, as: 'error_' + code
end
</code>```

config/application.rb (only the relevant line, everything else is standard):

```<code>config.exceptions_app = self.routes
</code>```

I have tried expanding the routes so that each was explicitly defined, as well as reverting to the first non-DRY form in the link. I've also tried changing the redirect_to call to a render_template call, to no effect.

I've scratched my head for days hoping to figure it out but I've had no luck. Again, the route works perfectly fine in development, but when I try to test that these routes work in rspec, it can't find any route.

The error message is the same for each spec in the file, aside from the status code. Any help would be appreciated!

答:
Try to add :id param to get method. Show action route is expecting an :id param (url for show action without :id param is actually index action url).

```<code>get :show, params: { id: 1, code: '422' }
</code>```

Title: UrlGenerationError in rspec test

Body:
I've been tasked with creating custom error pages that fall in line with our application. I found https://wearestac.com/blog/dynamic-error-pages-in-rails which works perfectly fine. I don't get any routing errors and manually testing shows that each page renders correctly.

However, when creating controller specs for the controller used to delegate the routes to the views, I am running into an issue. My views are named 404.html.erb, 500.html.erb, 422.html.erb. They are located in app/views. My code is almost exactly the same as what is listed in the link above, however for posterity and clarity, the relevant code is shown below as well as the error message is shown below:

Error message: ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"errors", :params=>{:code=>"404"}}

app/controllers/errors_controller.rb:

# frozen_string_literal: true
class ErrorsController < ApplicationController
  def show
    render status_code.to_s, status: status_code
  end

  protected

  # get status code from params, default 500 in cases where no error code
  def status_code
    params[:code] || 500
  end
end

spec/controllers/errors_controller_spec.rb:

require 'rails_helper'

describe ErrorsController, type: :controller do

    describe '#show' do
      it 'renders the 404 error page when it receives a 404 status code' do
      get :show, params: { code: '404' }
      # ive also tried changing the param passed to redirect_to to error_404 to no effect
      expect(response).to redirect_to(error_404_path)
    end

    it 'renders the 422 error page when it receives a 422 status code' do
      get :show, params: { code: '422' }
      expect(response).to redirect_to(error_422_path)
    end

    it 'renders the 500 error page when it receives a 500 status code' do
      get :show, params: { code: '500' }
      expect(response).to redirect_to(error_500_path)
    end
  end
end

config/routes.rb (only the relevant route, our full routes file is gigantic)

%w(404 422 500).each do |code|
  get code, to: "errors#show", code: code, as: 'error_' + code
end

config/application.rb (only the relevant line, everything else is standard):

config.exceptions_app = self.routes

I have tried expanding the routes so that each was explicitly defined, as well as reverting to the first non-DRY form in the link. I've also tried changing the redirect_to call to a render_template call, to no effect.

I've scratched my head for days hoping to figure it out but I've had no luck. Again, the route works perfectly fine in development, but when I try to test that these routes work in rspec, it can't find any route.

The error message is the same for each spec in the file, aside from the status code. Any help would be appreciated!

Body:
Try to add :id param to get method. Show action route is expecting an :id param (url for show action without :id param is actually index action url).

get :show, params: { id: 1, code: '422' }


问:
How to add link to  in thymeleaf using datatables and make it display correctly without page reloading
I making a simple CRUD web application using spring boot(1.5.2.RELEASE) + thymeleaf(2.1.5) + datatables(1.10.13) + jQuery(3.1.1) + Bootstrap(3.3.7). Everything works fine, but the problem is to make it display links correctly after adding new row from form.
(table_view_issue)
And after I reload the page - it's OK.
So, this is my table:

```<code><table id="table_users" class="display" cellspacing="0" width="100%">
                <thead>
                <tr>
                    <th class="text-center">NAME</th>
                    <th class="text-center">AGE</th>
                    <th class="text-center">ADDRESS</th>
                    <th class="text-center">DELETE</th>
                    <th class="text-center">EDIT</th>
                </tr>
                </thead>
                <tbody>
                <tr class="text-center" th:each="user : ${users}">
                    <td th:text="${user.name}"></td>
                    <td th:text="${user.age}"></td>
                    <td th:text="${user.address}"></td>
                    <td><a th:href="'/delete/' + ${user.id}">Delete</a></td>
                    <td><a th:href="'/edit/' + ${user.id}">Edit</a></td>
                </tr>
                </tbody>
            </table>
</code>```

form for adding:

```<code>    <form id="userForm" class="form-horizontal">
        <div class="form-group">
            <label class="col-sm-4 control-label" for="name">Name: </label>
            <div class="col-sm-4">
                <input class="form-control" id="name" name="name" type="text" th:minlength="1" th:maxlength="15"
                       th:required="required"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-4 control-label" for="age">Age: </label>
            <div class="col-sm-4">
                <input class="form-control" id="age" name="age" type="number" th:min="1" th:max="130"
                       th:required="required"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-4 control-label" for="address">Address: </label>
            <div class="col-sm-4">
                <input class="form-control" id="address" name="address" type="text" th:minlength="5"
                       th:required="required"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-4 col-sm-10">
                <input class="btn btn-success" type="submit" value="Add"/>
                <input class="btn btn-warning" type="reset" value="Reset"/>
            </div>
        </div>
    </form>
</code>```

script for datatables:

```<code>$(document).ready(function () {
    $('#table_users').DataTable({
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
    });
});
</code>```

script to add user:

```<code><script type="text/javascript">
        $(document).ready(function () {
            $("#userForm").submit(function (event) {
                // Prevent the form from submitting via the browser.
                event.preventDefault();
                ajaxPost();
            });

            function ajaxPost() {

                // PREPARE FORM DATA
                var formData = {
                    name: $("#name").val(),
                    age: $("#age").val(),
                    address: $("#address").val()
                };

                // DO POST
                $.ajax({
                    type: "post",
                    contentType: "application/json",
                    url: "/add",
                    data: JSON.stringify(formData),
                    dataType: 'json',
                    success: addData()
                });

                function addData() {
                    var deleteCell = '<td><a>Delete</a></td>';
                    var editCell = '<td><a>Edit</a></td>';

                    var rowAdded = $('#table_users').DataTable()
                        .row.add(
                        [
                            formData.name,
                            formData.age,
                            formData.address,
                            $(deleteCell).find('a').attr('href', '/delete/${user.id}'),
                            $(editCell).find('a').attr('href', '/edit/${user.id}')
                        ]
                    ).draw(false).node();

                    $(rowAdded).addClass('text-center');
                }

                // Reset FormData after Posting
                resetData();

            }

            function resetData() {
                $("#name").val("");
                $("#age").val("");
                $("#address").val("");
            }
        });
    </script>
</code>```

Is it possible to do that without reloading? Thanks!

答:
Problem 1 - Displaying the link in the table

I think that the problem is caused by the following two lines:

```<code>$(deleteCell).find('a').attr('href', '/delete/${user.id}'),
$(editCell).find('a').attr('href', '/edit/${user.id}')
</code>```

You are not adding the deleteCell and the editCell but the return value of attr... According to the jQuery doc the return value is a jQuery reference. We can fix this by binding the url first and insert the element afterwards:

```<code>function addData() {
    var deleteCell = $('<td><a>Delete</a></td>');
    var editCell = $('<td><a>Edit</a></td>');
    // bind href first and insert the cells later
    deleteCell.find('a').attr('href', '/delete/${user.id}'),
    editCell.find('a').attr('href', '/edit/${user.id}')
    var rowAdded = $('#table_users').DataTable()
        .row.add(
        [
            formData.name,
            formData.age,
            formData.address,
            deleteCell,
            editCell
        ]
    ).draw(false).node();
}
</code>```

Problem 2 - Actually generating the correct link...

I don't think that ${user.id} will be resolved to the actually userId in your Javascript. Thymeleaf can also be used for parsing javascript. However I don't think that it should be used like that in your case as you are using ajax requests any way.

There are some disadvantages when generating the new table row by using the form data:

if the server changes the format of the input (e.g. removing trailing whitespace) the user would still see the old format of the text as your table gathers the information from the form itself.

form validation (e.g. displaying error messages if the input was wrong). You could of course just validate the input on the client side. However be warned! Validating on the client side WONT stop bad requests from happening as we are not forced to use your from to submit data to your server.

That's why I'd suggest sending the validated data back to your client as an answer to your ajax request. The validated data can now also include your userId. This is a little more complex so i will only go into details if you want.

Title: How to add link to <td> in thymeleaf using datatables and make it display correctly without page reloading

Body:
I making a simple CRUD web application using spring boot(1.5.2.RELEASE) + thymeleaf(2.1.5) + datatables(1.10.13) + jQuery(3.1.1) + Bootstrap(3.3.7). Everything works fine, but the problem is to make it display links correctly after adding new row from form.
(table_view_issue)
And after I reload the page - it's OK.
So, this is my table:

                    NAME
                    AGE
                    ADDRESS
                    DELETE
                    EDIT

                    Delete
                    Edit

form for adding:

    <form id="userForm" class="form-horizontal">

            Name:

                <input class="form-control" id="name" name="name" type="text" th:minlength="1" th:maxlength="15"
                       th:required="required"/>

            Age:

                <input class="form-control" id="age" name="age" type="number" th:min="1" th:max="130"
                       th:required="required"/>

            Address:

                <input class="form-control" id="address" name="address" type="text" th:minlength="5"
                       th:required="required"/>

                <input class="btn btn-success" type="submit" value="Add"/>
                <input class="btn btn-warning" type="reset" value="Reset"/>

    </form>

script for datatables:

$(document).ready(function () {
    $('#table_users').DataTable({
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
    });
});

script to add user:

Is it possible to do that without reloading? Thanks!

Body:
Problem 1 - Displaying the link in the table

I think that the problem is caused by the following two lines:

$(deleteCell).find('a').attr('href', '/delete/${user.id}'),
$(editCell).find('a').attr('href', '/edit/${user.id}')

You are not adding the deleteCell and the editCell but the return value of attr... According to the jQuery doc the return value is a jQuery reference. We can fix this by binding the url first and insert the element afterwards:

function addData() {
    var deleteCell = $('<td><a>Delete</a></td>');
    var editCell = $('<td><a>Edit</a></td>');
    // bind href first and insert the cells later
    deleteCell.find('a').attr('href', '/delete/${user.id}'),
    editCell.find('a').attr('href', '/edit/${user.id}')
    var rowAdded = $('#table_users').DataTable()
        .row.add(
        [
            formData.name,
            formData.age,
            formData.address,
            deleteCell,
            editCell
        ]
    ).draw(false).node();
}

Problem 2 - Actually generating the correct link...

I don't think that ${user.id} will be resolved to the actually userId in your Javascript. Thymeleaf can also be used for parsing javascript. However I don't think that it should be used like that in your case as you are using ajax requests any way.

There are some disadvantages when generating the new table row by using the form data:

if the server changes the format of the input (e.g. removing trailing whitespace) the user would still see the old format of the text as your table gathers the information from the form itself.

form validation (e.g. displaying error messages if the input was wrong). You could of course just validate the input on the client side. However be warned! Validating on the client side WONT stop bad requests from happening as we are not forced to use your from to submit data to your server.

That's why I'd suggest sending the validated data back to your client as an answer to your ajax request. The validated data can now also include your userId. This is a little more complex so i will only go into details if you want.


问:
Angular validation after submit
I have form fields that are validated using required. The problem is, that the error is displayed immediately when the form is rendered. I want it only to be displayed after the user submit.

My question is similar to this one.

but in my case, I have more than one buttom in the form, so I don't understand how to implement the ng-submit or a solution to my problem.

This is my Plunker
 of what I want to do.

HTML form:

```<code>  <form name="myForm">
    <table>
      <tr>
        <td>
          <input type="text" ng-model="oldName">
        </td>
        <td>
          <button ng-click="copyName()"> Copy >> </button>
        </td>
        <td>
          <input type="text" name="newName" ng-model="newName" required>
        </td>
      </tr>
       <tr>
        <td>
          <input type="text" ng-model="oldEmail">
        </td>
        <td>
          <button ng-click="copyEmail()"> Copy >> </button>
        </td>
        <td>
          <input type="email" name="newEmail" ng-model="newEmail">
        </td>
      </tr>
    </table>

    <br>
    <button ng-click="Submit()">Submit </button>

  </form>
</code>```

答:
You can simply put $scope.myForm.$setSubmitted() in your $scope.submit function which will set your form submitted. Now, in your error message's ng-show, you can have something like this:

```<code><div ng-show="myForm.$submitted && myForm.newEmail.$invalid">
  <strong>invalid email </strong>
</div>
</code>```

working plunker

Title: Angular validation after submit

Body:
I have form fields that are validated using required. The problem is, that the error is displayed immediately when the form is rendered. I want it only to be displayed after the user submit.

My question is similar to this one.

but in my case, I have more than one buttom in the form, so I don't understand how to implement the ng-submit or a solution to my problem.

This is my Plunker
 of what I want to do.

HTML form:

  <form name="myForm">

          <input type="text" ng-model="oldName">

          <button ng-click="copyName()"> Copy >> </button>

          <input type="text" name="newName" ng-model="newName" required>

          <input type="text" ng-model="oldEmail">

          <button ng-click="copyEmail()"> Copy >> </button>

          <input type="email" name="newEmail" ng-model="newEmail">

    <button ng-click="Submit()">Submit </button>

  </form>

Body:
You can simply put $scope.myForm.$setSubmitted() in your $scope.submit function which will set your form submitted. Now, in your error message's ng-show, you can have something like this:

<div ng-show="myForm.$submitted && myForm.newEmail.$invalid">
  <strong>invalid email </strong>
</div>

working plunker


问:
ps -ax shows me a "rack" process. Is this normal?
I run a webpage using the Ruby web-framework Sinatra on my Ubuntu server. Today I looked to my processes and found these two lines:

```<code>30129 ?        S      0:00 Passenger ApplicationSpawner: /var/www/bla.com
30139 ?        S      0:00 Rack: /var/www/bla.com
</code>```

I never noticed these before. Are these normal, or should I be concerned?

答:
From what I could find, Rack is used by Sinatra:

Sinatra rides on Rack, a minimal standard interface for Ruby web frameworks.

from http://www.sinatrarb.com/intro

Body:
I run a webpage using the Ruby web-framework Sinatra on my Ubuntu server. Today I looked to my processes and found these two lines:

30129 ?        S      0:00 Passenger ApplicationSpawner: /var/www/bla.com
30139 ?        S      0:00 Rack: /var/www/bla.com

I never noticed these before. Are these normal, or should I be concerned?


问:
Form with editable elements should have `editable-form` attribute
I have a form within which i have used x-editable plugin for editing a text-field. But i am getting the following script error. Can anyone please tell me some solution for this

```<code>Form with editable elements should have `editable-form` attribute. <span editable-text="user.name" e-form="textBtnForm" class="ng-scope ng-binding editable">
</code>```

Working Demo

html

```<code><div ng-app='myApp' ng-controller="ArrayController">
    <form action="#" >
        <span editable-text="user.name" e-form="textBtnForm">
    {{ user.name || 'empty' }}
        </span>
        <button class="btn btn-default" ng-click="textBtnForm.$show()" ng-hide="textBtnForm.$visible">edit
        </button>
    </form>
</div>
</code>```

script

```<code>var app = angular.module('myApp', ["xeditable"]);
app.controller('ArrayController', function ($scope) {
    $scope.test = "manu";
    $scope.user = {
        name: 'awesome user'
    };
});
</code>```

答:
the previous approach is partial correct and can be applied only if use a single input in that form. Also if you try to add more elements, then will not work correct.
So the right solution that i have is to use ng-form with editable-form directive as block for each form element (input) that you want apply the xedit plugin, and of course remove editable-form from main form.

the sample based by your code is below:

```<code><div ng-app='myApp' ng-controller="ArrayController">
  <form action="#" >
    <div ng-form editable-form name="textBtnForm">
      <span editable-text="user.name" ng-click="textBtnForm.$show()">{{user.name||'empty'}}</span>
      <span ng-show="textBtnForm.$visible">
        <button type="button" class="btn btn-primary" ng-disabled="textBtnForm.$waiting" ng-click="textBtnForm.$submit()">              Save</button>
        <button type="button" class="btn btn-default" ng-disabled="textBtnForm.$waiting" ng-click="textBtnForm.$cancel()">cancel</button>
    </span>
    </div>

    <hr>second form element<hr>

    <div ng-form editable-form name="textBtnForm2">
      <span editable-text="user.phone" ng-click="textBtnForm2.$show()">{{ user.phone || 'empty' }}</span>
      <span ng-show="textBtnForm2.$visible">
        <button type="button" ng-disabled="textBtnForm2.$waiting" ng-click="textBtnForm2.$submit()">Save</button>
        <button type="button" class="btn btn-default" ng-disabled="textBtnForm2.$waiting" ng-click="textBtnForm2.$cancel()">  Cancel</button>
      </span>
    </div>
  </form>
</div>
</code>```

Body:
I have a form within which i have used x-editable plugin for editing a text-field. But i am getting the following script error. Can anyone please tell me some solution for this

Form with editable elements should have `editable-form` attribute.

Working Demo

html

    <form action="#" >

    {{ user.name || 'empty' }}

        <button class="btn btn-default" ng-click="textBtnForm.$show()" ng-hide="textBtnForm.$visible">edit
        </button>
    </form>

script

var app = angular.module('myApp', ["xeditable"]);
app.controller('ArrayController', function ($scope) {
    $scope.test = "manu";
    $scope.user = {
        name: 'awesome user'
    };
});

Body:
the previous approach is partial correct and can be applied only if use a single input in that form. Also if you try to add more elements, then will not work correct.
So the right solution that i have is to use ng-form with editable-form directive as block for each form element (input) that you want apply the xedit plugin, and of course remove editable-form from main form.

the sample based by your code is below:

<div ng-app='myApp' ng-controller="ArrayController">
  <form action="#" >
    <div ng-form editable-form name="textBtnForm">
      <span editable-text="user.name" ng-click="textBtnForm.$show()">{{user.name||'empty'}}</span>
      <span ng-show="textBtnForm.$visible">
        <button type="button" class="btn btn-primary" ng-disabled="textBtnForm.$waiting" ng-click="textBtnForm.$submit()">              Save</button>
        <button type="button" class="btn btn-default" ng-disabled="textBtnForm.$waiting" ng-click="textBtnForm.$cancel()">cancel</button>
    </span>
    </div>

    <hr>second form element<hr>

    <div ng-form editable-form name="textBtnForm2">
      <span editable-text="user.phone" ng-click="textBtnForm2.$show()">{{ user.phone || 'empty' }}</span>
      <span ng-show="textBtnForm2.$visible">
        <button type="button" ng-disabled="textBtnForm2.$waiting" ng-click="textBtnForm2.$submit()">Save</button>
        <button type="button" class="btn btn-default" ng-disabled="textBtnForm2.$waiting" ng-click="textBtnForm2.$cancel()">  Cancel</button>
      </span>
    </div>
  </form>
</div>


问:
Difference in RabbitMq and RabbitMq with JMS plugin
I am new to JMS.
I am little aware of RabbitMq and now trying to find the difference in rabbitMQ with JMS. How it is used and why it should be used?

Thanks in advance.

答:
I'm not sure what you mean by RabbitMQ for JMS. But, i'll list out the differences below.

RabbitMQ

Works on AMQP protocol and it is not a J2EE specification

Applications written in several languages can produce and consume messages(Python, Ruby, Java, C#, Perl etc.,)

Does not work with J2EE specs, so you cannot use XA Transactions, bean pools, connection factory pools which are all provided by J2EE container by default

Community is not so mature, but, if your organization needs to communicate with a lot of different types and languages of applications you can sacrifice all the beautiful features that are provided by J2EE/JMS spec.

JMS

It is J2EE specification, any application server that provides JMS support should follow the guidelines mentioned in the spec.

Only the Java/J2EE applications can produce and consume, it can be made to work for other languages but with use of adapters

J2EE container provides XA Transaction, Bean pooling, Connection pooling etc., out of the box with little configuration at your end.

If your organization only uses Java based applications, you need not look in RabbitMQ way as you have JMS support which works well.


问:
Python inserts both a carriage return and a line feed after variable, instead of just line feed
I've created a python script to output every 1-4 character letter combinations from AAAA-ZZZZ etc.

It works perfectly, however I require only a line feed to be inserted at the end of the printed variable, since I am using this as a word list to be used in another script.

I have attempted to use both \r and \n, however using \n inserts both a Carriage Return and a Line Feed at the end (e.g AAAA CR LF), using \r inserts only a Carriage Return (e.g AAAA CR).

My question is would it be possible to insert just a line feed at the end, or is this impossible due to a limitation in python? i've tried using notepad to manually replace each character, and this works, however this is just patching up the problem and is impractical for use.

Many thanks for any help!

```<code>import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha)
x=(a+b+c for a in alpha for b in alpha for c in alpha)
y=(a+b for a in alpha for b in alpha)
z=(a for a in alpha )
with open("Output.txt", "w") as text_file:
for i in [w, x, y, z]:
    for k in i:
        print("{}\r".format(k), file=text_file, end='')
</code>```

the problem here is the line

```<code>print("{}\r".format(k), file=text_file, end='')
</code>```

答:
In Python3 print() basically adds new line upon every execution. For this purpose I'd suggest you to use sys module's write function. I also had the same problem when I was making a download bar.

Code-

```<code>import sys
sys.stdout.write('\r')
sys.stdout.flush()
</code>```

This should solve your problem.

Body:
I've created a python script to output every 1-4 character letter combinations from AAAA-ZZZZ etc.

It works perfectly, however I require only a line feed to be inserted at the end of the printed variable, since I am using this as a word list to be used in another script.

I have attempted to use both \r and \n, however using \n inserts both a Carriage Return and a Line Feed at the end (e.g AAAA CR LF), using \r inserts only a Carriage Return (e.g AAAA CR).

My question is would it be possible to insert just a line feed at the end, or is this impossible due to a limitation in python? i've tried using notepad to manually replace each character, and this works, however this is just patching up the problem and is impractical for use.

Many thanks for any help!

import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha)
x=(a+b+c for a in alpha for b in alpha for c in alpha)
y=(a+b for a in alpha for b in alpha)
z=(a for a in alpha )
with open("Output.txt", "w") as text_file:
for i in [w, x, y, z]:
    for k in i:
        print("{}\r".format(k), file=text_file, end='')

the problem here is the line

print("{}\r".format(k), file=text_file, end='')

Body:
In Python3 print() basically adds new line upon every execution. For this purpose I'd suggest you to use sys module's write function. I also had the same problem when I was making a download bar.

Code-

import sys
sys.stdout.write('\r')
sys.stdout.flush()

This should solve your problem.


问:
How to find out that user is no longer interacting with a page (not reload or exit)
I'd like to track time when user is interacting with the page. As far as I understand user can basically leave a page by

Navigating away (back/forward)

Closing window

Opening new tab and just keeping the old tab in the background

Switch tabs/windows

While I understand I can use "onbeforeunload" for 1 and 2, what can I do about 3 and 4? From my experience it's pretty usual to see people with many tabs open all the time in Chrome/Edge but interacting only with one.
Is there any nice trick how to find out that user "deactivated" tab/window?

答:
You could check for the blur event.

```<code>  window.addEventListener("blur", function( event ) {
    //DO something
  }, true);
</code>```

Body:
You could check for the blur event.

  window.addEventListener("blur", function( event ) {
    //DO something
  }, true);


问:
Java double colon operator reference (::)
Is

```<code>test::testMethod == test::testMethod
</code>```

true? I want to find out whether they will refer to the same object. This code does not compile. But there may be several situations in which this needs clarification.

I suspect that this will expand to

```<code>Runnable r = () -> test.testMethod()
Runnable r1 = () -> test.testMethod()
</code>```

And whether the below is true.

```<code>r == r1
</code>```

答:
even if your code could compile and the test::testMethod declared as Runnable the answer test::testMethod == test::testMethod is always return false, because you comparing with two diff class instances. for each lambda expression the compiler will create a synthentic anonymous inner class for it.for example:

```<code>//a synthentic anonymous lambda class A implemented Runnable
Runnable r = () -> test.testMethod();

//a synthentic anonymous lambda class B implemented Runnable
Runnable r1 = () -> test.testMethod();

r.getClass().equals(r1.getClass());// always return false
</code>```

Body:
Is

test::testMethod == test::testMethod

true? I want to find out whether they will refer to the same object. This code does not compile. But there may be several situations in which this needs clarification.

I suspect that this will expand to

Runnable r = () -> test.testMethod()
Runnable r1 = () -> test.testMethod()

And whether the below is true.

r == r1

Body:
even if your code could compile and the test::testMethod declared as Runnable the answer test::testMethod == test::testMethod is always return false, because you comparing with two diff class instances. for each lambda expression the compiler will create a synthentic anonymous inner class for it.for example:

//a synthentic anonymous lambda class A implemented Runnable
Runnable r = () -> test.testMethod();

//a synthentic anonymous lambda class B implemented Runnable
Runnable r1 = () -> test.testMethod();

r.getClass().equals(r1.getClass());// always return false


问:
How to initialize a struct from a json object
HI i am new to swift any idea . How to initialize a struct from a json object . i could not figure out how can i do it .

{
   "user": {
     "name": "cruskuaka",
     "email": "cristlika@gmail.com",
     "phoneNo":"018833455"
   },
   "address": {
     "house": "100",
     "street": "B",
     "town":
     {
     "town_id": "1",
     "town_name": "Galway city center"
     },
     "city":
     {
     "city_id": "10",
     "city_name": "Galway"
     },
     "address_id":"200",
     "full_address":"100, B, Galway city center,Galway"
   },
   "delivery_instruction": "no call",
   "delivery_method": "1"
  }

Here all struct :

```<code>struct Contact  {
    let user : User
    let address : Address
    let deliveryInstruction : String
    let deliveryMethod : String
    init(dictionary: [String: Any]) {
        self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? ""
        self.deliveryMethod = dictionary["delivery_method"] as? String ?? ""
        self.address = Address(dictionary: dictionary["address"] as? [String:Any] ?? [:])
        self.user =  User(dictionary: dictionary["address"] as? [String:Any] ?? [:])
    }
  }
</code>```

```<code>struct User {
    let name : String
    let email : String
    let phoneNo : String
    init(dictionary : [String:Any] ) {
        self.name = dictionary["name"] as? String ?? ""
        self.email = dictionary["email"] as? String ?? ""
        self.phoneNo = dictionary["phoneNo"] as? String ?? ""
    }
}
</code>```

```<code>struct Address  {
    let city : City
    let town : Town
    let addressId : String
    let fullAddress : String
    let house : String
    let street: String
    init(dictionary : [String:Any] ) {
        self.addressId = dictionary["address_id"] as? String ?? ""
        self.fullAddress = dictionary["full_address"] as? String ?? ""
        self.house = dictionary["house"] as? String ?? ""
        self.street = dictionary["street"] as? String ?? ""
        self.city = City(dictionary: dictionary["address"] as? [String:Any] ?? [:])
        self.town = Town(dictionary: dictionary["address"] as? [String:Any] ?? [:])
    }
}
</code>```

```<code>struct City {
    let cityId : String
    let cityName : String
    init(dictionary : [String:Any] ) {
        self.cityId = dictionary["city_id"] as? String ?? ""
        self.cityName = dictionary["city_name"] as? String ?? ""
    }
}
</code>```

```<code>struct Town {
    let townId : String
    let townName : String
    init(dictionary : [String:Any]) {
        self.townId = dictionary["town_id"] as? String ?? ""
        self.townName = dictionary["town_name"] as? String ?? ""
    }
}
</code>```

答:
edit/update: Swift 4 or later you can use Codable Protocol:

```<code>struct Root: Codable {
    let user: User
    let address: Address
    let deliveryInstruction, deliveryMethod: String
}
</code>```

```<code>struct Address: Codable {
    let house, street, addressId, fullAddress: String
    let town: Town
    let city: City
}
</code>```

```<code>struct City: Codable {
    let cityId, cityName: String
}
</code>```

```<code>struct Town: Codable {
    let townId, townName: String
}
</code>```

```<code>struct User: Codable {
    let name, email, phoneNo: String
}
</code>```

```<code>extension Decodable {
    init(data: Data, using decoder: JSONDecoder = .init()) throws {
        self = try decoder.decode(Self.self, from: data)
    }
    init(json: String, using decoder: JSONDecoder = .init()) throws {
        try self.init(data: Data(json.utf8), using: decoder)
    }
}
</code>```

Just don't forget to set the JSONDecoder property keyDecodingStrategy to .convertFromSnakeCase:

```<code>let json = """
{"user": {"name": "crst","email": "crat@gmail.com","phoneNo":"018833455"},"address": {"house": "100","street": "B","town":{"town_id": "1","town_name": "Galway city center"},"city":{"city_id": "10","city_name": "Galway"},"address_id":"200", "full_address":"100, B, Galway city center,Galway" },"delivery_instruction": "no call","delivery_method": "1" }
"""

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let root = try decoder.decode(Root.self, from: Data(json.utf8))
    print(root)
} catch {
    print(error)
}
</code>```

or simply:

```<code>do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let root = try Root(json: json, using: decoder)  // or  Root(data: data, using: decoder)
    print(root)
} catch {
    print(error)
}
</code>```

This will print

Root(user: __lldb_expr_112.User(name: "cruskuaka", email:
"cristlika@gmail.com", phoneNo: "018833455"), address:
__lldb_expr_112.Address(house: "100", street: "B", addressId: "200", fullAddress: "100, B, Galway city center,Galway", town:
__lldb_expr_112.Town(townId: "1", townName: "Galway city center"), city: __lldb_expr_112.City(cityId: "10", cityName: "Galway")),
deliveryInstruction: "no call", deliveryMethod: "1")

Original Answer (before Codable protocol)

Swift 3

You have more than one error in your code, but you are in the right path. You are using the wrong key when initializing your user, city and town structs. I have also created two more initializers so you can initialize your struct with a dictionary, the json string or just its data:

```<code>struct Contact: CustomStringConvertible  {
    let user: User
    let address: Address
    let deliveryInstruction: String
    let deliveryMethod: String
    // customize the description to your needs
    var description: String { return "\(user.name) \(deliveryInstruction) \(deliveryMethod)" }
    init(dictionary: [String: Any]) {
        self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? ""
        self.deliveryMethod = dictionary["delivery_method"] as? String ?? ""
        self.address = Address(dictionary: dictionary["address"] as? [String: Any] ?? [:])
        self.user =  User(dictionary: dictionary["user"] as? [String: Any] ?? [:])
    }
    init?(data: Data) {
        guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }
        self.init(dictionary: json)
    }
    init?(json: String) {
        self.init(data: Data(json.utf8))
    }

}
</code>```

```<code>struct User: CustomStringConvertible {
    let name: String
    let email: String
    let phone: String
    let description: String
    init(dictionary: [String: Any]) {
        self.name = dictionary["name"] as? String ?? ""
        self.email = dictionary["email"] as? String ?? ""
        self.phone = dictionary["phoneNo"] as? String ?? ""
        self.description = "name: \(name) - email: \(email) - phone: \(phone)"
    }
}
</code>```

```<code>struct Address: CustomStringConvertible  {
    let id: String
    let street: String
    let house: String
    let city: City
    let town: Town
    let description: String
    init(dictionary: [String: Any] ) {
        self.id = dictionary["address_id"] as? String ?? ""
        self.description = dictionary["full_address"] as? String ?? ""
        self.house = dictionary["house"] as? String ?? ""
        self.street = dictionary["street"] as? String ?? ""
        self.city = City(dictionary: dictionary["city"] as? [String: Any] ?? [:])
        self.town = Town(dictionary: dictionary["town"] as? [String: Any] ?? [:])
    }
}
</code>```

```<code>struct City: CustomStringConvertible {
    let id: String
    let name: String
    // customize the description to your needs
    var description: String { return name }
    init(dictionary: [String: Any] ) {
        self.id = dictionary["city_id"] as? String ?? ""
        self.name = dictionary["city_name"] as? String ?? ""
    }

}
</code>```

```<code>struct Town: CustomStringConvertible {
    let id: String
    let name: String
    // customize the description to your needs
    var description: String { return name }
    init(dictionary: [String: Any]) {
        self.id = dictionary["town_id"] as? String ?? ""
        self.name = dictionary["town_name"] as? String ?? ""
    }
}
</code>```

Testing the initialization from JSON:

```<code>let contact = Contact(json: json)   // crst no call 1

contact               // crst no call 1
contact?.user         // name: crst - email: crat@gmail.com - phone: 018833455
contact?.user.name    //  "crst"
contact?.user.email   //  "crat@gmail.com"
contact?.user.phone   //  "018833455"
contact?.address      //  100, B, Galway city center,Galway
contact?.address.id           //  200
contact?.address.street       //  B
contact?.address.town         // Galway city center
contact?.address.city         //  Galway
contact?.deliveryInstruction  // "no call"
contact?.deliveryMethod       //    1
</code>```

Body:
HI i am new to swift any idea . How to initialize a struct from a json object . i could not figure out how can i do it .

{
   "user": {
     "name": "cruskuaka",
     "email": "cristlika@gmail.com",
     "phoneNo":"018833455"
   },
   "address": {
     "house": "100",
     "street": "B",
     "town":
     {
     "town_id": "1",
     "town_name": "Galway city center"
     },
     "city":
     {
     "city_id": "10",
     "city_name": "Galway"
     },
     "address_id":"200",
     "full_address":"100, B, Galway city center,Galway"
   },
   "delivery_instruction": "no call",
   "delivery_method": "1"
  }

Here all struct :

struct Contact  {
    let user : User
    let address : Address
    let deliveryInstruction : String
    let deliveryMethod : String
    init(dictionary: [String: Any]) {
        self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? ""
        self.deliveryMethod = dictionary["delivery_method"] as? String ?? ""
        self.address = Address(dictionary: dictionary["address"] as? [String:Any] ?? [:])
        self.user =  User(dictionary: dictionary["address"] as? [String:Any] ?? [:])
    }
  }

struct User {
    let name : String
    let email : String
    let phoneNo : String
    init(dictionary : [String:Any] ) {
        self.name = dictionary["name"] as? String ?? ""
        self.email = dictionary["email"] as? String ?? ""
        self.phoneNo = dictionary["phoneNo"] as? String ?? ""
    }
}

struct Address  {
    let city : City
    let town : Town
    let addressId : String
    let fullAddress : String
    let house : String
    let street: String
    init(dictionary : [String:Any] ) {
        self.addressId = dictionary["address_id"] as? String ?? ""
        self.fullAddress = dictionary["full_address"] as? String ?? ""
        self.house = dictionary["house"] as? String ?? ""
        self.street = dictionary["street"] as? String ?? ""
        self.city = City(dictionary: dictionary["address"] as? [String:Any] ?? [:])
        self.town = Town(dictionary: dictionary["address"] as? [String:Any] ?? [:])
    }
}

struct City {
    let cityId : String
    let cityName : String
    init(dictionary : [String:Any] ) {
        self.cityId = dictionary["city_id"] as? String ?? ""
        self.cityName = dictionary["city_name"] as? String ?? ""
    }
}

struct Town {
    let townId : String
    let townName : String
    init(dictionary : [String:Any]) {
        self.townId = dictionary["town_id"] as? String ?? ""
        self.townName = dictionary["town_name"] as? String ?? ""
    }
}

Body:
edit/update: Swift 4 or later you can use Codable Protocol:

struct Root: Codable {
    let user: User
    let address: Address
    let deliveryInstruction, deliveryMethod: String
}

struct Address: Codable {
    let house, street, addressId, fullAddress: String
    let town: Town
    let city: City
}

struct City: Codable {
    let cityId, cityName: String
}

struct Town: Codable {
    let townId, townName: String
}

struct User: Codable {
    let name, email, phoneNo: String
}

extension Decodable {
    init(data: Data, using decoder: JSONDecoder = .init()) throws {
        self = try decoder.decode(Self.self, from: data)
    }
    init(json: String, using decoder: JSONDecoder = .init()) throws {
        try self.init(data: Data(json.utf8), using: decoder)
    }
}

Just don't forget to set the JSONDecoder property keyDecodingStrategy to .convertFromSnakeCase:

let json = """
{"user": {"name": "crst","email": "crat@gmail.com","phoneNo":"018833455"},"address": {"house": "100","street": "B","town":{"town_id": "1","town_name": "Galway city center"},"city":{"city_id": "10","city_name": "Galway"},"address_id":"200", "full_address":"100, B, Galway city center,Galway" },"delivery_instruction": "no call","delivery_method": "1" }
"""

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let root = try decoder.decode(Root.self, from: Data(json.utf8))
    print(root)
} catch {
    print(error)
}

or simply:

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let root = try Root(json: json, using: decoder)  // or  Root(data: data, using: decoder)
    print(root)
} catch {
    print(error)
}

This will print

Root(user: __lldb_expr_112.User(name: "cruskuaka", email:
"cristlika@gmail.com", phoneNo: "018833455"), address:
__lldb_expr_112.Address(house: "100", street: "B", addressId: "200", fullAddress: "100, B, Galway city center,Galway", town:
__lldb_expr_112.Town(townId: "1", townName: "Galway city center"), city: __lldb_expr_112.City(cityId: "10", cityName: "Galway")),
deliveryInstruction: "no call", deliveryMethod: "1")

Original Answer (before Codable protocol)

Swift 3

You have more than one error in your code, but you are in the right path. You are using the wrong key when initializing your user, city and town structs. I have also created two more initializers so you can initialize your struct with a dictionary, the json string or just its data:

struct Contact: CustomStringConvertible  {
    let user: User
    let address: Address
    let deliveryInstruction: String
    let deliveryMethod: String
    // customize the description to your needs
    var description: String { return "\(user.name) \(deliveryInstruction) \(deliveryMethod)" }
    init(dictionary: [String: Any]) {
        self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? ""
        self.deliveryMethod = dictionary["delivery_method"] as? String ?? ""
        self.address = Address(dictionary: dictionary["address"] as? [String: Any] ?? [:])
        self.user =  User(dictionary: dictionary["user"] as? [String: Any] ?? [:])
    }
    init?(data: Data) {
        guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }
        self.init(dictionary: json)
    }
    init?(json: String) {
        self.init(data: Data(json.utf8))
    }

}

struct User: CustomStringConvertible {
    let name: String
    let email: String
    let phone: String
    let description: String
    init(dictionary: [String: Any]) {
        self.name = dictionary["name"] as? String ?? ""
        self.email = dictionary["email"] as? String ?? ""
        self.phone = dictionary["phoneNo"] as? String ?? ""
        self.description = "name: \(name) - email: \(email) - phone: \(phone)"
    }
}

struct Address: CustomStringConvertible  {
    let id: String
    let street: String
    let house: String
    let city: City
    let town: Town
    let description: String
    init(dictionary: [String: Any] ) {
        self.id = dictionary["address_id"] as? String ?? ""
        self.description = dictionary["full_address"] as? String ?? ""
        self.house = dictionary["house"] as? String ?? ""
        self.street = dictionary["street"] as? String ?? ""
        self.city = City(dictionary: dictionary["city"] as? [String: Any] ?? [:])
        self.town = Town(dictionary: dictionary["town"] as? [String: Any] ?? [:])
    }
}

struct City: CustomStringConvertible {
    let id: String
    let name: String
    // customize the description to your needs
    var description: String { return name }
    init(dictionary: [String: Any] ) {
        self.id = dictionary["city_id"] as? String ?? ""
        self.name = dictionary["city_name"] as? String ?? ""
    }

}

struct Town: CustomStringConvertible {
    let id: String
    let name: String
    // customize the description to your needs
    var description: String { return name }
    init(dictionary: [String: Any]) {
        self.id = dictionary["town_id"] as? String ?? ""
        self.name = dictionary["town_name"] as? String ?? ""
    }
}

Testing the initialization from JSON:

let contact = Contact(json: json)   // crst no call 1

contact               // crst no call 1
contact?.user         // name: crst - email: crat@gmail.com - phone: 018833455
contact?.user.name    //  "crst"
contact?.user.email   //  "crat@gmail.com"
contact?.user.phone   //  "018833455"
contact?.address      //  100, B, Galway city center,Galway
contact?.address.id           //  200
contact?.address.street       //  B
contact?.address.town         // Galway city center
contact?.address.city         //  Galway
contact?.deliveryInstruction  // "no call"
contact?.deliveryMethod       //    1

ContentLicense: CC BY-SA 4.0


问:
Suppress scientific notation in Haxe across targets
Is there a way to suppress scientific notation in Haxe?

For example, if I have:

```<code>var f:Float = 0.00007075;
var s:String = Std.string(f);
</code>```

In targets such as html5, this outputs: 0.00007075

However, c++ targets output: 7.075e-05

Is there a way to control whether scientific notation is used for string format?

答: Perhaps you can switch to a different library to convert floats to strings which specifies the format. E.g., https://github.com/polygonal/printf/blob/master/src/de/polygonal/Printf.hx#L119</p>

Body:
Is there a way to suppress scientific notation in Haxe?

For example, if I have:

var f:Float = 0.00007075;
var s:String = Std.string(f);

In targets such as html5, this outputs: 0.00007075

However, c++ targets output: 7.075e-05

Is there a way to control whether scientific notation is used for string format?


问:
How do i record the occurances of 'Y' in a txt file in Python 3.2
I'm trying to record how many times the letter Y appears in the 6th column of a .txt file and assign that to a variable. How would I go about doing that? Thx in advance!

.txt file:

```<code>119,29/12/15,18:00,Ripley,Magnitude,Y,Magnitude
120,30/12/15,18:00,Jenkins,Kes,Y,Kes
121,31/12/15,18:00,Big Boss,Ingsoc,Y,Ingsoc
122,01/01/16,18:00,Einstein100,RNGesus,,
123,02/01/16,18:00,Macho Man,Napoleon Wilson,,
124,03/01/16,18:00,Dennis,Billy Casper,,
</code>```

I've set the whole file to a variable and have created variables for each column in the file.

```<code>    NextRecord = data[x]
    Number = NextRecord[0]
    Date = NextRecord[1]
    Time = NextRecord[2]
    P1Nickname = NextRecord[3]
    P2Nickname = NextRecord[4]
    Status = NextRecord[5]
</code>```

答:
Use csv and sum:

```<code>import csv

with open(filename) as records:
    reader = csv.reader(records)
    print(sum(row[5] == 'Y' for row in reader))
</code>```

Your data is comma separated, and Python has the csv module for working with delimited values (could be semicolon separated, etc, as well).

The reader is iterable and yields a row at a time.

I've used the sum function which takes an iterable but I've used a generator expression to yield True or False for each row in the file.

The expression row[5] == 'Y' evaluates either True or False. When you give a boolean value to sum it converts to an integer and True becomes 1, False becomes 0. We could have written it as:

```<code>sum(1 for row in reader
    if row[5] == 'Y')
</code>```

This however is slightly different. It filters out only the rows which have Y in the 6th column and yields the value 1 for each of those rows. It's subtly different.

Body:
I'm trying to record how many times the letter Y appears in the 6th column of a .txt file and assign that to a variable. How would I go about doing that? Thx in advance!

.txt file:

119,29/12/15,18:00,Ripley,Magnitude,Y,Magnitude
120,30/12/15,18:00,Jenkins,Kes,Y,Kes
121,31/12/15,18:00,Big Boss,Ingsoc,Y,Ingsoc
122,01/01/16,18:00,Einstein100,RNGesus,,
123,02/01/16,18:00,Macho Man,Napoleon Wilson,,
124,03/01/16,18:00,Dennis,Billy Casper,,

I've set the whole file to a variable and have created variables for each column in the file.

    NextRecord = data[x]
    Number = NextRecord[0]
    Date = NextRecord[1]
    Time = NextRecord[2]
    P1Nickname = NextRecord[3]
    P2Nickname = NextRecord[4]
    Status = NextRecord[5]

Body:
Use csv and sum:

import csv

with open(filename) as records:
    reader = csv.reader(records)
    print(sum(row[5] == 'Y' for row in reader))

Your data is comma separated, and Python has the csv module for working with delimited values (could be semicolon separated, etc, as well).

The reader is iterable and yields a row at a time.

I've used the sum function which takes an iterable but I've used a generator expression to yield True or False for each row in the file.

The expression row[5] == 'Y' evaluates either True or False. When you give a boolean value to sum it converts to an integer and True becomes 1, False becomes 0. We could have written it as:

sum(1 for row in reader
    if row[5] == 'Y')

This however is slightly different. It filters out only the rows which have Y in the 6th column and yields the value 1 for each of those rows. It's subtly different.


问:
Error ng new projectName
I have updated me angular version to 4, but since i have a probelm to create new project with angular/cli, i know that the problem is a bout a packag.json file in my home directory how must be deleted but i cannot know how to find it.

```<code>@angular/cli: 1.0.0
node: 7.6.0
os: linux x64
@angular/animations: 4.0.1
@angular/common: 4.0.1
@angular/compiler: 4.0.1
@angular/compiler-cli: 4.0.1
@angular/core: 4.0.1
@angular/forms: 4.0.1
@angular/http: 4.0.1
@angular/platform-browser: 4.0.1
@angular/platform-browser-dynamic: 4.0.1
@angular/platform-server: 4.0.1
@angular/router: 4.0.1
@angular/cli: 1.0.0
</code>```

in the terminal:

```<code> ng new test4
 You cannot use the new command inside an Angular CLI project.
</code>```

Thanks for your help

答:
As the error says, you should run "ng new" in a parent directory, neither in a directory where you want the new project to be nor in a directory where there is already some project.

For example if you want to create a new project in /home/user/projects/hello, then you should go to /home/user/projects and run "ng new hello".

If you already had a working project, just upgraded the Angular to 4.0.1 and CLI to 1.0.0, then you need to follow the upgrade instructions https://github.com/angular/angular-cli#updating-angular-cli - removing node_modules and running "npm install" which will fetch new packages. No need to run "ng new" again.

Title: Error ng new projectName

Body:
I have updated me angular version to 4, but since i have a probelm to create new project with angular/cli, i know that the problem is a bout a packag.json file in my home directory how must be deleted but i cannot know how to find it.

@angular/cli: 1.0.0
node: 7.6.0
os: linux x64
@angular/animations: 4.0.1
@angular/common: 4.0.1
@angular/compiler: 4.0.1
@angular/compiler-cli: 4.0.1
@angular/core: 4.0.1
@angular/forms: 4.0.1
@angular/http: 4.0.1
@angular/platform-browser: 4.0.1
@angular/platform-browser-dynamic: 4.0.1
@angular/platform-server: 4.0.1
@angular/router: 4.0.1
@angular/cli: 1.0.0

in the terminal:

 ng new test4
 You cannot use the new command inside an Angular CLI project.

Thanks for your help


问:
angular/material md-slide-toggle cannot be re instantiated?
I have a simple model-driven Angular 2 form with two components:

An Angular Material slide-toggle.

A single button, which when clicked calls onReset(form: FormGroup) on my Component.

See this Plunkr. Code below:

select-overview-example.html

```<code><form novalidate [formGroup]="form">
<md-slide-toggle formControlName="example">Example</md-slide-toggle>
<button md-raised-button (click)="onReset(form)">Reset</button>
</form>
</code>```

select-overview-example.ts

```<code>@Component({
  selector: 'select-overview-example',
  templateUrl: './select-overview-example.html',
})
export class SelectOverviewExample implements OnInit {
  private form: FormGroup;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.createForm();
  }

  onReset(form: FormGroup) {
    this.createForm();
    return false;
  }

  private createForm() {
    let form = this.fb.group({
      example: true
    });

    this.form = form;
  }
}
</code>```

The page loads fine (i.e. constructor -> ngOnInit -> createForm) and the <md-slide-toggle> is rendered.

Clicking the reset button uses the FormBuilder to (re)construct the form. I do this because I want specific values reset (rather than just clearing the entire form).

```<code>onReset(form: FormGroup) {
    this.createForm();
    return false;
  }
</code>```

This works, but only when the slide-toggle is on. If toggled off, clicking the reset <button>, calling onReset and subsequently createForm, throws an exception (you'll have to look in your browser's developer console when using the example Plunkr). Exception repeated below:

```<code>ERROR Error: There is no FormControl instance attached to form control element with name: 'example'
</code>```

I added some debug logging to see what state the form's in, and the slide-toggle is instantiated:

```<code>private createForm() {
    if (this.form) {
        console.log(this.form.value.example);
    }
    let form = this.fb.group({
        example: true
    });
    this.form = form;
}
</code>```

Prints true when the page loads, and false when clicking reset.

答:
I have update createForm function and its working fine.

```<code>private createForm() {
if (this.form) {
  console.log(this.form.value);
}
if(!this.form){
  this.form = this.fb.group({
    example: true
  });
}
this.form.controls['example'].setValue(true);
}
</code>```

Body:
I have a simple model-driven Angular 2 form with two components:

An Angular Material slide-toggle.

A single button, which when clicked calls onReset(form: FormGroup) on my Component.

See this Plunkr. Code below:

select-overview-example.html

<form novalidate [formGroup]="form">
<md-slide-toggle formControlName="example">Example</md-slide-toggle>
<button md-raised-button (click)="onReset(form)">Reset</button>
</form>

select-overview-example.ts

@Component({
  selector: 'select-overview-example',
  templateUrl: './select-overview-example.html',
})
export class SelectOverviewExample implements OnInit {
  private form: FormGroup;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.createForm();
  }

  onReset(form: FormGroup) {
    this.createForm();
    return false;
  }

  private createForm() {
    let form = this.fb.group({
      example: true
    });

    this.form = form;
  }
}

The page loads fine (i.e. constructor -> ngOnInit -> createForm) and the <md-slide-toggle> is rendered.

Clicking the reset button uses the FormBuilder to (re)construct the form. I do this because I want specific values reset (rather than just clearing the entire form).

onReset(form: FormGroup) {
    this.createForm();
    return false;
  }

This works, but only when the slide-toggle is on. If toggled off, clicking the reset <button>, calling onReset and subsequently createForm, throws an exception (you'll have to look in your browser's developer console when using the example Plunkr). Exception repeated below:

ERROR Error: There is no FormControl instance attached to form control element with name: 'example'

I added some debug logging to see what state the form's in, and the slide-toggle is instantiated:

private createForm() {
    if (this.form) {
        console.log(this.form.value.example);
    }
    let form = this.fb.group({
        example: true
    });
    this.form = form;
}

Prints true when the page loads, and false when clicking reset.

Body:
I have update createForm function and its working fine.

private createForm() {
if (this.form) {
  console.log(this.form.value);
}
if(!this.form){
  this.form = this.fb.group({
    example: true
  });
}
this.form.controls['example'].setValue(true);
}


问:
Varnish / Nginx: initial connection after idle for ~5 seconds
I've set up a test server on: http://95.85.19.39/ With varnish 4.1.5 (port 80) and nginx 1.4.6 (port 8080) running on Ubuntu 14.04. I'm using Chrome 57.0.2987.110 (64-bit).

Varnish is caching the page, but when you wait 5+ seconds and hit refresh, you'll see an initial connection, why is this? When you hit refresh within 5 seconds, there won't be an initial connection.

If I remove varnish and run the server just on Nginx then I won't get the initial connection anymore, so I assume there's something wrong with my Varnish.

Does anyone know why this is happening and how would I go about fixing this issue?

Without initial connection

With initial connection

nginx.conf

```<code>user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;
    gzip_disable "msie6";

    include /etc/nginx/sites-enabled/default.conf;
}
</code>```

default.conf

```<code>server {
    listen 8080;

    root /var/www/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.(htaccess|htpasswd|ini|phps|fla|log|sh)$ {
        deny all;
    }
}
</code>```

default.vcl

```<code>vcl 4.0;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_recv {
}

sub vcl_backend_response {
}

sub vcl_deliver {
     if (obj.hits > 0) {
         set resp.http.X-Cache = "HIT";
     } else {
         set resp.http.X-Cache = "MISS";
     }
}
</code>```

/etc/default/varnish

```<code>START=yes
NFILES=131072
MEMLOCK=82000

DAEMON_OPTS="-a :80 \
            -T localhost:6082 \
            -f /etc/varnish/default.vcl \
            -S /etc/varnish/secret \
            -s malloc,256m"
</code>```

答:
What you observe is normal. The default keepalive value in Varnish 4 is 5 seconds.

First request involves additional TCP overhead. If second request takes place within 5 seconds, it is performed over existing TCP connection and no "initial connection" will be made, saving some time.

You can increase Varnish client timeout if you want keepalive timeout to be more than 5 seconds.

```<code>DAEMON_OPTS="-a :80 \
        -T localhost:6082 \
        -f /etc/varnish/default.vcl \
        -S /etc/varnish/secret \
        -s malloc,256m" \
        -p timeout_idle=75
</code>```

More on Keep-Alive in web servers (Varnish, Nginx, Apache).

Body:
I've set up a test server on: http://95.85.19.39/ With varnish 4.1.5 (port 80) and nginx 1.4.6 (port 8080) running on Ubuntu 14.04. I'm using Chrome 57.0.2987.110 (64-bit).

Varnish is caching the page, but when you wait 5+ seconds and hit refresh, you'll see an initial connection, why is this? When you hit refresh within 5 seconds, there won't be an initial connection.

If I remove varnish and run the server just on Nginx then I won't get the initial connection anymore, so I assume there's something wrong with my Varnish.

Does anyone know why this is happening and how would I go about fixing this issue?

Without initial connection

With initial connection

nginx.conf

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;
    gzip_disable "msie6";

    include /etc/nginx/sites-enabled/default.conf;
}

default.conf

server {
    listen 8080;

    root /var/www/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.(htaccess|htpasswd|ini|phps|fla|log|sh)$ {
        deny all;
    }
}

default.vcl

vcl 4.0;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_recv {
}

sub vcl_backend_response {
}

sub vcl_deliver {
     if (obj.hits > 0) {
         set resp.http.X-Cache = "HIT";
     } else {
         set resp.http.X-Cache = "MISS";
     }
}

/etc/default/varnish

START=yes
NFILES=131072
MEMLOCK=82000

DAEMON_OPTS="-a :80 \
            -T localhost:6082 \
            -f /etc/varnish/default.vcl \
            -S /etc/varnish/secret \
            -s malloc,256m"

Body:
What you observe is normal. The default keepalive value in Varnish 4 is 5 seconds.

First request involves additional TCP overhead. If second request takes place within 5 seconds, it is performed over existing TCP connection and no "initial connection" will be made, saving some time.

You can increase Varnish client timeout if you want keepalive timeout to be more than 5 seconds.

DAEMON_OPTS="-a :80 \
        -T localhost:6082 \
        -f /etc/varnish/default.vcl \
        -S /etc/varnish/secret \
        -s malloc,256m" \
        -p timeout_idle=75

More on Keep-Alive in web servers (Varnish, Nginx, Apache).


问:
WPF Generate Xaml template
How do i get the default xaml template for a control?
In expression blend you can right click a control and press style then i generates the current template as xaml.. how do i do this if i don't have expression blend?</p>

答:
.

For WPF,

Control Styles and Templates

For Silverlight,

Control Styles and Templates

.

Title: WPF Generate Xaml template


问:
Body of calendar entries converted from plain text to HTML using Outlook REST API
We are using the Microsoft Outlook REST API to synchronize the calendars of users  of our ERP system with Exchange online.

Entries from our ERP system are in plain text and are provided as such to the API.

Unfortunately, since around March 14, we noticed that, when reading back those entries, the body part of some of them was converted automatically to HTML like below

```<code><html><head><meta name="Generator" content="Microsoft Exchange Server">
<!-- converted from text -->
<style><!-- .EmailQuote { margin-left: 1pt; padding-left: 4pt; border-left: #800000 2px solid; } --></style></head>
<body>
<font size="2"><span style="font-size:10pt;"><div class="PlainText"> </div></span></font>
</body>
</html>
</code>```

The conversion seems to be done randomly as not all entries created for a user are converted, and the problem does not happen to all our users.

What can we do to prevent this and get back the original entries as plain text?

答:
When you are sending your email, are you specifying that your ContentType is Text? Your message should look something like this:</p>

```<code>                var messageFinal = {
                    "Message": {
                        "ToRecipients": $scope.message.toRecipients,
                        "CcRecipients": $scope.message.ccRecipients,
                        "BccRecipients": $scope.message.bccRecipients,
                        "Attachments": attachmentsFinal,
                        "Subject": $scope.message.subject,
                        "Body": {
                            "ContentType": "TEXT",
                            "Content": $scope.message.content
                        },
                        "Importance" : $scope.message.Importance
                    }
                };
</code>```

Body:
We are using the Microsoft Outlook REST API to synchronize the calendars of users  of our ERP system with Exchange online.

Entries from our ERP system are in plain text and are provided as such to the API.

Unfortunately, since around March 14, we noticed that, when reading back those entries, the body part of some of them was converted automatically to HTML like below

<meta name="Generator" content="Microsoft Exchange Server">

The conversion seems to be done randomly as not all entries created for a user are converted, and the problem does not happen to all our users.

What can we do to prevent this and get back the original entries as plain text?

Body:
When you are sending your email, are you specifying that your ContentType is Text? Your message should look something like this:

                var messageFinal = {
                    "Message": {
                        "ToRecipients": $scope.message.toRecipients,
                        "CcRecipients": $scope.message.ccRecipients,
                        "BccRecipients": $scope.message.bccRecipients,
                        "Attachments": attachmentsFinal,
                        "Subject": $scope.message.subject,
                        "Body": {
                            "ContentType": "TEXT",
                            "Content": $scope.message.content
                        },
                        "Importance" : $scope.message.Importance
                    }
                };


问:
Ruby on Rails - Refresh data when button pressed
I have a website which contains photos and videos and 3 buttons. One show only photos, one only videos and the last one show photos & videos. I have two different tables in the database (photos, videos) which contains only the name of the file. Their is no relationship between them.

Here is a example of my AJAX used to only show videos :

```<code>jQuery(document).ready(function() {
    $('#btn-videos').on('click', function(e){
    e.preventDefault();
    $.ajax({
    type:'GET',
    url:'/galerie',
    dataType: 'json',
    data: { 'type' : "videos", }
    });
    });
});
</code>```

Here is my galerie controller :

```<code>  def index
     case params[:type]
     when "videos"
        @medias = Video.order('created_at DESC')
     when "images"
        @medias = Picture.order('created_at DESC')
     else
        @medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)
     end
  end
</code>```

My AJAX is calling the controller but it doesn't update the view.

Is their a (better) way to do this ?
 I'm also wondering if its possible to do this line using only sql :

```<code>@medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)
</code>```

答:
You can do this in two ways:

send a remote request through your button and handle data update on index.js.erb file (in views folder). You can refer to this link.

Use ajax in js file in your asset. Once the ajax request is successful you need to replace your old data with your requested new data.

```<code>$('#btn-videos').on 'click', ->
   e.preventDefault();
   $.ajax
     type:'GET',
     url:'/galerie',
     dataType: 'json',
     data: { 'type' : "videos", }
     success: (data) ->
       console.log(data)
</code>```

Body:
I have a website which contains photos and videos and 3 buttons. One show only photos, one only videos and the last one show photos & videos. I have two different tables in the database (photos, videos) which contains only the name of the file. Their is no relationship between them.

Here is a example of my AJAX used to only show videos :

jQuery(document).ready(function() {
    $('#btn-videos').on('click', function(e){
    e.preventDefault();
    $.ajax({
    type:'GET',
    url:'/galerie',
    dataType: 'json',
    data: { 'type' : "videos", }
    });
    });
});

Here is my galerie controller :

  def index
     case params[:type]
     when "videos"
        @medias = Video.order('created_at DESC')
     when "images"
        @medias = Picture.order('created_at DESC')
     else
        @medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)
     end
  end

My AJAX is calling the controller but it doesn't update the view.

Is their a (better) way to do this ?
 I'm also wondering if its possible to do this line using only sql :

@medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)

Body:
You can do this in two ways:

send a remote request through your button and handle data update on index.js.erb file (in views folder). You can refer to this link.

Use ajax in js file in your asset. Once the ajax request is successful you need to replace your old data with your requested new data.

$('#btn-videos').on 'click', ->
   e.preventDefault();
   $.ajax
     type:'GET',
     url:'/galerie',
     dataType: 'json',
     data: { 'type' : "videos", }
     success: (data) ->
       console.log(data)


问:
swift UIImage blue square
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

```<code>sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)
</code>```

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction

答:
Try this code it will work </p>

```<code>let image = UIImage(named:"o")?.withRenderingMode(.alwaysOriginal)
sender.setImage(UIImage(named: image), for: .normal)
</code>```

Title: swift UIImage blue square

Body:
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction

Body:
Try this code it will work

let image = UIImage(named:"o")?.withRenderingMode(.alwaysOriginal)
sender.setImage(UIImage(named: image), for: .normal)


问:
Is using React with JSX in web apps simmilar to using Java with XML in Android
I've recently become a front-end developer and with the release of Angular2 i've decided to find a new framework and have decided to try my hands at Reactjs and
JSX. With my experience as a mobile developer i want to know if JSX works with Reactjs the way XML and Java work in android</p>

答:
Yes, react-native JSX's is used to define layouts and content presentation similar to XML in Android's development but it is more of an extension to ECMAScript than a separate markup language. From the spec:

JSX is a XML-like syntax extension to ECMAScript without any defined
  semantics. It's NOT intended to be implemented by engines or browsers.
  It's NOT a proposal to incorporate JSX into the ECMAScript spec
  itself. It's intended to be used by various preprocessors
  (transpilers) to transform these tokens into standard ECMAScript.


问:
C++ static prototype declaration in header file
Here's my code:

```<code>void got_Packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
//in home.h

void got_Packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet){

}
//in home.cpp

pcap_loop(handle, -1, got_Packet, NULL);
//in home.cpp
</code>```

This is the error I got.

```<code>error: invalid use of non-static member function
pcap_loop(handle, -1, got_Packet, NULL);
                                      ^"
</code>```

I added syntax static

on all three of them, error still occurred

on only the prototype and the declaration, error still occurred

on only the prototype, error is gone, MAGICALLY

Could anyone kindly enlighten me on this issue? Why must I only add the syntax static in the home.h  function prototype, but not in the home.cpp function declaration and calling?

答:
Inside a class definition, the keyword static declares members that are not bound to class instances.
  Outside a class definition, it has a different meaning: see storage duration.

source

If your intention is to make that method static, then the correct way to do that is to declare it that way within the class definition. Static methods cannot access data specific to an instance of the class.

Body:
Here's my code:

void got_Packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
//in home.h

void got_Packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet){

}
//in home.cpp

pcap_loop(handle, -1, got_Packet, NULL);
//in home.cpp

This is the error I got.

error: invalid use of non-static member function
pcap_loop(handle, -1, got_Packet, NULL);
                                      ^"

I added syntax static

on all three of them, error still occurred

on only the prototype and the declaration, error still occurred

on only the prototype, error is gone, MAGICALLY

Could anyone kindly enlighten me on this issue? Why must I only add the syntax static in the home.h  function prototype, but not in the home.cpp function declaration and calling?


问:
J2OBJC_HOME not correctly defined in Settings.xcconfig
I must to include *.jar files in my Xcode project so I decided to use j2objc to translate them into Objective C. I tried to configure my project with no success so I just downloaded a sample project from here and here. All of them cannot compile becouse of the same error

J2OBJC_HOME not correctly defined in Settings.xcconfig, currently set to '../j2objc-dist'
Command /bin/sh failed with exit code 1

looks like I am using the wrong path, this is my Settings.xcconfig

J2OBJC_HOME = ${HOME}/j2objc;

HEADER_SEARCH_PATHS = "${J2OBJC_HOME}/frameworks/JRE.framework/Headers";
FRAMEWORK_SEARCH_PATHS = "${J2OBJC_HOME}/frameworks";

I tried many different paths but no success
My j2objc folder path at this point is :/Users/username/j2objc

Thanks for any advice

答:
J2ObjC is distributed as a zip file, which you download and unzip into a local directory of your choosing. That local directory plus the release name ("j2objc-" + version) is the J2OBJC_HOME. For example, on my system I have a "/usr/local/tools" directory where I unzipped j2objc-1.3.zip, so my current J2OBJC_HOME is "/usr/local/tools/j2objc-1.3".

In each of the sample projects, J2OBJC_HOME is defined in an xcconfig file. To update the project to work on your system, edit that file and change the J2OBJC_HOME environment variable to wherever it is for your system.

There's nothing special about "J2OBJC_HOME", it's just an environment variable name both sample projects use.


问:
Microsoft debug symbol don't work
I try to analyze some memory dump. But I stack on debug symbols of some Microsoft dll (sechost.dll).
What I do:

1) !sym noisy

2) .symfix

3) .sympath

My .sympath is:

```<code>Symbol search path is: srv*
Expanded Symbol search path is: cache*;SRV*http://msdl.microsoft.com/download/symbols
</code>```

4) analyze -v
After it I saw symbols loading.
But for some symbols I have

```<code>......
SYMSRV:  The operation timed out
SYMSRV:  http://msdl.microsoft.com/download/symbols/sechost.pdb/C4FD72A96E384F62A5F796624D37EAB42/sechost.pdb not found
SYMSRV:  C:\ProgramData\dbg\sym\sechost.pdb\C4FD72A96E384F62A5F796624D37EAB42\sechost.pdb not found
DBGHELP: sechost.pdb - file not found
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for sechost.dll -
DBGHELP: sechost - export symbols
......
</code>```

When actual analyze start I saw:

```<code>.....
IMAGE_NAME:  sechost.dll
BUCKET_ID:  WRONG_SYMBOLS
FAILURE_BUCKET_ID:  WRONG_SYMBOLS_80000003_sechost.dll!SubscribeServiceChangeNotifications
.....
</code>```

I understand that I don't have PDB for this DLL. I try load it with .reload /f sechost.dll. But analyze got stuck on same place.
How to deal with this?
Maybe there is possibility to increase connection timeout or other way to get what I need?

答:
I asked this Microsoft and Andy Luhrs replied me that Microsoft needs 3 days to publish the symbols for new builds/ Windows 10 updates.

So if you analyze dumps after updates have been published, try to load symbols 3 days after the update was published.

Title: Microsoft debug symbol don't work

Body:
I try to analyze some memory dump. But I stack on debug symbols of some Microsoft dll (sechost.dll).
What I do:

1) !sym noisy

2) .symfix

3) .sympath

My .sympath is:

Symbol search path is: srv*
Expanded Symbol search path is: cache*;SRV*http://msdl.microsoft.com/download/symbols

4) analyze -v
After it I saw symbols loading.
But for some symbols I have

......
SYMSRV:  The operation timed out
SYMSRV:  http://msdl.microsoft.com/download/symbols/sechost.pdb/C4FD72A96E384F62A5F796624D37EAB42/sechost.pdb not found
SYMSRV:  C:\ProgramData\dbg\sym\sechost.pdb\C4FD72A96E384F62A5F796624D37EAB42\sechost.pdb not found
DBGHELP: sechost.pdb - file not found
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for sechost.dll -
DBGHELP: sechost - export symbols
......

When actual analyze start I saw:

.....
IMAGE_NAME:  sechost.dll
BUCKET_ID:  WRONG_SYMBOLS
FAILURE_BUCKET_ID:  WRONG_SYMBOLS_80000003_sechost.dll!SubscribeServiceChangeNotifications
.....

I understand that I don't have PDB for this DLL. I try load it with .reload /f sechost.dll. But analyze got stuck on same place.
How to deal with this?
Maybe there is possibility to increase connection timeout or other way to get what I need?


问:
WCF initializing code
I have created a WCF service which reads from a database and sends back results. For performance reasons I'd like to cache the tables on service startup (which happens in a windows service OnStart). But there's no such thing as constructors in WCF (right?) so best thing I came up with is create an Init() function and call that like the following:

```<code>protected override void OnStart(string[] args)
{
    mServiceHost = new ServiceHost(typeof(DLSService.DLSService), new Uri("http://localhost:8000/DLS"));
    mServiceHost.AddServiceEndpoint(typeof(DLSService.IDLSService), new BasicHttpBinding(), "ServicesHost");
    ((DLSService.DLSService)mServiceHost.SingletonInstance).Init();
    mServiceHost.Open();
}
</code>```

But using SingletonInstance and casting to the correct type does not seem all that elegeant to me.
Are there more elegant ways to achieve constructor like functionality in WCF?

答:
With framework 4.5 you can use a configuration's function in your service implementation code:

http://msdn.microsoft.com/en-us/library/hh205277(v=vs.110).aspx.

Title: WCF initializing code

Body:
I have created a WCF service which reads from a database and sends back results. For performance reasons I'd like to cache the tables on service startup (which happens in a windows service OnStart). But there's no such thing as constructors in WCF (right?) so best thing I came up with is create an Init() function and call that like the following:

protected override void OnStart(string[] args)
{
    mServiceHost = new ServiceHost(typeof(DLSService.DLSService), new Uri("http://localhost:8000/DLS"));
    mServiceHost.AddServiceEndpoint(typeof(DLSService.IDLSService), new BasicHttpBinding(), "ServicesHost");
    ((DLSService.DLSService)mServiceHost.SingletonInstance).Init();
    mServiceHost.Open();
}

But using SingletonInstance and casting to the correct type does not seem all that elegeant to me.
Are there more elegant ways to achieve constructor like functionality in WCF?


问:
How to pickle a scapy packet?
I need to pickle a scapy packet. Most of the time this works, but sometimes the pickler complains about a function object. As a rule of thumb: ARP packets pickle fine. Some UDP packets are problematic.

答:
My solution (as inspired by the scapy mailing list) is as follows:

```<code>class PicklablePacket:
    """A container for scapy packets that can be pickled (in contrast
    to scapy packets themselves)."""
    def __init__(self, pkt):
        self.contents = bytes(pkt)
        self.time = pkt.time

    def __call__(self):
        """Get the original scapy packet."""
        pkt = scapy.Ether(self.contents)
        pkt.time = self.time
        return pkt
</code>```

Anywhere I wish to pass a scapy Packet through a Queue I simply wrap it in a PicklablePacket and __call__ it afterwards. I am not aware of data that is not retained this way. However this approach only works with Ethernet packets. (All packets sniffed on a regular NIC (not WLAN) are Ethernet.) It could probably be extended to work for other types, too.

Title: How to pickle a scapy packet?

Body:
My solution (as inspired by the scapy mailing list) is as follows:

class PicklablePacket:
    """A container for scapy packets that can be pickled (in contrast
    to scapy packets themselves)."""
    def __init__(self, pkt):
        self.contents = bytes(pkt)
        self.time = pkt.time

    def __call__(self):
        """Get the original scapy packet."""
        pkt = scapy.Ether(self.contents)
        pkt.time = self.time
        return pkt

Anywhere I wish to pass a scapy Packet through a Queue I simply wrap it in a PicklablePacket and __call__ it afterwards. I am not aware of data that is not retained this way. However this approach only works with Ethernet packets. (All packets sniffed on a regular NIC (not WLAN) are Ethernet.) It could probably be extended to work for other types, too.


问:
How to convert numbers represented as characters for short into numeric in Python
I have a column in my data frame which has values like '3.456B' which actually stands for 3.456 Billion (and similar notation for Million). How to convert this string form to correct numeric representation?

This shows the data frame:

```<code>import pandas as pd
data_csv = pd.read_csv('https://biz.yahoo.com/p/csv/422conameu.csv')
data_csv
</code>```

This is a sample value:

```<code>data_csv['Market Cap'][0]
type(data_csv['Market Cap'][0])
</code>```

I tried this:

```<code>data_csv.loc[data_csv['Market Cap'].str.contains('B'), 'Market Cap'] = data_csv['Market Cap'].str.replace('B', '').astype(float).fillna(0.0)
data_csv
</code>```

But unfortunately there are also values with 'M' at the end which denotes Millions. It returns error as follows:

```<code>ValueError: invalid literal for float(): 6.46M
</code>```

How can I replace both B and M with appropriate values in this column? Is there a better way to do it?

答:
First extract units as last character in strings. Then convert values without units to floats and multiply where needed:

```<code>df = pd.DataFrame({'Market Cap':['6.46M','2.25B','0.23B']})
units = df['Market Cap'].str[-1]
df['Market Cap'] = df['Market Cap'].str[:-1].astype(float)
df.loc[units=='M','Market Cap'] *= 0.001
#    Market Cap
# 0     0.00646
# 1     2.25000
# 2     0.23000
</code>```

Now everything is in billions.

Body:
I have a column in my data frame which has values like '3.456B' which actually stands for 3.456 Billion (and similar notation for Million). How to convert this string form to correct numeric representation?

This shows the data frame:

import pandas as pd
data_csv = pd.read_csv('https://biz.yahoo.com/p/csv/422conameu.csv')
data_csv

This is a sample value:

data_csv['Market Cap'][0]
type(data_csv['Market Cap'][0])

I tried this:

data_csv.loc[data_csv['Market Cap'].str.contains('B'), 'Market Cap'] = data_csv['Market Cap'].str.replace('B', '').astype(float).fillna(0.0)
data_csv

But unfortunately there are also values with 'M' at the end which denotes Millions. It returns error as follows:

ValueError: invalid literal for float(): 6.46M

How can I replace both B and M with appropriate values in this column? Is there a better way to do it?

Body:
First extract units as last character in strings. Then convert values without units to floats and multiply where needed:

df = pd.DataFrame({'Market Cap':['6.46M','2.25B','0.23B']})
units = df['Market Cap'].str[-1]
df['Market Cap'] = df['Market Cap'].str[:-1].astype(float)
df.loc[units=='M','Market Cap'] *= 0.001
#    Market Cap
# 0     0.00646
# 1     2.25000
# 2     0.23000

Now everything is in billions.