问:
Get submatrix made from random rows and columns of large matix
I would like to extract (square) sub-matrices from a matrix, randomly with a size between some min and max values.

I would also like to retain the row and column indices which were selected.

Are there any built-in functions for this purpose? I would appreciate any general algorithm to achieve the desired results.

Just for an example without considering the square matrix constraint:

Input:

```<code>  | 1 2 3 4 5 6 7 8 <- column indices
--+----------------
1 | 4 3 1 4 0 1 0 1
2 | 2 0 1 5 6 3 2 0
3 | 5 5 0 6 7 8 9 0
4 | 2 3 5 6 7 9 0 1
^
Row indices
</code>```

Output sample:

```<code>  | 1 4 5 7 8 <- column indices
--+----------
1 | 4 4 0 0 1
2 | 2 5 6 2 0
4 | 2 6 7 0 1
^
Row indices
</code>```

Edit: I would like to have a function like this

```<code>matrixsample(numberOfSamples, minSize, maxSize, satisfyingFunction)
</code>```

the samples should vary their size between the minSize and maxSize.

If numberOfSamples = 10, minSize = 2 and maxSize = 6 then output should be randomly selected rows and columns like:

```<code>sampleMatrix1 2x2 sampleMatrix2 3x3 sampleMatrix3 5x5 ... sampleMatrix7 6x6 ... sampleMatrx10 4x4
</code>```

satisfyingFunction could test any attribute of the matrix; like being non-singular, rank > x, etc.

答:
If the table is given, you will do it by randsample:

```<code> minRowVal = 3;
 maxRowVal = 4;
 minColVal = 2;
 maxColVal = 4;
 kRow = randi([minRowVal maxRowVal]) ;
 kCol = randi([minColVal maxColVal]);
table(sort(randsample(size(table,1),kRow)),sort(randsample(size(table,2),kCol))
</code>```

choose some sample by the given size of kRow and kCol, then select the information from the table.

Body:
I would like to extract (square) sub-matrices from a matrix, randomly with a size between some min and max values.

I would also like to retain the row and column indices which were selected.

Are there any built-in functions for this purpose? I would appreciate any general algorithm to achieve the desired results.

Just for an example without considering the square matrix constraint:

Input:

  | 1 2 3 4 5 6 7 8 <- column indices
--+----------------
1 | 4 3 1 4 0 1 0 1
2 | 2 0 1 5 6 3 2 0
3 | 5 5 0 6 7 8 9 0
4 | 2 3 5 6 7 9 0 1
^
Row indices

Output sample:

  | 1 4 5 7 8 <- column indices
--+----------
1 | 4 4 0 0 1
2 | 2 5 6 2 0
4 | 2 6 7 0 1
^
Row indices

Edit: I would like to have a function like this

matrixsample(numberOfSamples, minSize, maxSize, satisfyingFunction)

the samples should vary their size between the minSize and maxSize.

If numberOfSamples = 10, minSize = 2 and maxSize = 6 then output should be randomly selected rows and columns like:

sampleMatrix1 2x2 sampleMatrix2 3x3 sampleMatrix3 5x5 ... sampleMatrix7 6x6 ... sampleMatrx10 4x4

satisfyingFunction could test any attribute of the matrix; like being non-singular, rank > x, etc.

Body:
If the table is given, you will do it by randsample:

 minRowVal = 3;
 maxRowVal = 4;
 minColVal = 2;
 maxColVal = 4;
 kRow = randi([minRowVal maxRowVal]) ;
 kCol = randi([minColVal maxColVal]);
table(sort(randsample(size(table,1),kRow)),sort(randsample(size(table,2),kCol))

choose some sample by the given size of kRow and kCol, then select the information from the table.


来源: stackexchange

问:
Porting permutation function from Python to C++
I've been using an algorithm from a Stack Overflow answer: https://stackoverflow.com/a/9650593/4771889
Namely the permute2() function.

I've changed things a little for my purposes, and it generates the correct data that I need.

Here is my Python version:

```<code>def permute(list, nextFixable, num, begin, end):
    if end == begin + 1:
        yield list
    else:
        for i in range(begin, end):
            if nextFixable[list[i]] == num[i]:
                nextFixable[list[i]] += 1
                num[begin], num[i] = num[i], num[begin]
                list[begin], list[i] = list[i], list[begin]
                for p in permute(list, nextFixable, num, begin + 1, end):
                    yield p
                list[begin], list[i] = list[i], list[begin]
                num[begin], num[i] = num[i], num[begin]
                nextFixable[list[i]] -= 1

if __name__ == "__main__":
    list = [0, 1, 2]
    nextFixable = {0:0, 1:0, 2:0}
    num = [0, 0, 0]

    for p in permute(list, nextFixable, num, 0, len(list)):
        print(p)
</code>```

I've simplified the usage a little there to give a basic example.

The output of this example is:

```<code>[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 1, 0]
[2, 0, 1]
</code>```

Since my practical usage for this is for longer lists (not the trivial "0, 1, 2") I REALLY like the generator functionality used here (the yield statements).

The problem is that Python is slow, and I sometimes have to wait a couple days to get a result.

I'm not a C++ expert, but previously I've found that C++ is much faster when compared with Python.  So you can guess what I did next - I tried to rewrite this in C++ (Visual Studio 2015).

Here's what I came up with:

```<code>#include "stdafx.h"

#include <iostream> // for std::cout
#include <vector> // for std::vector
#include <map> // for std::map

// https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
#include <experimental/generator>
using namespace std::experimental;
using namespace std;

using std::cout;
using std::vector;
using std::map;

void print(vector<unsigned short> data) {
    cout << "[";
    for (unsigned short i = 0; i < data.size(); ++i) {
        cout << (int)data[i];
        if (i < data.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]\n";
}

generator<vector<unsigned short>> permute(
    vector<unsigned short> list,
    map<unsigned short, unsigned short> nextFixable,
    vector<unsigned short> num,
    unsigned short begin,
    unsigned short end
) {
    if (end == begin + 1) {
        __yield_value list;
    }
    else {
        for (unsigned short i = begin; i < end; ++i) {
            if (nextFixable[list[i]] == num[i]) {
                nextFixable[list[i]]++;
                swap(num[begin], num[i]);
                swap(list[begin], list[i]);
                for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
                    __yield_value p;
                    swap(list[begin], list[i]);
                    swap(num[begin], num[i]);
                    nextFixable[list[i]]--;
                }
            }
        }
    }
}

int main()
{
    vector<unsigned short> list = { 0, 1, 2 };
    map<unsigned short, unsigned short> nextFixable = { {0, 0}, {1, 0}, {2, 0} };
    vector<unsigned short> num = { 0, 0, 0 };

    for (auto p : permute(list, nextFixable, num, 0, (unsigned short)list.size())) {
        print(p);
    }

    // Keep output window open.
    std::getchar();
    return 0;
}
</code>```

You can see I've referenced https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
which is what gives me the __yield_value feature.   (I presume this isn't portable, which is indeed going to be a problem for me eventually as I would prefer to run this in linux down the track, but for some early experiments it does the trick.)

The code runs fine, but the output is:

```<code>[0, 1, 2]
[0, 2, 1]
[1, 2, 0]
[2, 1, 0]
</code>```

So let's compare to the Python output - it seems we have two lines missing:

```<code>[0, 1, 2] - Yes
[0, 2, 1] - Yes
[1, 0, 2] - Missing
[1, 2, 0] - Yes
[2, 1, 0] - Yes
[2, 0, 1] - Missing
</code>```

Usually at this point of writing a SO question, the answer jumps out at me from having to explain the problem.  In this case it hasn't.

It's possible I've made an incorrect language assumption, and I don't have the knowledge to correct myself.

So to boil the question down - why is my port of the permute() function from Python to C++ not giving me the same output?

答:
I decided not to go to sleep tonight and find the answer by adding verbose debugging to both versions of the algorithm and studying how they differ.

The problem is this section of code:

```<code>        for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
            __yield_value p;
            swap(list[begin], list[i]);
            swap(num[begin], num[i]);
            nextFixable[list[i]]--;
        }
</code>```

To match the python it should be:

```<code>        for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
            __yield_value p;
        }
        swap(list[begin], list[i]);
        swap(num[begin], num[i]);
        nextFixable[list[i]]--;
</code>```

Possibly when pasting the Python code into VS it helpfully lined everything up, and thanks to Python's convenient lack of braces, when comparing the code again this went unnoticed.

This triggered a second issue where nextFixable[whatever] would decrement below 0 on an unsigned integer and overflow - but that's what gave it away.

(However as noted in comments I have taken on board the suggestion to use std:next_permutation in a do-while loop in conjunction with a std:sort beforehand.  That solution has in a simple experiment proven to be about 5-6 times faster than this algorithm.)

ContentLicense: CC BY-SA 3.0

Body:
I've been using an algorithm from a Stack Overflow answer: https://stackoverflow.com/a/9650593/4771889
Namely the permute2() function.

I've changed things a little for my purposes, and it generates the correct data that I need.

Here is my Python version:

def permute(list, nextFixable, num, begin, end):
    if end == begin + 1:
        yield list
    else:
        for i in range(begin, end):
            if nextFixable[list[i]] == num[i]:
                nextFixable[list[i]] += 1
                num[begin], num[i] = num[i], num[begin]
                list[begin], list[i] = list[i], list[begin]
                for p in permute(list, nextFixable, num, begin + 1, end):
                    yield p
                list[begin], list[i] = list[i], list[begin]
                num[begin], num[i] = num[i], num[begin]
                nextFixable[list[i]] -= 1

if __name__ == "__main__":
    list = [0, 1, 2]
    nextFixable = {0:0, 1:0, 2:0}
    num = [0, 0, 0]

    for p in permute(list, nextFixable, num, 0, len(list)):
        print(p)

I've simplified the usage a little there to give a basic example.

The output of this example is:

[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 1, 0]
[2, 0, 1]

Since my practical usage for this is for longer lists (not the trivial "0, 1, 2") I REALLY like the generator functionality used here (the yield statements).

The problem is that Python is slow, and I sometimes have to wait a couple days to get a result.

I'm not a C++ expert, but previously I've found that C++ is much faster when compared with Python.  So you can guess what I did next - I tried to rewrite this in C++ (Visual Studio 2015).

Here's what I came up with:

#include "stdafx.h"

#include <iostream> // for std::cout
#include <vector> // for std::vector
#include <map> // for std::map

// https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
#include <experimental/generator>
using namespace std::experimental;
using namespace std;

using std::cout;
using std::vector;
using std::map;

void print(vector<unsigned short> data) {
    cout << "[";
    for (unsigned short i = 0; i < data.size(); ++i) {
        cout << (int)data[i];
        if (i < data.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]\n";
}

generator<vector<unsigned short>> permute(
    vector<unsigned short> list,
    map<unsigned short, unsigned short> nextFixable,
    vector<unsigned short> num,
    unsigned short begin,
    unsigned short end
) {
    if (end == begin + 1) {
        __yield_value list;
    }
    else {
        for (unsigned short i = begin; i < end; ++i) {
            if (nextFixable[list[i]] == num[i]) {
                nextFixable[list[i]]++;
                swap(num[begin], num[i]);
                swap(list[begin], list[i]);
                for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
                    __yield_value p;
                    swap(list[begin], list[i]);
                    swap(num[begin], num[i]);
                    nextFixable[list[i]]--;
                }
            }
        }
    }
}

int main()
{
    vector<unsigned short> list = { 0, 1, 2 };
    map<unsigned short, unsigned short> nextFixable = { {0, 0}, {1, 0}, {2, 0} };
    vector<unsigned short> num = { 0, 0, 0 };

    for (auto p : permute(list, nextFixable, num, 0, (unsigned short)list.size())) {
        print(p);
    }

    // Keep output window open.
    std::getchar();
    return 0;
}

You can see I've referenced https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
which is what gives me the __yield_value feature.   (I presume this isn't portable, which is indeed going to be a problem for me eventually as I would prefer to run this in linux down the track, but for some early experiments it does the trick.)

The code runs fine, but the output is:

[0, 1, 2]
[0, 2, 1]
[1, 2, 0]
[2, 1, 0]

So let's compare to the Python output - it seems we have two lines missing:

[0, 1, 2] - Yes
[0, 2, 1] - Yes
[1, 0, 2] - Missing
[1, 2, 0] - Yes
[2, 1, 0] - Yes
[2, 0, 1] - Missing

Usually at this point of writing a SO question, the answer jumps out at me from having to explain the problem.  In this case it hasn't.

It's possible I've made an incorrect language assumption, and I don't have the knowledge to correct myself.

So to boil the question down - why is my port of the permute() function from Python to C++ not giving me the same output?

Body:
I decided not to go to sleep tonight and find the answer by adding verbose debugging to both versions of the algorithm and studying how they differ.

The problem is this section of code:

        for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
            __yield_value p;
            swap(list[begin], list[i]);
            swap(num[begin], num[i]);
            nextFixable[list[i]]--;
        }

To match the python it should be:

        for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
            __yield_value p;
        }
        swap(list[begin], list[i]);
        swap(num[begin], num[i]);
        nextFixable[list[i]]--;

Possibly when pasting the Python code into VS it helpfully lined everything up, and thanks to Python's convenient lack of braces, when comparing the code again this went unnoticed.

This triggered a second issue where nextFixable[whatever] would decrement below 0 on an unsigned integer and overflow - but that's what gave it away.

(However as noted in comments I have taken on board the suggestion to use std:next_permutation in a do-while loop in conjunction with a std:sort beforehand.  That solution has in a simple experiment proven to be about 5-6 times faster than this algorithm.)


问:
Mockito : Testing boolean method with when()..then()
I found a similar question here: Mockito when()...then() NullPointerException
but in that question method to be tested was static.

I have a class with a boolean method to be tested. The test class gives NULLPOINTEREXCEPTION on the when()..then() line.

Thanks for your help.

Class to be tested

```<code>   public class FMBaseController implements FMHandler {

    private PlayerHandler player;

    public FMBaseController(PlayerHandler player) {
        this.player = player;
    }

    @Override
    public boolean boostValue(FamilyMember fm, int increase) {
        if (player.getResourceHandler().getServants() < increase)
            return false;
        return true;
</code>```

Tested class

```<code>public class FMBaseControllerTest {

    //class to test
    private FMBaseController fmBase;

    //dependencies (these will be mocked)
    private FamilyMember fm;
    private PlayerHandler playerHandler;

    @Before
    public void setUp() throws Exception {

        fm = mock(FamilyMember.class);
        playerHandler = mock(PlayerHandler.class);

        fmBase = new FMBaseController(playerHandler);

    }

    @Test
    public void boostValueTest() {

        when(playerHandler.getResourceHandler().getServants()).thenReturn(3).thenReturn(5);

    //3 is less than 4 . assert you cannot boost
    Boolean bool1  = fmBase.boostValue(fm, 4);
    assertFalse( bool1 );

    //5 is not less than 4 . assert you can boost
    Boolean bool2  = fmBase.boostValue(fm, 4);
    assertTrue( bool2 );
    }
}
</code>```

FAILURE TRACE

```<code>FMBaseControllerTest
******.server.controller.FMBaseControllerTest
boostValueTest(******.server.controller.FMBaseControllerTest)
java.lang.NullPointerException

    at ******.server.controller.FMBaseControllerTest.boostValueTest(FMBaseControllerTest.java:44)
</code>```

答:
This happens because of the default behaviour of Mockito, described in the docs:

By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

Taking your call as an example playerHandler.getResourceHandler().getServants(), the playerHandler mock has no specified behaviour for the getResourceHandler() method, so it will return null, hence null.getServants() results in a NPE.

You can change this in at least the following 2 fashions:

define a behaviour for your method as @sbjavateam suggested to return another mock ResourceHandler:

    ResourceHandler resourceHandler = mock(resourceHandler.class);
    when(playerHandler.getResourceHandler()).thenReturn(resourceHandler);
```

<ul>
<li>configure Mockito to return deep stubs:</li>
</ul>

<blockquote>
  <p>Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing</p>
</blockquote>

<pre class="lang-java prettyprint-override"><code>    playerHandler = mock(PlayerHandler.class, RETURNS_DEEP_STUBS);
</code>```

    or, if you're using annotations:

   @Mock(answer = Answers.RETURNS_DEEP_STUBS)
   PlayerHandler playerHandler;
```

Nonetheless, while it's sometimes useful to do it, you should also take into account that:

WARNING: This feature should rarely be required for regular clean code! Leave it for legacy code. Mocking a mock to return a mock, to return a mock, (...), to return something meaningful hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).

Good quote I've seen one day on the web: every time a mock returns a mock a fairy dies.

Please note that this answer will return existing mocks that matches the stub. This behavior is ok with deep stubs and allows verification to work on the last mock of the chain.

Body:
I found a similar question here: Mockito when()...then() NullPointerException
but in that question method to be tested was static.

I have a class with a boolean method to be tested. The test class gives NULLPOINTEREXCEPTION on the when()..then() line.

Thanks for your help.

Class to be tested

   public class FMBaseController implements FMHandler {

    private PlayerHandler player;

    public FMBaseController(PlayerHandler player) {
        this.player = player;
    }

    @Override
    public boolean boostValue(FamilyMember fm, int increase) {
        if (player.getResourceHandler().getServants() < increase)
            return false;
        return true;

Tested class

public class FMBaseControllerTest {

    //class to test
    private FMBaseController fmBase;

    //dependencies (these will be mocked)
    private FamilyMember fm;
    private PlayerHandler playerHandler;

    @Before
    public void setUp() throws Exception {

        fm = mock(FamilyMember.class);
        playerHandler = mock(PlayerHandler.class);

        fmBase = new FMBaseController(playerHandler);

    }

    @Test
    public void boostValueTest() {

        when(playerHandler.getResourceHandler().getServants()).thenReturn(3).thenReturn(5);

    //3 is less than 4 . assert you cannot boost
    Boolean bool1  = fmBase.boostValue(fm, 4);
    assertFalse( bool1 );

    //5 is not less than 4 . assert you can boost
    Boolean bool2  = fmBase.boostValue(fm, 4);
    assertTrue( bool2 );
    }
}

FAILURE TRACE

FMBaseControllerTest
******.server.controller.FMBaseControllerTest
boostValueTest(******.server.controller.FMBaseControllerTest)
java.lang.NullPointerException

    at ******.server.controller.FMBaseControllerTest.boostValueTest(FMBaseControllerTest.java:44)

Body:
This happens because of the default behaviour of Mockito, described in the docs:

By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

Taking your call as an example playerHandler.getResourceHandler().getServants(), the playerHandler mock has no specified behaviour for the getResourceHandler() method, so it will return null, hence null.getServants() results in a NPE.

You can change this in at least the following 2 fashions:

define a behaviour for your method as @sbjavateam suggested to return another mock ResourceHandler:

    ResourceHandler resourceHandler = mock(resourceHandler.class);
    when(playerHandler.getResourceHandler()).thenReturn(resourceHandler);

configure Mockito to return deep stubs:

Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing

    playerHandler = mock(PlayerHandler.class, RETURNS_DEEP_STUBS);

    or, if you're using annotations:

   @Mock(answer = Answers.RETURNS_DEEP_STUBS)
   PlayerHandler playerHandler;

Nonetheless, while it's sometimes useful to do it, you should also take into account that:

WARNING: This feature should rarely be required for regular clean code! Leave it for legacy code. Mocking a mock to return a mock, to return a mock, (...), to return something meaningful hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).

Good quote I've seen one day on the web: every time a mock returns a mock a fairy dies.

Please note that this answer will return existing mocks that matches the stub. This behavior is ok with deep stubs and allows verification to work on the last mock of the chain.


问:
how to know when an action was performed and close automatically the modal
Let's consider the situation where we send, for example, a request and we are waiting a response.
While we are waiting a modal pops-up with a glyphicon, showing that the request is being processed. The result of this process is going to be an object, when it is null it means that the request was accepted with success, otherwise this object will come with an error message.
I would like to close the modal after receiving the notification, no matter if it was successful or not
can anyone give me an hint of java and wicket?</p>

答:
If you want to close the modal window after notification recieved, you can make this modal window invinsible, just:

```<code>public void recieveNotification(AjaxRequestTarget target) {
    Notification notification = service.getNotification;
    target.add(modalWindow.setVisible(false));
}
</code>```

and you wouldn't see it.

Body:
If you want to close the modal window after notification recieved, you can make this modal window invinsible, just:

public void recieveNotification(AjaxRequestTarget target) {
    Notification notification = service.getNotification;
    target.add(modalWindow.setVisible(false));
}

and you wouldn't see it.


问:
All my fields are tabindex=-1 in my editview
I've created a custom module based on people template.

i've customised the editView (which is synced with the detailView) and I have assigned a tabindex value for every field.

But when I use that editView almost every field has tabindex=-1 so I only can't get to them using my mouse, which is very slow.

I was changing include/EditView/EditView.tpl but it looks the changes there has no effect on the generated code.

I changed all tabindex=$tabindex for a tabindex="-3", "-4", "5" in every tabindex assignment, but I couldn't see it in my html page, I also tried making a QRR previously.

So my question is where can I fix that -1 issue or, at least, where is really being generated my editView.

Thanks in advance!!!

答:
Well! I found a workaround... I guessed that the problem was the autogenerated fields, they had no "space" among another fields's tabindex values...

So, instead of giving the fields tabindex values of 1, 2, 3, 4... I gave them as 10, 20, 30, 40...

And, against all odds, it works!

Perhaps it's useful for somebody....


问:
Java Casting to superclass not change object type?
I don't understand why this code outputs false. Java uses the object type (not reference) to choose the [instance] method to execute, in this case, initial object type is Owl (with method returns false), anyway, We cast this type to "Nocturnal" (not necessary, but We do). I have isBlind() method in the interface and the class.

Why our Owl converted to Nocturnal using a explicit Cast prints false, if the object type now is Nocturnal and the Nocturnal method prints true?

```<code>interface Nocturnal {
    default boolean isBlind() {
        return true;
    }
}

public class Owl implements Nocturnal {
    public boolean isBlind() {
        return false;
    }

    public static void main(String[] args) {
        Nocturnal nocturnal = (Nocturnal) new Owl();
        System.out.println(nocturnal.isBlind());
    }
}
</code>```

答:
When a sub class overrides a method of its base class then each invocation of the overridden method from outside the sub class (including the base class) will always result in invoking the overriden method.

The casting has no impact on the behavior of the method. If its overriden its overridden for the outside world.

Only way to invoke the method as per behavior provided by base class is by using super keyword with . ( dot operator ) from inside the instance method of the sub class.

Body:
I don't understand why this code outputs false. Java uses the object type (not reference) to choose the [instance] method to execute, in this case, initial object type is Owl (with method returns false), anyway, We cast this type to "Nocturnal" (not necessary, but We do). I have isBlind() method in the interface and the class.

Why our Owl converted to Nocturnal using a explicit Cast prints false, if the object type now is Nocturnal and the Nocturnal method prints true?

interface Nocturnal {
    default boolean isBlind() {
        return true;
    }
}

public class Owl implements Nocturnal {
    public boolean isBlind() {
        return false;
    }

    public static void main(String[] args) {
        Nocturnal nocturnal = (Nocturnal) new Owl();
        System.out.println(nocturnal.isBlind());
    }
}


问:
Flatten nested arrays in java
I want to flatten nested arrays like:

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

manually in java I can't find a clue ! :S

I have tried a manual java script guide but it doesn't get a solution

public static void main(String[] args) {

  Object arr[] = { 1, 2, new Object[] { 4, new int[] { 5, 6 }, 7 }, 10 };
  String deepToString = Arrays.deepToString(arr);
  String replace = deepToString.replace("[", "").replace("]", "");
  String array[] = replace.split(",");
  int temp[] = new int[array.length];
  for (int i = 0; i < array.length; i++) {
    temp[i] = Integer.parseInt(array[i].trim());
  }
  System.out.println(Arrays.toString(temp));
}
```

答:
The Stream API offers a compact and flexible solution. Using the method

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[] a? flatten(a): Stream.of(o));
}
```
<p>or prior to JDK 16</p>
<pre class="lang-java prettyprint-override"><code>private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}
</code>```

you can perform the operation as

```<code>Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10 };
System.out.println("original: "+Arrays.deepToString(array));

Object[] flat = flatten(array).toArray();
System.out.println("flat:     "+Arrays.toString(flat));
</code>```

or when you assume the leaf objects to be of a specific type:

```<code>int[] flatInt = flatten(array).mapToInt(Integer.class::cast).toArray();
System.out.println("flat int: "+Arrays.toString(flatInt));
</code>```

ContentLicense: CC BY-SA 4.0

Title: Flatten nested arrays in java

Body:
I want to flatten nested arrays like:

[[[1],2],[3]],4] -> [1,2,3,4]

manually in java I can't find a clue ! :S

I have tried a manual java script guide but it doesn't get a solution

public static void main(String[] args) {

  Object arr[] = { 1, 2, new Object[] { 4, new int[] { 5, 6 }, 7 }, 10 };
  String deepToString = Arrays.deepToString(arr);
  String replace = deepToString.replace("[", "").replace("]", "");
  String array[] = replace.split(",");
  int temp[] = new int[array.length];
  for (int i = 0; i < array.length; i++) {
    temp[i] = Integer.parseInt(array[i].trim());
  }
  System.out.println(Arrays.toString(temp));
}

Body:
The Stream API offers a compact and flexible solution. Using the method

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[] a? flatten(a): Stream.of(o));
}

or prior to JDK 16

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}

you can perform the operation as

Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10 };
System.out.println("original: "+Arrays.deepToString(array));

Object[] flat = flatten(array).toArray();
System.out.println("flat:     "+Arrays.toString(flat));

or when you assume the leaf objects to be of a specific type:

int[] flatInt = flatten(array).mapToInt(Integer.class::cast).toArray();
System.out.println("flat int: "+Arrays.toString(flatInt));


问:
Passing data to server before page is rendered in node.js?
After a user login, the data is stored on a client side.

There are some pages which don't require a logged user to be viewed...

for example, I have a route on node.js which render a profile page through a URL parameter.

```<code>app.get("Profile/:id",function(req,res){ //render page and send it.}
</code>```

anyone can see this page... but here is the situation... in my app, users can post notes on this pages so they can see it later. So the idea is, if a user is logged in when the user access that page he can see all his notes.

the data of the notes are in server side.

So my question is...
how can I pass the user data into app.get("profile/:id "... function so that the notes can be loaded and sent when is rendered
...

one thing is important to be known. I have a solution in wich I pass a unique key though the url which references to the active socket of the user so that the data is post on a json, is there any other way to pass data from client to server before the page is rendered?

答:
After several days I have manage to achieve the resolution of this question

The idea is to have a Session tipe variable like $_SESSION in php.

you need express-session npm and assign session on require parameter on a express post function. After you have set a value, every time that browser change from location, you can extract that same session variable and use the data to post a response when you are rendering.

I used ejs to render.

In the next link, there is a full tutorial to achieve this.

https://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/

Body:
After a user login, the data is stored on a client side.

There are some pages which don't require a logged user to be viewed...

for example, I have a route on node.js which render a profile page through a URL parameter.

app.get("Profile/:id",function(req,res){ //render page and send it.}

anyone can see this page... but here is the situation... in my app, users can post notes on this pages so they can see it later. So the idea is, if a user is logged in when the user access that page he can see all his notes.

the data of the notes are in server side.

So my question is...
how can I pass the user data into app.get("profile/:id "... function so that the notes can be loaded and sent when is rendered
...

one thing is important to be known. I have a solution in wich I pass a unique key though the url which references to the active socket of the user so that the data is post on a json, is there any other way to pass data from client to server before the page is rendered?


问:
How to delete a row from AP_PAYMENT_SCHEDULES_ALL Oracle R12 table?
Please I need to know how to delete a row from AP_PAYMENT_SCHEDULES_ALL table in oracle R12?

Thanks in advance

答:
Why you want to delete all rows? If you can't use HOLD_FLAG to 'Y' to place a hold on the scheduled payment ?
- Abhi</p>


问:
Disabling input field based on radio button in Angular 2
Say i have these radiobutton, i make a click function localClick and for first button it should have 1 and second give value 2

```<code><div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"></p-radioButton></div>
<div class="ui-g-12"><p-radioButton name="group1" value="Remote" label="Remote" (click)=localClick(2) ></p-radioButton></div>
</code>```

now i want my input field

```<code>Example

 <input id="pass" type="text" style="width:80%" disabled="exampleFlag" pInputText [(ngModel)]="password">
</code>```

I googled a bit and added this thing, disabled=exampleFlag and now in the ts file i set it to true or false based on which radiobutton was clicked so i do

```<code>exampleFlag=false; // set it to false initially so box is not disabled
localClick(x) {
if(x==1){
  this.exampleFlag=true;
}
else{
  this.exampleFlag=false;
}
}
</code>```

basically what im doing here is that if the first radiobutton is clicked then set it to true (so that the box will get disabled) but otherwise it should be enabled whether no buttons are selected or whether the 2nd radio button is selected.

I am new to this but i googled aa bit and came up to solutions like this however for me the box always stays disabled no matter what i do.

I think the mistake im making is the way the (click) thing is being defined in html file and maybe in the ts file also but im not sure.

答:
Wrap disabled in square brackets to bind it to an attribute value.</p>

```<code><input id="pass" type="text" style="width:80%" [disabled]="exampleFlag" pInputText [(ngModel)]="password">
</code>```

Body:
Say i have these radiobutton, i make a click function localClick and for first button it should have 1 and second give value 2

now i want my input field

Example

 <input id="pass" type="text" style="width:80%" disabled="exampleFlag" pInputText [(ngModel)]="password">

I googled a bit and added this thing, disabled=exampleFlag and now in the ts file i set it to true or false based on which radiobutton was clicked so i do

exampleFlag=false; // set it to false initially so box is not disabled
localClick(x) {
if(x==1){
  this.exampleFlag=true;
}
else{
  this.exampleFlag=false;
}
}

basically what im doing here is that if the first radiobutton is clicked then set it to true (so that the box will get disabled) but otherwise it should be enabled whether no buttons are selected or whether the 2nd radio button is selected.

I am new to this but i googled aa bit and came up to solutions like this however for me the box always stays disabled no matter what i do.

I think the mistake im making is the way the (click) thing is being defined in html file and maybe in the ts file also but im not sure.

Body:
Wrap disabled in square brackets to bind it to an attribute value.

<input id="pass" type="text" style="width:80%" [disabled]="exampleFlag" pInputText [(ngModel)]="password">


问:
R peak and valley filltering with threshold
I am using below code to list out Peaks and Valleys.

```<code>x_last <- as.numeric(series[1])
x <- as.numeric(series[2])
d_last <- (x-x_last)
series[1:2] <- NULL
output <- list()

for (x_next in series){
  if (x_next == x){
    next}
  d_next <- (x_next - x)
  if (d_last * d_next < 0){
    output <- append(output, x)}
  x_last <- x
  x <- x_next
  d_last <- d_next
}
</code>```

Here Output(list) contains "continuous Peaks and Valleys".

```<code>Output <- c(41.49916, 37.92029, 39.86477, 39.86432, 39.95672, 39.95465, 39.96144, 39.83994, 40.43357, 40.11285, 40.82250, 39.37034, 58.82975, 42.19894)
</code>```

so on...

the graph plotted using Output(list). My question is how to add threshold in this code? or how can i remove small Peaks and Valleys(values less than 1). I Need continuous Peaks and valleys.

Looking for answers. thank you in advance.

答:
If you just want to plot your data:

You could plot this with ggplot2 and add a geom_smooth() layer. It defaults to method "loess" which is kind of a "do-the-right-thing" smoother for small datasets.

```<code>dat <- data.frame(y=c(41.49916, 37.92029, 39.86477, 39.86432, 39.95672, 39.95465, 39.96144, 39.83994, 40.43357, 40.11285, 40.82250, 39.37034, 58.82975, 42.19894))
dat$x <- 1:length(dat$y)
library(ggplot2)

ggplot(dat, aes(x, y)) +
        geom_line() +
        geom_smooth(method="loess", se=FALSE)
</code>```

?

Or do you rather want to smoothen the data yourself? (Your data series is quite short for that.) Do you need an equation for the fit? It's easy to spend quite some time on that.

I don't fully understand this "peak/valley" stuff. In any case, take a look at the diff() function. Maybe this helps:

```<code>dat <- data.frame(y=c(41.49916, 37.92029, 39.86477, 39.86432, 39.95672, 39.95465, 39.96144, 39.83994, 40.43357, 40.11285, 40.82250, 39.37034, 58.82975, 42.19894))
dat[which(diff(dat$y) < 0.01)+1,"y"] <- NA
dat$y

 [1] 41.50    NA 39.86    NA 39.96    NA    NA    NA 40.43    NA 40.82    NA
[13] 58.83    NA
</code>```

Here I've used a threshold of 0.01.
I'm not sure if it's the right thing. But you can adapt this code for your needs.

Body:
I am using below code to list out Peaks and Valleys.

x_last <- as.numeric(series[1])
x <- as.numeric(series[2])
d_last <- (x-x_last)
series[1:2] <- NULL
output <- list()

for (x_next in series){
  if (x_next == x){
    next}
  d_next <- (x_next - x)
  if (d_last * d_next < 0){
    output <- append(output, x)}
  x_last <- x
  x <- x_next
  d_last <- d_next
}

Here Output(list) contains "continuous Peaks and Valleys".

Output <- c(41.49916, 37.92029, 39.86477, 39.86432, 39.95672, 39.95465, 39.96144, 39.83994, 40.43357, 40.11285, 40.82250, 39.37034, 58.82975, 42.19894)

so on...

the graph plotted using Output(list). My question is how to add threshold in this code? or how can i remove small Peaks and Valleys(values less than 1). I Need continuous Peaks and valleys.

Looking for answers. thank you in advance.

Body:
If you just want to plot your data:

You could plot this with ggplot2 and add a geom_smooth() layer. It defaults to method "loess" which is kind of a "do-the-right-thing" smoother for small datasets.

dat <- data.frame(y=c(41.49916, 37.92029, 39.86477, 39.86432, 39.95672, 39.95465, 39.96144, 39.83994, 40.43357, 40.11285, 40.82250, 39.37034, 58.82975, 42.19894))
dat$x <- 1:length(dat$y)
library(ggplot2)

ggplot(dat, aes(x, y)) +
        geom_line() +
        geom_smooth(method="loess", se=FALSE)

?

Or do you rather want to smoothen the data yourself? (Your data series is quite short for that.) Do you need an equation for the fit? It's easy to spend quite some time on that.

I don't fully understand this "peak/valley" stuff. In any case, take a look at the diff() function. Maybe this helps:

dat <- data.frame(y=c(41.49916, 37.92029, 39.86477, 39.86432, 39.95672, 39.95465, 39.96144, 39.83994, 40.43357, 40.11285, 40.82250, 39.37034, 58.82975, 42.19894))
dat[which(diff(dat$y) < 0.01)+1,"y"] <- NA
dat$y

 [1] 41.50    NA 39.86    NA 39.96    NA    NA    NA 40.43    NA 40.82    NA
[13] 58.83    NA

Here I've used a threshold of 0.01.
I'm not sure if it's the right thing. But you can adapt this code for your needs.


问:
Get unique value from an array php
I want to display only unique strings and I have this code:

```<code>$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    $array = array_unique($array);
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
    }
}
</code>```

I have put an array_unique like this:

```<code>$array = array_unique($array);
</code>```

But it returns this:

```<code>word-word
word
word2
word3
word-word
</code>```

It doesn't print only unique values. What is wrong?

答:
Think the problem is because the strings are being processed after the array_unique operation rather than before it. Try the following instead:

```<code>$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
    }
    $array = array_unique($array);
    foreach ($array as $value) {
        echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
    }
}
</code>```

Title: Get unique value from an array php

Body:
I want to display only unique strings and I have this code:

$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    $array = array_unique($array);
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        echo '' . $value . '
';
    }
}

I have put an array_unique like this:

$array = array_unique($array);

But it returns this:

word-word
word
word2
word3
word-word

It doesn't print only unique values. What is wrong?

Body:
Think the problem is because the strings are being processed after the array_unique operation rather than before it. Try the following instead:

$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
    }
    $array = array_unique($array);
    foreach ($array as $value) {
        echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
    }
}


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
I'm philosophically opposed to while(true).  It means "loop forever" and you never really want to loop forever.

On the other hand I'm also philosophically opposed to boolean variables that merely record state that can be found out in other ways.  There's a bug in waiting in that it may not always be correctly synchronised with the state it is supposed to reflect.  In this case, I'd prefer code like:

```<code>int main()
{
    string UserChoice = "not started"; // or empty string
    while (UserChoice != "exit")
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

    }

    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

Body:
I'm philosophically opposed to while(true).  It means "loop forever" and you never really want to loop forever.

On the other hand I'm also philosophically opposed to boolean variables that merely record state that can be found out in other ways.  There's a bug in waiting in that it may not always be correctly synchronised with the state it is supposed to reflect.  In this case, I'd prefer code like:

int main()
{
    string UserChoice = "not started"; // or empty string
    while (UserChoice != "exit")
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

    }

    return 0;
}


问:
How to split list to lists by condition?
I want split a list into multiple lists, based on a condition. If the difference in the series grows more than 4, then it is trigger to split the list till that item from last split item.

For example:

```<code>in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200]  ]
</code>```

by condition

```<code>If (next - prev) > 4
</code>```

答:
One of the possible approaches:

```<code>ls = [1,2,3,9,10,11,100,200, 201, 209]

#output list
output = list()
startind = 0

for ind, val in enumerate(ls):
    if ls[ind]-ls[ind-1] > 4:
        output.append(ls[startind:ind])
        startind = ind

# appending the left over from last detected difference of 4
output.append(ls[startind:])
print output
</code>```

Output: [[1, 2, 3], [9, 10, 11], [100], [200, 201], [209]]

Body:
I want split a list into multiple lists, based on a condition. If the difference in the series grows more than 4, then it is trigger to split the list till that item from last split item.

For example:

in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200]  ]

by condition

If (next - prev) > 4

Body:
One of the possible approaches:

ls = [1,2,3,9,10,11,100,200, 201, 209]

#output list
output = list()
startind = 0

for ind, val in enumerate(ls):
    if ls[ind]-ls[ind-1] > 4:
        output.append(ls[startind:ind])
        startind = ind

# appending the left over from last detected difference of 4
output.append(ls[startind:])
print output

Output: [[1, 2, 3], [9, 10, 11], [100], [200, 201], [209]]


问:
cert missing when request arrive Azure web role
my works based on a azure web site using client certificate authenticate. it work with old cert. and i applied for a new cert and add it into request. but when request arrived Azure web role side. nothing can retrieved from request, my own code is not executed and return 403 directly.

i guess there is a issue with cert? i installed the cert in local machine, it work well in local. and install it into azure with .pfx and password. no change happened.

there is any other operates when install cert into azure?
does anyone can help me? pls

答:
You need to share more details on what the exact error is. Start by figuring out, what the sub status code really is? whether it is 403.7 or 403.13 or something else

You can enable the logging for the site hosted on the web role and check what is the sub-status code (403.??).

Also you mentioned that the client is an Azure Web Site, so I guess you can enable System.Net tracing to gather more details and share it here. Add the following on the client web app's web.config.

```<code><configuration>
  <system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="System.Net">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Cache">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Http">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.HttpListener">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Sockets">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.WebSockets">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="System.Net" type="System.Diagnostics.TextWriterTraceListener" initializeData="D:\home\LogFiles\System.Net.trace.log" traceOutputOptions = "ProcessId, DateTime" />
    </sharedListeners>
    <switches>
      <add name="System.Net" value="Verbose" />
      <add name="System.Net.Sockets" value="Verbose" />
      <add name="System.Net.Http" value="Verbose"/>
      <add name="System.Net.Cache" value="Verbose" />
      <add name="System.Net.HttpListener" value="Verbose" />
      <add name="System.Net.WebSockets" value="Verbose"/>
    </switches>
    <trace autoflush="true"/>
  </system.diagnostics>
</configuration>
</code>```

Body:
You need to share more details on what the exact error is. Start by figuring out, what the sub status code really is? whether it is 403.7 or 403.13 or something else

You can enable the logging for the site hosted on the web role and check what is the sub-status code (403.??).

Also you mentioned that the client is an Azure Web Site, so I guess you can enable System.Net tracing to gather more details and share it here. Add the following on the client web app's web.config.

<configuration>
  <system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="System.Net">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Cache">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Http">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.HttpListener">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Sockets">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.WebSockets">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="System.Net" type="System.Diagnostics.TextWriterTraceListener" initializeData="D:\home\LogFiles\System.Net.trace.log" traceOutputOptions = "ProcessId, DateTime" />
    </sharedListeners>
    <switches>
      <add name="System.Net" value="Verbose" />
      <add name="System.Net.Sockets" value="Verbose" />
      <add name="System.Net.Http" value="Verbose"/>
      <add name="System.Net.Cache" value="Verbose" />
      <add name="System.Net.HttpListener" value="Verbose" />
      <add name="System.Net.WebSockets" value="Verbose"/>
    </switches>
    <trace autoflush="true"/>
  </system.diagnostics>
</configuration>


问:
transposing data with macro
I would like to transpose my data using a loop and not the typical transpose function so I don't have to merge the data with unused variables.

Data I have is the following:

```<code>df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50),
    Month=c("Jan", "Feb", "Mar", "Apr"))
</code>```

Which gives the following results:

```<code>ID Amount Month
1    100   Jan
2    150   Feb
3     75   Mar
4     50   Apr
</code>```

I would like the final results to be like this:

```<code>ID Amount Jan Feb Mar Apr
1    100   1   0   0   0
2    150   0   1   0   0
3     75   0   0   1   0
4     50   0   0   0   1
</code>```

I would know how to do this in SAS but couldn't find a solution with R.  Your help is appreciated.

答:
Here is a base R option with table

```<code>cbind(df1, as.data.frame.matrix(table(lapply(df1[-1],
                         function(x) factor(x, levels = unique(x))))))
</code>```

Title: transposing data with macro

Body:
I would like to transpose my data using a loop and not the typical transpose function so I don't have to merge the data with unused variables.

Data I have is the following:

df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50),
    Month=c("Jan", "Feb", "Mar", "Apr"))

Which gives the following results:

ID Amount Month
1    100   Jan
2    150   Feb
3     75   Mar
4     50   Apr

I would like the final results to be like this:

ID Amount Jan Feb Mar Apr
1    100   1   0   0   0
2    150   0   1   0   0
3     75   0   0   1   0
4     50   0   0   0   1

I would know how to do this in SAS but couldn't find a solution with R.  Your help is appreciated.

Body:
Here is a base R option with table

cbind(df1, as.data.frame.matrix(table(lapply(df1[-1],
                         function(x) factor(x, levels = unique(x))))))


问:
How do I write a program to ask user for 2 cities then return the distance between them
```<code>       Belfast   Dublin   Cork  Galway
Belfast 0        104    266     230
Dublin  104      0      161     129
Cork    266      161    0       123
Galway  230      129    123     0
</code>```

Declare a 2D array that holds these distances

Declare a list to hold the 4 city names in the same order as table above

Write a program to ask user for 2 cities then return the distance between them

Write a program to convert the 2D array to KM.  Iterate over the entire 2D array and multiply each value by 1.61

So far I have done following:

```<code>distances = ((0, 104, 266, 230),(104, 0, 161, 129),(266, 161, 0, 123),(230, 129, 123, 0))
cities = ((Belfast), (Dublin), (Cork), (Galway))
</code>```

答:
You have array distances that contain following data

```<code>distances = ((0, 104, 266, 230),(104, 0, 161, 129),(266, 161, 0, 123),(230, 129, 123, 0))
</code>```

And you have array

```<code>cities = ((Belfast), (Dublin), (Cork), (Galway))
</code>```

If you look at cities, then you can address them like cities[0] for Belfast cities[1] for Dublin and so on.

Same can be done for distances except it has two dimensions so it will be like distances[0][0]

BTW: in what language is your program written? Could you put it in your original post?

Body:
       Belfast   Dublin   Cork  Galway
Belfast 0        104    266     230
Dublin  104      0      161     129
Cork    266      161    0       123
Galway  230      129    123     0

Declare a 2D array that holds these distances

Declare a list to hold the 4 city names in the same order as table above

Write a program to ask user for 2 cities then return the distance between them

Write a program to convert the 2D array to KM.  Iterate over the entire 2D array and multiply each value by 1.61

So far I have done following:

distances = ((0, 104, 266, 230),(104, 0, 161, 129),(266, 161, 0, 123),(230, 129, 123, 0))
cities = ((Belfast), (Dublin), (Cork), (Galway))

Body:
You have array distances that contain following data

distances = ((0, 104, 266, 230),(104, 0, 161, 129),(266, 161, 0, 123),(230, 129, 123, 0))

And you have array

cities = ((Belfast), (Dublin), (Cork), (Galway))

If you look at cities, then you can address them like cities[0] for Belfast cities[1] for Dublin and so on.

Same can be done for distances except it has two dimensions so it will be like distances[0][0]

BTW: in what language is your program written? Could you put it in your original post?


问:
Javascript XMLHttpRequest: Ignore invalid SSL Certificate
so I have been having trouble with grabbing information from a device that is interfaced with via https due to the fact that it has an invalid security certificate.  I know the device is to be trusted and I don't have access to the server-side so I can't change it.  I was wondering if there was any way to set up an XMLHttpRequest object in Javascript to just ignore an invalid SSL certificate and just grab the information anyway.  As it is now it seems to just reject the certificate and stop.  Thanks.</p>

答:
Well I had found this solution before but it didn't work, this was because I was still using actual XMLHttpRequest though.  When creating it using this statement:

```<code>httpreq = new ActiveXObject("Msxml2.ServerXMLHTTP.3.0");
</code>```

There is a method called setOption that is opened up for use:

```<code>httpreq.setOption(2, 13056);
</code>```

With those parameters, the request now ignores the invalid certificate and grabs the information anyway.  If I understand correctly this won't work with any non-Microsoft technology trying to run the script, but that's ok for the scope of my project.

Body:
Well I had found this solution before but it didn't work, this was because I was still using actual XMLHttpRequest though.  When creating it using this statement:

httpreq = new ActiveXObject("Msxml2.ServerXMLHTTP.3.0");

There is a method called setOption that is opened up for use:

httpreq.setOption(2, 13056);

With those parameters, the request now ignores the invalid certificate and grabs the information anyway.  If I understand correctly this won't work with any non-Microsoft technology trying to run the script, but that's ok for the scope of my project.


问:
IOS mobile automation
I am new to IOS automation testing. I have to install appium for automation on actual physical device. I have followed a number of links but I am still confused. I have installed appium and xcode. But when I run appium inspector I always get error 'Could not launch Appium Inspector'. What could be the possible cause? Also can someone suggest a link which I can follow for appium set up on MAC.</p>

答:
Check this out latest appium desktop :

AppiumDesktop1.1.0beta4 iOS setup - Inspector and Record the scripts,

Link : https://www.youtube.com/watch?v=2_xHmofGgUE

If you face any issue please comment it.

Title: IOS mobile automation


问:
How to get the integer part and fractional part of a number in Swift
This is a super basic question, but, I can't seem to find an answer in Swift.

Question:

How do I get the whole integer part and fractional part (to the left and right of the decimal point respectively) of a number in Swift 2 and Swift 3? For example, for the number 1234.56789 —

How do I get the integer part 1234.56789 ?

How do I get the fractional part 1234.56789 ?

答:
You could do simple floor and truncating:</p>

```<code>let value = 1234.56789
let double = floor(value) // 1234.0
let integer = Int(double) // 1234
let decimal = value.truncatingRemainder(dividingBy: 1) // 0.56789
</code>```

Body:
You could do simple floor and truncating:

let value = 1234.56789
let double = floor(value) // 1234.0
let integer = Int(double) // 1234
let decimal = value.truncatingRemainder(dividingBy: 1) // 0.56789


答:
Convert your number into String later separate string from .

Try this:-

```<code>let number:Float = 123.46789
let numberString = String(number)
let numberComponent = numberString.components(separatedBy :".")
let integerNumber = Int(numberComponent [0])
let fractionalNumber = Int(numberComponent [1])
</code>```

Title: How to get the integer part and fractional part of a number in Swift

Body:
This is a super basic question, but, I can't seem to find an answer in Swift.

Question:

How do I get the whole integer part and fractional part (to the left and right of the decimal point respectively) of a number in Swift 2 and Swift 3? For example, for the number 1234.56789 —

How do I get the integer part 1234.56789 ?

How do I get the fractional part 1234.56789 ?

Body:
Convert your number into String later separate string from .

Try this:-

let number:Float = 123.46789
let numberString = String(number)
let numberComponent = numberString.components(separatedBy :".")
let integerNumber = Int(numberComponent [0])
let fractionalNumber = Int(numberComponent [1])


问:
How can my JUnit test connect to my Spring Service?
I have a Spring application built, like this ...

JSP -> MyController -> MyService -> MyDAO -> TheDatabase

Works great.

Now I want to build a JUnit test to exercise the MyService ... do creates, edits, delete, for santity testing functionality.

I created a JUnit 4 class in my src/test/java/com/mycompany/myapp folder, I run the server, and then I try to run the test.

But it fails because the @Autowired MyService is not getting instantiated.

```<code>public class Test1 {

    @Autowired
    MyService myService;

    @Test
    public void test() {

        myService.doSomething();

    }

}
</code>```

QUESTION: How do I get Spring to instantiate the MyService in my JUnit test?

答:
By adding the following annotations to your test class/dependencies (spring-test) to your project:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(/*...*/)
</code>```

The server will not be needed/involved at (test) runtime.
And of course additional studies, as proposed by dunni's comment, might help!

=> http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#testing

Body:
I have a Spring application built, like this ...

JSP -> MyController -> MyService -> MyDAO -> TheDatabase

Works great.

Now I want to build a JUnit test to exercise the MyService ... do creates, edits, delete, for santity testing functionality.

I created a JUnit 4 class in my src/test/java/com/mycompany/myapp folder, I run the server, and then I try to run the test.

But it fails because the @Autowired MyService is not getting instantiated.

public class Test1 {

    @Autowired
    MyService myService;

    @Test
    public void test() {

        myService.doSomething();

    }

}

QUESTION: How do I get Spring to instantiate the MyService in my JUnit test?

Body:
By adding the following annotations to your test class/dependencies (spring-test) to your project:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(/*...*/)

The server will not be needed/involved at (test) runtime.
And of course additional studies, as proposed by dunni's comment, might help!

=> http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#testing


问:
show same page with different menu item active
I have these 2 menu and sub-menus for my help manual which has a page leftmenu.php where I have all the menu's and I have included this file above all my pages.

```<code><li>
    <a href=""><i class="fa fa-briefcase"></i> <span class="nav-label">Main menu 1 </span><span class="fa arrow"></span></a>
    <ul class="nav nav-second-level collapse">
        <li><a href="project.php">Project Management</a></li>
        <li><a href="task.php">Task Management</a></li>
        <li><a href="defect.php">Defect Management</a></li>
        <li><a href="customer1.php">Customer Management</a></li>
        <li><a href="user.php">User Management</a></li>
        <li><a href="settings.php">Settings</a></li>
    </ul>
</li>
<li>
    <a href=""><i class="fa fa-ticket"></i> <span class="nav-label">Main menu 2 </span><span class="fa arrow"></span></a>
    <ul class="nav nav-second-level collapse">
        <li><a href="ticket.php">Ticket Management</a></li>
        <li><a href="resolution.php">Resolutions</a></li>
        <li><a href="customer.php">Customer Management</a></li>
        <li><a href="user.php">User Management</a></li>
        <li><a href="settings.php">Settings</a></li>
    </ul>
</li>
</code>```

Now I have this one customer.php which I would like to use in both the menu's but the menu from where Customer Management is clicked should only be active.
How to I achieve this as I am using only php and html for this.
Thankyou

My code now:

```<code><li <?= active('leads|user|settings')?>>
                    <a href=""><i class="fa fa-diamond"></i> <span class="nav-label">Main menu1</span> <span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li <?= active('leads') ?>><a href="leads.php">Lead Management</a></li>
                        <li <?= active('user') ?>><a href="user.php">User Management</a></li>
                        <li <?= active('settings') ?>><a href="settings.php">Settings</a></li>
                    </ul>
                </li>

                <li <?= active('project|task|defect|customer1|users|settings1')?>>
                    <a href=""><i class="fa fa-briefcase"></i> <span class="nav-label">Main menu2 </span><span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level collapse">
                      <li <?= active('project') ?>><a href="project.php">Project Management</a></li>
                        <li <?= active('task') ?>><a href="task.php">Task Management</a></li>
                        <li <?= active('defect') ?>><a href="defect.php">Defect Management</a></li>
                        <li <?= active('customer1') ?>><a href="customer1.php">Customer Management</a></li>
                        <li <?= active('users') ?>><a href="users.php">User Management</a></li>
                        <li <?= active('settings1') ?>><a href="settings1.php">Settings</a></li>
                    </ul>
                </li>
</code>```

答:
I would wrap it in a php if statement like this for each value you want to show</p>

```<code>if ($_SERVER['REQUEST_URI'] == "my/url/") {
// do something
} else {
// do something else
}
</code>```

OwnerDisplayName: anon

Body:
I have these 2 menu and sub-menus for my help manual which has a page leftmenu.php where I have all the menu's and I have included this file above all my pages.

     Main menu 1

Project Management

Task Management

Defect Management

Customer Management

User Management

Settings

     Main menu 2

Ticket Management

Resolutions

Customer Management

User Management

Settings

Now I have this one customer.php which I would like to use in both the menu's but the menu from where Customer Management is clicked should only be active.
How to I achieve this as I am using only php and html for this.
Thankyou

My code now:

<li <?= active('leads|user|settings')?>>
                     Main menu1

                        <li <?= active('leads') ?>>Lead Management

                        <li <?= active('user') ?>>User Management

                        <li <?= active('settings') ?>>Settings

                <li <?= active('project|task|defect|customer1|users|settings1')?>>
                     Main menu2

                      <li <?= active('project') ?>>Project Management

                        <li <?= active('task') ?>>Task Management

                        <li <?= active('defect') ?>>Defect Management

                        <li <?= active('customer1') ?>>Customer Management

                        <li <?= active('users') ?>>User Management

                        <li <?= active('settings1') ?>>Settings

Body:
I would wrap it in a php if statement like this for each value you want to show

if ($_SERVER['REQUEST_URI'] == "my/url/") {
// do something
} else {
// do something else
}


问:
How to remove FR or Tax from sale emails?
How can I remove FR (20%) or Tax from the sale emails? They are the same thing to me so I want to remove one of them from the emails/ invoices.

```<code>FR (20%) €48.00
Tax      €48.00
</code>```

If I go the template to look into the code,

```<code>app/locale/yourlanguage/template/email/sales/order_new.html
</code>```

I see this,

```<code>{{layout handle="sales_email_order_items" order=$order}}
</code>```

So I guess this must be where the FR & Tax are generated. So where can I go in the backoffice to configure this?

If I can, it would be better if I can change Tax to something else like Tax FR (20%) - is it possible?

答:
Copy app/design/frontend/base/sales/order/totals.phtml to your theme file and open it.
Add the following to the top of it.</p>

```<code>if($tax = $this->getTotal('tax')){    $this->removeTotal('tax');    $this->addTotal($tax, 'grand_total');}
</code>```

Body:
How can I remove FR (20%) or Tax from the sale emails? They are the same thing to me so I want to remove one of them from the emails/ invoices.

FR (20%) €48.00
Tax      €48.00

If I go the template to look into the code,

app/locale/yourlanguage/template/email/sales/order_new.html

I see this,

{{layout handle="sales_email_order_items" order=$order}}

So I guess this must be where the FR & Tax are generated. So where can I go in the backoffice to configure this?

If I can, it would be better if I can change Tax to something else like Tax FR (20%) - is it possible?

Body:
Copy app/design/frontend/base/sales/order/totals.phtml to your theme file and open it.
Add the following to the top of it.

if($tax = $this->getTotal('tax')){    $this->removeTotal('tax');    $this->addTotal($tax, 'grand_total');}


问:
Problems Installing ruby-netcdf
On Mavericks, I cannot get ruby-netcdf to install and work on my machine. Have been following these blog posts:

https://andrewsturges.blogspot.com/2011/03/how-to-use-rubynetcdf-to-read-netcdf.html

https://andrewsturges.blogspot.com/2011/03/how-to-install-rubynetcdf-on-ubuntu_24.html

```<code>RailsApps $ gem install ruby-netcdf
Building native extensions.  This could take a while...
ERROR:  Error installing ruby-netcdf:
ERROR: Failed to build gem native extension.

/Users/blanecordes/.rvm/rubies/ruby-1.9.3-p545/bin/ruby extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/Users/blanecordes/.rvm/rubies/ruby-1.9.3-p545/bin/ruby
extconf.rb:4:in `<main>': uninitialized constant Gem::GemPathSearcher (NameError)

extconf failed, exit code 1

Gem files will remain installed in /Users/blanecordes/.rvm/gems/ruby-1.9.3-p545/gems/ruby-    netcdf-0.6.6.1 for inspection.
Results logged to /Users/blanecordes/.rvm/gems/ruby-1.9.3-p545/extensions/x86_64-darwin-13/1.9.1/ruby-netcdf-0.6.6.1/gem_make.out
</code>```

答:
On Ubuntu, you need to install libnetcdf-dev:

```<code>sudo apt install libnetcdf-dev
gem install ruby-netcdf
</code>```

Title: Problems Installing ruby-netcdf

Body:
On Mavericks, I cannot get ruby-netcdf to install and work on my machine. Have been following these blog posts:

https://andrewsturges.blogspot.com/2011/03/how-to-use-rubynetcdf-to-read-netcdf.html

https://andrewsturges.blogspot.com/2011/03/how-to-install-rubynetcdf-on-ubuntu_24.html

RailsApps $ gem install ruby-netcdf
Building native extensions.  This could take a while...
ERROR:  Error installing ruby-netcdf:
ERROR: Failed to build gem native extension.

/Users/blanecordes/.rvm/rubies/ruby-1.9.3-p545/bin/ruby extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/Users/blanecordes/.rvm/rubies/ruby-1.9.3-p545/bin/ruby
extconf.rb:4:in `': uninitialized constant Gem::GemPathSearcher (NameError)

extconf failed, exit code 1

Gem files will remain installed in /Users/blanecordes/.rvm/gems/ruby-1.9.3-p545/gems/ruby-    netcdf-0.6.6.1 for inspection.
Results logged to /Users/blanecordes/.rvm/gems/ruby-1.9.3-p545/extensions/x86_64-darwin-13/1.9.1/ruby-netcdf-0.6.6.1/gem_make.out

Body:
On Ubuntu, you need to install libnetcdf-dev:

sudo apt install libnetcdf-dev
gem install ruby-netcdf


问:
egrep search for whitespace
I'm trying to use egrep with a regex pattern to match whitespace.

I've used RegEx with Perl and C# before and they both support the pattern \s to search for whitespace. egrep (or at least the version I'm using) does not seem to support this pattern.

In a few articles online I've come across a shorthand [[:space:]], but this does not seem to work. Any help is appreciated.

Using: SunOS 5.10

答:
I see the same issue on SunOS 5.10.  /usr/bin/egrep does not support extended regular expressions.

Try using /usr/xpg4/bin/egrep:

```<code>$ echo 'this line has whitespace
thislinedoesnthave' | /usr/xpg4/bin/egrep '[[:space:]]'
this line has whitespace
</code>```

Another option might be to just use perl:

```<code>$ echo 'this line has whitespace
thislinedoesnthave' | perl -ne 'chomp;print "$_\n" if /[[:space:]]/'
this line has whitespace
</code>```

Title: egrep search for whitespace

Body:
I see the same issue on SunOS 5.10.  /usr/bin/egrep does not support extended regular expressions.

Try using /usr/xpg4/bin/egrep:

$ echo 'this line has whitespace
thislinedoesnthave' | /usr/xpg4/bin/egrep '[[:space:]]'
this line has whitespace

Another option might be to just use perl:

$ echo 'this line has whitespace
thislinedoesnthave' | perl -ne 'chomp;print "$_\n" if /[[:space:]]/'
this line has whitespace

OwnerDisplayName: Jon Ericson

LastEditorDisplayName: Jon Ericson


问:
How does spark ML decision tree handle continuous features for regression problems
I have a mixture of categorical and continuous features. I have indexed all my categorical variables and I use VectorAssembler to create a features column

```<code>        StringIndexerModel indexer = new StringIndexer()
                    .setInputCol("categorical")
                    .setOutputCol("categoricalIdx1")
                    .setHandleInvalid("skip").fit(data);
        VectorAssembler assembler = new VectorAssembler()
                    .setInputCols(new String[]{"categoricalIdx1","continuous"})
                    .setOutputCol("features");

        DecisionTreeRegressor dt = new DecisionTreeRegressor()
                                       .setMaxBins(40)
                                       .setMaxDepth(10)
                                       .setFeaturesCol("features")
                                       .setLabelCol("commission")
                                       .setPredictionCol("prediction");
</code>```

I couldn't find any way to specify which features are categorical and which are continuous. And since all the columns have been converted to numerical values how does the DecisionTreeRegressor know the difference. What am I missing here?
The code seems to work and gives quite good result, But I have a hunch that I am doing something wrong here.

答: Spark use MaxBins to specify a feature is categorical or continuous. If the number of distinct values <= MaxBins, it is categorical. Otherwise, continuous. For more information, check the Spark's doc:decision tree

Body:
I have a mixture of categorical and continuous features. I have indexed all my categorical variables and I use VectorAssembler to create a features column

        StringIndexerModel indexer = new StringIndexer()
                    .setInputCol("categorical")
                    .setOutputCol("categoricalIdx1")
                    .setHandleInvalid("skip").fit(data);
        VectorAssembler assembler = new VectorAssembler()
                    .setInputCols(new String[]{"categoricalIdx1","continuous"})
                    .setOutputCol("features");

        DecisionTreeRegressor dt = new DecisionTreeRegressor()
                                       .setMaxBins(40)
                                       .setMaxDepth(10)
                                       .setFeaturesCol("features")
                                       .setLabelCol("commission")
                                       .setPredictionCol("prediction");

I couldn't find any way to specify which features are categorical and which are continuous. And since all the columns have been converted to numerical values how does the DecisionTreeRegressor know the difference. What am I missing here?
The code seems to work and gives quite good result, But I have a hunch that I am doing something wrong here.


问:
R lead and lag (shift) with times
I'm tried to use lag on a column of a data frame but when time is involved it just wont work. I've tried shift, lag and tlag.

Example:

```<code>y = strptime(sprintf("%s:%s:%s", 4, 20, 10), "%H:%M:%S")
yy = strptime(sprintf("%s:%s:%s", 10, 20, 10), "%H:%M:%S")
lag(c(y,yy))
</code>```

Error in format.POSIXlt(x, usetz = usetz) :
    invalid component [[10]] in "POSIXlt" should be 'zone'

tlag(c(y,yy))

Error in n_distinct_multi(list(...), na.rm) :
    argument "time" is missing, with no default

```<code>shift(c(y,yy))
[[1]]
[1] NA 10

[[2]]
[1] NA 20

[[3]]
[1] NA  4

[[4]]
[1] NA  4

[[5]]
[1] NA  6

[[6]]
[1]  NA 117

[[7]]
[1] NA  2

[[8]]
[1]  NA 184

[[9]]
[1] NA  1

[[10]]
[1] NA    "BST"

[[11]]
[1]   NA 3600
</code>```

I don't want any time differences, I simply want the value from the row above in my data frame, which I thought was what lag did: "Lead and lag are useful for comparing values offset by a constant (e.g. the previous or next value)".
The time shouldn't even matter, it should just choose whatever numeric/character/time from the previous position. How do I fix this or is there a different function that does the equivalent of what I'd like - I do not want to involve any loops as speed is important and the data frames are large.

Example from my dataframe:

```<code>structure(list(sec = c(52, 53, 54, 55, 56, 57, 58, 59, 0, 1),
    min = c(50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 51L, 51L),
    hour = c(11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L
    ), mday = c(4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), mon = c(6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), year = c(117L, 117L,
    117L, 117L, 117L, 117L, 117L, 117L, 117L, 117L), wday = c(2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), yday = c(184L, 184L,
    184L, 184L, 184L, 184L, 184L, 184L, 184L, 184L), isdst = c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), zone = c("BST", "BST",
    "BST", "BST", "BST", "BST", "BST", "BST", "BST", "BST"),
    gmtoff = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_)), .Names = c("sec", "min", "hour", "mday", "mon",
"year", "wday", "yday", "isdst", "zone", "gmtoff"), class = c("POSIXlt",
"POSIXt"))
</code>```

Title: R lead and lag (shift) with times

Body:
I'm tried to use lag on a column of a data frame but when time is involved it just wont work. I've tried shift, lag and tlag.

Example:

y = strptime(sprintf("%s:%s:%s", 4, 20, 10), "%H:%M:%S")
yy = strptime(sprintf("%s:%s:%s", 10, 20, 10), "%H:%M:%S")
lag(c(y,yy))

Error in format.POSIXlt(x, usetz = usetz) :
    invalid component [[10]] in "POSIXlt" should be 'zone'

tlag(c(y,yy))

Error in n_distinct_multi(list(...), na.rm) :
    argument "time" is missing, with no default

shift(c(y,yy))
[[1]]
[1] NA 10

[[2]]
[1] NA 20

[[3]]
[1] NA  4

[[4]]
[1] NA  4

[[5]]
[1] NA  6

[[6]]
[1]  NA 117

[[7]]
[1] NA  2

[[8]]
[1]  NA 184

[[9]]
[1] NA  1

[[10]]
[1] NA    "BST"

[[11]]
[1]   NA 3600

I don't want any time differences, I simply want the value from the row above in my data frame, which I thought was what lag did: "Lead and lag are useful for comparing values offset by a constant (e.g. the previous or next value)".
The time shouldn't even matter, it should just choose whatever numeric/character/time from the previous position. How do I fix this or is there a different function that does the equivalent of what I'd like - I do not want to involve any loops as speed is important and the data frames are large.

Example from my dataframe:

structure(list(sec = c(52, 53, 54, 55, 56, 57, 58, 59, 0, 1),
    min = c(50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 51L, 51L),
    hour = c(11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L
    ), mday = c(4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), mon = c(6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), year = c(117L, 117L,
    117L, 117L, 117L, 117L, 117L, 117L, 117L, 117L), wday = c(2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), yday = c(184L, 184L,
    184L, 184L, 184L, 184L, 184L, 184L, 184L, 184L), isdst = c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), zone = c("BST", "BST",
    "BST", "BST", "BST", "BST", "BST", "BST", "BST", "BST"),
    gmtoff = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_)), .Names = c("sec", "min", "hour", "mday", "mon",
"year", "wday", "yday", "isdst", "zone", "gmtoff"), class = c("POSIXlt",
"POSIXt"))

Body:
For a data.frame like below

  index                time
1     1 2017-07-04 04:20:10
2     2 2017-07-04 10:20:10

you can use dplyr

dplyr::lag(df$time, 1)
[1] NA                         "2017-07-04 04:20:10 CEST"

dplyr::lead(df$time, 1)
[1] "2017-07-04 10:20:10 CEST" NA

And to add the lead/lag column to your data.frame you can use

dplyr::mutate(df, lead_1 = dplyr::lead(time, 1), lag_1 = dplyr::lag(time, 1))
  index                time              lead_1               lag_1
1     1 2017-07-04 04:20:10 2017-07-04 10:20:10                <NA>
2     2 2017-07-04 10:20:10                <NA> 2017-07-04 04:20:10


问:
Cannot add server glassfish 4.1.2 in netbeans 8.1
When trying to add Glassfish 4.1.2 server in Netbeans 8.1 IDE, I'm getting the following error message:

"Not a valid GlassFish Server installation"

JDK 1.7.0_67 on Windows XP used.

答:
According to the release news, Glassfish 4.1.2 requires JDK 7 u80 or newer:

Minimum JDK required is JDK 7 u80.


问:
How to access pixels inside contour region and write back to the original image using opencv in android
I have written some code which will return contours from the actual image. I would like to access each contour, do some image manipulation at pixel level and write back to the image.

Is there a way to access the region of contour individually and iterate over individual pixel in the region and write back to the image.

```<code>      Rect rect = Imgproc.boundingRect(matOfPoint);
      Mat roiBox = rgbaMatrix.submat(rect)
</code>```

This returns a sub matrix which also has the pixels which are not part of the contour.

Please follow this link to see the screenshot of contour detections

答:
I found of a way which will always hold the context of the main matrix, as @AlexanderReynolds suggested masking is the only way to extract the exact region.

```<code>Rect rect = Imgproc.boundingRect(matOfPoint);
Mat subMat = new Mat(mRgba,rect);
Mat zeroMat = Mat.zeros(subMat.size(),subMat.type());
zeroMat.copyTo(subMat);
</code>```

This copies the zero matrix to the original matrix

Body:
I have written some code which will return contours from the actual image. I would like to access each contour, do some image manipulation at pixel level and write back to the image.

Is there a way to access the region of contour individually and iterate over individual pixel in the region and write back to the image.

      Rect rect = Imgproc.boundingRect(matOfPoint);
      Mat roiBox = rgbaMatrix.submat(rect)

This returns a sub matrix which also has the pixels which are not part of the contour.

Please follow this link to see the screenshot of contour detections

Body:
I found of a way which will always hold the context of the main matrix, as @AlexanderReynolds suggested masking is the only way to extract the exact region.

Rect rect = Imgproc.boundingRect(matOfPoint);
Mat subMat = new Mat(mRgba,rect);
Mat zeroMat = Mat.zeros(subMat.size(),subMat.type());
zeroMat.copyTo(subMat);

This copies the zero matrix to the original matrix


问:
Java Casting to superclass not change object type?
I don't understand why this code outputs false. Java uses the object type (not reference) to choose the [instance] method to execute, in this case, initial object type is Owl (with method returns false), anyway, We cast this type to "Nocturnal" (not necessary, but We do). I have isBlind() method in the interface and the class.

Why our Owl converted to Nocturnal using a explicit Cast prints false, if the object type now is Nocturnal and the Nocturnal method prints true?

```<code>interface Nocturnal {
    default boolean isBlind() {
        return true;
    }
}

public class Owl implements Nocturnal {
    public boolean isBlind() {
        return false;
    }

    public static void main(String[] args) {
        Nocturnal nocturnal = (Nocturnal) new Owl();
        System.out.println(nocturnal.isBlind());
    }
}
</code>```

答:
A powerful way to think about OO programming is to think of method calls as message passing. You send a message to the object "please give me the result of the isBlind() method". The object goes "OK, I know how to do isBlind(), does it, then sends a message to the caller containing the result.

Your Owl object receives that message asking to run isBlind(). It doesn't care where it came from. It doesn't know what the caller knows about it. It just runs its own version of isBlind() and sends the result back.

When you cast to a superclass (or an interface) in the caller, the caller "forgets" that it's talking to an Owl, but the Owl doesn't know that. It just keeps handling messages in the same way it always does.

This is the core of what makes polymorphism so powerful. It means you can put your Owl into a collection of Nocturnal, and call isBlind() on each one, getting the correct result:

```<code>  List<Nocturnal> animals = new ArrayList<>();
  animals.add(new Owl());
  animals.add(new Bat());

  for(Nocturnal animal : animals) {
      System.out.println(
           "Name: " + animal.getName() +
           " Blind: " + animal.isBlind());
  }
</code>```

As you progress with object-oriented programming, you will encounter tons of situations where this is invaluable. Not least, unit testing, in which you can substitute a test double (sometimes a mock) for the objects that collaborate with the object you're testing.

Note that modern Java programmers tend not to subclass all that often, preferring to to implement interfaces much of the time. "Prefer composition to inheritance". The same principles apply regarding polymorphism.

Body:
I don't understand why this code outputs false. Java uses the object type (not reference) to choose the [instance] method to execute, in this case, initial object type is Owl (with method returns false), anyway, We cast this type to "Nocturnal" (not necessary, but We do). I have isBlind() method in the interface and the class.

Why our Owl converted to Nocturnal using a explicit Cast prints false, if the object type now is Nocturnal and the Nocturnal method prints true?

interface Nocturnal {
    default boolean isBlind() {
        return true;
    }
}

public class Owl implements Nocturnal {
    public boolean isBlind() {
        return false;
    }

    public static void main(String[] args) {
        Nocturnal nocturnal = (Nocturnal) new Owl();
        System.out.println(nocturnal.isBlind());
    }
}

Body:
A powerful way to think about OO programming is to think of method calls as message passing. You send a message to the object "please give me the result of the isBlind() method". The object goes "OK, I know how to do isBlind(), does it, then sends a message to the caller containing the result.

Your Owl object receives that message asking to run isBlind(). It doesn't care where it came from. It doesn't know what the caller knows about it. It just runs its own version of isBlind() and sends the result back.

When you cast to a superclass (or an interface) in the caller, the caller "forgets" that it's talking to an Owl, but the Owl doesn't know that. It just keeps handling messages in the same way it always does.

This is the core of what makes polymorphism so powerful. It means you can put your Owl into a collection of Nocturnal, and call isBlind() on each one, getting the correct result:

  List<Nocturnal> animals = new ArrayList<>();
  animals.add(new Owl());
  animals.add(new Bat());

  for(Nocturnal animal : animals) {
      System.out.println(
           "Name: " + animal.getName() +
           " Blind: " + animal.isBlind());
  }

As you progress with object-oriented programming, you will encounter tons of situations where this is invaluable. Not least, unit testing, in which you can substitute a test double (sometimes a mock) for the objects that collaborate with the object you're testing.

Note that modern Java programmers tend not to subclass all that often, preferring to to implement interfaces much of the time. "Prefer composition to inheritance". The same principles apply regarding polymorphism.


问:
How do I access the extra attribute on join table in my show page?
My models look like this:

```<code>class Project < ApplicationRecord
  has_many :comments
  has_many :contractor_projects
  has_many :contractors, through: :contractor_projects
  validates_presence_of :title, :contract_number, :category, :project_start_date, :project_end_date, :substantial_completion_date, :category, :solicitation_number, :project_officer, :location
  accepts_nested_attributes_for :contractor_projects
end

class Contractor < ApplicationRecord
  has_many :contractor_projects
  has_many :projects, through: :contractor_projects

  validates :name, presence: true

  validates :email, presence: true, uniqueness: true
 end

class ContractorProject < ApplicationRecord
  belongs_to :contractor
  belongs_to :project
end
</code>```

The ContractorProject model has an extra attribute #bid_status that I want to reflect on project's show page but it does not appear even though it's in the params when i raised it.

答:
below is sample method for your case

```<code>def show
  @project = Project.find(params[:id]
  @contractors = @project.contractors
end
</code>```

inside show.html.erb, you have to loop it, since it may get more than one records

```<code><% @contractors.each do |contractor| %>
  <%= contractor.bid_status %>
<% end %>
</code>```

Body:
My models look like this:

class Project < ApplicationRecord
  has_many :comments
  has_many :contractor_projects
  has_many :contractors, through: :contractor_projects
  validates_presence_of :title, :contract_number, :category, :project_start_date, :project_end_date, :substantial_completion_date, :category, :solicitation_number, :project_officer, :location
  accepts_nested_attributes_for :contractor_projects
end

class Contractor < ApplicationRecord
  has_many :contractor_projects
  has_many :projects, through: :contractor_projects

  validates :name, presence: true

  validates :email, presence: true, uniqueness: true
 end

class ContractorProject < ApplicationRecord
  belongs_to :contractor
  belongs_to :project
end

The ContractorProject model has an extra attribute #bid_status that I want to reflect on project's show page but it does not appear even though it's in the params when i raised it.

Body:
below is sample method for your case

def show
  @project = Project.find(params[:id]
  @contractors = @project.contractors
end

inside show.html.erb, you have to loop it, since it may get more than one records

<% @contractors.each do |contractor| %>
  <%= contractor.bid_status %>
<% end %>