问:
Capture value from infinite thread c++
I have created a thread that is running parrallel with main thread. Both threads are doing something infinitely (both have while(true) statement). Main thread while(true) is creating game logic in frames, and second thread is receiveing messages from socket.

Is it possible to get string value of message received from second thread into main thread each frame without returning from second thread?
In c#, I would do it with method invoker but I didn't find anything helpful for c++. Is it possible to perform in c++?

Function which creates thread:

```<code>void ReceiveMessage() {
    //std::promise<int> p;
    //auto f = p.get_future();
    char buf[1024];
    string usernput;
    int bytesReceived = 0;
    std::thread receiveMessage(&FactoredThread::ThreadFunction, *this);
    receiveMessage.detach();
    //pokusajporuke = f.get();
}
</code>```

ThreadFunction:

```<code>void ThreadFunction() {
    bytesReceived = 0;
    while (true) {
        bytesReceived = recv(sock, buf, 1024, 0);
        if (bytesReceived > 0) {
            string primljeniString = "";
            for (int i = 0; i < sizeof(buf); i++) {
                if (buf[i] != 0)
                {
                    primljeniString += buf[i];
                }
            }
            ZeroMemory(buf, 1024);
            pokusajporuke = primljeniString;

        }
    }
}
</code>```

So how to get "pokusajporuke" string for main thread?

答: Actually what I needed was global static variable. And then with another method from main thread I put that global variable into class property</p>

Title: Capture value from infinite thread c++

Body:
I have created a thread that is running parrallel with main thread. Both threads are doing something infinitely (both have while(true) statement). Main thread while(true) is creating game logic in frames, and second thread is receiveing messages from socket.

Is it possible to get string value of message received from second thread into main thread each frame without returning from second thread?
In c#, I would do it with method invoker but I didn't find anything helpful for c++. Is it possible to perform in c++?

Function which creates thread:

void ReceiveMessage() {
    //std::promise<int> p;
    //auto f = p.get_future();
    char buf[1024];
    string usernput;
    int bytesReceived = 0;
    std::thread receiveMessage(&FactoredThread::ThreadFunction, *this);
    receiveMessage.detach();
    //pokusajporuke = f.get();
}

ThreadFunction:

void ThreadFunction() {
    bytesReceived = 0;
    while (true) {
        bytesReceived = recv(sock, buf, 1024, 0);
        if (bytesReceived > 0) {
            string primljeniString = "";
            for (int i = 0; i < sizeof(buf); i++) {
                if (buf[i] != 0)
                {
                    primljeniString += buf[i];
                }
            }
            ZeroMemory(buf, 1024);
            pokusajporuke = primljeniString;

        }
    }
}

So how to get "pokusajporuke" string for main thread?


来源: stackexchange

问:
AngularJS ng-view commented out and no error happend
I want to use ng-view in angularjs. I created 1 html files in a folder named detail.html. And I want to load it into my index.html ng-view tag. But the ng-view is commented. And no error happend.enter image description here</p>

答:
It'll not show error if you comment out any code inside html. So if you want different views along with manipulation based on $routeParams here's working example.

http://embed.plnkr.co/A67EbeUHS0QgiJksvsel/

ContentLicense: CC BY-SA 3.0


问:
Cannot register the hard disk VBox. Why and how to solve?
I'm trying to clone a VBox Machine, But getting the below error.
But it does not give error with other source file.

```<code>IMedium medium = sVirtualBox.OpenMedium(oldMediumPath,
DeviceType.DeviceType_HardDisk, AccessMode.AccessMode_ReadOnly, 0);
</code>```

Exception:

```<code>{"Cannot register the hard disk 'C:\\Code\\Data.vdi.backup' {e99dab6a-1e34-4579-ae6b-4a7e520933c6} because a hard disk 'C:\\Code\\hd\\Data.vdi' with UUID {e99dab6a-1e34-4579-ae6b-4a7e520933c6} already exists"}
</code>```

答:
I had the same problem, and this solution from the VirtualBox forum worked for me: delete the VirtualBox.xml file (or rename it to VirtualBox.xml_YYYYMMDD). On my ubuntu host, this file lives in $HOME/.VirtualBox/

When I restarted the VirtualBox GUI, I just had to do Machine-->Add to add all my virtual machines back in.

Body:
I'm trying to clone a VBox Machine, But getting the below error.
But it does not give error with other source file.

IMedium medium = sVirtualBox.OpenMedium(oldMediumPath,
DeviceType.DeviceType_HardDisk, AccessMode.AccessMode_ReadOnly, 0);

Exception:

{"Cannot register the hard disk 'C:\\Code\\Data.vdi.backup' {e99dab6a-1e34-4579-ae6b-4a7e520933c6} because a hard disk 'C:\\Code\\hd\\Data.vdi' with UUID {e99dab6a-1e34-4579-ae6b-4a7e520933c6} already exists"}


问:
Execute a method of a different namspace by dynamic code in C# winforms
I am implementing a dynamic code execution in C# which allows users to write their own c# for that particular application.

I am using C# code compiler for executing the dynamic codes. The C# compiler reads the code file and construct the code in new namespace (a complete new code), compiles and runs it. In other view the base application host all these.

I have few methods that are present in host application that I want to be executed by the dynamic code. Is there any way by which the method of other namespace or application can be executed?

答:
In order for the dynamic code to be able to call methods on the static code, you have to provide the needed reference when you compile the dynamic code.

In more details:

Say you have a class called MyClass that you want to access from the dynamic code.
Put the MyClass class in a separate assembly, let's call it MyAssembly. When you compile the dynamic code, one of the properties of the ICodeCompiler allows you to provide assemblies as references. So you should provide typeof(MyClass).Assembly through that property.

Now, when you compile the code, it will be able to do stuff like:

```<code>MyClass.CallSomeMethod();
</code>```

Namespaces are not an issue here. You can ensure the dynamic code uses the full type name (e.g. MyNameSpace.MyClass, or you can generate a using MyNamespace; at the beginning of the dynamic code.

Finally, I join Richard's recommendation to define a clear interface which the dynamic code would be able to consume. You just have to provide the assembly containing this interface as a reference when you compile.

ContentLicense: CC BY-SA 2.5

Body:
In order for the dynamic code to be able to call methods on the static code, you have to provide the needed reference when you compile the dynamic code.

In more details:

Say you have a class called MyClass that you want to access from the dynamic code.
Put the MyClass class in a separate assembly, let's call it MyAssembly. When you compile the dynamic code, one of the properties of the ICodeCompiler allows you to provide assemblies as references. So you should provide typeof(MyClass).Assembly through that property.

Now, when you compile the code, it will be able to do stuff like:

MyClass.CallSomeMethod();

Namespaces are not an issue here. You can ensure the dynamic code uses the full type name (e.g. MyNameSpace.MyClass, or you can generate a using MyNamespace; at the beginning of the dynamic code.

Finally, I join Richard's recommendation to define a clear interface which the dynamic code would be able to consume. You just have to provide the assembly containing this interface as a reference when you compile.


问:
MVC modal popup from partial view - not working
I'm developing an MVC webpage, where I'm intending to do Create and Edit operations via a pop-up. So, the idea is I click on the 'Create' button, a modal-popup appears with all the model fields empty and allows user to input. In the same way, when user double clicks on any row, the row would open up for edit via the same pop-up, this time with the details filled from that row.

So, for reusage, I have decided to develop a single partial view(that would be the pop-up) and accept 'Model' as input.

My problem is, no matter what I do, I'm not able to make the partial view come up as pop-up. (Note: my main parent Index view would accpet input as List

Here is my code:

MY Index view:

```<code> @model List<TrackBuildConfig.DAL.Models.BuildModel>
 @{
    Layout = null;
  }

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/MyScript.js" type="text/javascript"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="jumbotron">
        <h1>Track Coverity and Nightly builds</h1>
        <h4>on your own!</h4>
    </div>
    <div class="container-fluid">
        <div class="row btn-group">

            @Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 }, new { @class = "btn btn-primary modal-link", id = "btnCreate"})
        </div>
        <div class="modal fade" aria-labelledby="ModalLabel" id="modal-container" role="dialog" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content" style="width: 500px !important; margin:10px !important">
                </div>
            </div>
        </div>
    </div>
</body>
</html>
</code>```

Script:

```<code> $(function () {
    $('body').on('click', '.modal-link', function (e) {
        e.preventDefault();
        $('#btnCreate').attr('data-toggle', 'modal');
        $('#btnCreate').attr('data-target', '#modal-container');
        $('#modal-container').modal('show');
        return true;
    });
    }
});
</code>```

Partial view _PartialModal.csHtml

```<code>@model TrackBuildConfig.DAL.Models.BuildModel
@{
    Layout = null;
}
<html>
<head>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/MyScript.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="">
        <div class="modal-header">
            <button type="button" class="close" aria-hidden="true" data-dismiss="modal">&times</button>
            <h4>Configure Coverity and Nightly builds</h4>
        </div>
        <div class="modal-body" style="height: 400px;">
            @using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
            {
                <div class="row">
                    <div class="form-group row">

                        <div class="col-sm-4">
                            @Html.Label("Stream name", new { @class = "control-label" })
                        </div>
                        <div class="col-sm-6">
                            @Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { @class = "col-sm-6 form-control", id = "ddlBuildLocation" })
                        </div>
                    </div>
                    <div class="form-group row">

                        <div class="col-sm-4">
                            @Html.Label("Build Location", new { @class = "control-label" })
                        </div>
                        <div class="col-sm-6">
                            @Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { @class = "col-sm-6 form-control", id = "ddlStreams" })
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-4">
                            <div class="checkbox">
                                <label>
                                    @Html.CheckBoxFor(m => m.IsCoverity)
                                    Enable Coverity
                                </label>
                            </div>
                        </div>
                        <div class="col-sm-8">
                            <div class="checkbox">
                                <label>
                                    @Html.CheckBoxFor(m => m.IsNightly)
                                    Enable Nightly build
                                </label>
                            </div>
                        </div>
                        <label style="color: red; font-weight: 300;" id="warningEnableBuild"></label>
                    </div>
                    <div class="form-group row">
                        @Html.Label("Email for Coverity", new { @class = "col-sm-4 control-label" })
                        <div class="col-sm-8" style="width: 100%">
                            @Html.TextAreaFor(m => m.EmailCoverity, new { @class = "form-control clsEmailCoverity", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailCoverity" })
                            @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                            <span class="help-block">Please add only comma separated addresses!</span>
                            <label style="color: red; font-weight: 300;" id="warningLabelCoverity"></label>
                        </div>
                    </div>
                    <div class="form-group row">
                        @Html.Label("Email for Nightly", new { @class = "col-sm-4 control-label" })
                        <div class="col-sm-8" style="width: 100%">
                            @Html.TextAreaFor(m => m.EmailNightly, new { @class = "form-control clsEmailNightly", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailNightly" })
                            @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                            <span class="help-block">Please add only comma separated addresses!</span>
                            <label style="color: red; font-weight: 300;" id="warningLabelNightly"></label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            }
        </div>
    </div>
</body>
</html>
</code>```

Controller methods:

```<code>public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        GetData getdata = new GetData();
        return View(getdata.GetDataFromTable());
    }

    [HttpPost]
    public ActionResult SaveData()
    {
        return View("Index");
    }

    //[HttpGet]
    public ActionResult SaveData(int configID)
    {
        BuildModel model = new BuildModel();

        PopulateBuildLocations();
        PopulateStreams();

        //Create
        if (configID != 0)
        {
            GetData getdata = new GetData();
            model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
        }
        else
        {
            model.BuildLocation = "";
            model.EmailCoverity = "";
            model.EmailNightly = "";
            model.IsCoverity = false;
            model.IsNightly = false;
        }

        return PartialView("_PartialModal", model);
    }

    public void PopulateBuildLocations()
    {
        string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
        ViewBag.BuildLocations = reportTypes.Split('|')
            .Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }

    public void PopulateStreams()
    {
        List<string> lstStreams = new List<string>();
        for (int i = 0; i < 6; i++)
        {
            lstStreams.Add("Stream " + i);
        }
        ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }
}
</code>```

This is the link I used as reference. Reference

答:
Please put my code in your visual studio and see that it works.

Controller/View Model/Classes:

```<code>public class BuildModel
{
    public string theBuildModel { get; set; }
    public int ConfigID { get; set; }
    public string BuildLocation { get; set; }
    public string EmailCoverity { get; set; }
    public string EmailNightly { get; set; }
    public bool IsCoverity { get; set; }
    public bool IsNightly { get; set; }
}

public class GetData
{
    public IList<BuildModel> GetDataFromTable()
    {
        IList<BuildModel> list = new List<BuildModel>();
        var buildModel1 = new BuildModel { theBuildModel = "one" };
        var buildModel2 = new BuildModel { theBuildModel = "two" };
        var buildModel3 = new BuildModel { theBuildModel = "three" };
        list.Add(buildModel1);
        list.Add(buildModel2);
        list.Add(buildModel3);
        return list;
    }
}

public class HomeController : Controller
{
    [HttpPost]
    public ViewResult SaveData(BuildModel buildModel)
    {
        GetData getdata = new GetData();
        var model = getdata.GetDataFromTable();
        return View("IndexStackOverflow", model);
    }

    [HttpGet]
    public PartialViewResult SaveData(int configID)
    {
        BuildModel model = new BuildModel();

        PopulateBuildLocations();
        PopulateStreams();

        //Create
        if (configID != 0)
        {
            GetData getdata = new GetData();
            model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
        }
        else
        {
            model.BuildLocation = "";
            model.EmailCoverity = "";
            model.EmailNightly = "";
            model.IsCoverity = false;
            model.IsNightly = false;
        }

        return PartialView("_PartialModal", model);
    }

    public void PopulateBuildLocations()
    {
        string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
        ViewBag.BuildLocations = reportTypes.Split('|')
            .Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }

    public void PopulateStreams()
    {
        List<string> lstStreams = new List<string>();
        for (int i = 0; i < 6; i++)
        {
            lstStreams.Add("Stream " + i);
        }
        ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }

    public ActionResult IndexStackOverflow()
    {
        GetData getdata = new GetData();
        return View(getdata.GetDataFromTable());
    }
</code>```

web.config:

```<code><appSettings>
        <add key="ddlStreams" value="text1|value1"/>
</appSettings>
</code>```

View:

```<code>@model List<Testy20161006.Controllers.BuildModel>

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>IndexStackOverflow</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    @*YOU MUST PUT THE NEXT LINE FOLLOWING IN YOUR CODE-NUGET IF YOU NEED TO GET THE SCRIPT*@
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
    <div class="jumbotron">
        <h1>This is part of the Main Page</h1>
        <h1>Partial View rendered in result</h1>
        <h1>Track Coverity and Nightly builds</h1>
        <h4>on your own!</h4>
    </div>
    <div class="container-fluid">
        <div class="row btn-group">

            @*@Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 },
                new { @class = "btn btn-primary modal-link", id = "btnCreate" })*@
            @using (Ajax.BeginForm("SaveData", "Home", new { configID = 0 },
                new AjaxOptions
                {
                    UpdateTargetId = "result",
                    InsertionMode = InsertionMode.Replace,
                    OnFailure = "error",
                    HttpMethod = "Get"
                }))
            {
                <input id="btnCreate" type="submit" value="Create a new record" class="btn btn-primary modal-link" />

            }
            <div id="result"></div>
        </div>
    </div>
</body>
</html>
</code>```

Partial View in shared folder:

```<code>@model Testy20161006.Controllers.BuildModel

<script type="text/javascript">
    $(function () {
        $('#myModal').modal('show');
    })
</script>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">Configure Coverity and Nightly builds</h4>
            </div>
            <div class="modal-body">
                <div class="modal-body" style="height: 400px;">
                    @using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
                    {
                        <div class="row">
                            <div class="form-group row">

                                <div class="col-sm-4">
                                    @Html.Label("Stream name", new { @class = "control-label" })
                                </div>
                                <div class="col-sm-6">
                                    @Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { @class = "col-sm-6 form-control", id = "ddlBuildLocation" })
                                </div>
                            </div>
                            <div class="form-group row">

                                <div class="col-sm-4">
                                    @Html.Label("Build Location", new { @class = "control-label" })
                                </div>
                                <div class="col-sm-6">
                                    @Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { @class = "col-sm-6 form-control", id = "ddlStreams" })
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-sm-4">
                                    <div class="checkbox">
                                        <label>
                                            @Html.CheckBoxFor(m => m.IsCoverity)
                                            Enable Coverity
                                        </label>
                                    </div>
                                </div>
                                <div class="col-sm-8">
                                    <div class="checkbox">
                                        <label>
                                            @Html.CheckBoxFor(m => m.IsNightly)
                                            Enable Nightly build
                                        </label>
                                    </div>
                                </div>
                                <label style="color: red; font-weight: 300;" id="warningEnableBuild"></label>
                            </div>
                            <div class="form-group row">
                                @Html.Label("Email for Coverity", new { @class = "col-sm-4 control-label" })
                                <div class="col-sm-8" style="width: 100%">
                                    @Html.TextAreaFor(m => m.EmailCoverity, new { @class = "form-control clsEmailCoverity", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailCoverity" })
                                    @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                                    <span class="help-block">Please add only comma separated addresses!</span>
                                    <label style="color: red; font-weight: 300;" id="warningLabelCoverity"></label>
                                </div>
                            </div>
                            <div class="form-group row">
                                @Html.Label("Email for Nightly", new { @class = "col-sm-4 control-label" })
                                <div class="col-sm-8" style="width: 100%">
                                    @Html.TextAreaFor(m => m.EmailNightly, new { @class = "form-control clsEmailNightly", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailNightly" })
                                    @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                                    <span class="help-block">Please add only comma separated addresses!</span>
                                    <label style="color: red; font-weight: 300;" id="warningLabelNightly"></label>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
                                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            </div>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Body:
I'm developing an MVC webpage, where I'm intending to do Create and Edit operations via a pop-up. So, the idea is I click on the 'Create' button, a modal-popup appears with all the model fields empty and allows user to input. In the same way, when user double clicks on any row, the row would open up for edit via the same pop-up, this time with the details filled from that row.

So, for reusage, I have decided to develop a single partial view(that would be the pop-up) and accept 'Model' as input.

My problem is, no matter what I do, I'm not able to make the partial view come up as pop-up. (Note: my main parent Index view would accpet input as List

Here is my code:

MY Index view:

 @model List<TrackBuildConfig.DAL.Models.BuildModel>
 @{
    Layout = null;
  }

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

Track Coverity and Nightly builds

on your own!

            @Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 }, new { @class = "btn btn-primary modal-link", id = "btnCreate"})

Script:

 $(function () {
    $('body').on('click', '.modal-link', function (e) {
        e.preventDefault();
        $('#btnCreate').attr('data-toggle', 'modal');
        $('#btnCreate').attr('data-target', '#modal-container');
        $('#modal-container').modal('show');
        return true;
    });
    }
});

Partial view _PartialModal.csHtml

@model TrackBuildConfig.DAL.Models.BuildModel
@{
    Layout = null;
}

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

            <button type="button" class="close" aria-hidden="true" data-dismiss="modal">&times</button>

Configure Coverity and Nightly builds

            @using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
            {

                            @Html.Label("Stream name", new { @class = "control-label" })

                            @Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { @class = "col-sm-6 form-control", id = "ddlBuildLocation" })

                            @Html.Label("Build Location", new { @class = "control-label" })

                            @Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { @class = "col-sm-6 form-control", id = "ddlStreams" })

                                    @Html.CheckBoxFor(m => m.IsCoverity)
                                    Enable Coverity

                                    @Html.CheckBoxFor(m => m.IsNightly)
                                    Enable Nightly build

                        @Html.Label("Email for Coverity", new { @class = "col-sm-4 control-label" })

                            @Html.TextAreaFor(m => m.EmailCoverity, new { @class = "form-control clsEmailCoverity", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailCoverity" })
                            @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                            Please add only comma separated addresses!

                        @Html.Label("Email for Nightly", new { @class = "col-sm-4 control-label" })

                            @Html.TextAreaFor(m => m.EmailNightly, new { @class = "form-control clsEmailNightly", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailNightly" })
                            @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                            Please add only comma separated addresses!

                        <button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

            }

Controller methods:

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        GetData getdata = new GetData();
        return View(getdata.GetDataFromTable());
    }

    [HttpPost]
    public ActionResult SaveData()
    {
        return View("Index");
    }

    //[HttpGet]
    public ActionResult SaveData(int configID)
    {
        BuildModel model = new BuildModel();

        PopulateBuildLocations();
        PopulateStreams();

        //Create
        if (configID != 0)
        {
            GetData getdata = new GetData();
            model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
        }
        else
        {
            model.BuildLocation = "";
            model.EmailCoverity = "";
            model.EmailNightly = "";
            model.IsCoverity = false;
            model.IsNightly = false;
        }

        return PartialView("_PartialModal", model);
    }

    public void PopulateBuildLocations()
    {
        string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
        ViewBag.BuildLocations = reportTypes.Split('|')
            .Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }

    public void PopulateStreams()
    {
        List<string> lstStreams = new List<string>();
        for (int i = 0; i < 6; i++)
        {
            lstStreams.Add("Stream " + i);
        }
        ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }
}

This is the link I used as reference. Reference

Body:
Please put my code in your visual studio and see that it works.

Controller/View Model/Classes:

public class BuildModel
{
    public string theBuildModel { get; set; }
    public int ConfigID { get; set; }
    public string BuildLocation { get; set; }
    public string EmailCoverity { get; set; }
    public string EmailNightly { get; set; }
    public bool IsCoverity { get; set; }
    public bool IsNightly { get; set; }
}

public class GetData
{
    public IList<BuildModel> GetDataFromTable()
    {
        IList<BuildModel> list = new List<BuildModel>();
        var buildModel1 = new BuildModel { theBuildModel = "one" };
        var buildModel2 = new BuildModel { theBuildModel = "two" };
        var buildModel3 = new BuildModel { theBuildModel = "three" };
        list.Add(buildModel1);
        list.Add(buildModel2);
        list.Add(buildModel3);
        return list;
    }
}

public class HomeController : Controller
{
    [HttpPost]
    public ViewResult SaveData(BuildModel buildModel)
    {
        GetData getdata = new GetData();
        var model = getdata.GetDataFromTable();
        return View("IndexStackOverflow", model);
    }

    [HttpGet]
    public PartialViewResult SaveData(int configID)
    {
        BuildModel model = new BuildModel();

        PopulateBuildLocations();
        PopulateStreams();

        //Create
        if (configID != 0)
        {
            GetData getdata = new GetData();
            model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
        }
        else
        {
            model.BuildLocation = "";
            model.EmailCoverity = "";
            model.EmailNightly = "";
            model.IsCoverity = false;
            model.IsNightly = false;
        }

        return PartialView("_PartialModal", model);
    }

    public void PopulateBuildLocations()
    {
        string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
        ViewBag.BuildLocations = reportTypes.Split('|')
            .Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }

    public void PopulateStreams()
    {
        List<string> lstStreams = new List<string>();
        for (int i = 0; i < 6; i++)
        {
            lstStreams.Add("Stream " + i);
        }
        ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }

    public ActionResult IndexStackOverflow()
    {
        GetData getdata = new GetData();
        return View(getdata.GetDataFromTable());
    }

web.config:

<appSettings>
        <add key="ddlStreams" value="text1|value1"/>
</appSettings>

View:

@model List<Testy20161006.Controllers.BuildModel>

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>IndexStackOverflow</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    @*YOU MUST PUT THE NEXT LINE FOLLOWING IN YOUR CODE-NUGET IF YOU NEED TO GET THE SCRIPT*@
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
    <div class="jumbotron">
        <h1>This is part of the Main Page</h1>
        <h1>Partial View rendered in result</h1>
        <h1>Track Coverity and Nightly builds</h1>
        <h4>on your own!</h4>
    </div>
    <div class="container-fluid">
        <div class="row btn-group">

            @*@Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 },
                new { @class = "btn btn-primary modal-link", id = "btnCreate" })*@
            @using (Ajax.BeginForm("SaveData", "Home", new { configID = 0 },
                new AjaxOptions
                {
                    UpdateTargetId = "result",
                    InsertionMode = InsertionMode.Replace,
                    OnFailure = "error",
                    HttpMethod = "Get"
                }))
            {
                <input id="btnCreate" type="submit" value="Create a new record" class="btn btn-primary modal-link" />

            }
            <div id="result"></div>
        </div>
    </div>
</body>
</html>

Partial View in shared folder:

@model Testy20161006.Controllers.BuildModel

<script type="text/javascript">
    $(function () {
        $('#myModal').modal('show');
    })
</script>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">Configure Coverity and Nightly builds</h4>
            </div>
            <div class="modal-body">
                <div class="modal-body" style="height: 400px;">
                    @using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
                    {
                        <div class="row">
                            <div class="form-group row">

                                <div class="col-sm-4">
                                    @Html.Label("Stream name", new { @class = "control-label" })
                                </div>
                                <div class="col-sm-6">
                                    @Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { @class = "col-sm-6 form-control", id = "ddlBuildLocation" })
                                </div>
                            </div>
                            <div class="form-group row">

                                <div class="col-sm-4">
                                    @Html.Label("Build Location", new { @class = "control-label" })
                                </div>
                                <div class="col-sm-6">
                                    @Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { @class = "col-sm-6 form-control", id = "ddlStreams" })
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-sm-4">
                                    <div class="checkbox">
                                        <label>
                                            @Html.CheckBoxFor(m => m.IsCoverity)
                                            Enable Coverity
                                        </label>
                                    </div>
                                </div>
                                <div class="col-sm-8">
                                    <div class="checkbox">
                                        <label>
                                            @Html.CheckBoxFor(m => m.IsNightly)
                                            Enable Nightly build
                                        </label>
                                    </div>
                                </div>
                                <label style="color: red; font-weight: 300;" id="warningEnableBuild"></label>
                            </div>
                            <div class="form-group row">
                                @Html.Label("Email for Coverity", new { @class = "col-sm-4 control-label" })
                                <div class="col-sm-8" style="width: 100%">
                                    @Html.TextAreaFor(m => m.EmailCoverity, new { @class = "form-control clsEmailCoverity", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailCoverity" })
                                    @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                                    <span class="help-block">Please add only comma separated addresses!</span>
                                    <label style="color: red; font-weight: 300;" id="warningLabelCoverity"></label>
                                </div>
                            </div>
                            <div class="form-group row">
                                @Html.Label("Email for Nightly", new { @class = "col-sm-4 control-label" })
                                <div class="col-sm-8" style="width: 100%">
                                    @Html.TextAreaFor(m => m.EmailNightly, new { @class = "form-control clsEmailNightly", @placeholder = "Enter some value", @onkeyup = "return true;", @rows = "5", id = "txtEmailNightly" })
                                    @*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*@
                                    <span class="help-block">Please add only comma separated addresses!</span>
                                    <label style="color: red; font-weight: 300;" id="warningLabelNightly"></label>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
                                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            </div>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>


问:
Error when trying to use pubnub
Good day all, I've been developing an office chat app in which i plan on using the Codename one Pubnub lib, but whenever i try launching the app via the simulator i get this error: "Error:(1044, 23) java: cannot access org.json.JSONArray class file for org.json.JSONArray not found". And i didn't make use of JSON in my code. Really don't.
I have tried deleting and redownloading the JSON lib, still no positive result.
All my libs are up to date. A little direction on what to do will be appreciated. Thanks all</p>

答: The pubnub library has a dependency on their version of the JSON lib and you need to install that by its side for things to function. Notice this isn't our version of the JSON library but a specific version for pubnub.</p>

Title: Error when trying to use pubnub


问:
Create an empty object in JavaScript with {} or new Object()?
There are two different ways to create an empty object in JavaScript:

```<code>var objectA = {}
var objectB = new Object()
</code>```

Is there any difference in how the script engine handles them? Is there any reason to use one over the other?

Similarly it is also possible to create an empty array using different syntax:

```<code>var arrayA = []
var arrayB = new Array()
</code>```

答:
OK, there are just 2 different ways to do the same thing! One called object literal and the other one is a function constructor!

But read on, there are couple of things I'd like to share:

Using {} makes your code more readable, while creating instances of Object or other built-in functions not recommended...

Also, Object function gets parameters as it's a function, like Object(params)... but {} is pure way to start an object in JavaScript...

Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...

While Object in Javascript can be almost anything, {} only points to javascript objects, for the test how it works, do below in your javascript code or console:

```<code>var n = new Object(1); //Number {[[PrimitiveValue]]: 1}
</code>```

Surprisingly, it's creating a Number!

```<code>var a = new Object([1,2,3]); //[1, 2, 3]
</code>```

And this is creating a Array!

```<code>var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}
</code>```

and this weird result for String!

So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {} is better in my experience!

OwnerDisplayName: Jonas Pegerfalk

Body:
There are two different ways to create an empty object in JavaScript:

var objectA = {}
var objectB = new Object()

Is there any difference in how the script engine handles them? Is there any reason to use one over the other?

Similarly it is also possible to create an empty array using different syntax:

var arrayA = []
var arrayB = new Array()

Body:
OK, there are just 2 different ways to do the same thing! One called object literal and the other one is a function constructor!

But read on, there are couple of things I'd like to share:

Using {} makes your code more readable, while creating instances of Object or other built-in functions not recommended...

Also, Object function gets parameters as it's a function, like Object(params)... but {} is pure way to start an object in JavaScript...

Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...

While Object in Javascript can be almost anything, {} only points to javascript objects, for the test how it works, do below in your javascript code or console:

var n = new Object(1); //Number {[[PrimitiveValue]]: 1}

Surprisingly, it's creating a Number!

var a = new Object([1,2,3]); //[1, 2, 3]

And this is creating a Array!

var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}

and this weird result for String!

So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {} is better in my experience!


问:
What are the best use cases for Akka framework
I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.

Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)

答:
We are using Akka in a large scale Telco project (unfortunately I can't disclose a lot of details).
Akka actors are deployed and accessed remotely by a web application. In this way, we have a simplified RPC model based on Google protobuffer and we achieve parallelism using Akka Futures.
So far, this model has worked brilliantly. One note: we are using the Java API.</p>

ContentLicense: CC BY-SA 4.0


问:
how to use android sliding up panel
I have downloaded the umano sliding up panel from https://github.com/umano/AndroidSlidingUpPanel

Imported it into the workspace and added reference to it in my project.

Next I copied and pasted the following into a new layout -

Here is the Code :

```<code><com.sothree.slidinguppanel.SlidingUpPanelLayout
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:panelHeight="68dp"
    sothree:shadowHeight="4dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Main Content"
        android:textSize="16sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|top"
        android:text="The Awesome Sliding Up Panel"
        android:textSize="16sp" />
</com.sothree.slidinguppanel.SlidingUpPanelLayout>
</code>```

But I am getting an error unbound prefix.

What is wrong in my code?

And How can i fix this ?

答:
You can use BottomSheetBehavior from android support library from google as alternative. compile 'com.android.support:design:25.0.0'
You can checkout my sample https://github.com/andrisasuke/Android-SlidingUp-Panel

Title: how to use android sliding up panel

Body:
I have downloaded the umano sliding up panel from https://github.com/umano/AndroidSlidingUpPanel

Imported it into the workspace and added reference to it in my project.

Next I copied and pasted the following into a new layout -

Here is the Code :

<com.sothree.slidinguppanel.SlidingUpPanelLayout
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:panelHeight="68dp"
    sothree:shadowHeight="4dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Main Content"
        android:textSize="16sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|top"
        android:text="The Awesome Sliding Up Panel"
        android:textSize="16sp" />
</com.sothree.slidinguppanel.SlidingUpPanelLayout>

But I am getting an error unbound prefix.

What is wrong in my code?

And How can i fix this ?


问:
Why isn't this Python object property permanently overwritten?
I'm working on a Linked List partitioning problem using Python. The goal is to partition a linked list into 2 segments, the first where values are less than x, and the second where values are equal to or greater than x.

I'm confused right at the first line of the partition function:

```<code>current = ll.tail = ll.head
</code>```

Why doesn't this line permanently overwrite the value of ll.tail? I thought Python was a language where objects pass by reference. ll, ll.head and ll.tail are all objects, so my expectation is that this line would cause use to lose the value stored at ll.tail.

ll.tail stores a value that's necessary for the function's output, and it's still present in the function's output (and the output is correct), but I don't understand how.

Partition.py:

```<code>from LinkedList import LinkedList

def partition(ll, x):
    current = ll.tail = ll.head

    while current:
        nextNode = current.next
        current.next = None
        if current.value < x:
            current.next = ll.head
            ll.head = current
        else:
            ll.tail.next = current
            ll.tail = current
        current = nextNode

    # Error check in case all nodes are less than x
    if ll.tail.next is not None:
        ll.tail.next = None

ll = LinkedList()
ll.generate(10, 0, 99)
print(ll)
partition(ll, ll.head.value)
print(ll)
</code>```

LinkedList.py:

```<code>from random import randint

class LinkedListNode:

    def __init__(self, value, nextNode=None, prevNode=None):
        self.value = value
        self.next = nextNode
        self.prev = prevNode

    def __str__(self):
        return str(self.value)

class LinkedList:

    def __init__(self, values=None):
        self.head = None
        self.tail = None
        if values is not None:
            self.add_multiple(values)

    def __iter__(self):
        current = self.head
        while current:
            yield current
            current = current.next

    def __str__(self):
        values = [str(x) for x in self]
        return ' -> '.join(values)

    def __len__(self):
        result = 0
        node = self.head
        while node:
            result += 1
            node = node.next
        return result

    def add(self, value):
        if self.head is None:
            self.tail = self.head = LinkedListNode(value)
        else:
            self.tail.next = LinkedListNode(value)
            self.tail = self.tail.next
        return self.tail

    def add_to_beginning(self, value):
        if self.head is None:
            self.tail = self.head = LinkedListNode(value)
        else:
            self.head = LinkedListNode(value, self.head)
        return self.head

    def add_multiple(self, values):
        for v in values:
            self.add(v)

    def generate(self, n, min_value, max_value):
        self.head = self.tail = None
        for i in range(n):
            self.add(randint(min_value, max_value))
        return self
</code>```

答:
The line you think has a problem is not your problem. This code shows why:

```<code>def checker(ll):
    current = ll.tail = ll.head
    print(current)
    print(ll.tail)
    print(ll.head)
    return
ll = LinkedList()
ll.generate(10,0,99)
print(ll)
checker(ll)
print(ll.tail)
print(ll.head)
print("Some other interesting behavior:")
ll.head.value = -1
print(ll.head)
print(ll.tail)
ll.head = -2
print(ll.head)
print(ll.tail)
</code>```

Using your own code for the LL gives:

```<code>73 -> 39 -> 14 -> 5 -> 47 -> 29 -> 14 -> 66 -> 70 -> 9
73
73
73
73
73
Some other interesting behavior:
-1
-1
-2
-1
</code>```

so the linked list which you pass does change when modified within a function. Also note the behavior at the end: ll.tail is now pointing to where ll.head was pointing to, not ll.head itself. This is different from C's pointer references.

This implies that your algorithm is not doing what you expect. particularly I would focus on when the loop ends and the order of swapping it performs (generally that's where most errors with LL activities seem to occur).

General debugging techniques like unit-testing a potential function (or anticipated error cause) are really important programming skills. If you think something doesn't (or does) work then test it. It'll narrow the scope of your error search and help others answer your question more quickly if you can't figure it out yourself.

Body:
I'm working on a Linked List partitioning problem using Python. The goal is to partition a linked list into 2 segments, the first where values are less than x, and the second where values are equal to or greater than x.

I'm confused right at the first line of the partition function:

current = ll.tail = ll.head

Why doesn't this line permanently overwrite the value of ll.tail? I thought Python was a language where objects pass by reference. ll, ll.head and ll.tail are all objects, so my expectation is that this line would cause use to lose the value stored at ll.tail.

ll.tail stores a value that's necessary for the function's output, and it's still present in the function's output (and the output is correct), but I don't understand how.

Partition.py:

from LinkedList import LinkedList

def partition(ll, x):
    current = ll.tail = ll.head

    while current:
        nextNode = current.next
        current.next = None
        if current.value < x:
            current.next = ll.head
            ll.head = current
        else:
            ll.tail.next = current
            ll.tail = current
        current = nextNode

    # Error check in case all nodes are less than x
    if ll.tail.next is not None:
        ll.tail.next = None

ll = LinkedList()
ll.generate(10, 0, 99)
print(ll)
partition(ll, ll.head.value)
print(ll)

LinkedList.py:

from random import randint

class LinkedListNode:

    def __init__(self, value, nextNode=None, prevNode=None):
        self.value = value
        self.next = nextNode
        self.prev = prevNode

    def __str__(self):
        return str(self.value)

class LinkedList:

    def __init__(self, values=None):
        self.head = None
        self.tail = None
        if values is not None:
            self.add_multiple(values)

    def __iter__(self):
        current = self.head
        while current:
            yield current
            current = current.next

    def __str__(self):
        values = [str(x) for x in self]
        return ' -> '.join(values)

    def __len__(self):
        result = 0
        node = self.head
        while node:
            result += 1
            node = node.next
        return result

    def add(self, value):
        if self.head is None:
            self.tail = self.head = LinkedListNode(value)
        else:
            self.tail.next = LinkedListNode(value)
            self.tail = self.tail.next
        return self.tail

    def add_to_beginning(self, value):
        if self.head is None:
            self.tail = self.head = LinkedListNode(value)
        else:
            self.head = LinkedListNode(value, self.head)
        return self.head

    def add_multiple(self, values):
        for v in values:
            self.add(v)

    def generate(self, n, min_value, max_value):
        self.head = self.tail = None
        for i in range(n):
            self.add(randint(min_value, max_value))
        return self

Body:
The line you think has a problem is not your problem. This code shows why:

def checker(ll):
    current = ll.tail = ll.head
    print(current)
    print(ll.tail)
    print(ll.head)
    return
ll = LinkedList()
ll.generate(10,0,99)
print(ll)
checker(ll)
print(ll.tail)
print(ll.head)
print("Some other interesting behavior:")
ll.head.value = -1
print(ll.head)
print(ll.tail)
ll.head = -2
print(ll.head)
print(ll.tail)

Using your own code for the LL gives:

73 -> 39 -> 14 -> 5 -> 47 -> 29 -> 14 -> 66 -> 70 -> 9
73
73
73
73
73
Some other interesting behavior:
-1
-1
-2
-1

so the linked list which you pass does change when modified within a function. Also note the behavior at the end: ll.tail is now pointing to where ll.head was pointing to, not ll.head itself. This is different from C's pointer references.

This implies that your algorithm is not doing what you expect. particularly I would focus on when the loop ends and the order of swapping it performs (generally that's where most errors with LL activities seem to occur).

General debugging techniques like unit-testing a potential function (or anticipated error cause) are really important programming skills. If you think something doesn't (or does) work then test it. It'll narrow the scope of your error search and help others answer your question more quickly if you can't figure it out yourself.


问:
Linq return child entities not used in parent entities
I have the case whereby I have the following entities in my model.

```<code>public class Permission
{
  public int ID { get; set; }
  public Operation Operation { get; set; }
}

public class Operation
{
  public int ID { get; set; }
  public string Name { get; set; }
}
</code>```

The way my repository is set up I need to query the OperationRepository to find all those operations that have not been used in a permission. My EF Operation Entity has a navigation property back to the Permissions as an EntityCollection as below:

```<code>public partial class Operation : EntityObject
{
    public EntityCollection<Permission> Permissions
    {
        get; set;
    }
}
</code>```

The method in my OperationRepository is:

```<code>public IEnumerable<IOperation> FindUnassigned()
{
    //query here
}
</code>```

答:
Filter your Operations where the navigation property `Permissions doesn't have any elements

```<code>.Where(p => p.Permissions.Count() == 0)
</code>```

Body:
I have the case whereby I have the following entities in my model.

public class Permission
{
  public int ID { get; set; }
  public Operation Operation { get; set; }
}

public class Operation
{
  public int ID { get; set; }
  public string Name { get; set; }
}

The way my repository is set up I need to query the OperationRepository to find all those operations that have not been used in a permission. My EF Operation Entity has a navigation property back to the Permissions as an EntityCollection as below:

public partial class Operation : EntityObject
{
    public EntityCollection<Permission> Permissions
    {
        get; set;
    }
}

The method in my OperationRepository is:

public IEnumerable<IOperation> FindUnassigned()
{
    //query here
}

Body:
Filter your Operations where the navigation property `Permissions doesn't have any elements

.Where(p => p.Permissions.Count() == 0)


问:
Clone a single webpage (with images) and save to index.html
I want to clone a single webpage with all the images and no links in the html. I can achieve this with  wget -E -H -k -K -p {url} however this pulls down the webpage with a full structure and you have to navigate to the html file to display the contents. This makes it inconsistent in where the html file to display the webpage would be.

I can also do this wget --no-check-certificate -O index.html -c -k {url} however this keeps the links to images and doesn't make the webpage truly local as it has to go out to the web to display the page properly.

Is there any way to clone a single webpage and spit out an index.html with the images linked locally?

PS: I am using wget through a python script that makes changes to webpages so having an index.html is neccesary for me.  I am interested in other methods if there are better ones.

EDIT:

So it seems I haven't explain myself well but a bit background info on this project is I am working on a proof of concept for school on an automated phishing script which is supposed to clone a webpage, modify a few action tags and be placed on a local web server so that a user can navigate to it and the page will display correctly. Previously using the -O worked fine for my but since I am now incorporating DNS spoofing into my project the webpage cant have any links pointing externally as they will just end up getting rerouted to my internal webserver and the webpage will look broken. That is why I need to have just the information necessary for the single webpage to be displayed correctly but also have it predictable so that I am able to be sure that when i navigate to the directory I cloned the website from the webpage will be displayed (with proper links to images,css etc..)

答: use this wget facebook.com --domains website.org --no-parent --page-requisites --html-extension --convert-links if you wanna download all the entire website add --recursive after the web pages


问:
How to properly use bootstrap push and pull
I've been trying to re-order my bootstrap columns when in mobile view but my code is just not working. Most probably because I am doing something incorrect.

Here is my markup:

```<code><div class="container">
    <div class="row text-center">
        <div class="col-12">
            <h2 class="mb-lg-4 mb-sm-3">Early Stages</h2>
        </div>
        <div class="col-md-7 col-sm-push-5">
            <p>Also known as 'the Poor Fellow-Soldiers of Christ and of the Temple of Solomon', the Knights Templars were originally founded circa 1120 CE, by Hugues de Payens, as a means to protect Christian pilgrims to the Holy Land. It was originally intended that nine Templars would protect the pilgrims.</p>
        </div>
        <div class="col-md-5 col-sm-push-7">
            Image Here
        </div>
    </div><!--/row-->
</div>
</code>```

What I am trying to do is essentially make the "Image Here" section go above the "also known as the poor etc." section when in mobile view (col-sm). I looked at Bootstraps guide but I think I am understanding it incorrectly, can someone show me how its done?

Thanks in advance

答:
Try this HTML

```<code><div class="container">

  <div class="row text-center">
    <div class="col-12">
      <h2 class="mb-lg-4 mb-sm-3">Early Stages</h2>
    </div>

    <div class="col-md-5 col-sm-push-7">
      Image Here
    </div>
    <div class="col-md-7 col-sm-pull-5">
      <p>Also known as 'the Poor Fellow-Soldiers of Christ and of the Temple of Solomon', the Knights Templars were originally founded circa 1120 CE, by Hugues de Payens, as a means to protect Christian pilgrims to the Holy Land. It was originally
        intended that nine Templars would protect the pilgrims.</p>
    </div>
  </div>
  <!--/row-->
</code>```

Link for reference

hope this helps..

Body:
I've been trying to re-order my bootstrap columns when in mobile view but my code is just not working. Most probably because I am doing something incorrect.

Here is my markup:

Early Stages

Also known as 'the Poor Fellow-Soldiers of Christ and of the Temple of Solomon', the Knights Templars were originally founded circa 1120 CE, by Hugues de Payens, as a means to protect Christian pilgrims to the Holy Land. It was originally intended that nine Templars would protect the pilgrims.

            Image Here

What I am trying to do is essentially make the "Image Here" section go above the "also known as the poor etc." section when in mobile view (col-sm). I looked at Bootstraps guide but I think I am understanding it incorrectly, can someone show me how its done?

Thanks in advance

Body:
Try this HTML

<div class="container">

  <div class="row text-center">
    <div class="col-12">
      <h2 class="mb-lg-4 mb-sm-3">Early Stages</h2>
    </div>

    <div class="col-md-5 col-sm-push-7">
      Image Here
    </div>
    <div class="col-md-7 col-sm-pull-5">
      <p>Also known as &apos;the Poor Fellow-Soldiers of Christ and of the Temple of Solomon&apos;, the Knights Templars were originally founded circa 1120 CE, by Hugues de Payens, as a means to protect Christian pilgrims to the Holy Land. It was originally
        intended that nine Templars would protect the pilgrims.</p>
    </div>
  </div>
  <!--/row-->

Link for reference

hope this helps..


问:
GAE with IAP (Identity Aware Proxy) and mail inboundservice
I have a Java appengine standard project which handle incoming mails via activated inbound-service with out any problems.

If I configure and activate the IAP (identity aware proxy) the appengine projects still works fine with out any problems.

But now the incoming mail service rejects every incoming mail.

```<code>Message not delivered

There was a problem delivering your message to
<recipient>@<projectid>.appspotmail.com. See the technical details
below.

Final-Recipient: rfc822; [user]@[projectid].appspotmail.com
Action: failed
Status: 5.0.0
Last-Attempt-Date: Thu, 06 Jul 2017 07:46:33 -0700 (PDT)
</code>```

What I have forgotten? Thanks for any hint!!

----------------------------------------------

appengine-web.xml

```<code><inbound-services>
        <service>mail</service>
</inbound-services>
</code>```

web.xml

```<code><servlet>
        <servlet-name>MailhandlerServlet</servlet-name>
        <servlet-class>com.company.appengine.gae.mail.MailHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>MailhandlerServlet</servlet-name>
        <!-- /_ah/mail/* matches all email addressed to the app -->
        <url-pattern>/_ah/mail/*</url-pattern>
</servlet-mapping>
</code>```

答:
I just tried the App Engine Hello World example as the base and modified to accept incoming emails and it works for me. The destination email address format I used is recipient-user@PROJECT_ID.appspotmail.com

I would recommend you verify debugging using a development app server and verify the following:

Add some logging in your mail handler servlet when it gets the request. You can look at the example I've posted for some pointers.

Go to http://localhost:8080/_ah/admin/inboundmail to access the Inbound Mail page in Development Console and send a test email from there.

If you look at the server logs, you should see the logs from your servlet (i.e. the ones you added in Step 1) if the configuration is correct.

Once you've confirmed everything works with the development app server, deploy your app to App Engine and test by sending a real email and look again at the Service logs through Stackdriver Logging. You should see 200 responses for such incoming mail requests in addition to the logs you added in Step 1.

Also note that many email providers will start throttling mails to a destination email ID if there is no successful response after few retries. This is another good reason to verify using a development app server first.

Here is the diff from the App Engine Hello World example where I got it working:

pom.xml

```<code>--- a/appengine/helloworld/pom.xml
+++ b/appengine/helloworld/pom.xml
@@ -33,6 +33,11 @@ Copyright 2015 Google Inc.
       <version>2.5</version>
       <scope>provided</scope>
     </dependency>
+    <dependency>
+        <groupId>javax.mail</groupId>
+        <artifactId>mail</artifactId>
+        <version>1.5.0-b01</version>
+    </dependency>
   </dependencies>
   <build>
     <!-- for hot reload of the web application -->
</code>```

src/main/java/com/example/appengine/helloworld/MailHandlerServlet.java

```<code>--- /dev/null
+++ b/appengine/helloworld/src/main/java/com/example/appengine/helloworld/MailHandlerServlet.java
@@ -0,0 +1,36 @@
+package com.example.appengine.helloworld;
+
+import java.io.IOException;
+import java.util.logging.Logger;
+import java.util.logging.Level;
+import java.util.Properties;
+
+import javax.mail.Address;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.internet.MimeMessage;
+
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class MailHandlerServlet extends HttpServlet {
+
+  private static final Logger log = Logger.getLogger(MailHandlerServlet.class.getName());
+
+  @Override
+  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+    Properties props = new Properties();
+    Session session = Session.getDefaultInstance(props, null);
+    try {
+      MimeMessage message = new MimeMessage(session, req.getInputStream());
+      log.info("Received mail message content type: " + message.getContentType());
+      for (Address addr : message.getFrom()) {
+        log.info("Received mail from: " + addr);
+      }
+    } catch (MessagingException e) {
+      log.log(Level.SEVERE, "Failed to handle incoming message:", e);
+    }
+    // ...
+  }
+}
</code>```

src/main/webapp/WEB-INF/appengine-web.xml

```<code>--- a/appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml
+++ b/appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml
@@ -13,8 +13,11 @@
 -->
 <!-- [START config] -->
 <appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
   <application>YOUR-PROJECT-ID</application>
   <version>YOUR-VERSION-ID</version>
   <threadsafe>true</threadsafe>
+  <inbound-services>
+    <service>mail</service>
+  </inbound-services>
 </appengine-web-app>
 <!-- [END config] -->
</code>```

src/main/webapp/WEB-INF/web.xml

```<code>--- a/appengine/helloworld/src/main/webapp/WEB-INF/web.xml
+++ b/appengine/helloworld/src/main/webapp/WEB-INF/web.xml
@@ -7,8 +7,17 @@
     <servlet-name>hello</servlet-name>
     <servlet-class>com.example.appengine.helloworld.HelloServlet</servlet-class>
   </servlet>
+  <servlet>
+    <servlet-name>mailhandler</servlet-name>
+    <servlet-class>com.example.appengine.helloworld.MailHandlerServlet</servlet-class>
+  </servlet>
   <servlet-mapping>
     <servlet-name>hello</servlet-name>
     <url-pattern>/</url-pattern>
   </servlet-mapping>
+  <servlet-mapping>
+    <servlet-name>mailhandler</servlet-name>
+    <!-- /_ah/mail/* matches all email addressed to the app -->
+    <url-pattern>/_ah/mail/*</url-pattern>
+  </servlet-mapping>
 </web-app>
</code>```

Body:
I have a Java appengine standard project which handle incoming mails via activated inbound-service with out any problems.

If I configure and activate the IAP (identity aware proxy) the appengine projects still works fine with out any problems.

But now the incoming mail service rejects every incoming mail.

Message not delivered

There was a problem delivering your message to
<recipient>@<projectid>.appspotmail.com. See the technical details
below.

Final-Recipient: rfc822; [user]@[projectid].appspotmail.com
Action: failed
Status: 5.0.0
Last-Attempt-Date: Thu, 06 Jul 2017 07:46:33 -0700 (PDT)

What I have forgotten? Thanks for any hint!!

----------------------------------------------

appengine-web.xml

<inbound-services>
        <service>mail</service>
</inbound-services>

web.xml

<servlet>
        <servlet-name>MailhandlerServlet</servlet-name>
        <servlet-class>com.company.appengine.gae.mail.MailHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>MailhandlerServlet</servlet-name>

        <url-pattern>/_ah/mail/*</url-pattern>
</servlet-mapping>

Body:
I just tried the App Engine Hello World example as the base and modified to accept incoming emails and it works for me. The destination email address format I used is recipient-user@PROJECT_ID.appspotmail.com

I would recommend you verify debugging using a development app server and verify the following:

Add some logging in your mail handler servlet when it gets the request. You can look at the example I've posted for some pointers.

Go to http://localhost:8080/_ah/admin/inboundmail to access the Inbound Mail page in Development Console and send a test email from there.

If you look at the server logs, you should see the logs from your servlet (i.e. the ones you added in Step 1) if the configuration is correct.

Once you've confirmed everything works with the development app server, deploy your app to App Engine and test by sending a real email and look again at the Service logs through Stackdriver Logging. You should see 200 responses for such incoming mail requests in addition to the logs you added in Step 1.

Also note that many email providers will start throttling mails to a destination email ID if there is no successful response after few retries. This is another good reason to verify using a development app server first.

Here is the diff from the App Engine Hello World example where I got it working:

pom.xml

--- a/appengine/helloworld/pom.xml
+++ b/appengine/helloworld/pom.xml
@@ -33,6 +33,11 @@ Copyright 2015 Google Inc.
       <version>2.5</version>
       <scope>provided</scope>
     </dependency>
+    <dependency>
+        <groupId>javax.mail</groupId>
+        <artifactId>mail</artifactId>
+        <version>1.5.0-b01</version>
+    </dependency>
   </dependencies>
   <build>
     <!-- for hot reload of the web application -->

src/main/java/com/example/appengine/helloworld/MailHandlerServlet.java

--- /dev/null
+++ b/appengine/helloworld/src/main/java/com/example/appengine/helloworld/MailHandlerServlet.java
@@ -0,0 +1,36 @@
+package com.example.appengine.helloworld;
+
+import java.io.IOException;
+import java.util.logging.Logger;
+import java.util.logging.Level;
+import java.util.Properties;
+
+import javax.mail.Address;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.internet.MimeMessage;
+
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class MailHandlerServlet extends HttpServlet {
+
+  private static final Logger log = Logger.getLogger(MailHandlerServlet.class.getName());
+
+  @Override
+  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+    Properties props = new Properties();
+    Session session = Session.getDefaultInstance(props, null);
+    try {
+      MimeMessage message = new MimeMessage(session, req.getInputStream());
+      log.info("Received mail message content type: " + message.getContentType());
+      for (Address addr : message.getFrom()) {
+        log.info("Received mail from: " + addr);
+      }
+    } catch (MessagingException e) {
+      log.log(Level.SEVERE, "Failed to handle incoming message:", e);
+    }
+    // ...
+  }
+}

src/main/webapp/WEB-INF/appengine-web.xml

--- a/appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml
+++ b/appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml
@@ -13,8 +13,11 @@
 -->
 <!-- [START config] -->
 <appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
   <application>YOUR-PROJECT-ID</application>
   <version>YOUR-VERSION-ID</version>
   <threadsafe>true</threadsafe>
+  <inbound-services>
+    <service>mail</service>
+  </inbound-services>
 </appengine-web-app>
 <!-- [END config] -->

src/main/webapp/WEB-INF/web.xml

--- a/appengine/helloworld/src/main/webapp/WEB-INF/web.xml
+++ b/appengine/helloworld/src/main/webapp/WEB-INF/web.xml
@@ -7,8 +7,17 @@
     <servlet-name>hello</servlet-name>
     <servlet-class>com.example.appengine.helloworld.HelloServlet</servlet-class>
   </servlet>
+  <servlet>
+    <servlet-name>mailhandler</servlet-name>
+    <servlet-class>com.example.appengine.helloworld.MailHandlerServlet</servlet-class>
+  </servlet>
   <servlet-mapping>
     <servlet-name>hello</servlet-name>
     <url-pattern>/</url-pattern>
   </servlet-mapping>
+  <servlet-mapping>
+    <servlet-name>mailhandler</servlet-name>
+    <!-- /_ah/mail/* matches all email addressed to the app -->
+    <url-pattern>/_ah/mail/*</url-pattern>
+  </servlet-mapping>
 </web-app>


问:
Create Pages Automatically
Is there any method in Php by which I can create a page automatically based on a predefined template. Like if we create a new post in blogger it automatically creates page for that post with the name of that post, like this one:

http://learntoflash.blogspot.com/2009/12/exit-button-in-flash.html

Here Exit Button In Flash is the name of my post I have written and an automatic page is created for it.

Or like here on this website if we ask a question it automatically creates a page for that question. I want to know can I achieve this in Php or anything close to this ?

答: This is acheived by using mod_rewrite. A good place to look for inspiration is the .htaccess used in Wordpress.</p>

Title: Create Pages Automatically


问:
Implementing a function similar to EXCEL Lookup in VB.net
I have a lot of code that requires random numbers to be generated and then options selected based on percentage.  I have it working without issue by simply using an implementation of the Mersenne Twister and generating a double between 0 and 100, then assigning results by percentage with select case.  It works fine, but it's very cumbersome and truth be told, I'm tired of continuously writing this out everytime.

I'd much prefer something similar to EXCEL's Lookup Function where you give two arrays such as LOOKUP(5, {1,10,20,30,40}, {"1-10", "11-20", "21-30","31-40"})

Which in this case would return: "1-10" since 5 is between 1-10.

Is there an easy way to implement a C#/VB.Net version of this using LINQ?  I'm sure there must be but I'm at a loss for how to implement something like this.  It would be far easier to write this one line of code than long select case statements.

If there is a better way than implementing an equivalent of an EXCEL lookup function, I'd love to know that as well...

答:
There are few ways to do it with LINQ or Array/List .FindIndex, but integer division is probably the best:</p>

```<code>Dim d = 10.1, a = {1, 10, 20, 30, 40}, b = {"1-10", "11-20", "21-30", "31-40"}

Dim s1 = b(a.Count(Function(i) i <= d) - 1)

Dim s2 = b(Array.FindLastIndex(a, Function(i) i <= d))

Dim s3 = $"{d - d Mod 10 + 1}-{d - d Mod 10 + 10}"      ' "11-20"
</code>```

Body:
There are few ways to do it with LINQ or Array/List .FindIndex, but integer division is probably the best:

Dim d = 10.1, a = {1, 10, 20, 30, 40}, b = {"1-10", "11-20", "21-30", "31-40"}

Dim s1 = b(a.Count(Function(i) i <= d) - 1)

Dim s2 = b(Array.FindLastIndex(a, Function(i) i <= d))

Dim s3 = $"{d - d Mod 10 + 1}-{d - d Mod 10 + 10}"      ' "11-20"


答: wget is a bash command. There's no point in invoking it through Python when you can directly achieve this task in Python. Basically what you're trying to make is a web scraper. Use requests and BeautifulSoup modules to achieve this. Research a bit about them and start writing a script. If you hit any errors, feel free to post a new question about it on SO.</p>

Title: Clone a single webpage (with images) and save to index.html

Body:
I want to clone a single webpage with all the images and no links in the html. I can achieve this with  wget -E -H -k -K -p {url} however this pulls down the webpage with a full structure and you have to navigate to the html file to display the contents. This makes it inconsistent in where the html file to display the webpage would be.

I can also do this wget --no-check-certificate -O index.html -c -k {url} however this keeps the links to images and doesn't make the webpage truly local as it has to go out to the web to display the page properly.

Is there any way to clone a single webpage and spit out an index.html with the images linked locally?

PS: I am using wget through a python script that makes changes to webpages so having an index.html is neccesary for me.  I am interested in other methods if there are better ones.

EDIT:

So it seems I haven't explain myself well but a bit background info on this project is I am working on a proof of concept for school on an automated phishing script which is supposed to clone a webpage, modify a few action tags and be placed on a local web server so that a user can navigate to it and the page will display correctly. Previously using the -O worked fine for my but since I am now incorporating DNS spoofing into my project the webpage cant have any links pointing externally as they will just end up getting rerouted to my internal webserver and the webpage will look broken. That is why I need to have just the information necessary for the single webpage to be displayed correctly but also have it predictable so that I am able to be sure that when i navigate to the directory I cloned the website from the webpage will be displayed (with proper links to images,css etc..)


问:
Maven web project servlet class not found
Just setup an eclipse project using Maven webapp architype. I created a servlet file and that got added to the resources folder under src/main/
When I run the app tomcat gives an error:

Error instantiating servlet class com.ABCompany.Demo.SampleDemo. java.lang.ClassNotFoundException: com.ABCompany.Demo.SampleDemo

The file is under the folder src/main/resources/com/ABCompany/Demo/SampleDemo.java

My web.xml is below.

```<code><web-app>
 <display-name>Demo Example</display-name>
 <servlet>
 <servlet-name>SampleDemo</servlet-name>
 <display-name>SampleDemo</display-name>
 <description></description>
 <servlet-class>com.ABCompany.Demo.SampleDemo</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>SampleDemo</servlet-name>
 <url-pattern>/SampleDemo</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>
</code>```

答:
I had the same problem.

My solution is:
When the project is created please create the java folder under src/main manually, it is because the maven-archetype-webapp doesn't create the src/main/java by default.

```<code>Before: src/main
After:  src/main/java
</code>```

image:java folder manually created

When the first step is ready then you can create all the servlets that you need, please make sure that you create all your classes and servlets under src/main/java.

The problem is because the servlet was created under src/main/resources that means that all your .java files was packaged as a resource and not as .class compiled.

Body:
Just setup an eclipse project using Maven webapp architype. I created a servlet file and that got added to the resources folder under src/main/
When I run the app tomcat gives an error:

Error instantiating servlet class com.ABCompany.Demo.SampleDemo. java.lang.ClassNotFoundException: com.ABCompany.Demo.SampleDemo

The file is under the folder src/main/resources/com/ABCompany/Demo/SampleDemo.java

My web.xml is below.

<web-app>
 <display-name>Demo Example</display-name>
 <servlet>
 <servlet-name>SampleDemo</servlet-name>
 <display-name>SampleDemo</display-name>
 <description></description>
 <servlet-class>com.ABCompany.Demo.SampleDemo</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>SampleDemo</servlet-name>
 <url-pattern>/SampleDemo</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Body:
I had the same problem.

My solution is:
When the project is created please create the java folder under src/main manually, it is because the maven-archetype-webapp doesn't create the src/main/java by default.

Before: src/main
After:  src/main/java

image:java folder manually created

When the first step is ready then you can create all the servlets that you need, please make sure that you create all your classes and servlets under src/main/java.

The problem is because the servlet was created under src/main/resources that means that all your .java files was packaged as a resource and not as .class compiled.


问:
What are the meanings of the line colors in Git log graph?
I use git log --graph to get a console log graph as below. What are the meanings of the line colors on the left side? I can see red, blue, green, yellow colors. I don't know if there are more. And I even noticed the lines are totally broken once, not in this graph.

But in TortoiseGit GUI, the line color seems less complex.

答:
The lines are there to simply represent your graph in a way that is at least visibly discerning.  The lines represent ancestry, and the asterisks represent individual commits.  The only time a line would be "broken" is if there is no known ancestry for a commit, like in the case of root commits or orphaned branches.

The colors themselves follow commits along a specific ancestry so that it's easier to see when a specific commit made its way into the repository.

If you have many branches, you'll get many colors (and many, many lines).


问:
Servlet redirect error/ jsp cannot load css
I'm having some issues to redirect to an HTML page via servlet.

I have an index.jsp and index.htm page in the same directory.

When i use the following code my servlet redirects to the jsp page fine, but if i change it to index.htm i cannot redirect and get this error on the browser (mozilla)

"Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

```<code>response.setHeader("Location", "/portal/index.jsp");
response.setStatus(HttpServletResponse.SC_FOUND);
</code>```

The reason I want to redirect to the htm page instead of jsp page is because when i redirect to the jsp page, none of my css gets loaded..which is a whole other problem itself.

I have been spending some days now trying to find a solution but I am not getting anywhere. If anyone has any advice to either of the issues i will be so greatful. Thank You.

答:
The below url takes you to the question in mozilla support forum where it has a solution to what you are facing.
Mozilla support forum

For CSS in JSP: If you're using an external CSS file and including in JSP using link href="", make sure the relative path of the CSS file provided in the JSP file is correct.

Another way to redirect is using response.sendRedirect("...")

Body:
I'm having some issues to redirect to an HTML page via servlet.

I have an index.jsp and index.htm page in the same directory.

When i use the following code my servlet redirects to the jsp page fine, but if i change it to index.htm i cannot redirect and get this error on the browser (mozilla)

"Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

response.setHeader("Location", "/portal/index.jsp");
response.setStatus(HttpServletResponse.SC_FOUND);

The reason I want to redirect to the htm page instead of jsp page is because when i redirect to the jsp page, none of my css gets loaded..which is a whole other problem itself.

I have been spending some days now trying to find a solution but I am not getting anywhere. If anyone has any advice to either of the issues i will be so greatful. Thank You.


问:
Why did Windows use the FAT structure instead of a conventional linked list with a next pointer for each data block of a file?
Instead of storing references to next nodes in a table, why couldn't it be just stored like a conventional linked list, that is, with a next pointer?</p>

答:
If we ignore the detail of FAT12 sharing a byte between two items to compact 12 bite as 1.5 bytes, then we can concentrate on the deeper meaning of the question.

It turns out that the FAT system is equivalent to a linked list with the following points:

The "next" pointer is located in an array (the FAT) instead of being appended or prepended to the actual data

The value written in "next" is an integer instead of the more familiar memory address of the next node.

The nodes are not reserved dynamically but represented by another array. That array is the entire data part of the hard drive.

One fascinating exercise we were assigned as part of the software engineer education was to convert an application using memory pointer to an equivalent application which use integer value. The rationale was that some processors (PDP-11? or another PDP-xx) would perform integer arithmetic much faster than memory pointer operation or maybe even did forbid any arithmetic on pointers.


问:
Pandas: Apply rolling function to compute new column value
I am trying to compute a new column Y on each row by checking the 9 previous rows and current row values of column X. Basically the new column Y value on each row will tell us the percentage on values of column X were greater than 1 for previous 10 records including the current record . Below is the code i am using but getting a different result than expected

[EDITED]

```<code>def count_pcnt(x):
 return ((np.sum(x > 1) / len(x)) * 100.0)

def run():
df = pd.DataFrame(
data={'X': ['8.12', '7.13', '-5.30', '3.21', '4.21', '3.14','8.65',
            '7.33', '-5.10', '3.01']
      })

df['Y'] = df['X'].rolling(window=10, min_periods=1).apply(lambda x:
          count_pcnt(x)).apply(int)
</code>```

Expected Result  [ EDITED ]

```<code>     X    Y(%)
0   8.12  100
1   7.13  100
2  -5.30  66.67
3   3.21  75
4   4.21  80
5   3.14  83.33
6   8.65  85.71
7   7.33  87.50
8  -5.10  77.77
9   3.01  80
</code>```

Actual

```<code>      X    Y
 0   8.12  100
 1   7.13  100
 2  -5.30  0
 3   3.21  0
 4   4.21  0
 5   3.14  0
 6   8.65  0
 7   7.33  0
 8  -5.10  0
 9   3.01  0
</code>```

UPDATE I used this option recommended below and it worked. Though there are other options i felt this is much cleaner

```<code>df['Y'] = df['X'].astype(float)
             .rolling(window=w, min_periods=1)
             .apply(lambda x: (x>1).mean()) * 100
</code>```

if you want to compute column values based on next 10 rows rather than previous 10 rows -  below is the solution (Thanks to jezrael who provided it)

```<code>df['Y'] = (df['X'].astype(float).iloc[::-1].rolling(window=10, min_periods=1).apply(lambda x: (x>1).mean()) * 100)[::-1]
</code>```

答:
You may set the min_periods=1 attribute in df.rolling:

```<code>In [927]: def count_pcnt(x):
     ...:     return ((np.sum(x > 1) / len(x)) * 100.0)
     ...:

In [930]: df['Y'] = df['X'].astype(np.float64).rolling(window=10, min_periods=1).apply(lambda x: count_pcnt(x))

In [931]: df
Out[931]:
       X           Y
0   8.12  100.000000
1   7.13  100.000000
2  -5.30   66.666667
3   3.21   75.000000
4   4.21   80.000000
5   3.14   83.333333
6   8.65   85.714286
7   7.33   87.500000
8  -5.10   77.777778
9   3.01   80.000000
</code>```

I've modified your count_pcnt function to take into account variable window sizes being passed. I believe this is what you're looking for.

Body:
I am trying to compute a new column Y on each row by checking the 9 previous rows and current row values of column X. Basically the new column Y value on each row will tell us the percentage on values of column X were greater than 1 for previous 10 records including the current record . Below is the code i am using but getting a different result than expected

[EDITED]

def count_pcnt(x):
 return ((np.sum(x > 1) / len(x)) * 100.0)

def run():
df = pd.DataFrame(
data={'X': ['8.12', '7.13', '-5.30', '3.21', '4.21', '3.14','8.65',
            '7.33', '-5.10', '3.01']
      })

df['Y'] = df['X'].rolling(window=10, min_periods=1).apply(lambda x:
          count_pcnt(x)).apply(int)

Expected Result  [ EDITED ]

     X    Y(%)
0   8.12  100
1   7.13  100
2  -5.30  66.67
3   3.21  75
4   4.21  80
5   3.14  83.33
6   8.65  85.71
7   7.33  87.50
8  -5.10  77.77
9   3.01  80

Actual

      X    Y
 0   8.12  100
 1   7.13  100
 2  -5.30  0
 3   3.21  0
 4   4.21  0
 5   3.14  0
 6   8.65  0
 7   7.33  0
 8  -5.10  0
 9   3.01  0

UPDATE I used this option recommended below and it worked. Though there are other options i felt this is much cleaner

df['Y'] = df['X'].astype(float)
             .rolling(window=w, min_periods=1)
             .apply(lambda x: (x>1).mean()) * 100

if you want to compute column values based on next 10 rows rather than previous 10 rows -  below is the solution (Thanks to jezrael who provided it)

df['Y'] = (df['X'].astype(float).iloc[::-1].rolling(window=10, min_periods=1).apply(lambda x: (x>1).mean()) * 100)[::-1]

Body:
You may set the min_periods=1 attribute in df.rolling:

In [927]: def count_pcnt(x):
     ...:     return ((np.sum(x > 1) / len(x)) * 100.0)
     ...:

In [930]: df['Y'] = df['X'].astype(np.float64).rolling(window=10, min_periods=1).apply(lambda x: count_pcnt(x))

In [931]: df
Out[931]:
       X           Y
0   8.12  100.000000
1   7.13  100.000000
2  -5.30   66.666667
3   3.21   75.000000
4   4.21   80.000000
5   3.14   83.333333
6   8.65   85.714286
7   7.33   87.500000
8  -5.10   77.777778
9   3.01   80.000000

I've modified your count_pcnt function to take into account variable window sizes being passed. I believe this is what you're looking for.


问:
CoreData and unlimited textfields
I'm using Swift and I need your help.

How can I save the relevant properties / parameters to CoreData when I can't set up the attributes.

In my app users can make unlimited number of textfields and I need to save that to CoreData. How can I do this? I'm a bit new to the CoreData and I'd like some help. Any tips? I know I need to set up attributes but if the user can make an unlimited number of textfields and can save that how can I do this with CoreData? Thank you for your kind help :)

答:
Generally this is done by creating a model for your fields... You then give the object in question a ToMany relationship.

```<code>Fruit
 - name (string)
 - avg_weight (number)
 - characteristics (characteristic with to many relation)

Characteristic
  - name (string)
  - value (string)
</code>```

You can then use a category to provide getters/setters on Fruit...

```<code>Fruit (CharacteristicAdditions)
 - generalShape (string) // lookup characteristics where name == 'general_shape' and return value
</code>```

The value in this is you can then use predicates to lookup characteristics to do something like lookup all fruits whose 'general_shape' is 'round'.

There is always the secondary choice of encoding as JSON or any other serialization format... Thus:

```<code>Fruit
 - name (string)
 - avg_weight (number)
 - characteristics (string, json object, name as key, value as value)
</code>```

You'd still need a category to access that encoded characteristics field in a 'clean' manner.

Title: CoreData and unlimited textfields

Body:
Generally this is done by creating a model for your fields... You then give the object in question a ToMany relationship.

Fruit
 - name (string)
 - avg_weight (number)
 - characteristics (characteristic with to many relation)

Characteristic
  - name (string)
  - value (string)

You can then use a category to provide getters/setters on Fruit...

Fruit (CharacteristicAdditions)
 - generalShape (string) // lookup characteristics where name == 'general_shape' and return value

The value in this is you can then use predicates to lookup characteristics to do something like lookup all fruits whose 'general_shape' is 'round'.

There is always the secondary choice of encoding as JSON or any other serialization format... Thus:

Fruit
 - name (string)
 - avg_weight (number)
 - characteristics (string, json object, name as key, value as value)

You'd still need a category to access that encoded characteristics field in a 'clean' manner.


答:
to something like that you have to grasp the very fundamental in php or any programming language at all, i mean the core of php is to create dynamical generated pages based on user/browser input.

You might need to take a quick tutorial about php might I suggest http://www.tizag.com/phpT/
good step for step tutorial

Edit:

if you're wondering how the websites seems to have created a html page for every question, the answer would be they're not they are probably using mod_rewrite as mentioned before to rewrite to url to print a little more user friendly url, the actual url could be something like this https://stackoverflow.com/index.php?post=4499289 in reality

Title: Create Pages Automatically

Body:
Is there any method in Php by which I can create a page automatically based on a predefined template. Like if we create a new post in blogger it automatically creates page for that post with the name of that post, like this one:

http://learntoflash.blogspot.com/2009/12/exit-button-in-flash.html

Here Exit Button In Flash is the name of my post I have written and an automatic page is created for it.

Or like here on this website if we ask a question it automatically creates a page for that question. I want to know can I achieve this in Php or anything close to this ?