how to calculate the coordinates on a polyline perpendicular to point (in 3D)?

Question: I have two approximately parallel polylines representing railway tracks, consisting of hundreds (maybe thousands) of x, y, z coordinates. The two lines stay approximately 1.435m apart, but bend and curve as a railway would.
If I pick a point on one of the polylines, how do find the point which is perpendicular on the other parallel polyline?

I take it CAD programs use the cross product to find the distance / point and it chooses the line to snap to based on where your mouse is hovering.
I would like to achieve the same thing, but without hovering your mouse over the line.
Is there a way to simply compute the closest line segment on the parallel line? Or to see which segment of the polyline passes through a perpendicular plane at the selected point?
It isn't practical to loop through the segments as there are so many of them.
In python the input would be something like point x, y, z on rail1 and I would be looking to output point x, y, z on rail2.
Many thanks.
Comment: Well, you will HAVE to loop through the segments.  Given the point, you have to find the matching segment in line 1 just so you can tell which direction is "perpendicular".  Then you have to loop through the segments of line 2 to see if a point 1.435m on either side is on or part of that segment.
Comment: Thank you. By specifying the point you will also be specifying the segment for line 1. Really the input will be a point along line 1, as opposed to an x, y, z. For instance a point at 100m on line 1.
Comment: I guess you could filter the coordinates of rail2 to show only those near to the specified point on rail2 and then loop through a smaller number of segments. I am hoping there is a simpler solution.
Answer: You want the point of the minimum distance to the other track.
If the other track is defined by line segments, each spanning two points with a parameter t going between 0 and 1
pos(t) => pos_1 + t * ( pos_2 - pos_1 )

You need to find the t value that produces the minimum distance to the point. Place a temporary coordinate system on the point and express the ends of each line segment pos_1 and pos_2 in relative coordinates to the point of interest.
The value of t is for the closest point is
           dot(pos_1,pos_1) - dot(pos_1,pos_2)
t = ------------------------------------------------------
    dot(pos_1,pos_1)-2*dot(pos_1,pos_2)+dot(pos_2,pos_2)

where dot(a,b)=ax*bx+ay*by+az*bz is the vector dot product.
Now if the resulting t is between 0 and 1, then the closest point is on this segment, and its coordinates are given by
pos(t) => pos_1 + t * ( pos_2 - pos_1 )


How to let a user choose a role after their very first login?

Question: I want to let users to select their role. There are 4 available roles (created by me as an admin) and the selection should be done after first login, so not on the registration form.
Can anyone help me to resolve this problem?
Note: the question let the user choose role upon registration is not exactly the same as my question here: that one contains "... with their chosen role ...", which is clearly something they entered on the registration form.
Comment: Duplicate of http://drupal.stackexchange.com/questions/49889/let-the-user-choose-role-upon-registration?
Comment: Why don't you let them to select their role on registration instead of logging in?
Answer: I am not sure, but you can try somthing lke this: create form with Form API, on submission change value of Role array in user object.
Example:
<code>function MENUCALLBACKNAME($form, &$form_state, $user) {
 $form = array();
 $form['role'] = array(
  '#title' => t('select role'),
  '#type' => 'select',
  '#options' => //Array of your roles like array(id_of_role => t('Name of Role'), ...)
 );

 $form['uid'] = array(
  '#type' => 'value',
  '#value' => $user->uid,
 );

 $form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Choose'),
 );

 return $form;
}

function MENUCALLBACKNAME_submit($form, &$form_state) {
 $uid = $form_state['values']['uid'];
 $role = $form_state['values']['role'];

 $account = user_load($uid);

 $account->roles = $role;
 user_save($account);
 $form_state['redirect'] = 'SOME PATH';
}
</code>
Comment: I am using Profile 2 module, can You suggest me another solution ( module solution is preferable)
Comment: for me it is more comfortable to write code then installing contrib modules and configure them and so on :) I do not know how Profile2 module works but role which is assined to user is located in user object. Proile2 module does not matter here. Just create simple module, create hook_menu, alter registration form submit and after registration redirect user to that page which you created with hook_menu. it's done:)... I do not know there is any contrib module which can do this functionality.


Examples of PCA where PCs with low variance are "useful"

Question: Normally in principal component analysis (PCA) the first few PCs are used and the low variance PCs are dropped, as they do not explain much of the variation in the data.
However, are there examples where the low variation PCs are useful (i.e. have use in the context of the data, have an intuitive explanation, etc.) and should not be thrown away?
Comment: Quite a few. See [PCA, randomness of component?](http://stats.stackexchange.com/q/87198/32036) This may even be a duplicate, but your title is much clearer (hence probably easier to find by searching), so please don't delete it even if it gets closed as such.
Answer: Here's a cool excerpt from Jolliffe (1982) that I didn't include in my previous answer to the very similar question, "Low variance components in PCA, are they really just noise? Is there any way to test for it?" I find it pretty intuitive.

$\quad$Suppose that it is required to predict the height of the cloud-base, $H$, an important problem at airports. Various climatic variables are measured including surface temperature $T_s$, and surface dewpoint, $T_d$. Here, $T_d$ is the temperature at which the surface air would be saturated with water vapour, and the difference $T_s-T_d$, is a measure of surface humidity. Now $T_s,T_d$ are generally positively correlated, so a principal component analysis of the climatic variables will have a high-variance component which is highly correlated with $T_s+T_d$,and a low-variance component which is similarly correlated with $T_s-T_d$. But $H$ is related to humidity and hence to $T_s-T_d$, i.e. to a low-variance rather than a high-variance component, so a strategy which rejects low-variance components will give poor predictions for $H$.
  $\quad$The discussion of this example is necessarily vague because of the unknown effects of any other climatic variables which are also measured and included in the analysis. However, it shows a physically plausible case where a dependent variable will be related to a low-variance component, confirming the three empirical examples from the literature.
  $\quad$Furthermore, the cloud-base example has been tested on data from Cardiff (Wales) Airport for the period 1966–73 with one extra climatic variable, sea-surface temperature, also included.
  Results were essentially as predicted above. The last principal component was approximately
  $T_s-T_d$, and it accounted for only 0·4 per cent of the total variation. However, in a principal component regression it was easily the most important predictor for $H$.  [Emphasis added]

The three examples from literature referred to in the last sentence of the second paragraph were the three I mentioned in my answer to the linked question.

Reference
Jolliffe, I. T. (1982). Note on the use of principal components in regression. Applied Statistics, 31(3), 300–303. Retrieved from http://automatica.dei.unipd.it/public/Schenato/PSC/2010_2011/gruppo4-Building_termo_identification/IdentificazioneTermodinamica20072008/Biblio/Articoli/PCR%20vecchio%2082.pdf.
Comment: This is really cool. I'd just add a note that $V(A+B) =V(A)+V(B)+2\mathrm{Cov}(A,B)$ is always greater than $V(A-B) =V(A)+V(B)-2\mathrm{Cov}(A,B)$. That tripped me up for a second in understanding why $T_s - T_d$ was necessarily a "low variance" component
Comment: +1, this is a nice example. Interestingly, it is also an example of suppression.
Comment: This is a great example. Is one of the lessons here that principal component regression is useful as a potential aid to PCA interpretation, especially since the regressors will be uncorrelated (is this correct?) and so have a non-tangled interpretation?
Answer: If you have R, there is a good example in the crabs data in the MASS package.
> library(MASS)
> data(crabs)
> head(crabs)

  sp sex index   FL  RW   CL   CW  BD
1  B   M     1  8.1 6.7 16.1 19.0 7.0
2  B   M     2  8.8 7.7 18.1 20.8 7.4
3  B   M     3  9.2 7.8 19.0 22.4 7.7
4  B   M     4  9.6 7.9 20.1 23.1 8.2
5  B   M     5  9.8 8.0 20.3 23.0 8.2
6  B   M     6 10.8 9.0 23.0 26.5 9.8

> crabs.n <- crabs[,4:8]
> pr1 <- prcomp(crabs.n, center=T, scale=T)
> cumsum(pr1$sdev^2)/sum(pr1$sdev^2)
[1] 0.9577670 0.9881040 0.9974306 0.9996577 1.0000000

Over 98% of the variance is "explained" by the first two PCs, but in fact if you had actually collected these measurements and were studying them, the third PC is very interesting, because it is closely related to the crab's species. But it is swamped by PC1 (which seems to correspond to the size of the crab) and PC2 (which seems to correspond to the sex of the crab.)
Comment: +1, this is a really neat demonstration. I made 2 scatterplot matrices that could be added, if you like.
Comment: @gung: Thanks for adding the scatterplots! I upvoted this answer before, but did not fully appreciate it without seeing the plots. Scatterplot PC2 vs PC3 is really nice: separating both genders and species almost perfectly. I like this example also because it illustrates what happens when all variables are strongly positively correlated (i.e. PC1 explains lots of variance and is basically an average).
Comment: Thanks, @amoeba. I really like the way they turned out. I spent a lot of time futzing w/ them (colors, pch, lables, legend). I actually think they're kind of pretty now. You make a good point about PC1. We can also see that there is (probably) a constant coefficient of variation & an interaction by sex &/or species in many of the relationships: small (baby?) crabs tend to have the same values irregardless of sex or species, but as they grow (age?) they become more distinct. Etc. There's lots of neat stuff to see--you can just keep looking at them.
Answer: Here are two examples from my experience (chemometrics, optical/vibrational/Raman spectroscopy):

I recently had optical spectroscopy data, where > 99% of the total variance of the raw data was due to changes in the background light (spotlight more or less intense on the measured point, fluorescent lamps switched on/off, more or less clouds before the sun). After background correction with the optical spectra of known influencing factors (extracted by PCA on the raw data; extra measurements taken in order to cover those variations), the effect we were interested in showed up in PCs 4 and 5.
PCs 1 and 3 where due to other effects in the measured sample, and PC 2 correlates with the instrument tip heating up during the measurements.
In another measurement, a lens without color correction for the measured spectral range was used. The chromatic aberration lead to distortions in the spectra that accounted for ca. 90 % of total variance of the pre-processed data (captured mostly in PC 1).
For this data it took us quite a while to realize what exactly had happened, but switching to a better objective solved the problem for later experiments.

(I cannot show details as these studies are still unpublished)
Answer: I have noticed that PCs with low variance are most helpful when performing a PCA on a covariance matrix where the underlying data are clustered or grouped in some way. If one of the groups has a substantially lower average variance than the other groups, then the smallest PCs would be dominated by that group. However, you might have some reason to not want to throw away the results from that group.
In finance, stock returns have about 15-25% annual standard deviation. Changes in bond yields are historically much lower standard deviation. If you perform PCA on the covariance matrix of stock returns and changes in bond yields, then the top PCs will all reflect variance of the stocks and the smallest ones will reflect the variances of the bonds. If you throw away the PCs that explain the bonds, then you might be in for some trouble. For instance, the bonds might have very different distributional characteristics than stocks (thinner tails, different time-varying variance properties, different mean reversion, cointegration, etc). These might be very important to model, depending on the circumstances.
If you perform PCA on the correlation matrix, then you might see more of the PCs explaining bonds near the top.
Comment: This answer is very hard to understand if one does not know what stocks, bonds, yields, and returns are. I don't, and so I can't see how your first sentence is related to your second one...
Comment: I have made some edits.
Answer: In this talk (slides) the presenters discuss their use of PCA to discriminate between high variability and low variability features.
They actually prefer the low variability features for anomaly detection, since a significant shift in a low variability dimension is a strong indicator of anomalous behavior.  The motivating example they provide is as follows:

Assume a user always logs in from a Mac.  The "operating system" dimension of their activity would be very low variance.  But if we saw a login event from that same user where the "operating system" was Windows, that would be very interesting, and something we'd like to catch.


sharp symbol on sharp line

Question: I'm trying to learn how the music staff works.  I want to know what note is actually played for a sharpened note on a sharped line, like this image here:

Am I suppose to play a note that sounds like the G note? Or is it still an F sharp note?
Comment: It's a courtesy accidental. No they don't add up, so you play F#, see: https://music.stackexchange.com/questions/24355/
Comment: If it's written like that in actual music, it's pretty pointless. The # sign (key sig.) couldn't be closer or clearer to the affected note anyway. And since it's a courtesy/cautionary sign, it should have brackets around it.
Answer: It's still an F sharp note. This is usually what we call a "courtesy accidental". It's used to say that the note F would be sharp, when in a previous bar it was altered.
You can take a look on the wiki page for courtesy accidentals, where there is a list with when you would need to add such an accidental.

When the first note of a measure had an accidental in the previous measure
After a tie carries an accidental across a barline, and the same note appears in the next measure
When a chord contains a diminished or augmented octave
When there is a cross relation with another part
Answer:
Am I suppose to play a note that sounds like the G note? Or is it still an F sharp note?

It is still an F sharp. For F double sharp the sharp next to the note would be replaced by an "x".
The reason the sharp sign appears for a second time is that previously F was changed to either natural or double sharp, etc., by an accidental next to the note, probably but not necessarily in the preceding bar. The second appearance of the sharp sign is a courtesy reminder to the musician that now we are in a new bar the original key signature applies.

sharp symbol on sharp line


what is this "for-loop" doing?

Question:
Possible Duplicate:
foreach loop a java creation?

I am learning a Java program. But something , I don't understand. It is following:
for(Some obj : vc) {
  System.out.println(obj.getResult());

I tried to search "for-loop" in my book and google. They just had some basic method.
What means about "for(Some obj : vc)"?
Thanks a lot!
Comment: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Answer: It's a for-each loop, introduced in Java 1.5.
You can read it as "For each Some in vc".
It's effectively the same as using an iterator like so:
for(Iterator<Some> i = vc.iterator(); i.hasNext();) {
  Some obj = i.next();
  System.out.println(obj.getResult());
}

Only with less bloat.
Also, note that this syntax isn't limited to things that are Iterable.  This would also work if vc were an array of Some (i.e. Some[]).
Comment: Thanks for Tim. From your translation, I can get the meaning about this now. Thanks again!

what is this "for-loop" doing?


Display LilyPond fret diagrams next to chord names instead of below

Question: I am trying to display chord diagrams with LilyPond to the side of the chord names.
By default, LilyPond renders the diagram below the chord name like so:

but I want them to be side by side like so:
.
How can I accomplish this with LilyPond?
So far I am able to get the following output, but the diagrams are too far from the staff:

The ideal state would look something like this. The diagrams and chord names stick close together and also close to the staff below:
Answer: You can override the alignment direction of the fretboard diagrams with:
\override FretBoard.align-dir = #LEFT
And you can override the horizontal and vertical offsets with:
\override FretBoard.X-offset = #5 &
\override FretBoard.Y-offset = #5
To get the chord names and fretboard diagrams to sit to the top of the staff/tablature you will also need to use:
\override VerticalAxisGroup.staff-affinity = #DOWN
All together you'll get something like this:
\version "2.24.0"

\include "predefined-guitar-fretboards.ly"

theChords = {
    \set chordChanges = ##t
    \chordmode {
        a1:m | c | g | g | \break
        e | e | a:m | c |
    }
}

\score {
    <<
        \new FretBoards {
            \override VerticalAxisGroup.staff-affinity = #DOWN
            \override FretBoard.align-dir = #LEFT
            \override FretBoard.X-offset = #5
            \override FretBoard.Y-offset = #5

            \theChords
        }
        \new ChordNames {
            \theChords
        }
        \new TabStaff {
            \predefinedFretboardsOn
            \theChords
        }
    >>
}

(You might need to adjust the horizontal offset value depending on how many measures per line you have.)
Comment: @JAV If you want to change the chord names horizontal position, use something like: `\override ChordName.X-offset = #-4`, inside the `CordNames` block. (Then you might want to remove the fretboard's `X-offset`.)
Comment: Thank you! This is close to what I want. But when I try to move the chord name lower and closer to the diagram (similar to the shared image in my question), the diagram keeps moving up, further away from the staff and I end up having similar amount of vertical space, which I was trying to avoid. Any idea how to avoid this effect? I tried to use ```\override FretBoard.align-dir = #LEFT```
 ```\override FretBoard.X-offset = #6```
 ```\override FretBoard.Y-offset = #6```
Comment: @JAV I've added a Y-offset to my answer, but I'm not sure if this is quite right yet.  Are you saying that you want the chord names and the fretboard diagrams to be even closer to the tablature?
Comment: Thank youm this is awesome! :) When I try out the code from your example, my result looks a bit worse - the diagrams are a bit too far and the chord names too. I updated my answer to display what I currently get. I am on version 2.20.0. Maybe that could play some role?
Comment: @JAV Thanks for the image, I found what was going wrong.  I've added `\override VerticalAxisGroup.staff-affinity = #DOWN` to the other overrides, and I think that solves the problem.
Comment: It works, thank you very much. What is the `staff-affinity` property doing? Also is it possible to override the same properties for the chord names? In the example image that I posted, the chord name and chord diagram are centered to be above the place where the chord should be played. In the current version, the chord name is right above the place where it should be played and the diagram is shifted to the left. It could be possible to also move the chord name to the left a bit so that the chord note below is in between the name and the diagram.
Comment: The chord name offsets work like a charm. I tried to reduce the horizontal space between the chord name and the diagram - the modified chords such as `Cm` or `A7` show up close, but the base chords such as `C` or `A` keep an extra character space instead of sticking close to the diagram -- see eg. in your example - the `C` is further from the diagram than, say, `Am`. I tried to use `extra-spacing-width` and `self-alignment-X` to align the chord names to the right, but it had no effect. Any idea how this could be done? Also how to find all properties available on an object in the docs?
Comment: @JAV You might find something on one of the "internals", e.g. https://lilypond.org/doc/v2.24/Documentation/internals/chordnames. Or maybe you are looking for a property that is inherited from another class/object/context. I have trouble understanding the internals myself.
Comment: Thank you, I'll post some results if I manage to figure this out.


Are edited files in core modules overwritten on updating Drupal?

Question: I have searched related questions but could't really find a decisive YES or NO.
I changed a few files in core/modules/user/ ... to alter the display of the form used on my site. For example:
<code> $form['account']['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#description' => $this->t(''),
      '#required' => TRUE,
      '#attributes' => [
        'class' => ['username'],
        'placeholder' => $this->t('Username'),   // ADDED THIS
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
      ],
      '#default_value' => (!$register ? $account->getAccountName() : ''),
      '#access' => ($register || ($user->id() == $account->id() && $user->hasPermission('change own username')) || $admin),
    ];
</code>

Do these edited core files revert back to their original state thus deleting my changes when I update Drupal in the future?
Answer: YES, for sure. Clear enough ....?
PS: that's also why one should never hack core ...
Comment: Unless you use composer and composer patches, technically.. but otherwise no.
Comment: Why not use a form alter hook?
Comment: Thank you, that's very clear indeed. How can I alter this form then? @4k4 suggest a form alter hook, where do I place this?
Comment: In a custom module, in a custom theme..


Syntax Error in Join Operation in MS-Access when splitting and comparing records

Question: Above error message occurs with this statement:
 SELECT f.fullname INTO SummaryJudgment_FinalForgottenWithMiddle
FROM (
(SELECT Left([aname],InStr(1,[aname],",")-1)) As lastname FROM
SummaryJudgment_FinalForgotten) & " " & (SELECT
RIGHT([aname],InStr(1,[aname],",")+1)) As firstname FROM
SummaryJudgment_FinalForgotten) & " " & (SELECT
summary_judgment.middle_initial AS middlename FROM summary_judgment)
) AS fullname
FROM SummaryJudgment_FinalForgotten AS f INNER JOIN summary_judgment
AS s ON f.lastname = s.last_name && f.firstname = s.first_name;

Basically this is what two tables look like (note they will have more fields than 1 where last or first name of different fields can be similar):
SummaryJudgment_FinalForgotten (table)
aname (field)
Leventhal,Raymond (data)

summary_judgment (table)
first_name(field)
Raymond (data)
last_name (field)
Leventhal (data)
middle_initial (field)
P (data)

Ultimately, I'm trying to create a new table that is like
SummaryJudgment_FinalForgotten but with the middle initial from
summary_judgment appended:
Leventhal,Raymond P
Answer: You do not need to write 3 select statements to concatenate the values into one field.
select left(...) & right(...) & initial AS fullname INTO SummaryJudgment_FinalForgottenWithMiddle
 FROM SummaryJudgment_FinalForgotten

Comment: So you are saying something like this: select left([aname],InStr(1,[aname],",")-1)) & right([aname],InStr(1,[aname],",")+1)) & summary_judgment.middle_initial AS fullname INTO SummaryJudgment_FinalForgottenWithMiddle
 FROM SummaryJudgment_FinalForgotten, summary_judgment
Comment: Exactly. This is what I meant.
Answer: Are you trying to use two ampersands to represent a logical AND?
FROM SummaryJudgment_FinalForgotten AS f INNER JOIN summary_judgment
AS s ON f.lastname = s.last_name && f.firstname = s.first_name;

I don't think that's legal for Access' Jet/ACE database engines.  Try it with the AND keyword in place of &&.
OTOH, I wonder if you can do something simpler.
SELECT last_name & "," & first_name & " " & middle_initial AS fullname
INTO SummaryJudgment_FinalForgottenWithMiddle
FROM summary_judgment;

Answer: This works:
SELECT left([aname],InStr(1,[aname],",")-1) & " "
     & right([aname],Len(aname)-InStr(1,[aname],",")) & " "
     & summary_judgment.middle_initial AS fullname
INTO SummaryJudgment_FinalForgottenWithMiddle
FROM SummaryJudgment_FinalForgotten, summary_judgment;

Though you might want this instead:
SELECT left([aname],InStr(1,[aname],",")-1) & ", "
     & right([aname],Len(aname)-InStr(1,[aname],",")) & " "
     & summary_judgment.middle_initial AS fullname
INTO SummaryJudgment_FinalForgottenWithMiddle
FROM SummaryJudgment_FinalForgotten, summary_judgment;

The second version gives you the comma after the last name. Note that Right counts from the right, which is why you have to subtract the InStr value from the length.
EDIT:
The code I gave above works with your sample data--one row in each table. With more rows, it gives a cross product of (LastName, FirstName) x MiddleInitial. It occurred to me that that might be the case, so I went back to my test & added a second row--it is true. So then I tried to write the join expression....
Access doesn't like this:
... ON left([aname],InStr(1,[aname],",")-1) = last_name ...

It throws the error "Join expression not supported." Changing it to this:
... ON (trim((left(SummaryJudgment_FinalForgotten.aname,InStr(1,[aname],",")-1))=trim(summary_judgment.last_name))) ...

results in a query that runs & creates the table, but doesn't create any rows (the same was true before I added the "trim" calls in an attempt to fix it).
So I tried specifying the table for all occurences of aname. No joy--until I realized that I was making the wrong comparison (derived-last to last and derived-first to last--oops).
Using the following FROM clause with either above SELECT ... INTO does work correctly:
FROM
  SummaryJudgment_FinalForgotten INNER JOIN
  summary_judgment ON
    ((left(SummaryJudgment_FinalForgotten.aname,InStr(1,SummaryJudgment_FinalForgotten.[aname],",")-1))=summary_judgment.last_name) AND
    ((right(SummaryJudgment_FinalForgotten.aname,Len(SummaryJudgment_FinalForgotten.aname)-InStr(1,SummaryJudgment_FinalForgotten.[aname],","))=summary_judgment.first_name));

It might even work correctly without the full qualification of each field now that I'm joining first to first & last to last (since there is no duplication across the tables), but having proven that it does work, I'm done.
Comment: Wow! That last FROM clause you posted was the missing piece.


Tracking how long it takes a user to submit a node edit form?

Question: For a quiz node, I want to track how long it takes a user to submit a node form (the time from Drupal generating the form until the time that the user presses submit), and I want to store this duration in a field on my node.
Use case
Each node of content type Quiz is a 10 question quiz.  I want to track the time that users spend filling out the node in order to track their improvement in speed over time.
I do NOT want to track the time spent on the website in general; for that, I already use Google Analytics with scroll tracking, and there is also the Time Spent module.
What I tried
On my node, I added an Integer field, Duration.  My thought was that I could calculate the interval from the timestamp when the form was generated until the time the node was saved by adding code in hook_node_presave():
  $original_time = ??? // How do I get the time when the node form was generated?
  $current_time = \Drupal::time()->getCurrentTime();
  $duration = $current_time - $original_time;

Where I'm stuck is I don't know how to get the time when the node form was created.
I tried to add a Datetime field to my node with a Default date of Current date, but the current date is not set until the node is saved, so that doesn't work.
So, how can I track the time from generating a node edit form until the time the user presses submit?
Comment: I would take a look at the Honeypot module which also tracks the time between showing a form and submitting it. It uses this as part of a strategy to detect spam bots. Check out `honeypot_add_form_protection()` and `_honeypot_time_restriction_validate()`.
Answer: Here is how I would do it:
/*
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_quiz_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_duration']['widget'][0]['value']['#type'] = 'hidden'; // hide field
  $form['field_duration']['widget'][0]['value']['#default_value'] = time(); // set default value to start time
  array_unshift($form['actions']['submit']['#submit'], 'mymodule_calc_duration'); // adds a custom submit that runs before the default node submit
}

function mymodule_calc_duration(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $start_time = $form_state->getValue('field_duration')[0]['value']; // get default value
  $duration = time() - $start_time; // calculate duration
  $duration_value = [
    ['value' => $duration],
  ];
  $form_state->setValue('field_duration', $duration_value); // set duration value
}

Comment: Simple and clean solution
Comment: Updated the answer, its actually better practice to put in in a submit function. Doing it in validation would still be ok if the only validation is just the "required field" aspect, which in D8 it happens on the browser via jQuery. But if there is other validation that does not occur on the browser, it would cause the time to reset. So doing it on submit is full proof.
Answer: Based on NoSssweat's code, I was able to get a working solution for my site.
Note the use of \Drupal::time()->getCurrentTime() instead of time(); this is necessary if you are using something like the Datetime Testing module to change the time for behat tests, because in that case you have to rely on Drupal's time, not the server time.
/*
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_quiz_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_duration']['widget'][0]['field_duration']['#type'] = 'hidden'; // hide field
  $form['field_duration']['widget'][0]['field_duration']['#default_value'] = \Drupal::time()->getCurrentTime(); // set default value to start time
  $form['#validate'][] = 'mymodule_calc_duration'; // adds custom validation that runs after all other validation passes
}

function mymodule_calc_duration(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $start_time = $form_state->getValue('field_duration'); // get default value
  $duration = \Drupal::time()->getCurrentTime() - $start_time; // calculate duration
  $duration_value = [
    ['value' => $duration],
  ];
  $form_state->setValue('field_duration', $duration_value); // set duration value
}

Answer:
create a field in your form and in Hook_form_alter and hide it

  if ($form_id == 'form_id') {
      $form['field_view_node_start']['#access'] = FALSE;
      $form['field_view_node_start']['widget'][0]['value']['#default_value'] = time();
  }

at hook_entity_presave get time between field_view_node_start and field_view_node_end

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
      $entity->set("field_view_node_end",time());
}

Comment: Yes, the Form API does not cache the first build of a form. You could use a [hidden](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Hidden.php/class/Hidden/9.0.x) form element which value you then find in the submitted data in a submit handler. Or use a session value to store the start time on the server if you want to make sure the browser doesn't manipulate the submitted data.
Comment: That doesn't work; the values of `time()` in `hook_form_alter()` and `hook_entity_presave()` are the same.
Comment: Is it possible, that it's not the value of `time()`, which is the same, but that you assign a variable in `hook_form_alter()`, the value of which is overridden again when you submit the form? Or did you test it exactly in the suggested way?


How would these chords from "Christmas Time Is Here" be analyzed?

Question:
I'm wondering how to go about analyzing some of the chords from this piece. I have a lot of tonal harmony knowledge, but am a little limited in my knowledge of jazz theory. However, I'd love to hear any analysis you may have.
Specifically, I'm wondering about the second chord (the Eb9#11) and the first chord of measure 9 (the Bm7b5). I'm trying to figure out how these chords are functioning in the piece and how they could be analyzed. It sounds so smooth to listen to, yet I can't seem to come up with a simple explanation for them.
Any ideas are greatly appreciated. Thanks in advance!
Answer: The song is in F major, so that E♭9♯11 chord is really just an altered ♭VII chord. In music of this style ♭VII is often used as a type of dominant, so measures 5–8 just alternate between tonic and this dominant substitute.
As for the Bm7♭5 in m. 9, ultimately it's the start of a larger sequence: notice how m. 9 just moves down a step into m. 10, which then moves down a step for the beginning of m. 11. This sequence ends on the downbeat of m. 11 with a G7, which is just a V7/V in the key of F. So I would view that Bm7♭5 as just the beginning of a sequence that ultimately leads to that V7/V.
Comment: This is probably a common way of presenting an analysis and can't said to be wrong, but I think the analysis style is problematic: (1) using just one single roman numeral for a chord (with "it-is-a" sentences), suggesting to look at a chord as complex as Eb9#11 as a monolithic thing and not a combination of simpler things, and (2) looking at the final solution in hindsight, to explain things that haven't occurred yet. In jazz harmony you're supposed to see every moment as a set of possibilities to take advantage of - what else could you make it seem to be, if given the space and freedom. :)
Comment: Richard tells the other alternative: bVII = substitution of the dominant - and I agree: the rest is fifth-fall sequence (tritonus substitutions)
Comment: @piiperi I understand what you mean—this diachronic/synchronic difference is incredibly important—but your logic isn't limited to jazz. You could say the same thing about classical music, where a G-major triad might simultaneously be V in C but also III in a modulation towards E minor. But more importantly, the OP didn't ask "I'm in m. 9; what possibilities come next?" Rather, they asked "*Here is the score*, how does m. 9 function *within the context of this entire score*?"
Comment: I actually kinda think that the Eb9#11 is actually an inverted F9b13, complete with the F remaining the root despite not being in the bass. The beginning being a series of common-tone chord shifts makes sense to me.
Comment: OP wants to know "how these chords are functioning in the piece" ... and the functioning has to be understood as "what happens in my mind when I hear these chords". The function of notes and chords is to make listeners feel sensations. :) For example a dominant seventh chord, it makes you feel a certain way, it creates tensions and opens up possibilities, regardless of whether the tensions are resolved not. An analogy I've used often is, a dance can be sexual even if it doesn't lead to actual sex. The mechanics are there, and everyone (?) understands what _could_ happen and how things work.
Comment: Thank you for the great analysis! Much appreciated!
Answer: There are many plausible ways to see the chords, and all of the interpretations are equally true at the same time.

Eb9#11 : can be used like you would use (1) Bbm (or Bbmmaj7) in the key of F major, or (2) tritone substitute dominant A7 going to Dm, or (3) F7 or Cm going to Bb major, ... or maybe (4) like an Eb7 or Eb9 if this was a mixolydian blues/funk/soul thing in F.
Bm7b5, a.k.a. Dm6/B (it has a Dm in it!) : this kind of "resolves" the Eb9#11 to a Dm which was one of the possible expectations or interpretations above, but it's not just a regular Dm, there's an additional twist, the B in the bass. A nice and easy thing after that would be Bbm6, feeling like a quick release to tonic F.  If not even blatant F/C - C7 - F. But that's not what you get, things move slightly to the minor side with a chromatically descending bass line, Bbm7 - Am7 - Abm7 - Gm7 ... so a quick release ii-V-I cannot be far away anymore?

As a dominant there's a Bbm6/C, which sounds like a variation of the Eb9#11, it's just a notch closer to a plain vanilla C7.
IMO it's best to analyze jazzy chords in terms of a set of things you can do with the chord, and not try to come up with "it is a ... blah blah chord" sentences. The "is" sentences just don't cut it. Each chord is what it is, many different things but none.
Try to use the chords in the various roles. For example the Eb9#11 could work in place of a dominant C7 in "Happy Birthday" in F. "Plagal cadence" ... sort of, I guess? Try the alternative expected resolutions for the chords. Dm and Bb work after the Eb9#11, don't you think. How about after the Bm7-5... C/Bb - F/A - Gbdim7 - Gm7 - C7 - F.  Or how about Bm7-5 - E7 - A7?
Or to try interpretation (3) of Eb9#11: whenever you have a regular F7 - Bb chord progression, try replacing the F7 with Eb9#11.
To "understand" chords like that means, in my opinion, that you can see the possible different interpretations at the same time, and you can use the chords in the different roles in different contexts. It's like with borrowed chords - you have to see the other parallel interpretation from which you borrow. And you have to see the Dm in the Bm7b5, otherwise you don't understand the chord. Chord symbols are just a shorthand notation for groups of notes. The written root note of the chord symbol doesn't necessarily have to be the be-all-end-all definition of functionality like it's in simple traditional functional analysis, because there are multiple plausible functional stories in parallel. In "Bm7b5", sometimes the "b5" can be the most important note.
Comment: I tried to answer then I saw you say exactly what I meant to answer: * Bbm (or Bbmmaj7) in the key of F major, (2) tritone substitute dominant A7 going to Dm* ...*Bm7b5, a.k.a. Dm6/B (it has a Dm*
Comment: Thank you very much for this excellent and thorough insight! I'm so used to dealing with tonal harmony that I haven't gotten my mind used to understanding more complex chords in various ways. I'm looking to grow in that area, and an analysis like yours really gives me an idea on how to go about looking at what chords can do. Thanks again!


PHP in HTML: how to

Question: I made a PHP script for a form, but dont't know how to get it to work...How do i put the PHP in the page and make it active? I am a total noob to php, so i have no idea. Do you put the php inside the HTML doc, or make a separate PHP document and link to that?
The PHP thing is here, in case you need it.
<?php
$ToEmail = 'firstname.lastname@example.com';
$EmailSubject = 'Site contact form ';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."
";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."
";
$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."
";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>

Comment: This needs a form to be posted to it.  ``.
Answer: The easiest thing to do would be to create a separate PHP page (e.g. send.php) and then have the form in your HTML page use it in the action attribute (e.g. <form method="post" action="send.php">)
Answer: put it at the top of the .php file which contains the html code if you want it to work

PHP in HTML: how to


Why holomorphic functions on the unit disk which has star-shaped range are injective?

Question: I am recently reading a book named "Univalent  Functions: A primer", written by Derek K. Thomas.
Here are some definitions in the book. Here, $\mathbb{D}$ denotes the unit open disk in the complex plane.

$f: \mathbb{D} \rightarrow \mathbb{C}$ is in the family $\mathcal{A}$ if $f$ is analytic, $f(0)=0$, $f'(0)=1$.
$f \in \mathcal{A}$ is called "starlike" if the range of $f$ is star-shaped with respect to the origin. That is, if $z \in f(\mathbb{D})$ and $t \in [0,1]$, then $tz \in f(\mathbb{D})$.

The author claims that starlike functions are injective. For proof of this fact, he quotes the book "Univalent Functions" written by Peter L. Duren.
But  Duren's book defines "starlike functions" as an injective map satisfying the conditions above, so that the reasoning seems to be circular.
Can someone provide me a proof (or a precise reference) for the fact that all starlike functions are injective?
Comment: The claim seems to be false: for all $a,b$, $f(z)=a\beta(z)^2+b$ has a star-shaped range if $\beta$ is an automorphism of the unit disk not mapping $0$ to $0$. Given such a $\beta$, there are $a,b$ such that $f(0)=f'(0)-1=0$. Finally, $f$ is not injective.
Comment: you need an extra condition (e.g. $\Re{\frac{zf'}{f}} >0$ is one such,conformal radius of $f(D$) at zero is $1$ is another)
Comment: Thank you very much, @Mindlack. I will not delete this question since someone may wonder about this in the future. If you write down your comment as an answer, then I will accept it.
Answer: The statement is actually false:
Pick an automorphism of the unit disk $\beta$ not mapping $0$ to $0$.
Then for all complex numbers $a,b$, $f(z)=a\beta(z)^2+b$ has a star-shaped range and is not injective.
For suitable $a$, $b$, we can ensure $f(0)=0$, $f'(0)=1$.
Answer: Actually, one can characterize all functions $f$ holomorphic on the unit disc $D$ with $f(0)=0, f'(0)=1, f(D)=U$ starlike (at $0$) as the set of all compositions $f(z)=\frac{1}{B'(0)}h(B(z))$ where $h$ is a normalized ($h(0)=0, h'(0)=1$) univalent starlike function on $D$ and $B$ ranges through the set of holomorphic functions on $D$ that satisfy $B(0)=0, B'(0)>0, B(D)=D$.
Note that for example, finite Blaschke products (of order $n \ge 1$) that have a simple zero at the origin are examples of $B$ above after possibly a rotation (multiplication by $e^{i\theta}$) to make $B'(0) >0$ as $B(0)=0, B'(0) \ne 0$, and $B$ is $n$ to $1$ so surjective on the unit disc, while the only univalent such $B$ is the identity because the only Riemann map from $D$ to itself that satisfies $B(0)=0, B'(0) >0$ is the identity (by the unicity of the Riemann map).
Note also that by Schwarz lemma for all such $B$, $B'(0) \le 1$ with equality precisely iff $B(z)=z$, while any $f(z)=\frac{1}{B'(0)}h(B(z))$ as above clearly has a starlike image and is normalized as required, so we only need to prove the converse, so given $f$, find $h,B$ as required.
Let $g(0)=0, g'(0)>0$ be the unique Riemann map from $D$ to $U$ and let $B(z)=g^{-1}(f(z))$ so $f(z)=g(B(z))$. Clearly $B(0)=0, B'(0)>0, B(D)=D$ and $g'(0) =\frac{1}{B'(0)} \ge 1$ with equality iff $B(z)=z, g=f$, so $f$ was univalent to start with.
The function $h(z)=B'(0)g(z)$ is normalized univalent starlike and obviously $f(z)=\frac{1}{B'(0)}h(B(z))$.
By the unicity of the Riemann map, $f$ univalent iff $f=g$ iff $B(z)=z$ iff the conformal radius of $U$ at $0$ is $1$.


Vector space C over R's basis is linearly independent

Question: So, I have to show that the dimension of the vector space C with scalars from R is 2.
$$
\text{Let } B = \{1, i\}, z \in \mathbb{C}\\
\text{Then } z=a+bi \text{ for some } a,b \in R\\
\text{Hence } z \text{ is a linear combination of the elements of } B \text{, so }span B = \mathbb{C}.
$$
To show they are linearly independent, I have to show that $a+bi = 0 \Rightarrow a=0 \land b=0$. How would I go about doing this?
Answer: When I finished writing it, I thought of a way, but I thought I'd post the question anyway. Here's what I did.
$$ a+bi = 0 \Rightarrow (a + bi)(a - b i)=0 \Rightarrow a^2 + b^2 =0$$
Since $a,b \in \mathbb R$, $a^2, b^2 \geq 0$. So $a^2 = 0$ and $b^2 = 0$. Hence $a=0$ and $b=0$.
Comment: If you define them as ordered couples, operations on them must be done accordingly. If you define them this way however, $(a, b) = (0, 0) \Rightarrow a=0 \land b=0$ seems to be linear independence served on a silver platter!
Comment: How did you define the complex numbers in the first place? Maybe this exercise is easier than you think..
Comment: As an ordered pair. And $(a, b) = (0, 0) \Rightarrow a=0 \land b=0$
Comment: So should I just work with ordered pairs all the way through, instead of using $a + bi$
Comment: You seem to be confusing what you have as definitions and what you have to prove. I am sure once you clear this up it will look trivial to you.
Answer: Given that $a+ib=0$, we can write the right hand side
                     $$0=0+i0$$
So we get
$$       a+ib=0+i0$$
On comparing real and imaginary part we get
$      a=0$
and $b=0$.
Which show that $B$ is L.I. because $a,b \in \Bbb R$ are both zero.


Reducing Spaces: Domain

Question: Problem
Given a Hilbert space $\mathcal{H}$.
Consider normal operators:
$$N:\mathcal{D}(N)\subseteq\mathcal{H}\to\mathcal{H}:\quad N^*N=NN^*$$
Denote for readability:
$$\mathcal{D}:=\mathcal{D}(N)=\mathcal{D}(N^*)$$
Regard a closed space:
$$\mathcal{S}\leq\mathcal{H}:\quad\mathcal{H}=\mathcal{S}\oplus\mathcal{S}^\perp$$
Suppose invariance:
$$N(\mathcal{S}\cap\mathcal{D})\subseteq\mathcal{S}\quad N(\mathcal{S}^\perp\cap\mathcal{D})\subseteq\mathcal{S}^\perp$$

Then it may still happen:
  $$\mathcal{D}\supsetneq\mathcal{D}\cap\mathcal{S}+\mathcal{D}\cap\mathcal{S}^\perp$$

Does someone have a nonexample?
Reference
For a preexample: Preliminary
Comment: Are you asking for a proof of the equivalence, "$TZ....TP$"?
Comment: @Squirtle: Yep, but let me change my question. *(There was a flaw!)*
Answer: If $PT = TP$, then for any $x\in Z$
$$
Tx = TP(x) = PT(x) \in Z
$$
and so $T(Z) \subset Z$. Now since
$$
(I-P)T = T-TP = T-PT = T(I-P)
$$
it follows that $T(Z^{\perp}) \subset Z^{\perp}$.
Conversely, if $Z$ is reducing, then for any $x\in H$, write $x = Px + (I-P)x$, then
$$
Tx = P(Tx) + (I-P)Tx = T(Px) + T(I-P)x
$$
and so
$$
P(Tx) - T(Px) = T(I-P)x - (I-P)Tx \in Z\cap Z^{\perp} = \{0\}
$$
and so $TP = PT$.
Comment: But the domain is dense only and even worse it may fail to split: $\mathcal{D}\supsetneq\mathcal{D}\cap Z+\mathcal{D}\cap Z^\perp$
Comment: Let me specify my question. Do you mind?

Reducing Spaces: Domain


How can I test if a time-series data satisfies Markov's property and it is a martingale?

Question: My question is about investigating some properties of time-series.

How can I test if my time-series data satisfies Markov's property?
How can I test if my time-series data is a martingale?

I wonder if there are some measures to quantify the fit of above?
Thanks in advance.
Answer: You need to look up standard stationarity tests.
Markov property amounts to having a auto correlation statistically equal to zero.
Martingale means that the series is stationary around a constant value.


session in nodejs express

Question: I' m using const SessionStore = require('express-session-sequelize')(expressSession.Store); for storing the sessions.
I would like to save in session currenty user, which log to site.
here is a configuration for store:
const expressSession = require('express-session');
const SessionStore = require('express-session-sequelize')(expressSession.Store);
const Sequelize = require('sequelize');
const myDatabase = new Sequelize('analytic', 'root', '', {
    host: 'localhost',
    dialect: 'mysql'
});

const sequelizeSessionStore = new SessionStore({
    checkExpirationInterval: 15 * 60 * 1000, // The interval at which to cleanup expired sessions in milliseconds.
    expiration: 24 * 60 * 60 * 1000,  // The maximum age (in milliseconds) of a valid session.
    db: myDatabase
});
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(expressSession({
    secret: '412415415415415121212121',
    store: sequelizeSessionStore,
    name: 'session_id',
    resave: false,
    saveUninitialized: false
}));

So, now for login I have this:
var express = require('express');
var url = require('url');
var router = express.Router();
var User = require('../../model').User;
var jwt    = require('jsonwebtoken');
var app = require("../../application");
router.post('/authenticate', function(req, res) {
    User.doLogin(req).then((result)=> {
        if (result) {
            if (result.error) {
                if (result.error.hasOwnProperty("email")) {
                    res.send(400, { success: false, message: "Incorrect user / password"});
                } else if (result.error.hasOwnProperty("activated")) {
                    res.send(400, {success: false, message: "You are not activated yet"});
                }
            } else {
                //app.createSession(req);
                req.session.user = result;
                res.send(200, result);

            }
        }
    });
});

module.exports = router;

Now, after this    req.session.user = result; I have in db session table with current user data.
Now,

How can I verify is this user authenticated?
and I notice that for every request I get diferrent sessionID (is this ok)

Thanks
Answer: Hi there for user manager you can use passportjs
it's a great user manager for express and provide a high quality for handle with your user manager logic .

session in nodejs express


$F^n$ is a special case of the vector space $F^S$

Question: in the book Linear Algebra Done Right, $F^S$ is defined as follows:
If $S$ is a set, then $F^S$ denotes the set of functions from $S$ to $F$
where $F$ is a field.
It then writes that $F^n$ is a special case of the vector space $F^S$ because a list of length $n$ of numbers in $F$ can be thought of as a function from $\{1, 2, \ldots, n\}$ to $F$.
I'm confused on what this means. Consider $n = 2$ and $F = \mathbb{R}$, so the space $\mathbb{R}^2$, This is the familiar Cartesian plane. Based on the book, our set is $S = \{1, 2\}$ and $\mathbb{R}^2$ is the set of functions from $\{1, 2\}$ to $\mathbb{R}$.
I am struggling to reconcile the "set of functions" definition with the traditional notion of $\mathbb{R}^2$ - could someone explain this point?
Answer: We classically think of $\mathbb R^2$ as the set of ordered pairs $(x,y)$ with $x,y\in\mathbb R$. To view a pair $(x,y)$ as a function $\{1,2\}\to\mathbb R$, we simply map $1\mapsto x$ and $2\mapsto y$. So the elements in the domain of the function represent the place in the ordered pair, and the values of the function represent the numbers in the ordered pair.
More generally, $\mathbb R^n$ is the set of ordered $n$-tuples $(x_1,\ldots,x_n)$ with $x_1,\ldots,x_n\in\mathbb R$. This can be thought of as a function $\{1,\ldots,n\}\to\mathbb R$ by sending $i\mapsto x_i$ for each $i=1,\ldots,n$.
Comment: A function $f$ from a set ${1,2}$ to the set of real numbers $\mathbb{R}$ gives you a set of ordererd pairs $(1, x)$ or $(2, y)$ where $x, y \in \mathbb{R}$. It doesn't give you a set of ordered pairs $(x, y), x, y \in \mathbb{R}$ as does $\mathbb{R}^{2}$. How do you explain that ?
Comment: @David the function I am talking about in my answer sends $i\mapsto x_i$. Varying these functions amounts to varying the real numbers $x_i$. So the set of all such functions gives you the set of all tuples of real numbers.


Are all topological graphs geometric graphs?

Question: A topological graph or string graph is an intersection graph of curves. Can all such curves be drawn as intersection graph of line segments?
Comment: Is this not the same as [your previous question](https://math.stackexchange.com/q/3535037/167197)?
Comment: Searching for "intersection graph" , I found [this](https://en.wikipedia.org/wiki/Intersection_graph). Is it what you are referring to, with the curves as the intersecting sets?
Answer: Assuming my comment is correct, the answer is no. Consider a graph with vertices $a,b,c,d,e,f,g, h$ with edges connecting $a, b$ to all every vertex, and the following additional edges:
$$ce, df, cg, dh$$
I claim this graph cannot be the intersection graph of a collection of lines. Assume otherwise. Lines $a$ and $b$ intersect in some point $P$ and determine a plane $\pi$. lines $c,d,e,f$ each either intersects $a$ and $b$ in the same point $P$, or else intersects them in different points. In the latter case, the line must lie in $\pi$.
If neither $c$ nor $d$ pass through $P$, then they lie in $\pi$. Since they do not intersect, they must be parallel. But then $e$ contains points in $a, b, c$. These cannot all be the same point, since $a$ and $b$ only intersect in $P$, and $c$ does not contain $P$ by the assumption. So $e$ passes through two distinct points of $\pi$ and therefore lies within it. $e$ does not not intersect $d$ and so must be parallel to it, and therefore to $c$. But $c$ and $e$ intersect, a contradiction.
So either $c$ or $d$ passes through $P$. By swapping $(c,e,g)$ with $(d,f,h)$ if needed, we can assume WLOG that $P \in c$. Since neither intersects $c$, it must be that $d,f$ both lie in $\pi$. If either of $c, e$ lies in $\pi$, it is parallel to both $d$ and $f$, so those two must be parallel as well. But they intersect, a contradiction. So both $c$ and $e$ do not lie in $\pi$ and only intersect it in $P$.
$g$ intersects with all of $a, b, c$. If it did not pass through $P$, then it would contain separate points from $a,b$ and thus would lie in $\pi$. But that prevents it from intersecting $c$, a contradiction. So $g$ passes through $P$. But this is impossible, since $P\in e$, but $g$ does not intersect $e$.
However, this same graph is easily accomplished as the intersection set of a collection of curves in space, where $a$ though $f$ can be lines, but $g$ a curve that stays out of the plane except to pass through a point each of $a$ and $b$, and which intersects $c$ at some point other than $P$.


Pointers to the same location

Question: I have been struggling with this for quite some time now.
While copying array of strings like in the following code:
#include <stdio.h>

int main (int argc, char* argv[])
{
    int i = 0;

    for (i = 0; i < argc; i++)
    {
        printf ("%d: %s @ %p \n",i,argv[i],argv[i]);
    }

    char* states[7];

    for (i = 0; i <argc; i++)
    {
        states[i] = argv[i];      // line 36
        printf ( "State no.%d: %s @ %p \n", i ,states[i],&states[i]);
    }
    return 0;
}

I obtain the following output:

OUTPUT:
  0: ./ex1 @ 0x7fff651da366
  State no.0: ./ex1 @ 0x7fff651d94d0

Shouldn't both the addresses in the output be the same as on line 36 of the code I am making both the pointers point to the same address?
Comment: Please don't number lines of code. Copy-pasting a line to indicate which one in an answer is quick. Removing numbers that prevent from compiling to reproduce the problem is slow.
Comment: Both pointers point to the same place, that is, pointer values are the same. Their addresses are still different.
Answer: The expression &states[i] gives you the address of where states[i] is in memory, and not where it's pointing. Drop the address-of operator to fix the problem.

Pointers to the same location


how to overreide page.tpl.php with my custom menu

Question: I have override page.tpl.php with my new custom menu created in my custom module. my menu look like below
$items['node/edit/restaurant/%/barcodes'] = array(
    'title'=>'Barcodes',
    'menu_name' => 'barcodes',
    'description'=>'Barcodes',
    'page callback'      => 'drupal_get_form',
    'page arguments' => array('leo_MSTag_barcode', 5),
    'access callback'=>TRUE,
    'type' => MENU_CALLBACK,
  );

I already try with page--barcodes.tpl.php, page--node--edit--restaurant--barcodes.tpl.php but not work for me. any new template suggestion for override mu menu page?
Answer: I guess you could do something like this:
function MYMODULE_preprocess_page(&$vars) {
  $patterns = 'node/edit/restaurant/*/barcodes';
  if (drupal_match_path($_GET['q'], $patterns)) {
    $vars['theme_hook_suggestions'][] = 'page__node__edit__restaurant__barcodes';
  }
}

That would let you use page--node--edit--restaurant--barcodes.tpl.php after a cache clear.
As an aside, your page arguments are wrong in the router item, should be:
'page arguments' => array('leo_MSTag_barcode', 3), // <-- Index of arg is 3, not 5

Comment: thanks for quick replay but its not worked for me.
Comment: sorry my silly mistake i have put tpl file in my template folder instead of root theme folder. now its working thanks.
Answer: You can use themeName_preprocess_page in your template.php.
Check the below url.
http://drupal.org/node/1089656.


Comparing beta coefficient of same variable from two different models in R

Question: Let assume I have a data with 100 rows and 3 variables (y,x1,x2).
Now, I fit a regression model with the FIRST 70 observations & get the coefficients as b11 & b12 respectively for x1 & x2.
Then I fit another regression model with the remaining 30 observations & get b21 & b22 as the coefficient for x1 & x2 respectively.
What I want to be assist is ... how can I compare b11 & b21(or b12 & b22) using R.
There is "anova" option in R but that compares different model techniques with same data.
Comment: Compare what exactly? You can use `anova(model1,model2)` to compare the two models as a whole.
Comment: What do you mean by comparing? Models that are fitted to different chunks of the data set are not directly comparable in terms of explaining the entire dataset. However, you can make predictions using both models and see which one is more predictive. It is better to check with the Cross Validated community for this type of questions.
Comment: you can extract a fitted linear model's coefficients with `coef(fit)`
Comment: Would you please post a link to the data?
Answer: The example below shows how to fit 2 groups of data with a single linear model using the factor set. You can then do statistical tests (see summary and anova) to check if there is a significant difference in their coefficients. In this case, the generated data groups have the same y-intercept, but different slopes with respect to x.
# generate synthetic dataset ----------------------------------------------
set.seed(1)
n <- 140
df <- data.frame(x = seq(n), set = factor(rep(c("a","b"), each=n/2)))

# same intercept, but different slope coefs for the sets (plus error added)
df$y <- c(10, 10)[df$set] + df$x*c(1.3, 1.6)[df$set] + rnorm(n, sd = 10)

plot(y ~ x, df, col = df$set)

# fit models --------------------------------------------------------------

# model including different intercepts and slopes for both sets
fit0 <- lm(y ~ x + set + x:set, data = df)
summary(fit0)

# one could remove the intercept shift for setb
fit1 <- lm(y ~ x + x:set, data = df)
summary(fit1)

anova(fit0, fit1) # not significantly different, so take the simpler fit1 model


Determine the range of the function and whether it is one-to-one, onto, both or neither. Then, find all cases where $f(x) = x$

Question: A. $f: \Bbb R\rightarrow \Bbb Z$, defined by the equation $f(x) =\lfloor x \rfloor$
B. $f: \Bbb N\rightarrow \Bbb N$, Where the least significant digit of $x$ is removed. For example, $f(13579) = 1357,\space f(619) = 61,\space f(4) = 0,\space f(0) = 0.$

For A, The function is onto as every number of the range will be matched with at least one number on the domain, but it isn't one-to-one because $f(2) = 2$ and $f(2.1) = 2$.

The range of the function would be $ \Bbb Z$.

As for the cases where $f(x) = x$, then $\forall x \in \Bbb Z$ such that $f(x) = x$

For B, Since every single digit number will equal $0$, the tens will equal $1$, twenties will equal $2$... etc
We can determine that the function is onto as every number in the range will be matched with at least one number in the domain, but the function isn't one-to-one because $f(0) = 0$ and $f(1) = 0$

The range of the function would be $\Bbb Z$.

As for the cases, there's only one case: $x = 0$, $f(0) = 0$

This is the answer I ended up with. I am mainly uncertain when it comes to finding all cases where $f(x) = x$. A confirmation/feedback would be highly appreciated. Thank you!
Answer: Your answer for A is perfectly alright. Your answer for B however, has some mistakes that need to be addressed.

If $f: \Bbb N\to \Bbb N$, then any single digit natural number will not have an image in $\Bbb N$ ($0 \notin \Bbb N$) and thus the function cannot be defined $\Bbb N\to \Bbb N$. The correct co-domain, therefore must at least be $\Bbb N
\space \cup \{0\}$.
Now, for $f: \Bbb N\to \Bbb N \space \cup \{0\} $, there is no $x$ that would satisfy $f(x)=x$. To understand why, simply note any number with more than $1$ significant digit will yield a number with $1$ lesser significant digit. These two numbers can obviously not be equal. The single digit numbers on the other hand, yield $0$ which does not even belong to the domain.
If you wish to include $0$ in your domain, you can define $f: \Bbb N \space \cup \{0\} \to \Bbb N \space \cup \{0\} $ which now yields $x=0$ as the only solution to $f(x)=x.$
Answer: If $f(x)=x$,
$f:N\rightarrow N$ is one to one,
onto
$f:I \rightarrow R$ is one to one, into
$f:R \rightarrow I$ is not a not a map.
Here R is set of all real numbers, I is set of all integers, N is set of all natural numbers.


Regexp example for input accepting one or more spaces at the beginning and at the end but not in the middle

Question: regexp=/^([a-zA-Z0-9@_\s.#]+)$/;
I have tried this and not working
Comment: Add input data and desired output. More different examples are better.
Answer: Something like this can help you?
<code>// no spaces in the middle at all
regexp=/^[ ]{,2}[^ ]+?[ ]{,2}$/

// no two spaces in the middle, one is ok
regexp=/^[ ]{,2}[^ ]+?(?!  )[^ ][ ]{,2}$/
</code>
Comment: Not working. Examples " ", "abc abc" should not work. "abc","  abc  " should work
Comment: Found it in stack overflow /^(?:\s*[@_.#]*[a-zA-Z0-9@_.#]{1,}[@_.#]*\s*)$/


Vanity URL's for Model

Question: I want to add vanity URL's to a model in my application. Ideally, I'd like it to fallback to ID's if a user doesn't have a username. Here's the current solution I've built, but it isn't working.
User.rb
  def to_param
     username || id
  end

User Controller
@user = if params.key?(:username)
    User.find_by_name(params[:username])
else
    User.find(params[:id])
end

Routes
match "/:username" => "users#show", via: :get

Comment: Use friendly_id gem: https://github.com/norman/friendly_id
Comment: `find_by_x` methods have been deprecated for some time, you should be using `where(username: params[:username]).first`
Comment: Might be useful if you explained what exactly isn't working.
Answer: Your route generates a username param regardless of whether or not it's actually a username or an ID that you pass in. Therefore, in your controller you shouldn't be trying to use params[:id]. Other than that, I can see nothing wrong with your code.
Answer: Try this:--
get ':id', to: 'users#show', constraints: lambda { |request| User.where(:username => request.path_parameters[:id]).exists? }

User Controller
@user = User.find_by_username(params[:id])
unless @user
  @user = User.find(params[:id])
end

Vanity URL's for Model


iptables secure squid proxy

Question: I have a setup where my incoming internet connection feeds into a squid proxy/caching server, and from there into my local wireless router.
On the wan side of the proxy server, I have eth0 with address 208.78.∗∗∗.∗∗∗
On the lan side of the proxy server, I have eth1 with address 192.168.2.1
Traffic from my lan gets forwarded through the proxy transparently to the internet via the following rules.  Note that traffic from the squid server itself is also routed through the proxy/cache, and this is on purpose:
# iptables forwarding
iptables -A FORWARD -i eth1 -o eth0 -s 192.168.2.0/24 -m state --state NEW -j ACCEPT
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A POSTROUTING -t nat -j MASQUERADE

# iptables for squid transparent proxy
iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j DNAT --to 192.168.2.1:3128
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3128

How can I set up iptables to block any connections made to my server from the outside, while not blocking anything initiated from the inside?  I have tried doing:
iptables -A INPUT -i eth0 -s 192.168.2.0/24 -j ACCEPT
iptables -A INPUT -i eth0 -j REJECT

But this blocks everything.  I have also tried reversing the order of those commands in case I got that part wrong, but that didn't help.  I guess I don't fully understand everything about iptables.
Any ideas?
Answer: Depending on your iptables configuration, the first line may not be necessary, and the second line is definitely wrong (p.s is the second line eth0 or eth1).
The first line essentially allows your iptables to accept all incoming requests and connections from your internal network.
Try using this for the second line :

iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

This tells iptables to forward all packets coming in from eth1 (WAN) to eth0 (LAN) - that way no connections can be made from eth1 (WAN) to your server.
Just a word of caution though : a two-liner iptables rules is asking for trouble. I suggest you find out more about how to configure by looking at sample configurations found online. You can start looking at this article.
Comment: Those aren't my only rules.  I followed several tutorials online when setting up the masquerade.  I'll add those rules to the original post for clarity.
Answer: I think maybe I have the answer.  This seems to be working for me, and if anyone knows more checks to do than I did, please let me know.
I think I just needed to be sure to match the state of the connection.  I added the following rules:
iptables -A INPUT -i eth0 -p icmp --icmp-type 8 -j DROP
iptables -A INPUT -i eth0 -s 192.168.2.0/24 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i eth0 -j REJECT

I checked it by running nmap against the wan IP from a computer outside our network (my computer at home)...it just hung and never displayed anything.
I also attempted to connect to ports that are listening on the squid server, and all connection attempts failed.  Everything still works as desired from within the network, however.
Answer: First of all, what is your policy for each chain? You can check with iptables -L The Policy is the default action that will be performed if no rule matches.
For the server protection what you need is this:

Set the default rule to DROP
iptables -P INPUT DROP
Allow traffic from your LAN that is
entering the LAN interface
iptables -A INPUT -i eth1 -s 192.168.2.0/24 -j ACCEPT

and leave your FORWARD chain as is.
That's it.
Answer:
How can I set up iptables to block any connections made to my server from the outside,
  while not blocking anything initiated from the inside?

Put this in order at INPUT chain
iptables -A INPUT -i eth1 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i eth0 -m state --state INVALID -j DROP
iptables -A INPUT -i eth0 -j REJECT

If you want to debug it, see your conntrack.

iptables secure squid proxy


:after tag not working properly with

Question: I want to display a content"--" after every list items but when i use li:after then the content comes below the list items and when i use a:after then the content correctly comes after the list items. However i want the content"--" to be associated with the
 and not the  because when i will be using a:hover then there will be some problem. Here is the code. Can anyone help?
HTML

Link 1

Link 2

Link 3

Link 4

Link 5

CSS*
.group:after {
    content: "";
    display: table;
    clear: both;
}

ul {
    list-style:none;
    background:gray;
}

li {
    float:left;
    padding-left:30px;
}

a {
    text-decoration:none;
    display:block;
    padding:10px;
    color:white;
    font-weight:bold;
}

li:after{ content:'--'; }

Answer: The problem here is the element :after is rendered after the a tag, since you have this into the a tag:
a {
  display:block;
}

The :after content is in the next level pushed by the a block tag. Change this and you see the change:
a {
  display:inline-block;
}

The demo http://jsfiddle.net/6YuQ8/3/

:after tag not working properly with


NGINX Keeps Crashing, Seems to be because of too many open files

Question: As stated in the title, my Nginx server seems to be crashing constantly although the reason is unknown.
I do have some hints from my error log which may lead to the issue.
I have tried to increase the open file limit, which has some affect, but to no serious avail.
2015/09/29 17:18:01 [crit] 20560#0: accept4() failed (24: Too many open files)
2015/09/29 17:18:01 [crit] 20560#0: accept4() failed (24: Too many open files)

I have tried to increase the limit, but I see this in my error log also
2015/09/29 17:18:02 [alert] 20632#0: setrlimit(RLIMIT_NOFILE, 300000000) failed (1: Operation not permitted)
2015/09/29 17:18:02 [alert] 20633#0: setrlimit(RLIMIT_NOFILE, 300000000) failed (1: Operation not permitted)
2015/09/29 17:18:02 [alert] 20560#0: recvmsg() truncated data

How do I give permission to increase the file limit?
Also, is this even the reason my server is crashing?
Thank you!
Just checked some more data, I have edited my files, but for some reason when checking the hard limit it says 4096?
root@nalsec:~# sysctl -p
net.ipv4.ip_forward = 1
net.ipv6.conf.all.autoconf = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.eth0.autoconf = 0
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
net.ipv6.conf.eth0.accept_ra = 0
fs.file-max = 2500000000000000000
root@nalsec:~# ulimit -Hn
4096

Which contrasts with my fs.file-max
I tried this, and it says I don't have permission (I am root)
root@nalsec:~# ulimit -Hn 1000000000
-bash: ulimit: open files: cannot modify limit: Operation not permitted

I have edited this file already to no avail nano /etc/security/limits.conf
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#ftp             -       chroot          /ftp
#@student        -       maxlogins       4

# End of file
nginx       soft    nofile  10240000000000000000000
nginx       hard    nofile  10240000000000000000000
*         hard    nofile      10240000000000000000000000
*         soft    nofile      10240000000000000000000000
root      hard    nofile      10240000000000000000000000
root      soft    nofile      10240000000000000000000000
www-data soft nofile 1024000000000000000
www-data hard nofile 1024000000000000000

Answer: fs.file-max is a system-wide limit on the total number of file descriptors that can be open on the system.  It has no impact on the per-process limit.
To increase the file descriptor limit for individual processes, it's easiest to do it via limits.conf:
# cat /etc/security/limits.d/nofile.conf
* soft nofile 10000
* hard nofile 1000000

That'll give all processes 10,000 file descriptors by default, with the ability to request an upgrade to 1,000,000 (via setrlimit) if they want.
Comment: cat /etc/security/limits.d/nofile.conf
cat: /etc/security/limits.d/nofile.conf: No such file or directory
Comment: I was showing you what to put into that file -- you'll need to create it and put the contents I showed.
Comment: Hello, thank you for the response I am currently getting this
Comment: I have already edited a file with a different name with similar contents nano /etc/security/limits.conf

Should I still create the new file?
Comment: Ok I have added the new file anyway with the following contents

# cat /etc/security/limits.d/nofile.conf
* soft nofile 100000000000000000
* hard nofile 100000000000000000000000
Comment: It's still puking errors 2015/09/29 18:06:37 [alert] 24016#0: setrlimit(RLIMIT_NOFILE, 300000000) failed (1: Operation not permitted)
Comment: You'll need to logout and back in again to get the larger limits applied to your session.  If the machine isn't being used for anything, a reboot is the most effective way to ensure the limits are adjusted everywhere.


How do I download a sandbox project?

Question: I want to develop the recommendation platform for job orders. In drupal there is the Prediction IO module but it is a sandbox project. How can I download it?
Comment: See also: [Is it possible to download sandbox projects with Drush?](https://drupal.stackexchange.com/questions/145489/how-do-i-download-a-sandbox-project)
Answer: As reported in Installing sandbox projects, sandbox projects don't have download links, since versions are not enabled for them. You need to use git to download the code.
Assuming you mean the PredictionIO module, that doesn't still have code, at the moment; it is reported in its Version control tab.

No code is available for PredictionIO. File an issue or contact a maintainer if you have questions.

If there were code, you could download it with the following command.
<code>git clone --branch master http://git.drupal.org/sandbox/mrded/2116851.git predictionio
</code>
In the predictionio directory, you would find the module code.
Update
On June 17, 2015, the maintainer answered to Code? saying:

Hi guys,
We actually stopped developing of this module.
  If you're interested, I can publish your codebase as full project and give you a maintainer permissions to fully control the module.

If nobody is going to offer to be maintainer of that sandbox project, the project will not have any code.
Comment: It does because there have not been any commits. Once the project maintainer makes commits, the _Version control_ tab will reports how to clone the git repository.
Comment: Ok. thank u.in that git clone link shows 404 Not Found error

How do I download a sandbox project?


programing diff vim function, vim diff mapping

Question: I've found this function:
" Set up a keymapping from <Leader>df to a function call.
" (Note the function doesn't need to be defined beforehand.)
" Run this mapping silently. That is, when I call this mapping,
" don't bother showing "call DiffToggle()" on the command line.
nnoremap <silent> <Leader>df :call DiffToggle()<CR>

" Define a function called DiffToggle.
" The ! overwrites any existing definition by this name.
function! DiffToggle()
    " Test the setting 'diff', to see if it's on or off.
    " (Any :set option can be tested with &name.
    " See :help expr-option.)
    if &diff
        diffoff
    else
        diffthis
    endif
:endfunction

Now I would like to add an extra condition, if there is some selected text (visual mode) call another command instead of diffthis, Linediff
Reading the function I guess I need some extra set option to test, like they did with &dif but with the visual option. Something like:
function! DiffToggle()
    if &dif
        diffoff
    elseif &visual
        Linediff
    else
        diffthis
    endif
:endfunction

This doesn't work, but does anyone have any clue to make it work?
Also, it would be very useful any reference about what and how many setting variables of this kind are in vim.
Edit
I ended up with this in my vimrc, (works):
"LINEDIFF/VIMDIFF
 "--------------

nnoremap <silent> <Leader>df :call DiffToggle('n')<CR>
xnoremap <silent> <Leader>df :call DiffToggle('x')<CR>

function! DiffToggle(mode) range
    echo "difftoggle..."
    if &diff
        diffoff
        echo "diffoff..."
    else
        if a:mode=='x'
            echo "linediff..."
            echo a:firstline."---".a:lastline
            call linediff#Linediff(a:firstline, a:lastline)
        else
            echo "diff..."
            diffthis
        endif
    endif
:endfunction

Comment: but vim has no option called `visual`.
Check this out `:he option-summary`
Comment: `elseif has('visual')` ?
`:help has()`
Comment: Or if you need check current mode (visual, insert, normal etc) call `mode()`.
Comment: has() only tells you if the feature is supported, so in my case always returns 1
Comment: I see, I've just checked it :)
Answer: Simply call a slightly different function from  xnoremap <Leader>df ... ? That one will be called when you are in visual mode.
Or, pass the mode as argument to your function:
nnoremap <silent> <Leader>df :call DiffToggle('n')<CR>
xnoremap <silent> <Leader>df :call DiffToggle('x')<CR>

... and check a:mode inside your function, having the following prototype:
function! DiffToggle(mode)

Comment: Hi Laser, I tried but it doesn't work properly, now it executes DiffToggle once per line selected in visualmode. Can I make it to execute it just once?
Comment: I think you'll need to add the `range` keyword to your function prototype (`h: function`, `/range`) "   When the [range] argument is added, the function is expected to take care of a range itself.  The range is passed as "a:firstline" and "a:lastline".  If [range] is excluded, ":{range}call" will call the function for each line in the range, with the cursor on the start of each line.  See |function-range-example|."
Comment: Nice, now it runs only once but the range sets only to the current line (not the several lines selected). BTW now I'm busy but I''ll give it more tries later. Thanks a lot for your suggestions
Comment: The range is used only in visual mode, and you have to handle that case yourself, i.e. read all the lines (e.g. with `getline(i)` with `i` moving from `a:firstline` to `a:lastline`).


Which t-test should I go for?

Question: Newbie here. I'm wondering which t-test I should go for: a one-sample t-test or a paired-sample t-test? Happy to receive other suggestions.
A bit about my data:
I have data from 18 participants on how much time they planned to work on a Monday, and how much time they actually ended up working (from two different time-use diaries).
I checked and the data is normally distributed.
What I want to show with the data is that there is a difference between the amount of time people planned to work, and the amount of work they were eventually able to do (except for Diary Participant 11 who worked for exactly the amount of time they had planned).

My question is: which test would you say is more appropriate for this data, if any?
Comment: Which data are normally distributed? That should go a long way towards saying what you want to test.
Comment: the **Planned time** and the **Actual time**?
Answer: It can be a paired t test using columns 'Planned' and 'Actual', or (equivalently) a one-sample t test using column 'Difference'.
I wrote your differences into the vector d below. (Maybe check my
typing.)
d = c(140, -660, -60, -110,  195, 455, -140, -110,
      -210, -30, 0, 40,  -60, 230, 65, -55,
      -90, -235, - 35)

The first question is whether these differences are normally distributed.
A normal probability plot is "mainly" linear with a few exceptions, especially the lowest (-660) and highest (455) values .
qqnorm(d);  qqline(d, col="green2")

These extreme values show as 'outliers' in a boxplot of the differences.
boxplot(d, horizontal=T, pch="|")

Nevertheless, a Shapiro-Wilk test for normality does not (quite) reject the
null hypothesis (normal data) at the 5% level.
shapiro.test(d)

         Shapiro-Wilk normality test

data:  d
W = 0.91394, p-value = 0.08748

Various statisticians have different favorite ways of judging normality and tolerance for departure from normality in a one-sample t test.
A one-sample t test on the differences, does not find the average difference
$\bar D = -35.26$ in the sample mean to be significantly different from $0$
at the 5% level of significance. [If you had done a paired t test in R, the output would have looked much the same; the first step of the paired procedure would have been to find the differences used in the output below.]
t.test(d)

        One Sample t-test

data:  d
t = -0.68782, df = 18, p-value = 0.5003
 alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
  -142.97372   72.44741
sample estimates:
mean of x
-35.26316

If someone disbelieves the accuracy of the t test (on account of non-normality), they might say a nonparametric paired
Wilcoxon test (equivalently, one-sample Wilcoxon signed-rank test)
would be better. An objection to using this Wilcoxon test is that the
data are not symmetrical. (Look at the boxplot.) However, the Wilcoxon SR test also fails to reject the null hypothesis that subjects deviated
significantly from plan. (P-value above $0.05 = 5\%.$%
wilcox.test(d)

        Wilcoxon signed rank test with continuity correction

data:  d
V = 66.5, p-value = 0.4203
alternative hypothesis: true location is not equal to 0

As often happens in practice, neither test is perfect. But arguments
can be made for using either. And in the end, neither test finds a
significant difference from planned work time.
Pick one of the two tests
an use it. Neither test shows results anywhere near the borderline for rejection.
Some of your workers aren't very good at sticking to plan, but they do
not show a strong trend in either direction--above or below plan.
Note: For completeness: one possible additional test comes to mind. It's called a sign test.
Out of $n = 19$ observations, you have $n^\prime = 18$ non-zero results. Of these non-zero tests 6 are positive and 12 are negative. The probability of 6 or fewer positives or of 12 or more negatives
out of 18 is the P-value $0.2379$ of the sign test--nowhere near significant at the 5% level. There are also objections to the sign test because data are not symmetrical and because looking just at signs 'throws away' too much information.)
sum(dbinom(c(0:6,12:18), 18, .5))
[1] 0.2378845

By way of confirmation, Minitab statistical software shows the following results for
a sign test on your data:
Sign Test for Median: d

 Sign test of median =  0.00000 versus ≠ 0.00000

    N  Below  Equal  Above       P  Median
d  19     12      1      6  0.2379  -60.00

Comment: BruceET, thank you very much for your thorough explanation. I really appreciate it!

One quick question: could I treat the differences as positive numbers (rather than negative and positives) to see if there is a statistical difference? I'm wondering if this approach is, first of all correct, and secondly, if it would allow me to say that _overall_ participants did not stick to plan (rather than looking at the trend in either direction--above or below plan)?

Which t-test should I go for?


Decideing on Which method to run C#

Question: I was wondering if in c# there was kind of like an if and else statement for methods like an example would be
 private void button_click(object sender, EventArgs e)
 {
   if the ComputerSelectionmethod runs and executes don't execute the FindOpenCellCols method below
   {

        ComputersSelection();
        FindOpenCellCols();
    }
   }

Comment: Your sample is not very clear... What do you mean "method runs and executes"? Do you expect that method never terminate? Or throw exception? Or return value? Or have timeout?
Comment: `if/else` statements only require a boolean value that an expression can evaluate to.  Have your method return a boolean, and you're all set
Comment: As @AlexeiLevenkov says, "method runs and executes" is not very clear. The closest thing I can think of is "the method runs and returns without throwing an exception".  In that case, look at @Selman22#'s answer.
Answer: You can do something like this:
bool control = true;
try
{
    ComputersSelection();
}
catch (Exception)
{
    control = false;
}

if(!control) FindOpenCellCols();

I assume you mean runs and successfully executes by "runs and executes".
Comment: Why not just `try { ComputersSelection(); } catch (Exception) { FindOpenCellCols(); }`?
Answer: If you change the control variable to false in catch body, exception may have thrown in last lines of code in that case ComputersSelection() method's most part is executed and still FindOpenCellCols() would be executed. Try the below code
public bool control = true;

ComputersSelection()
{
   .......
   code;
   .......
   control = false;
}

if(control)
{
   FindOpenCellCols();

}

Decideing on Which method to run C#


How to write triplets in 4/4 time without using a 3 on top of the notes all the time

Question: I am writing a song and in cubase (DAW) the score I get looks this.
Is there really no better way to write this without using a 3 on top of each beat? Is there something I could put at the top of the piece since the whole song is a shuffle like this?
Comment: What is your intention with this - is the rhythm supposed to be a slow rock, shuffle, triplet swing, or lighter-than-triplet swing?
Comment: If you look at the score for "Bolero" by Ravel, you'll see it's just packed with triplets.
Comment: First movement of the Moonlight Sonata?
Comment: @DawoodibnKareem Good example - Most printings I've seen of the Moonlight have 3's over the triplets in the first measure, but then just leave the rest unmarked.  It's pretty clearly implied that the same rhythm continues for the whole piece.  This method of marking is pretty commonly used when the base part is just repeating a triplet pattern the whole time.  Possibly less so in the case of a shuffle where it's 2-1, 2-1, 2-1, 2-1 instead of the 1-1-1, 1-1-1, 1-1-1, 1-1-1 pattern of the Moonlight et al.
Comment: Or is your piece more in the classical music, soundtrack, or concert band vein? In those cases, swing indications are often inappropriate.
Comment: I know that Logic Pro has a "swing" option, which automatically turns what are notated as eighth note rhythms in the score editor into swung triplets. It even lets users adjust the strength of the swing, making the rhythm anything from a slightly late eighth note to a hard, traditional triplet swing. Perhaps Cubase has something similar?
Answer: You'll see it done in all of these ways.   12/8 is the obvious answer.   Straight 8s plus a 'Shuffle' instruction is useful if you're writing into a notation program like Sibelius - but you have to make sure 'Shuffle' IS defined in the Playback Dictionary.  The third way will be understood by live musicians, but will confuse computer playback.
I recommend 12/8.  Using 12/8 is completely clear and unambiguous both to humans and computers.
There's also the possibiity that you're playing with a Swing feel (not precise triplets), and triplets are Cubase's best guess.   If this is the case, write straight 8's and 'Swing'.
Comment: We see 'swing' far more than 'shuffle'. Unless 'shuffle is what they define it as in Sibelius, et al. Or do I read the wrong music? And the last one seems too far away from swing/shuffle at 75/25%. 12/8 is what came to mind when the question was read. +1.
Comment: 12/8 is often very hard to read if the rhythms are at all complicated.
Comment: Do you assume the OP means the song to be a shuffle? I think it's not clear at all what the intended rhythmic feeling or message to musicians is, and the notation shown is just a guess made by the software. Cubase won't be able to tell if your MIDI notes are trying to represent swing or shuffle or something. It's just a dumb machine.
Comment: @Tim When reading music, I always assumed "shuffle" to be roughly equivalent to "swing", i.e. implying an uneven eighth-note division inside the beat. Was I off the mark the whole time? I thought the two were nearly identical (shuffle carrying stylistically different implications than swing, but nonetheless...)? (Or perhaps this is one of those terms that gets a little twist when it crosses the Atlantic, if you catch my drift...)
Comment: @ Laurence, I have swing set at 100% in cubase and I realize that this could confuse the score plugin but among the swung notes there are lots of actual triplets and since the swing is set to 100% there is no doubt that it is a shuffle. Isn't your second example kind of the same as Meangreens? If so both are ideal since I only would need to write one word at the top of the score which would save me writing all those "3"s
Answer: Probably the same as the keyword "shuffle", but wouldn't the below example get your intention across?

Edit: Another option is to indicate the triples for the first bar, then use the word 'simile' to show the idea is to continue this for the reminder of the piece:

https://musicterms.artopium.com/s/Simile.htm

A directive to perform the indicated passage of a composition in a
  similar manner as the previous passage; similarly. One common use is
  to designate the continuation of the use of an articulation without
  repeating the articulation symbol. Often abbreviated as
  sim. . similarly; i.e., continue applying the preceding directive,
  whatever it was, to the following passageto continue to do something
  in the same way it was formerly notated such as pedaling or staccatos
Comment: @ Laurence. If the track is swing @ 100% then it is a shuffle isn't it?
Comment: Mathematically, perhaps.  But Shuffle and Swing are quite distinct feels.  Difficult to describe in words, easy to hear.
Comment: @MeanGreen thanks for this answer, but if I do use the "swing" bit at the top of my score I would still need to notate the triplets at the end of the first bar right?
Comment: I don't think so. As other answers have mentioned, the number of notes in each bar (but also the fact you combined the last notes of the first bar into a group of 3) should be indication enough, though not extremely helpful to future readers. I've added another image as an alternative solution: the simile instruction.
Comment: @armani: if you have an actual triplet in addition to the swinging eights, it's best to write it as a triplet. Otherwise it will be very confusing to read, because without the "3" it will look like its total time value is one and a half quarter-notes.
Answer: You might be able to use implicit tuplets if the groupings stay consistent throughout a significant section of the piece. Notate the first couple measures explicitly and let the musician figure it out from there (most moderately skilled musicians should be able to handle this). (Optionally, to make it more clear, you may want to add 'simile' or 'sim.' after the last explicitly marked tuple.) Again, this should only be used in long passages (preferably the entire piece) with consistent rhythmic groupings and patterns. Also, if the moderately skilled musician mentioned above can't figure it out, this probably isn't the best solution!
Here are a couple examples:

In Chopin's Fantasie Impromptu only the first sextuplet is notated and
  the rest are implied with slur markings, a repeated structural pattern
  and the fact that there are simply too many notes squeezed in. Also note that the melody (not shown) is written in non tuplets, making writing this in 12/8 impractical.

In Schubert's Impromptu Op. 90 No. 3 we are not given any tuplet
  notation at all. Instead, the groupings are inferred by the fact that
  there are 6 notes when there should clearly only be 4.

EDIT: And, of course, Moonlight Sonata, as mentioned in the OP comments. :)
Comment: The melody of that Chopin piece is 8 notes for every 6 in the bass.  To make those all line up on the beats without using tuplets would be insane.  Also, playing that piece with mathematical precision would sound very robotic and wholly unsatisfying.  You shouldn't be thinking about exactly where every note lies in the measure, but more about the overall flow they have.
Comment: @DarrelHoffman Aligning the 8 over 6 polyrhythm (or rather, 4 over 3, twice) isn't terribly difficult at slower speeds. Fantasie Impromptu, however, is just about as far from "slower speeds" as you can get! Chopin's works are full of odd tuples (septets, octets, etc.), complicated polyrhythms (like 8 over 3) and out-of-time runs (essentially 10 - 30 note "tuplets"). All of these techniques intentionally break away from the precise timing found in classical and baroque styles and require a mental separation from the pulse, driving the music by feeling and emotion instead of technical precision.
Comment: @DarrelHoffman So yes, while you could theoretically pick them apart mathematically, doing so would effectively ruin the piece, as you said.
Answer: I'd write it in 12/8, it's easier to write. And to read. And it will be interpreted the same.


Expand region to fill screen size

Question: I have a splash page where the user will choose a language before entering the site.
This page only needs the header region and a background image (for the #main-wrapper div) that should occupy the rest of the screen size.
I'm using
<code>#main-wrapper {
    background: url('img.jpg') center no-repeat;
    height: 100%;
    width: 100%;
    background-size: cover;
}
</code>
But it doesn't fill the available space, only the #main-wrapper div, so I end up with a grey area below the background image, where the footer should be.

Is there a way to make this region expand all the way to the bottom (I don't need the footer in this particular page) without declaring it's height in px?
I want to avoid scrollbars when not necessary, and have the image fill the space when resizing the window or viewed on mobile.

Is it possible to do this with Bartik theme?
EDIT:
I've already hidden the footer, but that doesn't make the #main-wrapper div reach all the way to the bottom. I still get a blank space below it.
Comment: Could you not add it to the body tag?
Comment: @th0ward That would add it to the header too :(
Comment: why don't you use background-image for body so it will take the whole page and put your header above it?
Answer: You could style that special page with css to not display the footer (display:none). Drupal delivers a css class in the body tag that identifies the current node, like so .page-node-x, where x is the node id of the page. So you could go like page-node-x .footer.
You could also use a page.tpl override for the specific page where you remove the footer region. Create a copy of page.tpl.php in your themes template folder and name it page--node--x.tpl.php. Remove footer in this file completely.
And as for fullsize background image, maybe this module could be interesting: https://www.drupal.org/project/supersized
Comment: I followed your comment above, I hadn't thought of that. Thanks :)
Answer: If footer is just transparent, you could also go by applying your rules to body instead of #main-wrapper.
Also, Drupal should hide empty regions AFAIK. Thus, you can try to hide everything in footer region using visibility rules. If that does not work, check page.tpl.php.
Hiding it via page-node-x class with display: none; visibility: hidden; is the easiest way though!
Answer: As many others have mentioned, why not just add the background-image to body?
<code>html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  background-image: url('img.jpg');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}
</code>

Expand region to fill screen size