问:
Why jQuery does not work in nested Ajax functions?
While calling nested Ajax, which innermost ajax doesn't work. As seen in the following example, I 'm calling getInnerResp into getResult.

Normally, when I debug with firebug is works interestingly. I think it behaves as async false but I setted async property as false didn't work again. Furthermore, I tried to get result set using callback function in getInnerResp function. Unfortunately I didn't succeed in any way. Also ftbl variable in getResult function returns null. getInnerResp only returns followed result;

Result

```<code><tr><td colspan='3'></td></tr><tr><td colspan='3'></td></tr><tr><td colspan='3'></td></tr><tr><td colspan='3'></td></tr>
</code>```

Javascript

```<code>function getResult(year){

    var visible  = true;
    var table    = $(".tbl"), tbody = $(".result").find("tbody"), ftbl = "";

    table.find("tbody>tr").each(function(){
        var data = {
            course : $(this).find(".course").val(),
            year   : year,
            prog   : $(this).find(".program").val()
        }

        if(year.length < 1){
          alert("Year field can not be empty!!");
          visible = false;
          return false;
        }

        $.ajax({
            url : "result.php",
            method : "GET",
            data : data,
            contentType: "application/json; charset=utf-8",
            traditional : true,
            success : function(d){
                tbody.append("<tr><td>" + course + "</td><td>" + d.enrolledStudent + "</td><td>" + d.failedStudent + "</td>");
                if(visible){
                    ftbl += getInnerResp(course, year);
                    console.log("inner" + ftbl);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown){
                alert("Javascript runtime error: " + textStatus);
            }
        });
    });

    if(visible){
        tbody.append(ftbl);
    }
}

function getInnerResp(course, year){

    var tbl = "";

    var data = {
        course : course,
        year   : year
    }

    for(var i = 0; i < 5; i++){
        tbl += "<tr><td colspan='3'></td></tr>";
    }

    $.ajax({
        url : "course.php",
        method : "GET",
        data : data,
        contentType: "application/json; charset=utf-8",
        success : function(json){
            $.each(json, function(i, val){
                tbl += "<tr><td>" + course + "</td><td colspan='2'>" + val + "</td></tr>";
            });
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert(textStatus);
        }
    });

    return tbl;
}
</code>```

答:
This is your issue:

```<code>ftbl += getInnerResp(course, year);
</code>```

you try to assign a value generated in future (async) to a local variable.

Try to move the task in the inner function, like:

```<code>function getResult(year){

        var visible  = true;
        var table    = $(".tbl"), tbody = $(".result").find("tbody"), ftbl = "";

        table.find("tbody>tr").each(function(){
            var data = {
                course : $(this).find(".course").val(),
                year   : year,
                prog   : $(this).find(".program").val()
            }

            if(year.length < 1){
                alert("Year field can not be empty!!");
                visible = false;
                return false;
            }

            $.ajax({
                url : "result.php",
                method : "GET",
                data : data,
                contentType: "application/json; charset=utf-8",
                traditional : true,
                success : function(d){
                    tbody.append("<tr><td>" + course + "</td><td>" + d.enrolledStudent + "</td><td>" + d.failedStudent + "</td>");
                    if(visible){
                        //
                        // do the remaing in the inner task....
                        //
                        getInnerResp(course, year, tbody);
                    }
                },
                error : function(XMLHttpRequest, textStatus, errorThrown){
                    alert("Javascript runtime error: " + textStatus);
                }
            });
        });

    }

    function getInnerResp(course, year, tbody){

        var tbl = "";

        var data = {
            course : course,
            year   : year
        }

        for(var i = 0; i < 5; i++){
            tbl += "<tr><td colspan='3'></td></tr>";
        }

        $.ajax({
            url : "course.php",
            method : "GET",
            data : data,
            contentType: "application/json; charset=utf-8",
            success : function(json){
                $.each(json, function(i, val){
                    tbl += "<tr><td>" + course + "</td><td colspan='2'>" + val + "</td></tr>";
                });
                tbody.append(tbl);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown){
                alert(textStatus);
            }
        });

        console.log("inner" + tbl);;
    }
</code>```

Body:
While calling nested Ajax, which innermost ajax doesn't work. As seen in the following example, I 'm calling getInnerResp into getResult.

Normally, when I debug with firebug is works interestingly. I think it behaves as async false but I setted async property as false didn't work again. Furthermore, I tried to get result set using callback function in getInnerResp function. Unfortunately I didn't succeed in any way. Also ftbl variable in getResult function returns null. getInnerResp only returns followed result;

Result

Javascript

function getResult(year){

    var visible  = true;
    var table    = $(".tbl"), tbody = $(".result").find("tbody"), ftbl = "";

    table.find("tbody>tr").each(function(){
        var data = {
            course : $(this).find(".course").val(),
            year   : year,
            prog   : $(this).find(".program").val()
        }

        if(year.length < 1){
          alert("Year field can not be empty!!");
          visible = false;
          return false;
        }

        $.ajax({
            url : "result.php",
            method : "GET",
            data : data,
            contentType: "application/json; charset=utf-8",
            traditional : true,
            success : function(d){
                tbody.append("
" + course + "	" + d.enrolledStudent + "	" + d.failedStudent + "	");
                if(visible){
                    ftbl += getInnerResp(course, year);
                    console.log("inner" + ftbl);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown){
                alert("Javascript runtime error: " + textStatus);
            }
        });
    });

    if(visible){
        tbody.append(ftbl);
    }
}

function getInnerResp(course, year){

    var tbl = "";

    var data = {
        course : course,
        year   : year
    }

    for(var i = 0; i < 5; i++){
        tbl += "

";
    }

    $.ajax({
        url : "course.php",
        method : "GET",
        data : data,
        contentType: "application/json; charset=utf-8",
        success : function(json){
            $.each(json, function(i, val){
                tbl += "
" + course + "	" + val + "
";
            });
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert(textStatus);
        }
    });

    return tbl;
}

Body:
This is your issue:

ftbl += getInnerResp(course, year);

you try to assign a value generated in future (async) to a local variable.

Try to move the task in the inner function, like:

function getResult(year){

        var visible  = true;
        var table    = $(".tbl"), tbody = $(".result").find("tbody"), ftbl = "";

        table.find("tbody>tr").each(function(){
            var data = {
                course : $(this).find(".course").val(),
                year   : year,
                prog   : $(this).find(".program").val()
            }

            if(year.length < 1){
                alert("Year field can not be empty!!");
                visible = false;
                return false;
            }

            $.ajax({
                url : "result.php",
                method : "GET",
                data : data,
                contentType: "application/json; charset=utf-8",
                traditional : true,
                success : function(d){
                    tbody.append("<tr><td>" + course + "</td><td>" + d.enrolledStudent + "</td><td>" + d.failedStudent + "</td>");
                    if(visible){
                        //
                        // do the remaing in the inner task....
                        //
                        getInnerResp(course, year, tbody);
                    }
                },
                error : function(XMLHttpRequest, textStatus, errorThrown){
                    alert("Javascript runtime error: " + textStatus);
                }
            });
        });

    }

    function getInnerResp(course, year, tbody){

        var tbl = "";

        var data = {
            course : course,
            year   : year
        }

        for(var i = 0; i < 5; i++){
            tbl += "<tr><td colspan='3'></td></tr>";
        }

        $.ajax({
            url : "course.php",
            method : "GET",
            data : data,
            contentType: "application/json; charset=utf-8",
            success : function(json){
                $.each(json, function(i, val){
                    tbl += "<tr><td>" + course + "</td><td colspan='2'>" + val + "</td></tr>";
                });
                tbody.append(tbl);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown){
                alert(textStatus);
            }
        });

        console.log("inner" + tbl);;
    }


来源: stackexchange

问:
How to move angular code from my local to github?
When i try to commit it displays the following,

On branch gh-pages
Untracked files:
        node_modules/max-buffer-exceeded-error/

nothing added to commit but untracked files present

答:
I think you added node_modules folder. Run

```<code>git rm node_modules
</code>```

to remove them from your repository.

After that operation, add node_modules to the .gitignore file.

Finally commit and push.

ContentLicense: CC BY-SA 3.0

Body:
I think you added node_modules folder. Run

git rm node_modules

to remove them from your repository.

After that operation, add node_modules to the .gitignore file.

Finally commit and push.


问:
Pass Image from Database to View, Null Reference Exception Error
After user click on search button, I want to show a list with info fields, all is fine except one for Image. I have a ActionResult method that takes an Id from the view and show image to user on click event.

The problem so far is that in controller even if 'item.Image.ImageId' has an Id value, the left part (Model that I send to the view), throws Null Reference Exception so I can't pass Image Id to the View with 'href = "~/Process/..."'

Screenshoot Error: Object reference not set to an instance of an object.

My controller:

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(SearchModel FormModel)
    {
        int districtNo = Convert.ToInt32(FormModel.DistrictNo);
        List<SearchModel> ResultsList = new List<SearchModel>();

        IQueryable<LetterInfo> DbQueries = // Get result from db

        foreach (var item in DbQueries.ToList())
        {
            FormModel.FirstName = item.FirstName;
            FormModel.LastName = item.LastName;
            ...
            FormModel.Image.ImageId = item.Image.ImageId;
// FromModel.Image.ImageId - null reference exception
            ResultsList.Add(FormModel);

        }
        ViewBag.ResultsToView = ResultsList;
    }
        return View(new SearchModel());
    }
</code>```

SearchModel class:

```<code>public class SearchModel
{
    .
    .
    .
    public Image Image { get; set; }
}
</code>```

LetterInfo class:

```<code> public class LetterInfo
 {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int LetterId { get; set; }
    .
    .
    .
    public virtual Image Image { get; set; }
 }
</code>```

Method that returns a image file:

```<code>    public ActionResult ViewImage(int Id)
    {
        var img = db.Images.First(a => a.ImageId == Id);
        var stream = new MemoryStream(img.FileContents);

        var lname = "letter" + Path.GetExtension(img.FileName)?.ToLower();

        Response.AppendHeader("Content-Disposition", $"inline; filename={lname}");
        return File(stream, Helpers.GetMimeType(img.FileName));
    }
</code>```

View:

```<code>@model SearchModel

@section scripts{
  <script type="text/javascript">
    var win;

    $('#openImage').click(function (event) {
        event.preventDefault();
        win = window.open(this.href, 'child', 'resizable=1');
        return false;
    });
  </script>
}
...
@foreach (var item in ModelList){
  <li></li>
  ...
  <li class="list-group-item">
    <a href="~/Process/ViewImage/@item.Image.ImageId" id="openImage">
<!-- On click open image file -->

      <span>Click to see image</span>
    </a>
  </li>
}
</code>```

答: Either FormModel.Image or item.Image is null. A NullReferenceException is a runtime error that occurs when you access a member that a particular object should have based on its type, but actually doesn't have because the instance is null, and null does not have a property like ImageId, for example.

Body:
After user click on search button, I want to show a list with info fields, all is fine except one for Image. I have a ActionResult method that takes an Id from the view and show image to user on click event.

The problem so far is that in controller even if 'item.Image.ImageId' has an Id value, the left part (Model that I send to the view), throws Null Reference Exception so I can't pass Image Id to the View with 'href = "~/Process/..."'

Screenshoot Error: Object reference not set to an instance of an object.

My controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(SearchModel FormModel)
    {
        int districtNo = Convert.ToInt32(FormModel.DistrictNo);
        List<SearchModel> ResultsList = new List<SearchModel>();

        IQueryable<LetterInfo> DbQueries = // Get result from db

        foreach (var item in DbQueries.ToList())
        {
            FormModel.FirstName = item.FirstName;
            FormModel.LastName = item.LastName;
            ...
            FormModel.Image.ImageId = item.Image.ImageId;
// FromModel.Image.ImageId - null reference exception
            ResultsList.Add(FormModel);

        }
        ViewBag.ResultsToView = ResultsList;
    }
        return View(new SearchModel());
    }

SearchModel class:

public class SearchModel
{
    .
    .
    .
    public Image Image { get; set; }
}

LetterInfo class:

 public class LetterInfo
 {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int LetterId { get; set; }
    .
    .
    .
    public virtual Image Image { get; set; }
 }

Method that returns a image file:

    public ActionResult ViewImage(int Id)
    {
        var img = db.Images.First(a => a.ImageId == Id);
        var stream = new MemoryStream(img.FileContents);

        var lname = "letter" + Path.GetExtension(img.FileName)?.ToLower();

        Response.AppendHeader("Content-Disposition", $"inline; filename={lname}");
        return File(stream, Helpers.GetMimeType(img.FileName));
    }

View:

@model SearchModel

@section scripts{

}
...
@foreach (var item in ModelList){

  ...

      Click to see image

}


问:
a large scale java project solution
I would like to start up a project from scratch. I am a java developer for years. I did even write my own mvc framework some time ago for fun. Now I am working in a company using in-house framework - which i think is a total loss of time and money. I respect the idea of  teaming up with different skilled people for a large scale project. The separation of the project is very important; Graphics guys, front end developers, software architectures, software developers, database experts, etc. I cannot risk to use a scripting language like php.

Lately, I am researching java technologies for a large scale project in every aspects. What I mean by that, for the front layer I come across with very famous technologies.

Spring

MyFaces

Tapestry

Google Web Toolkit

Cocoon

Velocity

Every one of them states that it is the simplest, the fastest, the latest technology and whatsoever. Of course only one them can hold the truth. I need a front end technology for fast implementation for ajax, customer/administrator security, themes, templates, internationalization, caching static pages, clustering and a support of ejb. It should also have IDE support, community support, rich documentation and online tutorials. Still I have no experience of those frameworks which to choose from. Maybe there is even better one? And most importantly, I cannot risk to start up on a technology which has development limitations. Is there any suggestions for this layer?

For the business layer, I am sure of EJB and JPA. I do even considering a web service for facade of this layer for interoperability purposes for future extensions. However, I have no idea about securing that layer (it could be applied on its web service level) which is still a problem for me. For the application server I am considering GlassFish.

And for the last question is what IDE should be picked for development. Regarding all the technologies, which are going to be used, an IDE should help me in every step, either doing the configuration for me or helping me configuring with its ready wizards. I suppose the IDE will have proper plugins for to be used technologies.

I know that I want too much, however I have a hope for a combination of technologies which will help me saving time and money in my future plans.

I ll be really glad to hear your responses, experiences for a bigger picture.

edited: There is no ultimate answer, I know that. I am just taking advice. Any answer is appreciated.

答:
Well, I'm going to go out on a limb and give concrete recommendations, since I think the question can be answered.

I'll simply recommend my stack.

My stack is Stripes for the front end, and Glassfish/Java EE 5 on the back end.

Stripes is a simple Action (or MVC, whatever floats your boat), that has a small, but robust and vocal community. It has tight integration with JPA (through a plug in), a very good, and current, printer book on the topic as well as excellent reference documentation. It's main rendering tech is JSP with JSP Tags and EL.

It is not a component framework like JSF/MyFaces, so it's implementation is simpler, and it's lifecycle is simpler. It works very well with Ajax.

The key factor around Stripes, since it's based on the HTTP request cycle is that it does most of the grunge work for you, yet is very lightweight. It's easy to pick up and understand. Creating a basic Stripes app is a couple lines in the web.xml and two jars (one of which is log4j). If you can think in HTTP, then Stripes is a good fit for you.

On the back end I would simply stick with EJB and GlassFish. Java EE 6 and GFv3 are out have been out for sometime. It offers a lot of new features over Java EE 5, and GlassFish offers most any web service tech you would like to use. Java EE 6 and Spring are pretty much equal on a bullet point by bullet point basis, and since you were looking at GF, you may as well use EJB since it's there and integrated in the box. If you were using Tomcat, then Spring might be a good choice.

And, that's it. That's all you need (I dunno what you wanted Velocity for, you can add that trivially if you like, but I wouldn't use it for pages, personally, modern JSP is much better IMHO).

Glassfish will secure your web services, you can use Java EE security with your web apps, you can share logic between the back end EJBs and your web app and web services. It all works out of the box with 15 minutes of configuration to get Stripes running.

I use NetBeans, but all of the other IDEs work as well. NetBeans is nice because it come integrated with Glassfish. One less thing to configure. Download it, fire it up, and it works.

There's a Stripes plugin for NetBeans, that I don't use. I don't see a need. Once you add your few lines to your web.xml that you cut and paste from the web site, you never see Stripes again. From there, it's all simple annotations.

Unless you have a crushing need for all of the complexity and learning curve of a component framework, it doesn't get any better than Stripes, and GF w/Java EE 6 has everything you need in the box.

So, in summary: Stripes distro from www.stripesframework.org, NetBeans download from netbeans.org, and stripersist from stripes-stuff.sourceforge.net. It's a rock solid foundation that will go wherever you want to take it.

Come on by to the Stripes IRC on freenode at #stripes, and we'll answer any question you have (or hit the mailing list).

ContentLicense: CC BY-SA 2.5

Title: a large scale java project solution


问:
sort an array with another array which has sorted keys
How to sort an 1st array with 2nd array which has sorted keys in 2nd array without using any loop.

1st Array.

```<code>$chunk = array(
                [0] => Array
                    (
                        [id] => 212
                        [order] => 1
                        [title] => fdfdfdfdf
                    )

                [1] => Array
                    (
                        [id] => 5
                        [order] => 2
                        [title] =>
                    )

                [2] => Array
                    (
                        [id] => 781
                        [order] => 3
                        [title] =>
                    )
            )
</code>```

2nd array with sorted keys of 1st array.

```<code>$sort = array
    (
        [2] => 2
        [0] => 0
        [1] => 1
    )
</code>```

答:
You could use array_map for that:

```<code>$arr = array_map(function($val) use($chunk){
    return $chunk[$val];
}, $sort);
</code>```

This is the output:

```<code>Array
(
    [2] => Array
        (
            [id] => 781
            [order] => 3
            [title] =>
        )

    [0] => Array
        (
            [id] => 212
            [order] => 1
            [title] => fdfdfdfdf
        )

    [1] => Array
        (
            [id] => 5
            [order] => 2
            [title] =>
        )

)
</code>```

Now, if you want the keys to be 0,1,2..., you can use array_values, after mapping:

```<code>$arr = array_values($arr);
</code>```

And the output:

```<code>Array
(
    [0] => Array
        (
            [id] => 781
            [order] => 3
            [title] =>
        )

    [1] => Array
        (
            [id] => 212
            [order] => 1
            [title] => fdfdfdfdf
        )

    [2] => Array
        (
            [id] => 5
            [order] => 2
            [title] =>
        )

)
</code>```

Body:
How to sort an 1st array with 2nd array which has sorted keys in 2nd array without using any loop.

1st Array.

$chunk = array(
                [0] => Array
                    (
                        [id] => 212
                        [order] => 1
                        [title] => fdfdfdfdf
                    )

                [1] => Array
                    (
                        [id] => 5
                        [order] => 2
                        [title] =>
                    )

                [2] => Array
                    (
                        [id] => 781
                        [order] => 3
                        [title] =>
                    )
            )

2nd array with sorted keys of 1st array.

$sort = array
    (
        [2] => 2
        [0] => 0
        [1] => 1
    )

Body:
You could use array_map for that:

$arr = array_map(function($val) use($chunk){
    return $chunk[$val];
}, $sort);

This is the output:

Array
(
    [2] => Array
        (
            [id] => 781
            [order] => 3
            [title] =>
        )

    [0] => Array
        (
            [id] => 212
            [order] => 1
            [title] => fdfdfdfdf
        )

    [1] => Array
        (
            [id] => 5
            [order] => 2
            [title] =>
        )

)

Now, if you want the keys to be 0,1,2..., you can use array_values, after mapping:

$arr = array_values($arr);

And the output:

Array
(
    [0] => Array
        (
            [id] => 781
            [order] => 3
            [title] =>
        )

    [1] => Array
        (
            [id] => 212
            [order] => 1
            [title] => fdfdfdfdf
        )

    [2] => Array
        (
            [id] => 5
            [order] => 2
            [title] =>
        )

)


问:
How to read a file to a list of lists?
I want to create a list of lists from a file that contains the following data:

```<code>101 Rahul
102 Julie
103 Helena
104 Kally
</code>```

CODE

```<code>lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)
</code>```

Output I Want

```<code>[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]
</code>```

Output I m getting

```<code>['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']
</code>```

答:
You can split by lines:

```<code>lis = []

with open("student_details.txt" , "r+") as f:
    for line in f:
       data = line.split()
       lis.append(data)
print(lis)
</code>```

Result :

```<code>[['101', 'Rahul'], ['102', 'Julie'], ['103', 'Helena'], ['104', 'Kally']]
</code>```

Or in a more compact way :

```<code>with open("student_details.txt" , "r+") as f:
    lis = [line.split() for line in f]
print(lis)
</code>```

Result :

```<code>[['101', 'Rahul'], ['102', 'Julie'], ['103', 'Helena'], ['104', 'Kally']]
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to read a file to a list of lists?

Body:
I want to create a list of lists from a file that contains the following data:

101 Rahul
102 Julie
103 Helena
104 Kally

CODE

lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

Output I Want

[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]

Output I m getting

['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']

Body:
You can split by lines:

lis = []

with open("student_details.txt" , "r+") as f:
    for line in f:
       data = line.split()
       lis.append(data)
print(lis)

Result :

[['101', 'Rahul'], ['102', 'Julie'], ['103', 'Helena'], ['104', 'Kally']]

Or in a more compact way :

with open("student_details.txt" , "r+") as f:
    lis = [line.split() for line in f]
print(lis)

Result :

[['101', 'Rahul'], ['102', 'Julie'], ['103', 'Helena'], ['104', 'Kally']]


问:
React and Multiple form fields
I was reading documentation on "onChange" and I am curious as to what I would do if my forum has multiple fields like select boxes, checkboxes, text areas and inputs? Do I just do something like:

```<code> getInitialState: function() {
    return {textArea: 'Hello!', input: 'World', ...};
  },
</code>```

to the initial state and then the same concept for handling that change of that field?

答:
Some of my friends were discussing this today. The solution proposed by @JunleLi  is great but it breaks Purerender which forces a re-render of all subcomponents every time a character it typed into one of the fields as it is regenerating the function.

Here is an example of our solution. We're still not sure if we're completely happy with it but it ultimately creates the function once and caches it.

I'd love to hear any feedback.

```<code>handleChange(key) {
    if(!this.changeHandlers) this.changeHandlers = {};
    return this.changeHandlers[key] || (this.changeHandlers[key] = event => this.setState({[key]: event.target.value}));
},

render() {
    return (
        <div>
          <input type="text" value={this.state.familyName} onChange={this.handleChange("familyName")} />
          ```{JSON.stringify(this.state, null, 4)}```
        </div>
    );
}
</code>```

Title: React and Multiple form fields

Body:
I was reading documentation on "onChange" and I am curious as to what I would do if my forum has multiple fields like select boxes, checkboxes, text areas and inputs? Do I just do something like:

 getInitialState: function() {
    return {textArea: 'Hello!', input: 'World', ...};
  },

to the initial state and then the same concept for handling that change of that field?

Body:
Some of my friends were discussing this today. The solution proposed by @JunleLi  is great but it breaks Purerender which forces a re-render of all subcomponents every time a character it typed into one of the fields as it is regenerating the function.

Here is an example of our solution. We're still not sure if we're completely happy with it but it ultimately creates the function once and caches it.

I'd love to hear any feedback.

handleChange(key) {
    if(!this.changeHandlers) this.changeHandlers = {};
    return this.changeHandlers[key] || (this.changeHandlers[key] = event => this.setState({[key]: event.target.value}));
},

render() {
    return (
        <div>
          <input type="text" value={this.state.familyName} onChange={this.handleChange("familyName")} />
          <pre>{JSON.stringify(this.state, null, 4)}</pre>
        </div>
    );
}


问:
Get vendor name of SCSI
How can I get the vendor name of SCSI device on linux & c? </p>

答:
You can use libudev to find SCSI devices and read the vendor attribute (untested):</p>

```<code>struct udev *context = udev_new();
struct udev_enumerate *enumerator = udev_enumerate_new(context);
udev_enumerate_add_match_subsystem(enumerator, "scsi");
udev_enumerate_scan_devices(enumerator);
struct udev_list_entry *scsi_devices = udev_enumerate_get_list_entry(enumerator);
struct udev_list_entry *current = 0;
udev_list_entry_foreach(current, scsi_devices) {
    struct udev_device *device = udev_device_new_from_syspath(
            context, udev_list_entry_get_name(current));
    const char *vendor = udev_device_get_sysattr_value(device, "vendor");
    printf("%s\n", vendor);
}
</code>```

Title: Get vendor name of SCSI

Body:
You can use libudev to find SCSI devices and read the vendor attribute (untested):

struct udev *context = udev_new();
struct udev_enumerate *enumerator = udev_enumerate_new(context);
udev_enumerate_add_match_subsystem(enumerator, "scsi");
udev_enumerate_scan_devices(enumerator);
struct udev_list_entry *scsi_devices = udev_enumerate_get_list_entry(enumerator);
struct udev_list_entry *current = 0;
udev_list_entry_foreach(current, scsi_devices) {
    struct udev_device *device = udev_device_new_from_syspath(
            context, udev_list_entry_get_name(current));
    const char *vendor = udev_device_get_sysattr_value(device, "vendor");
    printf("%s\n", vendor);
}


问:
Alternative way to code without loops in R and reduce looping time
I have 2 datasets with text data. dataset1: clusters11 and dataset2: transactns11. I am using For loop in the code and it takes more time to process the data. So can anyone suggest how I can reduce the time taken. Please go through the below sample datasets and the code I am using.

```<code>dataset1: clusters11
cluster_id  clusters
1   A,B,C
2   A,B
3   B,C
4   C,D,E
5   B,C,D
6   D,E,F
7   A,D,F
8   B,G,H
9   B,C,F
10  G,H,M
11  A,H,N
12  B,C,M

dataset2: transactns11
unique_id   skills
221 A,B,C
223 A,B
224 B,C
225 C,D,E,F
226 B,C,D,M
227 D,E,F,A
228 A,D,F
229 B,G,H
230 B,C,F,A
231 G,H,M
232 A,H,N
233 B,C,M
234 A,B,C
235 A,B
236 B,C
237 C,D,E
238 B,C,D
239 D,E,F
</code>```

I want to have my output:out_df like this( which ever cluster in clusters11 file matches 100% with the skills in transactns11 should appear as comma separate by cluster_id, with the column name matching_values in the output.

```<code>unique_id   skills  matching_values
221 A,B,C   1,2,3
223 A,B 2
224 B,C 3
225 C,D,E,F 4,6
226 B,C,D,M 3,5,12
227 D,E,F,A 6,7
228 A,D,F   7
229 B,G,H   8
230 B,C,F,A 1,2,3,9
231 G,H,M   10
232 A,H,N   11
233 B,C,M   3,12
234 A,B,C   1,2,3
235 A,B 2
236 B,C 3
237 C,D,E   4
238 B,C,D   3,5
239 D,E,F   6
</code>```

For this I have code and it is working fine with me

```<code>  out_df <- data.frame(matrix(0, ncol = 3, nrow = nrow(transactns11)))
  colnames(out_df) <- c("unique_id", "skills", "matching_values")

  transactns11$skills=as.character(transactns11$skills)
  clusters11$clusters=as.character(clusters11$clusters)

  for(n in 1:nrow(transactns11)) {

    trans1 <- strsplit(transactns11$skills[n], ",")
    trans1
    transvect <- unlist(trans1)
    transvect

    matching_clusters <- c("")
    out_df$unique_id[n] <- as.character(transactns11$unique_id[n])
    out_df$skills[n] <- transactns11$skills[n]

    for(i in 1:nrow(clusters11)) {

      cluster1 <- strsplit(clusters11$clusters[i],",")
      cluster1
      clustervect <- unlist(cluster1)
      clustervect

      if(length(intersect(transvect,clustervect)) == length(clustervect)) {
        matching_clusters <- paste(matching_clusters, clusters11$cluster_id[i], sep = ",")
      }
    }
    matching_clusters <- substring(matching_clusters,2)
    out_df$matching_values[n] <- matching_clusters
  }
</code>```

Problem is that, the code takes more time when the recods of the 2 files are more like 10000 or 20000( time taken will be 15 to 20 hrs).
Can any one please suggest how I can avoid this loops or any other method I can follow to improve the code and reduce the huge time taken to process.
Thanks in Advance.
Regards,
hari

答:
I don't konw how fast this would be, but let's try:

First, store cluster names in codes

```<code>codes<-LETTERS[1:14]
</code>```

Then make Boolean representation of clusters1$clusters and transactns1$skills

```<code>clusters2<-sapply(codes,grepl,x=clusters1$clusters)
transactns2<-sapply(codes,grepl,x=transactns1$skills)
</code>```

Write a function that tests if given cluster is appropriate for given transactn:

```<code>is_ok<-function(clus, tran) !any(!(tran) & clus)
</code>```

e.g.

```<code>is_ok(clusters2[1,], transactns2[2,])
[1] FALSE
</code>```

This tells you that cluster 1 is not suitable for second transactn.

Then write a function that check all the clusters for given transactn. I use magrittr package to get access to %>% operator.

```<code>library(magrittr)
matching_values<-function(tran) apply(clusters2,1,is_ok,tran=tran) %>% which
%>% paste(collapse=',')
</code>```

Fast check:

```<code>matching_values(transactns2[5,])
[1] "3,5,12"
</code>```

Finally, apply the last function to all the transactns:

```<code>apply(transactns2,1,matching_values)
[1] "1,2,3"   "2"       "3"       "4,6"     "3,5,12"  "6,7"     "7"       "8"       "1,2,3,9"
[10] "10"      "11"      "3,12"    "1,2,3"   "2"       "3"       "4"       "3,5"     "6"
</code>```

Body:
I have 2 datasets with text data. dataset1: clusters11 and dataset2: transactns11. I am using For loop in the code and it takes more time to process the data. So can anyone suggest how I can reduce the time taken. Please go through the below sample datasets and the code I am using.

dataset1: clusters11
cluster_id  clusters
1   A,B,C
2   A,B
3   B,C
4   C,D,E
5   B,C,D
6   D,E,F
7   A,D,F
8   B,G,H
9   B,C,F
10  G,H,M
11  A,H,N
12  B,C,M

dataset2: transactns11
unique_id   skills
221 A,B,C
223 A,B
224 B,C
225 C,D,E,F
226 B,C,D,M
227 D,E,F,A
228 A,D,F
229 B,G,H
230 B,C,F,A
231 G,H,M
232 A,H,N
233 B,C,M
234 A,B,C
235 A,B
236 B,C
237 C,D,E
238 B,C,D
239 D,E,F

I want to have my output:out_df like this( which ever cluster in clusters11 file matches 100% with the skills in transactns11 should appear as comma separate by cluster_id, with the column name matching_values in the output.

unique_id   skills  matching_values
221 A,B,C   1,2,3
223 A,B 2
224 B,C 3
225 C,D,E,F 4,6
226 B,C,D,M 3,5,12
227 D,E,F,A 6,7
228 A,D,F   7
229 B,G,H   8
230 B,C,F,A 1,2,3,9
231 G,H,M   10
232 A,H,N   11
233 B,C,M   3,12
234 A,B,C   1,2,3
235 A,B 2
236 B,C 3
237 C,D,E   4
238 B,C,D   3,5
239 D,E,F   6

For this I have code and it is working fine with me

  out_df <- data.frame(matrix(0, ncol = 3, nrow = nrow(transactns11)))
  colnames(out_df) <- c("unique_id", "skills", "matching_values")

  transactns11$skills=as.character(transactns11$skills)
  clusters11$clusters=as.character(clusters11$clusters)

  for(n in 1:nrow(transactns11)) {

    trans1 <- strsplit(transactns11$skills[n], ",")
    trans1
    transvect <- unlist(trans1)
    transvect

    matching_clusters <- c("")
    out_df$unique_id[n] <- as.character(transactns11$unique_id[n])
    out_df$skills[n] <- transactns11$skills[n]

    for(i in 1:nrow(clusters11)) {

      cluster1 <- strsplit(clusters11$clusters[i],",")
      cluster1
      clustervect <- unlist(cluster1)
      clustervect

      if(length(intersect(transvect,clustervect)) == length(clustervect)) {
        matching_clusters <- paste(matching_clusters, clusters11$cluster_id[i], sep = ",")
      }
    }
    matching_clusters <- substring(matching_clusters,2)
    out_df$matching_values[n] <- matching_clusters
  }

Problem is that, the code takes more time when the recods of the 2 files are more like 10000 or 20000( time taken will be 15 to 20 hrs).
Can any one please suggest how I can avoid this loops or any other method I can follow to improve the code and reduce the huge time taken to process.
Thanks in Advance.
Regards,
hari

Body:
I don't konw how fast this would be, but let's try:

First, store cluster names in codes

codes<-LETTERS[1:14]

Then make Boolean representation of clusters1$clusters and transactns1$skills

clusters2<-sapply(codes,grepl,x=clusters1$clusters)
transactns2<-sapply(codes,grepl,x=transactns1$skills)

Write a function that tests if given cluster is appropriate for given transactn:

is_ok<-function(clus, tran) !any(!(tran) & clus)

e.g.

is_ok(clusters2[1,], transactns2[2,])
[1] FALSE

This tells you that cluster 1 is not suitable for second transactn.

Then write a function that check all the clusters for given transactn. I use magrittr package to get access to %>% operator.

library(magrittr)
matching_values<-function(tran) apply(clusters2,1,is_ok,tran=tran) %>% which
%>% paste(collapse=',')

Fast check:

matching_values(transactns2[5,])
[1] "3,5,12"

Finally, apply the last function to all the transactns:

apply(transactns2,1,matching_values)
[1] "1,2,3"   "2"       "3"       "4,6"     "3,5,12"  "6,7"     "7"       "8"       "1,2,3,9"
[10] "10"      "11"      "3,12"    "1,2,3"   "2"       "3"       "4"       "3,5"     "6"


答:
Your code:

```<code>lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)
</code>```

Note the two for loops, what you are doing is looping through each line, then through each item on that line.  You are then pushing each item individually into your list lis.
To get the output you want, you want to be pushing a list of the two items on each line into your list.
You are actually already generating this list of items with f.read().split(), so you just need to append this.
This leaves you with the following:

```<code>lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        #no second loop here
        data = f.read().split()
        lis.append(data)
print(lis)
</code>```

This still doesn't give us the correct answer, the loop is the problem here,
we can fix this by just reading each line ideomatically, without specifying any ranges:

```<code>lis = []

with open("student_details.txt" , "r+") as f:
    for line in f:
        #no second loop here
        data = line.split()
        lis.append(data)
print(lis)
</code>```

Title: How to read a file to a list of lists?

Body:
Your code:

lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

Note the two for loops, what you are doing is looping through each line, then through each item on that line.  You are then pushing each item individually into your list lis.
To get the output you want, you want to be pushing a list of the two items on each line into your list.
You are actually already generating this list of items with f.read().split(), so you just need to append this.
This leaves you with the following:

lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        #no second loop here
        data = f.read().split()
        lis.append(data)
print(lis)

This still doesn't give us the correct answer, the loop is the problem here,
we can fix this by just reading each line ideomatically, without specifying any ranges:

lis = []

with open("student_details.txt" , "r+") as f:
    for line in f:
        #no second loop here
        data = line.split()
        lis.append(data)
print(lis)


问:
acceleration-field for unity3D racing game, c#
for a motorcycle racing game I want some parts of the track to increase the speed of the motorcycle.

I have a public float for the speed, which shows the speed in the inspector.

I added a plane with a Collider, which is a trigger and has the tag "speedfield"
Now I thought, some simple code, attached to the motorcyclescript below, would do it:

```<code>void OnTriggerEnter(Collider other)
{

    if (other.gameObject.CompareTag ("speedfield")) {
        Speed = Speed + 50;
    }
}
</code>```

But nothing happens. I think I'm missing something obvious here. Hope you can help! Greetings from germany :)

```<code>void FixedUpdate (){

    Inputs();
    Engine();
}

void Inputs (){

    Speed = rigid.velocity.magnitude * 3.6f;

    //Freezing rotation by Z axis.
    transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, 0);

    //If crashed...
    if(!crashed){
        if(!changingGear)
            motorInput = Input.GetAxis("Vertical");
        else
            motorInput = Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
        steerInput = Input.GetAxis("Horizontal");
    }else{
        motorInput = 0;
        steerInput = 0;
    }

    //Reverse bool
    if(motorInput < 0  && transform.InverseTransformDirection(rigid.velocity).z < 0)
        reversing = true;
    else
        reversing = false;

}

void Engine (){

    //Steer Limit.
    SteerAngle = Mathf.Lerp(defsteerAngle, highSpeedSteerAngle, (Speed / highSpeedSteerAngleAtSpeed));
    FrontWheelCollider.steerAngle = SteerAngle * steerInput;

    //Engine RPM.
    EngineRPM = Mathf.Clamp((((Mathf.Abs((FrontWheelCollider.rpm + RearWheelCollider.rpm)) * gearShiftRate) + MinEngineRPM)) / (currentGear + 1), MinEngineRPM, MaxEngineRPM);

    // Applying Motor Torque.
    if(Speed > maxSpeed){
        RearWheelCollider.motorTorque = 0;
    }else if(!reversing && !changingGear){
        RearWheelCollider.motorTorque = EngineTorque  * Mathf.Clamp(motorInput, 0f, 1f) * engineTorqueCurve[currentGear].Evaluate(Speed);
    }

    if(reversing){
        if(Speed < 10){
            RearWheelCollider.motorTorque = (EngineTorque  * motorInput) / 5f;
        }else{
            RearWheelCollider.motorTorque = 0;
        }
    }

}
</code>```

答:
You overriding speed variable:

```<code>void FixedUpdate (){

    Inputs();
    Engine();
}

void Inputs (){

    Speed = rigid.velocity.magnitude * 3.6f;
...
}
</code>```

change it to:

```<code>[SerializeField] float speedMultiplier = 3.6f;
[SerializeField] float speedMultiplierChange = 2;

void Inputs (){

        Speed = rigid.velocity.magnitude * speedMultiplier;
    ...
    }
</code>```

and

```<code>void OnTriggerEnter(Collider other)
{

    if (other.gameObject.CompareTag ("speedfield")) {
        speedMultiplier += speedMultiplierChange;
    }
}
</code>```

Body:
for a motorcycle racing game I want some parts of the track to increase the speed of the motorcycle.

I have a public float for the speed, which shows the speed in the inspector.

I added a plane with a Collider, which is a trigger and has the tag "speedfield"
Now I thought, some simple code, attached to the motorcyclescript below, would do it:

void OnTriggerEnter(Collider other)
{

    if (other.gameObject.CompareTag ("speedfield")) {
        Speed = Speed + 50;
    }
}

But nothing happens. I think I'm missing something obvious here. Hope you can help! Greetings from germany :)

void FixedUpdate (){

    Inputs();
    Engine();
}

void Inputs (){

    Speed = rigid.velocity.magnitude * 3.6f;

    //Freezing rotation by Z axis.
    transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, 0);

    //If crashed...
    if(!crashed){
        if(!changingGear)
            motorInput = Input.GetAxis("Vertical");
        else
            motorInput = Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
        steerInput = Input.GetAxis("Horizontal");
    }else{
        motorInput = 0;
        steerInput = 0;
    }

    //Reverse bool
    if(motorInput < 0  && transform.InverseTransformDirection(rigid.velocity).z < 0)
        reversing = true;
    else
        reversing = false;

}

void Engine (){

    //Steer Limit.
    SteerAngle = Mathf.Lerp(defsteerAngle, highSpeedSteerAngle, (Speed / highSpeedSteerAngleAtSpeed));
    FrontWheelCollider.steerAngle = SteerAngle * steerInput;

    //Engine RPM.
    EngineRPM = Mathf.Clamp((((Mathf.Abs((FrontWheelCollider.rpm + RearWheelCollider.rpm)) * gearShiftRate) + MinEngineRPM)) / (currentGear + 1), MinEngineRPM, MaxEngineRPM);

    // Applying Motor Torque.
    if(Speed > maxSpeed){
        RearWheelCollider.motorTorque = 0;
    }else if(!reversing && !changingGear){
        RearWheelCollider.motorTorque = EngineTorque  * Mathf.Clamp(motorInput, 0f, 1f) * engineTorqueCurve[currentGear].Evaluate(Speed);
    }

    if(reversing){
        if(Speed < 10){
            RearWheelCollider.motorTorque = (EngineTorque  * motorInput) / 5f;
        }else{
            RearWheelCollider.motorTorque = 0;
        }
    }

}

Body:
You overriding speed variable:

void FixedUpdate (){

    Inputs();
    Engine();
}

void Inputs (){

    Speed = rigid.velocity.magnitude * 3.6f;
...
}

change it to:

[SerializeField] float speedMultiplier = 3.6f;
[SerializeField] float speedMultiplierChange = 2;

void Inputs (){

        Speed = rigid.velocity.magnitude * speedMultiplier;
    ...
    }

and

void OnTriggerEnter(Collider other)
{

    if (other.gameObject.CompareTag ("speedfield")) {
        speedMultiplier += speedMultiplierChange;
    }
}


问:
How to customize error message with Tensorflow
I'm trying to show a custom message error with TensorFlow matrix, when the matrix has a determinant equals to 0, the inverse cannot be calculated but can't achieve to show message error with my function. My code is structured like so:

```<code>import tensorflow as tf
def inversematricx(arg):
    args = tf.convert_to_tensor(arg, dtype=tf.float32)
    try:
        return tf.matrix_inverse(args)
    except:
        raise ValueError("Determinant is 0. Input is not invertible")

mat1=tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) # Determinant is 0 for mat1
mat2=tf.constant([[1.0, 2.0, 4.0], [3.0, 5.0, 6.0], [7.0, 8.0, 9.0]])

inverse=inversematricx(mat1)

with tf.Session() as sess:

    result = sess.run(inverse)
    print(result)
</code>```

results for mat2

[[ 0.17647055 -0.82352936  0.47058824]  [-0.88235289  1.11764693
  -0.35294116]  [ 0.64705878 -0.35294113  0.05882351]]

But for mat1 which determinant is equals to 0, I want to force output
for ValueError message, not the error generated:

```<code>InvalidArgumentError: Input is not invertible.
     [[Node: MatrixInverse_21 = MatrixInverse[T=DT_FLOAT, adjoint=false, _device="/job:localhost/replica:0/task:0/cpu:0"](Const_69)]]

Caused by op 'MatrixInverse_21', defined at:
    File "D:\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 227, in <module>
main()
....
InvalidArgumentError (see above for traceback): Input is not invertible.
 [[Node: MatrixInverse_21 = MatrixInverse[T=DT_FLOAT, adjoint=false, _device="/job:localhost/replica:0/task:0/cpu:0"](Const_69)]]
</code>```

答:
I found solution with tf.Print on a custom function like as follow:</p>

```<code>sess = tf.InteractiveSession()
def checkMatrixInverse(arg):
    f=tf.matrix_determinant(arg).eval() #get determinant value
    args = tf.convert_to_tensor(arg, dtype=tf.float32)
    inv=tf.matrix_inverse(args)
    err='Input is not invertible:'
    if(f==0):
        return tf.Print(err,[err], name="NotInvertible")
    else:
        return tf.Print(inv, [inv], name="Inverse")

noninverse=checkMatrixInverse(mat1) #output b'Input is not invertible:'

inverse=checkMatrixInverse(mat2)
#output:
#[[ 0.17647055 -0.82352936  0.47058824]
# [-0.88235289  1.11764693 -0.35294116]
# [ 0.64705878 -0.35294113  0.05882351]]
</code>```

Body:
I'm trying to show a custom message error with TensorFlow matrix, when the matrix has a determinant equals to 0, the inverse cannot be calculated but can't achieve to show message error with my function. My code is structured like so:

import tensorflow as tf
def inversematricx(arg):
    args = tf.convert_to_tensor(arg, dtype=tf.float32)
    try:
        return tf.matrix_inverse(args)
    except:
        raise ValueError("Determinant is 0. Input is not invertible")

mat1=tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) # Determinant is 0 for mat1
mat2=tf.constant([[1.0, 2.0, 4.0], [3.0, 5.0, 6.0], [7.0, 8.0, 9.0]])

inverse=inversematricx(mat1)

with tf.Session() as sess:

    result = sess.run(inverse)
    print(result)

results for mat2

[[ 0.17647055 -0.82352936  0.47058824]  [-0.88235289  1.11764693
  -0.35294116]  [ 0.64705878 -0.35294113  0.05882351]]

But for mat1 which determinant is equals to 0, I want to force output
for ValueError message, not the error generated:

InvalidArgumentError: Input is not invertible.
     [[Node: MatrixInverse_21 = MatrixInverse[T=DT_FLOAT, adjoint=false, _device="/job:localhost/replica:0/task:0/cpu:0"](Const_69)]]

Caused by op 'MatrixInverse_21', defined at:
    File "D:\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 227, in <module>
main()
....
InvalidArgumentError (see above for traceback): Input is not invertible.
 [[Node: MatrixInverse_21 = MatrixInverse[T=DT_FLOAT, adjoint=false, _device="/job:localhost/replica:0/task:0/cpu:0"](Const_69)]]

Body:
I found solution with tf.Print on a custom function like as follow:

sess = tf.InteractiveSession()
def checkMatrixInverse(arg):
    f=tf.matrix_determinant(arg).eval() #get determinant value
    args = tf.convert_to_tensor(arg, dtype=tf.float32)
    inv=tf.matrix_inverse(args)
    err='Input is not invertible:'
    if(f==0):
        return tf.Print(err,[err], name="NotInvertible")
    else:
        return tf.Print(inv, [inv], name="Inverse")

noninverse=checkMatrixInverse(mat1) #output b'Input is not invertible:'

inverse=checkMatrixInverse(mat2)
#output:
#[[ 0.17647055 -0.82352936  0.47058824]
# [-0.88235289  1.11764693 -0.35294116]
# [ 0.64705878 -0.35294113  0.05882351]]


问:
PHP Online file analyzing
I'm looking for some tutorial on how from a webapplication upload a file and while uploading analyzing it.

I mean a user chooses a file from his computer on a web app, the file is excel. After choosing elaborate it the file is analyzed and some stuff is done, once the work is complete the user is redirect to  a webapp with the results.

I need just some hints on where to start investigating.

Many thanks!

答:
PHP won't be able to do much analysis since it is server-side. It cannot communicate with the file until it is entirely uploaded. You may want to look at creating a Java Applet uploader to analyze a user's file before or during the upload. However, this is not to say you cannot analyze the file with PHP after the user has uploaded the file to the server.

Good luck!

Dennis M.

Title: PHP Online file analyzing


问:
UIDocumentInteractionController not appearing on iPad but working on iPhone
I'm trying to display a UIDocumentInteractionController on my app. Everything is working perfectly on iPhone, but nothing is happening on iPad. Here is my code:

```<code>    interactionController = [UIDocumentInteractionController interactionControllerWithURL:imageFile];
    interactionController.UTI = @"com.instagram.photo";
    interactionController.annotation = [NSDictionary dictionaryWithObject:[self commentForInstagram] forKey:@"InstagramCaption"];
    [interactionController presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
</code>```

interactionController is a strong reference to an instance, and imageFile exists. On iPhone, it brings up the 'Open With..' dialog and Instagram is present. On iPad, absolutely nothing happens when the above code runs. Yes, I do have Instagram installed and working on my iPad.

What could be the reason that nothing is happening when the code is executed? self.view and self.view.frame are valid objects (tested on debug).

Thanks, Can.

答:
I had the same issue. I checked the frame that is being passed and saw that x and y are set to 0. Next I tried to change those values (by keeping width and height as passed) and the popup showed up. Here the code:

```<code>-(void)openDocument:(UIView*)senderView {

   CGRect rectForAppearing = [senderView convertRect:senderView.frame toView:senderView];

   if (isIPAD)
     rectForAppearing =  CGRectMake(100, 100, rectForAppearing.size.width, rectForAppearing.size.height);

   [interactionController presentOptionsMenuFromRect:rect inView:self.view animated:YES];
</code>```

}

The popup appears on an Ipad in the top right corner. You can of course twist those 100,100 parameters to your desire. On iPhones i leave the popover as is (at the bottom)

Body:
I'm trying to display a UIDocumentInteractionController on my app. Everything is working perfectly on iPhone, but nothing is happening on iPad. Here is my code:

    interactionController = [UIDocumentInteractionController interactionControllerWithURL:imageFile];
    interactionController.UTI = @"com.instagram.photo";
    interactionController.annotation = [NSDictionary dictionaryWithObject:[self commentForInstagram] forKey:@"InstagramCaption"];
    [interactionController presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];

interactionController is a strong reference to an instance, and imageFile exists. On iPhone, it brings up the 'Open With..' dialog and Instagram is present. On iPad, absolutely nothing happens when the above code runs. Yes, I do have Instagram installed and working on my iPad.

What could be the reason that nothing is happening when the code is executed? self.view and self.view.frame are valid objects (tested on debug).

Thanks, Can.

Body:
I had the same issue. I checked the frame that is being passed and saw that x and y are set to 0. Next I tried to change those values (by keeping width and height as passed) and the popup showed up. Here the code:

-(void)openDocument:(UIView*)senderView {

   CGRect rectForAppearing = [senderView convertRect:senderView.frame toView:senderView];

   if (isIPAD)
     rectForAppearing =  CGRectMake(100, 100, rectForAppearing.size.width, rectForAppearing.size.height);

   [interactionController presentOptionsMenuFromRect:rect inView:self.view animated:YES];

}

The popup appears on an Ipad in the top right corner. You can of course twist those 100,100 parameters to your desire. On iPhones i leave the popover as is (at the bottom)


问:
Shortcut to switch between design and text in Android Studio
Does anyone know some shortcut to switch between design and text in android studio while editing XML layout?

While I can switch from design view to source using Ctrl+B (and need to select something in layout before), I have no way to go back.

答: On Android Studio 2.3+, one can use the shortcut Ctrl+T.


问:
How to write Rspec for basic Show, Create, Destroy, Edit methods in rails (with or without FactoryGirl)
I have a basic user_controller.rb file like this:

```<code>class UserController < ApplicationController

  def new
    @user = User.new
  end

  def index
    @user = User.all
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])

  if @user.update(user_params)
      redirect_to @user
    else
      render 'edit'
    end
  end

 def destroy
  @user = User.find(params[:id])
  @user.destroy
  redirect_to action: 'index'
 end

 private
  def user_params
   params.require(:user).permit(:name, :key, :desc)
  end
end
</code>```

This is my (model) user.rb file:

```<code>class User < ApplicationRecord
  validates :name,    presence: true
  validates :key,     uniqueness: true, presence: true
  validates :desc,    presence: true
end
</code>```

And created a factories.rb file (in the specs folder):

```<code>FactoryGirl.define do
  factory :user do
   name "TestUser"
   key "TKey"
   desc "TestDescription"
  end
end
</code>```

I tried several ways to make the specs work but I can't because of the confusing syntax.

The only one which worked was (for the 'C' in the CRUD operations, the below file is user_controller_specs.rb):

```<code>require 'rails_helper'
require 'factory_girl_rails'

RSpec.describe UserController, :type => :controller do
 let(:temp) { FactoryGirl.build(:user) }

 describe "POST create" do
  it "should redirect back to the index page" do
     post :create, :user => { :user => temp }
     expect(get: user_url(subdomain: nil)).to route_to(controller: "user", action: "index")
  end
 end
end
</code>```

I skimmed through several tutorials to find what should be the correct approach for CRUD operations but didn't got any simple to understand specs. I am trying to write these in the specs/controllers folder but these are giving errors.  What should be the correct syntax to write the specs?

PS: I'am new to Ruby/Rails and trying to write test cases with Rspec and FactoryGirl. Any help is appreciated.

Edit:
 Maybe I framed the question wrongly... I'm more interested in the syntax part. If I get to know an example how to write one, I'll be able to write others by changing some tiny bits of logic here and there.... Let's say I have a basic test case just to see whether updating a user details is not returning an error because of validations, how should I write it with (or without) Factory Girl gem?

答:
It's a pretty broad question, but in any kind of test, you want test whatever use cases you have available to you. Example--are there different paths users might follow from hitting a specific controller action.

So you want your test to cover the basics. When you hit the create action, is a user actually created? If the relevant params are missing, is an error thrown? Use cases will drive your expectations.

With rspec controllers specifically, you'll use the appropriate verb and the name of the action, and pass it whatever parameters are necessary.

post :create, :user => { :user => temp }

That basically says, "do a post request to my create an action and pass it the parameters inside these curly braces."

After running that rspec gives you access to the response. You can always log the response after a controller request to help you debug the situation: p response.

You'll follow up each type of request with an expectation. The expectation should answer the question: "What did I expect hitting this action to do?" If you were, for instance, hitting the user update action and passed a param to change the user's age to 21, your expectation might be something like:

expect(user.age).to eq(21)

A great resource is the rspec documentation on relish. https://relishapp.com/rspec

"How to" do a broad general thing is a tough question to answer like this. My advice would be to try to actually test one, log the failure case, and post those logs in a new question and people on SO can help you work through testing a particular action you're struggling with.

Body:
I have a basic user_controller.rb file like this:

class UserController < ApplicationController

  def new
    @user = User.new
  end

  def index
    @user = User.all
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])

  if @user.update(user_params)
      redirect_to @user
    else
      render 'edit'
    end
  end

 def destroy
  @user = User.find(params[:id])
  @user.destroy
  redirect_to action: 'index'
 end

 private
  def user_params
   params.require(:user).permit(:name, :key, :desc)
  end
end

This is my (model) user.rb file:

class User < ApplicationRecord
  validates :name,    presence: true
  validates :key,     uniqueness: true, presence: true
  validates :desc,    presence: true
end

And created a factories.rb file (in the specs folder):

FactoryGirl.define do
  factory :user do
   name "TestUser"
   key "TKey"
   desc "TestDescription"
  end
end

I tried several ways to make the specs work but I can't because of the confusing syntax.

The only one which worked was (for the 'C' in the CRUD operations, the below file is user_controller_specs.rb):

require 'rails_helper'
require 'factory_girl_rails'

RSpec.describe UserController, :type => :controller do
 let(:temp) { FactoryGirl.build(:user) }

 describe "POST create" do
  it "should redirect back to the index page" do
     post :create, :user => { :user => temp }
     expect(get: user_url(subdomain: nil)).to route_to(controller: "user", action: "index")
  end
 end
end

I skimmed through several tutorials to find what should be the correct approach for CRUD operations but didn't got any simple to understand specs. I am trying to write these in the specs/controllers folder but these are giving errors.  What should be the correct syntax to write the specs?

PS: I'am new to Ruby/Rails and trying to write test cases with Rspec and FactoryGirl. Any help is appreciated.

Edit:
 Maybe I framed the question wrongly... I'm more interested in the syntax part. If I get to know an example how to write one, I'll be able to write others by changing some tiny bits of logic here and there.... Let's say I have a basic test case just to see whether updating a user details is not returning an error because of validations, how should I write it with (or without) Factory Girl gem?


问:
Best BDD practices for designing Cucumber scenarios for forms
Lets say you have a form which creates a new user.
How do you write your Cucumber scenario?

1.)

```<code>Given I am logged in as admin
When I create a new user
Then I should see "Successfully created user"
</code>```

2.)

```<code>Given I am logged in as admin
When I go to Create new user
And I fill in "Name" with "Name111"
And I fill in "Password" with "Password111"
And I press "Create new user"
Then I should see "Successfully created user"
</code>```

If you choose 1.) where do you document the requirements for a User (A user should have a name and a password). I see that BDD is about behavior but at some point you and the stakeholder have to specify which properties a user should have, don't you?

I'm very new to BDD so I appreciate any advise...

答:
The scenarios you've written are fairly low level. Unless you're actually producing secure login functionality to sell, I'd stick to the happy case and unit / manual test the rest. If you don't, you'll create so many scenarios it'll be a maintenance nightmare.

Find out what differentiates the product you're creating from all the similar products, then target that as the value of the scenario. Then it will look like this:

```<code>Given Fred is logged in
When Fred <does something>
Then Fred should <get some really differentiating value>
And <something else happens>
</code>```

Stick to the really high-level capabilities, rather than low-level form-based steps. For instance:

```<code>Given there is already a question on BDD and Cucumber
Given Peyote is logged in
When Peyote proposes a question on BDD and Cucumber
Then Peyote should see other questions on BDD and Cucumber.
</code>```

There's a concept called the "Page Paradigm", in which you create a class with all the low-level steps that the page or screen can perform. You can then call those low-level steps on the page from within the higher-level Cucumber step fixtures.

Your business will be much more engaged with scenarios like this. The main purpose of BDD is not to produce automated tests, but to have conversations around the scenarios so that you can find out where you're going wrong and what other options you could consider before you go to the trouble of implementing the code. Automated tests are a nice by-product.

The conversations, and the learning you get by talking through them, are the things which make BDD different from ATDD (Acceptance Test Driven Development). That's why we use language like Example, Scenario, Given, When, Then, Context, Event, Outcome instead of Test, SetUp, TearDown, Act, Arrange, Assert - so we can talk about these with business, BAs and testers in the same language.

See Dan North's article on Deliberate Discovery and the rest of his blog for more, and good luck with the BDD!

Body:
Lets say you have a form which creates a new user.
How do you write your Cucumber scenario?

1.)

Given I am logged in as admin
When I create a new user
Then I should see "Successfully created user"

2.)

Given I am logged in as admin
When I go to Create new user
And I fill in "Name" with "Name111"
And I fill in "Password" with "Password111"
And I press "Create new user"
Then I should see "Successfully created user"

If you choose 1.) where do you document the requirements for a User (A user should have a name and a password). I see that BDD is about behavior but at some point you and the stakeholder have to specify which properties a user should have, don't you?

I'm very new to BDD so I appreciate any advise...

Body:
The scenarios you've written are fairly low level. Unless you're actually producing secure login functionality to sell, I'd stick to the happy case and unit / manual test the rest. If you don't, you'll create so many scenarios it'll be a maintenance nightmare.

Find out what differentiates the product you're creating from all the similar products, then target that as the value of the scenario. Then it will look like this:

Given Fred is logged in
When Fred <does something>
Then Fred should <get some really differentiating value>
And <something else happens>

Stick to the really high-level capabilities, rather than low-level form-based steps. For instance:

Given there is already a question on BDD and Cucumber
Given Peyote is logged in
When Peyote proposes a question on BDD and Cucumber
Then Peyote should see other questions on BDD and Cucumber.

There's a concept called the "Page Paradigm", in which you create a class with all the low-level steps that the page or screen can perform. You can then call those low-level steps on the page from within the higher-level Cucumber step fixtures.

Your business will be much more engaged with scenarios like this. The main purpose of BDD is not to produce automated tests, but to have conversations around the scenarios so that you can find out where you're going wrong and what other options you could consider before you go to the trouble of implementing the code. Automated tests are a nice by-product.

The conversations, and the learning you get by talking through them, are the things which make BDD different from ATDD (Acceptance Test Driven Development). That's why we use language like Example, Scenario, Given, When, Then, Context, Event, Outcome instead of Test, SetUp, TearDown, Act, Arrange, Assert - so we can talk about these with business, BAs and testers in the same language.

See Dan North's article on Deliberate Discovery and the rest of his blog for more, and good luck with the BDD!


问:
Need to Format this JSON properly and display in HTML using AJAX
I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,

It's the first time I see a JSON like this.

I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.

I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...

I'm using scheb/yahoo-finance-api on packagist for that, if it helps.

Thanks for your help.

{
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
}

$(function(){
$("#get-data").click(function() {
    //do ajax here and load data
    var showData = $('#show-data');
    var $data = $.getJSON("data.php", function(data) {

        // $data = $data.responseText;
        function buildTree(data, container) {
            $data.forEach(function(node) {

                var el = document.createElement(node.tag);

                if (Array.isArray(node.content)) {
                    buildTree(node.content, el);
                }
                else if (typeof(node.content) == 'object') {
                    buildTree([node.content], el);
                }
                else {
                    el.innerHTML = node.content;
                }

                container.appendChild(el);
            });

        }

        console.log($data);
        buildTree($data, document.body);
    });
});
```

});

That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)

答:
literal notation, not Json.
You can go over this in a for in loop, something like this:</p>

```<code>var x = {
query: {
    count: 1,
    created: "2017-06-07T12:34:44Z",
    lang: "en-US",
    results: {
        quote: {
            symbol: "APLL",
            Symbol: "APLL",
            LastTradePriceOnly: "0.119",
            LastTradeDate: "6/6/2017",
            LastTradeTime: "11:13am",
            Change: "+0.023",
            Open: "0.119",
            DaysHigh: "0.119",
            DaysLow: "0.110",
            Volume: "300"
        }
    }
}
}

for (var key in x) {
    if (!x.hasOwnProperty(key)) continue;
    var obj = x[key];
    for (var prop in obj) {
        if(!obj.hasOwnProperty(prop)) continue;
        alert(prop + " = " + obj[prop]);
    }
}
</code>```

Body:
I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,

It's the first time I see a JSON like this.

I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.

I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...

I'm using scheb/yahoo-finance-api on packagist for that, if it helps.

Thanks for your help.

{
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
}

$(function(){
$("#get-data").click(function() {
    //do ajax here and load data
    var showData = $('#show-data');
    var $data = $.getJSON("data.php", function(data) {

        // $data = $data.responseText;
        function buildTree(data, container) {
            $data.forEach(function(node) {

                var el = document.createElement(node.tag);

                if (Array.isArray(node.content)) {
                    buildTree(node.content, el);
                }
                else if (typeof(node.content) == 'object') {
                    buildTree([node.content], el);
                }
                else {
                    el.innerHTML = node.content;
                }

                container.appendChild(el);
            });

        }

        console.log($data);
        buildTree($data, document.body);
    });
});

});

That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)

Body:
literal notation, not Json.
You can go over this in a for in loop, something like this:

var x = {
query: {
    count: 1,
    created: "2017-06-07T12:34:44Z",
    lang: "en-US",
    results: {
        quote: {
            symbol: "APLL",
            Symbol: "APLL",
            LastTradePriceOnly: "0.119",
            LastTradeDate: "6/6/2017",
            LastTradeTime: "11:13am",
            Change: "+0.023",
            Open: "0.119",
            DaysHigh: "0.119",
            DaysLow: "0.110",
            Volume: "300"
        }
    }
}
}

for (var key in x) {
    if (!x.hasOwnProperty(key)) continue;
    var obj = x[key];
    for (var prop in obj) {
        if(!obj.hasOwnProperty(prop)) continue;
        alert(prop + " = " + obj[prop]);
    }
}


问:
Variable for RowNum of first and last integer in a column and creating a range between the 2
I want to create two variables, one for the row number of the first integer in column J  and one for the last integer in column J (after this there are many rows of #N A N A).  I then would like to use these two points to create a range for column J but also for column D (using the same variables)
I just started using vba earlier this week, understand the simplicity and I have found similar answers elsewhere but none quite so specific.  Any help would be much appreciated.  What I have so far:</p>

```<code>Dim StartRow As Integer
Dim sht As Worksheet
Dim LastRow As Integer
Dim JRange As Range
Dim DRange As Range

Set StartRow = Range("j7:j100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
LastNonRow = sht.Cells(sht.Rows.Count, 8).End(xlUp).Row (I fear this includes the #N A N A rows too)

Set JRange = sht.Range(StartRow,10,sht.Cells(LastRow,10))
Set DRange = sht.Range(StartRow,4,sht.Cells(LastRow,4))
</code>```

答:
First, you should use:

```<code>Set JRange = sht.Range(sht.Cells(StartRow,10),sht.Cells(LastRow,10))
</code>```

Second, don't use the Set keyword with Integer or other value types. The Set keyword is only for use with objects. If you are not familiar with object vs. value types, you should do some research on that. Here are some Excel VBA examples:

```<code>Dim i     As Integer
Dim j     As Double
dim str   as String
Dim coll  As Collection
dim sht   As Worksheet
dim rng   As Range

i = 1
j = 2.4
str = "This is a string of text, also a value type"
Set coll = ThisWorkbook.Sheets    'Note that ThisWorkbook.Sheets is a Collection
Set sht = coll(1)    'sets sht to the first Sheet in coll
Set rng = sht.Range("A1")
</code>```

If you just care whether a number is in the cell and not necessarily an integer, you can do something like this

```<code>'Use Double instead of Integer because the possible range of values is larger.
'This reduces risk of error
Dim LastRow     As Double
Dim UpperLimit  As Double

'Assuming you already have StartRow
LastRow = StartRow + 1

'Use UpperLimit to ensure you don't go into an infinite loop
'Set UpperLimit to an appropriately high value
UpperLimit = 100000

'Test Loop
Do While IsNumeric(sht.Cells(LastRow,10).Value) and LastRow <= UpperLimit
    LastRow = LastRow + 1
Loop

'Check if it exceeded upper limit
If LastRow > UpperLimit Then
    MsgBox "Exceeded Limit"
    Exit Sub
End If

LastRow = LastRow - 1    'Because the sht.Cells(LastRow,10).value is non-numeric

'Now set ranges
</code>```

If you care whether it is actually an integer, you can use the above code, but put a conditional statement inside the loop to test whether the number is indeed an integer. There are many resources on the web that give code for determining whether value is an integer.

Also, you should make sure you set the sht variable before you use it.

```<code>Set sht = ThisWorkbook.Sheets(1)
</code>```

Or

```<code>Set sht = ThisWorkbook.Sheets("MySheetName")
</code>```

Hope this helps.

EDIT:
If the range is not continuous with integers, reverse the loop:

```<code>LastRow = UpperLimit
Do Until IsNumeric(sht.Cells(lastRow,10).Value)) Or LastRow = StartRow
    LastRow = LastRow - 1
Loop
</code>```

If you do this, remove the LastRow = LastRow-1 from the end of the code as the value you are looking for is already in LastRow.

Body:
I want to create two variables, one for the row number of the first integer in column J  and one for the last integer in column J (after this there are many rows of #N A N A).  I then would like to use these two points to create a range for column J but also for column D (using the same variables)
I just started using vba earlier this week, understand the simplicity and I have found similar answers elsewhere but none quite so specific.  Any help would be much appreciated.  What I have so far:

Dim StartRow As Integer
Dim sht As Worksheet
Dim LastRow As Integer
Dim JRange As Range
Dim DRange As Range

Set StartRow = Range("j7:j100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
LastNonRow = sht.Cells(sht.Rows.Count, 8).End(xlUp).Row (I fear this includes the #N A N A rows too)

Set JRange = sht.Range(StartRow,10,sht.Cells(LastRow,10))
Set DRange = sht.Range(StartRow,4,sht.Cells(LastRow,4))

Body:
First, you should use:

Set JRange = sht.Range(sht.Cells(StartRow,10),sht.Cells(LastRow,10))

Second, don't use the Set keyword with Integer or other value types. The Set keyword is only for use with objects. If you are not familiar with object vs. value types, you should do some research on that. Here are some Excel VBA examples:

Dim i     As Integer
Dim j     As Double
dim str   as String
Dim coll  As Collection
dim sht   As Worksheet
dim rng   As Range

i = 1
j = 2.4
str = "This is a string of text, also a value type"
Set coll = ThisWorkbook.Sheets    'Note that ThisWorkbook.Sheets is a Collection
Set sht = coll(1)    'sets sht to the first Sheet in coll
Set rng = sht.Range("A1")

If you just care whether a number is in the cell and not necessarily an integer, you can do something like this

'Use Double instead of Integer because the possible range of values is larger.
'This reduces risk of error
Dim LastRow     As Double
Dim UpperLimit  As Double

'Assuming you already have StartRow
LastRow = StartRow + 1

'Use UpperLimit to ensure you don't go into an infinite loop
'Set UpperLimit to an appropriately high value
UpperLimit = 100000

'Test Loop
Do While IsNumeric(sht.Cells(LastRow,10).Value) and LastRow <= UpperLimit
    LastRow = LastRow + 1
Loop

'Check if it exceeded upper limit
If LastRow > UpperLimit Then
    MsgBox "Exceeded Limit"
    Exit Sub
End If

LastRow = LastRow - 1    'Because the sht.Cells(LastRow,10).value is non-numeric

'Now set ranges

If you care whether it is actually an integer, you can use the above code, but put a conditional statement inside the loop to test whether the number is indeed an integer. There are many resources on the web that give code for determining whether value is an integer.

Also, you should make sure you set the sht variable before you use it.

Set sht = ThisWorkbook.Sheets(1)

Or

Set sht = ThisWorkbook.Sheets("MySheetName")

Hope this helps.

EDIT:
If the range is not continuous with integers, reverse the loop:

LastRow = UpperLimit
Do Until IsNumeric(sht.Cells(lastRow,10).Value)) Or LastRow = StartRow
    LastRow = LastRow - 1
Loop

If you do this, remove the LastRow = LastRow-1 from the end of the code as the value you are looking for is already in LastRow.


问:
Non-capturing lambda seems to nevertheless capture the enclosing instance
I wrote this code:

```<code>import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main();
    }

    private Main() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable) () -> new Thread() {};
        new ObjectOutputStream(System.out).writeObject(supplier);
    }
}
</code>```

If I run it, I'll get an exception:

```<code>Exception in thread "main" java.io.NotSerializableException: Main
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1378)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at Main.<init>(Main.java:28)
</code>```

However, my understanding is that I properly made the lambda Serializable and I declared it such that it doesn't refer to any surrounding context, being therefore a non-capturing lambda. Yet the Main instance is captured and the result of the lambda expression fails to be serialized. I realize I'm declaring an anonymous class inside the lambda, but I would expect the lambda instance itself to be its enclosing instance, not the surrounding Main type.

Is this behavior expected by the Java Language Specification and, if yes, how come?

答:
In your lambda expression’s body, you have the anonymous class declaration new Thread() {} and you are not in a static context, so this expression implicitly captures this, which has the same meaning within the lambda expression as outside of it, per JLS §15.27.2, Lambda Body:

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

The transparency of this (both explicit and implicit) in the body of a lambda expression - that is, treating it the same as in the surrounding context - allows more flexibility for implementations, and prevents the meaning of unqualified names in the body from being dependent on overload resolution.

Since the surrounding context determines the behavior of the anonymous class, you can easily fix the issue by using a static context to create a nested class instead:

```<code>import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        write();
    }

    static void write() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable)() -> new Thread() {};
        new ObjectOutputStream(System.out).writeObject(supplier);
    }
}
</code>```

Then, no surrounding instance will be captured.

Note that this can be seen as the general idea of lambda expressions, to define functions as expressions having exactly the same meaning as within the context they are written, except for the introduction of function parameters. The generation of an instance of a functional interface is only the vehicle to get this concept into the Java programming language in a compatible and useful way, but not a concept to influence the meaning of the lambda expression.

Body:
I wrote this code:

import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main();
    }

    private Main() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable) () -> new Thread() {};
        new ObjectOutputStream(System.out).writeObject(supplier);
    }
}

If I run it, I'll get an exception:

Exception in thread "main" java.io.NotSerializableException: Main
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1378)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at Main.<init>(Main.java:28)

However, my understanding is that I properly made the lambda Serializable and I declared it such that it doesn't refer to any surrounding context, being therefore a non-capturing lambda. Yet the Main instance is captured and the result of the lambda expression fails to be serialized. I realize I'm declaring an anonymous class inside the lambda, but I would expect the lambda instance itself to be its enclosing instance, not the surrounding Main type.

Is this behavior expected by the Java Language Specification and, if yes, how come?

Body:
In your lambda expression’s body, you have the anonymous class declaration new Thread() {} and you are not in a static context, so this expression implicitly captures this, which has the same meaning within the lambda expression as outside of it, per JLS §15.27.2, Lambda Body:

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

The transparency of this (both explicit and implicit) in the body of a lambda expression - that is, treating it the same as in the surrounding context - allows more flexibility for implementations, and prevents the meaning of unqualified names in the body from being dependent on overload resolution.

Since the surrounding context determines the behavior of the anonymous class, you can easily fix the issue by using a static context to create a nested class instead:

import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) throws Exception {
        write();
    }

    static void write() throws Exception {
        Supplier<Thread> supplier = (Supplier<Thread> & Serializable)() -> new Thread() {};
        new ObjectOutputStream(System.out).writeObject(supplier);
    }
}

Then, no surrounding instance will be captured.

Note that this can be seen as the general idea of lambda expressions, to define functions as expressions having exactly the same meaning as within the context they are written, except for the introduction of function parameters. The generation of an instance of a functional interface is only the vehicle to get this concept into the Java programming language in a compatible and useful way, but not a concept to influence the meaning of the lambda expression.


问:
Find Character In Primary Key and Update a field
I'm working on a e-commerce website that uses CMS that uses MS Access 2000 database. The CMS generates the website pages on upload so there's no database online other than Perl files to control the shopping cart. The CMS allows the creation of duplicate products that can be placed elsewhere on the site

I have a table called PRODUCTS in my database. Whereby if a product is a duplicate of the original it contains ! in the primary key

Within the Product table I wish to turn off a setting for all the duplicate products only in the database.

I'm trying to create an SQL statement which would say..

FROM Products
Where Product_Reference contains the character !
Set Can_Be_Ordered_Online to False

Can anyone help?

答:
What you're looking for is something like that:

```<code>UPDATE PRODUCTS SET Can_Be_Ordered_Online = FALSE
WHERE Product_Reference LIKE '%!%'
</code>```

If the ! is always at the end or at the start, you can remove one of the %.

Body:
What you're looking for is something like that:

UPDATE PRODUCTS SET Can_Be_Ordered_Online = FALSE
WHERE Product_Reference LIKE '%!%'

If the ! is always at the end or at the start, you can remove one of the %.


问:
How to move the browser window in Selenium 3?
The following code worked under older versions of Selenium but results in a timeout under Selenium 3:

```<code>WebDriver driver = new ChromeDriver();
driver.manage().window().setPosition(new Point(1315, 0));
</code>```

What is the correct way of moving the browser window in Selenium 3?

答:
I believe there is no way native way to resize, or manipulate browser windows in Selenium.

Source: https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/1750

The only simple way that I have seen it done in the past is what you did, using a point and setting the position.

Body:
The following code worked under older versions of Selenium but results in a timeout under Selenium 3:

WebDriver driver = new ChromeDriver();
driver.manage().window().setPosition(new Point(1315, 0));

What is the correct way of moving the browser window in Selenium 3?


问:
I got a TypeError message when using tensorflow
When I use tensorflow RNN, I met this problem.
Here is the version of my package:

```<code>Python version: 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609]

Packages versions:
numpy 1.12.1
tensorflow 1.1.0
</code>```

And the code is:

```<code>import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn

batches = 28

permutations = np.random.permutation(batches)

cell_class = rnn.BasicLSTMCell
cell = cell_class(200)
zero_state = cell.zero_state(batches, tf.float32)

with tf.Session() as sess:
    state = sess.run(zero_state)
    state[np.arange(batches)] = state[permutations]
</code>```

The message I got:

```<code>Traceback (most recent call last):
  File "test.py", line 15, in <module>
    state[np.arange(batches)] = state[permutations]
TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

答:
can you try replacing zero_state value with below line:

```<code>zero_state = cell.zero_state(batches, tf.float32)[0]
</code>```

This appears to be an issue with the latest version of Numpy. A recent change made it an error to treat a single-element array as a scalar for the purposes of indexing.

Body:
When I use tensorflow RNN, I met this problem.
Here is the version of my package:

Python version: 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609]

Packages versions:
numpy 1.12.1
tensorflow 1.1.0

And the code is:

import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn

batches = 28

permutations = np.random.permutation(batches)

cell_class = rnn.BasicLSTMCell
cell = cell_class(200)
zero_state = cell.zero_state(batches, tf.float32)

with tf.Session() as sess:
    state = sess.run(zero_state)
    state[np.arange(batches)] = state[permutations]

The message I got:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    state[np.arange(batches)] = state[permutations]
TypeError: only integer scalar arrays can be converted to a scalar index

Body:
can you try replacing zero_state value with below line:

zero_state = cell.zero_state(batches, tf.float32)[0]

This appears to be an issue with the latest version of Numpy. A recent change made it an error to treat a single-element array as a scalar for the purposes of indexing.


问:
HWnd of Visual Studio 2010
Is there a way to get the HWnd pointer to the top window of Visual Studio 2010 from a VSIX extension?  (I would like to change the title of the window).</p>

答:
Since there are good chances that your VSIX extension will be running in-process with Visual Studio, you should try this:

```<code>System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
</code>```

(Note if you do this too early, you'll get VS Splash screen ...)

Title: HWnd of Visual Studio 2010

Body:
Since there are good chances that your VSIX extension will be running in-process with Visual Studio, you should try this:

System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle

(Note if you do this too early, you'll get VS Splash screen ...)


问:
can't access to custom property that set to header in transformer - spring integration
I have these channel and transformer.

```<code><integration:channel id="channel">
<integration:interceptors>
        <integration:wire-tap channel="logChannel"/>
    </integration:interceptors>
</integration:channel>
<integration:transformer input-channel="channel"
                         output-channel="resultChannel"
                         ref="transformerImpl"
                         method="transform">
</integration:transformer>
</code>```

In transformer, I couldn't access to my custom property in header by @Header. but in logChannel, i log my headers, and everything is ok. my property is exist. any idea ?

答:
In the Framework we have a couple test-cases for similar approach:

```<code>    @Transformer
    public String headerTest(String s, @Header("number") Integer num) {
        return s + num;
    }

    @Transformer
    public String optionalHeaderTest(String s, @Header(value = "number", required = false) Integer num) {
        return s + num;
    }
</code>```

The tests for optionalHeaderTest transformer look like:

```<code>@Test
public void optionalHeaderAnnotation() throws Exception {
    TestBean testBean = new TestBean();
    Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class);
    MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod);
    Message<String> message = MessageBuilder.withPayload("foo").setHeader("number", 99).build();
    Message<?> result = transformer.transform(message);
    assertEquals("foo99", result.getPayload());
}

@Test
public void optionalHeaderValueNotProvided() throws Exception {
    TestBean testBean = new TestBean();
    Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class);
    MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod);
    Message<String> message = MessageBuilder.withPayload("foo").build();
    Message<?> result = transformer.transform(message);
    assertEquals("foonull", result.getPayload());
}
</code>```

Can you check what message have adding to your transform() the whole Message<?> object? This way you have access to all the headers.

Body:
I have these channel and transformer.

<integration:channel id="channel">
<integration:interceptors>
        <integration:wire-tap channel="logChannel"/>
    </integration:interceptors>
</integration:channel>
<integration:transformer input-channel="channel"
                         output-channel="resultChannel"
                         ref="transformerImpl"
                         method="transform">
</integration:transformer>

In transformer, I couldn't access to my custom property in header by @Header. but in logChannel, i log my headers, and everything is ok. my property is exist. any idea ?

Body:
In the Framework we have a couple test-cases for similar approach:

    @Transformer
    public String headerTest(String s, @Header("number") Integer num) {
        return s + num;
    }

    @Transformer
    public String optionalHeaderTest(String s, @Header(value = "number", required = false) Integer num) {
        return s + num;
    }

The tests for optionalHeaderTest transformer look like:

@Test
public void optionalHeaderAnnotation() throws Exception {
    TestBean testBean = new TestBean();
    Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class);
    MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod);
    Message<String> message = MessageBuilder.withPayload("foo").setHeader("number", 99).build();
    Message<?> result = transformer.transform(message);
    assertEquals("foo99", result.getPayload());
}

@Test
public void optionalHeaderValueNotProvided() throws Exception {
    TestBean testBean = new TestBean();
    Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class);
    MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod);
    Message<String> message = MessageBuilder.withPayload("foo").build();
    Message<?> result = transformer.transform(message);
    assertEquals("foonull", result.getPayload());
}

Can you check what message have adding to your transform() the whole Message<?> object? This way you have access to all the headers.