问:
"git cherry" shows an already cherry-picked commit as "ready to be applied"
I've been working on branch align and want to cherry-pick some commits from it to master.
I use git cherry to look for candidate commits:

```<code>C:\Users\me\Documents\repo>git cherry -v master align | head -1
+ c2bbb3d99440be7524673702c92ad65e6522d2b1 Made RW_assert() work on 64-bit.
</code>```

My understanding is the '+' means there's no equivalent commit on master.
But I remember cherry-picking this commit to master already.
In fact, it was the most recent change to file rw-fwd.h on branch align:

```<code>C:\Users\me\Documents\repo>git log align -1 rw-fwd.h
commit c2bbb3d99440be7524673702c92ad65e6522d2b1
Author: Me
Date:   Thu Jun 8 10:41:01 2017 +1000

    Made RW_assert() work on 64-bit.
</code>```

And is still the most recent change to rw-fwd.h on branch master:

```<code>C:\Users\me\Documents\repo>git log master -1 rw-fwd.h
commit 5bc790b9b0adfcdc6c0a07b679155e33974e343a
Author: Me
Date:   Thu Jun 8 10:41:01 2017 +1000

    Made RW_assert() work on 64-bit.
</code>```

The documentation for git cherry states: "The equivalence test is based on the diff, after removing whitespace and line numbers. git-cherry therefore detects when commits have been "copied" by means of git-cherry-pick[1], git-am[1] or git-rebase[1]."
Visually, using git show, the commits look the same, but let's be absolutely sure:

```<code>C:\Users\me\Documents\repo>git show c2bbb3d | git patch-id
f6ad0912fd71f694b6b00c6ea93c87af7cf4ab98 c2bbb3d99440be7524673702c92ad65e6522d2b1

C:\Users\me\Documents\repo>git show 5bc790b | git patch-id
f6ad0912fd71f694b6b00c6ea93c87af7cf4ab98 5bc790b9b0adfcdc6c0a07b679155e33974e343a
</code>```

The patch-ids are identical.  Why has git cherry not detected that this commit was already cherry-picked?

Edit: below is a sanitized git log --oneline --decorate --graph.
I've added this in response to the answer by @torek, not because I have any doubt the answer's correct, but because I'd value some help in interpreting the real commit log in light of that answer.

master is at a52f43e (first line) and align is at 9ffa94e (third line).
align is the rightmost line on the graph all the way down, and is not merged from.

```<code>* a52f43e ######## ############ #####
* 507e731 ##### ##### ### ## ###
| *   9ffa94e (origin/align) Merge branch 'master' of https://ghe/repo/repo into align
| |\
| |/
|/|
* |   657d6c8 Merge pull request #8 from repo/test_system
|\ \
| * \   679739b Merged origin master into local branch.
| |\ \
| |/ /
|/| |
* | |   c7a5944 Merge branch 'master' of https://ghe/repo/repo
|\ \ \
| * \ \   e12016c Merge pull request #7 from repo/lean-mean
| |\ \ \
| | * | | 144fefd ##### ####### ##### ## #######
| | * | | 87e0e23 ####### ############## ## ####### ####### ...
| * | | | 8613f4e ######## ####### ######### ## ###### #####...
| |/ / /
* | | | 8f70a8d ######### #### ##### ### ###### ### ########...
* | | |   aedb306 Merge branch 'master' of https://ghe/repo/repo
|\ \ \ \
* \ \ \ \   0a4fd59 Merge branch 'master' of https://ghe/repo/repo
|\ \ \ \ \
* \ \ \ \ \   e1cfbfd Merge branch 'PBA_Experiment' of https://ghe/repo/repo
|\ \ \ \ \ \
| * | | | | | 7f1bc5b (######/##############) ##########
| | | | | * | 323d965 ######## ######### ####### ########.##...
| | | | | * | 5839749 ##### #######-#### ###### ## ### ## ##...
| | | | | | * d96ba71 ##-####### ############, ## ##### ####...
| | | | | | * 680354b #### ##### ######### #####, ##-###### ...
| | | | | | * a066e66 #####.  ### ### ###### ########## ####...
| | | | | | * afb7945 (###: ####-##-##-#######, ###: ####-##...
| | | | | | *   a14e769 Merge remote-tracking branch 'origin/master' into align
| | | | | | |\
| | | | | |_|/
| | | | |/| |
| | | | * | |   4354de6 Merge pull request #5 from repo/tech-bug-fixes
| | | | |\ \ \
| | | | | * | | c084aa8 (######/####-###-#####) ##### ######...
| | | | | * | | aea8a4f ######### ###-######## # ###### ### ...
| | | | | * | | 7857c95 ### #### #############, ### ### ####...
| | | |_|/ / /
| | |/| | | |
| | | | * | | 0b65102 .
| | | | * | |   2448af9 Merge branch 'master' of https://ghe/repo/repo
| | | | |\ \ \
| | | | * | | | 04c03da ##### ##### ###### ## ###### #######...
| | | | | | | * e05b167 ###### ### ## ######### ##########, ...
| | | | | | | * c3422d5 ##### ###############() ###### ## ##...
| | | | | | | * 92f4eff ##### ### ## ######/######### ####-#...
| | | | | | | * 35fb291 ### ################## (##### ######...
| | | | | | | * 6d12b2c ##### # ####### ## ######### #-###-#...
| | | | | | | *   aa84d37 Merge branch 'master' into align
| | | | | | | |\
| | | | | | |_|/
| | | | | |/| |
| | | | | * | | a96cb9d ##### #### ##### ######## ### ##### ...
| | | | |/ / /
| | | | * | | 911e5d2 ######## ### ##### #########.
| | | |/ / /
| | | * | |   d32ef9a Merge pull request #4 from repo/tech
| | | |\ \ \
| | |/ / / /
| | | * | | 092858f (######/####) ######## #### ## ######.
| | | * | | 1d862dd ##### ############ ## #### ### ### #### ...
| | | * | |   7eae069 Merge branch 'master' into tech
| | | |\ \ \
| | | |/ / /
| | |/| | |
| | | * | | f639a00 ##### ##### ## ### ########
| | | * | | ac794d9 ##### ################ ###### #### #####...
| | | * | | b0296ac ####### ########## ## ####### #### ## ##...
| | | * | | 91f2adf ###########
| | | * | | 47ae5eb ######
| | | * | | a975c46 ####### ##### ## #########
| | | * | |   041a552 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | |\ \ \
| | | | * | | 908b8f7 ######
| | | | * | |   85ff704 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | | |\ \ \
| | | | * | | | 6351c83 ######
| | | * | | | | 1486296 ###### #### ########.
| | | | |/ / /
| | | |/| | |
| | | * | | | 89cefd9 ######### ############# #### ### #####...
| | | |/ / /
| | | * | | 401b346 ### ########## ## ######### ######### ##...
| | | * | |   0e36458 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | |\ \ \
| | | | * | | 7029347 ######
| | | | * | |   d819996 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | | |\ \ \
| | | | * | | | 1d11d8a ######
| | | | * | | |   0f52244 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | | |\ \ \ \
| | | | * | | | | 63f49c3 ######
| | | * | | | | | 15e0017 ######
| | | | |_|/ / /
| | | |/| | | |
| | | * | | | | a7c00b8 ######### ## ### #### ### #### ####
| | | | |/ / /
| | | |/| | |
| | | * | | | 5074fe5 ####### ## #### ########## ###### ## #...
| | | |/ / /
| | | * | | 989e68c ####### ## ### #### ### #### #### ####, ...
| | | * | |   9b3545c Merge branch 'tech' of https://ghe/repo/repo into tech
| | | |\ \ \
| | | | * | | 2a9f6b2 ##### #### ## ######## ######### #####...
| | | * | | | 519ac87 ######
| | | |/ / /
| | | * | | e850bac ######
| | | * | | 7e920c4 ######### ## ### #### ### ####### ### ##...
| | | * | | ac4608d ######## ## #### #### ########### ## ###...
| | | * | | f7f4e0c ###### ##-######### ## ###### ## ## ####...
| | | * | | 7ed258f ##### ######## ## ###### ##### ##### ###...
| | | | | * 67c8f71 ##### ### ## ######### ######## ########...
| | | | | * 2280a88 ##### ######### ### #### ### ##########
| | | | | * 3bd5b85 ##### # ### ## ##-######; ## ##### #####...
| | | | | *   7919cc3 Merge branch 'master' into align
| | | | | |\
| | | |_|_|/
| | |/| | |
| | * | | | 7278053 ##### #### ####### ##########.
| |/ / / /
|/| | | |
| | | | * 31d1e44 ##### # ### ### ### ######### ## ###### ##...
| | | | * 87f8195 ######## ### ### ###### ##### ####### ####...
| | | | * 379bd4a ### '#' ### ## #### # #### ### ####### ###...
| | | | * fe30105 ##### ######### ###### ##### ## ###### ###...
| | | | *   3b50f20 Merge branch 'master' of https://ghe/repo/repo into align
| | | | |\
| |_|_|_|/
|/| | | |
* | | | |   48ca2d6 Merge branch 'master' of https://ghe/repo/repo
|\ \ \ \ \
| |/ / / /
| * | | |   edbf46e Merged from align
| |\ \ \ \
| * | | | | af282b8 ##### ###### ### ######### ### ## .#####...
| * | | | | 2237855 ####### ### ######### ### #### ##### ## ...
| * | | | | f0711d9 ##### ###################() ### ########...
| * | | | | 5bc790b Made RW_assert() work on 64-bit.
* | | | | | c53aad5 ##### ######## ### ######## ####### ### ...
* | | | | | 1b4f135 ##### ####### #### #### ### ######-#####...
| | | | | * 49730f3 #####, ### ######, ## ###### ######## ##...
| | | | | * 8efc11e ##### ###### ### ######### ### ## .#####...
| | | | | * e0f583a ####### ### ######### ### #### ##### ## ...
| | | | | * 3b1a263 ##### ###################() ### ########...
| | | | | * c2bbb3d Made RW_assert() work on 64-bit.
| | | |_|/
| | |/| |
| | * | | 67154d6 ##### ##### ####### ### ####. ######### ##...
</code>```

Looking at the bottom of the log above, c2bbb3d is the initial commit to align, 5bc790b is the cherry-pick of that commit to master.  67154d6 I expect is the common ancestor, that's where the output of git cherry stops.

The question I still can't answer is, how could I get a list of commits made to align, which are not already on master?  It seems like any commit reachable from align, but not from master, is a candidate, as long as it hasn't already been cherry-picked to master.  Any branch which feeds into master would have to be checked for cherry-picks -- that includes every branch in the graph except the rightmost one, align.

NB: we've been using git for just a few months so I'm pretty sure much of what we're doing is not best practice.  We're learning a lot from trial and error.

答:
Let me put the newly added extra question at the top, since it's actually kind of more important, and easy to answer:

The question I still can't answer is, how could I get a list of commits made to align, which are not already on master?

You get that with the output of git rev-list (which is meant for computers) or git log (meant for humans) when given:

```<code>align ^master
</code>```

as the two constraints.  (Minor aside as a reminder: git rev-list and git log are essentially the same command, with the difference being that git rev-list is aimed at further processing, so that it just produces full hash IDs by default, while git log is aimed at human reading, so it shows commits by default.  There are a bunch of small-but-important details about the way git log shows commits, but for --oneline output they don't matter here.)

These constraints tell the Git revision-list walker: Find me commits that are "on"—meaning "reachable in a walk through history starting from"—the commit specified by the name align, but exclude from that list all commits that are "on" master.  Given the graph above, this list of commits is fairly long.

This particular form, yes ^no, can be spelled no..yes instead, giving the more familiar short form:

```<code>git log --decorate --oneline --graph master..align
</code>```

(note that there are two dots in this form).  I've included the DOG, Decorate Oneline Graph, options, since for this particular purpose the friendly dog really is often helpful.1

If you reverse the names—git log align..master—you get the, in this case two, commits that are on master that are not on align.

This is also what the three-dot or symmetric difference form deals with: when we write master...align or align...master, as seen in the original answer below, we tell Git to produce both of these walks.  One finds commits that are on master that are not on align (just two), and the other finds commits that are on align that are not on master (many).

When we use this three-dot symmetric difference form with git rev-list (or git log), we can tell Git to mark up the output to show which side the commits come from.  That mark-up can even use git patch-id to find commits in the two sides that are identical.  But it doesn't look at any commits that were not selected by both sides, and in particular, when you strip it down to --left-only or --right-only, you can drop a lot of data.  (Those data points are often useless ones and dropping them is good, but they're not always useless.)

1For git log, I think it's actually a good idea to have --decorate turned on pretty much all the time.  In fact, it's such a good idea that Linus Torvalds himself got it added to Git back in v2.1.0, but nobody remembered to document it until Git v2.9.0.

Note that the graph you have added above is somewhat complicated (many squirrelly little lines running around), so that there is more than one commit at which various lines fork and join.  When you use master...align or align...master, the revision-walking code prunes away any commits reachable from both starting-points.  Imagine printing out the log and taking two highlighters to it.  With one color, you start marking at master and color all the lines and stars you can get to from there.  With the other color, you start marking at align and color all the lines and stars you can reach from there.  Wherever the two highlightings overlap, those commits are on both; where they don't, those commits are on just one branch.

Original answer, regarding git cherry

The patch-ids are identical. Why has git cherry not detected that this commit was already cherry-picked?

The git cherry command looks only at a limited subset of the commit graph.  Looking at the whole thing would take too long for too little gain.

Exactly how you got into this particular situation, I am not sure (there is more than one way to get here), but here are two different [Edit: and simple] situations as they might be shown by git log --oneline --decorate --graph align master:

```<code>* c2bbb3d (align) Made RW_assert() work on 64-bit.
* xxxxxxx some other commit here
| * 5bc790b (master) Made RW_assert() work on 64-bit.
|/
* yyyyyyy whatever commit here
* zzzzzzz yet another commit
   ... snip ...
</code>```

Or:

```<code>* c2bbb3d (align) Made RW_assert() work on 64-bit.
* xxxxxxx some other commit here
| * zzzzzzz (master) yet another commit
|/
* yyyyyyy whatever commit here
* 5bc790b Made RW_assert() work on 64-bit.
   ... snip ...
</code>```

Running git cherry master align will show the commit as redundant, i.e., not needing cherry-picking, only for the first graph.  The reason for this is that git cherry looks at only the portion of the graph that "extends up" from the point where the two graph lines fork.

Since the two graph lines rejoin at yyyyyyy whatever commit here, the command never looks at any commit "at or below" that point.  Given that you got a claim that c2bbb3d was "new", your graph must resemble the second graph, not the first (and your comment reply says that it does).

A more precise definition

More precisely, git cherry master align uses git rev-list --left-right master...align to identify commits that are on either the align branch, or the master branch, but are not on both branches.  For simple graphs like the ones above, this cuts off the merge base and all its parent commits.  If the graph has a more complex topology, there may be multiple merge bases; all get excluded; exactly those commits that are reachable from just one of the two specific commits is included, and each such commit is marked, internally, as whether it was reached from the left-side argument (master in master...align) or the right-side argument (align in master...align).

The git cherry command—or even the git rev-list command itself, with the right arguments—then computes the git patch-id for each commit on the two sides.  This lets it detect which commits are the same, and which are different.  But it never computes a patch ID for any of the commits excluded by the symmetric-difference three-dot syntax.  In a large repository, that excludes most of the commits, and normally it does not matter for those since those commits are already on both branches anyway.

Body:
I've been working on branch align and want to cherry-pick some commits from it to master.
I use git cherry to look for candidate commits:

C:\Users\me\Documents\repo>git cherry -v master align | head -1
+ c2bbb3d99440be7524673702c92ad65e6522d2b1 Made RW_assert() work on 64-bit.

My understanding is the '+' means there's no equivalent commit on master.
But I remember cherry-picking this commit to master already.
In fact, it was the most recent change to file rw-fwd.h on branch align:

C:\Users\me\Documents\repo>git log align -1 rw-fwd.h
commit c2bbb3d99440be7524673702c92ad65e6522d2b1
Author: Me
Date:   Thu Jun 8 10:41:01 2017 +1000

    Made RW_assert() work on 64-bit.

And is still the most recent change to rw-fwd.h on branch master:

C:\Users\me\Documents\repo>git log master -1 rw-fwd.h
commit 5bc790b9b0adfcdc6c0a07b679155e33974e343a
Author: Me
Date:   Thu Jun 8 10:41:01 2017 +1000

    Made RW_assert() work on 64-bit.

The documentation for git cherry states: "The equivalence test is based on the diff, after removing whitespace and line numbers. git-cherry therefore detects when commits have been "copied" by means of git-cherry-pick[1], git-am[1] or git-rebase[1]."
Visually, using git show, the commits look the same, but let's be absolutely sure:

C:\Users\me\Documents\repo>git show c2bbb3d | git patch-id
f6ad0912fd71f694b6b00c6ea93c87af7cf4ab98 c2bbb3d99440be7524673702c92ad65e6522d2b1

C:\Users\me\Documents\repo>git show 5bc790b | git patch-id
f6ad0912fd71f694b6b00c6ea93c87af7cf4ab98 5bc790b9b0adfcdc6c0a07b679155e33974e343a

The patch-ids are identical.  Why has git cherry not detected that this commit was already cherry-picked?

Edit: below is a sanitized git log --oneline --decorate --graph.
I've added this in response to the answer by @torek, not because I have any doubt the answer's correct, but because I'd value some help in interpreting the real commit log in light of that answer.

master is at a52f43e (first line) and align is at 9ffa94e (third line).
align is the rightmost line on the graph all the way down, and is not merged from.

* a52f43e ######## ############ #####
* 507e731 ##### ##### ### ## ###
| *   9ffa94e (origin/align) Merge branch 'master' of https://ghe/repo/repo into align
| |\
| |/
|/|
* |   657d6c8 Merge pull request #8 from repo/test_system
|\ \
| * \   679739b Merged origin master into local branch.
| |\ \
| |/ /
|/| |
* | |   c7a5944 Merge branch 'master' of https://ghe/repo/repo
|\ \ \
| * \ \   e12016c Merge pull request #7 from repo/lean-mean
| |\ \ \
| | * | | 144fefd ##### ####### ##### ## #######
| | * | | 87e0e23 ####### ############## ## ####### ####### ...
| * | | | 8613f4e ######## ####### ######### ## ###### #####...
| |/ / /
* | | | 8f70a8d ######### #### ##### ### ###### ### ########...
* | | |   aedb306 Merge branch 'master' of https://ghe/repo/repo
|\ \ \ \
* \ \ \ \   0a4fd59 Merge branch 'master' of https://ghe/repo/repo
|\ \ \ \ \
* \ \ \ \ \   e1cfbfd Merge branch 'PBA_Experiment' of https://ghe/repo/repo
|\ \ \ \ \ \
| * | | | | | 7f1bc5b (######/##############) ##########
| | | | | * | 323d965 ######## ######### ####### ########.##...
| | | | | * | 5839749 ##### #######-#### ###### ## ### ## ##...
| | | | | | * d96ba71 ##-####### ############, ## ##### ####...
| | | | | | * 680354b #### ##### ######### #####, ##-###### ...
| | | | | | * a066e66 #####.  ### ### ###### ########## ####...
| | | | | | * afb7945 (###: ####-##-##-#######, ###: ####-##...
| | | | | | *   a14e769 Merge remote-tracking branch 'origin/master' into align
| | | | | | |\
| | | | | |_|/
| | | | |/| |
| | | | * | |   4354de6 Merge pull request #5 from repo/tech-bug-fixes
| | | | |\ \ \
| | | | | * | | c084aa8 (######/####-###-#####) ##### ######...
| | | | | * | | aea8a4f ######### ###-######## # ###### ### ...
| | | | | * | | 7857c95 ### #### #############, ### ### ####...
| | | |_|/ / /
| | |/| | | |
| | | | * | | 0b65102 .
| | | | * | |   2448af9 Merge branch 'master' of https://ghe/repo/repo
| | | | |\ \ \
| | | | * | | | 04c03da ##### ##### ###### ## ###### #######...
| | | | | | | * e05b167 ###### ### ## ######### ##########, ...
| | | | | | | * c3422d5 ##### ###############() ###### ## ##...
| | | | | | | * 92f4eff ##### ### ## ######/######### ####-#...
| | | | | | | * 35fb291 ### ################## (##### ######...
| | | | | | | * 6d12b2c ##### # ####### ## ######### #-###-#...
| | | | | | | *   aa84d37 Merge branch 'master' into align
| | | | | | | |\
| | | | | | |_|/
| | | | | |/| |
| | | | | * | | a96cb9d ##### #### ##### ######## ### ##### ...
| | | | |/ / /
| | | | * | | 911e5d2 ######## ### ##### #########.
| | | |/ / /
| | | * | |   d32ef9a Merge pull request #4 from repo/tech
| | | |\ \ \
| | |/ / / /
| | | * | | 092858f (######/####) ######## #### ## ######.
| | | * | | 1d862dd ##### ############ ## #### ### ### #### ...
| | | * | |   7eae069 Merge branch 'master' into tech
| | | |\ \ \
| | | |/ / /
| | |/| | |
| | | * | | f639a00 ##### ##### ## ### ########
| | | * | | ac794d9 ##### ################ ###### #### #####...
| | | * | | b0296ac ####### ########## ## ####### #### ## ##...
| | | * | | 91f2adf ###########
| | | * | | 47ae5eb ######
| | | * | | a975c46 ####### ##### ## #########
| | | * | |   041a552 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | |\ \ \
| | | | * | | 908b8f7 ######
| | | | * | |   85ff704 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | | |\ \ \
| | | | * | | | 6351c83 ######
| | | * | | | | 1486296 ###### #### ########.
| | | | |/ / /
| | | |/| | |
| | | * | | | 89cefd9 ######### ############# #### ### #####...
| | | |/ / /
| | | * | | 401b346 ### ########## ## ######### ######### ##...
| | | * | |   0e36458 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | |\ \ \
| | | | * | | 7029347 ######
| | | | * | |   d819996 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | | |\ \ \
| | | | * | | | 1d11d8a ######
| | | | * | | |   0f52244 Merge branch 'tech' of https://ghe/repo/repo into tech
| | | | |\ \ \ \
| | | | * | | | | 63f49c3 ######
| | | * | | | | | 15e0017 ######
| | | | |_|/ / /
| | | |/| | | |
| | | * | | | | a7c00b8 ######### ## ### #### ### #### ####
| | | | |/ / /
| | | |/| | |
| | | * | | | 5074fe5 ####### ## #### ########## ###### ## #...
| | | |/ / /
| | | * | | 989e68c ####### ## ### #### ### #### #### ####, ...
| | | * | |   9b3545c Merge branch 'tech' of https://ghe/repo/repo into tech
| | | |\ \ \
| | | | * | | 2a9f6b2 ##### #### ## ######## ######### #####...
| | | * | | | 519ac87 ######
| | | |/ / /
| | | * | | e850bac ######
| | | * | | 7e920c4 ######### ## ### #### ### ####### ### ##...
| | | * | | ac4608d ######## ## #### #### ########### ## ###...
| | | * | | f7f4e0c ###### ##-######### ## ###### ## ## ####...
| | | * | | 7ed258f ##### ######## ## ###### ##### ##### ###...
| | | | | * 67c8f71 ##### ### ## ######### ######## ########...
| | | | | * 2280a88 ##### ######### ### #### ### ##########
| | | | | * 3bd5b85 ##### # ### ## ##-######; ## ##### #####...
| | | | | *   7919cc3 Merge branch 'master' into align
| | | | | |\
| | | |_|_|/
| | |/| | |
| | * | | | 7278053 ##### #### ####### ##########.
| |/ / / /
|/| | | |
| | | | * 31d1e44 ##### # ### ### ### ######### ## ###### ##...
| | | | * 87f8195 ######## ### ### ###### ##### ####### ####...
| | | | * 379bd4a ### '#' ### ## #### # #### ### ####### ###...
| | | | * fe30105 ##### ######### ###### ##### ## ###### ###...
| | | | *   3b50f20 Merge branch 'master' of https://ghe/repo/repo into align
| | | | |\
| |_|_|_|/
|/| | | |
* | | | |   48ca2d6 Merge branch 'master' of https://ghe/repo/repo
|\ \ \ \ \
| |/ / / /
| * | | |   edbf46e Merged from align
| |\ \ \ \
| * | | | | af282b8 ##### ###### ### ######### ### ## .#####...
| * | | | | 2237855 ####### ### ######### ### #### ##### ## ...
| * | | | | f0711d9 ##### ###################() ### ########...
| * | | | | 5bc790b Made RW_assert() work on 64-bit.
* | | | | | c53aad5 ##### ######## ### ######## ####### ### ...
* | | | | | 1b4f135 ##### ####### #### #### ### ######-#####...
| | | | | * 49730f3 #####, ### ######, ## ###### ######## ##...
| | | | | * 8efc11e ##### ###### ### ######### ### ## .#####...
| | | | | * e0f583a ####### ### ######### ### #### ##### ## ...
| | | | | * 3b1a263 ##### ###################() ### ########...
| | | | | * c2bbb3d Made RW_assert() work on 64-bit.
| | | |_|/
| | |/| |
| | * | | 67154d6 ##### ##### ####### ### ####. ######### ##...

Looking at the bottom of the log above, c2bbb3d is the initial commit to align, 5bc790b is the cherry-pick of that commit to master.  67154d6 I expect is the common ancestor, that's where the output of git cherry stops.

The question I still can't answer is, how could I get a list of commits made to align, which are not already on master?  It seems like any commit reachable from align, but not from master, is a candidate, as long as it hasn't already been cherry-picked to master.  Any branch which feeds into master would have to be checked for cherry-picks -- that includes every branch in the graph except the rightmost one, align.

NB: we've been using git for just a few months so I'm pretty sure much of what we're doing is not best practice.  We're learning a lot from trial and error.

Body:
Let me put the newly added extra question at the top, since it's actually kind of more important, and easy to answer:

The question I still can't answer is, how could I get a list of commits made to align, which are not already on master?

You get that with the output of git rev-list (which is meant for computers) or git log (meant for humans) when given:

align ^master

as the two constraints.  (Minor aside as a reminder: git rev-list and git log are essentially the same command, with the difference being that git rev-list is aimed at further processing, so that it just produces full hash IDs by default, while git log is aimed at human reading, so it shows commits by default.  There are a bunch of small-but-important details about the way git log shows commits, but for --oneline output they don't matter here.)

These constraints tell the Git revision-list walker: Find me commits that are "on"—meaning "reachable in a walk through history starting from"—the commit specified by the name align, but exclude from that list all commits that are "on" master.  Given the graph above, this list of commits is fairly long.

This particular form, yes ^no, can be spelled no..yes instead, giving the more familiar short form:

git log --decorate --oneline --graph master..align

(note that there are two dots in this form).  I've included the DOG, Decorate Oneline Graph, options, since for this particular purpose the friendly dog really is often helpful.1

If you reverse the names—git log align..master—you get the, in this case two, commits that are on master that are not on align.

This is also what the three-dot or symmetric difference form deals with: when we write master...align or align...master, as seen in the original answer below, we tell Git to produce both of these walks.  One finds commits that are on master that are not on align (just two), and the other finds commits that are on align that are not on master (many).

When we use this three-dot symmetric difference form with git rev-list (or git log), we can tell Git to mark up the output to show which side the commits come from.  That mark-up can even use git patch-id to find commits in the two sides that are identical.  But it doesn't look at any commits that were not selected by both sides, and in particular, when you strip it down to --left-only or --right-only, you can drop a lot of data.  (Those data points are often useless ones and dropping them is good, but they're not always useless.)

1For git log, I think it's actually a good idea to have --decorate turned on pretty much all the time.  In fact, it's such a good idea that Linus Torvalds himself got it added to Git back in v2.1.0, but nobody remembered to document it until Git v2.9.0.

Note that the graph you have added above is somewhat complicated (many squirrelly little lines running around), so that there is more than one commit at which various lines fork and join.  When you use master...align or align...master, the revision-walking code prunes away any commits reachable from both starting-points.  Imagine printing out the log and taking two highlighters to it.  With one color, you start marking at master and color all the lines and stars you can get to from there.  With the other color, you start marking at align and color all the lines and stars you can reach from there.  Wherever the two highlightings overlap, those commits are on both; where they don't, those commits are on just one branch.

Original answer, regarding git cherry

The patch-ids are identical. Why has git cherry not detected that this commit was already cherry-picked?

The git cherry command looks only at a limited subset of the commit graph.  Looking at the whole thing would take too long for too little gain.

Exactly how you got into this particular situation, I am not sure (there is more than one way to get here), but here are two different [Edit: and simple] situations as they might be shown by git log --oneline --decorate --graph align master:

* c2bbb3d (align) Made RW_assert() work on 64-bit.
* xxxxxxx some other commit here
| * 5bc790b (master) Made RW_assert() work on 64-bit.
|/
* yyyyyyy whatever commit here
* zzzzzzz yet another commit
   ... snip ...

Or:

* c2bbb3d (align) Made RW_assert() work on 64-bit.
* xxxxxxx some other commit here
| * zzzzzzz (master) yet another commit
|/
* yyyyyyy whatever commit here
* 5bc790b Made RW_assert() work on 64-bit.
   ... snip ...

Running git cherry master align will show the commit as redundant, i.e., not needing cherry-picking, only for the first graph.  The reason for this is that git cherry looks at only the portion of the graph that "extends up" from the point where the two graph lines fork.

Since the two graph lines rejoin at yyyyyyy whatever commit here, the command never looks at any commit "at or below" that point.  Given that you got a claim that c2bbb3d was "new", your graph must resemble the second graph, not the first (and your comment reply says that it does).

A more precise definition

More precisely, git cherry master align uses git rev-list --left-right master...align to identify commits that are on either the align branch, or the master branch, but are not on both branches.  For simple graphs like the ones above, this cuts off the merge base and all its parent commits.  If the graph has a more complex topology, there may be multiple merge bases; all get excluded; exactly those commits that are reachable from just one of the two specific commits is included, and each such commit is marked, internally, as whether it was reached from the left-side argument (master in master...align) or the right-side argument (align in master...align).

The git cherry command—or even the git rev-list command itself, with the right arguments—then computes the git patch-id for each commit on the two sides.  This lets it detect which commits are the same, and which are different.  But it never computes a patch ID for any of the commits excluded by the symmetric-difference three-dot syntax.  In a large repository, that excludes most of the commits, and normally it does not matter for those since those commits are already on both branches anyway.


来源: stackexchange

问:
Date is getting Printed in echo command while executing shell script
Hope everyone is having a good day
i'm trying to write a script to introduce a cron job via script
the following command is working fine when executed in shell script

```<code>echo '0 20 * * * touch /global/appaem/aem/wrap-lock/wrap.lock-`date +"%Y%m%d"`' >> /tmp/tmp.txt
more /tmp/tmp.txt
0 20 * * * touch /global/appaem/aem/wrap-lock/wrap.lock-`date +"%Y%m%d"
</code>```

But when the same command is being executed from script it's displaying the below o/p

```<code>/global/appaem/aem/wrap-lock/wrap.lock-20170707
</code>```

can some help here

答:
First of all, you should prefer $() in bash to fork a subshell.

To print out your desired command without being interpreted by bash, you need to escape $, i.e.

```<code>#!/bin/bash
echo "0 20 * * * touch /global/appaem/aem/wrap-lock/wrap.lock-\$(date +\"%Y%m%d\")" >> /tmp/tmp.txt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hope everyone is having a good day
i'm trying to write a script to introduce a cron job via script
the following command is working fine when executed in shell script

echo '0 20 * * * touch /global/appaem/aem/wrap-lock/wrap.lock-`date +"%Y%m%d"`' >> /tmp/tmp.txt
more /tmp/tmp.txt
0 20 * * * touch /global/appaem/aem/wrap-lock/wrap.lock-`date +"%Y%m%d"

But when the same command is being executed from script it's displaying the below o/p

/global/appaem/aem/wrap-lock/wrap.lock-20170707

can some help here

Body:
First of all, you should prefer $() in bash to fork a subshell.

To print out your desired command without being interpreted by bash, you need to escape $, i.e.

#!/bin/bash
echo "0 20 * * * touch /global/appaem/aem/wrap-lock/wrap.lock-\$(date +\"%Y%m%d\")" >> /tmp/tmp.txt


问:
Issuing an Identity for a Participant not working on RestAPI, but it does in Command Line
I have deployed a custom .bna using the Fabric provided in the developer environment tutorial. Then, I started the composer-rest-server as follows:

```<code>composer-rest-server -p hlfv1 -n bonusetis -i admin -s adminpw -N never
</code>```

Then, I created some participants, and tried to issue an identity within the RestAPI Loopback (at 3000/explorer), where it sends a

```<code>curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
   "participant": "gemma", \
   "userID": "gemmatarres" \
 }' 'http://localhost:3000/api/system/issueIdentity'
</code>```

but I got the following error:

```<code>{
  "error": {
    "statusCode": 500,
    "name": "Error",
    "message": "error trying invoke chaincode. Error: chaincode error (status: 500, message: Error: Invalid fully qualified participant identifier)",
    "stack": "Error: error trying invoke chaincode. Error: chaincode error (status: 500, message: Error: Invalid fully qualified participant identifier)\n    at _initializeChannel.then.then.then.then.catch (/usr/lib/node_modules/composer-rest-server/node_modules/composer-connector-hlfv1/lib/hlfconnection.js:839:34)"
  }
}
</code>```

But when I try the same using the Command Line, as:

```<code>composer identity issue -n 'bonusetis' -i admin -s adminpw -u danigranados -a "org.basetis.bonusetis.user#dani" -p hlfv1
</code>```

The Command is successful and the identity created. I have tried with different participants with the same result. Also, despite the error, if I try to issue a new identity with the same userID I got the error, then it says that the identity is already registered.

Versions are all latest composer (0.9.1) and Fabric (RC1).

答:
Lluis

I believe the problem is you need the 'fully-qualified' participant name in your 'curl' command.

So:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
   "participant": "org.acme.acmeis.user#orgadmin1", \
   "userID": "dave" \
 }' 'http://localhost:3000/api/system/issueIdentity'

where orgadmin1 is your participant already added and 'dave' is your identity.

Body:
I have deployed a custom .bna using the Fabric provided in the developer environment tutorial. Then, I started the composer-rest-server as follows:

composer-rest-server -p hlfv1 -n bonusetis -i admin -s adminpw -N never

Then, I created some participants, and tried to issue an identity within the RestAPI Loopback (at 3000/explorer), where it sends a

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
   "participant": "gemma", \
   "userID": "gemmatarres" \
 }' 'http://localhost:3000/api/system/issueIdentity'

but I got the following error:

{
  "error": {
    "statusCode": 500,
    "name": "Error",
    "message": "error trying invoke chaincode. Error: chaincode error (status: 500, message: Error: Invalid fully qualified participant identifier)",
    "stack": "Error: error trying invoke chaincode. Error: chaincode error (status: 500, message: Error: Invalid fully qualified participant identifier)\n    at _initializeChannel.then.then.then.then.catch (/usr/lib/node_modules/composer-rest-server/node_modules/composer-connector-hlfv1/lib/hlfconnection.js:839:34)"
  }
}

But when I try the same using the Command Line, as:

composer identity issue -n 'bonusetis' -i admin -s adminpw -u danigranados -a "org.basetis.bonusetis.user#dani" -p hlfv1

The Command is successful and the identity created. I have tried with different participants with the same result. Also, despite the error, if I try to issue a new identity with the same userID I got the error, then it says that the identity is already registered.

Versions are all latest composer (0.9.1) and Fabric (RC1).


问:
DataGridView retrieve entire row
I'm using CellClick to open a message box and show the row contents of a single row from a DataGridView in a form. I was stumped in trying to find something more elegant than what I've got so far. I was searching for a way to display the contents of the column header, and the row value, possibly using foreach or a for loop, but no avail. Any recommendations?</p>

```<code>private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (authorDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            MessageBox.Show("Author Number: " + authorDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()
                + "\nAuthor First Name: " + authorDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()
                + "\nAuthor Last Name: " + authorDataGridView.Rows[e.RowIndex].Cells[2].Value.ToString());
        }
    }
</code>```

答:
Given that you are using a BindingSource, you can also achieve this using the BindingSource.Current property - in fact I prefer this because you'll be able to access the current selected Row in the DataGridView from any other event/method (for example a button click as well).

```<code>private void btnShow_Click(object sender, EventArgs e)
{
    var currentAuthor = (Author)authorBindingSource.Current;
    MessageBox.Show(currentAuthor.Name);
}
</code>```

Also to show Author's properties in desired format you could override the ToString() method and then just do a MessageBox.Show(currentAuthor.ToString()).

```<code>public class Author
{
    public int Number { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return $"Author Number: {Number}\nAuthor First Name: {FirstName}\nAuthor Last Name: {LastName}";
    }
}
</code>```

Refer to this MSDN help for more info BindingSource.Current

ContentLicense: CC BY-SA 4.0

Title: DataGridView retrieve entire row

Body:
I'm using CellClick to open a message box and show the row contents of a single row from a DataGridView in a form. I was stumped in trying to find something more elegant than what I've got so far. I was searching for a way to display the contents of the column header, and the row value, possibly using foreach or a for loop, but no avail. Any recommendations?

private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (authorDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            MessageBox.Show("Author Number: " + authorDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()
                + "\nAuthor First Name: " + authorDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()
                + "\nAuthor Last Name: " + authorDataGridView.Rows[e.RowIndex].Cells[2].Value.ToString());
        }
    }

Body:
Given that you are using a BindingSource, you can also achieve this using the BindingSource.Current property - in fact I prefer this because you'll be able to access the current selected Row in the DataGridView from any other event/method (for example a button click as well).

private void btnShow_Click(object sender, EventArgs e)
{
    var currentAuthor = (Author)authorBindingSource.Current;
    MessageBox.Show(currentAuthor.Name);
}

Also to show Author's properties in desired format you could override the ToString() method and then just do a MessageBox.Show(currentAuthor.ToString()).

public class Author
{
    public int Number { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return $"Author Number: {Number}\nAuthor First Name: {FirstName}\nAuthor Last Name: {LastName}";
    }
}

Refer to this MSDN help for more info BindingSource.Current


问:
angular 2 form submit with select tag
I trying to send form with angular 2 to rest api, my problem is I want to give a select tag name the label value.

example :

this is the component.html :

```<code><div class="ui raised segment">
  <h2 class="ui header">Demo Form: Sku</h2>
  <form #f="ngForm"
        (ngSubmit)="onSubmit(f.value)"
        class="ui form">

    <div class="field">
      <label for="skuInput">SKU</label>
      <input type="text"
             id="skuInput"
             placeholder="SKU"
             name="sku" ngModel>
    </div>
    <div class="field">
      <label for="select1" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:spanish: </label>
      <select class="form-control" name="note1" id="select1" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      <label for="select2" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">english: </label>
      <select class="form-control" name="note2" id="select2" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      <label for="select3" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:frensh: </label>
      <select class="form-control" name="note3" id="select3" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

    </div>

    <button type="submit" class="ui button">Submit</button>
  </form>
</div>
</code>```

I want the the name of select 1 be spanish (value of label 1)

component.ts :

```<code>import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-post-history',
  templateUrl: './post-history.component.html',
  styleUrls: ['./post-history.component.css']
})
export class PostHistoryComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }

  onSubmit(form: any): void {
    console.log('you submitted value:', form);
  }

}
</code>```

every thing work ok if i give every select tag a different name :

every select have name, instead of that name I want to show the label value of every select.

答:
LABELs are not form elements that can hold or send data. They are captions tied to form elements.

So, the label is not sent with the ngForm on submit.

Why not putting your label value as the name of the select control:

```<code><label for="select1" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:spanish: </label>
<select class="form-control" name="spanish" id="select1" ngModel>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
</code>```

Like this you will get the result you seek:

**
To address your comment, you can always keep your labels text in an array on the component like:

```<code>labelsName = [{select1: "your 15 words label"}, {select2: "another label"}]
</code>```

Then, when you get your submit, you map the name of each selector with the key on your array to get the label.

Title: angular 2 form submit with select tag

Body:
I trying to send form with angular 2 to rest api, my problem is I want to give a select tag name the label value.

example :

this is the component.html :

Demo Form: Sku

  <form #f="ngForm"
        (ngSubmit)="onSubmit(f.value)"
        class="ui form">

      SKU
      <input type="text"
             id="skuInput"
             placeholder="SKU"
             name="sku" ngModel>

      Langues:spanish:
      <select class="form-control" name="note1" id="select1" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      english:
      <select class="form-control" name="note2" id="select2" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      Langues:frensh:
      <select class="form-control" name="note3" id="select3" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

    <button type="submit" class="ui button">Submit</button>
  </form>

I want the the name of select 1 be spanish (value of label 1)

component.ts :

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-post-history',
  templateUrl: './post-history.component.html',
  styleUrls: ['./post-history.component.css']
})
export class PostHistoryComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }

  onSubmit(form: any): void {
    console.log('you submitted value:', form);
  }

}

every thing work ok if i give every select tag a different name :

every select have name, instead of that name I want to show the label value of every select.

Body:
LABELs are not form elements that can hold or send data. They are captions tied to form elements.

So, the label is not sent with the ngForm on submit.

Why not putting your label value as the name of the select control:

<label for="select1" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:spanish: </label>
<select class="form-control" name="spanish" id="select1" ngModel>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>

Like this you will get the result you seek:

**
To address your comment, you can always keep your labels text in an array on the component like:

labelsName = [{select1: "your 15 words label"}, {select2: "another label"}]

Then, when you get your submit, you map the name of each selector with the key on your array to get the label.


问:
Laravel Query Relationship on One Model Instance
I am aware that I can use count() to query for Eloquent relationships in Laravel, like so:

```<code>if(count($question->answers()))
</code>```

Where answers() is a hasMany relationship:

```<code> public function answers()
    {
        return $this->hasMany('App\Models\Answer', 'question_id');
    }
</code>```

My question is, how do I do this when $question is not an entire collection but one Model instance?

```<code>$question = Question::where('id',$key)->first();
</code>```

How do I query the above question, and only that question, for a potential relationship using count()?

I always am getting a count() of greater than zero, even when the selected question has no associated answers, which means my if block always runs and returns unwarranted null values:

```<code>if(count($question->answers()))
   {
   //returns nulls
   }
</code>```

答:
Since calling $question->answers() is returning a QueryBuilder instance, calling count() on that will most likely always return 1. If you access $question->answers (as a property and not a method), or use the full logic $question->answers()->get(); it should properly return a Collection, which count() will function correctly on:

```<code>$question = Question::where('id',$key)->first();

if(count($question->answers) > 0){
  // Do something
}

// OR

if(count($question->answers()->get()) > 0){
  ...
}
</code>```

As suggested by @maraboc, you could also eager load your $question with answers using a ->with() clause:

```<code>$question = Question::with(["answers"])->where('id',$key)->first();
</code>```

But even in this case, $question->answers() would still be returning a QueryBuilder instance, so access it as a property for count() to function correctly.

Body:
I am aware that I can use count() to query for Eloquent relationships in Laravel, like so:

if(count($question->answers()))

Where answers() is a hasMany relationship:

 public function answers()
    {
        return $this->hasMany('App\Models\Answer', 'question_id');
    }

My question is, how do I do this when $question is not an entire collection but one Model instance?

$question = Question::where('id',$key)->first();

How do I query the above question, and only that question, for a potential relationship using count()?

I always am getting a count() of greater than zero, even when the selected question has no associated answers, which means my if block always runs and returns unwarranted null values:

if(count($question->answers()))
   {
   //returns nulls
   }

Body:
Since calling $question->answers() is returning a QueryBuilder instance, calling count() on that will most likely always return 1. If you access $question->answers (as a property and not a method), or use the full logic $question->answers()->get(); it should properly return a Collection, which count() will function correctly on:

$question = Question::where('id',$key)->first();

if(count($question->answers) > 0){
  // Do something
}

// OR

if(count($question->answers()->get()) > 0){
  ...
}

As suggested by @maraboc, you could also eager load your $question with answers using a ->with() clause:

$question = Question::with(["answers"])->where('id',$key)->first();

But even in this case, $question->answers() would still be returning a QueryBuilder instance, so access it as a property for count() to function correctly.


问:
Uninstall multiple android packages using adb
I am trying to uninstall multiple packages using a bash script with adb uninstall.

In theory following scripts should work:

```<code>adb shell pm list packages com.your.app |
cut -d ':' -f 2 | while read line ; do
  adb uninstall --verbose $line
done
</code>```

OR

```<code>adb shell pm list packages com.your.app |
cut -d ':' -f 2 |
xargs -L1 -t adb uninstall
</code>```

I get the following error

Failure [DELETE_FAILED_INTERNAL_ERROR]

I also found that the problem is with adb commands not taking piped arguments or arguments from shell variables. For example the following command also

```<code>echo com.your.app | adb uninstall
</code>```

This will also give the same error.

I have already looked at delete packages of domain by adb shell pm

答:
\r is added added to the output from the first command. We can use tr -d '\r' to remove these characters.

```<code>adb shell pm list packages com.your.app |
cut -d ':' -f 2 |
tr -d '\r' |
xargs -L1 -t adb uninstall
</code>```

Found the solution in Echo outputting results in erratic order in BASH

Body:
I am trying to uninstall multiple packages using a bash script with adb uninstall.

In theory following scripts should work:

adb shell pm list packages com.your.app |
cut -d ':' -f 2 | while read line ; do
  adb uninstall --verbose $line
done

OR

adb shell pm list packages com.your.app |
cut -d ':' -f 2 |
xargs -L1 -t adb uninstall

I get the following error

Failure [DELETE_FAILED_INTERNAL_ERROR]

I also found that the problem is with adb commands not taking piped arguments or arguments from shell variables. For example the following command also

echo com.your.app | adb uninstall

This will also give the same error.

I have already looked at delete packages of domain by adb shell pm

Body:
\r is added added to the output from the first command. We can use tr -d '\r' to remove these characters.

adb shell pm list packages com.your.app |
cut -d ':' -f 2 |
tr -d '\r' |
xargs -L1 -t adb uninstall

Found the solution in Echo outputting results in erratic order in BASH


问:
RSS feed created with PHP only shows the title in the feed reader
I am using the following PHP code to generate the XML for an RSS feed, but it doesn't seem to be working correctly.  No short description is displayed in the feed reader, all I see is the title of the article.  Also, all of the articles say they were published at the same time.  This is the first time I have tried to setup an RSS feed, so I'm sure I've made several stupid mistakes.</p>

```<code>$result = mysql_query("SELECT * FROM blog ORDER BY id DESC LIMIT 10");

$date = date(DATE_RFC822);

header('Content-type: text/xml');

echo ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
echo ("<rss version=\"2.0\">\n");
echo ("<channel>\n");
echo ("<lastBuildDate>$date</lastBuildDate>\n");
echo ("<pubDate>$date</pubDate>\n");
echo ("<title>my website name</title>\n");
echo ("<description><![CDATA[the description]]></description>\n");
echo ("<link>http://my-domain.com</link>\n");
echo ("<language>en</language>\n");

$ch=100;
while ($a = mysql_fetch_array($result)) {
    $headline = htmlentities(stripslashes($a['subject']));
    $posturl = $a[perm_link];
    $content = $a['post'];
    $date = date(DATE_RFC822, $a['posted']);

    echo ("<item>\n");
    echo ("<title>$headline</title>\n");
    echo ("<link>$posturl</link>\n");
    echo ("<description><![CDATA[$content]]></description>\n");
    echo ("<guid isPermaLink=\"true\">$posturl</guid>\n");
    echo ("<pubDate>$date2</pubDate>\n");
    echo ("</item>\n");
}

echo ("</channel>\n");
echo ("</rss>\n");
</code>```

答:
Are you sure that $a['post'] contains the post?

Missing quotes for array index in $a[perm_link];

The variable you store the date in is called $date, while in the feed you're putting $date2;

(does not compromise the functionalities but) why did you declare that $ch var just before the loop?

ContentLicense: CC BY-SA 2.5

Body:
I am using the following PHP code to generate the XML for an RSS feed, but it doesn't seem to be working correctly.  No short description is displayed in the feed reader, all I see is the title of the article.  Also, all of the articles say they were published at the same time.  This is the first time I have tried to setup an RSS feed, so I'm sure I've made several stupid mistakes.

$result = mysql_query("SELECT * FROM blog ORDER BY id DESC LIMIT 10");

$date = date(DATE_RFC822);

header('Content-type: text/xml');

echo ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
echo ("<rss version=\"2.0\">\n");
echo ("<channel>\n");
echo ("<lastBuildDate>$date</lastBuildDate>\n");
echo ("<pubDate>$date</pubDate>\n");
echo ("<title>my website name</title>\n");
echo ("<description><![CDATA[the description]]></description>\n");
echo ("<link>http://my-domain.com</link>\n");
echo ("<language>en</language>\n");

$ch=100;
while ($a = mysql_fetch_array($result)) {
    $headline = htmlentities(stripslashes($a['subject']));
    $posturl = $a[perm_link];
    $content = $a['post'];
    $date = date(DATE_RFC822, $a['posted']);

    echo ("<item>\n");
    echo ("<title>$headline</title>\n");
    echo ("<link>$posturl</link>\n");
    echo ("<description><![CDATA[$content]]></description>\n");
    echo ("<guid isPermaLink=\"true\">$posturl</guid>\n");
    echo ("<pubDate>$date2</pubDate>\n");
    echo ("</item>\n");
}

echo ("</channel>\n");
echo ("</rss>\n");


问:
Wildfly: AMQ214016: Failed to create netty connect ion java.nio.channels.UnresolvedAddressException from client on natted network
I have a wildfly 10 instance installed in a docker container (Container-A). If I try to look up queues from other containers of the same engine (Server-B, the engine) everything works fine.

I have issues (see trace below), instead, when trying to lookup queues from a virtual machine that is on the same network of the engine (Server-C) using the server-B's IP address on port 7080 that is mapped on the container's 8080 port.

I tryed to open a telnet connection from Server-C to Container-A (using the Server-B ip address and 7080 port) and the connection looks OK.

Can anyone help me??

```<code>C:\App>java -jar my-jar.jar
log4j:WARN No appenders could be found for logger (com.myApp.S
etUpBowcaster).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more in
fo.
2017-05-30 18:44:01 INFO  SetUpBowcaster:? - PROCESSORS BUSES INITIALIZATION
2017-05-30 18:44:01 INFO  xnio:93 - XNIO version 3.3.4.Final
2017-05-30 18:44:01 INFO  nio:55 - XNIO NIO Implementation Version 3.3.4.Final
2017-05-30 18:44:01 INFO  remoting:73 - JBoss Remoting version 4.0.18.Final
2017-05-30 18:44:01 INFO  remoting:103 - EJBCLIENT000017: Received server versio
n 2 and marshalling strategies [river]
2017-05-30 18:44:01 INFO  remoting:219 - EJBCLIENT000013: Successful version han
dshake completed for receiver context EJBReceiverContext{clientContext=org.jboss
.ejb.client.EJBClientContext@15b3e5b, receiver=Remoting connection EJB receiver
[connection=Remoting connection <56467971>,channel=jboss.ejb,nodename=my-jms-master]} on channel Channel ID b9880cf2 (outbound) of Remoting connec
tion 71d15f18 to /10.0.0.247:7080
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further detail
s.
2017-05-30 18:44:02 INFO  client:45 - JBoss EJB Client version 2.1.4.Final
2017-05-30 18:44:03 ERROR client:686 - AMQ214016: Failed to create netty connect
ion
java.nio.channels.UnresolvedAddressException
        at sun.nio.ch.Net.checkAddress(Net.java:123)
        at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:622)
        at io.netty.channel.socket.nio.NioSocketChannel.doConnect(NioSocketChann
el.java:209)
        at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.connect(Abs
tractNioChannel.java:207)
        at io.netty.channel.DefaultChannelPipeline$HeadContext.connect(DefaultCh
annelPipeline.java:1097)
        at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(Abstract
ChannelHandlerContext.java:471)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:456)
        at io.netty.channel.ChannelOutboundHandlerAdapter.connect(ChannelOutboun
dHandlerAdapter.java:47)
        at io.netty.channel.CombinedChannelDuplexHandler.connect(CombinedChannel
DuplexHandler.java:167)
        at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(Abstract
ChannelHandlerContext.java:471)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:456)
        at io.netty.channel.ChannelDuplexHandler.connect(ChannelDuplexHandler.ja
va:50)
        at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(Abstract
ChannelHandlerContext.java:471)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:456)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:438)
        at io.netty.channel.DefaultChannelPipeline.connect(DefaultChannelPipelin
e.java:908)
        at io.netty.channel.AbstractChannel.connect(AbstractChannel.java:203)
        at io.netty.bootstrap.Bootstrap$2.run(Bootstrap.java:166)
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(Single
ThreadEventExecutor.java:358)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:357)
        at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThread
EventExecutor.java:112)
        at java.lang.Thread.run(Thread.java:745)
Exception in thread "main" com.myApp.exceptions.ProcessorStart
upException: javax.jms.JMSException: Failed to create session factory
        at com.myApp.SetUpBowcaster.main(Unknown Source)
Caused by: javax.jms.JMSException: Failed to create session factory
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.crea
teConnectionInternal(ActiveMQConnectionFactory.java:727)
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.crea
teQueueConnection(ActiveMQConnectionFactory.java:284)
        at com.myApp.applicationLayer.jms.BowcasterProcessorsH
andlersManager.setUpJmsConnection(Unknown Source)
        at com.myApp.applicationLayer.jms.BowcasterProcessorsH
andlersManager.<init>(Unknown Source)
        at com.myApp.applicationLayer.jms.BowcasterProcessorsH
andlersManager.getInstance(Unknown Source)
        ... 1 more
Caused by: ActiveMQNotConnectedException[errorType=NOT_CONNECTED message=AMQ1190
07: Cannot connect to server(s). Tried with all available servers.]
        at org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl.create
SessionFactory(ServerLocatorImpl.java:777)
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.crea
teConnectionInternal(ActiveMQConnectionFactory.java:724)
        ... 5 more
2017-05-30 18:44:03 INFO  remoting:482 - EJBCLIENT000016: Channel Channel ID b98
80cf2 (outbound) of Remoting connection 71d15f18 to /10.0.0.247:7080 can no long
er process messages
</code>```

答:
The address:port may need to be fully qualified. I fixed this by changing the following property in my code:

```<code>artemis.nodes=machine-artemis-01:port
</code>```

to:

```<code>artemis.nodes=machine-artemis-01.place.company.com:port
</code>```

Body:
I have a wildfly 10 instance installed in a docker container (Container-A). If I try to look up queues from other containers of the same engine (Server-B, the engine) everything works fine.

I have issues (see trace below), instead, when trying to lookup queues from a virtual machine that is on the same network of the engine (Server-C) using the server-B's IP address on port 7080 that is mapped on the container's 8080 port.

I tryed to open a telnet connection from Server-C to Container-A (using the Server-B ip address and 7080 port) and the connection looks OK.

Can anyone help me??

C:\App>java -jar my-jar.jar
log4j:WARN No appenders could be found for logger (com.myApp.S
etUpBowcaster).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more in
fo.
2017-05-30 18:44:01 INFO  SetUpBowcaster:? - PROCESSORS BUSES INITIALIZATION
2017-05-30 18:44:01 INFO  xnio:93 - XNIO version 3.3.4.Final
2017-05-30 18:44:01 INFO  nio:55 - XNIO NIO Implementation Version 3.3.4.Final
2017-05-30 18:44:01 INFO  remoting:73 - JBoss Remoting version 4.0.18.Final
2017-05-30 18:44:01 INFO  remoting:103 - EJBCLIENT000017: Received server versio
n 2 and marshalling strategies [river]
2017-05-30 18:44:01 INFO  remoting:219 - EJBCLIENT000013: Successful version han
dshake completed for receiver context EJBReceiverContext{clientContext=org.jboss
.ejb.client.EJBClientContext@15b3e5b, receiver=Remoting connection EJB receiver
[connection=Remoting connection <56467971>,channel=jboss.ejb,nodename=my-jms-master]} on channel Channel ID b9880cf2 (outbound) of Remoting connec
tion 71d15f18 to /10.0.0.247:7080
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further detail
s.
2017-05-30 18:44:02 INFO  client:45 - JBoss EJB Client version 2.1.4.Final
2017-05-30 18:44:03 ERROR client:686 - AMQ214016: Failed to create netty connect
ion
java.nio.channels.UnresolvedAddressException
        at sun.nio.ch.Net.checkAddress(Net.java:123)
        at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:622)
        at io.netty.channel.socket.nio.NioSocketChannel.doConnect(NioSocketChann
el.java:209)
        at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.connect(Abs
tractNioChannel.java:207)
        at io.netty.channel.DefaultChannelPipeline$HeadContext.connect(DefaultCh
annelPipeline.java:1097)
        at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(Abstract
ChannelHandlerContext.java:471)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:456)
        at io.netty.channel.ChannelOutboundHandlerAdapter.connect(ChannelOutboun
dHandlerAdapter.java:47)
        at io.netty.channel.CombinedChannelDuplexHandler.connect(CombinedChannel
DuplexHandler.java:167)
        at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(Abstract
ChannelHandlerContext.java:471)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:456)
        at io.netty.channel.ChannelDuplexHandler.connect(ChannelDuplexHandler.ja
va:50)
        at io.netty.channel.AbstractChannelHandlerContext.invokeConnect(Abstract
ChannelHandlerContext.java:471)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:456)
        at io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChanne
lHandlerContext.java:438)
        at io.netty.channel.DefaultChannelPipeline.connect(DefaultChannelPipelin
e.java:908)
        at io.netty.channel.AbstractChannel.connect(AbstractChannel.java:203)
        at io.netty.bootstrap.Bootstrap$2.run(Bootstrap.java:166)
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(Single
ThreadEventExecutor.java:358)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:357)
        at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThread
EventExecutor.java:112)
        at java.lang.Thread.run(Thread.java:745)
Exception in thread "main" com.myApp.exceptions.ProcessorStart
upException: javax.jms.JMSException: Failed to create session factory
        at com.myApp.SetUpBowcaster.main(Unknown Source)
Caused by: javax.jms.JMSException: Failed to create session factory
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.crea
teConnectionInternal(ActiveMQConnectionFactory.java:727)
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.crea
teQueueConnection(ActiveMQConnectionFactory.java:284)
        at com.myApp.applicationLayer.jms.BowcasterProcessorsH
andlersManager.setUpJmsConnection(Unknown Source)
        at com.myApp.applicationLayer.jms.BowcasterProcessorsH
andlersManager.<init>(Unknown Source)
        at com.myApp.applicationLayer.jms.BowcasterProcessorsH
andlersManager.getInstance(Unknown Source)
        ... 1 more
Caused by: ActiveMQNotConnectedException[errorType=NOT_CONNECTED message=AMQ1190
07: Cannot connect to server(s). Tried with all available servers.]
        at org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl.create
SessionFactory(ServerLocatorImpl.java:777)
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.crea
teConnectionInternal(ActiveMQConnectionFactory.java:724)
        ... 5 more
2017-05-30 18:44:03 INFO  remoting:482 - EJBCLIENT000016: Channel Channel ID b98
80cf2 (outbound) of Remoting connection 71d15f18 to /10.0.0.247:7080 can no long
er process messages

Body:
The address:port may need to be fully qualified. I fixed this by changing the following property in my code:

artemis.nodes=machine-artemis-01:port

to:

artemis.nodes=machine-artemis-01.place.company.com:port


问:
How to efficiently merge sort with vectors using C++
I have implemented a merge sort in c++ by using vectors as function
arguments instead of indices (start, end). However, I would love to
know if there is any trade off by doing this, in terms of speed
and space complexity

The code:

```<code>void mergeSort(std::vector<int> &array) {
    if(array.size() == 1) return;
    else {
      const unsigned int len = array.size();
      const int lo = floor((double)len/2);
      const int hi = ceil((double)len/2);

      std::vector<int> L(&array[0], &array[lo]);
      std::vector<int> R(&array[lo], &array[len]);

      mergeSort(L);
      mergeSort(R);
      merge(array, L, R);
    }
    return;
}
</code>```

Creating new lists every call to merge sort might not be the way to go,
but this is how the merge sort function works. Also, how fast/slow is the:

```<code>std::vector<int> L(&array[0], &array[lo]);
</code>```

The merge function then looks like:

```<code>void merge(
           std::vector<int> &array,
           std::vector<int> &L,
           std::vector<int> &R
          ) {
    std::vector<int>::iterator a = array.begin();
    std::vector<int>::iterator l = L.begin();
    std::vector<int>::iterator r = R.begin();

    while(l != L.end() && r != R.end()) {
      if (*l <= *r) {
      *a = *l;
      l++;
      }
      else {
        *a = *r;
        r++;
      }
      a++;
   }
   while (l != L.end()) {
     *a = *l;
     a++;
     l++;
   }
   while (r != R.end()) {
     *a = *r;
     a++;
     r++;
   }
   return;
</code>```

}

答:
Well, there is not need to create new space at each call of merge.
std::vector<int> L(&array[0], &array[lo]); will actually create space to accomodate lo elements and will perform lo copies as well.

You are never gonna use more then O(n) additional space for storing values. So, why don't you allocate a buffer large enough accommodate the
a copy of the whole vector upfront and make each recursive call operate on a specific portion of the data? this way you don't have to create new vectors at each call.

Plus, I will also encourage you to make the mergesort works on iterators instead on vector<int> only. An interface like the following should be enough.

```<code>template < typename Iterator, typename Compare>
void mergesort(Iterator s, Iterator e, Compare cmp);
</code>```

On Github you can find a version of mergesort I have implemented a while ago. It should be enough I guess.

Body:
I have implemented a merge sort in c++ by using vectors as function
arguments instead of indices (start, end). However, I would love to
know if there is any trade off by doing this, in terms of speed
and space complexity

The code:

void mergeSort(std::vector<int> &array) {
    if(array.size() == 1) return;
    else {
      const unsigned int len = array.size();
      const int lo = floor((double)len/2);
      const int hi = ceil((double)len/2);

      std::vector<int> L(&array[0], &array[lo]);
      std::vector<int> R(&array[lo], &array[len]);

      mergeSort(L);
      mergeSort(R);
      merge(array, L, R);
    }
    return;
}

Creating new lists every call to merge sort might not be the way to go,
but this is how the merge sort function works. Also, how fast/slow is the:

std::vector<int> L(&array[0], &array[lo]);

The merge function then looks like:

void merge(
           std::vector<int> &array,
           std::vector<int> &L,
           std::vector<int> &R
          ) {
    std::vector<int>::iterator a = array.begin();
    std::vector<int>::iterator l = L.begin();
    std::vector<int>::iterator r = R.begin();

    while(l != L.end() && r != R.end()) {
      if (*l <= *r) {
      *a = *l;
      l++;
      }
      else {
        *a = *r;
        r++;
      }
      a++;
   }
   while (l != L.end()) {
     *a = *l;
     a++;
     l++;
   }
   while (r != R.end()) {
     *a = *r;
     a++;
     r++;
   }
   return;

}

Body:
Well, there is not need to create new space at each call of merge.
std::vector<int> L(&array[0], &array[lo]); will actually create space to accomodate lo elements and will perform lo copies as well.

You are never gonna use more then O(n) additional space for storing values. So, why don't you allocate a buffer large enough accommodate the
a copy of the whole vector upfront and make each recursive call operate on a specific portion of the data? this way you don't have to create new vectors at each call.

Plus, I will also encourage you to make the mergesort works on iterators instead on vector<int> only. An interface like the following should be enough.

template < typename Iterator, typename Compare>
void mergesort(Iterator s, Iterator e, Compare cmp);

On Github you can find a version of mergesort I have implemented a while ago. It should be enough I guess.


问:
RestFuse vs Rest Assured vs MockMVC Rest Service Unit Test Framework
I've been trying to find a simple all purpose unit test framework for Spring MVC based Rest Services I've written.

I've been searching online and narrowed it down to:

RestFuse (http://developer.eclipsesource.com/restfuse/)

Rest Assured (https://github.com/jayway/rest-assured)

MockMVC (http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-rest-api/)

I like RestFuse because it's mostly annotation based, but rest assured seems to have a easier way of passing parameters and checking responses. And finally being a Spring MVC Rest Service project, I'm wondering if I should just stick with the already established way of testing Rest Services in Spring with MockMVC.

Interested to get any feedback, as well as performance, past experiences and if there's anything else I should take into consideration.

答:
The beauty of MockMVC is that it provides a mock servlet container, allowing you to integration-test your REST services without deploying to a web server.  I believe that you can still leverage this power when using REST Assured with the spring-mock-mvc module.

Another framework that I just learned of is Karate.  Its author is currently experimenting with a mechanism to allow execution in a mock servlet container (see Peter Thomas' answer to Is there a mechanism for integration testing JAX-RS services without deploying (a la MockMVC)?).


问:
Summing up more than two dataframes with the same indexes in Pandas
I want to add values of 4 Dataframes with the same indexes in Pandas. If there are two dataframes, df1 and df2, we may write:

```<code>df1.add(df2)
</code>```

and for 3 dataframes:

```<code>df3.add(df2.add(df1))
</code>```

I wonder if there is a more general way to do so in Python.

答:
Option 1

Use sum

```<code>sum([df1, df2, df3, df4])
</code>```

Option 2

Use reduce

```<code>from functools import reduce

reduce(pd.DataFrame.add, [df1, df2, df3, df4])
</code>```

Option 3

Use pd.concat and pd.DataFrame.sum with level=1

This only works if there is a single level to the dataframe indices.  We've have to get a little more cute to make it work.  I recommend the other options.

```<code>pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)
</code>```

Setup

```<code>df = pd.DataFrame([[1, -1], [complex(0, 1), complex(0, -1)]])
df1, df2, df3, df4 = [df] * 4
</code>```

Demo

```<code>sum([df1, df2, df3, df4])

        0        1
0  (4+0j)  (-4+0j)
1      4j      -4j
</code>```

```<code>from functools import reduce

reduce(pd.DataFrame.add, [df1, df2, df3, df4])

        0        1
0  (4+0j)  (-4+0j)
1      4j      -4j
</code>```

```<code>pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)

        0        1
0  (4+0j)  (-4+0j)
1      4j      -4j
</code>```

Timing

small data

```<code>%timeit sum([df1, df2, df3, df4])
%timeit reduce(pd.DataFrame.add, [df1, df2, df3, df4])
%timeit pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)

1000 loops, best of 3: 591 µs per loop
1000 loops, best of 3: 456 µs per loop
100 loops, best of 3: 3.61 ms per loop
</code>```

larger data

```<code>df = pd.DataFrame([[1, -1], [complex(0, 1), complex(0, -1)]])
df = pd.concat([df] * 1000, ignore_index=True)
df = pd.concat([df] * 100, axis=1, ignore_index=True)
df1, df2, df3, df4 = [df] * 4

%timeit sum([df1, df2, df3, df4])
%timeit reduce(pd.DataFrame.add, [df1, df2, df3, df4])
%timeit pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)

100 loops, best of 3: 3.94 ms per loop
100 loops, best of 3: 2.9 ms per loop
1 loop, best of 3: 1min per loop
</code>```

Body:
I want to add values of 4 Dataframes with the same indexes in Pandas. If there are two dataframes, df1 and df2, we may write:

df1.add(df2)

and for 3 dataframes:

df3.add(df2.add(df1))

I wonder if there is a more general way to do so in Python.

Body:
Option 1

Use sum

sum([df1, df2, df3, df4])

Option 2

Use reduce

from functools import reduce

reduce(pd.DataFrame.add, [df1, df2, df3, df4])

Option 3

Use pd.concat and pd.DataFrame.sum with level=1

This only works if there is a single level to the dataframe indices.  We've have to get a little more cute to make it work.  I recommend the other options.

pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)

Setup

df = pd.DataFrame([[1, -1], [complex(0, 1), complex(0, -1)]])
df1, df2, df3, df4 = [df] * 4

Demo

sum([df1, df2, df3, df4])

        0        1
0  (4+0j)  (-4+0j)
1      4j      -4j

from functools import reduce

reduce(pd.DataFrame.add, [df1, df2, df3, df4])

        0        1
0  (4+0j)  (-4+0j)
1      4j      -4j

pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)

        0        1
0  (4+0j)  (-4+0j)
1      4j      -4j

Timing

small data

%timeit sum([df1, df2, df3, df4])
%timeit reduce(pd.DataFrame.add, [df1, df2, df3, df4])
%timeit pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)

1000 loops, best of 3: 591 µs per loop
1000 loops, best of 3: 456 µs per loop
100 loops, best of 3: 3.61 ms per loop

larger data

df = pd.DataFrame([[1, -1], [complex(0, 1), complex(0, -1)]])
df = pd.concat([df] * 1000, ignore_index=True)
df = pd.concat([df] * 100, axis=1, ignore_index=True)
df1, df2, df3, df4 = [df] * 4

%timeit sum([df1, df2, df3, df4])
%timeit reduce(pd.DataFrame.add, [df1, df2, df3, df4])
%timeit pd.concat(dict(enumerate([df1, df2, df3, df4]))).sum(level=1)

100 loops, best of 3: 3.94 ms per loop
100 loops, best of 3: 2.9 ms per loop
1 loop, best of 3: 1min per loop


问:
How is Jersey framework implement JAX-RS API in REST?
I know there are a lot of answers on this questions , but i am still confused about difference between JAX-RS API(the specification), and Jersey framework( reference implementation).

I read that:

Jersey framework basically uses com.sun.jersey.spi.container.servlet.ServletContainer servlet to intercept all the incoming requests. As we configure in our projects web.xml, that all the incoming rest request should be handled by that servlet. There is an init-param that is configured with the jersey servlet to find your REST service classes. REST service classes are not Servlet and they need NOT to extend the HttpServlet as you did in your code. These REST service classes are simple POJOs annotated to tell the jersey framework about different properties such as path, consumes, produces etc. When you return from your service method, jersey takes care of marshalling those objects in the defined 'PRODUCES' responseType and write it on the client stream

My question is when you say :" jersey takes care of marshalling those objects in the defined 'PRODUCES' responseType and write it on the client stream",  what you mean by jersey , what is actual class or library  that handles objects .

I am confused when i read that jersey is the engine that handles JAX-RS API specification. Can someone please explain what exactly is behind word jersey in this sentence? What actual class from Jersey do do the job of processing requests and responses in Jersey?

答:
The concept of specification and implementation is really pretty basic software engineering concepts. Your specification is the high level design. To help understand, I just came up with a really simple example.

Say I want to have a parsing library. I know how I want to be able to use it. The only problem is that I am not very good at writing parsing code. So I create a high level specification, and I outsource the implementation. Here are the three classes that are part of the spec. They are all contained in one "API jar", say myparsers-api.jar

```<code>public interface Parser {
    String[] parse(String s);
}

public interface ParserFactory {
    Parser getBySpaceParser();
    Parser getByCommaParser();
}

public class ParserDepot {
    private static ServiceLoader<ParserFactory> loader
            = ServiceLoader.load(ParserFactory.class);

    public static ParserFactory getDefaultParserFactory() {
        final List<ParserFactory> factories = new ArrayList<>();
        loader.forEach(factories::add);
        if (factories.isEmpty()) {
            throw new IllegalStateException("No ParserFactory found");
        }
        return factories.get(0);
    }
}
</code>```

So at this point, I can actually code against this jar. If I were to uses it as is right now in another project, the project would compile just fine.

```<code>ParserFactory factory = ParserDepot.getDefaultParserFactory();
Parser parser = factory.getBySpaceParser();
String[] tokens = parser.parse("Hello World");
System.out.println(Arrays.toString(tokens));
</code>```

So even though there is no implementation of this specification, I can still code against it, and compile against it. But when I try to actually run the program, it won't work, as there is no implementation. You can try to run this code, and you will get an IllegalStateException (see the docs for ServiceLoader if you're unfamiliar with this pattern).

So I outsource the implementation to say a company called Stack Overflow. They get my myparsers-api.jar and they need to give me back an implementation. They would need to implement a ParserFactory, and a couple of Parsers. They might look something like this

```<code>public class SoByCommaParser implements Parser {
    @Override
    public String[] parse(String s) {
        return s.split("\\s+,\\s+");
    }
}

public class SoBySpaceParser implements Parser {
    @Override
    public String[] parse(String s) {
        return s.split("\\s+");
    }
}

public class SoParserFactory implements ParserFactory {
    @Override
    public Parser getBySpaceParser() {
        return new SoBySpaceParser();
    }

    @Override
    public Parser getByCommaParser() {
        return new SoByCommaParser();
    }
}
</code>```

Now Stack Overflow gives me back a jar (say so-myparsers-impl.jar) with these three classes and the required META-INF/services file (per the ServiceLoader pattern), and now when I add the so-myparsers-impl.jar to my project and try to run it again, the program now works, because now it has an implementation.

This is exactly how the JAX-RS spec works. It only defines the high level design of how it should work. The classes, interfaces, and annotations that are part of that design are placed in an "API jar" just like my high level parsers are put into a jar. Implementations cannot alter these classes. All the classes that are part of the JAX-RS specification (version 2.x) are put into one single jar javax.ws.rs-api. You can code against that jar, and your code will compile just fine. But there is nothing to make it "work".

You check out both the written specification and the classes defined by the specification and you will notice that the only classes included in the source code are those mentioned in the specification. But what you should notice is that the written specification doesn't mention anything at all about how it is supposed to be implementation.  Take for example the following code

```<code>@Path("/test")
public class TestResource {
    @GET
    public String get() {
        return "Testing";
    }
}

@ApplicationPath("/api")
public class MyApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(TestResource.class);
        return classes;
    }
}
</code>```

Now the specification states that this is all we need to run a JAX-RS application in a servlet container. And that's all it says. It says nothing about how it all supposed to work. This is just how it is designed to work.

So what, is there some magic voodoo in Java that we don't know about that will make this Application class start a server, and some hocus pocus that will make a @Path annotated class automatically accept requests. No. Some body needs to provide the engine. The engine might be 20,000 lines of code just to make the above code work as specified.

That being said, Jersey is just the name of an implementation. It's like when I outsourced my parser implementation to Stack Overflow; The name Jersey itself is just the name of the project, just like Hadoop is a name of the project. In this case, what the project is, is an implementation of the JAX-RS specification. And because JAX-RS is just a specification, it means that anyone can implement it. If you wanted to, you could write your own implementation. As long as it works how it is defined to work in the written specification, then you can say that your code is an implementation of JAX-RS. There's more than just Jersey out there; you also have RESTEasy, which is another implementation.

As far as how Jersey implements the engine, that is way too broad. What I can do, is give you a high level overview of what happens behinds the scenes.

A JAX-RS application is defined to run inside of a servlet container. If you understand servlet containers and the servlet spec, then you'll know that the only way to handle requests is either by writing a HttpServlet or Filter. So if you want to implement JAX-RS then you need to able to handle requests either through a HttpServlet or a Filter. The ServletContainer you mentioned, is actually both. So for Jersey, this is the "entry point" into the Jersey application, as far as request processing is concerned. It can be configured in a number of ways (I've leave that research to you).

And if you understand how to write your own servlet, then you know all you get is an HttpServletRequest and HttpServletResponse. You need to figure out what to do from there; get request info from the request, and send response info back out in the response. Jersey handles all of this.

If you really want to get into the gory details of what is going on under the hood, you will just need to to dig into the source code, starting from the entry point, the ServletContainer. Be prepared to spend months on this to get a really good understanding of how it all works. It's not something that can be explained in one Stack Overflow post, if that's what you're expecting.

Body:
The concept of specification and implementation is really pretty basic software engineering concepts. Your specification is the high level design. To help understand, I just came up with a really simple example.

Say I want to have a parsing library. I know how I want to be able to use it. The only problem is that I am not very good at writing parsing code. So I create a high level specification, and I outsource the implementation. Here are the three classes that are part of the spec. They are all contained in one "API jar", say myparsers-api.jar

public interface Parser {
    String[] parse(String s);
}

public interface ParserFactory {
    Parser getBySpaceParser();
    Parser getByCommaParser();
}

public class ParserDepot {
    private static ServiceLoader<ParserFactory> loader
            = ServiceLoader.load(ParserFactory.class);

    public static ParserFactory getDefaultParserFactory() {
        final List<ParserFactory> factories = new ArrayList<>();
        loader.forEach(factories::add);
        if (factories.isEmpty()) {
            throw new IllegalStateException("No ParserFactory found");
        }
        return factories.get(0);
    }
}

So at this point, I can actually code against this jar. If I were to uses it as is right now in another project, the project would compile just fine.

ParserFactory factory = ParserDepot.getDefaultParserFactory();
Parser parser = factory.getBySpaceParser();
String[] tokens = parser.parse("Hello World");
System.out.println(Arrays.toString(tokens));

So even though there is no implementation of this specification, I can still code against it, and compile against it. But when I try to actually run the program, it won't work, as there is no implementation. You can try to run this code, and you will get an IllegalStateException (see the docs for ServiceLoader if you're unfamiliar with this pattern).

So I outsource the implementation to say a company called Stack Overflow. They get my myparsers-api.jar and they need to give me back an implementation. They would need to implement a ParserFactory, and a couple of Parsers. They might look something like this

public class SoByCommaParser implements Parser {
    @Override
    public String[] parse(String s) {
        return s.split("\\s+,\\s+");
    }
}

public class SoBySpaceParser implements Parser {
    @Override
    public String[] parse(String s) {
        return s.split("\\s+");
    }
}

public class SoParserFactory implements ParserFactory {
    @Override
    public Parser getBySpaceParser() {
        return new SoBySpaceParser();
    }

    @Override
    public Parser getByCommaParser() {
        return new SoByCommaParser();
    }
}

Now Stack Overflow gives me back a jar (say so-myparsers-impl.jar) with these three classes and the required META-INF/services file (per the ServiceLoader pattern), and now when I add the so-myparsers-impl.jar to my project and try to run it again, the program now works, because now it has an implementation.

This is exactly how the JAX-RS spec works. It only defines the high level design of how it should work. The classes, interfaces, and annotations that are part of that design are placed in an "API jar" just like my high level parsers are put into a jar. Implementations cannot alter these classes. All the classes that are part of the JAX-RS specification (version 2.x) are put into one single jar javax.ws.rs-api. You can code against that jar, and your code will compile just fine. But there is nothing to make it "work".

You check out both the written specification and the classes defined by the specification and you will notice that the only classes included in the source code are those mentioned in the specification. But what you should notice is that the written specification doesn't mention anything at all about how it is supposed to be implementation.  Take for example the following code

@Path("/test")
public class TestResource {
    @GET
    public String get() {
        return "Testing";
    }
}

@ApplicationPath("/api")
public class MyApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(TestResource.class);
        return classes;
    }
}

Now the specification states that this is all we need to run a JAX-RS application in a servlet container. And that's all it says. It says nothing about how it all supposed to work. This is just how it is designed to work.

So what, is there some magic voodoo in Java that we don't know about that will make this Application class start a server, and some hocus pocus that will make a @Path annotated class automatically accept requests. No. Some body needs to provide the engine. The engine might be 20,000 lines of code just to make the above code work as specified.

That being said, Jersey is just the name of an implementation. It's like when I outsourced my parser implementation to Stack Overflow; The name Jersey itself is just the name of the project, just like Hadoop is a name of the project. In this case, what the project is, is an implementation of the JAX-RS specification. And because JAX-RS is just a specification, it means that anyone can implement it. If you wanted to, you could write your own implementation. As long as it works how it is defined to work in the written specification, then you can say that your code is an implementation of JAX-RS. There's more than just Jersey out there; you also have RESTEasy, which is another implementation.

As far as how Jersey implements the engine, that is way too broad. What I can do, is give you a high level overview of what happens behinds the scenes.

A JAX-RS application is defined to run inside of a servlet container. If you understand servlet containers and the servlet spec, then you'll know that the only way to handle requests is either by writing a HttpServlet or Filter. So if you want to implement JAX-RS then you need to able to handle requests either through a HttpServlet or a Filter. The ServletContainer you mentioned, is actually both. So for Jersey, this is the "entry point" into the Jersey application, as far as request processing is concerned. It can be configured in a number of ways (I've leave that research to you).

And if you understand how to write your own servlet, then you know all you get is an HttpServletRequest and HttpServletResponse. You need to figure out what to do from there; get request info from the request, and send response info back out in the response. Jersey handles all of this.

If you really want to get into the gory details of what is going on under the hood, you will just need to to dig into the source code, starting from the entry point, the ServletContainer. Be prepared to spend months on this to get a really good understanding of how it all works. It's not something that can be explained in one Stack Overflow post, if that's what you're expecting.