The Running Time For Arrays.Sort Method in Java

Question: Does anyone know the running time in big O notation for the arrays.sort java method? I need this for my science fair project.
Answer: From official docs
I've observed that there are primarily two approaches. So, it depends on what you are sorting and what overloaded method from sort family of methods you are calling.
Docs mention that for primitive types such as long, byte (Ex: static void sort(long[])):

The sorting algorithm is a tuned quicksort, adapted from Jon L.
  Bentley and M. Douglas McIlroy's "Engineering a Sort Function",
  Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November
  1993). This algorithm offers n*log(n) performance on many data sets
  that cause other quicksorts to degrade to quadratic performance.

For Object types: (Ex: void sort(Object list[]))
Guaranteed O(nlogn) performance

The sorting algorithm is a modified mergesort (in which the merge is
  omitted if the highest element in the low sublist is less than the
  lowest element in the high sublist). This algorithm offers guaranteed
  n*log(n) performance.

Hope that helps!
Comment: I also see `The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance.` Seems like the algorithm depends on what you are sorting...
Comment: @csmckelvey Yes it is called `Tim sort`
Answer: Arrays.sort() uses Tim sort - O(N log N)  for array of objects and QuickSort for arrays of primitives - again O(N log N).
Here is an awesome comparison of sorting algorithms: http://www.sorting-algorithms.com/
Answer: I have tested the time complexity of Arrays.sort() in the various datasets. In the worst case, it is O(n^2) time complexity.
Trying doing this question using Arrays.sort() and then using Collections.sort(). You will see the difference. Question link
when I used Arrays.sort() it took more than 2 sec.
and when I  used collections.sort() it took 0.2sec
Collections.sort() uses modified mergesort and Arrays.sort() uses QuickSort(). Below code is the best way to sort in java if you are using Array. In case of list you can use Collections.sort() by default.
static void sort(long[] a) {
    ArrayList<Long> l=new ArrayList<>();
    for (long i:a) l.add(i);
    Collections.sort(l);
    for (int i=0; i<a.length; i++) a[i]=l.get(i);
}

Answer: It depends on what you are sorting and on your Java version. Sort methods for arrays of different types have different time and space complexities. There are also improvements in the latter Java versions.
Arrays.sort(int[])
As well as Arrays.sort(long[]), Arrays.sort(float[]) and Arrays.sort(double[])
Time complexity
Time complexity of Arrays.sort(int[]) depends on the version of Java.
Prior to Java 14
A pretty ordinary quicksort was used with time complexity ranging from O(n) (when the array is already sorted and we are only checking that it is) to O(n2) for certain inputs that cause extremely uneven distribution of elements into parts with an average complexity of O(n log(n)). You can find a detailed analysis here.
From Java 14 to Java 19
In Java 14 the implementation was improved to guarantee the worst-case time complexity of O(n log(n)). The function was changed to resort to heapsort if recursion becomes too deep:
if ((bits += DELTA) > MAX_RECURSION_DEPTH) {
  heapSort(a, low, high);
  return;
}

which prevents the method from degrading to quadratic time complexity.
Glimpse into the future
There is an initiative to switch to radix sort for almost random big enough arrays thus reducing the time complexity to O(n) in the worst-case.
Space complexity
In all versions, the algorithm has space complexity ranging from O(1) (when the array is already sorted and we only to check that it is) to O(n) (when the array is highly structured (there is a small number of sorted subarrays inside the original array and we merge those subarrays)).
Here's where allocation happens in the worst case:
/*
 * Merge runs of highly structured array.
 */
if (count > 1) {
  int[] b; int offset = low;

  if (sorter == null || (b = (int[]) sorter.b) == null) {
    b = new int[size];
  } else {
    offset = sorter.offset;
  }
  mergeRuns(a, b, offset, 1, sorter != null, run, 0, count);
}
return true;

DualPivotQuicksort.java
While the question asks specifically about Arrays.sort(int[]) method I still decided to include answers for other data types since this is the first result when you look for Arrays.sort() time and space complexity in Google and it is not easy to find correct answers to this simple question in other places.
Arrays.sort(short[])
As well as Arrays.sort(char[]) and Arrays.sort(byte[])
Time and space complexity
Although the documentation says:

The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on all data sets, and is typically faster than traditional (one-pivot) Quicksort implementations.

This is not true at least starting from Java 7. Actually, an in-place counting sort used for big enough arrays, which has linear time complexity and constant space complexity:
private static void countingSort(short[] a, int low, int high) {
    int[] count = new int[NUM_SHORT_VALUES];

    /*
     * Compute a histogram with the number of each values.
     */
    for (int i = high; i > low; ++count[a[--i] & 0xFFFF]);

    /*
     * Place values on their final positions.
     */
    if (high - low > NUM_SHORT_VALUES) {
        for (int i = MAX_SHORT_INDEX; --i > Short.MAX_VALUE; ) {
            int value = i & 0xFFFF;

            for (low = high - count[value]; high > low;
                a[--high] = (short) value
            );
        }
    } else {
        for (int i = MAX_SHORT_INDEX; high > low; ) {
            while (count[--i & 0xFFFF] == 0);

            int value = i & 0xFFFF;
            int c = count[value];

            do {
                a[--high] = (short) value;
            } while (--c > 0);
        }
    }
}

Counting sort implementation
Arrays.sort(Object[])
Unlike other methods, this one is well-documented and the documentation here corresponds to reality.
Time complexity
O(n log(n))
Starting from Java 7

This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(java.lang.Object[])
Before Java 7

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance.

https://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(java.lang.Object[])
Space complexity
O(n)
Starting from Java 7

Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(java.lang.Object[])
Before Java 7

The algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort to sort object references is a "modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist)." It is a reasonably fast stable sort that guarantees O(n log n) performance and requires O(n) extra space.

https://bugs.openjdk.org/browse/JDK-6804124


Origin of "as useful as a chocolate teapot / fireguard"

Question: I ran across the expression "as useful as a chocolate teapot" (or sometimes a fireguard) which is apparently used to denote the utter uselessness of something. It received some coverage on Language Log back in 2004. Where/how did the expression originate?
Answer: Eric Partridge and Paul Beale's Dictionary of Slang and Unconventional English (8th edition, 1984, s.v. much use as) gives an example of "chocolate teapot" from the Guardian, January 1979.
I haven't found any earlier examples, and don't know where it came about; though there are a few references to it on lists of Irish slang, I don't personally associate it with Irish English. The logic is presumably that if you used a chocolate teapot then it would melt, though research shows that this is not always true!
Comment: I wouldn't particularly associate it with Irish use, either. About the only one of the very many "useless as a ..." joking similes like this that I'd consider likely to be particularly Irish is the less surreal "useless as tits on a bull". Still, there's no reason that that needn't have arisen elsewhere, and no reason why the chocolate teapot need not indeed be Irish; either assertion would need some demonstrating.
Comment: Thank you. A less successful experiment [can be found here](http://www.plokta.com/plokta/issue23/teapot.htm) :)
Answer: The expression was used in The Guardian of 17th July 1978 in an article titled "Barnsley bashers face the chop", written by Michael Parkin:

Tourists that go to home games of Barnsley Town will hear some of the finest football wit and repartee in the land. Players are accused of being "as nimble as a stone trough" or "as much use as a chocolate teapot."

The phrase is repeated in The Guardian of 13th February 1980 in "Barnsley go down and the fans love it", again by Parkin:

What the visit will do for the public relations on the terraces at the Oakwell ground has yet to be seen. Barnsley's supporters are notoriously critical and much given to witty judgments.
A visit down the pit will not save a dawdling player form the kind of remark in which the Oakwell crowd specialises: "That's as much use as a chocolate teapot."

A 1981 Google Books snippet also points to the terraces as origin for this ironic simile. Desmond Morris's The Soccer Tribe (1981) describes 'The Jokers':

If the referee gives the opponents a penalty, he yells, 'When they circumcised you they threw away the wrong part.' If a player is not trying hard enough, he bellows, 'You are as much use as a chocolate teapot.'

Wikipedia confirms the date and says:

In 1978 Desmond was elected Vice-Chairman of the Oxford United Football Club. Interesting to note, later in 1981 Morris publishes 'The Soccer Tribe,' analysis regarding the world of professional football, or rather soccer, to Canadians and Americans.
Answer: 'Michael Parkin' as referred to in Hugo's answer is the British journalist, author and chat show host Michael Parkinson. 'Chocolate teapot' features in his book Football Daft, published 1968.
In that book, Parkinson, famously from the Yorkshire town of Barnsley, describes Tottenham Hotspur coming to play Barnsley FC at the latter's Oakwell ground, a game at which Spurs and England fullback Alf Ramsey was tormented by a tricky winger playing for Barnsley. Parkinson says that a wag in the crowd at one point shouted "Ramsey th'art about as much use as a chocolate teapot!" and further posits (for comedic value) that this incident was the root cause of Ramsey's later aversion to wingers, as seen by his team of 'wingless wonders' that won the World Cup for England in 1966. The fact that he used the phrase later in other contexts suggests to me that it was of his own invention.
Answer: I found this in a Google Books snippet (so no further context) from The Accountant for 1981:

... is managing director of a hardware firm, singing IF's praises — in the hope, no doubt, that others in the profession will see the advantages and not consider, as does the Cleese-consultant, that 'it is about as much use as a chocolate teapot'.

This suggests that the phrase may come from one of the many humorous business training videos which Cleese's company Video Arts produced in the 1970s.
Answer: A Hathi Trust database search for "chocolate teapot" turns up a (nonviewable) match from what it identifies a "The New dawn. ser.2 v.026 yr.1972." A followup search in Google Books turns up the following snippet view from The New Dawn (1972) [combined snippets]:

MELTING POINT
Staff report: " About as much use as a chocolate teapot."

I couldn't confirm the date of this publication, but Google Books and Hathi Trust agree that it is 1972.
This and other instances of chocolate teapot discussed in answers to this question involve the expression chocolate teapot in the sense of "teapot made of chocolate." But it bears noting that an earlier meaning of chocolate teapot seems to have been either "chocolate-colored teapot" or "teapot for making hot chocolate." From William Chaffers & Frederick Litchfield, Marks and Monograms on European and Oriental Pottery and Porcelain,thirteenth edition (1912):

STAFFORDSHIRE. The following are marks of potters not hitherto mentioned who are believed to have worked in Staffordshire. The Editor has been unable to obtain any further information about them except the references given below.
...
Uncertain. The mark impressed on a chocolate teapot with twisted reed handle, similar to Wedgwood ware; in the possession of Mr. T. Hughes, Chester.

Whichever meaning Chaffers & Litchfield had in mind for the phrase chocolate teapot, it seems certain that this particular vessel was neither useless nor edible nor particularly easy to melt.
Comment: Your 1912 find appears at least as early as the 3rd edition, [1872](https://archive.org/details/marksmonogramson00chaf_0/page/536/mode/2up?q=%22chocolate+tea+pot%22).
Comment: *"chocolate-colored teapot" or "teapot for making hot chocolate."* This is a bit of a red-herring. Given that Chaffer was an authority on antiques and their markings, (and he was English), he would not have used "chocolate" to mean other than "dark brown". A chocolate pot was tall and narrow; distinct from a teapot.
Comment: @Greybeard: You're right. The book frequently uses _chocolate_ as a color, and it uses the term _chocolate pot_, not _chocolate teapot_, to refer to a receptacle for preparing chocolate for drinking.
Answer: The phrase and variants are reported by OED:

colloquial. as useful (also successful, etc.) as a chocolate teapot (also fireplace, etc.) and variants: not useful, successful, etc., at all. Hence in similar phrases.

The earliest attestation of the phrase given by OED is from 1973; I have, however, confirmed that a variant of the phrase appeared in print as early as 1968, as noted by an earlier answer given here, where the use of the phrase is attributed to a screaming football fan.
The idea behind the phrase had at least some currency earlier, as attested by this excerpt from an article titled "Our Sandman Could Do With a Wagon", from the (paywalled) Lancashire Evening Post of Saturday 02 April 1955 (emphasis mine):

This little mouse who was a naughty little mouse found some matches and lit a fire in the chocolate fireplace. And the walls all started to melt and…


How did William Stryker control Jason?

Question: In X-2, Jason is convincing Charles to concentrate on all Mutants, but why would Jason listen to Stryker in the first place? I doubt that Jason's spinal fluid would work.
Answer: Jason has a prominent lobotomy scar on the right side of his head. It would seem that his father, after Jason's antics resulted in the death of his mother, decided to tinker with Jason's brain to ensure compliance, evidently at the loss of his motor function.

Note that in the official novelisation we learn that Jason was/is a true psychopath. The fact that his actions would result in the deaths of millions of mutants would be of little concern to him on an emotional level.

As Xavier had sensed during that first interview, there was no empathy in Jason, no acknowledgment of the people around him as living, sentient beings worthy of even the slightest respect. To him, they were a different order of interactive toy. He took his pleasure from "mounting" them as the practitioners of voodoo believed their gods did when possessing their worshipers. He created scenarios that literally put his victims through Hell and gloried in the agonies that resulted.
X-Men 2: Official Novelisation
Comment: @C.Koca - in X-Men Origins: Wolverine we see that he was captured and frozen by his father. Presumably they were able to operate on him by either doing so while he was frozen (unlikely) or sedating him during the unfreezing process (likely).
Comment: How do you lobotomise a guy who can make you see any kind of hallucinations?
Comment: I mean, for Wade they inserted a chip to make him follow orders, but this looks more like some kind of brainwashing trigger, which is not explained, I understand.

How did William Stryker control Jason?


Azure B2C Scope - Restrict Access to Data Specific to a user

Question: I want to restrict access of user to particular objects say specific classrooms say  class room A and Class room B.  My understanding is that I can have a B2C scope say
AccessClassRoom but not specific Class Rooms.   For User Specific data I should not use scopes.  Let me know if my understanding is correct
Answer: You are correct.
Permissions/roles and scopes provide the two halves for this user access control.
Scopes -- such as AccessClassRoom -- determine whether an authorized application can access data on behalf of an authorizing/consenting user if this user, through their permission/role assignment/s, is permitted to do so.
Azure AD B2C doesn't have any current support for managing permissions/roles and assignments of them to users.
It does, however, have support for managing scopes and assignments of them to applications.


Report standard errors and exact p-value

Question: Is it necessary to include both standard errors and exact $p$ values in a result table? Or is an exact $p$ value enough?
Answer: This is a style issue, and each journal has its own.
However, if it was up to me, I'd require standard errors and make p values optional.
Answer: The $p$ values are already a hairy subject, but I would trust them much less if there were no indicators of where that $p$ value came from. From my personal standpoint, you should always:

List the exact $p$ value up to $3$ decimal places (this is the APA standard from what I remember).
List all inferential estimates related to that (standard errors, degrees of freedom, etc).
When possible, visualizing the data to determine what could be driving the $p$ values (such as a serious model misfit).
Avoid flowery language about $p$ values such as "strongly significant" or "important" to rate it over other predictors.
Always report effect sizes when possible (e.g. Cohen's $d$ or $R^2$).


Blue LED light source

Question: is it possible to change the color of a blue LED light source? Can the blue be filtered out to make white or some other color?
Answer: No, you can't. Most of the light emitted by a standard magnesium-doped gallium nitride blue LED is in the blue part of the spectrum, as shown here.

(Image from Science Direct)
So if you filter it to make it look less blue the resulting light will be rather dim.

Here's a chromaticity diagram from Wikipedia  that shows the colours corresponding to various wavelengths. The numbers it shows are nanometres, so they're 10 times smaller than the Angstrom units used in the graph above.

As Jon Custer mentioned in the comments, you can of course use the blue LED to power a phosphor, or mixture of phosphors, to produce any colour you want. But that's not the same as filtering out colours.
From Wikipedia:

A phosphor, most generally, is a substance that exhibits the phenomenon of luminescence; it emits light when exposed to some type of radiant energy.
The term is used both for fluorescent or phosphorescent substances which glow on exposure to ultraviolet or visible light, and cathodoluminescent substances which glow when struck by an electron beam (cathode rays) in a cathode ray tube.

Also see Why can blue LEDs be used for generating white light, but red LEDs cannot
Comment: One can, of course, use phosphors to alter the color.
Answer: You can't filter the light to add additional wavelengths (filters could only remove the blue wavelengths and then you'd be left with nothing else) but a completely different approach is extremely common and blue LEDs are actually the basis for white LEDs typically.
Phosphors are used to absorb the blue light emmited by the LED and this puts the phosphors in an excited energy state. When the phosphors return to their normal energy level they release the absorbed energy as photons at various different wavelengths depending on the material used.
Phosphors are extremely common outside of LEDs (fluorescent lighting also uses them to for exactly the same reasons) and are found in various types of displays such as CRT televisions.

Blue LED light source


Source code plagiarism detection tool that checks against online content

Question: I asked this question on Stackoverflow and was directed to ask it here. The question is:
I wanted to ask about plagiarism detection tools for source code written in C++. When I searched Google the ones I found compare between documents that you already have. What I'm looking for is a tool that compares against content on the internet (i.e Github).
Comment: @Davidmh: Surprising as it is, students keep trying to conduct such "most blatant and poorly done plagiarism".
Comment: @Davidmh: Modern plagiarism tools (such as Moss) are not fooled by changing variable names.
Comment: @O.R.Mapper They do indeed. There was an incident where someone copied handwritten homework word for word from another classmate. *They even copied their classmate's name at the top of the paper*.  Then they both handed it in in class, one submission on top of the other (as if the TA never marks work sequentially). Stupid is as stupid does. If an intelligent plagiarizer substantially improves or obfuscates the code that they plagiarized, they probably actually managed to understand the program and you'll have a hard time proving they plagiarized.
Comment: While this isn't a real answer, what I use is Google.  Take the code snippet and throw it into Google search. You'll quickly find if there are any exact copies. it doesn't easily find those that have been refactored but it does find those really lazy cheaters.
Comment: I think it is unlikely to be of use except for the most blatant and poorly done plagiarism. After all, I can copy code, paste in my IDE, Edit -> Refactor -> Change variable names and get brand new code in no time.
Comment: Not really meant for plagiarism, but there is Black Duck Software. It's a tool that checks against open source code, to allow companies to make sure that their employees didn't copy copy-left source code into their proprietary code base. https://www.blackducksoftware.com/ I assume it must also check for source code from the public domain or from the Apache/MIT licenses, since knowing that a piece of code has been legally copied is also useful information for companies to know.
Answer: We use the MOSS (Measure of Software Similarity) system provided by Stanford, at here.
Comment: I think MOSS just compares between the corpus that you submit, not against code in the web. I'm not aware of anything that indexes code on the web for comparison in this way.
Comment: I am unable to register for MOSS and download and use it, I also have not got any reply of the email I sent them.
Comment: @FarazAhmad, are you sure the email you sent is correct? I just used it and got a response within a minute.
Answer: Haven't used it, but I found this:
https://codequiry.com/
Answer: There are many general sites such as:
http://smallseotools.com/plagiarism-checker/
Sure, they will flag everything that "has to be copied" such as
    int main
but everything that "has to be copied" should be common between your students. It should then be fairly easy to not take it into account using a simple script removing anything shared by more than 80% of your students, preferably before submitting it to the plagiarism checker.
It would probably be easier using a website with an API such as:
https://api.plagscan.com/guide
Comment: It is actually terribly bad for source code. It finds all the things that _have_ to be copied, like `int main` and `\"%s\"\n"`
Comment: This doesn't answer the question, the OP was looking for a plagiarism detector for source code, not free-form text.


What is the median of the non-central F ratio distribution

Question: I am looking for a simple approximation to the median of the (simply) non-central F distribution with parameters dlnum, dldenominator, and ncp, the non-centrality parameter. Clearly, there is no closed-form expression; an approximation if fine. Thanks.
Answer: Here is an approach (as opposed to a complete answer unfortunately) to obtain a good approximation with maybe a limited amount of programming.
It appears that for any fixed values of the two degrees of freedom parameters (call these $\nu_1$ and $\nu_2$), the median for the noncentral F distribution is a close to a linear function of $\lambda$ (the noncentrality parameter).  To support that observation consider the Mathematica code below.  (And from your profile I see that you use Mathematica.)
 Manipulate[
 Plot[N[InverseCDF[NoncentralFRatioDistribution[v1, v2, \[Lambda]], 1/2]],
   {\[Lambda], 0, max\[Lambda]},
   PlotLabel -> Style["\[Nu]1=" <> ToString[v1] <> "  \[Nu]2=" <> ToString[v2], Bold, 24],
   Frame -> True,
   FrameLabel -> (Style[#, Bold, 18] &) /@ {"Noncentrality parameter (\[Lambda])", "Median"},
   ImagePadding -> {{50, 10}, {50, 10}},
   PlotRange -> {{0, max\[Lambda]}, {0, 5}}],
 {{v1, 1, "\[Nu]1"}, 1, 100, 1, Appearance -> "Labeled"},
 {{v2, 1, "\[Nu]2"}, 1, 100, 1, Appearance -> "Labeled"},
 {{max\[Lambda], 20, "Maximum \[Lambda]"}, 1, 100, 1, Appearance -> "Labeled"},
 TrackedSymbols :> {v1, v2, max\[Lambda]}]

Moving the sliders will show that given $\nu_1$ and $\nu_2$ the relationship remains fairly linear.  So it would seem that one could generate a grid of values for $\nu_1$, $\nu_2$, and $\lambda$ and then interpolate/extrapolate where desired.
Alternatively, one could probably come up with a function that estimates the slope and intercept from $\nu_1$ and $\nu_2$ which would be a much more compact approximation.  Such a function will look something like that for the mean which is a linear function of $\lambda$:
$$\mu={{\nu_2}\over{\nu_2-2}}+\lambda {{\nu_2}\over{\nu_1(\nu_2-2)}}$$
(at least for large values of $\nu_1$ and $\nu_2$).
Comment: Thanks for this approach, it does give me a strong direction to further deepen the relation.
Answer: Why code your own if a function with a lot of testing is available?
R:
qf(0.5, 3, 12, 1)

Mathematica:
N[InverseCDF[NoncentralFRatioDistribution[3, 12, 1], 1/2]]

My suggestion about using what's available besides being well-tested, is that many of the algorithms that you'll find will likely work only for large values of the degrees of freedom.  So that means multiple algorithms depending on the size of the degrees of freedom.  Also, many of the algorithms will be for the cumulative distribution function when means you'll need to make a guess as to the median and have an iterative routine to pin that down.
Maybe the best places to start are Abramowitz and Stegun "Handbook of Mathematical Functions" or Johnson and Kotz "Univariate Distributions".
Comment: @ jimB: Because. Because I want to inverse the relation to get a heuristic relation between the median and the parameter; because I want a faster-running function to run 10^8 simulations; because I want to provide a solution that is not software-dependent. Because. Users of StackExchange should not have to justify their questions.
Comment: @Alexis My response was an attempt to be both helpful and challenging which I think we should do more often when the question appears to lack details.  For example, the OP doesn't mention what particular language in which the algorithm would be implemented.  That seems important as  some respondent might know of a package that already implements the desired function.  Responses that don't address what's in the OP's mind hopefully suggest that additional clarity or details are needed.
Comment: Denis, I don't think JimB was challenging your question.  He offers a plausible interpretation and a simple solution to the question as interpreted.  The clarifications in your comment are helpful and welcome, but please put them more prominently in your post itself so that all readers will better understand what you are looking for.
Comment: @whuber JimB's answer strikes me precisely as a challenge to the OP's question, which seems very clear. While JimB's intentions were surely intended as helpful, they seem to assume that the OP must not know his own motivations.
Comment: JimB, I am of two minds about your answer. I agree that frame challenges can useful. Your point about languages is a good one. But I think there's also something to be said about not opening an answer with the challenge: answer part 1 – here's my take plus some good resources; answer part 2 – the precise solution to your question will vary depending on circumstances, have you considered a, b, c. <—This approach seems more inviting to (especially **new**) folks asking the questions in contrast to opening with "why are you asking this?"


CodeNameOne - Library update broke textboxes

Question: I think it was two updates before the present one that TextField were working. Now when selecting a TextField which has text inside the text moves to the side AND remains as a ghost in the middle of the TextField. New and old texts overlap.
Any idea what changed with respect to TextField? Or better can I revert to a library version of my choosing?
This only seems to happen in Android devices, IOS (and simulator) works fine.
Found this question which seems to be the same (only with the text uncentered), but it has no accepted answer (tried the answer there to no avail):
TextFields not updating/repainting correctly on codenameone
Answer: I think this is a simulator only issue that doesn't affect the device. If so it should be addressed by this commit.
Since updates occur every Friday this should be fixed on June 3rd 2016.


See-through windows on a Dell LCD?

Question: At work I have a Dell 2001FP monitor hooked up to my MacBook. I usually keep my email clients and TweetDeck up on it. I've noticed that when I drag a window over an email client window, the text in the email client is still visible, almost as if the front window was not totally opaque. Obviously this is not the case, since it only happens on this particular external monitor and never on the main laptop display. Is there a name for this effect and or anything I can do to avoid it? This does NOT show up in a screenshot! It must be a physical problem with the monitor.
Comment: When did DELL start selling Macbook? ;)
Comment: My employer only has Dell monitors in inventory, so for my second display from my Macbook, I have to use a Dell monitor, which is the only thing exhibiting this behavior.
Answer: Is it the whole window or the titlebar?
If it is only when dragging and not when it is open/selected, it could just be one of the Aero effects that you can configure under System Properties>Advanced System Settings > Performance / Settings. If it isn't the one I drew an arrow next to, it is probably one of them.

As for not seeing it on the laptop monitor - it could simply be that it has always done it but the laptop's panel is bad quality or can't display all the colours and you simply have never noticed it. I am sometimes amazed at the difference when I drag windows between screens.
Comment: No, it shows up mostly in dark areas of the window body. I should have mentioned that it's a Mac too, oops.
Answer: It's a phenomenon called Image Persistence. It used to happen to me on my original G5 iMac 20" after several years of use.
You might try to "exercise" the LCD within the projector by displaying a sequence of pure red, green, blue, and white (hex #F00, #0F0, #00F, #FFF) full-screen on your computer, but there's not really anything you can do to really fix it except get another display. Good luck!
Comment: Do the photos in the Wikipedia article link look like what you're experiencing?
Comment: It's not as bad as that. I wonder how to make such a full screen sequence without writing a screen saver module.
Comment: Since you said it's a Mac, you can just use Preview's slideshow mode with some images that are the size of your display. (Probably 1280x800?) Check out http://pixlr.com/editor/ to make some images using the hex values I gave you (They are shortened so you might have to use #FF0000, #00FF00, #0000FF, #FFFFFF instead). After saving those images as PNG to your hard drive, select them all and open them in Preview so that they open in a group and can all be seen in Preview's sidebar/drawer. Then go to View > Slideshow (or press shift-cmd-F) to view the photos fullscreen. From here press play.

See-through windows on a Dell LCD?


Symmetries and faces of the associahedron

Question:
The dihedral group of order $2n+2$ acts on $K_n$, the ($n-2$)-dimensional associahedron.  Are there any other symmetries?  References?

Does the answer to 1 change if we restrict to just the 1-skeleton of $K_n$?  References?

It is "obvious" that any simple circuit (simple closed walk, simple closed path, whatever terminology you prefer) of length 4 or 5 is a 2-dimensional face of $K_n$.  Is this true?  Proof?  Reference?
Answer: The answer to question 1 is no.  A reference for this is:
Carl Lee, The associahedron and triangulations of the $n$-gon, European Journal of Combinatorics, 10 (1989), no. 6, 551--560.
The answer to question 3 is yes.  I think this is clear from the viewpoint where you think of vertices of the associahedron as triangulations of an $(n+1)$-gon and you obtain higher dimensional faces containing such a vertex by deleting edges from the triangulation.  This is the viewpoint e.g. discussed by Carl Lee.  A 4-cycle involving a vertex $v$ of the associahedron implies that the two edges $e_1,e_2$ in the 4-cycle containing $v$ correspond to the deletion of a pair of edges $E_1,E_2$ from the triangulation corresponding to $v$ such that the concurrent deletion of $E_1, E_2$ yields two quadrilateral regions in the resulting subdivision; a 5-cycle involving a vertex $v$ of the associahedron likewise results from two edges $E_1, E_2$ of the corresponding triangulation whose concurrent deletion yields a single pentagonal region.  In either case, the 4-cycle or 5-cycle then clearly bounds a face of the associahedron, namely the one given by the subdivision in which $E_1$ and $E_2$ are deleted from the triangulation corresponding to $v$.
${\bf Edit:}$  I just realized we can deduce that the answer to 2 is also no, by virtue of a result of Gil Kalai.  Kalai proved that any $d$-dimensional simple polytope is determined by its 1-skeleton.  So we can use that the associahedron is a simple polytope to see that its 1-skeleton can't have any extra symmetries not present in the associahedron itself.
Comment: Patricia: Your comments on 2 and 3 are clear.  I don't see how Lee answers 1.  I have not digested the paper, but it seems at least partly devoted to geometrically realizing symmetries that are combinatorially obvious.  I don't mean that the geometric symmetries are obvious, just the combinatorial ones.  I am interested in the combinatorial symmetries.  I don't see where more combinatorial symmetries are ruled out.  Am I missing something?
Comment: Sorry about my confusion.  Here is a way to prove 1.  The maximal faces of the associahedron may be labeled by single arcs $(i,j)$ connecting vertices $v_i$ and $v_j$ of the $n$-gon.  A symmetry must send facet $(i,j)$ to one of the form $(i+r,j+r)$, where vertices of the $n$-gon are indexed mod n.  This is because the facet given by $(i,j)$ is a product of two smaller (possibly degenerate) associahedra, one given by triangulations of a $(j-i+1)$-gon and the other given by triangulations of an $(n-j+i+1)$-gon.  Now use that flags of faces $F_1\subseteq F_2 \cdots $ must be sent to like flags.
Comment: I tried to squeeze a whole proof into a single comment above, which wasn't easy -- does it make sense?  (I'll check back here in a couple days.)
Comment: This is fine.  The product structures on the faces is the key.  Of course, one must prove some sort of uniqueness of factorization, but I assume I can do this with a little work.
Comment: Ok, great.  I was thinking the fact that there are Catalan many vertices and related face counts should already help with that.  You might like looking at the PCMI volume on Geometric Combinatorics and in particular the chapter by Sergey Fomin and Nathan Reading on Associahedra and Cluster Algebras.  This whole book is really well written, with many interesting survey articles.
Comment: A note on your edit: it is *not* true that the 1-skeleton if a simple polytope can have no extra symmetries (see e.g. the construction in [this answer](https://mathoverflow.net/a/312033/108884)). Kalai's result states that the combinatorics of the polytopes is uniquely determined yb the 1-skeleton, but it says nothing about the realization of its symmetries.
Answer: I have just seen this question, while looking for something else. The answer to 1 is indeed "no", and an explicit proof appears in Lemma 2.2 of Ceballos, Santos, and Ziegler - Many non-equivalent realizations of the associahedron (not surprisingly, it follows the same ideas as Patricia's).


"Repentant" vs "penitent"

Question: Are these words interchangeable or there is some different perception of "feeling sorry" that underlies the concept? Are they both equally often used in religion? I found more derivatives from the second one. If they aren't, what are the spheres of usage for the each?
Answer: While, according to the OED, penitent (first found in English in 1341) and repentant (from 1230) have separate roots, they have similar meanings, and are partially defined in terms of each other.
The OED has for the pair:

Penitent:  A. adj.  1.a. That repents with sincere desire to amend the
  sin or wrongdoing;    repentant, contrite.
B. noun  1. A person who repents; a repentant sinner.
Repentant: A. adj. 1. Experiencing repentance; feeling contrition or
  regret for past sins or actions; penitent.
  B. n. 1. A person who
  repents, a penitent.

In both cases, the majority of citations given imply a religious context.
The definitions in Merriam-Webster are even more circular:

Penitent (adj.):  feeling or expressing humble or regretful pain or sorrow
  for sins or offenses :  repentant
Repentant (adj.):  1 :  experiencing repentance :  penitent
              2 :  expressive of repentance

From the definitions found in these two dictionaries, it's difficult to draw any distinction between the terms.  Both are predominantly found in a religious context, but neither one is, from the definitions given, necessarily more religious than the other.
Answer: James Fernald, English Synonyms and Antonyms (1914) bundles repentance and penitence with attrition, compunction, contriteness, contrition, regret, remorse, self-condemnation, and sorrow, and then offers this succinct distinction between the two:

Repentance is sorrow for sin with self-condemnation, and complete turning from the sin. Penitence is transient, and may involve no change of character or conduct.

The 1947 edition of Fernald's book, now titled Funk & Wagnalls Standard Handbook of Synonyms, Antonyms, and Prepositions, rearranges the order of the sentences in the larger block of text, but leaves the wording of the remarks about repentance and penitence unchanged.
Meanwhile, Webster's Dictionary of Synonyms (1942) offers this commentary on penitence and repentance, which it places in a group with contrition, attrition, compunction, and remorse:

Penitence, repentance, contrition, attrition, compunction, and remorse agree in denoting sorrow or regret for sin or wrongdoing. Penitence implies little more than such sorrow or regret; as, the outward signs of penitence; his penitence is only skin-deep; he showed his penitence in many ways. Repentance is richer in its implications, for it also implies a change of heart, an awareness of one's shortcomings morally or or spiritually, or of the evil of one's actions or life as a whole. "I came not to call the righteous, but sinners to repentance" (Luke v. 32) "God of his mercy give/ You patience to endure, and true repentance" (Shak[espeare]).

Merriam-Webster's Dictionary of Synonyms (1984) updates the examples of repentance and penitence, but not the language of the distinction that its predecessor drew 42 years earlier.
I find the insistence by both of these resources on the relative superficiality of penitence surprising. Perhaps in the first half of the twentieth century, there was a general sense that penitence was mere lip service and repentance was heartfelt—but if so, I think that distinction has very nearly vanished in current usage.
With regard to the adjectives penitent and repentant, I acknowledge that penitent seems to me rather more likely to appear in connection with conduct such as enduring physical chastisement as the price of forgiveness, whereas repentant doesn't seem especially concerned with the scourging of one's sins by some third party. But in general today, I don't detect a difference in sincerity between a person who is penitent and one who is repentant.

"Repentant" vs "penitent"


Need to restrict AD users - Windows Authentication in ASP.NET

Question: I have a website which uses Windows Authentication. I need to restrict access to only a few users, who are present in a local database. How can I achieve it? Example DB has "domain\user1", only user1 should be allowed. "domain\user2" should not be allowed.
Thanks in advance
Answer: in your controller class, you can use the [Authorize] attribute to restrict access.
If you use it by itself, then you restrict the entire controller to only authenticated users.
If you want specific users to access a controller, you can add parameters to the Authorize attribute, such as:
<code>[Authorize(Roles ="Administrators")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
</code>
In the example above, I'm restricting the use of the homecontroller to administrators only, I can also give access only to specific users:
<code>[Authorize(Users = "user1")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
</code>
You can also apply this to specific methods in your controller
Comment: Thank you for the answer, but the website is in ASP.NET (not ASP.NET MVC).


How to set up a computer network with ruby

Question: I would like to set up a network with some computers I have, where they can connect to one main source, then receive and send messages back to it. I have never done any network programming before, so I'm just wondering what are the best tutorials using Ruby that I could use.
Thanks in advance.
Answer: There are about a billion ways you could do this.  Could you post more about what the problem is you're trying to solve, or what the content/purpose/size/format/etc. of the messages is to be?  Are you building something "for real" or just trying to learn network programming?
Also, do you already have the lower layer stuff figured out?  You have networking infrastructure setup, IP addresses assigned, etc?  If not, you'll need to get through that.  Once you have that, you could start with a tutorial on basic socket programming in Ruby, but - depending on the answers to the questions above - you might not want to "roll your own" solution at that level.  The answer might be to use an XMPP (Jabber) server, and use an XMPP client library, or you might want to deploy something like ActiveMQ, HornetQ, etc. and use a library for interfacing with that.  Or maybe you want to use HTTP and pass messages around in JSON, or XML or $WHATEVER.  In short, there are a LOT of options in this area.


"Packing" linux up onto USB drive

Question: I have been using my Linux Mint Nadia for some time and customized it a little, I was wondering if I can "pack it" onto a USB and make it into an ISO which I can boot on another computer and it will have all the settings and files that I currently have? Is that possible?
Answer: This is possible but I'm not sure how automated an approach it's going to be. You can see this example using Arch Linux where they take a previously installed Arch Linux system and create similar partitions on a USB thumb drive and then use rsync to copy the files over to their corresponding locations on the thumb drive.
https://bbs.archlinux.org/viewtopic.php?id=139680
To accomplish this you'll need to make sure of tools such as gparted & rsync and have to have familiarity in editing your grub menu on the USB thumb drive to get it working correctly.
Answer: I've done this with mint using remastersys.  It seems a new developer is taking over the project.  The new URL is http://system-imaging.blogspot.ca
Answer: First do this:
http://www.geekconnection.org/remastersys/
Then do this:
http://unetbootin.sourceforge.net/
Comment: Welcome to Stack Exchange. This is a [questions and answers site](http://unix.stackexchange.com/about), not a link farm. Please do not post an answer that just contains links. Your answer must make sense even if the reader cannot or does not follow the links. For more tips on writing good answers, read [how to answer](http://unix.stackexchange.com/questions/how-to-answer).

"Packing" linux up onto USB drive


Scientific names to piano key numbers

Question: Is there a formula that converts scientific note names to piano key numbers? As an example, given A4 it would output 49.
Comment: This doesn't feel like the right place for this question.  Anyone have a better spot?
Answer: The frequencies are on an exponential scale.  You can use any note as your base value.  On a Chromatic scale, each note is a twelfth step of an octave (doubling of frequency, same tone).  So, a very common formula is to use the 440Hz A note.  (Search on 432Hz to see a controversy about this.)
$$ f = 440 \cdot 2^{\frac{n}{12}} $$
Where $n$ is the semi-tone count from your base.
Here is a good reference:  Note names, MIDI numbers and frequencies

Upon rereading, I didn't really answer your question.  Because of the gaps in note names (black keys on the piano), this is more of a programming exercise than a simple formula.
In Python:

#=======================================================
def NoteConverter( ArgNoteName ):

        theLetter = ArgNoteName[0:1]
        theNumber = int( ArgNoteName[1:] )

        theOrdinal = "C D EF G A B".find( theLetter )

        theMidiNumber = theNumber * 12 + theOrdinal + 12

        return theMidiNumber

#=======================================================

This is for Midi numbering.  Subtract 20 to get your piano key number (on most pianos).
Comment: Note that the logarithmic computation is for an even-tempered scale, which is good enough for most work.  But there are *all sorts of temperings*, each of which is a compromise of some sort.

Scientific names to piano key numbers


Outlook 2010 removes + from mobile numbers

Question: i want to organize my business contacts in Outlook 2010(on Windows 7 Professional) and then synchronize them with my HTC Sensation. But when i enter mobile phone number in format +421900000000(+421 is international prefix for Slovakia) Outlook removes +(plus) sign from beginning of number(i need this format for my HTC).
How can i set up Outlook to not remove + from numbers?
Thanks
Answer: Actually, Outlook does not remove pluses if you have your Windows' Dialing Rules setup correctly. Make sure you have your area code entered in Windows' Dialing Rules (Phone and Modem in the Control Panel).
Comment: mega thx thims, thats works superbly and you saved me from long editing ;-)
Comment: But, this doesn't support using + in the "If you dial a number to access an outside line, what is it?" field. I know 00 is an alternative, but really, afaik + is *the* standard for this. I've also heard that some smart-phones doesn't actually even support 00.
Comment: This does not seem to work in areas without area codes. But it actually does. Just going there once solved the problem from me. I can now import contacts from the company address book and the plus signs will not be deleted.
Answer: What also works is just entering the data in their format, so "+xx", space, "(xxx)", space, "xxxxxxx". Just in case you can't find the modem settings like me or do not want to change them.
Comment: In whose format?
Answer: You can use space between area code and main number,
for example Outlook converts "+77771234567" in this format "77771234567" in fact deletes + in the beginning.
If you will change it to this format "+7 7771234567" Outlook will understood that +7 is area code and will leave it as is.
e.g. if you have database with list of numbers you can easily edit them all.
Answer: I have had the same problem.  The solution is somewhat unintuitive and US-style...but it works.
In the Windows Dialing Rules just insert the area code of your location (20 in case of London) and save.
I found that when entering the telephone number in the Contacts list the plus sign is not removed.  Don't be put off by the fact that the city area code is suddenly enclosed in brackets, e.g. +421 (90) 000000, taking the number of the initial post as an example.  Entering directly in that format as suggested by another contributor here also worked.
How this works when I have sync'ed to my (Windows) phone and I try to dial the number I shall find out in a few months' time when I migrate out of Windows Live Mail (where there is no such problem with phone numbers).
As regards the 'prefix for an outside line' question somebody asked, that refers to a code needed to get out of a shared line/hotel/office environment and precedes (sometimes with a short pause) any country code (00, 011, 001...) or city area code. The plus sign was introduced to bypass the varying country-code prefixes but does not (yet?) work on fixed-line phones using traditional technology.


My network manager applet is dumb?

Question: I'm using a modem to connect to internet,
may be because of poor signal strength my internet gets disconnected often,
but when it does network manager applet have to show that I've been disconnected but it doesn't. is this the problem with my modem or the applet?
I've been using ping command in a terminal window to check my connection
Comment: This question appears to be abandoned and unanswered, could you perhaps add more detail to your question? If this question no longer applies then you can either delete it or answer it yourself if you've solved the problem. Thanks!
Answer: You have the option to upgrade your Ubuntu to v.11.04 and it will be fixed automatically !! I fixed a laptop and a desktop using this solution !!! They say it's a bug !!!
Comment: I'm using ubuntu 11.10 beta

My network manager applet is dumb?


What are the shields on the ribbons for?

Question: On the stats screen in the tavern of dungeon defenders I see a ribbon for each of the difficulties I have passed for a level/map.  Some of them have a shield in the middle and some do not.  What does the shield signify?

Answer: The shield indicates that you've cleared that difficulty (or a harder difficulty) in Hardcore Mode.
Comment: @SeanB, I think it will give you credit for completion on the hardest difficulty + any lower ones.  Did you get the Insane shield for playing on Hard?
Comment: Thanks!  I confirmed by playing one of the non-shield level/maps on hardcore and got the shield afterward.  However, the shield appears to be awarded on a level/map basis not on a difficulty basis.  I played hardcore on hard and the shield appeared for all ribbons.
Comment: Yep that's it.  I played a level on insane that I hadn't previously completed, but not on hardcore and the shield was not on the insane ribbon, but was on the hard and lower ribbons (since I had hardcored on hard).
Comment: @SeanB, okay, cool.  I thought that was the way it worked.  I made a small edit so that my answer reflects this clarification.


Black dots on betta fins

Question: I have a giant veil tailed betta. Two days ago I moved him from a 2.5 gallon tank (filtered and heated) to a 10 gallon tank with a divider. One side of the divider has him and there is another male betta in the other side. At first they noticed each other and were mad but they don't seem to care anymore. Both very active. In my giant betta, he has developed little black dots all over his fins since he was moved into this new tank. I read something that it is rare but when you move a fish into a darker environment then they could develop these spots. Could this be it? I would really appreciate any help. This new tank is filtered and heated. Each fish has 5 gallons.
Answer: From my knowledge this is normal. This is a common occurrence in blue betta or blue fish in general. It is just the fish maturing or like you said just a change in the environment. As long as he is acting normal, I wouldn't worry. The only thing I am unsure on is the very end of the tail from the first picture it looks like tail rot but the second it doesn't; regardless the black spots are normal and there is nothing to worry about.

Black dots on betta fins


What is the cosmological redshift of SN 1987A?

Question: I haven't found any literature on SN 1987A, which provides me with its cosmological [not gravitational, wrong in inital question, thanks for the remark] redshift. Is it larger or smaller than $z=0.1$, the "time" after which the universe started to accelerate?
Answer: SN 1987A is (was?) in the Large Magellanic Cloud, which is gravitationally bound to the Milky Way.  This means that its motion relative to us is only minimally affected by cosmological expansion, and talking about it in terms of a $z$ parameter is misleading at best.
The best estimates of the distance to SN 1987A are about 168,000 light-years.  If you really wanted to assign a $z$ value to it, you could take the Hubble parameter $H_0$, find the velocity that an object 168,000 light-years away would have in the absence of significant gravitational forces, and divide by $c$:
$$
z = \frac{v}{c} = \frac{H_0 d}{c} = 1.16 \times 10^{-5}.
$$
(This calculation uses the most recent Planck estimate of $H_0$ of 67.8 km/s/Mpc.)  But, as noted above, if you actually measured the redshift of SN 1987A, you would almost certainly get a different value from this due to its particular motion within the Large Magellanic Cloud and due to the particular motion of the Large Magellanic Cloud relative to the Milky Way.
Addendum:  Regardless of whether one can assign a $z$-value to SN 1987A, though, you are probably justified in saying that the supernova occurred well after the acceleration of the Universe became significant.
Answer: The Magellanic clouds are satellite galaxies of the Milky Way. They are right next door. Google says 61 kPc to the LMC which means trivial cosmological redshift.
Comment: I assumed the OP was confusing the jargon and went with what seemed the balance of the evidence. That said the actual gravitational redshift will also be quite small as the LMC is not a large galaxy at all. Even the sun's gravitational red-shift relative flat space is quite small and the Milky Way is a fairly big galaxy.
Answer: Of course you won't find it anywhere - SN 1987A is in the Large Magellanic Cloud, just 168000 ly away. At this scales cosmological expansion is negligible compared to other processes so measuring its redshift is says little useful about its distance.
$z=0.1$ corresponds roughly to 1 Gly. The universe is HUGE. Here's plot from wikipedia
Comment: Well, considering the changes made to the question, I can safely return my answer
Comment: yep , now let's remove the unuseful comments :)


Trigger a modal to show no a non click

Question: I have a hidden modal that is want to trigger using data-toggle.
But it needs to start on it's own. so without a click.
I can show the modal using a icon with a data-toggle like this:

This shows the modal 'AddSerialNumberModal'.
Now do I wanna check if !empty($_GET['sn']) and if it isn't I wanna open the modal on it's own.
I tried it with JS like this:
$('#RemoveSerialNumberModal').modal();
$('#RemoveSerialNumberModal').modal(show);
$('#RemoveSerialNumberModal').data-toggle(modal);

But that doesn't work.
(I really wanna do it in JS).
-------------edit-------------

This is how I test this. When I run the example it alerts the first 1 but doesn't show the second alert. So it breaks somehow on the code in the middle.
Comment: use `$('#RemoveSerialNumberModal').modal('show');`
Comment: I just tried your example, but it didn't work. New idea?
Comment: try  $("#RemoveSerialNumberModal").dialog({modal: true});
Comment: thnx. But your example doens't work @Viraj.
Comment: Do you have another idea?
Answer: you can trigger click function if other way are not working to show modal

$('#someid').trigger('click');

Comment: thnx for you help. But your example doens't work for me.
Comment: by click on  modal popup or not ?
Comment: Look at my added info in my question. I get my first alert but after that not the modal or the second alert

Trigger a modal to show no a non click


WPF ViewModel not active presenter

Question: There is a ViewModel that consists of some related object (nodes and lines( ,
How it can be possible to display (synchronize) these VM in View and keep object connections.
I use some DataTemplate to map model to view but each object would be synchronized (with powerful binding) to its related object but how can i link (and synchronize) this DataTemplate generated UI element together.
I describe problem from another viewpoint here:
Sunchronizing view model and view
Answer: To keep your view synchronized you should use bindings, your binding sources need to implement certain interfaces or be dependency properties though. For collections you need to implement INotifyCollectionChanged and for properties you'd use INotifyPropertyChanged, if you then change the source your view will change as well.
Comment: Thanks for your help, but I did that, mean I implemented  INotifyPropertyChanged in view model. But I want to link generated UI elements to each other, as i describe I generate them with DataTemplate.
Answer: Next to implementing INotifyPropertyChanged and using ICollectionChanged (ObservableCollection) and binding to the views, you might consider implementing IEditableObject when you want to support the editing of the data.
This interface allows you to undo edit actions. Without implementing IEditableObject you would need to go back to the data source to reset the to the original values when canceling the modifications. The interface is also supported by the DataGrid.
Answer: You can synchronize the VM and View using Relaying Command Logic.
you can see a sample workout here
Binding the "WindowState" property of a window in WPF using MVVM

WPF ViewModel not active presenter


How to know when a job in screen finishes?

Question: Is it possible to know if a script executed inside a screen session finished or not? The script can be seen by typing jobs and I would like to terminate the screen session when the script is finished. How can I do so or can I have the screen terminate itself after the script successfully executes? It is not convenient to do it manually since I run 72 screen sessions at once. It would be really nice to somehow check the status of the jobs inside the screen sessions automatically and print them to stdout and have the screen sessions terminate when the jobs running within are finished.
Comment: "I would like to terminate the screen session when the script is finished." `some_script && exit`
Comment: Can't you just execute the jobs in the background?
Comment: @John1024 Seems plausible can I stuff it into a detached screen?
Comment: @Vesnog Yes.  The `exit` will cause the window that it is in to close.  If that is the only window in the screen session, then the screen session will close.  If, as shown, `&&` is used, the window will remain open for your inspection if the script fails.  If you want it to close regardless of whether the script succeeded or failed, then replace `&&` with `;`.
Answer: You just chain the commands 1. your_script and 2. kill this screen session
Let foo.sh be your script. The command to kill a screen session is kill. You issue commands to a screen session with screen -X, making screen -X kill the shell/bash command to kill the screen session you are currently in. You would
screen -S the_session_for_my_job

to create the screen session and then you would
/path/to/foo.sh; screen -X kill

This will kill the screen session, independent from the number of windows and will do so after foo.sh has finished.
A more complicated way is to watch process ids and issue the kill command when a certain PID disappears.
Let 12345 the PID of the process you want to watch. Then you would
while ps a | grep ^12345;do sleep 2; done; screen -X kill

The while loop watches the process list for a process with the PID 12345. If such a process exists, it will sleep 2 seconds before checking again. If no process with this PID exists, the while loop terminates. Then the kill command is issued.
Comment: Okay thanks for the answer can I use the second statement with the `stuff` command? Actually I send the commands to a detached screen with a `zsh` script.
Comment: Yes, I saw your other post. It should work just as well as any other string you can `stuff`.
Comment: Better to use `grep "^ *12345"` because may miss it due to padding at the beginning of the line.
Answer: I use email with the following:
command | mail-s job_output email@example.com; exit

Or if it's already running you can type  (or copy-paste if there is lots of output) commands to execute after completion:
echo $STY done | mail -s job_done email@example.com; exit

Comment: Thanks this is a nice option too, but how can it send an email to me.


Swept outer section of the wing on turboprops

Question: It's quite common to see turboprops having a wing with the outer part of the wing with a small sweep (around 3 deg at 1/4 of the chord). What's the reason?
It's usually stated that wing taper is used mainly for reducing the critical mach number or to fix the CG problem. For turboprops such as ATR-42/72 or Dash-8 the effect of Mach number is still negligible and it's unlikely that both of these planes and their subvariants have this feature because they needed to fix the CG.
Comment: If the main spar is straight across, the wing isn't swept, just tapered.
Answer: Don't think of those wings as swept.  As far as aerodynamics are concerned, they are straight wings.
Think of them as tapered -- The taper is there to improve the lift distribution.
The line about which the wing has zero sweep is chosen for non-aerodynamic purposes (since there is little aerodynamic benefit or penalty to one choice or another).
In these cases, the wing is un-swept at the mid-chord or possibly the 3c/4 line.  This is usually for simplicity of layout of structures and systems.
In a related manner, some aircraft twist their wings about the line that the control surfaces are attached to.  This leads to a straight and true aft spar that is easy to hang control surfaces from.
Answer:
It's quite common to see turboprops having a wing with the outer part of the wing with a small sweep

At least for the ATR-42/72/Dash-8, the wing possesses no sweep as it can be gathered from the following cutaway (source):

As it can be seen, the wing spars (185 in that picture) are basically straight and perpendicular to the fuselage. An angle different from 90° would denote a swept wing, which is not the case here.
What you're referring to is actually the taper ratio i.e. the fact that the chord length reduces spanwise from root to tip.

What's the reason?

This is done to reduce lift (which is proportional to the chord length) from root to tip in order to optimise its spanwise distribution, reduce the relevant induced drag and optimise the wing structure, as explained in several answers here, like for example this one.

It's usually stated that wing taper is used mainly for reducing the critical mach number or to fix the CG problem

Tapering the wing doesn't really help in reducing the critical Mach number: sweeping the wing and choosing an appropriate airfoil (so called supercritical airfoil) reduces transonic effect with the relevant drag increase. If you find a CG problem after the design freeze then changing the taper and/or the sweep angle is definitely not a quick way to fix this problem since it entails a major (and costly) redesign of the wing itself.
Comment: There are two 185's in the diagram, both the forward and aft outboard spars are labeled the same.  Which of these is the 'main' spar is certainly up for debate.  The aft spar is un-swept in this case and it lies at about 60% chord.

Notice that both the flaps and the ailerons are attached to the aft spar.  In this case, it is evident that the aft spar was placed to coincide with the control surface hinge line -- and that said line was set to be un-swept.
Comment: @RobMcDonald: right, corrected, thanks for the comment


Supermarkets industry market structure

Question: If the industry is dominated by a few major large retailers like Walmart and target with thousands of many other small supermarkets around the country, what is the market structure of the industry? is it a perfect competition or an oligopoly?
Comment: See [Herfindahl-Hirschman Index](https://www.investopedia.com/terms/h/hhi.asp)
Comment: It may also be a monopsony, but there are usually few indices available to measure this type of market power.
Answer: Oligopoly is best understood as occuring when firms behave strategically: when firms decide how much to produce, under oligopoly they will take into account the optimal responses of other firms.
If you have a long tail of small firms, beyond a certain size these firms won't have much influence at all on prices and will act as 'price-takers'.
So either the firms are large enough to have an impact - in which case everyone is an oligopolist, or they are small enough not to matter much - in which case the market is still oligopolistic because only the larger firms matter. Note competition authorities regularly block mergers in markets with 2-3 large firms and a bunch of very small ones: E.g. the European Commission's DG Comp has just blocked Siemens/Alstom given the large market shares of these firms, despite the fact that they face competition from a few smaller suppliers.
Only if all firms were small / had to act as price takers would you have something (that might approximate) perfect competition

Supermarkets industry market structure


Signal listening

Question: Is there a way to know if someone listens to signal I produce (air signal as well as signal on network)? Is there a way to know if the signal was listened along the way until the signal is reached to the required listener? Can I distinguish between a signal that was listened in his way to non-listened signal?
Answer: Passive detection is called "passive" exactly for that reason: it is not detectable. That's by definition.
Now your question might be: is there a way to "emit a signal" (i.e. convey information) that cannot be passively detected ? In fact physicist have found a method, called quantum key distribution. This requires sending photons one by one, and security relies on some rather fundamental characteristics of quantum theory. This is Science: you can never be sure of having attained the Truth; you can only make theories that seem to work well, or not. However, breaking QKD would meaning proving wrong a century of the smartest physicists, so that's deemed rather improbable. Of course, any experimental setup can have shortcomings; e.g. some instances of QKD have been broken by crafty attackers who, instead of observing the photons going in the optic fibre, used the fibre to observe the state of the apparatus at the sending site.
Information security is the art of cheating with definitions. Thus, one can have something which is almost as good as detecting passive detection: encryption. Encrypted data, if done properly, ensures that the actual information cannot be observed by outsiders. It does not tell whether some people are trying; only that they are not expected to succeed.
Comment: Highly related to this excellent answer: SIGINT is the military discipline of gathering information from the signals emitted by others.  The military has a *tremendous* vested interest in minimizing their SIGINT footprint, and the fact that they don't 100% succeed shows just how hard it can be
Answer: Thomas is correct, as usual. I'm going to add a small observation related to the physics involved.
Radio waves have two regions of propagation (with the same underlying Maxwell's equations): near-field and far-field.
In the near field presence of listening devices can be "detected" from the way they interfere with the transmissions (with some hoop-jumping and practical limits).
In the far field this type of detection is impossible. Yet, to listen to what you transmit over the air, one has to employ an electronic device. When improperly implemented, such devices radiate their own weak signals which can alert you to the fact of possible interception.

TLDR: Passive interception does leave physical traces but you won't be able to detect those without equipment at prices in the 10^5 - 10^6 $ range, some training, being sufficiently close to the listener, and sheer luck.

In practice, it is safe to assume that everything you transmit can be intercepted by someone and plan accordingly. There are satellites in space, automated radio scanners at listening posts, vast antenna fields, ships, planes, helicopters, mobile teams, your nosy neighbor, his 10-year old boy, and perhaps even the neighbor's dog that can listen to your messages.
Comment: Don't forget the doggy door with the proximity unlocking mechanism. That one is listening, too.

Signal listening


What are safe alternatives of electrical tape?

Question: What are safe alternatives to using electrical tape? I don't have it right now nor am I sure when I'll be able to get it. Could I just use regular scotch tape over one of the shattered festoon bulbs?
Comment: duct tape would be better. scotch tape will fall off if it gets wet. saran wrap might work if it sticks and doesn't tear. a condom would probably work. all of these ideas are for a temporary fix. be sure to leave a weep hole.
Answer: As far as safe, duct tape is conductive in some brands especially when wet. Scotch tape is not conductive but it lacks the dielectric properties especially over a shattered globe to be considered safe. To be safe don't use this string of lamps.
Festoon lighting is normally used outdoors or on construction jobs. With a damaged lamp that gets wet a greater shock hazard is there. It would be better to remove the bulb than to have the broken parts extending from the socket.
Answer: A trick to removing a broken bulb is to carve the end of a large potato down to a size that will fit into the bulb base, then jam it hard into that base with the broken glass. It will then stick over the broken parts and give you enough leverage to unscrew the bulb base from the socket. DO THIS WITH THE POWER UNPLUGGED THOUGH!!

When you are done, wrap the potato and broken bulb very well in newspaper or plastic before disposing of it, otherwise animals (or scavenger people) may try to eat it.
Comment: I've tried this before an it only chipped the fragments and made a mess. Maybe if you're in the habit of using bulb lubricant it would work well. I stuff a few hot soggy paper towels into the hole and wrap a thick washcloth around the "ball" to gently torque it out.


Composting pineapple crowns, corn sheath and kernel

Question: Do these take a long time to compost, if so is there some way to speed up the process. Or should I leave them out of the compost bin altogether?
Answer: The crown leaves likely contain a semi-valuable fibre; there is a variety of pineapple specifically grown for those fibres. They are very fine and durable, so the leaves will, yes, take a while to break down. Pulling the crown apart into its separate leaves would help to break them down more quickly. You could consider using the crown to propagate more plants rather than compost it.
As for sheath and kernel, I presume by these terms you mean the inedible core and the outer skin? These would appear to be a prime candidate for worm- or vermi-composting. If you can chop up the core somewhat and put the outer shell, intact as a cylinder packed with core bits, into the vermi-compost bin this is the kind of environment that worms will congregate in and take care of the breakdown for you.
Comment: What do you mean by "semi-valuable fibre"?
Answer: I find they take a long time to break down in my compost bin. The more surface area a substance has the more area there is for it to be broken down by microbes and other small creatures. To create that surface area the best thing is to chop it up as much as you can.


Exponential ergodicity of biased random walk confined to the positive integer quadrant

Question: I am looking at a discrete-time random walk on $(\mathbb{Z}^{+})^n$, where $\mathbb{Z}^{+}:=\{0,1,2,\dots\}$ and $n\in\mathbb{N}$. At any time, the random walk chooses a uniformly random co-ordinate and then either walks up (by 1) w.p. $p<\frac{1}{2}$ or tries to walk down (by 1) w.p. $1−p$, so nothing happens if he is already at the boundary. I would like to show that this random walk has exponential ergodicity, that is, $$P(\text{not returned to $(0,...,0)$ by time }t)\leq e^{-\eta t}$$for some constant $\eta$. Any hints on how I might do this?
Comment: Maybe try to consider it in one dimension first and then generalize? Each directional movement is independent according to you, so you could multiply together the one dimensional cases n times(with some adjustment for the fact that you "skipped a turn" going in another coordinate direction)
Comment: This is my initial idea. The result holds for $n=1$ either from standard large deviation arguments (since the increments are independent and have negative drift) or standard birth-death chain results. So I am thinking about the $n=2$ case as induction should be easy.
Comment: I like the first suggestion.  The sum of the co-ordinates is a simple random walk with negative drift until you hit the boundary, where you  skip a few.  The hitting time  should be dominated by hitting time of simple plus a sum of geometrics  for the skipping.  The number of geometrics you sum can't be more than the hitting time, at most one for each step in the process.  A sum of geometrics where summand has exponential tails also has exponential tails.
Comment: Do you know a simple argument showing that the random walk hits $(0,\ldots,0)$ almost surely?
Comment: Hi Didier, I don't quite yet. I'm attempting Mike's suggestion, and will post some thoughts after a good long try at this..
Answer: The $\mathbf{1}$-Dimensional Problem
According to the result here, the number of unilateral walks of type-$k$ (the number of strings of $k\;$ "$+1$"s and $k\;$ "$-1$"s whose partial sums are never negative) is
$$
\frac{1}{k+1}\binom{2k}{k}\tag{1}
$$
In the same article, it is shown that
$$
\frac{1-\sqrt{1-4x}}{2x}=\sum_{k=0}^\infty\frac{1}{k+1}\binom{2k}{k}x^k\tag{2}
$$
A walk of length $2k+2$ would be a "$+1$" followed by a walk of type $k$ and finished with a "$-1$" resulting in a probability of
$$
\frac{1}{k+1}\binom{2k}{k}p^{k+1}(1-p)^{k+1}\tag{3}
$$
Plugging $(3)$ into $(2)$ yields a total probability of $p$, which is exactly as expected since there is only a probability $p$ of an initial "$+1$".
To compute the probability of a walk of length at least $2m+2$, sum $(3)$ for $k\ge m$. For this, we will use Stirling's Approximation to get
$$
\begin{align}
\binom{2k}{k}
&=\frac{4^k}{\sqrt{\pi k}}\left(1-\frac{1}{8k}+O\left(\frac{1}{k^2}\right)\right)\\
&\le\frac{4^k}{\sqrt{\pi k}}\qquad\text{for }k\ge1\tag{4}
\end{align}
$$
Plugging $(4)$ into $(3)$ and summing for $k\ge m$ yields that the probability of a walk of length at least $2m+2$ is
$$
\begin{align}
\sum_{k=m}^\infty\frac{1}{k+1}\binom{2k}{k}p^{k+1}(1-p)^{k+1}
&\le\sum_{k=m}^\infty\frac{1}{k+1}\frac{4^k}{\sqrt{\pi k}}p^{k+1}(1-p)^{k+1}\\
&\le\frac{p(1-p)}{m\sqrt{\pi m}}\sum_{k=m}^\infty4^kp^{k}(1-p)^{k}\\
&=\frac{p(1-p)m^{-3/2}}{\sqrt{\pi}(1-2p)^2}(4p(1-p))^m\tag{5}
\end{align}
$$
Bound $(5)$ is in the form desired when $p<\frac12$.
Letting $t=2m+2$ in $(5)$, we get that the probability of a walk of length at least $t\ge4$ is no greater than
$$
\frac{1}{4\sqrt{\pi}(1-2p)^2}(4p(1-p))^{t/2}=\frac{1}{4\sqrt{\pi}(1-2p)^2}e^{-\eta\,t}\tag{6}
$$
where $\eta=-\frac12\log(4p(1-p))>0$ when $0<p<\frac12$.
As has been pointed out, I need to rework the $n$-dimensional extension.
Comment: Doesn't $f$ stay the same if the walk tries to walk down and can't? Also, the result seems rather implausible, since one might expect that walks will take longer to return to the origin if they have more directions in which they have to return simultaneously to reach the origin.
Comment: On your random walk? :-)
Comment: @Joriki: Thanks. I had worried about that part earlier. I was working on the $n$-dimensional case on my walk last night, and forgot about the edge cases. I have removed the $n$-dimensional case for reworking.
Answer: Caveat: This is a partial answer, restricted to the regime $p\lt1/(n+1)$.

For every $x$ in $(\mathbb Z^+)^n$, let $|x|$ denote the sum of the coordinates of $x$ and $z(x)$ the proportion of coordinates $i$ such that $x_i=0$. Let $(X_t)_t$ denote the Markov chain in $(\mathbb Z^+)^n$, starting from $X_0\ne0$, and $T$ the first hitting time of $0$. For every $a\ne0$,
$$
\mathrm E(a^{|X_{t+1}|}\mid\mathcal F^X_t)=a^{|X_t|}\cdot n^{-1}\sum_{i=1}^n\left(pa+(1-p)a^{-1}[X_t^{(i)}\ne0]+(1-p)[X_t^{(i)}=0]\right),
$$
thus, $\mathrm E(a^{|X_{t+1}|}\mid\mathcal F^X_t)=a^{|X_t|}b(X_t)$, where
$$
b(x)=pa+(1-p)a^{-1}(1-z(x))+(1-p)z(x).
$$
Assume that $a\gt1$, then $b(x)$ is maximal when $z(x)\leqslant1-n^{-1}$ is maximal, that is, for every $x\ne0$, $b(x)\leqslant c(a)$ with
$$
c(a)=pa+(1-p)a^{-1}n^{-1}+(1-p)(1-n^{-1}).
$$
Hence $(M_t)_{t\leqslant T}$ is a positive supermartingale, where $M_t=a^{|X_t|}c(a)^{-t}$. In particular, $\mathrm E(M_T)\leqslant M_0$, that is, for every $x\ne0$,
$$
\mathrm E_x(c(a)^{-T})\leqslant a^{|x|}.
$$
If, for some $a\gt1$, $c(a)\lt1$, this yields the exponential control
$$
\mathrm P_x(T\geqslant t)\leqslant c(a)^t\mathrm E_x(c(a)^{-T})\leqslant c(a)^ta^{|x|},
$$
hence we are done since one can relate the distribution of $T$ starting from $X_0=0$ to the distribution of $T$ starting from any neighbour $x$ of $0$, namely,
$$
\mathrm P_0(T\geqslant t+1)=p\mathrm P_x(T\geqslant t)\leqslant pac(a)^t.
$$
Finally, $c(1)=1$ and $c'(1)=p-(1-p)n^{-1}$ hence we are done for every $p\lt1/(n+1)$.


HP LaserJet printer doesn't have 2 sided option

Question: When I want to print something, I don't get the option to print on both sides of a paper although my printer supports this feature. How can I fix this? Do I have to download a proprietary driver?
My printer is a HP LaserJet p2015n.
Answer: In addition to lamcro and wdypdx22's answer (check that the hplip package is installed) you need to make sure your printer is set to using the right driver. In System->Administration->Printers you can select the printer:

Right click on your printer and select properties, then click on the Button next to Make and Model that is labeled "Change", then the system will go looking for a driver:

Since you have it installed this won't take long (it can fetch updated ones from openprinting.org so there's never a need to manually install drivers). After the search it will give you an option to use the driver, select the one with (HPIJS). Now the printer options should be available in the "Printer Options" section of the last screenshot.
As a bonus, HP provides a native tool for Linux users that provides even more features than the bundled generic tool. It's called the hplip toolbox, you can install it by installing the hplip-gui package or just search for it in the Software Center.

This is the tool I prefer to use to manager my hp printers. There is a wishlist request bug asking that when anyone with an hp printer plugs in it just installs all this automagically, which would be pretty great.
Comment: Anything for SCX 3200 Series?
Answer: In the output of lpoptions -l, you should see a line that says:
HPOption_Duplexer/Duplex Unit: True *False

You can change this to True via lpoptions -o HPOption_Duplexer=True, and then your print dialog should allow you to print double-sided.
If you don't even have the "HPOption_Duplexer" option (e.g., lpoptions -l | fgrep -c Duplexer prints 0), then:

either you have the incorrect printer description file configured (the so-called PPD),
or you didn't check the "Duplex printing" option in the printer capabilities section.

To solve 1., the quickest path is probably to re-install the printer and choose the correct make/model combination.
To address 2., just open System -> Administration -> Printers, right-click on your printer and choose "Properties", then click on "Installed options" in the left pane and finally check the "Duplex printing" box on the right.
Comment: Thank you very much Mr.Riccardo Murri, it's really very help full for linux user, because main problem for new user of linux is that they don't under stand it's functionalities. I was facing this issue since last two months, once again very very thank you.

  Sunil kumar.
Comment: This was a life saver! Thank you for the help!
Answer: I found a lot of help here:
http://www.linuxfoundation.org/collaborate/workgroups/openprinting
Here's a link to your model:
http://www.openprinting.org/printer/HP/HP-LaserJet_P2015
The site helped a lot with printer issues I was having a while back.
Answer: Try getting the latest version of HP's Linux Printing drivers (HPLIP).
Not all functionality comes pre-installed on Ubuntu.  I myself had to install it and it accessed a lot of additional functionality.
Answer: Use the printer control panel to print information pages with details about the product and its current settings, check to see that the Duplex unit is listed, and then disable the Manual Duplex option in Device Settings.
Right click on the HP laserjet Printer, select Properties, and then select the Device Settings tab.

In the Installable options section, make sure that Duplex unit is Installed and that the Allow Manual Duplexing option is Disabled.
Click Apply and then click OK.
Try again to print the Configuration page.
Make sure that the Manual Duplex option is Disabled in Properties on the Device Settings tab.


What to show to future employer as portfolio if my previous works are confidential?

Question: I work on several enterprise level applications at my current job, but I don't have clearance to share any detail about it. Nobody has. Although the applications are available publicly behind pay-wall/trial-wall, the employers don't want employees to showcase those in their portfolios. On the other hand, all the new jobs I have applied to are keen on seeing "real-world" projects. What I can show them as my portfolio (because I can't show the things I work on)?
Comment: I'm voting to close this question because it is about career advice.
Comment: Before you do so, please direct me towards the channel I can ask this.
Comment: Not sure which site is best to be honest. Perhaps it might fit on [workplace.se], not entirely sure on their rules though so be sure to check before you post.
Answer: Avoid employers like that, they don't care about the people doing the work. An employer has a responsibility to nurture talent and careers, not simply squeeze employees dry and throw them away. You are allowed to talk about your experience, there is also "fair use" when it comes to copyright - if you were writing an article about the product, what could you show? You could show screenshots and video.
Work on your own projects, they will be much more rewarding long term and can provide you with experience that short-term projects never will.
Answer: What I do is present in short details about the projects with hidden names and state that I can present the work on an interview with shared screen.
Comment: What is hidden name ?
Answer: I'm in the same boat (along with many designers.) I have yet to update my portfolio, but my thinking is to concentrate on the written story-telling aspect in your portfolio. Even if you don't have images or interactive prototypes you can show, you can write the story of your contribution.
Before you read my suggestions I want to emphasize one important thing to help prevent this conundrum in the future: ask potential employers during your interview what you can/can't show in your portfolio. A company should understand the importance of maintaining your portfolio. This will help clear up any confusion before you even accept a job offer, and hopefully give you the opportunity to keep it updated without worry.
1.) Tell the story of your contribution. What was the project's goal? What did you do on the project? What were the results? Are there metrics you can provide? (i.e., increased conversion rates by 25%, improved web performance by 50%, etc.)
2.) Draw some sketches to illustrate the narratives of your contribution. (Leave a note to say these are not representative of the UI, just graphics for visual purposes only.)
3.) Make sure the UI design of your portfolio shines. If you can't provide a lot, or any, UI examples of the work you've done in your portfolio, then make sure your portfolio is designed well and accurately reflects your style.
4.) Create a side project for fun that is representative of your capabilities. I tend to dislike this option because, personally, I'm super busy as it is. (Full-time designer + mom of two + helping my 1st-grader with virtual learning due to Covid-19.) I typically work every evening right now just to make up for lost time during the day. But this is a tough industry and if you're having trouble getting your foot in the door, you might want to give it a try. On the other hand, personal projects can be a ton of fun compared to what we're contracted to work on for clients and are an excellent opportunity to practice and expand your skillset.
5.) Recreate the work you did. Change the styles, colors, values, labels, headings, copy, or anything that might be considered intellectual property. Note: this is a suggestion but I don't know if this would still infringe on your agreement. It might be worth asking if you can.
6.) Zoom in on specific elements. Instead of showing a screenshot of an entire screen or linking to a prototype, zoom in on one specific area that you worked on to talk about only that area without displaying the entire context. You can do this with different areas of the same project. You might have to create similar redesigns to these small sections, still, as with the above suggestion for #5. And the same concerns would probably apply.
I hope these help! I'd love to check out your portfolio once you've implemented whatever solutions you come up with.


On Ubuntu 16.04, Freeipa ssh logins working, GUI logins fails with "incorrect password"

Question: I've got this working on one virtual machine but must have missed recording something I installed or configured, as I can't get it working on any other machines that I create. I've been digging through Google and here, but most everything I find winds up having to do with displaying the "Other..." login field in the greeter, or getting FreeIPA to work properly in the first place.
Steps I take: I create a fresh install of Ubuntu/Mate 16.04, do all updates/upgrades, add the machine to FreeIPA, install freeipa-client, do the configs and run ipa-client-install, see that the new VM is enrolled properly in FreeIPA, and then test by ssh-ing into myself and some other machines with users that are only in FreeIPA. That all works fine-- I can see the various hosts without using FQDNs and use users that aren't in the local passwd file.
However, when I try to use the Mate GUI to switch users to a user in FreeIPA that can successfully log in via ssh (which will otherwise quickly fail and return me to the login screen, as the user doesn't yet have a home directory), I get the error "Incorrect password, please try again". The only user that can log in via this screen is the one that I defined locally. I've tried creating a home directory owned by a FreeIPA user just in case, but that makes no difference.
So ssh is resolving names that lightdm or some other component in the login process isn't. The lightdm log shows this for a user "student", a user only defined in FreeIPA:
<code>[+6783.50s] DEBUG: Continue authentication
[+6784.83s] DEBUG: Session pid=25854: Authentication complete with return value 0: Success
[+6784.83s] DEBUG: Authenticate result for user student: Success
[+6784.83s] DEBUG: User student authorized, but no account of that name exists
[+6784.84s] DEBUG: Greeter start authentication for student
[+6784.84s] DEBUG: Seat seat0: Failed to work out session ID to mark
[+6784.84s] DEBUG: Session pid=25872: Started with service 'lightdm', username 'student'
[+6784.84s] DEBUG: Session pid=25854: Exited with return value 0
[+6784.84s] DEBUG: Seat seat0: Session stopped
[+6784.85s] DEBUG: Session pid=25872: Got 1 message(s) from PAM
[+6784.85s] DEBUG: Prompt greeter with 1 message(s)
</code>
This is distinctly different from my Ubuntu/Mate machine where this is all working right; there, the log looks like:
<code>[+50005.95s] DEBUG: Continue authentication
[+50006.20s] DEBUG: Session pid=10425: Authentication complete with return value 0: Success
[+50006.20s] DEBUG: Authenticate result for user student: Success
[+50006.20s] DEBUG: User student authorized
[+50006.20s] DEBUG: Greeter sets language en_GB
[+50006.23s] DEBUG: Greeter requests session mate
</code>
During failure, the auth log shows this:
<code>Aug 20 18:19:26 client2 lightdm: pam_unix(lightdm:auth): authentication failure; logname= uid=0 euid=0 tty=:1 ruser= rhost=  user=student
Aug 20 18:19:27 client2 lightdm: pam_sss(lightdm:auth): authentication success; logname= uid=0 euid=0 tty=:1 ruser= rhost= user=student
Aug 20 18:19:27 client2 lightdm: PAM unable to dlopen(pam_kwallet.so): /lib/security/pam_kwallet.so: cannot open shared object file: No such file or directory
Aug 20 18:19:27 client2 lightdm: PAM adding faulty module: pam_kwallet.so
Aug 20 18:19:27 client2 lightdm: PAM unable to dlopen(pam_kwallet5.so): /lib/security/pam_kwallet5.so: cannot open shared object file: No such file or directory
Aug 20 18:19:27 client2 lightdm: PAM adding faulty module: pam_kwallet5.so
Aug 20 18:19:27 client2 lightdm: pam_succeed_if(lightdm:auth): requirement "user ingroup nopasswdlogin" not met by user "student"
</code>
I have some vague impression that I had to add some package that make sure that LDAP is contacted, but after lots of investigation this just hasn't revealed anything. I'm happy to have more pointers of things to look at or reconcile between my working and non-working system, but I'm kind of at a loss here.
This seemed a plausible cause, but I can't find any differences in /etc/pam.d that point to the error: https://stackoverflow.com/questions/14983807/ldap-login-works-via-terminal-but-doesnt-work-via-gui.
Does this ring any bells for anyone?
Answer: The answer can be found in the site below:
https://help.ubuntu.com/lts/serverguide/sssd-ad.html
particularly the section about "Home directories with pam_mkhomedir (optional)"
session    required    pam_mkhomedir.so skel=/etc/skel/ umask=0022
I added this after the optional call to sssd from /etc/pam.d/common-session

On Ubuntu 16.04, Freeipa ssh logins working, GUI logins fails with “incorrect password”