问:
using ng-style to convert new height for div
I am going to try to set a new height on a div, using ng-style.
I am trying to calculate the new height for this div with the factor of the width. That looks like this:

```<code>var a = bigImage.style.width/topImage.style.width;
var heigthNewImage = bigImage.style.height/a;
</code>```

The only problem is that it gives me NaN.
So how do I have to get the values of the width and height in the right ways of the div elements? So that it gives me the right values back to set height of another div element.

var bigImage = document.getElementById('bigImage').style;
var topImage = document.getElementById('topImage').style;
var a = bigImage.width/topImage.width;
var heigthNewImage = bigImage.height/a;
vm.convertheight = {
  height: heigthNewImage
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
 padding:0;
 margin:0;
}

/*.small-image{

position:sticky; top:0; left:0;
}*/

#bigImage{
 width:3000px;
 height: 2000px;

}
#topImage{
 position:sticky;
  top:0;
  left:0;
 height:250px;
 width:300px;
 background-repeat: no-repeat;
 background-image: url('../img/scale.jpg');
 background-size: 400px 250px;
}

.movingBox{
 /*height:50px;*/
 width:300px;
 border: 1px solid red;
}</code>```

```

答:
```<code>var a = bigImage.style.width/topImage.style.width;
</code>```

you're getting NAN most likely because you're doing the calculation before the dom is actually rendered resulting in a 0/0.

Assuming those elements do exist in your dom , if you wrap your code inside a $timeout, the code will be executed after the rendering has completed

```<code>$timeout(function(){
  $scope.height= bigImage.style.width/topImage.style.width;
})
</code>```

Body:
I am going to try to set a new height on a div, using ng-style.
I am trying to calculate the new height for this div with the factor of the width. That looks like this:

var a = bigImage.style.width/topImage.style.width;
var heigthNewImage = bigImage.style.height/a;

The only problem is that it gives me NaN.
So how do I have to get the values of the width and height in the right ways of the div elements? So that it gives me the right values back to set height of another div element.

var bigImage = document.getElementById('bigImage').style;
var topImage = document.getElementById('topImage').style;
var a = bigImage.width/topImage.width;
var heigthNewImage = bigImage.height/a;
vm.convertheight = {
  height: heigthNewImage
};

body{
 padding:0;
 margin:0;
}

/*.small-image{

position:sticky; top:0; left:0;
}*/

#bigImage{
 width:3000px;
 height: 2000px;

}
#topImage{
 position:sticky;
  top:0;
  left:0;
 height:250px;
 width:300px;
 background-repeat: no-repeat;
 background-image: url('../img/scale.jpg');
 background-size: 400px 250px;
}

.movingBox{
 /*height:50px;*/
 width:300px;
 border: 1px solid red;
}

Body:
var a = bigImage.style.width/topImage.style.width;

you're getting NAN most likely because you're doing the calculation before the dom is actually rendered resulting in a 0/0.

Assuming those elements do exist in your dom , if you wrap your code inside a $timeout, the code will be executed after the rendering has completed

$timeout(function(){
  $scope.height= bigImage.style.width/topImage.style.width;
})


来源: stackexchange

问:
Auto Close Modal that will activate the function timer multiple times
So my problem is here: I tried to set a timer function that closes the modal but I noticed the modal is only closed once. I pressed the button again to show the modal but it stays there and it doesn't hide anymore.

heres my script:

```<code><script type="text/javascript">
      setTimeout(function(){
    $('#dialogModal').modal('hide')
      }, 10000);

</script>
</code>```

here is the HTML button tag:

```<code><button id="reqpay" type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal" data-target="#dialogModal" onclick="function();"> REQUEST PAYMENT
    </button>
</code>```

答:
The problem is setTimeout runs only once. You need to implement your code with setInterval and clearInterval.

setInterval MDN: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

clearInterval MDN: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval

ContentLicense: CC BY-SA 3.0

Body:
So my problem is here: I tried to set a timer function that closes the modal but I noticed the modal is only closed once. I pressed the button again to show the modal but it stays there and it doesn't hide anymore.

heres my script:

here is the HTML button tag:

<button id="reqpay" type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal" data-target="#dialogModal" onclick="function();"> REQUEST PAYMENT
    </button>


问:
Dom manipulation removal doesn't properly work
I'm making a generic todolist, except the li removal part isn't like it should, for testing purposes I created 7 lis to be instantly added when the page loads, all have ids set to them, this is what happens when i try to remove them. (Their names are numbers so "number 1" is the first li)
(The html is just a UL)

number 1 has id of 0

number 2 has id of 1

number 3 has id of 2

number 4 has id of 3

number 5 has id of 4

number 6 has id of 5

number 7 has id of 6

Deleted 7 then  1

error at 6 (Cannot read property 'remove' of undefined)

Pressed 2 and 3 got deleted

pressed 2 and 4 got deleted

pressed 5 and error

pressed 2 and 5 got deleted

pressed 2 and 6 got deleted

I know that this could be improved in MANY ways, you don't need to tell me that.

```<code>let wholeObject = {

    todos: [],

  //THIS ADDS TO THE ARRAY CALLED TODOS (BUT NOT THE LI, this a work in progress)
addTodo: function(name){
    this.todos.push(name)
},

  //THIS TAKES THE LAST ITEM IN THE ARRAY AND PUSHES IT AS AN LI AND MAKES A BUTTON ON IT
pushLast: function() {

        let ul = document.querySelector("ul");
        let li = document.createElement("li");
        let uuh = ul.appendChild(li);
        uuh.textContent = this.last()

        for (let q = 0; q <= this.todos.length; q++ ){
            uuh.setAttribute("id", [q -1])
        };

        let btn = document.createElement("button");

        let btnCreate = uuh.appendChild(btn);
        btnCreate.textContent = "Delete";
        btnCreate.className = "buttonClass"
        // btnCreate.setAttribute("onclick", "wholeObject.remove()")
},

delete: function (position){
    this.todos.splice(position, 1)
},

let ulSelect = document.querySelector("ul")

ulSelect.addEventListener("click", function(event){

    let test = event.target

    if (test.className === "buttonClass"){

        wholeObject.delete(parseInt(test.parentNode.id));
        let please = document.querySelectorAll("li");
        please[parseInt(test.parentNode.id) ].remove()

        }
    })
</code>```

答:
You have several syntax errors and naming issues. Not really sure why you even need/want the array in the first place since the li elements that you add to the ul create a node list (which already is an array-like object). With the array, you now have two lists that you have to keep in sync. I kept it for demonstration, but in real life, I'd get rid of it.

See comments below:

// Just get this once:
let ul = document.querySelector("ul");

let toDoList = {

  todos: [],
  insertItem: function () {

    let li = document.createElement("li");

    // Completely configure nodes before inserting them into the DOM
    // to avoid unecessary DOM reparsing and document re-flowing
    li.textContent = "Item: " + this.todos.length;
    li.id = this.todos.length;
    this.todos.push(li);  // Add li to array of li items

    let btn = document.createElement("button");
    btn.textContent = "Delete";
    btn.className = "buttonClass"
    btn.addEventListener("click", this.delete);

    li.appendChild(btn);  // Button is complete. Append to li
    ul.appendChild(li);   // li is complete. Append to ul
  },
  // delete is a reserved word - you can't name anything that
  deleteItem: function (position, node) {
    this.todos.splice(position, 1);  // Update the array
    ul.removeChild(node);            // Delete the node
  },
};

// Assign a click event to the ul:
ul.addEventListener("click", function (event) {

  // Check to see if the event originated with a button click
  if (event.target.className === "buttonClass") {
    toDoList.deleteItem(event.srcElement.id,event.srcElement.parentNode);
  }

});

// Automated function to create items
(function makeItems(num){
  for(var i = 0; i < num; i++){
    toDoList.insertItem();
  }
})(10);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
  margin-bottom:.5em;
}

.buttonClass {
  margin-left:1em;
  border:1px solid #e0e0e0;
  box-shadow: 1px 1px 1px #606060;
  padding:6px;
  background-color:#a33;
  color:#ff0;
}

.buttonClass:active {
  box-shadow:-1px -1px 1px #f00;
}</code>```

```

Body:
I'm making a generic todolist, except the li removal part isn't like it should, for testing purposes I created 7 lis to be instantly added when the page loads, all have ids set to them, this is what happens when i try to remove them. (Their names are numbers so "number 1" is the first li)
(The html is just a UL)

number 1 has id of 0

number 2 has id of 1

number 3 has id of 2

number 4 has id of 3

number 5 has id of 4

number 6 has id of 5

number 7 has id of 6

Deleted 7 then  1

error at 6 (Cannot read property 'remove' of undefined)

Pressed 2 and 3 got deleted

pressed 2 and 4 got deleted

pressed 5 and error

pressed 2 and 5 got deleted

pressed 2 and 6 got deleted

I know that this could be improved in MANY ways, you don't need to tell me that.

let wholeObject = {

    todos: [],

  //THIS ADDS TO THE ARRAY CALLED TODOS (BUT NOT THE LI, this a work in progress)
addTodo: function(name){
    this.todos.push(name)
},

  //THIS TAKES THE LAST ITEM IN THE ARRAY AND PUSHES IT AS AN LI AND MAKES A BUTTON ON IT
pushLast: function() {

        let ul = document.querySelector("ul");
        let li = document.createElement("li");
        let uuh = ul.appendChild(li);
        uuh.textContent = this.last()

        for (let q = 0; q <= this.todos.length; q++ ){
            uuh.setAttribute("id", [q -1])
        };

        let btn = document.createElement("button");

        let btnCreate = uuh.appendChild(btn);
        btnCreate.textContent = "Delete";
        btnCreate.className = "buttonClass"
        // btnCreate.setAttribute("onclick", "wholeObject.remove()")
},

delete: function (position){
    this.todos.splice(position, 1)
},

let ulSelect = document.querySelector("ul")

ulSelect.addEventListener("click", function(event){

    let test = event.target

    if (test.className === "buttonClass"){

        wholeObject.delete(parseInt(test.parentNode.id));
        let please = document.querySelectorAll("li");
        please[parseInt(test.parentNode.id) ].remove()

        }
    })

Body:
You have several syntax errors and naming issues. Not really sure why you even need/want the array in the first place since the li elements that you add to the ul create a node list (which already is an array-like object). With the array, you now have two lists that you have to keep in sync. I kept it for demonstration, but in real life, I'd get rid of it.

See comments below:

// Just get this once:
let ul = document.querySelector("ul");

let toDoList = {

  todos: [],
  insertItem: function () {

    let li = document.createElement("li");

    // Completely configure nodes before inserting them into the DOM
    // to avoid unecessary DOM reparsing and document re-flowing
    li.textContent = "Item: " + this.todos.length;
    li.id = this.todos.length;
    this.todos.push(li);  // Add li to array of li items

    let btn = document.createElement("button");
    btn.textContent = "Delete";
    btn.className = "buttonClass"
    btn.addEventListener("click", this.delete);

    li.appendChild(btn);  // Button is complete. Append to li
    ul.appendChild(li);   // li is complete. Append to ul
  },
  // delete is a reserved word - you can't name anything that
  deleteItem: function (position, node) {
    this.todos.splice(position, 1);  // Update the array
    ul.removeChild(node);            // Delete the node
  },
};

// Assign a click event to the ul:
ul.addEventListener("click", function (event) {

  // Check to see if the event originated with a button click
  if (event.target.className === "buttonClass") {
    toDoList.deleteItem(event.srcElement.id,event.srcElement.parentNode);
  }

});

// Automated function to create items
(function makeItems(num){
  for(var i = 0; i < num; i++){
    toDoList.insertItem();
  }
})(10);

li {
  margin-bottom:.5em;
}

.buttonClass {
  margin-left:1em;
  border:1px solid #e0e0e0;
  box-shadow: 1px 1px 1px #606060;
  padding:6px;
  background-color:#a33;
  color:#ff0;
}

.buttonClass:active {
  box-shadow:-1px -1px 1px #f00;
}

<ul></ul>


问:
C# Rhino.Mocks - How do I write test code without repeating myself?
I wish to stub all dependencies out in my Rhino.Mocks unit tests, but I end up repeating myself. As the number of dependencies keeps increasing, I need to revisit my existing unit tests and need to add the dependencies. It's unsatisfying and also a signal that I should be doing it in another way.

If I just move initialization to a separate method, I pass into it all the mocks and I have achieved nothing.

Is there a way to initialize and then pass the Using(mocks.Record) into a method as a lambda expression? Or how do you do it?!

Thanks in advance for any comments,

Anders, Denmark

```<code>    [Test, Category("UnitTest")]
    public void TestThatApplicationCanExitByDefault()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        var canAppExit = target.CanAppExit();

        Assert.IsTrue(canAppExit);

        mocks.VerifyAll();
    }

    [Test, Category("UnitTest")]
    public void TestThatInsertProjectWorks()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();
        var workspaceViewModel = mocks.StrictMock<IWorkspaceViewModel>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();

            workspaceViewModelProvider
                .Stub(x => x.GetViewModel())
                .Return(workspaceViewModel);

            workspaceViewModel
                .Stub(x => x.InsertProject());
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        target.InsertProject();

        mocks.VerifyAll();
    }
</code>```

答:
Try using a base class with protected mocked objects and use [SetUp]/[TestFixtureSetUp] (with NUnit for example).

It is wise to put only common objects with initialization to base class - use [SetUp]/[TestFixtureSetUp] in the same class where there are multiple unit tests and you need to mock/initialize something specific only to this tests. Putting everything in your base bloats your unit tests as well (at least they execute longer).

ContentLicense: CC BY-SA 2.5

Body:
I wish to stub all dependencies out in my Rhino.Mocks unit tests, but I end up repeating myself. As the number of dependencies keeps increasing, I need to revisit my existing unit tests and need to add the dependencies. It's unsatisfying and also a signal that I should be doing it in another way.

If I just move initialization to a separate method, I pass into it all the mocks and I have achieved nothing.

Is there a way to initialize and then pass the Using(mocks.Record) into a method as a lambda expression? Or how do you do it?!

Thanks in advance for any comments,

Anders, Denmark

    [Test, Category("UnitTest")]
    public void TestThatApplicationCanExitByDefault()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        var canAppExit = target.CanAppExit();

        Assert.IsTrue(canAppExit);

        mocks.VerifyAll();
    }

    [Test, Category("UnitTest")]
    public void TestThatInsertProjectWorks()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();
        var workspaceViewModel = mocks.StrictMock<IWorkspaceViewModel>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();

            workspaceViewModelProvider
                .Stub(x => x.GetViewModel())
                .Return(workspaceViewModel);

            workspaceViewModel
                .Stub(x => x.InsertProject());
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        target.InsertProject();

        mocks.VerifyAll();
    }


问:
Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation
Even though I manually configured JDK project structure file/Project structure it still shows this error
FAILURE: Build failed with an exception.

`What went wrong:
Execution failed for task ':sample:compileReleaseJavaWithJavac'.

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation.`

I'm confused why it is still looking for C:\Program Files\Java\jre1.8.0_151 instead of JDK

答:
I had the same problem and fixed it like this:

Install the JDK from the Oracle website with the same version number
as the JRE if you didn't already.

Furthermore add JAVA_HOME to the environment variables of Windows.

Restart your terminal or development environment to load the new JAVA_HOME value.


问:
Calling JavaScript function as parameter in @Url.Action
So I am trying to return a value from a text box as the parameter to another controller action that returns another partial. I think it would easier to just post some sample code rather than trying to explain what I am trying to do, so here is some sample code:

CSHTML:

```<code><div class="row">
  <div class="pt-sm-30 pb-xs-30 has-50px-footer">
    <div class="col-lg-offset-1 col-lg-10">
        <h3>CREATE A NEW PERSON PROFILE</h3>
        <form class="form-spacers">
            <div class="form-group">
                <div class="row">
                    <div class="col-md-6">
                        <label class="input-label" for="functionalRole">First Name <span class="ReqField">*</span></label>
                        @Html.TextBoxFor(model => model.Person.FirstName, new { @class = "form-control input-sm", @id = "firstName", @type = "text" })
                    </div>
                    <div class="col-md-6">
                        <label class="input-label" for="functionalRole">Last Name <span class="ReqField">*</span></label>
                        @Html.TextBoxFor(model => model.Person.LastName, new { @class = "form-control input-sm", @id = "lastName", @type = "text" })
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="row">
    <div class="col-sm-8 col-md-9 col-lg-10 new-profile-footer">
        <div class="col-lg-offset-1 col-lg-5 col-md-4 hidden-sm hidden-xs" style="margin-top: 16px;">
        </div>
        <div class="col-lg-6 col-md-8 col-sm-12" style="margin-top: 10px; text-align: right;">
            <div class="row" style="white-space: nowrap;">
                <button class="btn btn-primary button-blue btn-xs-110" onclick="location.href='@Url.Action("Index", "DirectoryMaintainer")'"><i class="fa fa-times-circle-o icon-xs-hidden" aria-hidden="true" style="padding-right: 5px;"></i>CANCEL</button>
                <button id="continue" type="button" class="btn btn-success button-green btn-xs-110">CONTINUE<i class="fa fa-caret-right icon-xs-hidden" style="padding-left: 5px;" aria-hidden="true"></i></button>
            </div>
        </div>
    </div>
</div>
</code>```

```<code><script>
    $("#continue").click(function () {
        $("#partialViewDiv").load('@(Url.Action("RecordsMatch", "DirectoryMaintainer", new { @firstName = getFirstName(), @lastName = getLastName()}, Request.Url.Scheme))');
    });

    function getFirstName() {
        return document.getElementById("firstName").value;
    }

    function getLastName() {
        return document.getElementById("lastName").value;
    }

</script>
</code>```

Controller:

```<code>    public PartialViewResult RecordsMatch(string firstName, string lastName)
    {
        //Do some logic with parameters here
        return PartialView("_RecordsMatch");
    }
</code>```

So the issue I am having this that the line

```<code>$("#partialViewDiv").load('@(Url.Action("RecordsMatch", "DirectoryMaintainer", new { @firstName = getFirstName(), @lastName = getLastName()}, Request.Url.Scheme))');
</code>```

is giving me an error on getFirstName() and getLastName(). The error is "The name getFirstName() does not exist in the current context". I am pretty new to MVC so I'm not sure if this is even possible or if there is a better way of doing it. If there is, then I am more than happy to learn it. Any and all suggestions would be greatly appreciated.

答:
You cannot mix c# and js like that as the Url.Action gets executed in the server before your js code

Basically any C# code in your razor view gets executed by the razor view engine  in the server and output of that (which is HTML/plain text) will be send to the browser.  All your javascript code gets executed in the browser.

You can use Url.Action to generate the base url (without route value parameters) and add query strings to that at client side later.

```<code>$(function(){

  $("#continue").click(function () {

     var url='@Url.Action("RecordsMatch", "DirectoryMaintainer")';
     url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();

     $("#partialViewDiv").load(url);

  });

});
</code>```

When razor executes this code, it will render output like this (you can check the page view source and see this)

```<code>$(function(){

  $("#continue").click(function () {

     var url='/DirectoryMaintainer/RecordsMatch';
     url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();

     $("#partialViewDiv").load(url);

  });

});
</code>```

Body:
So I am trying to return a value from a text box as the parameter to another controller action that returns another partial. I think it would easier to just post some sample code rather than trying to explain what I am trying to do, so here is some sample code:

CSHTML:

CREATE A NEW PERSON PROFILE

        <form class="form-spacers">

                        First Name *
                        @Html.TextBoxFor(model => model.Person.FirstName, new { @class = "form-control input-sm", @id = "firstName", @type = "text" })

                        Last Name *
                        @Html.TextBoxFor(model => model.Person.LastName, new { @class = "form-control input-sm", @id = "lastName", @type = "text" })

        </form>

                <button class="btn btn-primary button-blue btn-xs-110" onclick="location.href='@Url.Action("Index", "DirectoryMaintainer")'">CANCEL</button>
                <button id="continue" type="button" class="btn btn-success button-green btn-xs-110">CONTINUE</button>

Controller:

    public PartialViewResult RecordsMatch(string firstName, string lastName)
    {
        //Do some logic with parameters here
        return PartialView("_RecordsMatch");
    }

So the issue I am having this that the line

$("#partialViewDiv").load('@(Url.Action("RecordsMatch", "DirectoryMaintainer", new { @firstName = getFirstName(), @lastName = getLastName()}, Request.Url.Scheme))');

is giving me an error on getFirstName() and getLastName(). The error is "The name getFirstName() does not exist in the current context". I am pretty new to MVC so I'm not sure if this is even possible or if there is a better way of doing it. If there is, then I am more than happy to learn it. Any and all suggestions would be greatly appreciated.

Body:
You cannot mix c# and js like that as the Url.Action gets executed in the server before your js code

Basically any C# code in your razor view gets executed by the razor view engine  in the server and output of that (which is HTML/plain text) will be send to the browser.  All your javascript code gets executed in the browser.

You can use Url.Action to generate the base url (without route value parameters) and add query strings to that at client side later.

$(function(){

  $("#continue").click(function () {

     var url='@Url.Action("RecordsMatch", "DirectoryMaintainer")';
     url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();

     $("#partialViewDiv").load(url);

  });

});

When razor executes this code, it will render output like this (you can check the page view source and see this)

$(function(){

  $("#continue").click(function () {

     var url='/DirectoryMaintainer/RecordsMatch';
     url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();

     $("#partialViewDiv").load(url);

  });

});


问:
jQuery to loop through elements with the same class
I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?

答:
try this...</p>

```<code>$('.testimonial').each(function(){
    //if statement here
    // use $(this) to reference the current div in the loop
    //you can try something like...

    if(condition){

    }

 });
</code>```

Body:
try this...

$('.testimonial').each(function(){
    //if statement here
    // use $(this) to reference the current div in the loop
    //you can try something like...

    if(condition){

    }

 });


问:
angular value is not reflecting from the function
I am trying to assign value to $scope variable from a controller function. I can see the value is assigned from console but it is not reflecting in html page.

my html

```<code><div id="NodeDetails" class="NodeDetails">{{NodeDetails}}</div>
</code>```

my controller function

```<code>$scope.ShowDetails = function() {
    $scope.NodeDetails = "in am called in function";
    console.log($scope.NodeDetails)
};
</code>```

i can see the data in console but same is not displayed in html.

it works when i put,

```<code>$scope.NodeDetails = "in am called in individual";
</code>```

is there any specific way to set variable in function. I have tried by return value also but that also didn't work.

```<code>$scope.NodeDetails = function() {
return "in am called in function";
};
</code>```

please suggest.

答:
Instead of creating NodeDetails as a string, change it to an object and try changing it https://jsfiddle.net/paka2/d0mf0g9j/1/

```<code><div id="NodeDetails" class="NodeDetails">{{nodeObject.NodeDetails}}</div>
$scope.nodeObject = {
NodeDetails: ""
}
</code>```

This solves the problem of any child scope issue

Body:
I am trying to assign value to $scope variable from a controller function. I can see the value is assigned from console but it is not reflecting in html page.

my html

{{NodeDetails}}

my controller function

$scope.ShowDetails = function() {
    $scope.NodeDetails = "in am called in function";
    console.log($scope.NodeDetails)
};

i can see the data in console but same is not displayed in html.

it works when i put,

$scope.NodeDetails = "in am called in individual";

is there any specific way to set variable in function. I have tried by return value also but that also didn't work.

$scope.NodeDetails = function() {
return "in am called in function";
};

please suggest.

Body:
Instead of creating NodeDetails as a string, change it to an object and try changing it https://jsfiddle.net/paka2/d0mf0g9j/1/

<div id="NodeDetails" class="NodeDetails">{{nodeObject.NodeDetails}}</div>
$scope.nodeObject = {
NodeDetails: ""
}

This solves the problem of any child scope issue


问:
Awk - Call for a second associated value from file1 after finding a match in file2
I have a code to read gene names from file1 and find them in file2, then I put them together into a table, my problem is that I need to add another column with the associated "start" value from file1 into the table, but couldn't make it. I've tried, but I don't know much about awk in first place, so any help is welcomed.

The idea of final table is:

```<code>File1_gen  File2_gen  Start_from_file1  Value_1_from_file2  Value_2_from_file2
</code>```

File 1:
This file has ~70.000 rows and 4 columns; row number, gene name, gene start and gene end, and I just need gene name and start from this

```<code>        seqnames    start   end
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535
</code>```

File 2:
Then, the second file has ~100.000 rows and 3 columns; gene name, and start and end values, and I need the three of them

```<code>Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313
</code>```

I've already have a pseudocode that do almost all of this

```<code>awk '
FNR == NR {
  # reading file1
    scaf[$2]
    co_id[$3]
next
}
{
  # reading file2
  for (i in scaf) {
    id in co_id
    if ( i == $1 )
    print "[1] "  i "\t" "[2] " $1 "\t" "[3] " id "\t" "[4] " $4 "\t" "[5] "$5
    }
       }
 ' Search.txt Genes.txt
</code>```

Resulting something like this:

```<code>[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522    [4] 1    [5] 602
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 8838    [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 8838    [5] 12313
</code>```

As you can see, the [3] column is empty, and I know the 'id in co_id' is wrong, but it was the last attempt I tried.

In other words, how can I call the associated "start" value for each gene in file1 into the new table I've made?

Edit: Changed the sample data for something that should work. And if there is repeated gene names it should show all the combinations.

Body:
I have a code to read gene names from file1 and find them in file2, then I put them together into a table, my problem is that I need to add another column with the associated "start" value from file1 into the table, but couldn't make it. I've tried, but I don't know much about awk in first place, so any help is welcomed.

The idea of final table is:

File1_gen  File2_gen  Start_from_file1  Value_1_from_file2  Value_2_from_file2

File 1:
This file has ~70.000 rows and 4 columns; row number, gene name, gene start and gene end, and I just need gene name and start from this

        seqnames    start   end
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535

File 2:
Then, the second file has ~100.000 rows and 3 columns; gene name, and start and end values, and I need the three of them

Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313

I've already have a pseudocode that do almost all of this

awk '
FNR == NR {
  # reading file1
    scaf[$2]
    co_id[$3]
next
}
{
  # reading file2
  for (i in scaf) {
    id in co_id
    if ( i == $1 )
    print "[1] "  i "\t" "[2] " $1 "\t" "[3] " id "\t" "[4] " $4 "\t" "[5] "$5
    }
       }
 ' Search.txt Genes.txt

Resulting something like this:

[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522    [4] 1    [5] 602
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 8838    [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 8838    [5] 12313

As you can see, the [3] column is empty, and I know the 'id in co_id' is wrong, but it was the last attempt I tried.

In other words, how can I call the associated "start" value for each gene in file1 into the new table I've made?

Edit: Changed the sample data for something that should work. And if there is repeated gene names it should show all the combinations.

Body:
NOTE: This answer is based on the original question which required I create some sample test data; original question also didn't mention that gene names could occur multiple times in either data file.

Some sample data:

$ cat gene.1
1   Gen_3989161.1   696 720
2   Gen_3989469.1   693 733
3   Gen_3989837.1   462 515
4   Gen_3990203.1   27  112
5   Gen_3990467.1   476 481
6   Gen_3991323.1   134 152
7   Gen_3991401.1   597 681
8   Gen_3991403.1   175 217
9   Gen_3991951.1   897 907
10  Gen_6899912.3   888 999

$ cat gene.2
Gen_3989161.1   1696 2720
Gen_3989469.1   1693 2733
Gen_3989837.1   1462 2515
Gen_3990203.1   127  2112
Gen_3990467.1   1476 2481
Gen_3991323.1   1134 2152
Gen_3991401.1   1597 2681
Gen_3991403.1   1175 2217
Gen_3991951.1   1897 2907
Gen_8877722.9   7777 8888

One awk solution:

$ awk '
# process first file ...
FNR==NR { # use gene seq name as index; store start value
          start[$2]=$3
          next }

# process second file ...
{ # if we have a start value for the current gene seq name ($1)
  if ( start[$1] != "" )
       # then print
       print "[1] " $1 "\t" "[2] " $1 "\t" "[3] " start[$1] "\t" "[4] " $2 "\t" "[5] "$3
}
' gene.1 gene.2

[1] Gen_3989161.1       [2] Gen_3989161.1       [3] 696 [4] 1696        [5] 2720
[1] Gen_3989469.1       [2] Gen_3989469.1       [3] 693 [4] 1693        [5] 2733
[1] Gen_3989837.1       [2] Gen_3989837.1       [3] 462 [4] 1462        [5] 2515
[1] Gen_3990203.1       [2] Gen_3990203.1       [3] 27  [4] 127 [5] 2112
[1] Gen_3990467.1       [2] Gen_3990467.1       [3] 476 [4] 1476        [5] 2481
[1] Gen_3991323.1       [2] Gen_3991323.1       [3] 134 [4] 1134        [5] 2152
[1] Gen_3991401.1       [2] Gen_3991401.1       [3] 597 [4] 1597        [5] 2681
[1] Gen_3991403.1       [2] Gen_3991403.1       [3] 175 [4] 1175        [5] 2217
[1] Gen_3991951.1       [2] Gen_3991951.1       [3] 897 [4] 1897        [5] 2907

If you need the output to line up with fixed width columns, that could be accomplished by replacing the print with an appropriate printf format string ...


问:
React state vs. Redux state (real usecase)
I have read multiple tutorials how to make CRUD in React with Redux bot none of the authors explained why they are using Redux. (Like they are only using it for fancyness or because all other are using it.)

Citate from here:

People often choose Redux before they need it.

Through further researching i learned that Redux is good for:

Share state between components

Let some data be accessable in the entire application

It does not exist a wrong or right. But only the do what makes sense.

My usecase

I have a component that uses a shared component:

```<code>¦-- domains/FooManagement/Components/Editor.jsx <-- Most-parent of the editor
¦-- domains/FooManagement/Components/..the children of Editor.jsx
¦-- shared/Components/Tabs/Tabs.jsx <-- Most-parent of the tabs
¦-- shared/Components/Tabs/..the children of Tabs.jsx
</code>```

Tabs.jsx is used in Editor.jsx.

Which is the right approach?

Approach 1: React state (I think its the right one)

Every dynamic rendering that can happen is stored in the state of Editor.jsx.

onClick on a tab (nested shared component) calls a callback written in Editor.jsx that updates the state in Editor.jsx. This state change then rerenders the new active tab

That means that on every other component like Editor.jsx that uses the same nested Tabs.jsx, the changes for the tabs must be handled in the editor.

Code example:

```<code>/**
 * domains/FooManagement/Components/Editor.jsx
 * or
 * domains/BarManagement/Components/Editor.jsx
 */
onTabChange(activeTab) {
    this.state.activeTab = activeTab;
    this.setState(this.state);
}
</code>```

I think this is the right approach because:

I dont need the state of the editor or the tabs component in the entire application. But only on this view one time. Like the short term duration definition.

Approach 2: Redux state

Editor.jsx has its own state

Tabs.jsx has its own state

States are stored in Redux

Editor.jsx dont passes data down to Tabs.jsx because Tabs.jsx takes the data from the Redux store

Benefit:

The code example above must not be in Editor.jsx because its not the editor's interests how the tabs component behaves. (Or should the editor interests?)

I think this is bad because

Its too much magic in here. Immagine there comes more components in the editor like sortables, tables, etc. In the Editor.jsx you will not see what can render your view. It is hidden in the other components.

But if its all handled in Editor.jsx, you have the overview and the control of all what must be rendered on any change.

What is the right approach for you?

答: speaking of real usecases, I'm working on an everyday growing project, at first, pure React state management seemed like a very convenient way to develop, and it was working just fine when the components structures were still somehow flattened, but as we go along it, the project gets more complicated and by complicated I mean, more component become nested, and one parent has a serie of nested children, so we have to pass props all the way from the parent to the most furthest child, and whenever we need to rerender the parent, all the children have to go through this cycle also, as for your case, if you know that your project won't get way more complicated, and Tabs.jsx won't have maybe something like form that contains further nested subForm that contains a Grid maybe, you surely don't need to complicate your life with Redux, but as I stated earlier, for us we started to notice that at this stage, integrating Redux would be considerable

Body:
I have read multiple tutorials how to make CRUD in React with Redux bot none of the authors explained why they are using Redux. (Like they are only using it for fancyness or because all other are using it.)

Citate from here:

People often choose Redux before they need it.

Through further researching i learned that Redux is good for:

Share state between components

Let some data be accessable in the entire application

It does not exist a wrong or right. But only the do what makes sense.

My usecase

I have a component that uses a shared component:

¦-- domains/FooManagement/Components/Editor.jsx <-- Most-parent of the editor
¦-- domains/FooManagement/Components/..the children of Editor.jsx
¦-- shared/Components/Tabs/Tabs.jsx <-- Most-parent of the tabs
¦-- shared/Components/Tabs/..the children of Tabs.jsx

Tabs.jsx is used in Editor.jsx.

Which is the right approach?

Approach 1: React state (I think its the right one)

Every dynamic rendering that can happen is stored in the state of Editor.jsx.

onClick on a tab (nested shared component) calls a callback written in Editor.jsx that updates the state in Editor.jsx. This state change then rerenders the new active tab

That means that on every other component like Editor.jsx that uses the same nested Tabs.jsx, the changes for the tabs must be handled in the editor.

Code example:

/**
 * domains/FooManagement/Components/Editor.jsx
 * or
 * domains/BarManagement/Components/Editor.jsx
 */
onTabChange(activeTab) {
    this.state.activeTab = activeTab;
    this.setState(this.state);
}

I think this is the right approach because:

I dont need the state of the editor or the tabs component in the entire application. But only on this view one time. Like the short term duration definition.

Approach 2: Redux state

Editor.jsx has its own state

Tabs.jsx has its own state

States are stored in Redux

Editor.jsx dont passes data down to Tabs.jsx because Tabs.jsx takes the data from the Redux store

Benefit:

The code example above must not be in Editor.jsx because its not the editor's interests how the tabs component behaves. (Or should the editor interests?)

I think this is bad because

Its too much magic in here. Immagine there comes more components in the editor like sortables, tables, etc. In the Editor.jsx you will not see what can render your view. It is hidden in the other components.

But if its all handled in Editor.jsx, you have the overview and the control of all what must be rendered on any change.

What is the right approach for you?


问:
Blank space at the right of the div which has width:100% property
There is a blank space at the right of the div which I use as a topbar. I want it to cover the page horizontally 100%, but that small space at the right of the page seems to go anywhere.

I tried adding padding:0; and margin:0; to the body property but it didn't work.

There are no other CSS at play since I've been re-designing the page.

body {

    background-image:url(images/background-awcc.png);
    background-repeat:no-repeat;
    background-size:100%;
    background-attachment: fixed;
    background-position: center;
    padding: 0 !important;
    margin: 0 !important;

}

/* Top Menu All Pages */

.topmenu {

    padding:30px;
    background-color:rgba(55, 21, 21, 1);
    border-right:solid rgba(55, 21, 21, 1);
    margin-left:-9px;
    margin-top:-9px;
    text-align:center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    box-sizing : border-box;
}

.topmenulink {

    padding:30px;
    color:antiquewhite;
    text-decoration:none;
}

.topmenulink:visited  {

    text-decoration:none;
    color:burlywood;

}

.topmenulink:hover  {

    background-color:darkgoldenrod;
    color:black;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="wrapper">
        <div class="topmenu">

            My Account
            Appointments
            Tutors
            Clients
            Schedule
            Statistics
            Help
            Logout

        </div>
    </div></code>```

答: Remove margin-left -9px from the topmenu classname</p>

Body:
There is a blank space at the right of the div which I use as a topbar. I want it to cover the page horizontally 100%, but that small space at the right of the page seems to go anywhere.

I tried adding padding:0; and margin:0; to the body property but it didn't work.

There are no other CSS at play since I've been re-designing the page.

body {

    background-image:url(images/background-awcc.png);
    background-repeat:no-repeat;
    background-size:100%;
    background-attachment: fixed;
    background-position: center;
    padding: 0 !important;
    margin: 0 !important;

}

/* Top Menu All Pages */

.topmenu {

    padding:30px;
    background-color:rgba(55, 21, 21, 1);
    border-right:solid rgba(55, 21, 21, 1);
    margin-left:-9px;
    margin-top:-9px;
    text-align:center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    box-sizing : border-box;
}

.topmenulink {

    padding:30px;
    color:antiquewhite;
    text-decoration:none;
}

.topmenulink:visited  {

    text-decoration:none;
    color:burlywood;

}

.topmenulink:hover  {

    background-color:darkgoldenrod;
    color:black;

}

            My Account
            Appointments
            Tutors
            Clients
            Schedule
            Statistics
            Help
            Logout


问:
I'm trying to write a code the takes two dimensional array "Sudoku" and arrange them into blocks
I'm trying to write a code the takes two dimensional array "Sudoku"
(matrix.length * matrix.length) and I should check if the matrix is (n^2 * n^2) and a number (n) and I should arrange the rows into blocks (n * n). Any suggestions?
if any body can do it if 4 "fors" i will be more than happy

```<code>public static int[][] blocks(int[][] matrix, int sqrtN) {
    int [][] returnedMatrix = new int [matrix.length][matrix.length];
    if (matrix.length !=  Math.pow(sqrtN, 2))
            throw new RuntimeException("Matrix length is not" + Math.pow(sqrtN, 2 ));
    for(int i=0 ; i <= matrix.length ;i=i+sqrtN) {
        for(int j=sqrtN; j <= matrix.length;j=j+1) {
            int temporarily =

        }
    }
    return returnedMatrix;
}
</code>```

for exsample

```<code>int[][] matrix1 = {{11,12,13,14},
{15,16,17,18},
{19,20,21,22},

{23,24,25,26}} ;

int[][] matBlocks1 = blocks (matrix1, 2) ;
/*
* matBlocks1 = {{11, 12, 15, 16},
* {13, 14, 17, 18},
* {19, 20, 23, 24},
* {21, 22, 25, 26}}
*/
</code>```

答:
If you define a class Grid to represent an Sudoku grid, and a class Cell to refer to a cell of this grid, you can access rows, columns and blocks with a array of cells Cell[]:

```<code>public class Grid {
    public final int N;
    public final int n;
    private final int[][] matrix;

    public class Cell {
        private final int row;
        private final int col;

        private Cell(int row, int col) {
            this.row = row;
            this.col = col;
        }

        public int get() {
            return matrix[row][col];
        }

        public void set(int value) {
            matrix[row][col] = value;
        }
    }

    public Grid(int[][] matrix) throws Exception {
        N = matrix.length;
        n = (int)Math.sqrt(N);
        if (n*n != N) {
            throw new IllegalArgumentException(
                    "Matrix size must be a square number");
        }
        this.matrix = new int[N][];
        for (int i = 0; i < N; ++i) {
            int[] row = matrix[i];
            if (row.length != N) {
                throw new IllegalArgumentException("Matrix must be a square");
            }
            int[] newRow = new int[N];
            for (int j = 0; j < N; ++j) {
                newRow[j] = row[j];
            }
            this.matrix[i] = newRow;
        }
    }

    public Cell cell(int row, int col) {
        return new Cell(row, col);
    }

    public Cell[] row(int row) {
        if (row < 0 || row >= N) {
            throw new IndexOutOfBoundsException("Invalid row number: " + row);
        }
        Cell[] result = new Cell[N];
        for (int col = 0; col < N; ++col) {
            result[col] = cell(row, col);
        }
        return result;
    }

    public Cell[] colum(int col) {
        if (col < 0 || col >= N) {
            throw new IndexOutOfBoundsException("Invalid row number: " + col);
        }
        Cell[] result = new Cell[N];
        for (int row = 0; row < N; ++row) {
            result[row] = cell(row, col);
        }
        return result;
    }

    public Cell[] block(int br, int bc) {
        if (br < 0 || br >= n) {
            throw new IndexOutOfBoundsException("Invalid block row: " + br);
        }
        if (bc < 0 || bc >= n) {
            throw new IndexOutOfBoundsException("Invalid block column: " + bc);
        }
        int startRow = br*n;
        int startCol = bc*n;
        Cell[] result = new Cell[N];
        int k = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                result[k++] = cell(startRow+i, startCol+j);
            }
        }
        return result;
    }
}
</code>```

To list all blocks, you would do:

```<code>        int[][] matrix1 = {
            {11, 12, 13, 14},
            {15, 16, 17, 18},
            {19, 20, 21, 22},
            {23, 24, 25, 26}};
        Grid grid = new Grid(matrix1);
        for (int i = 0; i < grid.n; ++i) {
            for (int j = 0; j < grid.n; ++j) {
                Cell[] block = grid.block(i, j);
                System.out.print("{");
                for (int k = 0; k < block.length; ++k) {
                    if (k > 0) {
                        System.out.print(", ");
                    }
                    System.out.print(block[k].get());
                }
                System.out.println("}");
            }
        }
</code>```

The advantage using Cells instead of int has the advantage of letting you change the value in the cell.

Body:
I'm trying to write a code the takes two dimensional array "Sudoku"
(matrix.length * matrix.length) and I should check if the matrix is (n^2 * n^2) and a number (n) and I should arrange the rows into blocks (n * n). Any suggestions?
if any body can do it if 4 "fors" i will be more than happy

public static int[][] blocks(int[][] matrix, int sqrtN) {
    int [][] returnedMatrix = new int [matrix.length][matrix.length];
    if (matrix.length !=  Math.pow(sqrtN, 2))
            throw new RuntimeException("Matrix length is not" + Math.pow(sqrtN, 2 ));
    for(int i=0 ; i <= matrix.length ;i=i+sqrtN) {
        for(int j=sqrtN; j <= matrix.length;j=j+1) {
            int temporarily =

        }
    }
    return returnedMatrix;
}

for exsample

int[][] matrix1 = {{11,12,13,14},
{15,16,17,18},
{19,20,21,22},

{23,24,25,26}} ;

int[][] matBlocks1 = blocks (matrix1, 2) ;
/*
* matBlocks1 = {{11, 12, 15, 16},
* {13, 14, 17, 18},
* {19, 20, 23, 24},
* {21, 22, 25, 26}}
*/

Body:
If you define a class Grid to represent an Sudoku grid, and a class Cell to refer to a cell of this grid, you can access rows, columns and blocks with a array of cells Cell[]:

public class Grid {
    public final int N;
    public final int n;
    private final int[][] matrix;

    public class Cell {
        private final int row;
        private final int col;

        private Cell(int row, int col) {
            this.row = row;
            this.col = col;
        }

        public int get() {
            return matrix[row][col];
        }

        public void set(int value) {
            matrix[row][col] = value;
        }
    }

    public Grid(int[][] matrix) throws Exception {
        N = matrix.length;
        n = (int)Math.sqrt(N);
        if (n*n != N) {
            throw new IllegalArgumentException(
                    "Matrix size must be a square number");
        }
        this.matrix = new int[N][];
        for (int i = 0; i < N; ++i) {
            int[] row = matrix[i];
            if (row.length != N) {
                throw new IllegalArgumentException("Matrix must be a square");
            }
            int[] newRow = new int[N];
            for (int j = 0; j < N; ++j) {
                newRow[j] = row[j];
            }
            this.matrix[i] = newRow;
        }
    }

    public Cell cell(int row, int col) {
        return new Cell(row, col);
    }

    public Cell[] row(int row) {
        if (row < 0 || row >= N) {
            throw new IndexOutOfBoundsException("Invalid row number: " + row);
        }
        Cell[] result = new Cell[N];
        for (int col = 0; col < N; ++col) {
            result[col] = cell(row, col);
        }
        return result;
    }

    public Cell[] colum(int col) {
        if (col < 0 || col >= N) {
            throw new IndexOutOfBoundsException("Invalid row number: " + col);
        }
        Cell[] result = new Cell[N];
        for (int row = 0; row < N; ++row) {
            result[row] = cell(row, col);
        }
        return result;
    }

    public Cell[] block(int br, int bc) {
        if (br < 0 || br >= n) {
            throw new IndexOutOfBoundsException("Invalid block row: " + br);
        }
        if (bc < 0 || bc >= n) {
            throw new IndexOutOfBoundsException("Invalid block column: " + bc);
        }
        int startRow = br*n;
        int startCol = bc*n;
        Cell[] result = new Cell[N];
        int k = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                result[k++] = cell(startRow+i, startCol+j);
            }
        }
        return result;
    }
}

To list all blocks, you would do:

        int[][] matrix1 = {
            {11, 12, 13, 14},
            {15, 16, 17, 18},
            {19, 20, 21, 22},
            {23, 24, 25, 26}};
        Grid grid = new Grid(matrix1);
        for (int i = 0; i < grid.n; ++i) {
            for (int j = 0; j < grid.n; ++j) {
                Cell[] block = grid.block(i, j);
                System.out.print("{");
                for (int k = 0; k < block.length; ++k) {
                    if (k > 0) {
                        System.out.print(", ");
                    }
                    System.out.print(block[k].get());
                }
                System.out.println("}");
            }
        }

The advantage using Cells instead of int has the advantage of letting you change the value in the cell.


问:
what is the most pythonic way to split a 2d array to arrays of each row?
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

```<code>a;b = foo()
</code>```

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

答:
You can do this simply by using zip function like:

```<code>def foo(mylist):
   return zip(*mylist)
</code>```

Now call foo with as much dimension as you have in mylist, and it would do the requisite like:

```<code>mylist = [[1, 2], [3, 4], [5, 6]]
a, b = foo(mylist)
# a = (1, 3, 5)
# b = (2, 4, 6)
</code>```

Body:
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

a;b = foo()

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

Body:
You can do this simply by using zip function like:

def foo(mylist):
   return zip(*mylist)

Now call foo with as much dimension as you have in mylist, and it would do the requisite like:

mylist = [[1, 2], [3, 4], [5, 6]]
a, b = foo(mylist)
# a = (1, 3, 5)
# b = (2, 4, 6)


答:
Use each: 'i' is the postion in the array, obj is the DOM object that you are iterating (can be accessed through the jQuery wrapper $(this) as well).

```<code>$('.testimonial').each(function(i, obj) {
    //test
});
</code>```

Check the api reference for more information.

Title: jQuery to loop through elements with the same class

Body:
I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?

Body:
Use each: 'i' is the postion in the array, obj is the DOM object that you are iterating (can be accessed through the jQuery wrapper $(this) as well).

$('.testimonial').each(function(i, obj) {
    //test
});

Check the api reference for more information.


问:
How to read from a plist with Swift 3 iOS app
-Disclaimer-

I'm extremely new to iOS and Swift development, but I'm not particularly new to programming.

I have a basic iOS application with Swift3 elements in it.
I've created a plist file with some entries I want to read and display in my application. (No write access is necessary)

How can you read a value for a given key for a bundled plist file, in Swift3?

This seems like a really simple question to me, but a bunch of searching is making me question my whole conceptual approach.

Helpful tips would be appreciated.

答:
Here is example how to get BundleID from Info plist:

```<code>var appBundleID = "Unknown Bundle ID"
if let bundleDict = Bundle.main.infoDictionary,
   let bundleID = bundleDict[kCFBundleIdentifierKey as String] as? String {
       appBundleID = bundleID
   }
</code>```

The same way you may easily access any key. This approach is good for many-target projects.

Body:
Here is example how to get BundleID from Info plist:

var appBundleID = "Unknown Bundle ID"
if let bundleDict = Bundle.main.infoDictionary,
   let bundleID = bundleDict[kCFBundleIdentifierKey as String] as? String {
       appBundleID = bundleID
   }

The same way you may easily access any key. This approach is good for many-target projects.


问:
What exactly can we describe Factory Method of design pattern?
I am confused with the concept ? Is it just as simple as incorporating a static method to return the object instead of a constructor ? So that client doesn't need to change the code while we update the library or there is something more to it ? </p>

答:
The book Head First Design Patterns will be your definitive guide for Java. That is a great book. If you check out my answer to this Stack Overflow Question, you will be able to see my implementation for an ArbitraryPointFactory class in the Point Example code that uses the Factory Method pattern as well as how it differs from Abstract Factory pattern seen in the Point Factory class. Although this answer is presented with C# code samples, the design pattern language I am using to describe their usage, should warrant you an answer.

What you are thinking of in your question is not a design pattern at all. This static method that returns an object to encapsulate the instantiation, is known as the Simple Factory as seen in the Wiki page. The Factory Method pattern more or less abstracts the type being returned via an interface. This is typically done where the sole job of the factory method class is to control creation of the objects for one concrete class that implements the interface being returned. The Abstract Factory provides encapsulation for a group of related products. In my example I was showing for different types of points, however they could implement different interfaces and all use the same Abstract Factory.

The idea is that you are programming to interfaces, not implementations. True factories pull creation logic to a single location in your application and encapsulate the instantiation via interfaces.


问:
Decreasing google closure run time using gulp
I am trying to find an alternative for plovr while development, because plovr is a little bit far behind and upgrading google closure every time is becoming troublesome there.

So I considered using gulp. I set up a gulp webserver using gulp connect and on fallback, it triggers the google closure compile, then it waits until the file is generated and it will then serve it to the client. The problem that I am facing is that the compile time is much bigger than plovr ~40s vs ~20s. For a frontend developer that will be a long time to wait for the page to load after a small change. Any idea what can be done to optimize the compile time of the closure compiler. Here is my gulpfile.js to give you an idea about my setup.

```<code>var gulp = require('gulp'),
    closureCompiler = require('google-closure-compiler').gulp({
        extraArguments: ['-Xms2048m']
    }),
    fs = require('fs-extra'),
    grepit = require('grepit'),
    connect = require('gulp-connect'),
    sleep = require('system-sleep'),
    outputPath = './target/js',
    pathToJavascriptCode = './project/',
    compilationLevel = 'ADVANCED',
    entryPoint = undefined;

gulp.task('js-clean', function() {
    fs.removeSync(outputPath);
});

gulp.task('js-compile', function() {
    var outputFileName = entryPoint + '.' + compilationLevel.toLowerCase() + '.js.compiled';
    return gulp.src([
    pathToJavascriptCode + '/**/*.js',
    './node_modules/google-closure-library/closure/goog/**/*.js',
    '!./node_modules/google-closure-library/closure/goog/**/*_test.js'],
    {base: './'})
      .pipe(closureCompiler({
          closure_entry_point: entryPoint,
          externs: [
              './public/javascripts/libs/jquery-1.7-externs.js'],
          compilation_level: compilationLevel,
          warning_level: 'VERBOSE',
          js_output_file: './' + outputFileName,
          manage_closure_dependencies: true,
          language_in: 'ECMASCRIPT6',
          language_out: 'ECMASCRIPT5'
        }))
      .pipe(gulp.dest(outputPath))
      .pipe(connect.reload());
});

gulp.task('webserver', function () {
    connect.server({
        root: ['./target/js/'],
        port: 8080,
        livereload: true,
        middleware: function() {
            return [function(req, res, next) {
                res.setHeader('Access-Control-Allow-Origin', '*');
                next();
            }];
        },
        fallback: function(req, res) {
            var requestedFileName = req.url.replace('/', '');
            var requestedFileNameParts = requestedFileName.split('.');

            compilationLevel = requestedFileNameParts[3] === 'simple' ? 'SIMPLE' : 'ADVANCED';
            entryPoint = requestedFileNameParts[2] !== 'all' ? requestedFileNameParts.splice(0, 3).join('.') : undefined;
            gulp.start('js-compile');

            var path = './target/js' + req.url;
            while(fs.existsSync(path) !== true) {
                console.log(path + ' does not exist yet, sleeping for 1 second');
                sleep(1000)
            }
            return path;
        }
    })
});

gulp.task('watch', function() {
    gulp.watch('./project/pauljs/**/*.js', ['js-clean']);
});

gulp.task('default', ['js-clean', 'webserver', 'watch']);
</code>```

After some research I guess the problem is the slow startup time of the jvm, I found this https://www.npmjs.com/package/closure-gun which uses nailgun to run google closure compiler, but I am not sure how can I integrate this with my current setup, any pointers will be appreciated :)

答:
I found the answer and added the solution to the readme of google-closure-compiler npm repo
https://github.com/google/closure-compiler-npm/pull/77/files</p>

Body:
I am trying to find an alternative for plovr while development, because plovr is a little bit far behind and upgrading google closure every time is becoming troublesome there.

So I considered using gulp. I set up a gulp webserver using gulp connect and on fallback, it triggers the google closure compile, then it waits until the file is generated and it will then serve it to the client. The problem that I am facing is that the compile time is much bigger than plovr ~40s vs ~20s. For a frontend developer that will be a long time to wait for the page to load after a small change. Any idea what can be done to optimize the compile time of the closure compiler. Here is my gulpfile.js to give you an idea about my setup.

var gulp = require('gulp'),
    closureCompiler = require('google-closure-compiler').gulp({
        extraArguments: ['-Xms2048m']
    }),
    fs = require('fs-extra'),
    grepit = require('grepit'),
    connect = require('gulp-connect'),
    sleep = require('system-sleep'),
    outputPath = './target/js',
    pathToJavascriptCode = './project/',
    compilationLevel = 'ADVANCED',
    entryPoint = undefined;

gulp.task('js-clean', function() {
    fs.removeSync(outputPath);
});

gulp.task('js-compile', function() {
    var outputFileName = entryPoint + '.' + compilationLevel.toLowerCase() + '.js.compiled';
    return gulp.src([
    pathToJavascriptCode + '/**/*.js',
    './node_modules/google-closure-library/closure/goog/**/*.js',
    '!./node_modules/google-closure-library/closure/goog/**/*_test.js'],
    {base: './'})
      .pipe(closureCompiler({
          closure_entry_point: entryPoint,
          externs: [
              './public/javascripts/libs/jquery-1.7-externs.js'],
          compilation_level: compilationLevel,
          warning_level: 'VERBOSE',
          js_output_file: './' + outputFileName,
          manage_closure_dependencies: true,
          language_in: 'ECMASCRIPT6',
          language_out: 'ECMASCRIPT5'
        }))
      .pipe(gulp.dest(outputPath))
      .pipe(connect.reload());
});

gulp.task('webserver', function () {
    connect.server({
        root: ['./target/js/'],
        port: 8080,
        livereload: true,
        middleware: function() {
            return [function(req, res, next) {
                res.setHeader('Access-Control-Allow-Origin', '*');
                next();
            }];
        },
        fallback: function(req, res) {
            var requestedFileName = req.url.replace('/', '');
            var requestedFileNameParts = requestedFileName.split('.');

            compilationLevel = requestedFileNameParts[3] === 'simple' ? 'SIMPLE' : 'ADVANCED';
            entryPoint = requestedFileNameParts[2] !== 'all' ? requestedFileNameParts.splice(0, 3).join('.') : undefined;
            gulp.start('js-compile');

            var path = './target/js' + req.url;
            while(fs.existsSync(path) !== true) {
                console.log(path + ' does not exist yet, sleeping for 1 second');
                sleep(1000)
            }
            return path;
        }
    })
});

gulp.task('watch', function() {
    gulp.watch('./project/pauljs/**/*.js', ['js-clean']);
});

gulp.task('default', ['js-clean', 'webserver', 'watch']);

After some research I guess the problem is the slow startup time of the jvm, I found this https://www.npmjs.com/package/closure-gun which uses nailgun to run google closure compiler, but I am not sure how can I integrate this with my current setup, any pointers will be appreciated :)


问:
How to extend a php class with more classes
I was wondering if it was a way to get what you would see as

```<code>class main_class extends main_class {...}
</code>```

But php was not happy. :(

So then I though to myself lets ask stackoverflow, I'm sure someone will know a solution.
Never the less several hours of debugging I self-solved my problem, with only a little code.

The problem was the fact of class some_class won't let you override an existing class so what I needed to do was use __get and __call and add another 2 lines into my __construct function.

So here is my solved-code:

```<code>class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}
</code>```

Then simply run this to extend my main_class without overriding the original functions, so it has me run my new functions but if I need to I can get the original functions:

```<code>$MODS_ENABLED=array();
class mod_mail {...}
$MODS_ENABLED[]=new mod_mail;
</code>```

Now lets load our class and run a function from our mod:

```<code>$obj = new main_class(...);
$obj -> mail("root@localhost", "me@me.me", "Testing a mod.", "This email was sent via My main_class but this is a mod that extended main_class without renaming it.");
</code>```

Okay well my mod was not for sending emails but instead redirects sub-domains to there aliased pathname, but you understand the concept shown here.

Edit: After I solved the issue I saw a comment saying a possible duplicate exists so I check it out and find out someone else has an extremely similar solution, but please don't mark it as a duplicate as he was asking about adding to a class that was already constructed, I want to override functions while constructing. My solution takes in an array of constructed classes and "merges" them into my main_class, This method does reserve the original functions but I can also call the original functions using another function to by-pass the __call function.

Thanks to anyone who posted answers.

答:
Self-Solved :)
I have figured this out on my own and I'm sure someone else will find it useful so here is my php code.

```<code>class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}
</code>```

Then simply run:

```<code>$MODS_ENABLED=array();
class mod_mail {...}
$MODS_ENABLED[]=new mod_mail;
</code>```

Now all you need to do is just call your main class via.

```<code>$obj = new main_class(...);
$obj -> mail("root@localhost", "me@me.me", "Testing a mod.", "This email was sent via my main_class but this is a mod that extended main_class without renaming it.");
</code>```

Okay this was not my usage but I'm sure you get the idea, My class is a CMS-back-end and my mod was a redirecting a few sub-domains to other locations, such as mail.sitegen.com.au and phpmyadmin.sitegen.com.au get redirected to there web-gui's out side of my CMS. I am also making more mods for my CMS.

BTW: my extensions are split into two categories, mods and plugins, mods run on every site that is powered by my CMS (SiteGen) and plug-ins have there own settings for each site and they are not required. In other words mods are chosen by me, and plug-ins are chosen by the owner of the site.

Body:
I was wondering if it was a way to get what you would see as

class main_class extends main_class {...}

But php was not happy. :(

So then I though to myself lets ask stackoverflow, I'm sure someone will know a solution.
Never the less several hours of debugging I self-solved my problem, with only a little code.

The problem was the fact of class some_class won't let you override an existing class so what I needed to do was use __get and __call and add another 2 lines into my __construct function.

So here is my solved-code:

class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}

Then simply run this to extend my main_class without overriding the original functions, so it has me run my new functions but if I need to I can get the original functions:

$MODS_ENABLED=array();
class mod_mail {...}
$MODS_ENABLED[]=new mod_mail;

Now lets load our class and run a function from our mod:

$obj = new main_class(...);
$obj -> mail("root@localhost", "me@me.me", "Testing a mod.", "This email was sent via My main_class but this is a mod that extended main_class without renaming it.");

Okay well my mod was not for sending emails but instead redirects sub-domains to there aliased pathname, but you understand the concept shown here.

Edit: After I solved the issue I saw a comment saying a possible duplicate exists so I check it out and find out someone else has an extremely similar solution, but please don't mark it as a duplicate as he was asking about adding to a class that was already constructed, I want to override functions while constructing. My solution takes in an array of constructed classes and "merges" them into my main_class, This method does reserve the original functions but I can also call the original functions using another function to by-pass the __call function.

Thanks to anyone who posted answers.

Body:
Self-Solved :)
I have figured this out on my own and I'm sure someone else will find it useful so here is my php code.

class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}

Then simply run:

$MODS_ENABLED=array();
class mod_mail {...}
$MODS_ENABLED[]=new mod_mail;

Now all you need to do is just call your main class via.

$obj = new main_class(...);
$obj -> mail("root@localhost", "me@me.me", "Testing a mod.", "This email was sent via my main_class but this is a mod that extended main_class without renaming it.");

Okay this was not my usage but I'm sure you get the idea, My class is a CMS-back-end and my mod was a redirecting a few sub-domains to other locations, such as mail.sitegen.com.au and phpmyadmin.sitegen.com.au get redirected to there web-gui's out side of my CMS. I am also making more mods for my CMS.

BTW: my extensions are split into two categories, mods and plugins, mods run on every site that is powered by my CMS (SiteGen) and plug-ins have there own settings for each site and they are not required. In other words mods are chosen by me, and plug-ins are chosen by the owner of the site.


答:
Removing the margin-left: -9px from .topmenu seems to alleviate your issue.

body {

    background-image:url(images/background-awcc.png);
    background-repeat:no-repeat;
    background-size:100%;
    background-attachment: fixed;
    background-position: center;
    padding: 0 !important;
    margin: 0 !important;

}

/* Top Menu All Pages */

.topmenu {

    padding:30px;
    background-color:rgba(55, 21, 21, 1);
    border-right:solid rgba(55, 21, 21, 1);
    margin-top:-9px;
    text-align:center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    box-sizing : border-box;
}

.topmenulink {

    padding:30px;
    color:antiquewhite;
    text-decoration:none;
}

.topmenulink:visited  {```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
        <div class="topmenu">

            My Account
            Appointments
            Tutors
            Clients
            Schedule
            Statistics
            Help
            Logout

        </div>
    </div></code>```

Title: Blank space at the right of the div which has width:100% property

Body:
Removing the margin-left: -9px from .topmenu seems to alleviate your issue.

body {

    background-image:url(images/background-awcc.png);
    background-repeat:no-repeat;
    background-size:100%;
    background-attachment: fixed;
    background-position: center;
    padding: 0 !important;
    margin: 0 !important;

}

/* Top Menu All Pages */

.topmenu {

    padding:30px;
    background-color:rgba(55, 21, 21, 1);
    border-right:solid rgba(55, 21, 21, 1);
    margin-top:-9px;
    text-align:center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    box-sizing : border-box;
}

.topmenulink {

    padding:30px;
    color:antiquewhite;
    text-decoration:none;
}

.topmenulink:visited  {

<div id="wrapper">
        <div class="topmenu">

            <a class="topmenulink" href="myaccount.php">My Account</a>
            <a class="topmenulink" href="appointments.php">Appointments</a>
            <a class="topmenulink" href="tutors.php">Tutors</a>
            <a class="topmenulink" href="clients.php">Clients</a>
            <a class="topmenulink" href="schedule.php">Schedule</a>
            <a class="topmenulink" href="statistics.php">Statistics</a>
            <a class="topmenulink" href="help.php">Help</a>
            <a class="topmenulink" href="logout.php">Logout</a>

        </div>
    </div>


问:
C++ Using Method on Vector (If is word)
So I have a couple methods defined, one checks if the next is a word, one checks if there is a next word.

I take inputs for the text files, add the files content to a vector, then use the for loop

I can make it work by simply doing a for loop through the vector:

```<code> for (int x = 0; x != v2.size(); ++x) {
</code>```

But I want to use my two methods

```<code>bool ReadWords::isNextWord()
</code>```

and

```<code>string ReadWords::getNextWord()
{
 //take the input of the file until end of list is reached and return it

}
</code>```

So how would I do something like

```<code>vector<string> bigTextFile;
vector<string> vct;

while(vct.isNextWord) {
      vct.getNextWord

      if(vct.getNextWord == bigTextFile[i] {
         counter++
     }
}
</code>```

Let me know if you need any more of the code

答:
I'm not sure why are you trying to write an object, but here is how I would have approached the problem:

Step 1. Create a predicate for the words

```<code>bool is_needed_word(const std::string& word, const std::vector<std::string>& needed_words)
{
    if (std::find(needed_words.begin(),
                  needed_words.end(),
                  word) != needed_words.end())
        return true;
}

//some where in your function
std::vector<std::string> needed_words{"apple", "moon", "etc"};
auto predicate = [&needed_words](const auto& word)
                 {return is_needed_word(word, needed_words);}
</code>```

Step 2. Copy/count/whatever you want to do with the words in the stream

```<code>//copying
std::vector<std::string> extracted_words;
std::ifstream input_file{"input.txt"};
//check if opened correctly
std::copy_if(std::istream_iterator<std::string>(input_file), {},
             std::back_inserter(extracted_words));

//counting
std::size_t occurrence_counter = std::count_if(std::istream_iterator<std::string>(input_file),{},predicate)
</code>```

Title: C++ Using Method on Vector (If is word)

Body:
So I have a couple methods defined, one checks if the next is a word, one checks if there is a next word.

I take inputs for the text files, add the files content to a vector, then use the for loop

I can make it work by simply doing a for loop through the vector:

 for (int x = 0; x != v2.size(); ++x) {

But I want to use my two methods

bool ReadWords::isNextWord()

and

string ReadWords::getNextWord()
{
 //take the input of the file until end of list is reached and return it

}

So how would I do something like

vector<string> bigTextFile;
vector<string> vct;

while(vct.isNextWord) {
      vct.getNextWord

      if(vct.getNextWord == bigTextFile[i] {
         counter++
     }
}

Let me know if you need any more of the code

Body:
I'm not sure why are you trying to write an object, but here is how I would have approached the problem:

Step 1. Create a predicate for the words

bool is_needed_word(const std::string& word, const std::vector<std::string>& needed_words)
{
    if (std::find(needed_words.begin(),
                  needed_words.end(),
                  word) != needed_words.end())
        return true;
}

//some where in your function
std::vector<std::string> needed_words{"apple", "moon", "etc"};
auto predicate = [&needed_words](const auto& word)
                 {return is_needed_word(word, needed_words);}

Step 2. Copy/count/whatever you want to do with the words in the stream

//copying
std::vector<std::string> extracted_words;
std::ifstream input_file{"input.txt"};
//check if opened correctly
std::copy_if(std::istream_iterator<std::string>(input_file), {},
             std::back_inserter(extracted_words));

//counting
std::size_t occurrence_counter = std::count_if(std::istream_iterator<std::string>(input_file),{},predicate)


问:
refresh_token grant type supplies another refresh token?
While developing my Spring Rest API I am noticing something I don't quite understand. I am using the refresh_token grant type. It works fine when I access /myapi/oauth/token?grant_type=refresh_token but I am confused as to why it returns a shiny new refresh token along with a new access token.

Wouldn't this render the expiration time of the refresh token useless? If they can use a refresh token to get another refresh token, wouldn't they have unlimited refresh tokens?

edit: relevant parts of OAuth config

```<code>@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private UserDetailsService userDetailsService;

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
    accessTokenConverter.setSigningKey("abcd1234");
    return accessTokenConverter;
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}

@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    return defaultTokenServices;
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("myclient")
            .secret("mysecret")
            .authorizedGrantTypes("password", "refresh_token")
            .scopes("read")
            .autoApprove("read")
            .accessTokenValiditySeconds(300)
            .refreshTokenValiditySeconds(12000);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
    tokenEnhancerChain.setTokenEnhancers(Arrays.accessTokenConverter()));
    endpoints
            .tokenStore(tokenStore())
            .tokenEnhancer(tokenEnhancerChain)
            .authenticationManager(authenticationManager)
            .userDetailsService(userDetailsService);
}

}
</code>```

答:
According to the OAuth2 spec (point H), it is okay to optionally return a new refresh token when refreshing the access token, so the behavior is inline with the spec.

Spring Boot provides the reuseRefreshToken flag to control this behavior. It is set to true by default, which means refresh tokens should be reused and it should not generate new refresh tokens when you request a new access token.

However, in case of JWT tokens, there is a open bug due to which, the flag value seems to be ignored and a new refresh token generated every time in JwtAccessTokenConverter#enhance() method.

Side Note: The reuseRefreshToken flag can be set on an instance of AuthorizationServerConfigurerAdapter or by exposing a bean of type DefaultTokenServices and setting the flag in it.

Body:
While developing my Spring Rest API I am noticing something I don't quite understand. I am using the refresh_token grant type. It works fine when I access /myapi/oauth/token?grant_type=refresh_token but I am confused as to why it returns a shiny new refresh token along with a new access token.

Wouldn't this render the expiration time of the refresh token useless? If they can use a refresh token to get another refresh token, wouldn't they have unlimited refresh tokens?

edit: relevant parts of OAuth config

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private UserDetailsService userDetailsService;

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
    accessTokenConverter.setSigningKey("abcd1234");
    return accessTokenConverter;
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}

@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    return defaultTokenServices;
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("myclient")
            .secret("mysecret")
            .authorizedGrantTypes("password", "refresh_token")
            .scopes("read")
            .autoApprove("read")
            .accessTokenValiditySeconds(300)
            .refreshTokenValiditySeconds(12000);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
    tokenEnhancerChain.setTokenEnhancers(Arrays.accessTokenConverter()));
    endpoints
            .tokenStore(tokenStore())
            .tokenEnhancer(tokenEnhancerChain)
            .authenticationManager(authenticationManager)
            .userDetailsService(userDetailsService);
}

}


问:
how to attribute to navigation (

) from an xml source navigation
HI,

my xml file is as follows

```<code><?xml version="1.0"?>
<config>
<nav>
    <home>
        <label>HOME</label>
        <controller>index</controller>
        <action>index</action>
    </home>

    <aboutus>
        <label>ABOUT US</label>
        <controller>about-us</controller>
        <action>index</action>
    </aboutus>

    <destination>
        <label>DESTINATION</label>
        <controller>destination</controller>
        <action>index</action>
    </destination>

</nav>
</config>
</code>```

for code in my layout.phtml file

```<code>    $config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/clientnav.xml', 'nav');
    $container = new Zend_Navigation($config);
    $this->navigation()->setContainer($container);
    echo $this->navigation();
</code>```

i get the result

```<code><ul class="navigation">
    <li class="active">
    <a href="/globaltours.com/public/">HOME</a>
    </li>
    <li>

    <a href="/globaltours.com/public/about-us">ABOUT US</a>
    </li>
</ul>
</code>```

but i want the result

```<code><ul class="navigation">
    <li class="active">
    <a href="/globaltours.com/public/">HOME</a>
    </li>

    <li classs="sep"></li>

    <li>

    <a href="/globaltours.com/public/about-us">ABOUT US</a>
    </li>
</ul>
</code>```

Note the separator between two list. Help me out.

答:
If you HAVE to have the sep there and you cannot amend your CSS as @trickwallett suggested then you can query the navigation directly and then iterate over it yourself. Note that if you do this you will need to apply your own ACL rules.

```<code>$config = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml');

$container = new Zend_Navigation($config);

$pages = $this->navigation($container)->findAllById("main");

foreach ($pages as $i => $page)
{
    if(!$page->getVisible())
        continue;

    echo $this->menu()->htmlify($page);
}
</code>```

There I use findAllById() but there are many others documented here

Title: how to attribute to navigation (<ul><li>) from an xml source navigation

Body:
HI,

my xml file is as follows

<?xml version="1.0"?>
<config>

    <home>
        HOME
        <controller>index</controller>
        <action>index</action>
    </home>

    <aboutus>
        ABOUT US
        <controller>about-us</controller>
        <action>index</action>
    </aboutus>

    <destination>
        DESTINATION
        <controller>destination</controller>
        <action>index</action>
    </destination>

</config>

for code in my layout.phtml file

    $config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/clientnav.xml', 'nav');
    $container = new Zend_Navigation($config);
    $this->navigation()->setContainer($container);
    echo $this->navigation();

i get the result

    HOME

    ABOUT US

but i want the result

    HOME

    ABOUT US

Note the separator between two list. Help me out.

Body:
If you HAVE to have the sep there and you cannot amend your CSS as @trickwallett suggested then you can query the navigation directly and then iterate over it yourself. Note that if you do this you will need to apply your own ACL rules.

$config = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml');

$container = new Zend_Navigation($config);

$pages = $this->navigation($container)->findAllById("main");

foreach ($pages as $i => $page)
{
    if(!$page->getVisible())
        continue;

    echo $this->menu()->htmlify($page);
}

There I use findAllById() but there are many others documented here


问:
Xamarin Forms UWP Capture Screenshot Include Signature Pad
I have a Xamarin Forms page using Signature Pad (https://github.com/xamarin/SignaturePad). I'm attempting to capture a screenshot of the entire view. It should include the signature as well.

However, using the following code I'm noticing the signature does not show up.

What is the best way to capture the full Page including the signature? (not just the signature)

```<code>public class ScreenshotService : IScreenshotService
{
    public async Task<byte[]> CaptureAsync()
    {
    var rtb = new RenderTargetBitmap();
    await rtb.RenderAsync(Window.Current.Content);

    var pixelBuffer = await rtb.GetPixelsAsync();
    var pixels = pixelBuffer.ToArray();

    // Useful for rendering in the correct DPI
    var displayInformation = DisplayInformation.GetForCurrentView();

    var stream = new InMemoryRandomAccessStream();
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
    BitmapAlphaMode.Premultiplied,
    (uint)rtb.PixelWidth,
    (uint)rtb.PixelHeight,
    displayInformation.RawDpiX,
    displayInformation.RawDpiY,
    pixels);

    await encoder.FlushAsync();
    stream.Seek(0);

    var readStram = stream.AsStreamForRead();
    var bytes = new byte[readStram.Length];
    readStram.Read(bytes, 0, bytes.Length);

    return bytes;
}
}
</code>```

答:
Here is my final implementation including converting to byte array. </p>

```<code>    public async Task<byte[]> CaptureAsync(Stream signatureStream)
    {
        var rtb = new RenderTargetBitmap();
        await rtb.RenderAsync(Window.Current.Content);

        var pixelBuffer = await rtb.GetPixelsAsync();
        var pixels = pixelBuffer.ToArray();

        var displayInformation = DisplayInformation.GetForCurrentView();
        var stream = new InMemoryRandomAccessStream();
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8,
        BitmapAlphaMode.Premultiplied,
        (uint)rtb.PixelWidth,
        (uint)rtb.PixelHeight,
        displayInformation.RawDpiX,
        displayInformation.RawDpiY,
        pixels);
        await encoder.FlushAsync();
        stream.Seek(0);
        var readStram = stream.AsStreamForRead();

        var pagebitmap = await GetSoftwareBitmap(readStram);
        var softwareBitmap = await GetSoftwareBitmap(signatureStream);

        CanvasDevice device = CanvasDevice.GetSharedDevice();
        CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, rtb.PixelWidth, rtb.PixelHeight, 96);

        using (var ds = renderTarget.CreateDrawingSession())
        {
            ds.Clear(Colors.White);
            var page = CanvasBitmap.CreateFromSoftwareBitmap(device, pagebitmap);
            var image = CanvasBitmap.CreateFromSoftwareBitmap(device, softwareBitmap);
            ds.DrawImage(page);
            ds.DrawImage(image, 50, 55);
        }

        InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
        await renderTarget.SaveAsync(randomAccessStream, CanvasBitmapFileFormat.Jpeg, 1f);

        var fileBytes = new byte[randomAccessStream.Size];
        using (var reader = new DataReader(randomAccessStream))
        {
            await reader.LoadAsync((uint)randomAccessStream.Size);
            reader.ReadBytes(fileBytes);
        }

        return fileBytes;
    }
</code>```

Body:
I have a Xamarin Forms page using Signature Pad (https://github.com/xamarin/SignaturePad). I'm attempting to capture a screenshot of the entire view. It should include the signature as well.

However, using the following code I'm noticing the signature does not show up.

What is the best way to capture the full Page including the signature? (not just the signature)

public class ScreenshotService : IScreenshotService
{
    public async Task<byte[]> CaptureAsync()
    {
    var rtb = new RenderTargetBitmap();
    await rtb.RenderAsync(Window.Current.Content);

    var pixelBuffer = await rtb.GetPixelsAsync();
    var pixels = pixelBuffer.ToArray();

    // Useful for rendering in the correct DPI
    var displayInformation = DisplayInformation.GetForCurrentView();

    var stream = new InMemoryRandomAccessStream();
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
    BitmapAlphaMode.Premultiplied,
    (uint)rtb.PixelWidth,
    (uint)rtb.PixelHeight,
    displayInformation.RawDpiX,
    displayInformation.RawDpiY,
    pixels);

    await encoder.FlushAsync();
    stream.Seek(0);

    var readStram = stream.AsStreamForRead();
    var bytes = new byte[readStram.Length];
    readStram.Read(bytes, 0, bytes.Length);

    return bytes;
}
}

Body:
Here is my final implementation including converting to byte array.

    public async Task<byte[]> CaptureAsync(Stream signatureStream)
    {
        var rtb = new RenderTargetBitmap();
        await rtb.RenderAsync(Window.Current.Content);

        var pixelBuffer = await rtb.GetPixelsAsync();
        var pixels = pixelBuffer.ToArray();

        var displayInformation = DisplayInformation.GetForCurrentView();
        var stream = new InMemoryRandomAccessStream();
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8,
        BitmapAlphaMode.Premultiplied,
        (uint)rtb.PixelWidth,
        (uint)rtb.PixelHeight,
        displayInformation.RawDpiX,
        displayInformation.RawDpiY,
        pixels);
        await encoder.FlushAsync();
        stream.Seek(0);
        var readStram = stream.AsStreamForRead();

        var pagebitmap = await GetSoftwareBitmap(readStram);
        var softwareBitmap = await GetSoftwareBitmap(signatureStream);

        CanvasDevice device = CanvasDevice.GetSharedDevice();
        CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, rtb.PixelWidth, rtb.PixelHeight, 96);

        using (var ds = renderTarget.CreateDrawingSession())
        {
            ds.Clear(Colors.White);
            var page = CanvasBitmap.CreateFromSoftwareBitmap(device, pagebitmap);
            var image = CanvasBitmap.CreateFromSoftwareBitmap(device, softwareBitmap);
            ds.DrawImage(page);
            ds.DrawImage(image, 50, 55);
        }

        InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
        await renderTarget.SaveAsync(randomAccessStream, CanvasBitmapFileFormat.Jpeg, 1f);

        var fileBytes = new byte[randomAccessStream.Size];
        using (var reader = new DataReader(randomAccessStream))
        {
            await reader.LoadAsync((uint)randomAccessStream.Size);
            reader.ReadBytes(fileBytes);
        }

        return fileBytes;
    }