How can I get a list of Git branches, ordered by most recent commit?

Question: I want to get a list of all the branches in a Git repository with the "freshest" branches at the top, where the "freshest" branch is the one that's been committed to most recently (and is, therefore, more likely to be one I want to pay attention to).
Is there a way I can use Git to either (a) sort the list of branches by latest commit, or (b) get a list of branches together with each one's last-commit date, in some kind of machine-readable format?
Worst case, I could always run git branch to get a list of all the branches, parse its output, and then git log -n 1 branchname --format=format:%ci for each one, to get each branch's commit date. But this will run on a Windows box, where spinning up a new process is relatively expensive, so launching the Git executable once per branch could get slow if there are a lot of branches. Is there a way to do all this with a single command?
Comment: @Spundun regarding the answer with `git for-each-ref` from Jakub Narębski: you can get remote branches passing `refs/remotes/` instead of `refs/heads/` (or you can pass both, whitespace-separated); `refs/tags/` for tags, or just `refs/` for all three kinds.
Comment: @Spundun, you lost me there. How is a combination of multiple commands, including stuff piped through perl and sed, "better" than using a command that Git already has?
Comment: Starting git 2.7 (Q4 2015), no more `for-each-ref`! You will use directly `git branch --sort=-committerdate`: see [my answer below](http://stackoverflow.com/a/33163401/6309)
Comment: http://stackoverflow.com/a/2514279/1804124 Has a better answer.
Comment: Because with the answer here , I didn't get all the branches in the repo. In my particular case, the answer would give me one branch and the answer there gave me 20 or so branches(with the -r option).
Comment: @JoeWhite it will still be available, but part of its semantic will be directly accessible from git branch itself.
Comment: I have completed [my answer below](http://stackoverflow.com/a/33163401/6309): when the comparison doesn't tiebreak branches (for instance same timestamp because committed together), it fallback on alphabetical comparison.
Comment: @VonC, do you mean `for-each-ref` will no longer be available, or just that it won't be needed here because there'll be a better way?
Comment: Is there a way to achieve this without cloning, ie.in the style of  `git ls-remote` ?
Comment: From a practical point of view, given a github repository with many branches, I want to be able to identify asap which branches are active versus stale. This is only possible via the web interface. For example: `https://github.com///branches/active`. This means, no command line can make this active vs stale determination.
Answer: Use the --sort=-committerdate option of git for-each-ref;
Also available since Git 2.7.0 for git branch:
Basic Usage:
git for-each-ref --sort=-committerdate refs/heads/

# Or using git branch (since version 2.7.0)
git branch --sort=-committerdate  # DESC
git branch --sort=committerdate  # ASC

Result:

Advanced Usage:
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'

Result:

Pro Usage (Unix):
You can put the following snippet in your ~/.gitconfig. The recentb alias accepts two arguments:

refbranch: which branch the ahead and behind columns are calculated against. Default master
count: how many recent branches to show. Default 20

[alias]
    # ATTENTION: All aliases prefixed with ! run in /bin/sh make sure you use sh syntax, not bash/zsh or whatever
    recentb = "!r() { refbranch=$1 count=$2; git for-each-ref --sort=-committerdate refs/heads --format='%(refname:short)|%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always --count=${count:-20} | while read line; do branch=$(echo \"$line\" | awk 'BEGIN { FS = \"|\" }; { print $1 }' | tr -d '*'); ahead=$(git rev-list --count \"${refbranch:-origin/master}..${branch}\"); behind=$(git rev-list --count \"${branch}..${refbranch:-origin/master}\"); colorline=$(echo \"$line\" | sed 's/^[^|]*|//'); echo \"$ahead|$behind|$colorline\" | awk -F'|' -vOFS='|' '{$5=substr($5,1,70)}1' ; done | ( echo \"ahead|behind|branch|lastcommit|message|author\n\" && cat) | column -ts'|';}; r"

Result:
Comment: This is a colorized version including hashes, messages, ordered ascending based on commit date, with the relative age of the last commit on each branch. I stole all of the ideas from you guys above. It's in my .gitconfig in the `[alias]` section and I love it. `br = for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'`
Comment: This is better for me: `git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname) %(committerdate) %(authorname)' | sed 's/refs\/heads\///g'`
Comment: @ilius: As @BeauSmith wrote: `git for-each-ref --sort=-committerdate --format='%(refname:short)' refs/heads/`.  git-for-each-ref(1) manpage says: *For a non-ambiguous short name of the ref append `:short`.*
Comment: Perfect! I can even restrict the output to just the ref names by appending `--format=%(refname)`.
Comment: @ilius: why not use `:shortname`?
Comment: @MikePercy ...what uh...what else you got in your `.gitconfig[alias]`? :)
Comment: @KevinFriedheim mostly just this and git log colorization stuff, but if you really want to know: https://github.com/mpercy/Dotfiles/blob/master/gitconfig :)
Comment: Also since Git 1.7.0 you don't need to resort to plumbing (low-level) commands; thanks to GSoC project of branch / tag / for-each-ref code unification, you can simply use `git branch --sort=-committerdate`.
Comment: Jakub's "Advanced Usage" example is the ascending type, for those who'd prefer the "Descending Usage", don't overlook the subtle difference he points out in his simple examples (the "-" sign). Here it is: `git for-each-ref --sort=-committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'`.Makes more sense as a super minor edit to show both "Advanced Usage" versions as an edit to the answer, but my minor edit was rejected.
Comment: To get the commit message as well: `git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname) %(committerdate) %(authorname) - %(contents:subject)' | sed 's/refs\/heads\///g'` Thanks!
Comment: @Poni: Nice.  Though you can use `%(refname:short)` instead of piping output to sed (and hoping that commit message does not contain `refs/heads/`).
Comment: To colorize the output: `git for-each-ref --sort='-committerdate' --format='%(color:green)%(committerdate:iso)  %(color:blue)%(authorname)%09%(color:reset)%(refname:short)'`
Comment: And this version will only show the last 10 entries, use `--count` to show more, also works as an alias if you want to: `git for-each-ref --sort=-committerdate --count=10 refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'`
Comment: `git branch --sort=-committerdate` is not working in git version 2.1.4 @jakub-narębski
Comment: @QiLuo: I'm sorry, a typo: it was meant to be Git **2.7.0** is the version from which you can use `git branch --sort=-committerdate`. See also e.g. https://git-blame.blogspot.com/2016/05/fun-with-new-feature-in-recent-git.html
Comment: I used refname:short but still a bunch of "heads/" are there while the branch name itself is not ambiguous.
Comment: Docs are here: http://www.kernel.org/pub/software/scm/git/docs/git-for-each-ref.html
Comment: @Spundun: while `git-for-each-ref` doesn't support all the bells and whistles that `--pretty` option in `git show` does, it does allow for advanced formatting of output via `--format` option.
Comment: pretty option is nice. But I liked the other answer mainly because this answer gave me only one branch while the other answer (with the -r option) gave me more than 20 branches.
Comment: @Spundun: The original question was about **list of branches** (not a single branch), **sorted**.  You can always pipe to `head -1`
Comment: I also wanted a list of branches, but I only got one branch. The other answer gave me the whole list of branches.
Comment: It's easier to read the output if you format it with the date first, as the dates are (to 1 character) the same length.
Comment: As of Git 2.7(ish), you can also add `align` fields to clean up the formatted output.
Comment: Advanced Usage is a bit inconsistent with Basic Usage in sort order as it uses `--sort=committerdate`. Is it worth to use `--sort=-committerdate` (with dash) as well?
Comment: Love the format. I changed it to accommodate my 'I don't want to have old branches lying around'-obsession and modified the format to my need:
`git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'`
Comment: Using the idea to pipe the output through `column` from @dimid [below](http://stackoverflow.com/a/30076212/3991403) my version of the command is: `git for-each-ref --sort=-committerdate refs/heads/ --format='%(HEAD) %(color:red)%(objectname:short)%(color:reset)|%(color:yellow)%(refname:short)%(color:reset)|%(contents:subject)|%(authorname) (%(color:green)%(committerdate:relative)%(color:reset))' | column -ts'|'`
Comment: Seems also `git branch` takes a format parameter (version 2.17.1), so the coloring works for it to. `branch` have the perk that it accepts `-r` or `-a` to show remote/all branches. I use alias `work = branch --sort=-committerdate --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'`
Comment: Windows: Replace single quotes with double quotes
Comment: `man git branch` shows the sort option: `--sort=`. How can I see a list of all "keys" one can use here to sort by?
Comment: For the current branch to stand out, consider using `%(if)%(HEAD)%(then)* %(color:red bold)%(refname:short)%(color:reset)%(else)  %(refname:short)%(end) `, which will color and bold it.
Comment: Since the `git branch` version doesn't take a count=n parameter, I added `--color=always` and piped it through `head -n 5`.
Comment: including remote branches `git branch -a --sort=-committerdate`
Comment: well, committerdate is not what I am looking for. I want to sort my branches by createdAt like sort the branches by the time they have in their createAt coloum not committedDate. Any idea?
Comment: @MKJ as far as I know it is not possible to sort branches using `git for-each-ref` by their  creation data. Moreover, the idea of "creation date of a branch" in Git is quite murky, and not easy to find. You could find it for the local branches in the reflog, as its first entry... unless those entries did expire.
Comment: On OS X Montery (at least) the column alignment is off for the header, inserting some backspaces (`\b`) into it helps fix things:

`echo \"ahead|behind||branch|\b\b\b\blastcommit|\b\b\b\b\b\bmessage|\b\b\b\bauthor\\n\"`
Comment: Now include whether the branch was merged into the default branch or not.
Comment: my contribution following @MichaelPercy, includes alignment & `git b` for recents vs `git ball` for all branches: `b = "! git ball | grep -v week | grep -v month"` then `ball = for-each-ref --color --sort=committerdate refs/heads/ --format='%(align:width=33,position=left)(committed %(color:bold green)%(committerdate:relative)%(color:reset))%(end) %(align:width=33,position=left)(authored %(color:green)%(creatordate:relative)%(color:reset))%(end) %(color:red)%(o  bjectname:short)%(color:reset) \t %(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(contents:subject) - %(authorname)'`
Comment: The column header alignment does not fit, there is a blind column between behind and branch.
`( echo \"ahead|behind||branch|lastcommit|message|author\\n\" && cat)`
With:
`( echo \"ahead|behind|branch|lastcommit|message|author\\n\" && cat)` it works like a charm.
Answer: Here is a simple command that lists all branches with latest commits:
git branch -v

To order by most recent commit, use
git branch -v --sort=committerdate

Source: http://git-scm.com/book/en/Git-Branching-Branch-Management
Comment: `git branch -av` if you want to see non-local branches too.
Comment: This is awesome. I like `git branch -va --sort=-committerdate` to show non-local branches, with the most recently changed branches at the top.
Comment: Is it easy to get `git branch -v` to include the date of each commit listed?
Comment: `git branch -v --format='%(committerdate:short) %(refname:short)'` will include the date.
Comment: For those coming from search, yes, `committerdate` will catch the last time that you amended or rebased. (The other possibility is `authordate`, which `amend` or `rebase` will not change by default.)
Comment: Not sure why it's not mentioned but to get the branch with the most recent commit at the top of the output you have to use `git branch -v --sort=committerdate | tac` on Linux so that the output is reversed. Otherwise you have the branch with the oldest commit at the top.
Comment: Sort order can be changed with a - prefix:
`git branch -v --sort=-committerdate`
https://git-scm.com/docs/git-branch#Documentation/git-branch.txt---sortltkeygt
Answer: List of Git branch names, ordered by most recent commit…
Expanding on Jakub's answer and Joe's tip, the following will strip out the "refs/heads/" so the output only displays the branch names:

Command:
git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format='%(refname:short)'

Result:
Comment: aah - @jakub.g already explained:  you can get remote branches passing refs/remotes/ instead of refs/heads/.  Perfect!!
Comment: Is there any way to do this for the REMOTE repository?
Comment: And now you can do this with `git branch`, so getting local, remote or all branches works like on git-branch (i.e. -r, -a). `git branch -r --sort=committerdate --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'`
Comment: @AllanBowe the following will output the top 5 active branches in a repo: `git branch -va --sort=committerdate | tail -5`. Perhaps that's an alternative to what you were asking and discovered.
Comment: I like this one, if you're trying to alias it, which I did, to `git rb` remember to surround the command in quotes: `git config --global alias.rb "for-each-ref --count=20 --sort=-committerdate refs/heads/ --format=\'%(refname:short)\'"`
Comment: To align the results, you can use tab (`%09`) instead of ` - `; then pipe it into columns. So, `git for-each-ref --sort=-committerdate refs/ --format='%(HEAD)%09%(color:yellow)%(refname:short)%(color:reset)%09%(color:red)%(objectname:short)%(color:reset)%09%(contents:subject)%09%(authorname)%09(%(color:green)%(committerdate:relative)%(color:reset))' | column -t -s $'\t'`
Answer: Here's the optimal code, which combines the other two answers:
git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(authorname) %(refname:short)'

Comment: Even a little mor optimized to get a tabular output: `git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(authorname) %(refname:short)'`
Comment: for some reason i had to use double-quotes on windows, but otherwise these work just fine :)
Comment: @schoetbi That code looks exactly like the one from nikolay, what did you change to make it tabular?
Comment: @Enrico and others that may wonder about the same thing. nikolay changed his answer using schoetbis suggestion. By moving date first which is always the same length the result seems more tabular.
Answer: I use the following alias:
recent = "!r() { count=$1; git for-each-ref --sort=-committerdate refs/heads --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always --count=${count:=10} | column -ts'|';}; r"
which produces:

We can also give a custom count, e.g.,
git recent 20 (the default is 10).
Comment: I had to add --color=always to get color.

`git for-each-ref --sort=-committerdate refs/heads --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always|column -ts'|'}`
Comment: I could not git this to work as a git alias. I had to use `[alias]
 recent = !git for-each-ref --sort=-committerdate refs/heads --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)'|column -ts'|'`
Comment: @mwfearnley: For me, putting a semicolon inside the braces helped `!r(){git for-each-ref ... ;}; r`
Comment: At least in the latest version of git you can just add `'%(HEAD) ...'` at the start of the format string to get the same effect without piping throught the `sed` command
Comment: I also need to add a semi-colon after `-ts'|'` i.e. `"!r(){ git ... -ts'|'; }; r"`
Comment: Great alias! I would suggest `column -ts'|'` and pipe characters if the comma char can occur inside relative timestamps in your locale.
Comment: great alias, thank you very much. can you improve it to show the current branch with an other colour or with * at the beginning?
Comment: Note there should be a space after `{`, also it might be an issue wit the shell, e.g. https://stackoverflow.com/questions/46435606/how-to-use-a-bash-function-in-a-git-alias
Comment: What does the `!r()` do?
Comment: @BrianLow Defines a function. See here https://jondavidjohn.com/git-aliases-parameters/
Comment: In case the ```sed \"s/m${cur}|/m* ${cur}|/\"``` gives you an error about an unknown option to s, the solution is to replace ```\"``` by a simple quote.
Comment: @thoroc but then I won't be able to expand `cur`
Comment: Any idea how to use `git branch --color[=]` to display branches in multiple colors
Comment: these anonymous function are not supported in fish :(. nice work, Id pipe it through some command to truncate the commit message.  some are longer than they should be, on occasion.
Comment: Could you include example shell commands necessary to set up and test this?  On my git (2.17.1), I basically get `r: not found`.
Comment: @mwfearnley Nothing special really, just add this alias to your git config file and call `git recent` from the shell.
Comment: Thanks, that's pretty much what I tried though.  You can see my ~/.gitconfig file at https://pastebin.com/JS2VJDwR .  I basically get: `r(){git for-each-ref  ... }; r: r: not found`.  Does it work for you?
Comment: Removing the `r` function  would also work: `!git for-each-ref --sort=-committerdate refs/heads --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always | column -ts'|'`
Comment: Please review *[Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/)* (e.g., *"Images should only be used to illustrate problems that* ***can't be made clear in any other way***, *such as to provide screenshots of a user interface."*) and take the appropriate [action](https://stackoverflow.com/posts/30076212/edit) (it covers answers and screen output as well).
Answer: I was able to reference the previous examples to create something that works best for me.

git for-each-ref --sort=-committerdate refs/heads
--format='%(authordate:short) %(color:red)%(objectname:short) %(color:yellow)%(refname:short)%(color:reset)
(%(color:green)%(committerdate:relative)%(color:reset))'

As suggested in the comments below you can also include remote branches and the author's name.

git for-each-ref --sort=-committerdate refs/heads refs/remotes
--format='%(authordate:short) %(color:red)%(objectname:short) %(color:yellow)%(refname:short)%(color:reset)
(%(color:green)%(committerdate:relative)%(color:reset)) %(authorname)'

Here are both commands as shell aliases that you can easily add to your shell profile.
# show a list of local git branches sorted by the commit date
alias git.branches='git for-each-ref --sort=-committerdate refs/heads --format="%(authordate:short) %(color:red)%(objectname:short) %(color:yellow)%(refname:short)%(color:reset) (%(color:green)%(committerdate:relative)%(color:reset))"'

# show a list of local and remote git branches sorted by the commit date
alias git.branches.remote='git for-each-ref --sort=-committerdate refs/heads refs/remotes --format="%(authordate:short) %(color:red)%(objectname:short) %(color:yellow)%(refname:short)%(color:reset) (%(color:green)%(committerdate:relative)%(color:reset)) %(authorname)"'

Comment: This one is clean and neat. Sometime I'd add remote and authorname as this:
    `git for-each-ref --sort=-committerdate refs/heads/ refs/remotes --format='%(authordate:short) %(authorname) %(color:red)%(objectname:short) %(color:yellow)%(refname:short)%(color:reset) (%(color:green)%(committerdate:relative)%(color:reset))'`
Comment: That looks nice, more colorful than using directly git branch as I suggested in https://stackoverflow.com/a/33163401/6309. +1
Comment: Ditto - this one worked out-of-box, unlike a number of others I just tried.  Thanks.
Comment: Like this one! Clean and concise, thanks. :)
Comment: Thanks, @VonC glad you like it!
Comment: Please review *[Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/)* (e.g., *"Images should only be used to illustrate problems that* ***can't be made clear in any other way***, *such as to provide screenshots of a user interface."*) and take the appropriate [action](https://stackoverflow.com/posts/44529712/edit) (it covers answers and screen output as well).
Answer: git 2.7 (Q4 2015) will introduce branch sorting using directly git branch:
See commit aa3bc55, commit aedcb7d, commit 1511b22, commit f65f139, ... (23 Sep 2015), commit aedcb7d, commit 1511b22, commit ca41799 (24 Sep 2015), and commit f65f139, ... (23 Sep 2015) by Karthik Nayak (KarthikNayak).
(Merged by Junio C Hamano -- gitster -- in commit 7f11b48, 15 Oct 2015)
In particular, commit aedcb7d:

branch.c: use 'ref-filter' APIs

Make 'branch.c' use 'ref-filter' APIs for iterating through refs sorting. This removes most of the code used in 'branch.c' replacing it
with calls to the 'ref-filter' library.
It adds the option --sort=<key>:

Sort based on the key given.
Prefix - to sort in descending order of the value.
You may use the --sort=<key> option multiple times, in which case the last key becomes the primary key.
The keys supported are the same as those in git for-each-ref.
Sort order defaults to sorting based on the full refname (including refs/... prefix). This lists detached HEAD (if present) first, then local branches and finally remote-tracking branches.

Here:
git branch --sort=-committerdate

Or (see below with Git 2.19)
# if you are sure to /always/ want to see branches ordered by commits:
git config --global branch.sort -committerdate
git branch

See also commit 9e46833 (30 Oct 2015) by Karthik Nayak (KarthikNayak).
Helped-by: Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 415095f, 03 Nov 2015)

When sorting as per numerical values (e.g. --sort=objectsize) there is no fallback comparison when both refs hold the same value. This can cause unexpected results (i.e. the order of listing refs with equal values cannot be pre-determined) as pointed out by Johannes Sixt ($gmane/280117).
Hence, fallback to alphabetical comparison based on the refname
whenever the other criterion is equal.
$ git branch --sort=objectsize

*  (HEAD detached from fromtag)
    branch-two
    branch-one
    master

With Git 2.19, the sort order can be set by default.
git branch supports a config branch.sort, like git tag, which already had a config tag.sort.
See commit 560ae1c (16 Aug 2018) by Samuel Maftoul (``).
(Merged by Junio C Hamano -- gitster -- in commit d89db6f, 27 Aug 2018)

branch.sort:

This variable controls the sort ordering of branches when displayed by git-branch.
Without the "--sort=<value>" option provided, the value of this variable will be used as the default.

To list remote branches, use git branch -r --sort=objectsize.  The -r flag causes it to list remote branches instead of local branches.

With Git 2.27 (Q2 2020), "git branch" and other "for-each-ref" variants accepted multiple --sort=<key> options in the increasing order of precedence, but it had a few breakages around "--ignore-case" handling, and tie-breaking with the refname, which have been fixed.
See commit 7c5045f, commit 76f9e56 (03 May 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 6de1630, 08 May 2020)

ref-filter: apply fallback refname sort only after all user sorts
Signed-off-by: Jeff King

Commit 9e468334b4 ("ref-filter: fallback on alphabetical comparison", 2015-10-30, Git v2.7.0-rc0 -- merge listed in batch #10) taught ref-filter's sort to fallback to comparing refnames.
But it did it at the wrong level, overriding the comparison result for a single "--sort" key from the user, rather than after all sort keys have been exhausted.
This worked correctly for a single "--sort" option, but not for multiple ones.
We'd break any ties in the first key with the refname and never evaluate the second key at all.
To make matters even more interesting, we only applied this fallback sometimes!
For a field like "taggeremail" which requires a string comparison, we'd truly return the result of strcmp(), even if it was 0.
But for numerical "value" fields like "taggerdate", we did apply the fallback. And that's why our multiple-sort test missed this: it uses taggeremail as the main comparison.
So let's start by adding a much more rigorous test. We'll have a set of commits expressing every combination of two tagger emails, dates, and refnames. Then we can confirm that our sort is applied with the correct precedence, and we'll be hitting both the string and value comparators.
That does show the bug, and the fix is simple: moving the fallback to the outer compare_refs() function, after all ref_sorting keys have been exhausted.
Note that in the outer function we don't have an "ignore_case" flag, as it's part of each individual ref_sorting element. It's debatable what such a fallback should do, since we didn't use the user's keys to match.
But until now we have been trying to respect that flag, so the least-invasive thing is to try to continue to do so.
Since all callers in the current code either set the flag for all keys or for none, we can just pull the flag from the first key. In a hypothetical world where the user really can flip the case-insensitivity of keys separately, we may want to extend the code to distinguish that case from a blanket "--ignore-case".

The implementation of "git branch --sort"(man) wrt the detached HEAD display has always been hacky, which has been cleaned up with Git 2.31 (Q1 2021).
See commit 4045f65, commit 2708ce6, commit 7c269a7, commit d094748, commit 75c50e5 (07 Jan 2021), and commit 08bf6a8, commit ffdd02a (06 Jan 2021) by Ævar Arnfjörð Bjarmason (avar).
(Merged by Junio C Hamano -- gitster -- in commit 9e409d7, 25 Jan 2021)

branch: show "HEAD detached" first under reverse sort
Signed-off-by: Ævar Arnfjörð Bjarmason

Change the output of the likes of "git branch -l --sort=-objectsize"(man) to show the "(HEAD detached at <hash>)" message at the start of the output.
Before the compare_detached_head() function added in a preceding commit we'd emit this output as an emergent effect.
It doesn't make any sense to consider the objectsize, type or other non-attribute of the "(HEAD detached at <hash>)" message for the purposes of sorting.
Let's always emit it at the top instead.
The only reason it was sorted in the first place is because we're injecting it into the ref-filter machinery so builtin/branch.c doesn't need to do its own "am I detached?" detection.

With Git 2.35 (Q1 2022), things like "git -c branch.sort=bogus branch new HEAD"(man), i.e.
the operation modes of the "git branch"(man) command that do not need the sort key information, no longer errors out by seeing a bogus sort key.
See commit 98e7ab6, commit 1a89796 (20 Oct 2021) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 5126145, 29 Nov 2021)

for-each-ref: delay parsing of --sort=<atom> options

The for-each-ref family of commands invoke parsers immediately when it sees each --sort=<atom> option, and die before even seeing the other options on the command line when the <atom> is unrecognised.
Instead, accumulate them in a string list, and have them parsed into a ref_sorting structure after the command line parsing is done.
As a consequence, "git branch --sort=bogus  -h"(man) used to fail to give the brief help, which arguably may have been a feature, now does so, which is more consistent with how other options work.
Comment: To list remotes with this option, add `-r`
Answer: I also needed colors, tags and remote references without any duplicates:
for ref in $(git for-each-ref --sort=-committerdate --format="%(refname)" refs/heads/ refs/remotes ); do git log -n1 $ref --pretty=format:"%Cgreen%cr%Creset %C(yellow)%d%Creset %C(bold blue)<%an>%Creset%n" | cat ; done | awk '! a[$0]++'

Because quoting can be hard, here is the alias for Bash:
alias glist='for ref in $(git for-each-ref --sort=-committerdate --format="%(refname)" refs/heads/ refs/remotes ); do git log -n1 $ref --pretty=format:"%Cgreen%cr%Creset %C(yellow)%d%Creset %C(bold blue)<%an>%Creset%n" | cat ; done | awk '"'! a["'$0'"]++'"

Comment: @MichaelDiscenza just pipe everything to head. that would be to add `| head -n20` at the end. If you are using the alias, be sure this goes *within* the quotes.
Comment: $
awk: syntax error near line 1
awk: bailing out near line 1
Comment: @GotNoSugarBaby You are using single quotes like the example right? which shell are you using? Bash gives that character a special meaning otherwise.
Comment: hey, I ran this on /bin/bash (GNU bash, version 4.0.28(1)-release (i386-pc-solaris2.11)) with a straight copy and paste of your example — but since then I've run it on /bin/bash (GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin12)) and it works, so I'll remove the down-vote. Thanks a lot estani.
Comment: @GotNoSugarBaby I use  4.2.25(1)-release (x86_64-pc-linux-gnu) nad tried on 3.x and worked. I'm not sure what issue it was... but it might have bennn a git version related issue, instead of a bash one. In any case, I'm glad it works for you!
Comment: How would I limit this command to say the 20 most recent branches? On the repo I run it on, it gives me tons of pages full of branches over the past two years (I know we probably shouldn't have so many old, un-merged branches lying around  in the repo)
Comment: Best answer for remote branches, sadly the colors are not working for me
Comment: Best answer since this supports remote branches.
Answer: As of Git 2.19 you can simply:
git branch --sort=-committerdate

You can also:
git config branch.sort -committerdate

So whenever you list branches in the current repository, it will be listed sorted by committerdate.
If whenever you list branches, you want them sorted by comitterdate:
git config --global branch.sort -committerdate

Disclaimer: I'm the author of this feature in Git, and I implemented it when I saw this question.
Comment: Most up-to-date answer, far easier than using complex scripts or aliases
Comment: @Jazimov you are right, I edited the answer so it's clearer
Comment: @theartofrain you're welcome, I also use it a lot ;)
Comment: **Use with caution!** Beware everyone, this is not a command to list the branches. It's a command to change the configuration of Git and will have permanent global repercussions.
Comment: thank you for adding this neat feature, @smaftoul, i use it a lot. ; )
Comment: Don't forget to also use `git config --global column.ui auto`. Disclaimer: I'm NOT the author of this feature, I just know it all :P
Comment: Recently seen a lot people talking about this config, probably following Scott Chacon's presentation at fosdem and this blog article https://blog.gitbutler.com/git-tips-2-new-stuff-in-git/#some-git-branch-stuff
Answer: Another variation:
git branch -r --sort=-committerdate --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always | column -ts'|'

It is worth noting that even though it's looking at changes in remote branches, it's worth synchronising with origin before running the command (you can use Git fetch), as I found it can return out of date information if your local Git folder hasn't been updated in a while.
Also, this is a version that works in Windows cmd and PowerShell:
git branch -r --sort=-committerdate --format="%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)" --color=always

Comment: Thanks for the answer for Windows Cmd/Powershell. I can confirm it also works in Cmder.
Comment: Thank you, you checked remote branches too, that is I want!
Comment: Drop the `-r` ifi you want your local branches, and not just what's been pushed/synced to your remote(s).
Answer: Getting just the top five branch names sorted based on committer date:
git branch --sort=-committerdate | head -5
Answer: The other answers don't seem to allow passing -vv to get verbose output.
So here's a one-liner that sorts git branch -vv by commit date, preserving color etc:
git branch -vv --color=always | while read; do echo -e $(git log -1 --format=%ct $(echo "_$REPLY" | awk '{print $2}' | perl -pe 's/\e\[?.*?[\@-~]//g') 2> /dev/null || git log -1 --format=%ct)"\t$REPLY"; done | sort -r | cut -f 2

If you additionally want to print the commit date, you can use this version instead:
git branch -vv --color=always | while read; do echo -e $(git log -1 --format=%ci $(echo "_$REPLY" | awk '{print $2}' | perl -pe 's/\e\[?.*?[\@-~]//g') 2> /dev/null || git log -1 --format=%ci)" $REPLY"; done | sort -r | cut -d ' ' -f -1,4-

Sample output:
2013-09-15   master                  da39a3e [origin/master: behind 7] Some patch
2013-09-11 * (detached from 3eba4b8) 3eba4b8 Some other patch
2013-09-09   my-feature              e5e6b4b [master: ahead 2, behind 25] WIP

It's probably more readable split into multiple lines:
git branch -vv --color=always | while read; do
    # The underscore is because the active branch is preceded by a '*', and
    # for awk I need the columns to line up. The perl call is to strip out
    # ansi colors; if you don't pass --color=always above you can skip this
    local branch=$(echo "_$REPLY" | awk '{print $2}' | perl -pe 's/\e\[?.*?[\@-~]//g')
    # git log fails when you pass a detached head as a branch name.
    # Hide the error and get the date of the current head.
    local branch_modified=$(git log -1 --format=%ci "$branch" 2> /dev/null || git log -1 --format=%ci)
    echo -e "$branch_modified $REPLY"
# cut strips the time and timezone columns, leaving only the date
done | sort -r | cut -d ' ' -f -1,4-

This should also work with other arguments to git branch, e.g. -vvr to list remote-tracking branches, or -vva to list both remote-tracking and local branches.
Comment: This is the best. And adding -avv makes it take into account remote branches as well. Thanks for this!
Comment: `-vv` can be useful indeed, thanks. However, this solution still spawns new processes for each branch, which the OP wanted to avoid.
Comment: Actually `git branch` doesn't specifically define the meaning of `-vv`, but only of `-v`, so `-vv` should have the same as `-v`.
Comment: @musiphil My _git branch_ manpage, section `-v, -vv, --verbose` contains the following:
`If given twice, print the name of the upstream branch, as well`
Comment: @Perleone: I don't know how I got that information, but you are right, and I stand corrected. Thanks!
Comment: this was the only one that worked for me as I am on an old verion of git (at work), added the **-r -vv** to make it work remotely, this gave a slightly different dated response to **-avv** or **-rvv**
Answer: I find the following command helpful for my purposes.
git branch --sort=-committerdate | head -n 10

This will list the latest 10 branches. It is short and can be used without an alias as well.
Comment: `git config --global alias.br "! git branch --sort=-committerdate | head -n 10"`
Answer: I like using a relative date and shortening the branch name like this:
git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads

Which gives you output:
21 minutes ago  nathan/a_recent_branch
6 hours ago     master
27 hours ago    nathan/some_other_branch
29 hours ago    branch_c
6 days ago      branch_d

I recommend making a Bash file for adding all your favorite aliases and then sharing the script out to your team. Here's an example to add just this one:
#!/bin/sh

git config --global alias.branches "!echo ' ------------------------------------------------------------' && git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads && echo ' ------------------------------------------------------------'"

Then you can just do this to get a nicely formatted and sorted local branch list:
git branches

Update: Do this if you want coloring:
#!/bin/sh
#
(echo ' ------------------------------------------------------------' && git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads && echo ' ------------------------------------------------------------') | grep --color -E "$(git rev-parse --abbrev-ref HEAD)$|$"

Comment: Fancy colored output is fancy, but this is simple and just what I was looking for. Replace `refs/heads` with `refs/remotes` to have a look at remote branches.
Comment: This gives me `fatal: unknown field name: '-authordate:iso8601'`
Comment: The command itself is lovely, but the alias throws an error: `expansion of alias 'branches' failed; 'echo' is not a git command`
Comment: Works for me. What happens if you just copy paste this into terminal? ```(echo ' ------------------------------------------------------------' && git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads && echo ' ------------------------------------------------------------') | grep --color -E "$(git rev-parse --abbrev-ref HEAD)$|$"```
Answer: Adds some color (since pretty-format isn't available)
[alias]
    branchdate = for-each-ref --sort=-committerdate refs/heads/ --format="%(authordate:short)%09%(objectname:short)%09%1B[0;33m%(refname:short)%1B[m%09"

Answer: I came up with the following command (for Git 2.13 and later):
git branch -r --sort=creatordate \
    --format "%(creatordate:relative);%(committername);%(refname:lstrip=-1)" \
    | grep -v ";HEAD$" \
    | column -s ";" -t

If you don't have column you can replace the last line with
    | sed -e "s/;/\t/g"

The output looks like
6 years ago             Tom Preston-Werner  book
4 years, 4 months ago   Parker Moore        0.12.1-release
4 years ago             Matt Rogers         1.0-branch
3 years, 11 months ago  Matt Rogers         1.2_branch
3 years, 1 month ago    Parker Moore        v1-stable
12 months ago           Ben Balter          pages-as-documents
10 months ago           Jordon Bedwell      make-jekyll-parallel
6 months ago            Pat Hawks           to_integer
5 months ago            Parker Moore        3.4-stable-backport-5920
4 months ago            Parker Moore        yajl-ruby-2-4-patch
4 weeks ago             Parker Moore        3.4-stable
3 weeks ago             Parker Moore        rouge-1-and-2
19 hours ago            jekyllbot           master

I wrote a blog post about how the various pieces work.
Comment: Nice. +1. It does use the `git branch --sort` I mentioned in https://stackoverflow.com/a/33163401/6309.
Comment: @DanNissenbaum Make sure you're using Git 2.13 (released in May 2017) or later.
Answer: Git v2.19 introduces branch.sort configuration option (see branch.sort).
So git branch will sort by committer date (descending) by default with
# gitconfig
[branch]
    sort = -committerdate     # Descending

Script:
git config --global branch.sort -committerdate

So,
git branch

Output:
* dev
  master
  _

And
git branch -v

Output:
* dev    0afecf5 Merge branch 'oc' into dev
  master 652428a Merge branch 'dev'
  _      7159cf9 Merge branch 'bashrc' into dev

Answer: I had the same problem, so I wrote a Ruby gem called Twig. It lists branches in chronological order (newest first), and can also let you set a max age so that you don't list all branches (if you have a lot of them). For example:
$ twig

                              issue  status       todo            branch
                              -----  ------       ----            ------
2013-01-26 18:00:21 (7m ago)  486    In progress  Rebase          optimize-all-the-things
2013-01-26 16:49:21 (2h ago)  268    In progress  -               whitespace-all-the-things
2013-01-23 18:35:21 (3d ago)  159    Shipped      Test in prod  * refactor-all-the-things
2013-01-22 17:12:09 (4d ago)  -      -            -               development
2013-01-20 19:45:42 (6d ago)  -      -            -               master

It also lets you store custom properties for each branch, e.g., ticket id, status, todos, and filter the list of branches according to these properties. More info: http://rondevera.github.io/twig/
Comment: That name might not help as I am pretty sure there are a few pieces of software out there with the same name.
Answer: FYI, if you'd like to get a list of recently checked out branches (as opposed to recently committed) you can use Git's reflog:
$ git reflog | egrep -io "moving from ([^[:space:]]+)" | awk '{ print $3 }' | head -n5
master
stable
master
some-cool-feature
feature/improve-everything

See also: How can I get a list of Git branches that I've recently checked out?
Answer: Here's a little script that I use to switch between recent branches:
#!/bin/bash
# sudo bash

re='^[0-9]+$'

if [[ "$1" =~ $re ]]; then
    lines="$1"
else
    lines=10
fi
branches="$(git recent | tail -n $lines | nl)"
branches_nf="$(git recent-nf | tail -n $lines | nl)"
echo "$branches"

# Prompt which server to connect to
max="$(echo "$branches" | wc -l)"
index=
while [[ ! ( "$index" =~ ^[0-9]+$ && "$index" -gt 0 && "$index" -le "$max" ) ]]; do
    echo -n "Checkout to: "
    read index
done

branch="$( echo "$branches_nf" | sed -n "${index}p" | awk '{ print $NF }' )"
git co $branch
clear

Using those two aliases:
recent = for-each-ref --sort=committerdate refs/heads/ --format=' %(color:blue) %(authorname) %(color:yellow)%(refname:short)%(color:reset)'
recent-nf = for-each-ref --sort=committerdate refs/heads/ --format=' %(authorname) %(refname:short)'

Just call that in a Git repository, and it will show you the last N branches (10 by default) and a number aside each. Input the number of the branch, and it checks out:
Comment: Please review *[Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/)* (e.g., *"Images should only be used to illustrate problems that* ***can't be made clear in any other way***, *such as to provide screenshots of a user interface."*) and take the appropriate [action](https://stackoverflow.com/posts/40876689/edit) (it covers answers as well).
Answer: Here is another script that does what all the other scripts do. In fact, it provides a function for your shell.
Its contribution is that it pulls some colours from your Git configuration (or uses defaults).
# Git Branch by Date
# Usage: gbd [ -r ]
gbd() {
    local reset_color=`tput sgr0`
    local subject_color=`tput setaf 4 ; tput bold`
    local author_color=`tput setaf 6`

    local target=refs/heads
    local branch_color=`git config --get-color color.branch.local white`

    if [ "$1" = -r ]
    then
        target=refs/remotes/origin
        branch_color=`git config --get-color color.branch.remote red`
    fi

    git for-each-ref --sort=committerdate $target --format="${branch_color}%(refname:short)${reset_color} ${subject_color}%(subject)${reset_color} ${author_color}- %(authorname) (%(committerdate:relative))${reset_color}"
}

Answer: Normally  we consider the remote branches recently.  So try this
git fetch
git for-each-ref --sort=-committerdate refs/remotes/origin

Answer: This is based on saeedgnu's version, but with the current branch shown with a star and in color, and only showing anything that is not described as "months" or "years" ago:
current_branch="$(git symbolic-ref --short -q HEAD)"
git for-each-ref --sort=committerdate refs/heads \
  --format='%(refname:short)|%(committerdate:relative)' \
  | grep -v '\(year\|month\)s\? ago' \
  | while IFS='|' read branch date
    do
      start='  '
      end=''
      if [[ $branch = $current_branch ]]; then
        start='* \e[32m'
        end='\e[0m'
      fi
      printf "$start%-30s %s$end\\n" "$branch" "$date"
    done

Answer: git for-each-ref --sort=-committerdate refs/heads/

# Or using Git branch (since version 2.7.0)
git branch --sort=-committerdate  # Descending
git branch --sort=committerdate  # Ascending

Comment: An explanation would be in order. E.g., what is the idea/gist? How does it contrast with the previous 30 answers? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/66420618/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today).
Answer: My best result as a script:
git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short)|%(committerdate:iso)|%(authorname)' |
    sed 's/refs\/heads\///g' |
    grep -v BACKUP  |
    while IFS='|' read branch date author
    do
        printf '%-15s %-30s %s\n' "$branch" "$date" "$author"
    done

Comment: What kind of script? Bash?
Answer: The accepted command-line answer rocks, but if you want something prettier, like a GUI, and your origin === "github".
You can click  "Branches" in the repository. Or hit the URL  directly: https://github.com/ORGANIZATION_NAME/REPO_NAME/branches
Answer: The simplest one to print along with the last commit date:
git branch --all  --format='%(committerdate:short) %(refname:short)'|sort

Answer: Here's the variation I was looking for:
git for-each-ref --sort=-committerdate --format='%(committerdate)%09%(refname:short)' refs/heads/ | tail -r

That tail -r reverses the list so the most-recent commiterdate is last.
Comment: You can also change --sort=-committerdate to --sort=committerdate to accomplish this.
Comment: Which `tail` has `-r`?
Answer: I know there are a lot of answers already, but here are my two cents for a simple alias (I like to have my most recent branch at the bottom):
[alias]
        br = !git branch --sort=committerdate --color=always | tail -n15
[color "branch"]
        current = yellow
        local = cyan
        remote = red

This will give you a nice overview of your latest 15 branches, in color, with your current branch highlighted (and it has an asterisk).
Answer: I didn't find exactly what I was looking so here is my version based on https://stackoverflow.com/a/66134817/1958520, which:

works under Windows (but you have to have awk installed - mine came with  MinGW, can be installed with Git, Cygwin, ....)
is not based on complex aliases to be usable as one-liner in command line / script
is colorized
uses recent git branch --sort=committerdate
output is aligned to columns

So here it is:
git branch -a --sort=committerdate --format='%(HEAD)%(color:yellow)%(refname:short)@SEP@%(color:bold green)%(committerdate:relative)@SEP@%(color:magenta)%(authorname)%(color:reset)@SEP@%(color:blue)%(subject)' --color=always | awk -F "@SEP@" '{printf("%-100s %-30s %-20s %s \n", $1, $2, $3, $4)}'

When inside cmd script it has to be modified to handle %:
git branch -a --sort=committerdate --format="%%(HEAD)%%(color:yellow)%%(refname:short)@SEP@%%(color:bold green)%%(committerdate:relative)@SEP@%%(color:magenta)%%(authorname)%%(color:reset)@SEP@%%(color:blue)%%(subject)" --color=always | awk -F "@SEP@" '{printf("%%-100s %%-30s %%-20s %%s \n", $1, $2, $3, $4)}'

Screenshot for openapi-generator github repo
Notes, howto:

use --sort=-committerdate to reverse the sort order
numbers and hyphens in awk printf spec "%-100s %-30s %-20s %s \n" are columns length and aligning specifications so this is a place for customization
@SEP@ is used as a unique separator string, which then awk uses to match data columns via -F "@SEP". Overkill but avoids accidental confusion when using some simple separator
Answer: I pipe the output from the accepted answer into dialog, to give me an interactive list:
#!/bin/bash

TMP_FILE=/tmp/selected-git-branch

eval `resize`
dialog --title "Recent Git Branches" --menu "Choose a branch" $LINES $COLUMNS $(( $LINES - 8 )) $(git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short) %(committerdate:short)') 2> $TMP_FILE

if [ $? -eq 0 ]
then
    git checkout $(< $TMP_FILE)
fi

rm -f $TMP_FILE

clear

Save as (e.g.) ~/bin/git_recent_branches.sh and chmod +x it. Then git config --global alias.rb '!git_recent_branches.sh' to give me a new git rb command.
Answer: git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))' this is that you need


Securely attaching a 4-ft 4"x4" lumber to concrete?

Question: How can I attach/bolt a 4 ft treated 4x4 to concrete so it stands up securely?
Comment: Under what circumstances? "Securely" is a relative term. We'd do better with a description of the actual project at hand.
Comment: Agreed: we'll need more info (e.g. a diagram).
Answer: If a picture is worth a thousand words
Here is a 4K word answer
Comment: Next time maybe copy image addresses and use those rather than complete screenshots. And charge your phone.
Comment: The first example wouldn't hold anything upright. It's merely to secure the base location.


Twilio TaskRouter - Retrieving caller number in Assigment Callback

Question: I'm following a tutorial on Twilio TaskRouter. I have successfully set up a workspace, workflows, activities, taskqueues and workers. Currently i am looking at this documentation at step 3:

When my twilio number recieves an inbound call, my server returns a enqueue instruction. When a worker is reserved for my newly created task, my AssignmentCallback endpoint is hit.
My question is: How to i retrieve the phone number of the caller in my callback?
Thank you in advance!
Answer: TaskRouter engineer here.
In the sections below this in the documentation referenced you should see "Attaching data to a call using Tasks". For reference, any data you plop in here will end up in the Task's attributes, which you can then inspect in your callback.
However, it's actually even easier than that, as the caller ID should already be there for you. Have a look at this documentation, which shows you the attributes that will be populated for you simply by using the <Enqueue>. In this case, I believe what you're after is from.


What could cause corrosion in a water heater?

Question: My water heater was replaced about 5 years ago.  Recently I discovered some corrosion on some of the pipes and valves connected to the heater.   Pictures are attached.  I have yet to inspect the anode rod but wondered if these pictures indicated a particular problem that required corrective actions or some maintenance tasks.  Any direction to help this situation would be appreciated.   Thanks!
Answer: The long copper pipe, is that the discharge pipe? If moisture collects at the end of it, it can become acidic and cause corrosion. You may want to test the acidity of your water, but in general discharge pipe corrosion is not too much of a concern.
The other pipes, however, seem to be suffering from galvanic corrosion which occurs when you have different metals connected to each other. Normally this is prevented by installing a plastic insert between the two metals so they do not contact each other. You may want to do this the next time the water heater is replaced.
Comment: That doesn't look like galvanic corrosion to me. Just a simple leak in the valve. Often those leaks are self healing.


How do I rewire from this old bathroom switch to new?

Question: I have never seen a switch like this before and although I have changed out many I can't seem to wrap my head around this particular one. Any help would be appreciated. My light in the bathroom will not turn off so I need to replace it. I'm going from this old one and hopefully to this Legrand 2 in 1 paddle switch.
Comment: What seems to be the exact problem?  That switch uses push in connections(quite common), and seems to control two devices(red and black wires on top).  Maybe the light and exhaust fan.
Comment: What does this switch turn on and off?
Comment: Yes it is the bathroom light and the fan
Answer: you need to find which wire is hot. Most likely the black closest to the thumb in your pic. That goes to the line screw on the new switch. ( or the screw that is alone on one side.) The other 2 wires (the red and other black) go to the screws on the opposite side of the new switch.
Comment: you are welcome. Please upvote my answer.
Comment: I think I may be a tad stupid. I don't know how to upvote.. if you tell me how I will.
Comment: click the up triangle to the left of the answer
Comment: So I did it assuming the hot wire was the one closest to the thumb in the pic but only the fan works. Could the red one be the hot wire instead?
Comment: It is possible the red is hot. Can you show a pic of the new switch with the connections present.


Laminate separating from cabinet doors

Question: I purchased a house with laminate cabinet doors, and later noticed that the laminate is not fully adhered.
It's kind of hard to tell from a picture but you can see the way it bulges out and catches the light in the top left corner.

The outer edges seem to be fine, but in the middle around where the design is it begins to separate.
I looked around but the only solutions I see are if it is peeling on the edges.
Would the whole coating need to be removed and glued or is there any easier way?
Comment: Any chance water/moisture getting into the door?
Comment: Is it just the one door?
Comment: I don't think there's any moisture getting to it.
There are a few doors doing the same thing near the stove.
Comment: Thanks all. Seems like just ignoring it may be the best way to go and hope the next buyer doesn't notice like me.
Comment: If you ever get to the point that you need to replace them all, you'll find custom door providers online that can be very reasonable, price-wise.
Comment: are you certain  that the door is not shaped like that from the factory?
Comment: When you go to sell it, you're going to reface those BS-Home-Depot-Special cabinets in IKEA crap for 2k, or take a 10k hit on the sale price. Sooner than later? Get the metal faced ones that cost a saw blade every time you do it. Those seem to last pretty good even for tenets.
Answer: If the edges are adhering well and the bulge is only near the center, there is not a way to repair the door. ( Other than removing the laminate and reglueing a new panel.)
The idea of removing the old laminate and re attaching it is about impossible.
Having a piece of matching laminate that is larger than the door, so it can be trimmed is probably not likely. Additionally you probably don't have a router with a laminate trimming bit or a laminate trimmer.
The only reasonable way to correct your issue is to have a new door made. Try taking the door off and taking it to a custom cabinet maker.  They make doors like that every day.  You may have to buy a whole sheet of laminate ( 4' x8')
However the cost is much more reasonable than new cabinets.
Answer: If it's not swelling from moisture, and there's a "bubble" between the laminate surface and the core material, you can (roughly in order of difficulty):

learn to ignore it.

replace the whole door.

Find someone with a vacuum-bag press and see if glue could be injected, and then have the thing placed in the vacuum bag to suck the surface flat until the glue cures. I believe this type of thing is typically made by a similar method, though it may involve some difficult to arrange outside of a factory "vacuum and heat" process.

As above, but use a board the size of the middle of the door to press it with weights. If it's ONLY the middle that's peeling, that might work. Or it might encourage the "molding" sections around it to start peeling.

Attempt to remove and replace the surface, as you mention. I have doubts about this producing a result that looks better than learning to ignore it, to be honest. It's not a DIY-friendly "finish."

If it's solid in the middle and has gotten wet at some point, causing the inside MDF to swell:

replace the whole door.

Laminate separating from cabinet doors


Duplicate info.plist files when using pods

Question: I'm using my own Pods, and I've got 4 that work in my current project.
However, when I do a pod install of the 4, each one has its own info.plist so predictably I get an error of duplicated files.

I can remove the reference to each info.plist from my development pods but I have to repeat this process after each pod install.
I understand I can legacy build (not an ideal solution), and the plist files can be played around with in the build settings (which does not seem to work in this case). The easiest and best way therefore seems the manual deletion.
What is the correct way to approach this problem which means I don't have to manually remove the plist files each time.
PodSpec file:
<code>#
#  Be sure to run `pod spec lint GameManager.podspec' to ensure this is a
#  valid spec and to remove all comments including this before submitting the spec.
#
#  To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
#  To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#

Pod::Spec.new do |s|

  # ―――  Spec Metadata  ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  These will help people to find your library, and whilst it
  #  can feel like a chore to fill in it's definitely to your advantage. The
  #  summary should be tweet-length, and the description more in depth.
  #

  s.name         = "GameManager"
  s.version      = "0.0.1"
  s.summary      = "A short description of GameManager."

  # This description is used to generate tags and improve search results.
  #   * Think: What does it do? Why did you write it? What is the focus?
  #   * Try to keep it short, snappy and to the point.
  #   * Write the description between the DESC delimiters below.
  #   * Finally, don't worry about the indent, CocoaPods strips it!
  s.description  = <<-DESC
    A tested, reusable FameManager

                   DESC

  s.homepage     = "http://www.test.com/GameManager"
  # s.screenshots  = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"

  # ―――  Spec License  ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Licensing your code is important. See http://choosealicense.com for more info.
  #  CocoaPods will detect a license file if there is a named LICENSE*
  #  Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
  #

  # s.license      = "MIT (example)"
  s.license      = { :type => "MIT", :file => "FILE_LICENSE" }

  # ――― Author Metadata  ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Specify the authors of the library, with email addresses. Email addresses
  #  of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
  #  accepts just a name if you'd rather not provide an email address.
  #
  #  Specify a social_media_url where others can refer to, for example a twitter
  #  profile URL.
  #

  s.author             = { "Steven Curtis" => "firstname.lastname@example.com" }
  # Or just: s.author    = "Steven Curtis"
  # s.authors            = { "Steven Curtis" => "email@example.com" }
  # s.social_media_url   = "http://twitter.com/Steven Curtis"

  # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  If this Pod runs only on iOS or OS X, then specify the platform and
  #  the deployment target. You can optionally include the target after the platform.
  #

  # s.platform     = :ios
  # s.platform     = :ios, "5.0"

  #  When using multiple platforms
  # s.ios.deployment_target = "5.0"
  # s.osx.deployment_target = "10.7"
  # s.watchos.deployment_target = "2.0"
  # s.tvos.deployment_target = "9.0"

  # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Specify the location from where the source should be retrieved.
  #  Supports git, hg, bzr, svn and HTTP.
  #

 #  s.source       = { :git => "http://EXAMPLE/GameManager.git", :tag => "#{s.version}" }
 s.source = { :git => "/Users/stevencurtis/Documents/CommercialApps/Frameworks/GameManager", :tag => "#{s.version}" }

  # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  CocoaPods is smart about how it includes source code. For source files
  #  giving a folder will include any swift, h, m, mm, c & cpp files.
  #  For header files it will include any header in the folder.
  #  Not including the public_header_files will make all headers public.
  #

 s.source_files  = "Classes", "GameManager/**/*.*"
  s.exclude_files = "Classes/Exclude"

  # s.public_header_files = "Classes/**/*.h"

  # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  A list of resources included with the Pod. These are copied into the
  #  target bundle with a build phase script. Anything else will be cleaned.
  #  You can preserve files from being cleaned, please don't preserve
  #  non-essential files like tests, examples and documentation.
  #

  # s.resource  = "icon.png"
  # s.resources = "Resources/*.png"

  # s.preserve_paths = "FilesToSave", "MoreFilesToSave"

  # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Link your library with frameworks, or libraries. Libraries do not include
  #  the lib prefix of their name.
  #

  # s.framework  = "SomeFramework"
  # s.frameworks = "SomeFramework", "AnotherFramework"

  # s.library   = "iconv"
  # s.libraries = "iconv", "xml2"

  # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  If your library depends on compiler flags you can set them in the xcconfig hash
  #  where they will only apply to your library. If you depend on other Podspecs
  #  you can include multiple dependencies to ensure it works.

  # s.requires_arc = true

  # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
  # s.dependency "JSONKit", "~> 1.4"

end
</code>
Podfile
<code># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'ExampleQuizAndGame' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for ExampleQuizAndGame

    pod 'HTTPManager', :path => '/Users/stevencurtis/Documents/CommercialApps/Frameworks/HTTPManager'
    pod 'DataManager', :path => '/Users/stevencurtis/Documents/CommercialApps/Frameworks/DataManager'
    pod 'GameManager', :path => '/Users/stevencurtis/Documents/CommercialApps/Frameworks/GameManager'
    pod 'QuizManager', :path => '/Users/stevencurtis/Documents/CommercialApps/Frameworks/QuizManager'

  target 'ExampleQuizAndGameTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'ExampleQuizAndGameUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end
</code>
Comment: take a look at https://stackoverflow.com/a/50719379/5464805. It may help.
Comment: I don't believe setting to legacy build settings (which works) is the correct approach. I already have a poor solution to this, I'm looking for a good one.
Comment: Maybe you can show how are you creating your own pods, can you show the Podspec file?
Comment: Thanks for the podspec, I think everything looks ok, maybe you can also share the `podfile` you are using on your current project?
Comment: @WishIHadThreeGuns I am not talking about the legacy build setting, this is never a solution. The solution I linked is about bundle resources that are copied from pods.
Comment: Which also doesn't work, as the plist files are not listed there
Answer: In your pod repo, move the Info.plist up from your source code directory and into the project directory. Also, remove it from your project source files. As long as the project has the path to the Info.plist, it doesn't need to be a project source file.
That worked for me.


Adding multiple items to a listview with each item received from another intent on a button click

Question: I'm creating a birthday reminder application, where the app starts on the main activity, goes to a new activity using  intent and there the person selects the birthday, and the selected birth day, month and year is returned back to  the main activity.
Then in the main activity I've created a new button which retrieves all the information sent by the bday picker activity and tries to display it in a list activity every time I press a button.
The problem I'm facing is if once I run the app, the birthday gets recorded and is shown in the listview, but if I add another Birthday and try to display it in the listview,the previous record is removed and I'm left with only the present record.
What I exactly want to know is how can I add items in my listView so that all my previous birthdays are shown as well.
The code File Provided is as Follows:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="#97B252D5">

        <TextView
            android:id="@+id/editText"
            android:layout_width="213dp"
            android:layout_height="52dp"
            android:ems="10"
            android:fontFamily="sans-serif-black"
            android:text="Remindro"
            android:textAllCaps="true"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:textSize="36sp"
            android:textStyle="bold|italic"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.067"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/newEntry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#C1E6E60F"
            android:fontFamily="sans-serif-black"
            android:onClick="addNewEntry"
            android:text="+ADD"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:textSize="30sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.88"
            app:layout_constraintStart_toEndOf="@+id/editText"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.48" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="9"
        android:background="#A071D4ED">

        <ListView
            android:id="@+id/list"
            android:layout_width="410dp"
            android:layout_height="596dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/viewRecord"
            app:layout_constraintVertical_bias="0.0" />

        <Button
            android:id="@+id/viewRecord"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="#9650EC31"
            android:onClick="viewRecord"
            android:text="View Record"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:textStyle="bold"
            app:layout_constraintBottom_toTopOf="@+id/_dynamic"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.0" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>

Code file for : MainActivity.java
package com.example.remindro;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";

    ArrayList<String> listItems = new ArrayList<String>();

    ArrayAdapter<String> adapter;

    Calendar calendar = Calendar.getInstance();
    int thisYear = calendar.get(Calendar.YEAR);
    int thisMonth = calendar.get(Calendar.MONTH) + 1;
    int thisDay = calendar.get(Calendar.DAY_OF_MONTH);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter=new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                listItems);
        ListView records = (ListView) findViewById(R.id.list);
        records.setAdapter(adapter);
    }

    public void addNewEntry(View v)
    {
        Intent adding = new Intent();
        adding.setClass(this,addinglist.class);
        startActivity(adding);
        finish();

    }
    public void viewRecord(View v)
    {
        Intent receiver = getIntent();
        int day = receiver.getIntExtra("day",0);
        int month = receiver.getIntExtra("month",0);
        int year = receiver.getIntExtra("year",0);
        String name = receiver.getStringExtra("nameofperson");
        String choice = receiver.getStringExtra("radio");
        String mss = name + " has his " + choice + " on " + day + "/" + month + "/" + year;
        //Toast.makeText(getApplicationContext(),mss,Toast.LENGTH_LONG).show();

        int age = thisYear - year;
        calendar.set(thisYear,thisMonth,thisDay);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(thisYear,month,day);

        long milliseconds1 = calendar.getTimeInMillis();
        long milliseconds2 = calendar1.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        int noOfDays = (int) (diff / (24 * 60 * 60 * 1000));
        String msg2 = "Turning " + age + " in " + noOfDays + "days!!";
//        Toast.makeText(getApplicationContext(),msg2,Toast.LENGTH_LONG).show();

        String finalMsg = mss + " " + msg2;
        listItems.add(finalMsg);
        adapter.notifyDataSetChanged();
    }
}

activity_addinglist.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#8AEC9F18"
    tools:context=".addinglist">

    <NumberPicker
        android:id="@+id/day"
        android:layout_width="97dp"
        android:layout_height="131dp"
        android:background="#B5EA1241"
        android:scaleX="1.3"
        android:scaleY="1.3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.298">

    </NumberPicker>

    <NumberPicker
        android:id="@+id/month"
        android:layout_width="97dp"
        android:layout_height="131dp"
        android:layout_marginStart="60dp"
        android:layout_marginLeft="60dp"
        android:background="#B5EA1241"
        android:scaleX="1.3"
        android:scaleY="1.3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/day"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.298">

    </NumberPicker>

    <NumberPicker
        android:id="@+id/year"
        android:layout_width="97dp"
        android:layout_height="131dp"
        android:layout_marginStart="56dp"
        android:layout_marginLeft="56dp"
        android:background="#B5EA1241"
        android:scaleX="1.3"
        android:scaleY="1.3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/month"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.298">

    </NumberPicker>

    <Button
        android:id="@+id/submit"
        android:layout_width="121dp"
        android:layout_height="59dp"
        android:layout_marginBottom="156dp"
        android:background="#9A7CEF46"
        android:onClick="addingEvent"
        android:text="ADD Event"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <RadioGroup
        android:id="@+id/typer"
        android:layout_width="384dp"
        android:layout_height="88dp"
        app:layout_constraintBottom_toTopOf="@+id/submit"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.407"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/month"
        app:layout_constraintVertical_bias="0.666">

        <RadioButton
            android:id="@+id/birthday"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Birthday"
            android:textAppearance="@style/TextAppearance.AppCompat.Large" />

        <RadioButton
            android:id="@+id/anniversary"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Anniversary"
            android:textAppearance="@style/TextAppearance.AppCompat.Large" />
    </RadioGroup>

    <EditText
        android:id="@+id/name"
        android:layout_width="413dp"
        android:layout_height="53dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:hint="Enter the Name of the Person"
        app:layout_constraintBottom_toTopOf="@+id/month"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.045"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.475" />

    <EditText
        android:id="@+id/resultshower"
        android:layout_width="412dp"
        android:layout_height="95dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.045"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/submit"
        app:layout_constraintVertical_bias="0.518" />

</androidx.constraintlayout.widget.ConstraintLayout>

and addinglist.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;

public class addinglist extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addinglist);
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        day.setMinValue(1);
        day.setMaxValue(31);
        month.setMinValue(1);
        month.setMaxValue(12);
        year.setMinValue(1950);
        year.setMaxValue(2020);
    }

    public void addingEvent(View v)
    {
        String name;
        EditText nameEntered = (EditText) findViewById(R.id.name);
        name = nameEntered.getText().toString();
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        int day1 = day.getValue();
        int month1 = month.getValue();
        int year1 = year.getValue();
        RadioGroup typer = (RadioGroup) findViewById(R.id.typer);
        int selectedId = typer.getCheckedRadioButtonId();
        RadioButton checked = (RadioButton) findViewById(selectedId);
        String typee = checked.getText().toString();
        EditText resultbox = (EditText) findViewById(R.id.resultshower);
        String Finalmsg = name + " has his " + typee + " on " + day1 + "/" + month1 + "/" + year1;
        resultbox.setText(Finalmsg);
        Intent newintent = new Intent();
        newintent.putExtra("nameofperson",name);
        newintent.putExtra("day",day1);
        newintent.putExtra("month",month1);
        newintent.putExtra("year",year1);
        newintent.putExtra("radio",typee);
        newintent.setClass(this,MainActivity.class);
        startActivity(newintent);
    }
}

Thanks in advance for taking out time to solve this query.
Answer: To get a result from an activity you should use startActivityForResult() and onActivityResult() APIs instead of startActivity().
You can learn it from this simple example given by tutorialspoint : https://www.tutorialspoint.com/how-to-manage-startactivityforresult-on-android
But latest Android developer documentation recommends us to use new Activity Result APIs for this.
To learn, you can refer to the Google's documentation : https://developer.android.com/training/basics/intents/result
And this write up by Wajahat Karim : https://wajahatkarim.com/2020/05/activity-results-api-onactivityresult/
I'm trying to give you an answer using this new Activity Result API.
First, you must add AndroidX Activity and Fragment libraries as dependencies.
app/build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.lakindu.birthdayreminder"
        minSdkVersion 14
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // Reference 1 : https://developer.android.com/training/basics/intents/result
    // Reference 2 : https://wajahatkarim.com/2020/05/activity-results-api-onactivityresult/
    implementation 'androidx.activity:activity:1.2.0-alpha04'
    implementation 'androidx.fragment:fragment:1.3.0-alpha04'
}

I'm going to send a Parcelable object from the addinglist activity to the MainActivity as the result.
This is the implementation of that Parcelable Event class.
Event.java
import android.os.Parcel;
import android.os.Parcelable;

public class Event implements Parcelable {

    // Name of the person
    private String nameOfPerson;

    // Day of month
    // byte (8 bit) as the type, because day can only have a value from 1 to 31
    private byte day;

    // Month of year
    // byte (8 bit) as the type, because month can only have a value from 1 to 12
    private byte month;

    // Year
    // Short (16 bit) as the type, because year can only have a realistic A.D. year
    private short year;

    // Type of event
    private String eventType;

    // Constructor (auto-generated using Android Studio)
    public Event(String nameOfPerson, byte day, byte month, short year, String eventType) {
        this.nameOfPerson = nameOfPerson;
        this.day = day;
        this.month = month;
        this.year = year;
        this.eventType = eventType;
    }

    // Getters for each private member field (auto-generated using Android Studio)

    public String getNameOfPerson() {
        return nameOfPerson;
    }

    public byte getDay() {
        return day;
    }

    public byte getMonth() {
        return month;
    }

    public short getYear() {
        return year;
    }

    public String getEventType() {
        return eventType;
    }

    // Parcelable implementation (auto-generated using Android Studio)

    protected Event(Parcel in) {
        nameOfPerson = in.readString();
        day = in.readByte();
        month = in.readByte();
        year = (short) in.readInt();
        eventType = in.readString();
    }

    public static final Creator<Event> CREATOR = new Creator<Event>() {
        @Override
        public Event createFromParcel(Parcel in) {
            return new Event(in);
        }

        @Override
        public Event[] newArray(int size) {
            return new Event[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(nameOfPerson);
        dest.writeByte(day);
        dest.writeByte(month);
        dest.writeInt((int) year);
        dest.writeString(eventType);
    }
}

Then we have to create a class to encapsulate inputs given to addinglist activity from MainActivity (in this example there's none), and outputs returned from addinglist activity to MainActivity (Event Parcelable object).
This class is an ActivityResultContract, which is like a contract we give to the Android system to open a specific Activity, and get a result from it for us.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class GetEvent extends ActivityResultContract<Void, Event> {

    @NonNull
    @Override
    public Intent createIntent(@NonNull Context context, Void input) {

        // Create Intent that should be used to start addinglist activity for result
        Intent intent = new Intent(context, addinglist.class);

        // If you need to send any inputs to addinglist activity,
        // you can put them in intent as extras.
        // Eg: intent.putExtra("input", input)
        // But for now we don't have to send any inputs to addinglist activity.

        return intent;
    }

    @Override
    public Event parseResult(int resultCode, @Nullable Intent intent) {

        // Action is cancelled? Return null
        if(Activity.RESULT_OK != resultCode) return null;

        // No intent to get output? Return null
        if(null == intent) return null;

        // Successfully got result from addinglist activity
        return intent.getExtras().getParcelable("output");
    }
}

Here is how we launch the addinglist activity from MainActivity and get the result.
MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;

import java.util.ArrayList;
import java.util.Calendar;

public class MainActivity extends ComponentActivity {

    private static final String TAG = "";

    ArrayList<String> listItems = new ArrayList<String>();

    ArrayAdapter<String> adapter;

    Calendar calendar = Calendar.getInstance();
    int thisYear = calendar.get(Calendar.YEAR);
    int thisMonth = calendar.get(Calendar.MONTH) + 1;
    int thisDay = calendar.get(Calendar.DAY_OF_MONTH);

    // Holds the latest event received from addinglist activity
    private Event mLatestEvent = null;

    // Register a callback to be called on an event received from addinglist activity
    private ActivityResultLauncher<Void> mGetEvent = registerForActivityResult(
            // Instance that encapsulates input and output when starting addinglist activity for result
            new GetEvent(),

            // Callback to be called when event is received
            new ActivityResultCallback<Event>() {
                @Override
                public void onActivityResult(Event result) {
                    // Save as latest event received
                    mLatestEvent = result;
                }
            }
    );

    private static final Void NO_INPUT = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter=new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                listItems);
        ListView records = (ListView) findViewById(R.id.list);
        records.setAdapter(adapter);
    }

    public void addNewEntry(View v)
    {
        // Launch addinglist activity to get an event
        mGetEvent.launch(NO_INPUT);
    }
    public void viewRecord(View v)
    {
        // No latest event? Then nothing to add to list, just return.
        if(null == mLatestEvent) return;

        // Prepare string that is being added to the list.
        // Using a StringBuilder as there are multiple number of immutable strings to be appended.
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(mLatestEvent.getNameOfPerson())
                .append(" has his ")
                .append(mLatestEvent.getEventType())
                .append(" on ")
                .append(mLatestEvent.getDay())
                .append("/")
                .append(mLatestEvent.getMonth())
                .append("/")
                .append(mLatestEvent.getYear());

        String mss = stringBuilder.toString();
        //Toast.makeText(getApplicationContext(),mss,Toast.LENGTH_LONG).show();

        int age = thisYear - mLatestEvent.getYear();
        calendar.set(thisYear,thisMonth,thisDay);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(thisYear, mLatestEvent.getMonth(), mLatestEvent.getDay());

        long milliseconds1 = calendar.getTimeInMillis();
        long milliseconds2 = calendar1.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        int noOfDays = (int) (diff / (24 * 60 * 60 * 1000));
        String msg2 = "Turning " + age + " in " + noOfDays + "days!!";
//        Toast.makeText(getApplicationContext(),msg2,Toast.LENGTH_LONG).show();

        String finalMsg = mss + " " + msg2;
        listItems.add(finalMsg);
        adapter.notifyDataSetChanged();
    }
}

Note that MainActivity is a ComponentActivity now. Not a AppCompatActivity.
Here is how to send the result from addinglist activity to MainActivity.
addinglist.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;

public class addinglist extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addinglist);
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        day.setMinValue(1);
        day.setMaxValue(31);
        month.setMinValue(1);
        month.setMaxValue(12);
        year.setMinValue(1950);
        year.setMaxValue(2020);
    }

    public void addingEvent(View v)
    {
        String name;
        EditText nameEntered = (EditText) findViewById(R.id.name);
        name = nameEntered.getText().toString();
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        byte day1 = (byte) day.getValue();
        byte month1 = (byte) month.getValue();
        short year1 = (short) year.getValue();
        RadioGroup typer = (RadioGroup) findViewById(R.id.typer);
        int selectedId = typer.getCheckedRadioButtonId();
        RadioButton checked = (RadioButton) findViewById(selectedId);
        String typee = checked.getText().toString();
        EditText resultbox = (EditText) findViewById(R.id.resultshower);
        String Finalmsg = name + " has his " + typee + " on " + day1 + "/" + month1 + "/" + year1;
        resultbox.setText(Finalmsg);

        // Prepare the result to output
        Intent newintent = new Intent();
        newintent.putExtra(
                "output",
                new Event(name, day1, month1, year1, typee)
        );

        // Set the result
        setResult(Activity.RESULT_OK, newintent);

        // Finish the addinglist activity.
        // Then result will be sent to the MainActivity.
        finish();
    }
}

Here is the working app.
Comment: **Code explanation part 1** -

When '+ADD' button is pressed, `addNewEntry(View)` is being called, and MainActivity initiates call to launch the addinglist activity to get Event result.

But MainActivity does not get destroyed. It just goes to background, and addinglist activity appears on top of it to get inputs from user.

After user setting inputs and pressed 'ADD Event' button, addinglist activity creates the Event, set it as the result, and closes itself.
Comment: **Code explanation part 2** -

When MainActivity received the Event through the registered callback, it is being saved to `Event mLatestEvent` member field in MainActivity.

When `viewRecord(View)` method is called upon 'View Record' button press, it takes the `mLatestEvent`, prepare a string using the event, and adds it to the listview.

**We will see all previously added strings in listview as long as MainActivity doesn't get destroyed.**

If it gets destroyed somehow (may be by the Android system in low memory situation), you will loose all your data in listview.
Comment: So as much as I understand, the transferring of the data between classes would  be taking place in form of custom object created in form of the parcelable object. The ActivityResultsContract is like the  medium of taking the input from main to addinglist and providing the output from addinglist to main. But what I still don't get is how you are adding the multiple results on the listview, the object at a time would have only one data! and where and how the multiple data entries would have been stored because they need to be stored in order to display in listview.
Comment: Thank You for your Patience and please correct me if I have got something wrong up there.
Comment: So once you receive an Event, you should persist it in a database.

Read about `Room` database to save data to a database, and `LiveData` to update your listview with the saved data in database.


PS4 buttons do not work in-game?

Question: I bought a PS4 that I have never had any problems with until now.
I was just playing God of War. I used the PS button to go back to the Home menu and wanted to change some settings. As a result, I suddenly found that all the buttons except the PS button failed on the Home menu.
I pressed the power button to put it in standby mode and restart. After restarting all the keys were normal in the home menu, but any game using the gamepad did not work, as only the PS key has a reaction.
Is there a way to fix this?
Answer: This is a tricky one, mainly because from what you describe it seems like one of the buttons on your controller is stuck and it's overriding the rest.
But before addressing that, you can try a few things first:

Completely turn off your console (not rest mode), wait a few minutes and turn it back on.
Reset the controller by sticking an unfolded paper clip in the small hole on the back of the controller. You can check Step 3 on DS4 troubleshooting guide
Launch a game, when in-game, turn off the controller (hold middle button > Adjust devices > turn off controller) and then turn it back on.

If the above don't work, there's a good chance that a button is stuck on the controller and is blocking the rest of the buttons to work properly.
You can check this by connecting the DS4 controller to a computer the USB cable, the drivers should be installed easily on their own and then check the controller's properties. Windows have a screen which shows which buttons are pressed. If you have a button stuck it should show up as pressed all the time.
If you can confirm that the button is stuck, then you need to clean it.
On a Reddit thread I was reading, someone said that they smacked the controller against their thigh a couple of times and the controller worked fine afterwards. For the record, I don't take any responsibility if you break your controller.
There are several ways to clean it, like compressed air or taking it apart completely. You can check this Reddit post about dealing with a stuck button.
Comment: I personally experienced this rather recently myself, and all the above help. The only thing though is that resetting the controller was only temporary (turning off/on the controller had the same results). For me, I ended up taking the controller apart and discovered one of the internal components was loose. After putting it back in-place, the controller functioned properly
Comment: @Wondercricket I'm afraid that's probably inevitable. It sounds like a hardware failure.
Answer: Best way to deal with this is:

Open any game in which the controller is not working
Press the PS button whilst being on the game screen
Go to device setting tile
Turn off the controller
Turn the controller back on
Do all the above steps after opening the game and not on the home screen.

This should solve it, certainly did for me.
Answer: Sounds like It's a sticky button issue, happens often on my controller cause I have stickers on it. Like shake it and slide your palm over the input buttons to loosen them up, not too rough though but a little firm to dislodge any crud that might be causing the button to be stuck. Do I while in an app and you should see something move eventually on the screen and then you'll know it's working again
Answer: I just bought a new PS4 controller and had the same issue.  I don't have the knowledge or tools to clean it so I was just going to bring it back.  I figured I'd try "smacking it on my thigh" and sure enough it worked!
Lol I'm so happy!

PS4 buttons do not work in-game?


Chrome 61: Unexpected token import

Question: Running Chrome 61 which is supposed to support module loading with import.
Indeed Paul's demo works for me. However, when I try it myself I get a JS error "Unexpected token import". Chrome seems to balk at import:
test.html
<!doctype html>

test.js:
import {hello} from './something.js'
console.log(hello())

something.js
export {hello}
function hello() {
    return "hello world"
}

Why does Chrome not understand "import"
Answer: That should be

So as you can see just add the type "module" to your script tag, then below you do the import.  For my test the CalcArea.js file is this:
const circleArea = r => 3.14 * (r ** 2);

const squareArea = s => s * s;

export {circleArea, squareArea};

Comment: I agree, you need to enable the `import.meta.url` flag in Chrome *AND* add `type="module"` to your `
Answer: Finally... figured it out.  chrome://flags search for import enable ES6 import syntax. Restart Chrome.  Be happy.
Comment: ...after going through and renaming all my `.js` files to `.mjs` because I thought the error went away after trying it, but apparently it was just processing.  Now I need to decide whether to name them all back or stick with `.mjs`

Chrome 61: Unexpected token import