问:
Unable to pass parameter after submitting form
I recorded a 15 seconds video to show this error: https://www.youtube.com/watch?v=LYQ4pjo5rV8

I am trying to make a web application for admin to manage members.

So, admin can selected update action or delete action from dropdown list to be performed for a specific member.

onchange is set for the dropdown list.

Therefore, if admin selected a action, the form will be submitted to MemberAdmin servlet.

And then MemberAdmin will perform the update or delete function to the member.

I faced difficulties to pass a parameter to my servlet.

Even though I am using get method for the form, my servlet unable to receive any parameter.

I expecting to have url like

```<code>http://localhost:8080/Assignment/MemberAdmin?action=update~M0001
</code>```

But I am getting this url:

```<code>http://localhost:8080/Assignment/MemberAdmin?
</code>```

update - selected action

~      - act as separator

M0001  - member id

After obtaining all the members' data from the database, I print out row by row.

Is there any wrong with my form?

```<code><%@page import="java.sql.Date"%>
<%@page import="java.util.ArrayList"%>
<%@page import="domain.Member"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:useBean id="memberControl"
             class="control.MemberControl" scope="page" >
</jsp:useBean>

<html>
    <head>
        <link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

        <title>Environmental Society</title>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#myTable').DataTable();
            });
        </script>
        <script type="text/javascript">
            function actionFunc(sel) {
                if (sel.options[sel.selectedIndex].text === "Delete") {
                    if (confirm("Confirm to delete this member?")) {
                        document.getElementById("actionForm").submit();
                    }
                } else {
                    document.getElementById("actionForm").submit();
                }
            }
        </script>
    </head>

    <body id="body">
        <div id="bodyContent" style="color: black; overflow-y: scroll;">
                <%
                    ArrayList<Member> member = new ArrayList<Member>();
                    member = memberControl.getAllRecord();
                %>
                <h3 style="text-align: left">Select the member you wish to update:</h3>
                <p>
                <table class="display" cellspacing="0" width="100%" id="myTable" style="padding-top: 5px">
                    <!--column width-->
                    <thead>
                        <tr class="memberAdmin">
                            <th class="memberAdmin">No</th>
                            <th class="memberAdmin">ID</th>
                            <th class="memberAdmin">Name</th>
                            <th class="memberAdmin">Action</th>
                        </tr>
                    </thead>
                    <%
                        for (int i = 0; i < member.size(); i++) {
                            String id = member.get(i).getId();
                            String name = member.get(i).getName();
                    %>
                    <form action="../MemberAdmin" method="get" id="actionForm" name="actionForm">
                        <tr class="memberrow">
                            <td class="member"><%=i + 1%></td>
                            <td class="member"><%=id%></td>
                            <td class="member"><%=name%></td>
                            <td class="member">
                                <select name="action" id="action" onchange="actionFunc(this)">
                                    <option disabled selected value>- select action -</option>
                                    <option value="update~<%=id%>">Update</option>
                                    <option value="delete~<%=id%>">Delete</option>
                                </select>
                                <button type="submit" value="submit" name="button" hidden=""></button>
                            </td>
                        </tr>
                    </form>
                    <%}%>
                </table>
                </p>
        </div>
    </body>
</html>
</code>```

Any help is appreciated. I been solving this for many hours.

*There is no web.xml error.

答:
As per your output in video it's clearly telling null pointer exception means not getting the parameter value which you are using in further server side process.

Can you tell in server side how you are trying to get it?

It should be like request.getParameter("action"), you will get the right value. getParameter is for retrieving parameters from form data and URL query string. Make sure you are not using getAttribute which is for transfer data through the process chain during the request life cycle.

Still if you have doubt in your form than hard code value of your option and try to check it's working as expected.

Body:
I recorded a 15 seconds video to show this error: https://www.youtube.com/watch?v=LYQ4pjo5rV8

I am trying to make a web application for admin to manage members.

So, admin can selected update action or delete action from dropdown list to be performed for a specific member.

onchange is set for the dropdown list.

Therefore, if admin selected a action, the form will be submitted to MemberAdmin servlet.

And then MemberAdmin will perform the update or delete function to the member.

I faced difficulties to pass a parameter to my servlet.

Even though I am using get method for the form, my servlet unable to receive any parameter.

I expecting to have url like

http://localhost:8080/Assignment/MemberAdmin?action=update~M0001

But I am getting this url:

http://localhost:8080/Assignment/MemberAdmin?

update - selected action

~      - act as separator

M0001  - member id

After obtaining all the members' data from the database, I print out row by row.

Is there any wrong with my form?

<%@page import="java.sql.Date"%>
<%@page import="java.util.ArrayList"%>
<%@page import="domain.Member"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:useBean id="memberControl"
             class="control.MemberControl" scope="page" >
</jsp:useBean>

        <link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

        <title>Environmental Society</title>

                <%
                    ArrayList<Member> member = new ArrayList<Member>();
                    member = memberControl.getAllRecord();
                %>

Select the member you wish to update:

                            No
                            ID
                            Name
                            Action

                    <%
                        for (int i = 0; i < member.size(); i++) {
                            String id = member.get(i).getId();
                            String name = member.get(i).getName();
                    %>
                    <form action="../MemberAdmin" method="get" id="actionForm" name="actionForm">

                            <%=i + 1%>
                            <%=id%>
                            <%=name%>

                                <select name="action" id="action" onchange="actionFunc(this)">
                                    <option disabled selected value>- select action -</option>
                                    <option value="update~<%=id%>">Update</option>
                                    <option value="delete~<%=id%>">Delete</option>
                                </select>
                                <button type="submit" value="submit" name="button" hidden=""></button>

                    </form>
                    <%}%>

Any help is appreciated. I been solving this for many hours.

*There is no web.xml error.


来源: stackexchange

问:
React, Apollo 2, GraphQL, Authentication. How to re-render component after login
I have this code: https://codesandbox.io/s/507w9qxrrl

I don't understand:

1) How to re-render() Menu component after:

```<code>this.props.client.query({
  query: CURRENT_USER_QUERY,
  fetchPolicy: "network-only"
});
</code>```

If I login() I expect my Menu component to re-render() itself. But nothing.
Only if I click on the Home link it re-render() itself. I suspect because I'm using this to render it:

```<code><Route component={Menu} />
</code>```

for embrace it in react-router props. Is it wrong?

Plus, if inspect this.props of Menu after login() I see loading: true forever. Why?

2) How to prevent Menu component to query if not authenticated (eg: there isn't a token in localStorage); I'm using in Menu component this code:

```<code>export default graphql(CURRENT_USER_QUERY)(Menu);
</code>```

3) Is this the right way to go?

答:
EDITED

1) I just created new link https://codesandbox.io/s/0y3jl8znw

You want to fetch the user data in the componentWillReceiveProps method:

```<code>  componentWillReceiveProps() {
    this.props.client.query({query: CURRENT_USER_QUERY})
    .then((response) => {
      this.setState({ currentUser: response.data.currentUser})
    })
    .catch((e) => {
      console.log('there was an error ', e)
    })
  }
</code>```

This will make the component re-render.

2) Now when we moved the query call in the component's lifecycle method we have full control over it. If you want to call the query only if you have something in localstorage you just need to wrap the query in a simple condition:

```<code>  componentWillReceiveProps() {
    if(localstora.getItem('auth_token')) {
      this.props.client.query({query: CURRENT_USER_QUERY})
      .then((response) => {
        this.setState({ currentUser: response.data.currentUser})
      })
      .catch((e) => {
        console.log('there was an error ', e)
      })
    }
  }
</code>```

3) You want to store the global application state in redux store. Otherwise you will have to fetch the user info every time you need to work with it. I would recommend to define a state in you App component and store all the global values there.

ContentLicense: CC BY-SA 3.0

Body:
I have this code: https://codesandbox.io/s/507w9qxrrl

I don't understand:

1) How to re-render() Menu component after:

this.props.client.query({
  query: CURRENT_USER_QUERY,
  fetchPolicy: "network-only"
});

If I login() I expect my Menu component to re-render() itself. But nothing.
Only if I click on the Home link it re-render() itself. I suspect because I'm using this to render it:

<Route component={Menu} />

for embrace it in react-router props. Is it wrong?

Plus, if inspect this.props of Menu after login() I see loading: true forever. Why?

2) How to prevent Menu component to query if not authenticated (eg: there isn't a token in localStorage); I'm using in Menu component this code:

export default graphql(CURRENT_USER_QUERY)(Menu);

3) Is this the right way to go?

Body:
EDITED

1) I just created new link https://codesandbox.io/s/0y3jl8znw

You want to fetch the user data in the componentWillReceiveProps method:

  componentWillReceiveProps() {
    this.props.client.query({query: CURRENT_USER_QUERY})
    .then((response) => {
      this.setState({ currentUser: response.data.currentUser})
    })
    .catch((e) => {
      console.log('there was an error ', e)
    })
  }

This will make the component re-render.

2) Now when we moved the query call in the component's lifecycle method we have full control over it. If you want to call the query only if you have something in localstorage you just need to wrap the query in a simple condition:

  componentWillReceiveProps() {
    if(localstora.getItem('auth_token')) {
      this.props.client.query({query: CURRENT_USER_QUERY})
      .then((response) => {
        this.setState({ currentUser: response.data.currentUser})
      })
      .catch((e) => {
        console.log('there was an error ', e)
      })
    }
  }

3) You want to store the global application state in redux store. Otherwise you will have to fetch the user info every time you need to work with it. I would recommend to define a state in you App component and store all the global values there.


问:
.htaccess multiple parameters in URL
I'm now using this .htaccess file. It only changes the URL from www.example.com/?page=home to www.example.com/home.

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

RewriteRule ^([\w-]+)?$ index.php?page=$1 [L]
RewriteRule ^([\w-]+)/?$ index.php?page=$1 [L]
</code>```

I want to add more $_GET parameter, for example www.example.com/home/parameter1/value1/.
and preferably that you can do those parameters indefinitely.

答:
You can't do this "indefinitely" using .htaccess alone. You would need to decide on the maximum number (N) of parameters and write a directive for each in order: N, N-1, N-2, ... 1. However, you are also limited by the number of backreferences that are supported. ie. With just $1 to $9, you are limited to 4 parameters, using your method of including the parameter name in the URL path as well.

For example:

```<code># 3 additional parameters
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?page=$1&$2=$3&$4=$5&$6=$7 [L]

# 2 additional parameters
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?page=$1&$2=$3&$4=$5 [L]

# 1 additional parameter
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?page=$1&$2=$3 [L]

# No parameters (just the page)
RewriteRule ^([\w-]+)/?$ index.php?page=$1 [L]
</code>```

These all allow an optional trailing slash (as in your current example). However, you are better off deciding whether a trailing slash is required or not and choosing one or the other. Having the trailing slash optional simply promotes duplicate content.

This URL pattern is also a bit too "generalised" in my opinion. It is more usual to be specific and avoid including the parameter name in the URL. For example: example.com/home/value1/value2/value2 - the parameter names (param1, param2, etc.) would be hardcoded in the RewriteRule substitution. This would also allow you to have twice as many parameters.

```<code>RewriteRule ^([\w-]+)?$ index.php?page=$1 [L]
RewriteRule ^([\w-]+)/?$ index.php?page=$1 [L]
</code>```

You shouldn't need two directives here. (Providing the DirectoryIndex is set correctly.)

Title: .htaccess multiple parameters in URL

Body:
I'm now using this .htaccess file. It only changes the URL from www.example.com/?page=home to www.example.com/home.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

RewriteRule ^([\w-]+)?$ index.php?page=$1 [L]
RewriteRule ^([\w-]+)/?$ index.php?page=$1 [L]

I want to add more $_GET parameter, for example www.example.com/home/parameter1/value1/.
and preferably that you can do those parameters indefinitely.

Body:
You can't do this "indefinitely" using .htaccess alone. You would need to decide on the maximum number (N) of parameters and write a directive for each in order: N, N-1, N-2, ... 1. However, you are also limited by the number of backreferences that are supported. ie. With just $1 to $9, you are limited to 4 parameters, using your method of including the parameter name in the URL path as well.

For example:

# 3 additional parameters
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?page=$1&$2=$3&$4=$5&$6=$7 [L]

# 2 additional parameters
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?page=$1&$2=$3&$4=$5 [L]

# 1 additional parameter
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?page=$1&$2=$3 [L]

# No parameters (just the page)
RewriteRule ^([\w-]+)/?$ index.php?page=$1 [L]

These all allow an optional trailing slash (as in your current example). However, you are better off deciding whether a trailing slash is required or not and choosing one or the other. Having the trailing slash optional simply promotes duplicate content.

This URL pattern is also a bit too "generalised" in my opinion. It is more usual to be specific and avoid including the parameter name in the URL. For example: example.com/home/value1/value2/value2 - the parameter names (param1, param2, etc.) would be hardcoded in the RewriteRule substitution. This would also allow you to have twice as many parameters.

RewriteRule ^([\w-]+)?$ index.php?page=$1 [L]
RewriteRule ^([\w-]+)/?$ index.php?page=$1 [L]

You shouldn't need two directives here. (Providing the DirectoryIndex is set correctly.)


问:
Get the difference between two dates
How to find difference between two dates displayed in two text boxes
?.I was using following code and what i want is if the date difference goes beyond 90 days then i have to show some message to user.Here dates are dd/MM/yyyy format ,so here if i select from date as 23/8/17 and todate as 9/11/2017 ,the difference is coming as 423 days why?</p>

```<code>function checkDate() {
            debugger;
            var txtdate1 = document.getElementById('<%= txtFromDate.ClientID %>').value;
            var txtdate2 = document.getElementById('<%= txtToDate.ClientID %>').value;
            var date1 = new Date(txtdate2 );
            var date2 = new Date(txtdate1);
            var timeDiff = Math.abs(date2.getTime() - date1.getTime());
            var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
            if (diffDays > 90) {
                var Message = 'Dates are too far apart,It should be with in 3 months';}
</code>```

Title: Get the difference between two dates

Body:
How to find difference between two dates displayed in two text boxes
?.I was using following code and what i want is if the date difference goes beyond 90 days then i have to show some message to user.Here dates are dd/MM/yyyy format ,so here if i select from date as 23/8/17 and todate as 9/11/2017 ,the difference is coming as 423 days why?

function checkDate() {
            debugger;
            var txtdate1 = document.getElementById('<%= txtFromDate.ClientID %>').value;
            var txtdate2 = document.getElementById('<%= txtToDate.ClientID %>').value;
            var date1 = new Date(txtdate2 );
            var date2 = new Date(txtdate1);
            var timeDiff = Math.abs(date2.getTime() - date1.getTime());
            var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
            if (diffDays > 90) {
                var Message = 'Dates are too far apart,It should be with in 3 months';}

Body:
The result is 19 .I think your formating for date is wrong :

Math.ceil(Math.abs((new Date('2017/08/23 00:00:00.000')).getTime()-(new Date('2017/09/11 00:00:00.000')).getTime())/(1000*3600*24))

//==> 19


问:
Get img from canvas (toDataURL) --> Tainted canvases may not be exported
I have following error message:

```<code>Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
at draw (http://motherlang-bananalang.com/videator-b.php:172:50)
at HTMLVideoElement.<anonymous> (http://)
at HTMLVideoElement.dispatch (http:/)
at HTMLVideoElement.r.handle (http:/)
</code>```

HTML:

```<code><input type='hidden' class='input_img' name='imgBase64'/>
<?php
   $contents = $s3->getBucket("motherla-temp");
   $furl = "http://motherla- temp.s3.amazonaws.com/".$_SESSION['file_name'];
   echo '<video id="v" width="100%" height="auto" controls><source src="'.$furl.'" type="video/mp4"> </video>';
 ?>
 <p style=' '> Thumbnail: Pause video and choose a thumbnail! </p>
 <canvas id='c' style=';border:1px solid silver;'></canvas>
</code>```

JQUERY:

```<code> $('#v').on('pause', function(){
    var video = document.getElementById('v');
    var w = $(this).width();
    var h = $(this).height();
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');
    canvas.width = w;
    canvas.height = h;
    draw(this,context,w,h);
  })

function draw(v,c,w,h) {
  c.crossOrigin = "Anonymous";
  c.drawImage(v,0,0,w,h);
  //setTimeout(draw,20,v,c,w,h);
  var dataURL = document.getElementById('c').toDataURL();
  $('.input_img').val(dataURL);
}
</code>```

Now, what this code does is on video pause it grabs the video caption and draws it onto the canvas then it gets the dataURL from the canvas to transform it into img and save later on in the database and to the server. Basically, I'm making a custom video thumbnail script.

The question is: how to get rid of the error and get the canvas NOT tainted. (when I was working on locahost - everything was fine, but now my website is online and here is the problem) I've searched the issue and none of the possible solution helped me (maybe, because this is my first website and I'm a complete newbie in this(sorry, if someone may ask to give the website link - this is kind of a secret till I finish developing it)). I've read about CORS and if I'd make the page at the root of the server it will all go but I actually want the page to STAY located at where it is - at the public_html/ folder. So, I'm guessing (though i'm really clueless here at this point, as I did a research on the topic and it did not help me out) I should either use this line of code somewhere:

```<code>crossorigin="Anonymous"
</code>```

or I should ask my hosting server support team to change some settings in server for my website so that it would work even if the page is not located at the root of server.

If I should use that line of code - please, help me out where, because I know it has something to do with img tag but I have no img tag at all!

And if I can ask my hosting provider (the support team of it) to "change something on the server so the error would go away" (lol, sounds as goofy as it is) then please point me out what exactely should i ask the support team to change (what settings).

I know I should add this:

```<code><img src="otherdomain.com" crossorigin="Anonymous" />

  <!-- Or with Javascript -->
  <script>
   var image = new Image();
   image.crossOrigin = "Anonymous";
    ...
 </script>
</code>```

somewhere in my code but I dont know where, as I don't have any img tag. I'd apreciate if you guys would modify my code so the error would vanish or just point me out the possible ways of solving the issue.

Again, I'm real newbie to the programming in general, so any advices and help would be really apreciated!

Thank you in advance. Peace, guys.

答:
To others who have not been able to solve the problem here is a sample xml code that should allow CORS from your s3 bucket.</p>

```<code><!-- Sample policy -->
<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
</code>```

Body:
I have following error message:

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
at draw (http://motherlang-bananalang.com/videator-b.php:172:50)
at HTMLVideoElement.<anonymous> (http://)
at HTMLVideoElement.dispatch (http:/)
at HTMLVideoElement.r.handle (http:/)

HTML:

<input type='hidden' class='input_img' name='imgBase64'/>
<?php
   $contents = $s3->getBucket("motherla-temp");
   $furl = "http://motherla- temp.s3.amazonaws.com/".$_SESSION['file_name'];
   echo '<video id="v" width="100%" height="auto" controls><source src="'.$furl.'" type="video/mp4"> </video>';
 ?>

 Thumbnail: Pause video and choose a thumbnail!

 <canvas id='c' style=';border:1px solid silver;'></canvas>

JQUERY:

 $('#v').on('pause', function(){
    var video = document.getElementById('v');
    var w = $(this).width();
    var h = $(this).height();
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');
    canvas.width = w;
    canvas.height = h;
    draw(this,context,w,h);
  })

function draw(v,c,w,h) {
  c.crossOrigin = "Anonymous";
  c.drawImage(v,0,0,w,h);
  //setTimeout(draw,20,v,c,w,h);
  var dataURL = document.getElementById('c').toDataURL();
  $('.input_img').val(dataURL);
}

Now, what this code does is on video pause it grabs the video caption and draws it onto the canvas then it gets the dataURL from the canvas to transform it into img and save later on in the database and to the server. Basically, I'm making a custom video thumbnail script.

The question is: how to get rid of the error and get the canvas NOT tainted. (when I was working on locahost - everything was fine, but now my website is online and here is the problem) I've searched the issue and none of the possible solution helped me (maybe, because this is my first website and I'm a complete newbie in this(sorry, if someone may ask to give the website link - this is kind of a secret till I finish developing it)). I've read about CORS and if I'd make the page at the root of the server it will all go but I actually want the page to STAY located at where it is - at the public_html/ folder. So, I'm guessing (though i'm really clueless here at this point, as I did a research on the topic and it did not help me out) I should either use this line of code somewhere:

crossorigin="Anonymous"

or I should ask my hosting server support team to change some settings in server for my website so that it would work even if the page is not located at the root of server.

If I should use that line of code - please, help me out where, because I know it has something to do with img tag but I have no img tag at all!

And if I can ask my hosting provider (the support team of it) to "change something on the server so the error would go away" (lol, sounds as goofy as it is) then please point me out what exactely should i ask the support team to change (what settings).

I know I should add this:

somewhere in my code but I dont know where, as I don't have any img tag. I'd apreciate if you guys would modify my code so the error would vanish or just point me out the possible ways of solving the issue.

Again, I'm real newbie to the programming in general, so any advices and help would be really apreciated!

Thank you in advance. Peace, guys.

Body:
To others who have not been able to solve the problem here is a sample xml code that should allow CORS from your s3 bucket.

<!-- Sample policy -->
<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>


问:
How to call global function from promise function?
When performing the below function:

```<code>        try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    }
};

updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
....
</code>```

The updateAuction function is not called (even though the console.log functions are working correctly and displaying a message). How can I call the updateAuction function?

答:
You must define your function befor try. correct it like this</p>

```<code>var updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
    ...
}

try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    ;
</code>```

Body:
When performing the below function:

        try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    }
};

updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
....

The updateAuction function is not called (even though the console.log functions are working correctly and displaying a message). How can I call the updateAuction function?

Body:
You must define your function befor try. correct it like this

var updateAuction = function(data) {
    console.log("UPDATE AUCTIONS!");
    ...
}

try {
            Auction.deployed().then(function(contractInstance) {
                contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
                    console.log("AUCTION HAS STARTED!!");
                    console.log(result);
                    updateAuction(result.receipt);
                });
            });
        } catch (err) {}
    ;


问:
Replace wchar_t error return memory address
I want to replace a specific character wchar_t. as a result it return memory address. is there a way to return replaced wchar_t?

```<code>#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Psapi.h>

using namespace std;

int main()
{
    wchar_t processPath[MAX_PATH];

    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 3820);

    GetProcessImageFileName(hProcess, processPath, MAX_PATH);

    CloseHandle(hProcess);

    wchar_t * pwc;

    pwc = wcsstr(processPath, L"\\Device\\HardiskVolume1");

    wcscpy_s(pwc, 100, L"C:", 100);

    wcout << processPath;

    return 0;
}
</code>```

Thank you

答:
Use GetModuleFileNameEx Windows XP and higher. Or QueryFullProcessImageName for Vista and higher.

Otherwise, you can't assume "\\Device\\HardiskVolume1" is always "C:"

See also this SO Q&A: Convert HarddiskVolume path to normal path

Start by changing "\Device" to "\\?":

```<code>`"\\Device\\HardiskVolume1\\path.exe"` //to
`"\\\\?\\HardiskVolume1\\path.exe"`

wchar_t buf[MAX_PATH];
wchar_t *ptr = wcsstr(processPath, L"\\Device");
if(ptr)
{
    wcscpy_s(buf, L"\\\\?");
    wcscat_s(buf, ptr + wcslen(L"\\Device"));
}
</code>```

Now you can open buf in CreateFile, then use GetFinalPathNameByHandle to get

```<code>`"\\\\?\\C:\\path.exe"`
</code>```

Note that wcsstr returns NULL if search string is not found. If search string was found and copy was successful, you end up overwriting processPath the way you have done that. Moreover, wcscpy_s is the secure version of wcscpy. If you don't want to use wcscpy_s correctly then just use wcscpy without using a random number like 100 as the argument.

Body:
I want to replace a specific character wchar_t. as a result it return memory address. is there a way to return replaced wchar_t?

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Psapi.h>

using namespace std;

int main()
{
    wchar_t processPath[MAX_PATH];

    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 3820);

    GetProcessImageFileName(hProcess, processPath, MAX_PATH);

    CloseHandle(hProcess);

    wchar_t * pwc;

    pwc = wcsstr(processPath, L"\\Device\\HardiskVolume1");

    wcscpy_s(pwc, 100, L"C:", 100);

    wcout << processPath;

    return 0;
}

Thank you

Body:
Use GetModuleFileNameEx Windows XP and higher. Or QueryFullProcessImageName for Vista and higher.

Otherwise, you can't assume "\\Device\\HardiskVolume1" is always "C:"

See also this SO Q&A: Convert HarddiskVolume path to normal path

Start by changing "\Device" to "\\?":

`"\\Device\\HardiskVolume1\\path.exe"` //to
`"\\\\?\\HardiskVolume1\\path.exe"`

wchar_t buf[MAX_PATH];
wchar_t *ptr = wcsstr(processPath, L"\\Device");
if(ptr)
{
    wcscpy_s(buf, L"\\\\?");
    wcscat_s(buf, ptr + wcslen(L"\\Device"));
}

Now you can open buf in CreateFile, then use GetFinalPathNameByHandle to get

`"\\\\?\\C:\\path.exe"`

Note that wcsstr returns NULL if search string is not found. If search string was found and copy was successful, you end up overwriting processPath the way you have done that. Moreover, wcscpy_s is the secure version of wcscpy. If you don't want to use wcscpy_s correctly then just use wcscpy without using a random number like 100 as the argument.


问:
Using command line parameters to manipulate values in a csv file
I am given a variety of .csv files and for each one I need to identify the keys associated with the longest list; and print that key. As well as the values that only appear in the last column of the csv file, and print that value. I am encouraged to use command line parameters, which I am new to so I'm having a hard time with this. Here is an example of a csv file given:

Grasshopper,Grass

Lizard,Grasshopper

Hawk,Grasshopper,Lizard,Rabbit,Mouse,Snake

Rabbit,Grass

Snake,Mouse

Mouse,Grass

So the key with the longest list I would be trying to print is the Hawk.
This is the code I have so far:

```<code>    import sys
    import csv
    if len(sys.argv) != "":
        inf = open(sys.argv[0], "r")
        outf = open(sys.argv[1], "w")

        words = 0
        maxvalue = 0

        line = inf.readline()
        for line in data:
            while line != "":
               words = words + len(line.split())

               maxvalue = maxvalue + words
               if words > value:
                   maxline = words

              # Read the next line from the file.
              line = inf.readline()

       outf.write(str(maxvalue))
</code>```

But with my little knowledge of command line parameters it doesn't work as I am given an index error, and I'm unsure of how to fix it.
Prior to this code I have opened/read the files. I'm using python3, any help would be much appreciated!!
Thank you!

答:
You need to change your if condition to:

```<code>if sys.argv:
</code>```

Body:
I am given a variety of .csv files and for each one I need to identify the keys associated with the longest list; and print that key. As well as the values that only appear in the last column of the csv file, and print that value. I am encouraged to use command line parameters, which I am new to so I'm having a hard time with this. Here is an example of a csv file given:

Grasshopper,Grass

Lizard,Grasshopper

Hawk,Grasshopper,Lizard,Rabbit,Mouse,Snake

Rabbit,Grass

Snake,Mouse

Mouse,Grass

So the key with the longest list I would be trying to print is the Hawk.
This is the code I have so far:

    import sys
    import csv
    if len(sys.argv) != "":
        inf = open(sys.argv[0], "r")
        outf = open(sys.argv[1], "w")

        words = 0
        maxvalue = 0

        line = inf.readline()
        for line in data:
            while line != "":
               words = words + len(line.split())

               maxvalue = maxvalue + words
               if words > value:
                   maxline = words

              # Read the next line from the file.
              line = inf.readline()

       outf.write(str(maxvalue))

But with my little knowledge of command line parameters it doesn't work as I am given an index error, and I'm unsure of how to fix it.
Prior to this code I have opened/read the files. I'm using python3, any help would be much appreciated!!
Thank you!

Body:
You need to change your if condition to:

if sys.argv:


问:
Send query parameters over with an array
I have a class Pagination with a method that counts the total number of articles. When I instantiate the class, I explicitly type the sql query and give him the parameters. Here is an example:

```<code>$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ?',
    'params' => "%$keyWord%"
]);
</code>```

The method that handles the query runs it and returns the result:

```<code>return $this->db->getRows($this->query['query'], [$this->query['params']]);
</code>```

Everything works perfect, however, for this particular case (for searching articles) I want not only to count the results that match title but also by content, in other words I want to change to:

```<code>'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? OR content LIKE ?'
</code>```

But how do I pass the second parameter in 'params' => "%$keyWord%" ?

Edit:
Pagination class.

```<code>    public function __construct(string $table, $currentPage = 1, $perPage, $query = [])
{
    $this->db = Database::getInstance();
    $this->currentPage = $currentPage;
    $this->perPage = $perPage;
    $this->table = $table;
    $this->query = $query;

    $getTotalRows = $this->countResultsFromTable();
    $getTotalRows = $getTotalRows[0]->count;
    $this->total = ceil($getTotalRows / $this->perPage);
}

public function countResultsFromTable()
{
    if(empty($this->query))
    {
        return $this->db->getRows("SELECT COUNT(*) as count FROM $this->table");
    }
    else
    {
        return $this->db->getRows($this->query['query'], [$this->query['params']]);
    }
}
</code>```

答:
Try the following: extend your call to

```<code>$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? AND content LIKE ?',
    'title' => "%$keyWord%",
    'content' => $CONTENT
]);
</code>```

and the query evaluation to

```<code>return $this->db->getRows($this->query['query'],
  [$this->query['title'], $this->query['content']]
);
</code>```

If you don't want to change the Pagination class, append the content to the query before instantiating the Pagination:

```<code>$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? AND content LIKE "%' . your_escaping_function($content) . '%"',
    'title' => "%$keyWord%"
]);
</code>```

Body:
I have a class Pagination with a method that counts the total number of articles. When I instantiate the class, I explicitly type the sql query and give him the parameters. Here is an example:

$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ?',
    'params' => "%$keyWord%"
]);

The method that handles the query runs it and returns the result:

return $this->db->getRows($this->query['query'], [$this->query['params']]);

Everything works perfect, however, for this particular case (for searching articles) I want not only to count the results that match title but also by content, in other words I want to change to:

'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? OR content LIKE ?'

But how do I pass the second parameter in 'params' => "%$keyWord%" ?

Edit:
Pagination class.

    public function __construct(string $table, $currentPage = 1, $perPage, $query = [])
{
    $this->db = Database::getInstance();
    $this->currentPage = $currentPage;
    $this->perPage = $perPage;
    $this->table = $table;
    $this->query = $query;

    $getTotalRows = $this->countResultsFromTable();
    $getTotalRows = $getTotalRows[0]->count;
    $this->total = ceil($getTotalRows / $this->perPage);
}

public function countResultsFromTable()
{
    if(empty($this->query))
    {
        return $this->db->getRows("SELECT COUNT(*) as count FROM $this->table");
    }
    else
    {
        return $this->db->getRows($this->query['query'], [$this->query['params']]);
    }
}

Body:
Try the following: extend your call to

$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? AND content LIKE ?',
    'title' => "%$keyWord%",
    'content' => $CONTENT
]);

and the query evaluation to

return $this->db->getRows($this->query['query'],
  [$this->query['title'], $this->query['content']]
);

If you don't want to change the Pagination class, append the content to the query before instantiating the Pagination:

$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? AND content LIKE "%' . your_escaping_function($content) . '%"',
    'title' => "%$keyWord%"
]);


问:
How to ORDER MySQL results while excluding a string from the order title
Im trying use MySQL to order by excluding "excl" if it's found at the start of a string, and using what ever comes after "excl" to order the results.

So it will order like this:

title a name

excl title b name2

title c name

title d name

But not:

title a name

title c name

title d name

excl title b name2

答:
You want to tell the ORDER clause that if the string begins with the text you're looking for, then use a substring that comes after that string.  So "excl title a" becomes "title a" as far as the ORDER process is concerned.

```<code>SELECT  title
FROM    table_name
ORDER BY
IF (SUBSTRING(LOWER(title), 1, 5) = 'excl ',
    SUBSTRING(title, 6),
    title
)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You want to tell the ORDER clause that if the string begins with the text you're looking for, then use a substring that comes after that string.  So "excl title a" becomes "title a" as far as the ORDER process is concerned.

SELECT  title
FROM    table_name
ORDER BY
IF (SUBSTRING(LOWER(title), 1, 5) = 'excl ',
    SUBSTRING(title, 6),
    title
)


问:
How do i fix the unbound local error?
Error
selfpoints += cardPoints
UnboundLocalError: local variable 'selfpoints' referenced before assignment</p>

```<code>class userpoint_status:
     def __init__():
         selfpoints = 0
     def increase_points():
         self.points += cardPoints
         print("You have",selfpoints,"points")
         if selfpoints > 21:
                 lose_game()
</code>```

答: you have multiple occurences in your code where you type selfpoints instead of self.points. You need to put the dot there so it becomes an instance variable. Given that cardPoints and lose_game are global variables you won't have any more errors.

Title: How do i fix the unbound local error?

Body:
Error
selfpoints += cardPoints
UnboundLocalError: local variable 'selfpoints' referenced before assignment

class userpoint_status:
     def __init__():
         selfpoints = 0
     def increase_points():
         self.points += cardPoints
         print("You have",selfpoints,"points")
         if selfpoints > 21:
                 lose_game()


问:
React router and nginx giving Unexpected Token <
I have a react website which I am hosting inside a Docker container that is running Nginx, which I have running on Port 3000. I then have an instance of Nginx on my host machine, which I have a reverse proxy pointing to 127.0.0.1:3000.

Everything works fine, except I have a Twitter authentication call, which uses a callback. When the url points back to mysite.com/authenticated, this is asking Nginx for the path which of course falls over.

I have scoured the internet and have found many posts indicating I should have this in my nginx default file:

```<code>location / {
        proxy_pass 127.0.0.1:3000;
        try_files $uri $uri/ /index.html;
    }
</code>```

When I then navigate to my website, even the root, I am getting unexpected token < in the console errors.

What could be causing this issue?

答:
For me it was the link to app.js

```<code><script src="/app/bundle.js"></script>
</code>```

When I tried to reach my App at

```<code>http://localhost:8080/serv9090
</code>```

the browser tried to find /app/bundle.js via

```<code>http://localhost:8080/app/bundle.js
</code>```

Which is not found at localhost:8080 (nginx)
For a first try I changed

```<code><script src="/app/bundle.js"></script>
</code>```

to

```<code><script src="http://localhost:8080/serv9090/app/bundle.js"></script>
</code>```

This worked fine.
Hope this helped.

Body:
I have a react website which I am hosting inside a Docker container that is running Nginx, which I have running on Port 3000. I then have an instance of Nginx on my host machine, which I have a reverse proxy pointing to 127.0.0.1:3000.

Everything works fine, except I have a Twitter authentication call, which uses a callback. When the url points back to mysite.com/authenticated, this is asking Nginx for the path which of course falls over.

I have scoured the internet and have found many posts indicating I should have this in my nginx default file:

location / {
        proxy_pass 127.0.0.1:3000;
        try_files $uri $uri/ /index.html;
    }

When I then navigate to my website, even the root, I am getting unexpected token < in the console errors.

What could be causing this issue?

Body:
For me it was the link to app.js

<script src="/app/bundle.js"></script>

When I tried to reach my App at

http://localhost:8080/serv9090

the browser tried to find /app/bundle.js via

http://localhost:8080/app/bundle.js

Which is not found at localhost:8080 (nginx)
For a first try I changed

<script src="/app/bundle.js"></script>

to

<script src="http://localhost:8080/serv9090/app/bundle.js"></script>

This worked fine.
Hope this helped.


问:
Parse XML file and grab value from parent node
XML file looks like this:

<?xml version="1.0"?>
<catalog>
    <book id="bk101">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>
        <publish_date>2000-10-01</publish_date>
        <description>An in-depth look at creating applications with XML.</description>
    </book>
    <book id="bk102">
        <author>Ralls, Kim</author>
        <title>Midnight Rain</title>
        <genre>Fantasy</genre>
        <price>5.95</price>
        <publish_date>2000-12-16</publish_date>
        <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
    </book>
</catalog>
```

<p>I need to read all data to my class:</p>

```public class Book
{
    public string Id { get; set; }

    public string Author { get; set; }
    public string Title { get; set; }
    public Genre Genre { get; set; }
    public decimal Price { get; set; }
    public DateTime PublishDate { get; set; }
    public string Description { get; set; }

}
```

<p>Below code doesn't work, I can grab bookId from node, but not Title, Author..
How to achieve that result?   This is what I have so far:</p>

```const string filePath = @"C:\Users\Michał\Desktop\books.xml";

XDocument xmlDoc = XDocument.Load(filePath);

var dupa = xmlDoc
    .Descendants("book")
    .Select(x => new Book()
    {
        Id = (string) x.Attribute("bookid"),

        Title = (string) x.Attribute("title") // Title is empty after that code runs

    }).ToList();
```

答:
id is an attribute of <book> but the other nodes are child XML elements so you need to access them using XContainer.Element(XName name):

```<code>var dupa = xmlDoc
    .Descendants("book")
    .Select(x => new Book
    {
        Id = (string)x.Attribute("bookid"),
        Author = (string)x.Element("author"),
        Title = (string)x.Element("title"),
        Genre = (Genre)Enum.Parse(typeof(Genre), (string)x.Element("genre")),
        Price = (decimal)x.Element("price"),
        PublishDate = (DateTime)x.Element("publish_date"),
        Description = (string)x.Element("description"),
    }).ToList();
</code>```

Here I am assuming that Genre is an enum that looks something like:

```<code>public enum Genre
{
    Computer,
    Fantasy,
};
</code>```

Sample fiddle #1.

Alternatively, you could create a Catalog type that contains your list of books, annotate it and Book with attributes that control XML serialization, and deserializing everything using XmlSerializer.

Define your types like so:

```<code>[XmlRoot(ElementName = "book")]
public class Book
{
    [XmlElement(ElementName = "author")]
    public string Author { get; set; }
    [XmlElement(ElementName = "title")]
    public string Title { get; set; }
    [XmlElement(ElementName = "genre")]
    public Genre Genre { get; set; }
    [XmlElement(ElementName = "price")]
    public decimal Price { get; set; }
    [XmlElement(ElementName = "publish_date")]
    public string PublishDate { get; set; }
    [XmlElement(ElementName = "description")]
    public string Description { get; set; }
    [XmlAttribute(AttributeName = "id")]
    public string Id { get; set; }
}

[XmlRoot(ElementName = "catalog")]
public class Catalog
{
    [XmlElement(ElementName = "book")]
    public List<Book> Books { get; set; }
}

public enum Genre
{
    Computer,
    Fantasy,
};
</code>```

And then deserialize as follows:

```<code>List<Book> dupa;
using (var reader = XmlReader.Create(filePath))
{
    var serializer = new XmlSerializer(typeof(Catalog));
    dupa = ((Catalog)serializer.Deserialize(reader)).Books;
}
</code>```

Sample fiddle #2.

Notes:

Consider changing Genre from an enum to a string.  With your current model, deserialization will fail if new genres are later added to the XML.

There are a variety of tools to auto-generate types from XML that are compatible with XmlSerializer.  I used https://xmltocsharp.azurewebsites.net/ and then modified the property names and types as required.  Another option is xsd.exe.  For more see Generate C# class from XML.

Body:
XML file looks like this:

<?xml version="1.0"?>
<catalog>
    <book id="bk101">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>
        <publish_date>2000-10-01</publish_date>
        <description>An in-depth look at creating applications with XML.</description>
    </book>
    <book id="bk102">
        <author>Ralls, Kim</author>
        <title>Midnight Rain</title>
        <genre>Fantasy</genre>
        <price>5.95</price>
        <publish_date>2000-12-16</publish_date>
        <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
    </book>
</catalog>

I need to read all data to my class:

public class Book
{
    public string Id { get; set; }

    public string Author { get; set; }
    public string Title { get; set; }
    public Genre Genre { get; set; }
    public decimal Price { get; set; }
    public DateTime PublishDate { get; set; }
    public string Description { get; set; }

}

Below code doesn't work, I can grab bookId from node, but not Title, Author..
How to achieve that result?   This is what I have so far:

const string filePath = @"C:\Users\Michał\Desktop\books.xml";

XDocument xmlDoc = XDocument.Load(filePath);

var dupa = xmlDoc
    .Descendants("book")
    .Select(x => new Book()
    {
        Id = (string) x.Attribute("bookid"),

        Title = (string) x.Attribute("title") // Title is empty after that code runs

    }).ToList();

Body:
id is an attribute of <book> but the other nodes are child XML elements so you need to access them using XContainer.Element(XName name):

var dupa = xmlDoc
    .Descendants("book")
    .Select(x => new Book
    {
        Id = (string)x.Attribute("bookid"),
        Author = (string)x.Element("author"),
        Title = (string)x.Element("title"),
        Genre = (Genre)Enum.Parse(typeof(Genre), (string)x.Element("genre")),
        Price = (decimal)x.Element("price"),
        PublishDate = (DateTime)x.Element("publish_date"),
        Description = (string)x.Element("description"),
    }).ToList();

Here I am assuming that Genre is an enum that looks something like:

public enum Genre
{
    Computer,
    Fantasy,
};

Sample fiddle #1.

Alternatively, you could create a Catalog type that contains your list of books, annotate it and Book with attributes that control XML serialization, and deserializing everything using XmlSerializer.

Define your types like so:

[XmlRoot(ElementName = "book")]
public class Book
{
    [XmlElement(ElementName = "author")]
    public string Author { get; set; }
    [XmlElement(ElementName = "title")]
    public string Title { get; set; }
    [XmlElement(ElementName = "genre")]
    public Genre Genre { get; set; }
    [XmlElement(ElementName = "price")]
    public decimal Price { get; set; }
    [XmlElement(ElementName = "publish_date")]
    public string PublishDate { get; set; }
    [XmlElement(ElementName = "description")]
    public string Description { get; set; }
    [XmlAttribute(AttributeName = "id")]
    public string Id { get; set; }
}

[XmlRoot(ElementName = "catalog")]
public class Catalog
{
    [XmlElement(ElementName = "book")]
    public List<Book> Books { get; set; }
}

public enum Genre
{
    Computer,
    Fantasy,
};

And then deserialize as follows:

List<Book> dupa;
using (var reader = XmlReader.Create(filePath))
{
    var serializer = new XmlSerializer(typeof(Catalog));
    dupa = ((Catalog)serializer.Deserialize(reader)).Books;
}

Sample fiddle #2.

Notes:

Consider changing Genre from an enum to a string.  With your current model, deserialization will fail if new genres are later added to the XML.

There are a variety of tools to auto-generate types from XML that are compatible with XmlSerializer.  I used https://xmltocsharp.azurewebsites.net/ and then modified the property names and types as required.  Another option is xsd.exe.  For more see Generate C# class from XML.

ContentLicense: CC BY-SA 4.0


问:
For loop: Count matches and unique elements among two dataframes and apply function to counts
I would like to conduct a very involved loop. I have multiple regions, each with hundreds of plots in my real data frame. I would like to subset by region and then plot and preform various functions on the subsets to ultimately calculate dissimilarity owed to only species that are shared.  I will preface by saying each row is representative of an interaction.

My example df:

```<code> set.seed(540)
 df<- data.frame(region= c(rep(1, 16), rep(2,8)),
            plot= c(rep("A",5), rep("B",9), rep("C", 2), rep("D", 6),rep("E", 2)),
            plantsp= sample(1:24,24, replace= TRUE),
            lepsp= sample(1:24,24,replace= TRUE),
            psitsp= sample(1:24,24,replace= TRUE))
 df[] <- lapply(df, as.character)
 df$plantsp<-paste('plantsp', df$plantsp, sep='_')
 df$lepsp<-paste('lepsp', df$lepsp, sep='_')
 df$psitsp<-paste('psitsp', df$psitsp, sep='_')
 df$paste1<- paste(df$plantsp, df$lepsp, sep='_')
 df$paste2<- paste(df$lepsp, df$psitsp, sep='_')
 df$paste3<- paste(df$plantsp,df$lepsp, df$psitsp)
</code>```

Step1: Subset df by region. Example:

```<code>region_sub <- split(df, df$region)
</code>```

Step2: Subset df by plot. Example:

```<code>plot_sub <- split(region_sub[[1]], region_sub[[1]][[2]])
</code>```

Step3: We will call each subset (each list component) from the step above a plot subset. In this example I will use the first subset (region1, plotA) as an example for all subsequent outputs. I will call this region1, plotA subset  plot_sub1. I want to compare plot_sub1 to the original df to make three df subsets. We will call these df_sub1, df_sub2, df_sub3. First, df_sub1 consists of matches among entries in the plantsp, lepsp columns among plot_sub1 and df. Rows with any unique entries are removed, as well as and rows where a plantsp match, but not the lepsp and visa versa. Example of df_sub1:

```<code>df_sub1<- df[c(1,2,3,4,5,22),c(1:4,6)]
</code>```

Notice, only those rows with shared species remain. Further, only those rows with shared species that also interact remain. Also, I have removed unnecessary columns (e.g. psitsp, paste2, paste3) to draw your attention to the results of this step. These columns do not need to be removed for the code.

Step4: Repeat step3 for lepsp and psitsp columns to make df_sub2. Example:

```<code>df_sub2<- df[1:5,c(1:2,4,5,7)]
</code>```

Step5: Repeat step3 for plantsp,lepsp and psitsp column to make df_sub3. Example:

```<code>df_sub3<- df[1:5,c(1:5,8)]
</code>```

Step6: Now that all subsets are made, I want to count matching elements in the paste1 column among plot_sub1 and df_sub1 (=5). Example:
This would be stored in a vector match. The results  will be stored in the match or unique vector, accordingly.  Example:

```<code>match<- length(intersect(df_sub1$paste1,  plot_sub[[1]]$paste1))
match
</code>```

I also want to count the unique elements (=1). This would be stored in a vector unique. This will be repeated for plot_sub1 and df_sub2and plot_sub1 and df_sub3. I am not sure how to count unique elements among two df so I cannot offer example code for that.

```<code> unique<- 1
</code>```

Note: Matches among plot_sub only need to be counted 1 time in the event the df_sub has repeated interactions or matches. This needs to account for presence- absence of matches, not the abundance.

In summary for this subset, the two vectors would be:

```<code>match<- c( length(intersect(df_sub1$paste1,  plot_sub[[1]]$paste1)),
length(intersect(df_sub2$paste2,  plot_sub[[1]]$paste2)),
length(intersect(df_sub3$paste3,  plot_sub[[1]]$paste3))

match

unique<-c(1,0,0)
</code>```

The sum will then be totaled for each vector. Example:

```<code>sum_match<- 15
sum_unique<- 1
</code>```

Step7: Lastly, these values would be input into a function:
       ((a + b)/((2*a + b)/2) - 1)   Where a= sum_match and b=sum_unique.
       The value is then input into the result vector res_vec.

Step8: This process (step3-7) would be iterated for each plot subset.

Effectively, this will calculate the dissimilarity of shared interactions among plot interactions and the corresponding metaweb (all possible interactions). This is a modification from (Poisot et al 2012) to account for tritrophic interactions.

It's quite pathetic, but to start the for loop I have:

```<code>res_vec<- NA

for (i in 1:length(unique(df$region)))
  {
      for (j in 1:length(unique(df$plot)))
     {
</code>```

I really appreciate any time one is willing to help me realize the arguments within the loop. That is where it gets tricky for me.

答:
Thans @Gregor for all the clarification you've already done in the comments!

Here is my solution using the the tidyverse.

CODE + EXPLANATION

```<code>## Load packages
library(tidyverse)

## Nest data
new_df <- df %>%
  group_by(region, plot) %>%
  nest(.key = plot_sub)

new_df

# A tibble: 5 x 3
#     region   plot         plot_sub
#      <dbl> <fctr>           <list>
#   1      1      A <tibble [5 x 3]>
#   2      1      B <tibble [9 x 3]>
#   3      1      C <tibble [2 x 3]>
#   4      2      D <tibble [6 x 3]>
#   5      2      E <tibble [2 x 3]>
</code>```

The column plot_sub contains the same data as the list with the same name in your question. Think of this column as a list of dataframes.

I know write a function to create the df_sub's. This keeps our code more clean, and avoids unecessary repetition. This function will then be applied to our column plot_sub

```<code># Function to create the df_sub
# Takes the plot_sub, original dataframe (df) and a list of columns, which should be compared
# Returns the desired df_sub with new interactions of species which are in plot_sub
# Only unique interactions are returned

create_df_sub <-  function(plot_sub, df, col_list){
  # Filter df such that it only contains species which are in plot_sub
  for (x in col_list) {
    df <- df[df[[x]] %in% plot_sub[[x]], ]
  }

  # Combine plot_sub and filtered df
  df_sub <- rbind(plot_sub[, col_list], df[, col_list])
  # Paste relevant colums together
  df_sub$paste_col <- do.call(paste, c(df_sub[, col_list], sep = '_'))
  # Exclude duplicated values
  df_sub <- df_sub[!duplicated(df_sub$paste_col), ]

  return(df_sub)
}
</code>```

Now I define the columns I want to create the df_sub with and then apply the function to the plot_sub-column

```<code>col_list1 <- c('plantsp', 'lepsp')
col_list2 <- c('lepsp', 'psitsp')
col_list3 <- c('plantsp', 'lepsp', 'psitsp')

new_df <- new_df %>%
  mutate(df_sub1 = map(plot_sub, create_df_sub, df = df, col_list = col_list1),
         df_sub2 = map(plot_sub, create_df_sub, df = df, col_list = col_list2),
         df_sub3 = map(plot_sub, create_df_sub, df = df, col_list = col_list3))
</code>```

map takes a vector or list as argument and applies the specified function to each element (like lapply). Compare the first elements of df_sub1 and plot_sub to see the difference.

```<code>new_df$plot_sub[[1]]
# A tibble: 5 x 3
#      plantsp    lepsp    psitsp
#        <chr>    <chr>     <chr>
# 1  plantsp_2 lepsp_19 psitsp_19
# 2 plantsp_21 lepsp_19  psitsp_4
# 3 plantsp_19  lepsp_2 psitsp_11
# 4  plantsp_9 lepsp_13 psitsp_24
# 5 plantsp_24  lepsp_9  psitsp_2

new_df$df_sub1[[1]]
# A tibble: 6 x 3
#      plantsp    lepsp           paste_col
#        <chr>    <chr>               <chr>
# 1  plantsp_2 lepsp_19  plantsp_2_lepsp_19
# 2 plantsp_21 lepsp_19 plantsp_21_lepsp_19
# 3 plantsp_19  lepsp_2  plantsp_19_lepsp_2
# 4  plantsp_9 lepsp_13  plantsp_9_lepsp_13
# 5 plantsp_24  lepsp_9  plantsp_24_lepsp_9
# 6  plantsp_9  lepsp_2   plantsp_9_lepsp_2
</code>```

The new interaction is added in df_sub1.

To extract matching and unique values, I use inner_join and anti_join on the plot_sub-column and the different df_sub's

```<code>new_df <- new_df %>%
  mutate(match1 = map2(df_sub1, plot_sub, inner_join, by = col_list1),
         match2 = map2(df_sub2, plot_sub, inner_join, by = col_list2),
         match3 = map2(df_sub3, plot_sub, inner_join, by = col_list3),
         unique1 = map2(df_sub1, plot_sub, anti_join, by = col_list1),
         unique2 = map2(df_sub2, plot_sub, anti_join, by = col_list2),
         unique3 = map2(df_sub3, plot_sub, anti_join, by = col_list3))
</code>```

The inner_join returns all rows, which have matching values in the columns specified in the by-argument, whereas the anti_join returns all rows of df_sub, which are not matched.
Here I use the map2-function, which takes two vectors/list and applies the specified function.

```<code>new_df$match1[[1]]
# A tibble: 5 x 4
#      plantsp    lepsp    psitsp           paste_col
#        <chr>    <chr>     <chr>               <chr>
# 1  plantsp_2 lepsp_19 psitsp_19  plantsp_2_lepsp_19
# 2 plantsp_21 lepsp_19  psitsp_4 plantsp_21_lepsp_19
# 3 plantsp_19  lepsp_2 psitsp_11  plantsp_19_lepsp_2
# 4  plantsp_9 lepsp_13 psitsp_24  plantsp_9_lepsp_13
# 5 plantsp_24  lepsp_9  psitsp_2  plantsp_24_lepsp_9

new_df$unique1[[1]]
# A tibble: 1 x 3
#     plantsp   lepsp         paste_col
#       <chr>   <chr>             <chr>
# 1 plantsp_9 lepsp_2 plantsp_9_lepsp_2
</code>```

In the last step I extract the number of rows of each match and unique and sum it up. I also calculate the res_vec.

```<code>new_df <- new_df %>%
  mutate(sum_match = map_int(match1, nrow) + map_int(match2, nrow) + map_int(match3, nrow),
         sum_unique = map_int(unique1, nrow) + map_int(unique2, nrow) + map_int(unique3, nrow),
         res_vec = ((sum_match + sum_unique)/((2*sum_match + sum_unique)/2)) - 1)
</code>```

Here I use map_int as my return value is an integer and I want to directly use it in a sum. Using map only would return a list which I first have to convert to a integer vector.

```<code>new_df %>% select(region, plot, sum_match, sum_unique, res_vec)
# A tibble: 5 x 5
#   region   plot sum_match sum_unique    res_vec
#    <dbl> <fctr>     <int>      <int>      <dbl>
# 1      1      A        15          1 0.03225806
# 2      1      B        27          3 0.05263158
# 3      1      C         6          2 0.14285714
# 4      2      D        18          1 0.02702703
# 5      2      E         6          0 0.00000000
</code>```

DATA

```<code>set.seed(540)
df <- data.frame(region = c(rep(1, 16), rep(2, 8)),
                plot = c(rep('A', 5), rep('B', 9), rep('C', 2), rep('D', 6),rep('E', 2)),
                plantsp = sample(1:24, 24, replace = TRUE),
                lepsp = sample(1:24, 24, replace = TRUE),
                psitsp = sample(1:24, 24, replace = TRUE))
df$plantsp <- paste('plantsp', df$plantsp, sep = '_')
df$lepsp <- paste('lepsp', df$lepsp, sep = '_')
df$psitsp <- paste('psitsp', df$psitsp, sep = '_')
</code>```

Body:
I would like to conduct a very involved loop. I have multiple regions, each with hundreds of plots in my real data frame. I would like to subset by region and then plot and preform various functions on the subsets to ultimately calculate dissimilarity owed to only species that are shared.  I will preface by saying each row is representative of an interaction.

My example df:

 set.seed(540)
 df<- data.frame(region= c(rep(1, 16), rep(2,8)),
            plot= c(rep("A",5), rep("B",9), rep("C", 2), rep("D", 6),rep("E", 2)),
            plantsp= sample(1:24,24, replace= TRUE),
            lepsp= sample(1:24,24,replace= TRUE),
            psitsp= sample(1:24,24,replace= TRUE))
 df[] <- lapply(df, as.character)
 df$plantsp<-paste('plantsp', df$plantsp, sep='_')
 df$lepsp<-paste('lepsp', df$lepsp, sep='_')
 df$psitsp<-paste('psitsp', df$psitsp, sep='_')
 df$paste1<- paste(df$plantsp, df$lepsp, sep='_')
 df$paste2<- paste(df$lepsp, df$psitsp, sep='_')
 df$paste3<- paste(df$plantsp,df$lepsp, df$psitsp)

Step1: Subset df by region. Example:

region_sub <- split(df, df$region)

Step2: Subset df by plot. Example:

plot_sub <- split(region_sub[[1]], region_sub[[1]][[2]])

Step3: We will call each subset (each list component) from the step above a plot subset. In this example I will use the first subset (region1, plotA) as an example for all subsequent outputs. I will call this region1, plotA subset  plot_sub1. I want to compare plot_sub1 to the original df to make three df subsets. We will call these df_sub1, df_sub2, df_sub3. First, df_sub1 consists of matches among entries in the plantsp, lepsp columns among plot_sub1 and df. Rows with any unique entries are removed, as well as and rows where a plantsp match, but not the lepsp and visa versa. Example of df_sub1:

df_sub1<- df[c(1,2,3,4,5,22),c(1:4,6)]

Notice, only those rows with shared species remain. Further, only those rows with shared species that also interact remain. Also, I have removed unnecessary columns (e.g. psitsp, paste2, paste3) to draw your attention to the results of this step. These columns do not need to be removed for the code.

Step4: Repeat step3 for lepsp and psitsp columns to make df_sub2. Example:

df_sub2<- df[1:5,c(1:2,4,5,7)]

Step5: Repeat step3 for plantsp,lepsp and psitsp column to make df_sub3. Example:

df_sub3<- df[1:5,c(1:5,8)]

Step6: Now that all subsets are made, I want to count matching elements in the paste1 column among plot_sub1 and df_sub1 (=5). Example:
This would be stored in a vector match. The results  will be stored in the match or unique vector, accordingly.  Example:

match<- length(intersect(df_sub1$paste1,  plot_sub[[1]]$paste1))
match

I also want to count the unique elements (=1). This would be stored in a vector unique. This will be repeated for plot_sub1 and df_sub2and plot_sub1 and df_sub3. I am not sure how to count unique elements among two df so I cannot offer example code for that.

 unique<- 1

Note: Matches among plot_sub only need to be counted 1 time in the event the df_sub has repeated interactions or matches. This needs to account for presence- absence of matches, not the abundance.

In summary for this subset, the two vectors would be:

match<- c( length(intersect(df_sub1$paste1,  plot_sub[[1]]$paste1)),
length(intersect(df_sub2$paste2,  plot_sub[[1]]$paste2)),
length(intersect(df_sub3$paste3,  plot_sub[[1]]$paste3))

match

unique<-c(1,0,0)

The sum will then be totaled for each vector. Example:

sum_match<- 15
sum_unique<- 1

Step7: Lastly, these values would be input into a function:
       ((a + b)/((2*a + b)/2) - 1)   Where a= sum_match and b=sum_unique.
       The value is then input into the result vector res_vec.

Step8: This process (step3-7) would be iterated for each plot subset.

Effectively, this will calculate the dissimilarity of shared interactions among plot interactions and the corresponding metaweb (all possible interactions). This is a modification from (Poisot et al 2012) to account for tritrophic interactions.

It's quite pathetic, but to start the for loop I have:

res_vec<- NA

for (i in 1:length(unique(df$region)))
  {
      for (j in 1:length(unique(df$plot)))
     {

I really appreciate any time one is willing to help me realize the arguments within the loop. That is where it gets tricky for me.

Body:
Thans @Gregor for all the clarification you've already done in the comments!

Here is my solution using the the tidyverse.

CODE + EXPLANATION

## Load packages
library(tidyverse)

## Nest data
new_df <- df %>%
  group_by(region, plot) %>%
  nest(.key = plot_sub)

new_df

# A tibble: 5 x 3
#     region   plot         plot_sub
#      <dbl> <fctr>           <list>
#   1      1      A <tibble [5 x 3]>
#   2      1      B <tibble [9 x 3]>
#   3      1      C <tibble [2 x 3]>
#   4      2      D <tibble [6 x 3]>
#   5      2      E <tibble [2 x 3]>

The column plot_sub contains the same data as the list with the same name in your question. Think of this column as a list of dataframes.

I know write a function to create the df_sub's. This keeps our code more clean, and avoids unecessary repetition. This function will then be applied to our column plot_sub

# Function to create the df_sub
# Takes the plot_sub, original dataframe (df) and a list of columns, which should be compared
# Returns the desired df_sub with new interactions of species which are in plot_sub
# Only unique interactions are returned

create_df_sub <-  function(plot_sub, df, col_list){
  # Filter df such that it only contains species which are in plot_sub
  for (x in col_list) {
    df <- df[df[[x]] %in% plot_sub[[x]], ]
  }

  # Combine plot_sub and filtered df
  df_sub <- rbind(plot_sub[, col_list], df[, col_list])
  # Paste relevant colums together
  df_sub$paste_col <- do.call(paste, c(df_sub[, col_list], sep = '_'))
  # Exclude duplicated values
  df_sub <- df_sub[!duplicated(df_sub$paste_col), ]

  return(df_sub)
}

Now I define the columns I want to create the df_sub with and then apply the function to the plot_sub-column

col_list1 <- c('plantsp', 'lepsp')
col_list2 <- c('lepsp', 'psitsp')
col_list3 <- c('plantsp', 'lepsp', 'psitsp')

new_df <- new_df %>%
  mutate(df_sub1 = map(plot_sub, create_df_sub, df = df, col_list = col_list1),
         df_sub2 = map(plot_sub, create_df_sub, df = df, col_list = col_list2),
         df_sub3 = map(plot_sub, create_df_sub, df = df, col_list = col_list3))

map takes a vector or list as argument and applies the specified function to each element (like lapply). Compare the first elements of df_sub1 and plot_sub to see the difference.

new_df$plot_sub[[1]]
# A tibble: 5 x 3
#      plantsp    lepsp    psitsp
#        <chr>    <chr>     <chr>
# 1  plantsp_2 lepsp_19 psitsp_19
# 2 plantsp_21 lepsp_19  psitsp_4
# 3 plantsp_19  lepsp_2 psitsp_11
# 4  plantsp_9 lepsp_13 psitsp_24
# 5 plantsp_24  lepsp_9  psitsp_2

new_df$df_sub1[[1]]
# A tibble: 6 x 3
#      plantsp    lepsp           paste_col
#        <chr>    <chr>               <chr>
# 1  plantsp_2 lepsp_19  plantsp_2_lepsp_19
# 2 plantsp_21 lepsp_19 plantsp_21_lepsp_19
# 3 plantsp_19  lepsp_2  plantsp_19_lepsp_2
# 4  plantsp_9 lepsp_13  plantsp_9_lepsp_13
# 5 plantsp_24  lepsp_9  plantsp_24_lepsp_9
# 6  plantsp_9  lepsp_2   plantsp_9_lepsp_2

The new interaction is added in df_sub1.

To extract matching and unique values, I use inner_join and anti_join on the plot_sub-column and the different df_sub's

new_df <- new_df %>%
  mutate(match1 = map2(df_sub1, plot_sub, inner_join, by = col_list1),
         match2 = map2(df_sub2, plot_sub, inner_join, by = col_list2),
         match3 = map2(df_sub3, plot_sub, inner_join, by = col_list3),
         unique1 = map2(df_sub1, plot_sub, anti_join, by = col_list1),
         unique2 = map2(df_sub2, plot_sub, anti_join, by = col_list2),
         unique3 = map2(df_sub3, plot_sub, anti_join, by = col_list3))

The inner_join returns all rows, which have matching values in the columns specified in the by-argument, whereas the anti_join returns all rows of df_sub, which are not matched.
Here I use the map2-function, which takes two vectors/list and applies the specified function.

new_df$match1[[1]]
# A tibble: 5 x 4
#      plantsp    lepsp    psitsp           paste_col
#        <chr>    <chr>     <chr>               <chr>
# 1  plantsp_2 lepsp_19 psitsp_19  plantsp_2_lepsp_19
# 2 plantsp_21 lepsp_19  psitsp_4 plantsp_21_lepsp_19
# 3 plantsp_19  lepsp_2 psitsp_11  plantsp_19_lepsp_2
# 4  plantsp_9 lepsp_13 psitsp_24  plantsp_9_lepsp_13
# 5 plantsp_24  lepsp_9  psitsp_2  plantsp_24_lepsp_9

new_df$unique1[[1]]
# A tibble: 1 x 3
#     plantsp   lepsp         paste_col
#       <chr>   <chr>             <chr>
# 1 plantsp_9 lepsp_2 plantsp_9_lepsp_2

In the last step I extract the number of rows of each match and unique and sum it up. I also calculate the res_vec.

new_df <- new_df %>%
  mutate(sum_match = map_int(match1, nrow) + map_int(match2, nrow) + map_int(match3, nrow),
         sum_unique = map_int(unique1, nrow) + map_int(unique2, nrow) + map_int(unique3, nrow),
         res_vec = ((sum_match + sum_unique)/((2*sum_match + sum_unique)/2)) - 1)

Here I use map_int as my return value is an integer and I want to directly use it in a sum. Using map only would return a list which I first have to convert to a integer vector.

new_df %>% select(region, plot, sum_match, sum_unique, res_vec)
# A tibble: 5 x 5
#   region   plot sum_match sum_unique    res_vec
#    <dbl> <fctr>     <int>      <int>      <dbl>
# 1      1      A        15          1 0.03225806
# 2      1      B        27          3 0.05263158
# 3      1      C         6          2 0.14285714
# 4      2      D        18          1 0.02702703
# 5      2      E         6          0 0.00000000

DATA

set.seed(540)
df <- data.frame(region = c(rep(1, 16), rep(2, 8)),
                plot = c(rep('A', 5), rep('B', 9), rep('C', 2), rep('D', 6),rep('E', 2)),
                plantsp = sample(1:24, 24, replace = TRUE),
                lepsp = sample(1:24, 24, replace = TRUE),
                psitsp = sample(1:24, 24, replace = TRUE))
df$plantsp <- paste('plantsp', df$plantsp, sep = '_')
df$lepsp <- paste('lepsp', df$lepsp, sep = '_')
df$psitsp <- paste('psitsp', df$psitsp, sep = '_')


问:
Store JSON object in data attribute in HTML jQuery
I am storing data using the data- approach in a HTML tag like so:

```<code><td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>
</code>```

I am then retrieving the data in a callback like this:

```<code>$(this).data('imagename');
</code>```

That works fine. What I am stuck on is trying to save the object instead of just one of the properties of it. I tried to do this:

```<code><td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>
</code>```

Then I tried to access the name property like this:

```<code>var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);
</code>```

The log tells me undefined. So it seems like I can store simple strings in the data- attributes but I can't store JSON objects...

I've also tried to use this kid of syntax with no luck:

```<code><div data-foobar='{"foo":"bar"}'></div>
</code>```

Any idea on how to store an actual object in the HTML tag using the data- approach?

答:
The trick for me was to add double quotes around keys and values. If you use a PHP function like json_encode will give you a JSON encoded string and an idea how to properly encode yours.

jQuery('#elm-id').data('datakey') will return an object of the string, if the string is properly encoded as json.

As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)

Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

"{test: 1}" (test does not have double quotes around it).

"{'test': 1}" ('test' is using single quotes instead of double quotes).

"'test'" ('test' is using single quotes instead of double quotes).

".1" (a number must start with a digit; "0.1" would be valid).

"undefined" (undefined cannot be represented in a JSON string; null, however, can be).

"NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also n

Body:
I am storing data using the data- approach in a HTML tag like so:

<"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button>

I am then retrieving the data in a callback like this:

$(this).data('imagename');

That works fine. What I am stuck on is trying to save the object instead of just one of the properties of it. I tried to do this:

<button class='delete' data-image='"+results[i]+"'>Delete</button>

Then I tried to access the name property like this:

var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);

The log tells me undefined. So it seems like I can store simple strings in the data- attributes but I can't store JSON objects...

I've also tried to use this kid of syntax with no luck:

Any idea on how to store an actual object in the HTML tag using the data- approach?


问:
Python: Attempting to replace one element in a 2D list replaces all the elements at a certain point in every list.
This my code.

```<code>def spiral(length):
    half = length//2
    matrix = [[None]*length]*length
    matrix[half][half]= 1
    return matrix

spiral(5)
</code>```

Sorry if this is a silly question, I'm not very familiar with Python. When I attempt to replace a single element, I end up replacing the elements of every list.

```<code>def spiral(length):
    half = length//2
    matrix = [[None]*length]*length
    matrix[half][half]= 1
    return matrix

spiral(5)
</code>```

My current output is:

```<code>   [[None, None, 1, None, None], [None, None, 1, None, None], [None, None, 1, None, None], [None, None, 1, None, None], [None, None, 1, None, None]]
</code>```

My intended output is:

```<code>   [[None, None, None, None, None], [None, None, None, None, None], [None, None, 1, None, None], [None, None, None, None, None], [None, None, None, None, None]]
</code>```

答:
List multiplication creates several references to the same list. So when you change one, all recieve the changes.

To fix this, you can use list comprehension.

Change this:

```<code>matrix = [[None]*length]*length
</code>```

To this:

```<code>matrix = [[None]*length for _ in range(length)]
</code>```

More about list comprehensions here.

Body:
This my code.

def spiral(length):
    half = length//2
    matrix = [[None]*length]*length
    matrix[half][half]= 1
    return matrix

spiral(5)

Sorry if this is a silly question, I'm not very familiar with Python. When I attempt to replace a single element, I end up replacing the elements of every list.

def spiral(length):
    half = length//2
    matrix = [[None]*length]*length
    matrix[half][half]= 1
    return matrix

spiral(5)

My current output is:

   [[None, None, 1, None, None], [None, None, 1, None, None], [None, None, 1, None, None], [None, None, 1, None, None], [None, None, 1, None, None]]

My intended output is:

   [[None, None, None, None, None], [None, None, None, None, None], [None, None, 1, None, None], [None, None, None, None, None], [None, None, None, None, None]]

Body:
List multiplication creates several references to the same list. So when you change one, all recieve the changes.

To fix this, you can use list comprehension.

Change this:

matrix = [[None]*length]*length

To this:

matrix = [[None]*length for _ in range(length)]

More about list comprehensions here.


问:
Using php exception is still returning exception error page
I have the following controller :

```<code><?php

namespace App\Http\Controllers;

use App\WebPackage;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class WebProcessController extends Controller
{

    public function sendPayment(Request $request)
    {

       if ($request->ptitle && $request->pricetotal ){

           try {
               $product = WebPackage::findOrFail($request->ptitle);
           }
           catch (NotFoundHttpException $exception){
               die();
           }
           return $product;

       }
</code>```

Just for trying i have send a $request->ptitle with value id not in WebPackage Model.

As i know when there is error exception showing , the die() function should be work.
But still error page showing :

```<code>Sorry, the page you are looking for could not be found.

2/2
NotFoundHttpException in Handler.php line 113:
No query results for model [App\WebPackage] 20
</code>```

Is there any thing wrong i did when using 'try' and 'catch' ?

答:
The problem is that you are catching invalid exception type. findOrFail throws \Illuminate\Database\Eloquent\ModelNotFoundException if no record is found and you are catching here NotFoundHttpException and this is completely different exception.

In addition you should consider handling exceptions in Handler or set APP_DEBUG to false in .env file if you just want to hide errors from users.

Body:
I have the following controller :

<?php

namespace App\Http\Controllers;

use App\WebPackage;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class WebProcessController extends Controller
{

    public function sendPayment(Request $request)
    {

       if ($request->ptitle && $request->pricetotal ){

           try {
               $product = WebPackage::findOrFail($request->ptitle);
           }
           catch (NotFoundHttpException $exception){
               die();
           }
           return $product;

       }

Just for trying i have send a $request->ptitle with value id not in WebPackage Model.

As i know when there is error exception showing , the die() function should be work.
But still error page showing :

Sorry, the page you are looking for could not be found.

2/2
NotFoundHttpException in Handler.php line 113:
No query results for model [App\WebPackage] 20

Is there any thing wrong i did when using 'try' and 'catch' ?


问:
Table class for tables that, when too wide split all their cells into rows
I am trying to figure out what HTML / CSS I need to get a certain breaking behavior depending on how much space is available. Basically, I want to have a long line of text automatically break at certain places, and all at one), when there is no longer space for it.

Example 1:

There is enough horizontal space for the entire line of text:

There isn't enough horizontal space for the whole line (but even if there is space for the first two items, everything ends up on its own line)

Example 2: This is the same as the previous example, yet it shows that I'd like to be able to use this in a nested fashion too:

There is enough horizontal space for the entire line of text:

There is just not enough horizontal space for the entire line, so each cell goes onto its own line

There is not enough horizontal space for the second cell

I'm looking for a solution that uses only HTML and CSS (or only uses JavaScript very lightly) since my intended use-case is to use this pretty heavily in automatically generated HTML documentation pages.

I've come across examples like these, but I'm not sure I see how to make this work for subitems (and how to make this work without assigning a fixed size to each cell - I want to the cell-size to be determined by its content).

Clarfiying edit

Just bringing extra emphasis to a crucial part of the question which has been overlooked. I never want to find myself in a state where there are two items on one line and the third item on the next line. The three items should go straight from being all on one line to all on separate lines.

答:
As I mentioned in  my comment you can make use of flexbox, here is a demonstration of how you wanted.

.flex-container {
  display: flex;
  align-items: center;
  flex-direction: row;
  flex-wrap: wrap;
  flex-flow: row wrap;
  align-content: flex-end;
}

.flex-item {
  background: gray;
  color: white;
  margin: 2px;
  height: 80px;
  text-align: center;
  font-size: 30px;
  border:3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div class="flex-container">
  <div class="flex-item">Something One</div>
  <div class="flex-container" style="border:2px solid black">
     <div class="flex-item">Something 2</div>
     <div class="flex-item">Something random3</div>
     <div class="flex-item">Some 4</div>
  </div>
  <div class="flex-item">Something Five</div>
</div></code>```

Body:
As I mentioned in  my comment you can make use of flexbox, here is a demonstration of how you wanted.

.flex-container {
  display: flex;
  align-items: center;
  flex-direction: row;
  flex-wrap: wrap;
  flex-flow: row wrap;
  align-content: flex-end;
}

.flex-item {
  background: gray;
  color: white;
  margin: 2px;
  height: 80px;
  text-align: center;
  font-size: 30px;
  border:3px solid black;
}

<div>
<div class="flex-container">
  <div class="flex-item">Something One</div>
  <div class="flex-container" style="border:2px solid black">
     <div class="flex-item">Something 2</div>
     <div class="flex-item">Something random3</div>
     <div class="flex-item">Some 4</div>
  </div>
  <div class="flex-item">Something Five</div>
</div>


问:
XMLHttpRequest - Troubles with a cross domain API call
I need to do a very simple cross domain api call, and for reasons of overhead/compatibility,  dont want to use a fully-featured framework (such a jQuery), since this simple ajax request is pretty much all I need to do. I need to call do a GET request on http://bar.com from a page on http://foo.com. I cannot access the HTTP headers on foo.com however. I do not need to return data to the browser.

Currently doing the center code hereall results in (on Chrome):

```<code>XMLHttpRequest cannot load http://bar.com/api?=x.
Origin http://foo.com is not allowed by Access-Control-Allow-Origin.
http://bar.com/api?=x Failed to load resource
</code>```

Incidentally, even though this call throws an error, it comes through fine on bar.com, so another option is basically just catching that error and ignoring it(?). Somewhat unfamiliar with JS though, so not sure if this will fail on other browsers?

Came across this: http://code.google.com/p/xmlhttprequest/source/browse/trunk/source/XMLHttpRequest.js - not sure if this is completely overkill for my use (overhead is pretty critical)?

答:
Yes, this will always fail unless you have set the Access-Control-Allow-Origin HTTP header to define specific domains which are allowed to be accessed via XHR.

One way you could work around this issue is by using script injection:

```<code>function load_script(loc) {
   var s = document.createElement('script');
   s.src = loc;
   document.getElementsByTagName('head')[0].appendChild(s);
}

load_script('http://bar.com/api?=x');
</code>```

Body:
I need to do a very simple cross domain api call, and for reasons of overhead/compatibility,  dont want to use a fully-featured framework (such a jQuery), since this simple ajax request is pretty much all I need to do. I need to call do a GET request on http://bar.com from a page on http://foo.com. I cannot access the HTTP headers on foo.com however. I do not need to return data to the browser.

Currently doing the center code hereall results in (on Chrome):

XMLHttpRequest cannot load http://bar.com/api?=x.
Origin http://foo.com is not allowed by Access-Control-Allow-Origin.
http://bar.com/api?=x Failed to load resource

Incidentally, even though this call throws an error, it comes through fine on bar.com, so another option is basically just catching that error and ignoring it(?). Somewhat unfamiliar with JS though, so not sure if this will fail on other browsers?

Came across this: http://code.google.com/p/xmlhttprequest/source/browse/trunk/source/XMLHttpRequest.js - not sure if this is completely overkill for my use (overhead is pretty critical)?

Body:
Yes, this will always fail unless you have set the Access-Control-Allow-Origin HTTP header to define specific domains which are allowed to be accessed via XHR.

One way you could work around this issue is by using script injection:

function load_script(loc) {
   var s = document.createElement('script');
   s.src = loc;
   document.getElementsByTagName('head')[0].appendChild(s);
}

load_script('http://bar.com/api?=x');


问:
Functional programming in Python: find smallest odd number in list

How can I find the smallest odd number in a list of integers, if the problem statement says that I can't use for and if?

答:
you can use

```<code>ints = [2,6,8,4,6  ]

srt = sorted(ints)

while len(srt) > 0 and not srt[0] % 2:
    srt = srt[1:]

s = None
while len(srt):
    s = srt[0]
    srt=[]

print(s)
</code>```

to circumvent the rules.  You sort the list, discard any even values from front.

The resulting list is either empty or has the value at front.

The second while is only entered if the list contains elements, and the list is reset to empty (which is false and will not renter the while).

It will print "None" or the lowest not even number.

Body:
you can use

ints = [2,6,8,4,6  ]

srt = sorted(ints)

while len(srt) > 0 and not srt[0] % 2:
    srt = srt[1:]

s = None
while len(srt):
    s = srt[0]
    srt=[]

print(s)

to circumvent the rules.  You sort the list, discard any even values from front.

The resulting list is either empty or has the value at front.

The second while is only entered if the list contains elements, and the list is reset to empty (which is false and will not renter the while).

It will print "None" or the lowest not even number.


问:
With List<KeyValuePair<int, int>>, to make 1 in 4 of the values equal 1
I have a List< KeyValuePair < int,int >>. (I chose this over a dictionary since multiple keys will be the same (though consecutive keys won't be the same); and because I want to output them in the order input).

All the keys are equal to a randNum between 1-5 (inclusive). (The keys don't really matter in relation to my problem).

All the values are the default, 0.

I want to change 1 in 4 of the values to equal 1 (the others still equal 0). The position of the value=1 in each range of 4 is randomly chosen.

An example output of what I want, printing the KVPs in the list:

```<code>[5,0]
[3,1]
[2,0]
[5,0]
[1,0]
[4,0]
[2,0]
[3,1]
[1,0]
[5,0]
[4,1]
[2,0]
</code>```

So, in groups of 4, the values would be: 0100 | 0001 | 0010.

Here's what I've tried to do so far:
(the sequence is already set up with all the keys)

```<code>List<KeyValuePair<int,int>> sequence = new List<KeyValuePair<int,int>>();

// Populate keys in sequence with random numbers 1-5
// ...

public static void SetSequenceValues()
{
    Random randNum = new Random();
    bool allValuesSet = false;

    // count is the max (non-inclusive) in each range of 4
    // i.e. first loop is 1-4
    // then count += 4
    // second loop is 5-8, etc.
    int count = 5;

    while (allValuesSet == false)
    {
        int randPos = randNum.Next(count - 4, count);

        // If changing the first key in the range,
        // the desired key index = count-4
        if (randPos == count - 4)
        {
            var oldKVP = sequence[count - 4];
            sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count -3)
        {
            var oldKVP = sequence[count - 3];
            sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 2)
        {
            var oldKVP = sequence[count - 2];
            sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 1)
        {
            var oldKVP = sequence[count - 1];
            sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }

        // Increase count by 4, so on the next loop, e.g. the range looked at will be 4-8 (not including 8, i.e. 4-7)
        count += 4;

        if (count >= sequence.Count)
            allValuesSet = true;
    }
}
</code>```

Currently, the output is kind of close-ish, but, occasionally there'll be a couple of 1s in each group. Also, I think it may be using groups of 5 rather than 4? Though that doesn't seem to entirely be it either.

答:
This would be much easier if you used a Dictionary<int, List<int>>. You can just loop through each key and assign a random entry in the collection to 1:

```<code>var data = new Dictionary<int, List<int>>();
data.Add(1, new List<int> { 0, 0, 0, 0, 0 });
// continue filling the dictionary...

var random = new Random();
foreach (var entry in data)
{
    entry.Value[random.Next(0, entry.Value.Count - 1)] = 1;
}

// print the results

foreach (var entry in data)
{
    Console.WriteLine("{0} => {1}", entry.Key, entry.Value.Join(", "));
}
</code>```

Body:
I have a List< KeyValuePair < int,int >>. (I chose this over a dictionary since multiple keys will be the same (though consecutive keys won't be the same); and because I want to output them in the order input).

All the keys are equal to a randNum between 1-5 (inclusive). (The keys don't really matter in relation to my problem).

All the values are the default, 0.

I want to change 1 in 4 of the values to equal 1 (the others still equal 0). The position of the value=1 in each range of 4 is randomly chosen.

An example output of what I want, printing the KVPs in the list:

[5,0]
[3,1]
[2,0]
[5,0]
[1,0]
[4,0]
[2,0]
[3,1]
[1,0]
[5,0]
[4,1]
[2,0]

So, in groups of 4, the values would be: 0100 | 0001 | 0010.

Here's what I've tried to do so far:
(the sequence is already set up with all the keys)

List<KeyValuePair<int,int>> sequence = new List<KeyValuePair<int,int>>();

// Populate keys in sequence with random numbers 1-5
// ...

public static void SetSequenceValues()
{
    Random randNum = new Random();
    bool allValuesSet = false;

    // count is the max (non-inclusive) in each range of 4
    // i.e. first loop is 1-4
    // then count += 4
    // second loop is 5-8, etc.
    int count = 5;

    while (allValuesSet == false)
    {
        int randPos = randNum.Next(count - 4, count);

        // If changing the first key in the range,
        // the desired key index = count-4
        if (randPos == count - 4)
        {
            var oldKVP = sequence[count - 4];
            sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count -3)
        {
            var oldKVP = sequence[count - 3];
            sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 2)
        {
            var oldKVP = sequence[count - 2];
            sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 1)
        {
            var oldKVP = sequence[count - 1];
            sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }

        // Increase count by 4, so on the next loop, e.g. the range looked at will be 4-8 (not including 8, i.e. 4-7)
        count += 4;

        if (count >= sequence.Count)
            allValuesSet = true;
    }
}

Currently, the output is kind of close-ish, but, occasionally there'll be a couple of 1s in each group. Also, I think it may be using groups of 5 rather than 4? Though that doesn't seem to entirely be it either.

Body:
This would be much easier if you used a Dictionary<int, List<int>>. You can just loop through each key and assign a random entry in the collection to 1:

var data = new Dictionary<int, List<int>>();
data.Add(1, new List<int> { 0, 0, 0, 0, 0 });
// continue filling the dictionary...

var random = new Random();
foreach (var entry in data)
{
    entry.Value[random.Next(0, entry.Value.Count - 1)] = 1;
}

// print the results

foreach (var entry in data)
{
    Console.WriteLine("{0} => {1}", entry.Key, entry.Value.Join(", "));
}