Integrating angular momentum, velocity and acceleration on two touching, spinning discs

Question:
first let me get some things out of the way. I'm a programmer at heart, but not very versatile with the maths stuff. Which is why I come here to seek help.
That said, I don't fully understand everything regarding formulas and integration etc, when it comes to this problem. So if possible you could also express the steps or solution in programming terms, I'd be very grateful!

The problem
I'm trying to find a solution to a derivative problem of a, what seems to be, a classical mechanical problem.
The original problem is finding the final angular velocity between two discs, spinning at different speeds, after they've touched eachother. Think a record player and a record being dropped on top. As such the problem focuses on conservation of angular momentum as far as I have researched.
Now, I've come as far as to solve for the final angular velocity of the two discs; that solution and formula is readily available with a search.
But I can't find the solution on how to integrate this over time.
For instance, how do I know how long it will take the discs to get to final velocity?
How can I integrate this with a defined time step?

What I've got so far...
Given that the discs have intertia $I_n$ and an initial angular velocity $\omega_n$, and the systems total inertia $I_t = I_1 + I_2$
then the final velocity for both discs should be
$$\omega_f = \frac{I_1\omega_1 + I_2\omega_2}{I_t}$$
So what I've figured out is that, obviously the total difference in angular velocity for a disc would be $\Delta\omega_n = \omega_f - \omega_n$ and that's where I start to get lost.
If I'm understanding it right, the total difference in angular velocity can be seen as an instant impulse to acceleration?
How do I integrate this acceleration over time?
What I've got so far is, if we have angular velocity $v$, and timestep $t$ then either,
$$\alpha_n = \frac{\omega_f - \omega_n}{I_n}$$
or divided by total inertia,
$$\alpha_n = \frac{\omega_f - \omega_n}{I_t}$$
and then I integrate like so
$$\omega_n = \omega_n + {\alpha_n}t$$

Am I right in my assumptions and/or calculations?
What did I get wrong if not? What's the proper way to integrate the acceleration and velocities of the discs, over time?

And finally
One last thing I've been pondering about when thinking about this problem is; how does friction and outside forces (i.e. torque) come into play in these formulas/calculations? How would I calculate it?

If you've come this far, thank you for taking your time to read through my problem. If you don't have a solution I'm still thankful for reading it.
If however you know the solution, please let me know! This problem has been bugging me for a while, and I can't seem to find any solution to it at all. Only for final velocity.
Thank you!
Answer: The situation seems basically similar to a "dry clutch" in engineering. The simplest model of that, I think, would be almost identical to a block sliding on a flat surface, subject to frictional forces. And the common assumption there is that the kinetic friction force is proportional to the normal force applied to the block (which might be its weight), and to a coefficient of friction, but it is independent of the speed. This is the angular equivalent of that. The frictional torque between the two discs will act on the relative motion, and will conserve total angular momentum.
So we can start by writing
$$
I_1 \dot{\omega}_1(t) = -\tau , \qquad I_2 \dot{\omega}_2(t) = +\tau
$$
where
the dot represents the time derivative and
$\tau$, the frictional torque, is a constant.
We need to integrate these equations in time, from $t=0$, up to the point where $\omega_1(t)=\omega_2(t)=\omega_f$. Beyond that point, the discs will rotate together.
This is simple enough to do analytically. The angular velocities will change linearly in time
$$
\omega_1(t) = \omega_1(0) -\frac{\tau t}{I_1 } , \qquad
\omega_2(t) = \omega_2(0) +\frac{\tau t}{I_2 }
$$
An easy way to get a solution is to write an equation for the relative angular velocity $\omega=\omega_1-\omega_2$,
set $\omega(t)=0$, and solve it for $\tau t$:
\begin{align*}
\omega(t) &= \omega(0)
- \tau t \left(\frac{I_1+I_2}{I_1I_2}\right) = 0
\\
\quad\Rightarrow\quad
\tau t_f &= \left(\frac{I_1I_2}{I_1+I_2}\right) \omega(0)
=  \left(\frac{I_1I_2}{I_1+I_2}\right)
[ \omega_1(0)-\omega_2(0)]
\end{align*}
where I've called this final time $t_f$.
We can check that this gives the correct answers by substituting back in
\begin{align*}
\omega_1(t_f) &= \omega_1(0) -\frac{1}{I_1 }\left(\frac{I_1I_2}{I_1+I_2}\right)
[ \omega_1(0)-\omega_2(0)]
=
\frac{I_1\omega_1(0) + I_2\omega_2(0)}{I_1+I_2}
 \\
\omega_2(t_f) &= \omega_2(0) +\frac{1}{I_2 } \left(\frac{I_1I_2}{I_1+I_2}\right)
[ \omega_1(0)-\omega_2(0)]
=
\frac{I_1\omega_1(0) + I_2\omega_2(0)}{I_1+I_2}
\end{align*}
So, both equal to $\omega_f$ at that time $t=t_f$.
Of course,
if you want to make the frictional torque depend on
relative angular velocity in some complicated way,
the solution may require a computer.
But the underlying equations will be similar to the above.
[Edit following OP comments]
Note that I wrote the equation for $t_f$, time needed to reach equal angular velocities, as an expression for the product $\tau\, t_f$:
this product is equal to a function of the initial angular velocities and the moments of inertia.
You need to know $\tau$ before you can calculate $t_f$.
To evaluate $t_f$ for a particular physical case, you need to
multiply my equation for $\tau t_f$ by $1/\tau$ on both sides, i.e.
take $\tau$ over to the right hand side.
This illustrates that $t_f$ is inversely proportional to $\tau$,
if the other parameters are kept constant.
If the friction between the two discs is zero, it will take
an infinite time to reach the same angular velocity,
because the two discs will have no effect on each other.
If the friction is very large,
the time taken will be very short.
In any case, the integration of those equations
should stop at $t=t_f$,
since after that time the two discs are not rotating relative to each other.
So, to solve the problem you want to solve, you must provide the physics of the interaction between the discs. Let me emphasise that my solution is only based on the simplest assumption about this. Your situation might be more complicated. However, some aspects of my solution will still apply, e.g. the torque between the discs must still conserve total angular momentum. For more discussion of friction in general, see for example https://physics.stackexchange.com/questions/2408/does-the-force-of-kinetic-friction-increase-with-the-relative-speed-of-the-objec and https://physics.stackexchange.com/questions/154443/why-is-the-equation-for-friction-so-simple .


$\sqrt{d}\in{\mathbb Z}_+$ or $\sqrt{d}\in {\mathbb R}\setminus{\mathbb Q}$ for every positive integer $d$?

Question: I just guess that the following statement is true:

$\sqrt{d}\in{\mathbb Z}_+$ or $\sqrt{d}\in {\mathbb R}\setminus{\mathbb Q}$ for positive integer $d$?

But I don't see a way to deal with it. I think the point is to discuss $dn^2=m^2$ where $n$ and $m$ are positive integers. If I can conclude that $n|m$ then the proof will be done. Help?
Comment: It follows from unique factorization. Better to assume $m,n$ are relatively prime and show that $dn^2=m^2$ implies $n=1$.
Comment: http://math.stackexchange.com/questions/4467/sqrt-a-is-either-an-integer-or-an-irrational-number http://math.stackexchange.com/questions/324724/p1-n-is-irrational-if-p-is-prime-and-n1  http://math.stackexchange.com/questions/448172/what-rational-numbers-have-rational-square-roots
Comment: Suppose to the contrary $\sqrt{d} = a/b$ with $(a,b) = 1$ and $b > 1$. Then $b^2 d = a^2$. Hence $b | a^2$, but $b > 1$ and $(a,b) = 1$ so we got a contradiction!
Answer: Lemma: If $a|bc$ and $(a,b)=1$ , then $a|c$.
Lemma: If $(m,n)=1$ then $(m^2,n^2)=1$.
Theorem: If $(m,n)=1$ and $dn^2=m^2$, then $d=m^2$.
Proof of theorem only: If $dn^2=m^2$, then $m^2|dn^2$ and therefore $m^2|d$ by lemmas. So $m^2|d$ and $d|m^2$ implies $d=\pm m^2$. But clearly $d$ is positive.
Both of the lemmas can be proven using the fact that if $(a,b)=1$ then $ax+by=1$ has a solution for $x,y\in\mathbb Z$.
Comment: @Jack Sure, that way works just as fine. This is essentially a coded version of that counting argument. Arnold Ross insisted that the first Lemma is what really ought to be called the "fundamental theorem of arithmetic," and a lot of unique factorization proofs can be quickly represented via that lemma.
Comment: Regarding your comment about, can I just count the prime factors on both side to reach a conclusion?
Comment: Nice presentation! :)
Comment: @ThomasAndrews Fair enough. I was just about to ask how you would write the proof neatly according to your comment. Thanks!
Answer: $dn^2=m^2 $. If $p|d$ prime such that $p^{2n+1}||d$ (such a prime exists) then $p^{2n+1}||m^2$ , which is clearly impossible.
Answer: More directly, without assuming $m,n$ are coprime, you can try the following steps:

$n\vert m$ if and only if for any prime $p$ and natural number $k$, if $p^k$ divides $n$, then it divides $m$ (by prime factorization).
Choose arbitrary $p^k$ dividing $n$. Then $p^{2k}$ divides $n^2$ and consequently $m^2$.
If $p^k$ did not divide $m$, then by uniqueness of factorization, $p^{2k}$ could not divide $m^2$, so $p^k$ divides $m$ and we're done.

In fact, you can prove a similar theorem for arbitrary UFD in the same way: any element of an UFD $R$ has a square root in $R$ if and only if it has one in the quotient field. This is a special case of a more general fact that a unique factorization domain is always integrally closed.


Can I use Wilcoxon Signed-Rank Test to test pairs of data in a time series?

Question: I have a dataset of measurements (non-normally distributed).
Each line of this dataset is composed of two measurements of the same variable at a specific time (i.e. XYY [time, meas1, meas2]). This dataset contains 24 lines.
Is it correct to use the Wilcoxon Signed-Rank Test to compare these two measurements? Is it correct to use this test to compare the mean value of these measurements between different experiments?
Thanks
Answer: One major concern is whether there's serial dependence in the differences, due to the observations being over time. The test assumes independence and if that doesn't hold, it could be badly affected. [The rest of my answer is predicated on independence being sufficiently close to true that the null distribution of the test statistic is not badly affected.]
If you want to test the null hypothesis that the pairs of measurements have the same distribution against the alternative that they don't, the Wilcoxon signed rank test will be suitable (there are some other pairs of hypotheses that would fit with the test).
If you want to specifically test for an alternative of a difference in means, the test will be sensitive to that difference (under a null of identical distributions), but the location-shift estimate it gives is not a shift in means (it's the Hodges-Lehmann estimate, the median of pairwise differences; if you like it's the median shift). If your alternative is explicitly a shift alternative, the Hodges-Lehmann estimate will be a reasonable estimator for the population mean of the pairwise shifts.
(In short, if I understand your description, then yes, it looks like a signed rank test would be suitable, but to make your inference about the means you have to make additional assumptions.)
If your interest is particularly in the mean of the differences, I'd suggest looking at a permutation test; with a reasonably efficient implementation, your sample is small enough to cover all possible permutations.
Comment: One possible concern is there may be dependence between pair-differences over time (such as serial correlation).
Comment: Sorry... continuing...

I don't know if I understood it right.

My situation is that I'm dealing with biological experiments. I have 2 biological replicates and each one with 2 technical replicates. My goal is to statistically say if the data is valid for further analysis or not.

Should I analyse each point (i.e. 4 values) or the whole dataset (i.e. 4 * 24 values).... or, even, just the mean values?
Comment: Another potential concern is that the test is for continuous distributions. If that's not the case, there may be some problems, especially if most of the data occurs in a few values.
Comment: I don't know if I have understood it right.
Comment: @user3075205 Another possible concern is that the time series may be non-stationary/integrated/unit root.
Comment: I don't think that "observations come from the same distribution" is the correct description of the null hypothesis in the signed-rank test.
Comment: @AdamO with paired data, it is fine to word it that way
Answer: I have also been wondering about this.  It turns out that this question has cropped up a few times in the recent past:

Is Wilcoxon Signed-Rank Test the right test to use?
Can I use wilcoxon signed rank test for time series data

@Glen_b makes the point that autocorrelation in the data (e.g. the tendency for readings close in time to be close in value) breaks the central assumption of the Wilcoxon Signed-Rank Test that the pairs are independent in your data.
Put another way, if your 100 paired readings are highly correlated over time (as is often the case), then you are not testing 100 independent pairs.  Your effective sample size is much smaller. If observation A >> observation B at time 1, the same is likely to be true at time 2, time 3 and so on... depending on the level of autocorrelation in the data.
Now Wilcoxon comes along and sees 100 independent samples that all have the property A >> B.  Bingo! A differs from B with dramatically high statistical significance.  But in reality, if you were to run the test again you might find that $A \approx B$ at time 1 and this propagates forwards in time as before. Wilcoxon now says that A and B have the same distribution.
So, having laboured this point, I now admit that I have no real idea how to deal with it!  A recent study gives a modification to the test to deal with clustered data.  For example a left eye - right eye (before and after) test. But our problem only has one 'cluster' - a single time series - so I don't think this will help.
Comment: In general, it would be plausible to suppose that measurements of even a serially correlated variable would be conditionally independent of that variable (although of course whether this is actually the case depends on the type of measurement). Thus the autocorrelation in the data does not necessarily indicate there is any kind of a problem in comparing *differences* between the two measurements to zero (or any other dataset, for that matter).


Get table name in doctrine join query

Question: I'm using Symfony 1.4 with Doctrine, and have this situation:
I have a table A that holds common fields, and 3 more tables B, C and D which all have a foreign key to A (a_id), and extra fields specific to each one.
In my model, I'm writing the following query:
 public function getAllFields(){
    $query = Doctrine_Core::getTable('A')
    ->createQuery('a')
    ->leftJoin('a.B b')
    ->leftJoin('a.C c')
    ->leftJoin('a.D d');
    $result = $query->execute();
    return $result;

Having that data (a DoctrineCollection), I need to iterate it in my view to fill a grid. The thing is that I need to specify in that list, the type of the record (that'd be whether it belongs to the table B, C, or D). How can I know from which table each field comes from?
Answer: Well normally the records will be hydrated as the appropriate model class, so you wont have a flat result set. You then access the properties from the record with an accessor/array notation/object notation.
Example:
foreach($result as $record) {
   echo $a->getSomeAProperty();

   $b = $a->getB();
   echo $b->someBProperty();

   $c = $a->getC();
   echo $c->getSomeCProperty();

}

To get a table name from a model you can do:
$theModel->getTable()->getTableName();

Likewise if you use standard array hydration you will get back a nested array structure like:
array(
   'some_a_property' => 'value',
   'C' = > array(
      'some_c_property' => 'value'
   )
   // etc..
)

So you could determine what model/table the property comes from by the key for the nested array.
That said if you are doing things correctly table name should be unimportant, instead you should be concerned with what type of object it is. Table names can change and are merely a storage construct you probably don't want your logic at this level to be concerned with.
For that you can use instanceof and get_class to act appropriately.

Get table name in doctrine join query


Using 1 Parameter per Table Matrix in Winform RDLC

Question: I am working on a report viewer for a small winform application. Is there a way for me to use 2-3 tables (Tablix) that each take a different parameter in the rdlc?
To clarify, I have this statement in my dataset
SELECT something
FROM Table
WHERE something_date = @date

and in my report, I would like to have 3 tables that display the dates 10/05/2016, 10/06/2016, and 10/07/2016
so that when I populate the rows and columns via load or button click I would use
this.DataTable1TableAdapter.Fill(this.DataSetScheduleReport.DataTable1, param1, param2, param3);
//where of course param1, param2, and param3 are the dates

so basically, the final output is
table for 10/05/2016
[something1]
[something2]
[something3]

table for 10/06/2016
[something1]
[something2]
[something3]

table for 10/07/2016
[something1]
[something2]
[something3]

Any other alternatives and suggestions would also be very helpful as I would still be learning tidbits from them.
Thank you
Answer: You can have two approaches to solve your problem.
First approach:- Create three different tables and pass on all the three tables to the RDLC; then for each tablix specify respective table as its datasource.
Second approach:- Create only one table which contains data of all the three dates and pass on this table to RDLC; additionally, pass on three different dates as report parameters. For all the tablix specify same table as datasource but apply fiter so that each tablix display data of specific date only.


Counting itab groups without a loop

Question: I recently found out about the GROUP BY command in loops.
Now imagine following example:
I have an itab with a column categories. I want to know how many different categories there are.
Using the GROUP BY statement linked above I could count the number of times the loop is executed. Is there a simpler way without having to loop?
Comment: Anyway, you can imagine that the processor must iterate the lines to count the number of distinct values, so I guess your question is more about the shortest way to write it … no doubt that you should use REDUCE … FOR GROUPS … GROUP BY …, but that would help a lot if you could provide your code snippet to help answering.
Comment: Can you provide existing code?
Answer: Here is a short example code wrapped in a report you can try on your system.
REPORT Z_GROUP_COUNT.

  TYPES: BEGIN OF lty_st_for_reduce,
           categories TYPE C LENGTH 4,
         END OF lty_st_for_reduce.

  DATA: lt_for_reduce TYPE STANDARD TABLE OF lty_st_for_reduce.

  APPEND VALUE #( categories = 'ABAP' ) TO lt_for_reduce.
  APPEND VALUE #( categories = 'OBJC' ) TO lt_for_reduce.
  APPEND VALUE #( categories = 'ABAP' ) TO lt_for_reduce.
  APPEND VALUE #( categories = 'ABAP' ) TO lt_for_reduce.
  APPEND VALUE #( categories = 'OBJC' ) TO lt_for_reduce.

  DATA(lv_categories_count) = REDUCE i( INIT count = 0
                                        FOR GROUPS categories OF entry IN lt_for_reduce
                                        GROUP BY ( categories = entry-categories )
                                        NEXT count = count + 1 ).

  " Will output `2`.
  WRITE: lv_categories_count.

Comment: Looks good, I will check this as the answer once I succesfully tested it in my code :) So it seems `Reduce` was what I was looking for, I knew something like this must exist somewhere :D
Comment: I don't see any performance differences. This is a loop also, just in a fancy way. :)

Counting itab groups without a loop


How to add common functions to template classes?

Question: I have two template classes, pseudocode:
template<class L, class M>
class A
{
  L l; // copyable
  M m; // only moveable
}

template<class L, class M>
class B
{
  L l;
  M& m_ref;

  B(A& a, ExtraParameter ep)
    : l(a.l.subset(ep))
    , m(a.m) {}

  // +copy and move constructors and operators
}

(The idea here is to be use B's as references to parts of A's. So l might be different, but b.m_ref references an a.m.)
Depending on L and M, I want to add some member functions that are added to both functions. This functions need access to an L and an M.
(how) is this possible?
edit: Emphazise the depending on L and M. There will be different combinations of L and M and some allow extra member functions and/or are specialised to use features of L or M.
I tried to add these to B and made A a child of B. But I failed to come up with an move-operator for A that updates m_ref.
edit: I found the move operator by casting this to B. I still do not like this, but I gone close this question, since the problem is solved.
I thought about adding the new member function to a third class template C and make both (A and B) children of C. But I was not able to think of a way to provide the reference to M. CRTP does not seem to fit, since only L and M should be template parameters of C.
Comment: I don't understand your reasoning about CRTP. It seems that CRTP can do the job here. Just put `getL`/`getM` functions into `A` and `B`, and CRTP should call these to get `L` and `M`.
Comment: "only `L` and `M` should be template parameters of `C`" Why? `C>` can have access to `l` and `m`
Comment: @Caleth I will need to specialise `C` for different combinations of `L` and `M`. I would like to be sure, that `A` and `B` call the same logic, have the same functions from `C`.
Answer: It sounds like you misunderstand what you can do with CRTP. The template base can have L and M as parameters
// base template
template <class AorB, class L, class M>
class C
{
};

// partial specialisation for some pair of L, M
template <class AorB>
class C<AorB, int, std::string>
{
};

template<class L, class M>
class A : public C
{
  L l; // copyable
  M m; // only moveable
}

template<class L, class M>
class B : public C
{
  L l;
  M& m;

  B(A& a, ExtraParameter ep)
    : l(a.l.subset(ep))
    , m(a.m) {}
}


How to maintain the modified record on jsp

Question: i have a small requirement like following.
I have one Jsp on which i am population all details of employee details.
ON jsp i have more than 100 record. To Edit the details i am not opening any pop up. User can update some field from drop down from UI.
Also i have save button on the same Jsp so that the same record can be updated.
All the records are showing on JSP row wise.
As per requirement, i have to maintain the last modified record.
e,g user has done the modification on 100th record and clink on save, so after save JSP page will show 100th record ON JSP (as highlighted or may be some other solution ).
usually if i click on save, so all the records will be shown On JSP, so user has to go to 100th record to find the modification.
is there is any way to implement this situation.
Best Regards
Arvind Porlekar
Answer: First request: GET /displayRecords: shows all the records.
Now the user chooses to scroll, edit and save the 100th record, identified by the ID 3542: POST /saveRecord, with the parameters recordId=3542, recordFoo=bar, etc. The server saves the record, and redirects to /displayRecords?highlightedRecord=3542#3542.
So third request: GET /displayRecords?highlightedRecord=3542. The JSP regenerates the list of records, and highlights the record identified by 3542 (thanks to the value of the parameter highlightedRecord).
The list of records is redisplayed, and since there is #3542 at the end of the URL, the browser looks for an anchor named or identified by 3542. If found, it automatically scrolls to this location. You just need to generate such an anchor in your HTML:

Data of the record 3542

Comment: Here the problem is i dont have hyperLink to edit the record. user just modify couple of fields of the row and click on save.
Comment: When they click on save, they submit a form. In this form, you have the ID of the record as a hidden field. Without it, the server can't know which record it must update. So, since you have the ID of the record, you can redirect to /displayRecords?highlightedRecord=# after the record has been saved.


How to use the method When in FluentAssertions

Question: Sometimes I have to assert that two lists have the same items. With fluent assertions this can be done like this:
class MyObject { public string MyString {get; set;} }

var o1 = new MyObject { MyString = "1    " }
list1.Add(o1);

var o2 = new MyObject { MyString = "1" }
list2.Add(o2);

list1.Should().BeEquivalentTo(list2)

But sometimes I want a specific property to be compared in a different way, like this:
list1.Should().BeEquivalentTo(list2, options => options
            .Using<string>(context => context.Subject.TrimEnd().Should().Be(context.Expectation))
            .When<string>( ??????? ));

I have tried:
it => it.SelectedMemberInfo.Name == PropertyNameHere

But SelectedMemberInfo can be null and it throws an exception when null and I dont know if I'm calling it the correct way.
Update 1: Tried, but null reference exception:
        options => options
        .Using<DateTime>(it => it.Subject.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMinutes(1)))
        .When(it =>
            it != null
            && it.SelectedMemberInfo != null
            && it.SelectedMemberInfo.Name == nameof(Y.X)));

Comment: Can you provide a [Minimal Complete Example](https://stackoverflow.com/help/minimal-reproducible-example) of what you trying to achieve?
Comment: Can you specify what is missing in my question? I think it can be understood quite easily
Comment: In this case it's not clear to me `list1` and `list2` are.

It's easier to help, if you provide a complete example I can copy/paste into an IDE and run.
Comment: Edited question
Answer: To match the MyString property, the two most used ways are either to match by type or by path.
To match MyString by type, you use WhenTypeIs<string>.
[TestMethod]
public void MatchByType()
{
    var o1 = new MyObject { MyString = "1    " };
    var list1 = new[] { o1 };

    var o2 = new MyObject { MyString = "1" };
    var list2 = new[] { o2 };

    list1.Should().BeEquivalentTo(list2, opt => opt
        .Using<string>(ctx => ctx.Subject.TrimEnd().Should().Be(ctx.Expectation))
        .WhenTypeIs<string>());
}

For the curious WhenTypeIs<TMemberType> is simply an alias for
When(info => info.RuntimeType.IsSameOrInherits(typeof(TMemberType))

To match MyString by its name, you can use When(e => e.SelectedMemberPath).
SelectedMemberPath is defined as

the full path from the root object until the current object separated by dots.

In this case the root object is MyObject, so SelectedMemberPath will be "MyString".
So this can be written as:
[TestMethod]
public void MatchByName()
{
    var o1 = new MyObject { MyString = "1    " };
    var list1 = new[] { o1 };

    var o2 = new MyObject { MyString = "1" };
    var list2 = new[] { o2 };

    list1.Should().BeEquivalentTo(list2, opt => opt
        .Using<string>(ctx => ctx.Subject.TrimEnd().Should().Be(ctx.Expectation))
        .When(e => e.SelectedMemberPath.EndsWith(nameof(MyObject.MyString))));
}

UPDATE: SelectedMemberPath was renamed to Path in v.6.0.0
Answer: The problem here is that you are trying to access a member in an object that hasn't been instantiated. Because it.SelectedMemberInfo is null, there is no member Name to access. The .NET documentation on NullReferenceException has a good explanation of this.
https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=netcore-3.1
Assuming there are no other special circumstances when SelectedMemberInfo is null, you will just want to make the expression in .When() null-safe. You can do this pretty easily with a single character (null propagation):
it => it.SelectedMemberInfo?.Name == PropertyNameHere

The way null propagation works is if the object that precedes the question mark is null, it will evaluate as a null instance of the type at the end of the statement. So in this case, if it.SelectedMemberInfo is null, this will evaluate as (string) null.
If you like extra lines, you could also do this -
it => it.SelectedMemberInfo != null && it.SelectedMemberInfo.Name == PropertyNameHere)

If there's a chance that you could have null items in the parent collection, you're also going to want a null check on that -
it => it?.SelectedMemberInfo?.Name == PropertyNameHere

Comment: Updated question and tried your suggestion but still null reference


Help with a custom field widget

Question: I am trying to create a custom field widget to be used by the taxonomy term reference field.
Basically I would like to select which taxonomy terms can be shown in the select list.
So far I am able to register the widget along with a custom settings page but when I use the widget on a node edit form. The values are not saved.
Here is the code below I have implemented a hook_widget_info hook_widget_settings_form and hook_field_widget_form from my understanding those three hooks should be enough
function my_module_field_widget_info() {
  return array(
    'my_module_term_reference_limit' => array(
      'label' => t('my module Term reference select'),
      'field types' => array('taxonomy_term_reference'),
      'description' => t('Allows you to limit the number of terms allowed in a select list'),
    ),
    'settings' => array(
        'terms' => array(),
      ),
  );
}

function my_module_utils_field_widget_settings_form($field, $instance) {
  $widget = $instance['widget'];
  $settings = $widget['settings'];
  $vocabulary = taxonomy_vocabulary_machine_name_load($field['settings']['allowed_values'][0]['vocabulary']);
  $type = $instance['widget']['type'];
  $terms = taxonomy_get_tree($vocabulary->vid);
  $options = array();
  $default_value = array();

  foreach($terms as $key => $term){
    $options[$term->name] = t($term->name);
  }

  $form = array();
  if($instance['widget']['type'] == 'my_module_term_reference_limit') {
    $form['terms'] = array(
      '#type' => 'checkboxes',
      '#title' => t('My module terms'),
      '#options' => $options,

      '#description' => t('Select compatible templates'),
  );
}
  return $form;
}

function my_module_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $settings = $instance['widget']['settings'];

 $type = $instance['widget']['type'];

  $options = array();
  foreach($settings['terms'] as $key => $value){
    if($value !== 0){
     $options[$value] = t($value);
   }
 }

$widget = $element;

  switch ($instance['widget']['type']) {
    case 'ii_term_reference_limit':
      $field['cardinality'] = 1;
      $widget += array(
       '#title' => t('my term select box'),
       '#type' => 'select' ,
       '#options' => $options,

  );
      break;
  }

  $element +=  $widget;
  return $element;

}

Thank you for your help
Comment: As an aside, `$field['cardinality'] = 1;` will have no effect as `$field` is not passed by reference
Comment: the whole example is a bot rough around the edges but your answer below solves my issue. Im sure they may be a few other issues icase anbody wants to use this example
Answer: Looks like you're just missing the column name for the field (tid).
Just before the return of the widget form function, try changing
$element +=  $widget;

to
$element['tid'] = $widget;

Help with a custom field widget


$H^{\frac12}$ norm and preimage via the trace operator

Question: In this article, at one point, a chain of (in)equalities much like the following is found:
$$\|u\|_{H^1(D_1)}=\|f\|_{H^1(\partial D_1)}\leq C\|f\|_{H^{\frac12}(\partial D_1)},$$
where $u\in H^1(D_1)$ is the harmonic extension of $f\in H^1(\partial D_1)$ and $D_1$ is the unit disk in $\mathbb R^2$. Now, using Proposition 2.2 on p. 8 here in a local way, I can convince myself that the inequality holds. However, the equality is unjustified. Now, being $u$ harmonic, the Dirichlet principle tells us that:
$$\|u\|_{H^1(D_1)}=\inf_{\substack{v\in H^1(D_1) \\ v|_{\partial D_1}=f}}\|v\|_{H^1(D_1)},$$
and this Math SE post suggests $\|u\|_{H^{\frac12}(\partial D_1)}$ equals the latter expression, which would allow us to conclude the chain works. However, I cannot seem to find a proof of this equality. So how is it proved?
PS I am happy with a reference as long as it is available online. Google books are, however, best avoided, since I have the impression that at least half the times the page(s) needed are not in the preview.
Answer: Expand $f$ into a Fourier series, $f(e^{it})=\sum_{n\in \mathbb{Z}} c_n e^{in t}$. The harmonic extension is
$$
u(re^{it})= \sum_{n\in \mathbb{Z}} r^{|n|} c_n e^{in t}
$$
The gradient squared is $u_r^2 + u_t^2/r^2$, which ends up being
$$
|\nabla u(re^{it})|^2 =
\left|\sum_{n\ne 0} |n| r^{|n|-1} c_n e^{in t}\right|^2 +
\left|\sum_{n\ne 0} r^{|n|-1} c_n (in)e^{in t}\right|^2
$$
Integrating over $t$ and using Parseval, we get
$$
4\pi  \sum_{n\ne 0}n^2r^{2(|n|-1)} |c_n|^2
$$
and then integrating  $\int_0^1 \cdots r\,dr$,
$$
4\pi  \sum_{n\ne 0}n^2 \frac{1}{2|n|}|c_n|^2 = 2\pi  \sum_{n\ne 0}|n||c_n|^2
$$
This is the $H^{1/2}$ seminorm on the circle, shown to be equal to the $H^1$ seminorm of the harmonic extension. (In both cases, constants get 0).
Comment: Shouldn't the $H^1$ norm squared equal the $L^2$ norm squared of the gradient plus that of the function? I only see the first term here...


If $a, b, c$ are the sidelengths of a triangle, show that $a^2b(a−b) +b^2c(b−c)+c^2a(c−a)\ge0$.

Question: After many days of work and some help with some helpful Math Stack Exchange community members, I have only one inequality homework question which remains unsolved:

If $a, b, c$ are the sidelengths of a triangle, show that $a^2b(a−b) +b^2c(b−c)+c^2a(c−a)\ge0$.

My attempt:
Let $a=y+z, b=z+x, c=x+y$. Then $x,y,z\ge0$.
But after substitute into the inequality, and expand, I still cannot use Muirhead.
This question is one of the starred question and I can't do it.
Can someone help me? Any help is appreciated!
Answer: Using the Ravi-substitution we get
$$xy^3+x^3z+yz^3\geq xyz(x+y+z)$$ or
$$\frac{x^2}{y}+\frac{y^2}{z}+\frac{z^2}{x}\geq x+y+z$$
Now using Cauchy Schwarz in Engelform:
$$\frac{x^2}{y}+\frac{y^2}{z}+\frac{z^2}{x}\geq \frac{(x+y+z)^2}{x+y+z}=x+y+z.$$
Comment: A open bracket is missing.
Comment: It is closed now! Thx.
Answer: Let $c=\min\{a,b,c\}$.
Thus, we need to prove that
$$\frac{a^2}{c}+\frac{b^2}{a}+\frac{c^2}{b}\geq\frac{a^2b^2+a^2c^2+b^2c^2}{abc}$$ or
$$\frac{a^2}{b}+\frac{b^2}{a}-a-b+\frac{a^2}{c}-\frac{a^2}{b}+\frac{c^2}{b}-c\geq\frac{a^2b^2+a^2c^2+b^2c^2-abc(a+b+c)}{abc}$$ or
$$\frac{(a-b)^2(a+b)}{ab}+\frac{(c^2-a^2)(c-b)}{bc}\geq\frac{(ac-bc)^2+(bc-ab)(ac-ab)}{abc}$$ or
$$\frac{(a-b)^2(a+b)}{ab}+\frac{(c-a)(c-b)(a+c)}{bc}\geq\frac{(a-b)^2c}{ab}+\frac{(c-a)(c-b)}{c}.$$
Can you end it now?
Answer: Hint
Schur inequality might be helpful
$$\sum_{cyc}a^2(a-b)(a-c) \geq 0$$
Now, the triangle inequalities like $a-c \leq b \Leftrightarrow a \leq b+c$ might be helpful.
Comment: @MichaelRozenberg ... ooops.. right ... shouldn't have done it quicky in between ... thanks for pointing out.
Comment: What happens if in your case $a-b<0$? I think you understood now that your solution is total wrong.
Comment: @Culver Kwan: There was a mistake in the last line. So, I removed it and edited the answer to be really only a hint. Anyways, your inequality is very similar to Schur's inequality, that's why it might be helpful.
Answer: The same inequality holds for bigger exponents i.e:
$$\sum_{\text{cyc}}a^pb(a-b)\geq 0$$
for $p\geq 2$ and $a,b,c$ sides of a triangle. You can prove it easily by thinking of the expression as $f(p)$, a function of $p$, and take a derivative to show $f(p)$ is non-decreasing and so
$$f(p)\geq f(2)\geq 0.$$


How do you fork and develop a globally installed Node.js NPM package?

Question: I'm trying to create a fix for a an NPM package that I rather enjoy, Wintersmith. However, Wintersmith is supposed to be globally installed (executable with wintersmith <command>) and I can't seem to run it from the root of a project where I have it installed locally manually with git clone <my fork url> with something like node ./node_modules/wintersmith/bin/wintersmith without receiving path errors:
module.js:340
throw err;
      ^
Error: Cannot find module '../lib/cli/'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (F:\web\wintersmith\node_modules\bin\wintersmith:3:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)

The only way I can figure to properly develop and test this is by manually replacing my globally installed Wintersmith package with my forked version and then executing commands using that version to test whether or not my changes are working.
Is there some workflow step that I'm missing when working with/developing global NPM packages?
Answer: You should use npm install git:// instead git clone
Install your fork like this:
npm install git://github.com/YOURNAME/wintersmith.git

You can also install it as global module use -g:
npm install -g git://github.com/YOURNAME/wintersmith.git

Answer: NodeJS eats an environment variable NODE_PATH. You can make use of that besides PATH.
This document describes it better:
http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
Answer: I can execute wintersmith like this, without having to install it globally:
$ git clone https://github.com/jnordberg/wintersmith.git
$ cd wintersmith
$ npm install               # This installs all dependencies I need for the next step.
$ npm run-script prepublish # Run the prepublish script which compiles sources to ./lib
$ bin/wintersmith

I get the usage message that it gives when there is nothing passed as arguments.
When creating a node package that is meant to be installed globally it is possible and desirable to design it so that it can be run and tested without having to install it. I was surprised that wintersmith would not be designed this way.
Generally speaking, if I had to deal with a node package that cannot be tested without being installed globally, I'd call it "defective". (Maybe there are exceptions but such exceptions are rare and they should be justified in the package's documentation.)
So, generally, if I had to deal with a package that cannot be run and tested without being installed globally, I'd look for a package providing equivalent functionality which can be run without being installed globally, or fix the faulty package.


Difference between WebDriver and HtmlUnit

Question: i have a little doubt about htmlUnit driver.Do v need to install any web browsers while performing htmlUnit testing?
Answer: No. HtmlUnit is a web browser. The difference with traditional browser is that it doesn't have a GUI (it's a headless web browser), and is driven by your Java code instead of your mouse clicks.
Comment: Should also mention that you can emulate different browsers, in case the OP is looking for that. If possible, I usually emulate for a production system, if not, Firefox. Either way, just a recommendation.


A puzzle about vector space

Question: When beginning to study the notion of vector space using the book"linear algebra and its applications" of D.C.Lay,the book give an example of vector space.It says all continuous functions on the interval [a,b] could be a vector space. Shouldn't a element of vector space be a vector?Why a function in the case above?
Comment: Once you start with (abstract) vector spaces in general, you should let go the physical interpretation of a vector as a geometrical object, e.g. "an arrow". Look at the definition of a vector space (without thinking about your previous notions of vectors) and then consider "vector" as a new object: *an element of a vector space*. A vector space could then be the continuous functions on [a,b], the elements ("vectors") are then functions.
Answer: I suppose it depends on your definition of a vector. I assume when you think of a vector you think about something like $(1,2)$ or $(1,\pi,6,3.3)$ and the associated geometric meanings.
Another way to define a vector is a vector is any element of a vector space. Look at the definition of a vector space does it specify that the vectors must be like the form above? No it doesn't and there is no reason why they should be.
For example we can define vector spaces over sets of polynomials where the vectors are polynomials and similarly we can define vector spaces of matrices.
You must get used to thinking about vectors in this new way and appreciate it.
It is often more convenient and meaningful to think about vectors this way as it becomes easier to work with. For example if we considered only the geometrical interpretation then we would not really be able to interpret any vectors above $3$ dimensions.
Answer: In linear algebra, an important concept is abstracting concepts of its fundamentals. Typically, you may have thought of a vector to have specific magnitude and length and fit some sort of pre-conceived definition. In the study of linear algebra, this notion does not typically exist. We can abstract this idea and apply it to many objects, so long as it fits with our well-defined rules for what is a "vector space" and a "vector" (in the most basic terms, a set of mathematical objects that abide by certain properties we have decided on).
A matrix is a vector, a number ($5, 2.1, 4$) is a vector. In fact, the real numbers $\mathbb{R}$ are a vector space. The well-defined rules (axioms) can be found here:
https://en.wikipedia.org/wiki/Vector_space
Answer: You can also think of a (continuous) real-valued function on $[a,b]$ as an 'uncountable-tuple' where each 'component' is indexed by a real number in $[a,b]$.
Or conversely, you can think of a vector in $\mathbb{R}^n$ as a function from $\{1,2,\dots,n\}$ to $\mathbb{R}$, where $f(i)=$ the $i$-th component of the vector.

A puzzle about vector space


How do I correct the "spring integration is a one-way 'MessageHandler' and it isn't appropriate to configure 'outputChannel'" exception?

Question: I have reviewed Spring Integration and DSL upgrade - one-way 'MessageHandler' and it isn't appropriate to configure 'outputChannel' Error , and it looks to me like the shape of my solution is here, but the solution is expressed in a way that doesn't make sense to me.
spring-integration parallel split-route-aggregate flow fails due to one-way MessageHandler is much more understandable, but I'm not seeing where the handler method (whatever it is) is returning a void to give me this hiccup.
The exception spring integration is a one-way 'MessageHandler' and it isn't appropriate to configure 'outputChannel' is being thrown for the .aggregate() factory method. The queues are constructed dynamically at runtime based on metadata collected by the application.
Based on debugging into the framework, it looks like the .routeToRecipients(r -> this.buildRecipientListRouterSpecForRules(r, rules)) clause is returning a void. Adding a .defaultOutputToParentFlow() to the recipientListRouter cuts out he exception, but is probably not the right solution since the flow doesn't actually start when I make this adjustment.
I'd welcome any suggestions.
Code snip:
        StandardIntegrationFlow flow = IntegrationFlows
            .from(setupAdapter,
                    c -> c.poller(Pollers.fixedRate(1000L, TimeUnit.MILLISECONDS).maxMessagesPerPoll(1)))
            .enrichHeaders(h -> h.headerExpression("xxx", "payload[0].get(\"xxx\")")
                    .headerExpression("yyy", "payload[0].get(\"yyy\")")
                    )
            .split(tableSplitter)
            .enrichHeaders(h -> h.headerExpression("aaa", "payload[0].get(\"aaa\")")
                    .headerExpression("bbb", "payload[0].get(\"bbb\")")
                    )
            .channel(c -> c.executor(stepTaskExecutor))
            .routeToRecipients(r -> this.buildRecipientListRouterSpecForRules(r, rules))
            .aggregate()
            .handle(cleanupAdapter).get();

    return flow;

private RecipientListRouterSpec buildRecipientListRouterSpecForRules(RecipientListRouterSpec recipientListSpec,
        Collection<RuleMetadata> rules) {
    rules.forEach(
            rule -> recipientListSpec.recipientFlow(getFilterExpression(rule), f -> createFlowDefForRule(f, rule)));

    return recipientListSpec;
}

EDIT: Revised code for solution based on discussion below:
        StandardIntegrationFlow flow = IntegrationFlows
            .from(setupAdapter,
                    c -> c.poller(Pollers.fixedRate(1000L, TimeUnit.MILLISECONDS).maxMessagesPerPoll(1)))
            .enrichHeaders(h -> h.headerExpression("xxx", "payload[0].get(\"xxx\")")
                    .headerExpression("yyy", "payload[0].get(\"yyy\")")
                    )
            .gateway(new DirectChannel())
            .split(tableSplitter)
            .enrichHeaders(h -> h.headerExpression("aaa", "payload[0].get(\"aaa\")")
                    .headerExpression("bbb", "payload[0].get(\"bbb\")")
                    )
            .channel(c -> c.executor(stepTaskExecutor))
            .routeToRecipients(r -> this.buildRecipientListRouterSpecForRules(r, rules).defaultOutputToParentFlow())
            .aggregate()
            .handle(cleanupAdapter).get();

Answer: You cannot continue the flow after routeToRecipients(). I mean your .aggregate() is causing that error since a RecipientListRouter is not an AbstractReplyProducingMessageHandler, but just plain AbstractMessageHandler and it knows where to send a message after routing function only according the mapping provided for this router type.
See defaultOutputToParentFlow() JavaDocs for more info:
/**
 * Make a default output mapping of the router to the parent flow.
 * Use the next, after router, parent flow {@link MessageChannel} as a
 * {@link AbstractMessageRouter#setDefaultOutputChannel(MessageChannel)} of this router.
 * @return the router spec.
 */
public S defaultOutputToParentFlow() {

So, it would continue your flow only if it doesn't match the recipients mapping.
The ignoreSendFailures(true) has to be set, too, to let it to not fail with an error, but rather fallback to this default output.
Comment: I think we need to see your new flow configuration , but that's probably need to be done in the separate SO thread
Comment: Thank you @Artem Bilan. Reading between the lines here, I'm missing some key concept embodied in the classes, and using a completely incorrect mechanism for splitting to subflows then later rejoining to the main flow. Is this corrrect?
Comment: You need to think about a gateway on top of recipient list router . Then an aggregator to re-join results from those recipient sub-flows. And only after that you can send reply back to the gateway and continue the main flow.
Comment: Does each recipient flow requires its own gateway? Or is a single gateway referenced by all recipient flows required?
Comment: Single gateway from the main flow to wait for aggregated reply
Comment: I think I understand better. I have updated my code snip as I understand it now, and am reading "Pro Spring Integration" to try to further my understanding.
Comment: The flow constructs now, but does not appear to start.

The thread appears to be claimed from the thread pool when flow.start() is invoked, but a breakpoint set in JdbcPollingChannelAdapter.doPoll() is never hit. Logs show nothing from org.springframework.integration
Comment: A simplified flow for the :won't start" has been posted at https://stackoverflow.com/questions/65499125/sprint-integration-flow-wont-start
Comment: Is there a good primer for the concepts here? All of the documentation and books I have found on Spring Integration start with the assumption that you already know how these components tie together and when to use them. Monkeying it until it works is not a viable solution, nor is harassing you on SO every time I hit a minor NOOB roadblock.
Comment: Right. You need to know what is EIP, first of all, to understand what is a message, endpoint and channel between them. Then you need to learn what is Spring and its application context with beans and some infrastructure . And only after that you come to Spring Integration with its concept to implement EIP on top of Spring Framework. If you miss some pieces (as we all do), then you go try-n-fall road until you got used to everything you need from these tools. I don't see nothing problematic in the asking questions. This is really was the way for me when I learned Java 20 years ago...
Comment: Sadly, I have a very short timeframe for this. The Java is super easy, it's the rest of this particular stack that is proving hard to wrap my head around.
Comment: Ok. So, do your best with whatever you know already introducing Spring features gradually as you learn them.
Comment: (Venting) Your help throughout has been valuable, but we are missing something very core that you are taking for granted. After almost a year and multiple SO questions, we have achieved nothing and are at the end of our rope. Every time we think we have made a step forward, we appear to be further from a solution. Constructing and debugging this dead simple flow has been a year long project for several experienced java programmers, with no solution. Do you have any ideas?
Comment: The recipient list router (or better to say any router) is a one-way component in the flow. It cannot answer directly to the next channel, just because it is multi-channel (or dynamic) output component. See its pattern: https://www.enterpriseintegrationpatterns.com/MessageRouter.html. The flow is linear, and cannot have several channels to branch. That's how it happens the router can be only in the end of flow. We probably need to state that clearly in the docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-routing.html#router
Comment: That may help, and works for our flow. After routing, its jdbc fetch -> jdbc CRUD -> jdbc cleanup -> done.  I noticed in your examples you have bridge() at the end of every subflow. When we use bridge(), the component complains it has no reply channel. Is there a clean way to say "this is the end of the flow"? Would giving hte null channel as the reply channel do the trick?
Comment: Yes, Will do. That's one of those corner-cases when `nullChannel` is useful: https://docs.spring.io/spring-integration/docs/current/reference/html/core.html#channel-special-channels


Proguard Obfuscate java code to single line & identifiers with _(numbers)

Question: I've used proguard to obfuscate my jar file. is there any way to remove newline in java code and specify identifiers to have _(numbers) instead of chars using proguard?.
Regards,
Rajan.M
Comment: Proguard obfuscates byte code. As there is no new line inside your byte code, I can't understand your question on that matter.

Also, can you explain why you want to have such control over obfuscation of variable names in proguard ?
Comment: What is the purpose (of obfuscating your code at all)? Is your code so brilliant and/or proprietary that you have to hide it? If it is proprietary (contains trade secrets) than keep it on network/web accessible server and expose webservices **ONLY**. If (you think that) it is so brilliant let others learn from it.   Or if it is so rubbish let others correct it.
Comment: @sincolas then how come decompilers displays java code in multilines?. and i prefer numbers than chars to obfuscate inorder to make it bit more hard to read.
Comment: @German Arlington its proprietary code i'm working with embeded within desktop application.
Answer: ProGuard only reads and writes Java bytecode, not source code. By default, it picks obfuscated names a, b, c, etc., but you can specify your own set with the option -obfuscationdictionary.
Comment: I created java file with class and functions aligned in single line and compiled to get class file then used proguard for obfuscation but the output we got is properly aligned classes and functions??


Django search for static parts of the site

Question: I am planning to use Django-Haystack to add a search component to my site. This will take care of the data I have in my models.py. I however also want data which is not in a model, but part of templates to be searchable. How can I get this.
Answer: There is a django app called haystack-static-pages that should help here. It's not been updated for a while so I doubt it will work with haystack 2.0, but I hope this might be of some help to you:
https://github.com/trapeze/haystack-static-pages


A message saying "confusing indentation" and "assign return value to new variable"

Question: I have been working on this project, the project runs fine, but it shows "confusing indentation" and "assign return value to new variable" warnings and I have no idea what it's about. This is the line with the warning:
System.out.printf("The sum of the squares: %.0f\n", tsquee);
The following is the complete project. Thanks!
    double n = 0;
    while (n < 25)
    {
        n = n + 1;
        if (n > 25)
            break;

        System.out.printf("%3.0f%15.2f%16.2f%17.2f%15.2f\n", n, Math.cbrt(n), Math.sqrt(n), Math.pow(n, 3), Math.pow(n, 2));

    }

    {
        double tsquee = 0.0, tsqueer = 0.0;
        int csq = 0, ccube = 0;

        for (n = 0; n <= 25; n++)
            tsquee += Math.pow(n, 2); tsqueer += Math.sqrt(n);

        for (n = 0; n <= 25; n++)
        if (Math.pow(n, 2) > 250)
        {
            csq++;
        }
        else if (Math.pow(n, 3) > 2000)
        {
            ccube++;
        }

        System.out.printf("The sum of the squares: %.0f\n", tsquee);
        System.out.printf("The sum of the square roots: %.2f\n", tsqueer);
        System.out.println("The number of squares greater than 250: " + csq);
        System.out.println("The number of cubes greater than 2000: " + ccube);
    }

}

Kay
Comment: The warning is quite specific. Your indentation is very, very confusing -- for example, look at your `if/else` in the `for`. It looks like it's on the same level, and therefore occurs after the `for`, not inside.
Comment: It's a good idea to use `{` and `}` whenever you use `for`, `while`, `do`, `if` or `else`.  Omitting them can lead to errors.  I think  every Java programmer has fallen into this trap at some point.
Answer: The "confusing indentation" warning is likely because the set of curly braces that start after the while loop and go to the end are not needed. Also, your for loop syntax is incorrect. I think what you want is this:
for (n = 0; n <= 25; n++)
{
    if (Math.pow(n, 2) > 250)
    {
        csq++;
    }
    else if (Math.pow(n, 3) > 2000)
    {
        ccube++;
    }
}

but I'm not sure. You need to enclose the code you wanted to loop through inside curly braces just like you've done with your while loop.
Also, since your two for loops have identical bounds and conditions, you could combine them into one for loop:
for (n = 0; n <= 25; n++)
{
    tsquee += Math.pow(n, 2);
    tsqueer += Math.sqrt(n); // I would also put these on separate lines

    if (Math.pow(n, 2) > 250)
    {
        csq++;
    }
    else if (Math.pow(n, 3) > 2000)
    {
        ccube++;
    }
}


How do I execute a function every 3 months?

Question: What's the proper way to execute a function every 3 months? Watchdog variables don't seem to be available after a certain time. I could create another table to insert the execute function date to compare, but it doesn't seem to be the best approach.
The functionality of such functions are:

Send an eMail
Tag an inactive user
Answer: watchdog() is not appropriate place for storage; the $variables parameter is for formatting the display of variable data (e.g. the USERNAME in "User USERNAME has logged in"), not for long term storage of application data.
Instead, use a combination of hook_cron() and the persistent variable functions (variable_get() and variable_set()) to execute a cron task that remembers when it was last run.
/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Look up last time MYMODULE_function() was run compared to 3 months ago.
  if (variable_get('MYMODULE_function_last_run', 0) <= strtotime('-3 month')) {
     // Run my function
     MYMODULE_function();

     //Store the time when MYMODULE_function() was last run.
     variable_set('MYMODULE_function_last_run', time());
  }
}

Answer: The Rules module together with Rules Scheduler (a sub-module of it), can be used for executing functions such as sending eMails (as in your comment below the question), as explained in the steps below,.
Step 1: Create a field to store the "next renewal" date
Add a field to the "user" entity with machine name (say) field_next_renewal. Allow only 1 date (to store the "next" date for a sending an eMail to some user, eg about some renewal).
Step 2: Create a Rules "Component"
Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Reminder about your next renewal",
          "message" : "This is a reminder about your next renewal on [user-to-notify:field_next_renewal] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.
Step 3: Create a "Rule" using the Rules Component
Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):
{ "rules_email_user_every_3_months" : {
    "LABEL" : "eMail user every 3 months",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_renewal" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-next-renewal" ], "value" : "+6 month" } },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-renewal",
            "date_offset" : { "value" : 7776000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

The above rule refers to the Rules Component from the previous step.
Note that the 7776000 is the equivalent of 3 months in seconds. You may want to reduce that a bit, e.g. with a number of seconds equivalent to a few days (or a week or so). That way the eMail will be triggered a few days before the actual renewal.
Step 4: tagging inactive users
By creating an extra rule similar to the rule in step 3, you could also "flag" inactive user using the integration of Rules with the Flag module. That would be a solution for tagging such users (as in your comment below the question) also. The only remaining challenge about that would be to find the Rules Condition to identify "inactive" users.
Comment: I suppose, that if I trigger a Rule to send eMail to inactive users, it will be possible to identify who was inactive at a certain date?
Comment: I cannot answer "that" yet, first I need to know what "you" consider as "inactive" for a user. Can you explain what you call "inactive"? Like is it "last login date is at least X days or months ago"?
Comment: The purpose of this function is to identify all users who were inactive on the site for the last 3 months, send an email to notify, and after 1 week, if that user doesn't enter the site, proceed to delete his account.
Comment: OK, this extra comment makes it a little more clear, but: **(1)** that's really like a new question, why not post a new question about that (also because changing the content of a question to a new question is not allowed according to the rules on this site, which I did not invent ...) and **(2)** since you marked Shawn's answer as accepted, I assume Shawn's answer is an answer to your original question here and **(3)** repeat from my prior comment (which you still did not answer, sorry): ***Can you explain what you call "inactive"?***
Comment: I was searching for a simple functionality that trigger a function after 3 months, but after reading your answer, I saw a lot more possibilities, that is why I was going more deep on my prior question. You probably are right, I should posted it as another question. In order to at least answer your question, I mark a User as inactive, before 3 months without a login on the site.
Comment: OK, "now" I understand what "you" call an active user (which makes sense). Good to know that my additional answer inspired you somehow to see more possibilities. I suggest you post like a followup question (eventually referring to this answer if you need/want). But make sure to not make it a too broad question (to avoid a valid/complete answer would be like writing a manual). Or do you think I should post my own question with a summary of some of your comments here, and post my own answer (with about 4 steps ...) to it also?


The most searched keyword of the default search?

Question: Is there a way, or a module, to get the most searched keyword of the site's default search?
Answer: You can check the "Top Search Phrases" report at "/admin/reports/search". This will give you a count of the search phrases used. It doesn't make it out by individual keyword, but at least gives you an idea of what people are searching for.


Convert $3^n$ to some form of $2^n$

Question: I am not from Maths field, but I need your help to convert the $3^n$ form to $2^n$. I need to change the base from $3$ to $2$. The resultant expression can be of any form.
Comment: $2^n=e^{nln(2)}=e^{nln(2)/ln(3)ln(3)}=3^{nln(2)/ln(3)}$
Answer: $$3 = 2^{\log_23}$$
Therefore $$3^n = (2^{\log_23})^n=2^{n\log_23}$$

Convert $3^n$ to some form of $2^n$


Run command remotely on Windows computer

Question: I have a Windows Server 2008 instance on Amazon EC2 (Amazon's cloud compute platform, which provides VMs in the cloud). It has an external IP, and I have an admin account on the box. I would like to 'bootstrap' this instance remotely i.e. I want to run commands to download, install and configure apps on it, all without having to log on even once. Also, I cannot use psexec on the source computer.
I have figured out how to do this to a remote, domain-joined computer using WMI. However, I have NOT been able to do for a remote computer on EC2. Here are some specific restrictions:

The remote computer is not part of my domain, hence no Kerberos
The remote computer does not have a cert I trust, or vice versa

I am sure I am running into to some auth/trust restriction. Is there any way I can run a single command on the remote, given that I have admin privileges? I'm not tied down to using WMI, but I do need to run a command somehow. Feels like this should be a solved problem.
Comment: Have you considered installing SSH on the server? (via cygwin)
Answer: While it's not directly the answer you're looking for, bear in mind that you can build a custom AMI that already contains the appropriate bootstrapping code on the server when it comes online. This is by far the most common solution to the problem you're facing, and is, in fact, the way Amazon expects you to solve this problem.
Simply add a program that, on startup, connects to a server you control and downloads a list of commands for it to run. Alternately, you can add a program that listens for inbound connections which, again, send the server a set of instructions to run. Obviously you can integrate any form of security you want.
There are several tutorials out there on rebuilding AMI images. Here's one from amazon:
http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?creating-an-ami-windows.html
Comment: That works for EC2. How about for providers like Rightscale or Linode?
Comment: Rightscale is a solutions provider for EC2. Linode also uses Xen. The solution is roughly the same, though the details might change a bit.
Answer: I'm running Windows on EC2 and am able to do a lot of the things you're referring to -  you're right this problem has been solved. The best solution being offered by cloud management providers currently for Windows, IMHO, is RightScale's recent addition for Windows support.
I use RightScale's FREE developer account and they enable you to do exactly what you're referring to above. It's a slight shift in tradtional Windows management. They have the concept of Chef Recipes (or scripts) that are downloaded by the instances and run on boot time. These are script that you can use to confgure/install software. It's actually a very compelling tool and surprisingly powerful. If you do not wish to use any cloud management providers like Rightscale or Scalr.net or Kaavo etc, I'd suggest running your own Chef server or use similar tools (Puppet, CfEngine etc), and use that to configure and deploy your cloud instances. Chef's latest release supports Windows clients.
If you're simply looking for a quick win to issue commands remotely from your laptop/desktop to your cloud instance, then the you can simply install Windows Management Framework which comes with Powershell 2.0. Using Powershell 2.0, you can issue remote commands ("Invoke-Command", much like ssh) and have it execute pretty much whatever you want on your instance - single lines commands or entire scripts. Authentication is quite simple w/o a Windows domain. You simply have to create an admin user on your desktop with the same username/password as your instance and Invoke-Command will work.


How to theme the separate page for editing profiles provided by Profile2

Question: I'm using D7.
I'd like to theme the separate page for editing profiles provided by Profile2 module(whose URL is MYWEBSITE.com/profile-MYPROFILE/[uid]/edit).
I searched and found the way that somebody has already suggested. And, by reference to that, I tried the way below. But it doesn't work. Can anybody tell me where I made a mistake?
Here is the way I tried but that didn't work...
1st: Create the customthem_theme() below into  template.php file of customtheme theme.
function customtheme_theme() {
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'customtheme') . '/templates',
        'template' => 'user-profile-form',
        'preprocess functions' => array(
             'customtheme_preprocess_user_profile_form'
        ),
    );
    return $items;
}

2nd:  Create the template file user-profile-form.tpl.php and place it in the templates folder of custometheme.
3rd: Code the fields I want to display on user-profile-form.tpl.php
for ex

<?php

print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
?>

         <?php  print render($form['profile_MYPROFILE']['field_MYFIELD']); ?>

I'm still very new to drupal and, honestly, don't figure out how its system works yet. I'm sorry if this is a very easy mistake to you.
Thanks.
Answer: Change where it says customtheme to the actual theme name you are using.
for example if you are using bartik:
function bartik_theme() {
'path' => drupal_get_path('theme', 'bartik') . '/templates',
'preprocess functions' => array(
         'bartik_preprocess_user_profile_form'
    ),

The files should be located in your theme folder.
Comment: Thank you for answering, Akko.
Actually, I tried the way you suggested on.
I coded it after
 [return _zen_theme($existing, $type, $theme, $path);]
within function_zen_theme(). But it didn't work. Do you know where I made mistake?
Comment: Can you show me the code of your comeplete theme function please? Then it's easier to see where you went wrong.


Quais são as boas práticas para se trabalhar com Banco de Dados Legado em Django?

Question: Tenho um banco de dados legado e gostaria de saber quais boas práticas para nome de tabelas, ou dicas de como usar inflections(como no Rails) para Django na última versão.
Comment: Bem-vindo ao site, user1320! Seria possível editar sua pergunta para torná-la mais clara e específica? Por exemplo, você quer saber se o Django possui algum padrão de nomenclatura de tabelas, ou "boas práticas" em geral (o que seria um pouco amplo)? Sugiro mostrar exemplos de nomenclatura da sua base legada, e o tipo de resultado que quer atingir. Obrigado!
Answer: A "melhor prática" seria deixar que o próprio Django atribuísse os nomes das tabelas e dos campos, mas isso não se aplica ao seu caso, certo? Se tem um banco de dados legado, pode manter sua estrutura tal como está - não há necessidade de fazer modificações (exceto em um caso, como explicarei a seguir).
Criando modelos automaticamente
O Django possui uma ferramenta chamada inspectdb para facilitar a criação dos seus modelos, quando você já possui um banco de dados pronto. Você pode usá-la para "dar a partida", mas em geral adaptações serão necessárias.
Modelos gerenciados ou não
O django possui uma ferramenta chamda syncdb (nas versões futuras, será feito obsoleto e substituído por migrate) que cuida da criação das tabelas, seus campos e índices automaticamente, a partir dos modelos definidos. Nas versões futuras, também contará com ferramentas de migração de esquema. Quando você usa um modelo assim, ele é chamado gerenciado (managed).
Caso você não queira fazer uso dessa funcionalidade - criando e mantendo suas tabelas de outra forma - você pode marcá-lo como não gerenciado (unmanaged). Isso é feito através de um atributo na classe Meta do seu modelo:
class Pessoa(models.Model):
    id = models.IntegerField(primary_key=True)
    primeiro_nome = models.CharField(max_length=70)
    class Meta:
        managed = False
        db_table = 'nome_da_tabela'

Note que o fato da tabela já existir não significa automaticamente que você precise de um modelo não gerenciado - você pode pegar a tabela do jeito que está, e deixar que o Django te auxilie nas futuras migrações de esquema. Isso é uma opção sua.
Nomes de tabelas e de colunas
Se você não especificar nada, o Django procurará/criará tabelas e colunas com um nome padronizado, inferido a partir do nome de sua app e os nomes dos seus modelos e campos. Se você precisar especificá-los manualmente, basta usar db_table (como já demonstrado no exemplo acima) para o nome da tabela e/ou db_column para os nomes das colunas:
class Pessoa(models.Model):
    id = models.IntegerField(primary_key=True, db_column="pessoa_id")
    primeiro_nome = models.CharField(max_length=70, db_column="nome")
    class Meta:
        managed = False
        db_table = 'nome_da_tabela'

Também há outras opções para se customizar a integração com o DB (como db_index e db_tablespace), consulte a documentação do Django para mais detalhes.
Toda tabela precisa de uma chave primária
Esse é o único caso em que talvez uma adaptação nas suas tabelas seja necessária. Para o ORM do Django funcionar, é necessário que toda tabela tenha uma chave primária, e essa chave primária tem de ser simples (i.e. uma única coluna - não pode ser uma chave composta). Se você não especificar nada, o Django assumirá que você possui um campo númérico chamado id. Se você precisar especificar, basta usar a propriedade primary_key, como já demonstrado nos exemplos anteriores.
Sempre que possível, use o nome das tabelas no singular
Levou um tempinho pra eu descobrir o que eram "inflections", mas pelo que eu entendi é aquela funcionalidade onde o Rails automaticamente "pluraliza" o nome da tabela pra você, certo? Não há nada parecido com isso no Django, o comportamento padrão é usar o nome no singular mesmo para as tabelas (e na minha opinião esse é o ideal - pluralizar introduz uma complicação desnecessária para resolver um problema que não existe).
Se você realmente precisa que os nomes estejam no plural, use db_table manualmente como explicado acima.
Answer: As database views também podem ser utilizadas nos seus models, para isso inclua no inspectdb o parametro --include-views, entretanto, providencie a inclusão de uma chave primária em suas views, como @mgibsonbr já citou, são necessárias.
CREATE OR REPLACE VIEW ... AS
   id ROW_NUMBER() OVER(),
   field1 ...
   fieldn ...


Calculate $\int {\frac{{\sqrt {x + 1} - \sqrt {x - 1} }}{{\sqrt {x + 1} + \sqrt {x - 1} }}} dx $

Question: Calculate
$$\int {\frac{{\sqrt {x + 1}  - \sqrt {x - 1} }}{{\sqrt {x + 1}  + \sqrt {x - 1} }}} dx
$$
My try:
$$\int {\frac{{\sqrt {x + 1}  - \sqrt {x - 1} }}{{\sqrt {x + 1}  + \sqrt {x - 1} }}} dx = \left| {x + 1 = {u^2}} \right| = 2\int {\frac{{(u - \sqrt { - 2 + {u^2}} )}}{{u + \sqrt { - 2 + {u^2}} }}du}
$$
I tried to do first Euler substitute:
$$\sqrt { - 2 + {u^2}}  = {u_1} - u
$$
But it did not lead me to the goal. Any thoughts will be appriciated.
Comment: Multiply the numerator and the denominator by the numerator.
Answer: Try
$$\left (\sqrt{x+1}+\sqrt{x-1} \right )\left (\sqrt{x+1}-\sqrt{x-1} \right ) = 2$$
Then the integral is
$$\frac12 \int dx \, \left (\sqrt{x+1}-\sqrt{x-1} \right )^2$$
which is
$$\int dx \left (x -  \sqrt{x^2-1}\right ) $$
Can you take it from here?
Comment: (↑) As it happened, I posted more or less the same answer as you. I've deleted mine...
Answer: $$\begin{eqnarray*}\int\frac{\sqrt{x+1}-\sqrt{x-1}}{\sqrt{x+1}+\sqrt{x-1}}\,dx &=& \int\frac{2x-2\sqrt{x^2-1}}{2}\,dx\\ &=&\; C+\frac{x^2}{2}-\frac{x}{2}\sqrt{x^2-1}+\frac{1}{2}\log\left(x+\sqrt{x^2-1}\right).\end{eqnarray*}$$


postfix catchall user not found in virtual alias table

Question: My task is to create a postfix config that accepts all mail from all domains, recipients, etc. and forwards them to a catchall mailbox. This may be further filtered in future and indeed the config will need to be latered in another environment so that mail goes through to the intended recipient.
Here's an abbreviated main.cf:
....
myhostname = mailserver.fqdn
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydestination =
myorigin = localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.168.5.0/24
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = 192.168.5.43, 127.0.0.1
inet_protocols = all

virtual_alias_maps = pcre:/etc/postfix/virtual

virtual_mailbox_base = /var/vmail
virtual_minimum_uid = 2222
virtual_transport = virtual
virtual_uid_maps = static:2222
virtual_gid_maps = static:2222
....

/etc/postfix/virtual:
/.*/     catchall
/catchall\@localhost/ catchall

Other machines are configured to use this mail server as a relayhost, and when mail makes it to here, this appears in the log:
Nov 28 10:08:10 mailserver.fqdn postfix/error[23768]: 5EA9BBD9F5: to=<catchall@localhost>, orig_to=<email@example.com>, relay=none, delay=0, delays=0/0/0/0, dsn=5.1.1, status=bounced (User unknown in virtual alias table)

I'm probably missing something obvious, is it the presence of alias_maps = hash:/etc/aliases?
Also, if all goes well, can I expect the catchall mailbox to be created automatically, or is there another config item needed?
Answer: You can test the outcome with postmap -q "firstname.lastname@example.com" pcre:/etc/postfix/virtual. It should return catchall. What may happen here is that the /.*/  catchall also includes the catchall@localhost, making it to loop back to itself and eventually not resolved to any real user.
If you only have a certain domain and its subdomains, it would be more safe to use:
/@((\w[\w\-]*)\.)+example\.com/ catchall

Then, handle the localhost with $local_transport mail delivery transport using
mydestination = localhost

Now, your catchall@localhost may be a real local user or an alias defined in /etc/aliases.
Comment: Hmm, that seems to relay the mail, which is actually what I don't want. I'd like the "catchall" user to receive all mail. For testing, I created a UNIX user "joeschmo" and added `catchall:       joeschmo` to `/etc/aliases` and ran `newaliases`
Comment: Gah! It seems I had a correct configuration a few hours ago, but didn't realise and have since changed it! There are lines like `Nov 28 14:50:56 mailserver.fqdn postfix/local[9353]: B36F4BD8F4: to=, orig_to=, relay=local, delay=0.01, delays=0.01/0/0/0, dsn=2.0.0, status=sent (delivered to mailbox)`. Very frustrating!
Comment: The above answer is correct, but for a solution to the requirements stated in the first paragraph, I answered my own original question here: https://serverfault.com/a/886114/87359, if anyone's interested
Answer: Just editing the /etc/postfix/virtual file is not enough to make the changes take affect. You must run the postmap command to make postfix read the file, like so:
/usr/sbin/postmap /etc/postfix/virtual

This creates a new file called /etc/postfix/virtual.db and the aliases are now loaded into postfix.
Comment: Sorry - I should have stated that I'd already done this, and tested using `postmap -q ...`
Comment: Also, this is not the typical `hash:/etc/postfix/virtual` that needs the `.db` file, but a [pcre table](http://www.postfix.org/pcre_table.5.html), `pcre:/etc/postfix/virtual`.


Probability mass function for the first non-increasing sample from a random sequence

Question: Consider a sequence of random numbers drawn IID from some distribution $g(x)$. How would I determine the distribution of the value of the first sample from that sequence which is not greater than all previous samples? What about the special case where $g(x)$ is uniform over $[0, 1]$?
Example: Some example IID sequences drawn from $U(0,1)$ are
0.35, 0.29, 0.19, 0.64, ...
      ^^^^
0.33, 0.35, 0.22, 0.62, ...
            ^^^^
0.21, 0.01, 0.98, 0.11, ...
      ^^^^
0.59, 0.77, 0.93, 0.17, ...
                  ^^^^

The first non-monotonic samples are 0.29, 0.22, 0.01, 0.17. I'm interested in the distribution function for these values, either in the general or the $U(0,1)$ case.
Comment: Possible duplicate of [Brain-teaser: What is the expected length of an iid sequence that is monotonically increasing when drawn from a uniform \[0,1\] distribution?](https://stats.stackexchange.com/questions/350923/brain-teaser-what-is-the-expected-length-of-an-iid-sequence-that-is-monotonical)
Comment: Actually, it looks like the continuous case is completely covered by the answer [here](https://stats.stackexchange.com/questions/350923/brain-teaser-what-is-the-expected-length-of-an-iid-sequence-that-is-monotonical) (*mutatis mutandis* in relation to the shift-by-one in the definition of the variable); I will leave this open for the moment (pending clarification on the above question).
Comment: Note that I'm not asking about the *length* of the sequence, but rather the value of the first non-monotonic sample. I'm interested in the continuous case only.
Comment: Is this a continuous variable in your more general case? (the continuous case is really straightforward; the answer is the same for all continuous distributions)  Or do you seek to cover discrete variables? What about discrete/continuous mixtures?
Comment: Yep, got it now; you want he unconditional distribution of $X_L$ (where $L$ is defined as the position of the first "dip")
Comment: Some pseudo code: Do[If[$y_{i-1}>y_i,$Print("i; ",i);exit loop],($i,2,n$)]
Comment: Hint: the solution for the Uniform$(0,1)$ case easily produces the solution for the continuous case.  You might find it easier to begin by finding the distribution of the value that immediately precedes the first dip and then consider the distribution of next value conditional on it not being greater than that.
Answer: Let $X_1,X_2,X_3,... \sim \text{IID } G$ be your exchangeable sequence of random variables and define $N \equiv \max \{ n \in \mathbb{N} | X_1 < X_2 < \cdots < X_n \}$, which is the length of the largest increasing portion at the start of the sequence.  You are looking for the distribution of the random variable $X_{N+1}$, which is the first value that is not greater than all the previous values.  This question is tractable if the distribution $G$ is continuous, but it gets much more complicated if the distribution has any discrete part, since that requires dealing with ties.  For simplicity, I am going to show you the answer that holds when you have a continuous distribution.

Some preliminary work: We will use $G$ to denote the (continuous) distribution function and $g$ to denote the corresponding density function.  In this related question it was established that the mass function for $n$ is:
$$p_N(n) = \mathbb{P}(N=n) = \frac{n}{(n+1)!} \quad \quad \quad \quad
\text{for all } n \in \mathbb{N}.$$
Since $N=n$ requires that $X_1< \cdots <X_n \geqslant X_{n+1}$ (and the maximum is invariant to the order) we also have:
$$\mathbb{P}(X_n \leqslant r | N=n) = \mathbb{P}(X_i \leqslant r)^{n+1} = G(r)^{n+1},$$
which gives the corresponding density:
$$p(X_n = r|N=n) = (n+1) g(r) G(r)^n.$$

Finding the target density: Using the above results we have:
$$\begin{equation} \begin{aligned}
p(X_{N+1} = x|N=n)
&= \int p(X_{n+1} = x | X_n = r, N=n) \ dP(X_{n} \leqslant r | N=n) \\[6pt]
&= \int \limits_x^\infty p(X_{n+1} = x | X_n = r, N=n) \cdot p(X_{n} = r | N=n) \ dr \\[6pt]
&= \int \limits_x^\infty p(X_{n+1} = x | X_{n+1} \leqslant r) \cdot p(X_{n} = r | N=n) \ dr \\[6pt]
&= \int \limits_x^\infty \frac{g(x)}{G(r)} \cdot (n+1) g(r) G(r)^{n} \ dr \\[6pt]
&= g(x) \int \limits_x^\infty (n+1) g(r) G(r)^{n-1} \ dr \\[6pt]
&= g(x) \Bigg[ \frac{n+1}{n} \cdot G(r)^{n} \Bigg]_{r=x}^{r \rightarrow \infty} \\[12pt]
&= \frac{n+1}{n} \cdot g(x) (1 - G(x)^n). \\[6pt]
\end{aligned} \end{equation}$$
Hence, we have:
$$\begin{equation} \begin{aligned}
p(X_{N+1} = x)
&= \sum_{n=1}^\infty \ p(X_{n+1} = x | N=n) \cdot \mathbb{P}(N=n) \\[6pt]
&= \sum_{n=1}^\infty \ \frac{n+1}{n} \cdot g(x) (1 - G(x)^n) \cdot \frac{n}{(n+1)!} \\[6pt]
&= g(x) \sum_{n=1}^\infty \ \frac{1 - G(x)^n}{n!} \\[6pt]
&= g(x) \sum_{n=0}^\infty \ \frac{1 - G(x)^n}{n!} \\[6pt]
&= g(x) ( e - e^{G(x)} ). \\[6pt]
\end{aligned} \end{equation}$$
The corresponding distribution function is:
$$\begin{equation} \begin{aligned}
\mathbb{P}(X_{N+1} \leqslant x)
&= \int \limits_{-\infty}^x g(r) ( e - e^{G(r)} ) \\[6pt]
&= \Bigg[ G(r) \cdot e - e^{G(r)} \Bigg]_{r \rightarrow - \infty}^{r=x} \\[6pt]
&= \Bigg[ G(x) \cdot e - e^{G(x)} - (-1) \Bigg] \\[6pt]
&= 1 + G(x) \cdot e - e^{G(x)}. \\[6pt]
\end{aligned} \end{equation}$$

Special case - uniform distribution: In the case where we use the standard uniform distribution we have $g(x) = 1$ and $G(x) = x$ for all $0 \leqslant x \leqslant 1$ so we have:
$$\begin{equation} \begin{aligned}
p(X_{N+1} = x)
&= e - e^{x}. \\[6pt]
\end{aligned} \end{equation}$$
Comment: Thank you! This all looks correct *except* the equation for (=|=) -- I believe this is (n+1)g(r)G(r)^n (because X_n is the maximum of n+1 samples in this context, not n samples). This simplifies the overall result to a sum of 1/n! g(x) (1 - G(x)^n). I confirmed this result with Monte Carlo simulation for the uniform case.
Comment: and furthermore, for the uniform case, the result simplifies to e - e^x
Comment: Well spotted - I have edited the answer to correct this, and that does indeed simplify the mathematics considerably.
Answer: @Ben provides most of the solution, here's a summary that fixes a minor error:
The sequence we are interested in consists of N monotonic elements ($X_1 < X_2 < ... < X_N$) followed by a non-monotonic element at position N+1. We are interested in $p(X_{N+1}=x)$
The PDF for the length of the monotonic sequence at the start of the chain (excluding the first non-monotonic sample) is $p(N=n) = \frac{n}{(n+1)!}$
The PDF for the maximum value among the first N+1 elements (which, in this context, is also the value of the element at position N) is $p(X_n=r | N=n) = (n+1)g(r)G(r)^n$, where G is the cumulative distribution function corresponding to g.
The distribution for $X_{N+1}$ is $p(X_{N+1} = x) = \sum_{n=1}^{\infty}\int_x^{\infty}{p(X_{N+1}=x|X_N=r, N=n)p(X_n=r|N=n)p(N=n)dr}$
Using the fact that $X_{N+1} < X_{N}$, the first term is equivalent to
$\sum_{n=1}^{\infty}\int_x^{\infty}{p(X_{N+1}=x|X_{N+1} < r, N=n)p(X_n=r|N=n)p(N=n)dr}$
Which we can flip around using Bayes' rule:
$\sum_{n=1}^{\infty}\int_x^{\infty}{\frac{p(X_{N+1}<r|X_{N+1}=x, N=n)p(X_{N+1}=x|N=n)}{p(X_{N+1} < r | N=n)}p(X_n=r|N=n)p(N=n)dr}$
Finally, plugging in $g$ and $G$ based on the above identities:
$ \sum_{n=1}^{\infty}\int_x^{\infty} \frac{g(x)}{G(r)}(n+1)g(r)G(r)^n\frac{n}{(n+1)!} dr$
$ \sum_{n=1}^{\infty}g(x)\frac{1}{n!}\int_x^{\infty}ng(r)G(r)^{n-1} dr$
$ \sum_{n=1}^{\infty}\frac{g(x)}{n!}[1 - G(x)^n]$
For the case where $X \sim U(0,1)$, $g(x)=1$, $G(x)=x$, and
$p(X_{N+1})=\sum_{n=1}^{\infty}\frac{1-x^n}{n!} = e-e^x$
Which we can confirm against Monte Carlo simulation:
def sample(g = np.random.uniform):
    x = top = g()
    while x >= top:
        top = x
        x = g()
    return x

def f(x):
    return np.e - np.exp(x)

plt.hist([sample() for _ in range(100000)], bins=100, density=True)
x = np.linspace(0, 1, 20)
y = np.array([f(xx) for xx in x])
plt.plot(x, y)


How to implement barriers to stop the player moving through walls

Question: Quick note. This is for my A-Level NEA Programming Project. There are two main sections - One where a maze is generated and the user must navigate through it in a given time period, the time period is not currently implemented, and a second section where the user has to answer educational physics questions in order to get the best score. Questions are imported from a text file stored locally on my system. The user's score is then exported to a local text file along with the date completed.
So far my program generates the maze and the user can move freely. The educational aspect works as intended.
# Imports
import pygame
import sys
import csv
import random
from datetime import date
# Initialising pygame
pygame.init()

# Setting parameters for commonly used colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Creating a variable set to 'False' for the generation of the maze
done = False
# Setting variables for the size of the maze, how many columns and rows there will be
cols = 10
rows = 10
# Setting variables for the size of the window and the size of each individual part of the walls
width = 600
height = 600
wr = width/cols
hr = height/rows
# Initialising the 'screen' this is the surface within pygame that everything will be displayed upon
screen = pygame.display.set_mode([width, height])
screen_rect = screen.get_rect()
pygame.display.set_caption("Maze Generator")
# Creating a clock for the pygame module to run off of
clock = pygame.time.Clock()

# This is a class for the pathfinder section of the maze, it will allow the program to spot where needs to be visited
class Spot:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.f = 0
        self.g = 0
        self.h = 0
        self.neighbors = []
        self.visited = False
        self.walls = [True, True, True, True]

    def show(self, color=BLACK):
        if self.walls[0]:
            pygame.draw.line(screen, color, [self.x*hr, self.y*wr],       [self.x*hr+hr, self.y*wr], 2)
        if self.walls[1]:
            pygame.draw.line(screen, color, [self.x*hr+hr, self.y*wr],    [self.x*hr+hr, self.y*wr + wr], 2)
        if self.walls[2]:
            pygame.draw.line(screen, color, [self.x*hr+hr, self.y*wr+wr], [self.x*hr, self.y*wr+wr], 2)
        if self.walls[3]:
            pygame.draw.line(screen, color, [self.x*hr, self.y*wr+wr],    [self.x*hr, self.y*wr], 2)

    def show_block(self, color):
        if self.visited:
            pygame.draw.rect(screen, color, [self.x*hr+2, self.y*wr+2, hr-2, wr-2])

    def add_neighbors(self):
        if self.x > 0:
            self.neighbors.append(grid[self.x - 1][self.y])
        if self.y > 0:
            self.neighbors.append(grid[self.x][self.y - 1])
        if self.x < rows - 1:
            self.neighbors.append(grid[self.x + 1][self.y])
        if self.y < cols - 1:
            self.neighbors.append(grid[self.x][self.y + 1])

grid = [[Spot(i, j) for j in range(cols)] for i in range(rows)]

for i in range(rows):
    for j in range(cols):
        grid[i][j].add_neighbors()

current = grid[0][0]
visited = [current]
completed = False

def breakwalls(a, b):
    if a.y == b.y and a.x > b.x:
        grid[b.x][b.y].walls[1] = False
        grid[a.x][a.y].walls[3] = False
    if a.y == b.y and a.x < b.x:
        grid[a.x][a.y].walls[1] = False
        grid[b.x][b.y].walls[3] = False
    if a.x == b.x and a.y  b.y:
        grid[a.x][a.y].walls[0] = False
        grid[b.x][b.y].walls[2] = False

class Player:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, hr-2, wr-2)
        self.x = int(x)
        self.y = int(y)
        self.colour = (255, 0, 0)
        self.velX = 0
        self.velY = 0
        self.left_pressed = False
        self.right_pressed = False
        self.up_pressed = False
        self.down_pressed = False
        self.speed = 5

    def draw(self, win):
        pygame.draw.rect(win, self.colour, self.rect)

    def update(self):
        self.velX = 0
        self.velY = 0
        if self.left_pressed and not self.right_pressed:
            self.velX = -self.speed
        if self.right_pressed and not self.left_pressed:
            self.velX = self.speed
        if self.up_pressed and not self.down_pressed:
            self.velY = -self.speed
        if self.down_pressed and not self.up_pressed:
            self.velY = self.speed

        self.x += self.velX
        self.y += self.velY

        self.rect = pygame.Rect(self.x, self.y, hr-2, wr-2)

def readMyFiles():
    questionsAndAnswers = []
    correctAnswers = []

    with open('questions.txt', newline='') as f:
        reader = csv.reader(f, delimiter='\t')
        for row in reader:
            questionsAndAnswers.append(row)

    return questionsAndAnswers

def game(questions, answers, correctAnswers):
    score = 0
    counter = 0
    numberOfQuestions = len(questions)
    while not counter == numberOfQuestions:
        print(questions[counter])
        print(answers[counter])
        userAnswer = input('\nWhat is the correct answer?\n')
        if userAnswer == correctAnswers[counter]:
            print('Well done! That is correct.')
            score += 1
        else:
            print('Better luck next time, that is not correct.')
        counter += 1

    return score

def shuffleSplit(qna):
    random.shuffle(qna)
    questions = []
    answers = []
    correctAnswers = []
    for q in qna:
        questions.append(q[0])
        correctAnswers.append(q[1])
        del q[0]
        random.shuffle(q)
        answers.append(q)

    return (questions, answers, correctAnswers)

def exportScores(score, ):
    with open('scores.txt', mode='a') as scores:
        scores = csv.writer(scores, delimiter='\t')

        today = date.today()
        dateFormat = today.strftime("%d/%m/%Y")

        scores.writerow([dateFormat, score])

player = Player(2, 2)

while not done:
    clock.tick(60)
    screen.fill(BLACK)
    if not completed:
        grid[current.x][current.y].visited = True
        got_new = False
        temp = 10

        while not got_new and not completed:
            r = random.randint(0, len(current.neighbors)-1)
            Tempcurrent = current.neighbors[r]
            if not Tempcurrent.visited:
                visited.append(current)
                current = Tempcurrent
                got_new = True
            if temp == 0:
                temp = 10
                if len(visited) == 0:
                    completed = True
                    break
                else:
                    current = visited.pop()
            temp = temp - 1

        if not completed:
            breakwalls(current, visited[len(visited)-1])

        current.visited = True
        current.show_block(WHITE)

    for i in range(rows):
        for j in range(cols):
            grid[i][j].show(WHITE)
            # grid[i][j].show_block(BLUE)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            questionsAndAnswers = readMyFiles()
            questions, answers, correctAnswers = shuffleSplit(questionsAndAnswers)
            score = game(questions, answers, correctAnswers)
            exportScores(score)
            print('\nYour score is', str(score))
            sys.exit()
        if event.type == pygame.KEYDOWN and completed:
            if event.key == pygame.K_LEFT:
                player.left_pressed = True
            if event.key == pygame.K_RIGHT:
                player.right_pressed = True
            if event.key == pygame.K_UP:
                player.up_pressed = True
            if event.key == pygame.K_DOWN:
                player.down_pressed = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.left_pressed = False
            if event.key == pygame.K_RIGHT:
                player.right_pressed = False
            if event.key == pygame.K_UP:
                player.up_pressed = False
            if event.key == pygame.K_DOWN:
                player.down_pressed = False
    player.rect.clamp_ip(screen_rect)

    if player.x <= 2:
        player.left_pressed = False
        player.x = 2
    if player.y <= 2:
        player.up_pressed = False
        player.y = 2
    if player.x >= width-(wr-2):
        player.right_pressed = False
        player.x = width-(wr-2)
    if player.y >= height-(wr-2):
        player.down_pressed = False
        player.y = height-(wr-2)

    player.draw(screen)
    player.update()
    pygame.display.flip()

Where do I go from here to get to a point so that the walls act as physical barriers rather than just visual barriers? Currently, the maze is generated and the user can move throughout the screen. It always stays on the screen however I am not sure what the best way to implement the walls would be.
Answer: Compute the bounding rectangle of the player and compute the grid indices of the corner points and and center point:
player_rect = pygame.Rect(player.x, player.y, wr-3, hr-3)
xC, yC = int(player_rect.centerx / wr), int(player_rect.centery / hr)
x0, y0 = int(player_rect.left / wr), int(player_rect.top / hr)
x1, y1 = int(player_rect.right / wr), int(player_rect.bottom / hr)

Restrict the movement dependent on the direction and walls. For instance:
if player.left_pressed and player_rect.x < xC*wr+2:
    if grid[xC][y0].walls[3] or grid[xC][y1].walls[3]:
        player.x = xC*wr+2
        player.left_pressed = False

Complete collision test:

while not done:
    # [...]

    player_rect = pygame.Rect(player.x, player.y, wr-3, hr-3)
    xC, yC = int(player_rect.centerx / wr), int(player_rect.centery / hr)
    x0, y0 = int(player_rect.left / wr), int(player_rect.top / hr)
    x1, y1 = int(player_rect.right / wr), int(player_rect.bottom / hr)

    if player.left_pressed and player_rect.x < xC*wr+2:
        if grid[xC][y0].walls[3] or grid[xC][y1].walls[3]:
            player.x = xC*wr+2
            player.left_pressed = False
        if player.y != yC*hr+2 and grid[x0][y0].walls[2]:
            player.x = xC*wr+2
            player.left_pressed = False

    if player.right_pressed and player_rect.x > xC*wr+2:
        if grid[xC][y0].walls[1] or grid[xC][y1].walls[1]:
            player.x = xC*wr+2
            player.right_pressed = False
        if player.y != yC*hr+2 and grid[x0+1][y0].walls[2]:
            player.x = xC*wr+2
            player.right_pressed = False

    if player.up_pressed and player_rect.y < yC*hr+2:
        if grid[x0][yC].walls[0] or grid[x1][yC].walls[0]:
            player.y = yC*hr+2
            player.up_pressed = False
        if player.x != xC*wr+2 and grid[x0][y0].walls[3]:
            player.y = yC*hr+2
            player.up_pressed = False

    if player.down_pressed and player_rect.y > yC*hr+2:
        if grid[x0][yC].walls[2] or grid[x1][yC].walls[2]:
            player.y = yC*hr+2
            player.down_pressed = False
        if player.x != xC*wr+2 and grid[x0][y0+1].walls[3]:
            player.y = yC*hr+2
            player.down_pressed = False

See also How do I prevent the player from moving through the walls in a maze?
Comment: Thank you very much for your detailed reply. This is really helpful and most appreciated. Have a fantastic day, you've helped me out tremendously.


Aggregate columns specified in list

Question: I'm aggregating multiple columns in an R data frame using the following method:
data = data.frame(X=c(1, 3, 3), Y=c(2, 3, 3), Z=c(5, 6, 7), ID=c(10, 11, 12))
with(data, aggregate(cbind(Z, ID), list(X=X, Y=Y), c))

However, I want to select columns using a list variable. I've tried some intricate paste statements looking at this question and this question, but I get error messages like "object 'Z' not found".
How do I do this in a short-hand, easy-to-read manner using base R, preferably without libraries, do.call or hard-to-read paste statements full of parenthesis and apostrophes? Ideally:
k = c("Z", "ID")
aggregate(magic(k), list(X=X, Y=Y), data, c)

Comment: `aggregate(data[k], data[c("X","Y")], c)` covered in `?aggregate` that there are two forms of syntax.
Comment: @Frank: `aggregate(data[k], data[c("X","Y")], c)` is short and beautiful! You may post this as a suggested answer. I doubt there will be better suggestions.
Answer: You can do
aggregate(data[k], data[c("X","Y")], c)

A data.frame is a list, so by=data[c("X","Y")] works as needed here.
Comment: Posting because I couldn't find a dupe and the OP suggested it.
Answer: Try this:
data = data.frame(X=c(1, 3, 3), Y=c(2, 3, 3), Z=c(5, 6, 7), ID=c(10, 11, 12))

# I would use quote:
by.expr <- quote(cbind(Z, ID))
with(data, aggregate(eval(by.expr), list(X=X, Y=Y), c))

# list-version:
by.l <- list("Z", "ID")
by.expr <- parse(text = paste("cbind(", unlist(by.l), ")"))
with(data, aggregate(eval(by.expr), list(X=X, Y=Y), c))

Aggregate columns specified in list