500 Server Error after deployment

Question: I apologized as I'm not well versed specifically with drupal. But anyway, I was migrating an existing installation on a Windows Server to a Linux Server (debian).
I went ahead and moved all the files, setup the database, updated settings.php in /sites/default
I also chown'd with correct user, and set /sites/default/files to 777 permissions with all other directories set to 755 and files set to 644.
I have errors with some images, css, and js. I checked the files, and they exist. When attempting to access via GET request (http protocol) I get 500 Internal Server error.
Looking at PHP's error logs I see these alerts (no errors):
/sites/default/files/.htaccess: Option FollowSymLinks not allowed here

When I edit said .htaccess files to:
#Options None
#Options +FollowSymLinks

The images load, but the CSS and JS does not (it exists but tries pulling from incorrect directory). I am also worried about security in this folder.
ie:
Actual Request: GET site.com/css/css_49249400b301b59bd86200648ba96215.css
Correct Request: GET site.com/sites/default/files/css/css_49249400b301b59bd86200648ba96215.css
Anything I could be doing wrong?
Help is appreciated!
UPDATE:
Rewrites are enabled and working.
Comment: What is your configuration at admin/config/media/file-system?
Answer: Did you have "Clean URLs" enabled on the Windows install?  You may need mod_rewrite enabled in Apache (a2enmod rewrite)
I'm not sure how your server is configured (os/php version/etc), but I had a similar issue that required me to change the following in .htaccess
# RewriteBase /
to
RewriteBase /

Another thing to check would be that overrides are allowed at all.  Apache needs to be set to something like "AllowOverride All"
More info regarding AllowOverride:
How can I enable clean URLs?
How to enable Clean URLs?
Regarding permissions, there is a bunch of information available including a script that can help repair permissions (obviously use extreme caution when running and verify before you do.)
Source for the script below.
#!/bin/bash

# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:

  1) Path to your Drupal installation.
  2) Username of the user that you want to give files/directories ownership.
  3) HTTPD group name (defaults to www-data for Apache).

Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}

if [ $(id -u) != 0 ]; then
  printf "**************************************\n"
  printf "* Error: You must run this with sudo or root*\n"
  printf "**************************************\n"
  print_help
  exit 1
fi

drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"

# Parse Command Line Arguments
while [ "$#" -gt 0 ]; do
  case "$1" in
    --drupal_path=*)
        drupal_path="${1#*=}"
        ;;
    --drupal_user=*)
        drupal_user="${1#*=}"
        ;;
    --httpd_group=*)
        httpd_group="${1#*=}"
        ;;
    --help) print_help;;
    *)
      printf "***********************************************************\n"
      printf "* Error: Invalid argument, run --help for valid arguments. *\n"
      printf "***********************************************************\n"
      exit 1
  esac
  shift
done

if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
  printf "*********************************************\n"
  printf "* Error: Please provide a valid Drupal path. *\n"
  printf "*********************************************\n"
  print_help
  exit 1
fi

if [ -z "${drupal_user}" ] || [[ $(id -un "${drupal_user}" 2> /dev/null) != "${drupal_user}" ]]; then
  printf "*************************************\n"
  printf "* Error: Please provide a valid user. *\n"
  printf "*************************************\n"
  print_help
  exit 1
fi

cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .

printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;

printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;

printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;

printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
  find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
  find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done setting proper permissions on files and directories"

500 Server Error after deployment


How can I loop through a filtered table and check if each row is in another sheet using vba?

Question: I have 2 worksheets. Lets call them worksheet A and worksheet B. In worksheet A I automatically pull in a huge amount of data and apply the proper filters to narrow down to the critical data (see image)
this next part is where I need help:

loop through only the visible rows in sheet A
check if the first column matches any row in the first column of sheet b
if it does match then I need to check that the second column in that same row in sheet A also matches the second column in the matched row in sheet B.
if it passes both those test then I need to copy the whole row and append it to the end of the data in row B.

so far I have:
<code>    with ThisWorkbook.Sheets(sheet_name)
    Dim open_package As Range
    Set open_package = ThisWorkbook.Sheets("Open Packages").Range("A2", Range("A" & Rows.Count).End(xlUp))
    Dim rng3 As Range

    Dim rng_package As Range
    Set rng_package = Range("A1", Range("A" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
    Dim cl_package As Range

    For Each cl_package In rng_package.Rows
        For Each rng3 In open_package
            MsgBox rng3
            Debug.Print (cl_package.Cells(1) & " " & cl_package.Cells(2))
        Next rng3
    Next cl_package
End With
</code>
I am trying to troubleshoot the nested loop to see exactly in what way is it looping through everything.
Comment: Why don't you create a column C with `c2:  =A2&"-"&B2`. on sheet A and sheet B.Then you have only one test and can compare the values easily. `MATCH`, `INDEX` and `VLOOKUP` will do the rest!
Comment: What have you tried so far?
Comment: edit it above to include some of my code.
Answer: Ivan!
I made a code to loop only visible rows from first table and lookup them in second table, when you find a match between Transaction and Package you append a line to second table
<code>Sub LoopALL()

  Dim i As Long
  Sheets("A").Select
  Range("A1048576").End(xlUp).Select 'selects the last visible row
  LVR = ActiveCell.Row + 1

  While Cells(LVR, 1).EntireRow.Hidden = True
      LVR = LVR + 1
  Wend

  'End of Table, first row blank
  EoT = LVR

  For i = 2 To EoT
  Sheets("A").Select

      If Cells(i, 1).EntireRow.Hidden = False Then
        TRS = Cells(i, 1)
        PCK = Cells(i, 2)
        STS = Cells(i, 3)
        DES = Cells(i, 4)

        Sheets("B").Select
        Z = Range("A1048576").End(xlUp).Row

        For x = 2 To Z
          If Cells(x, 1).Value = TRS And Cells(x, 2).Value = PCK Then
             Cells(Z + 1, 1).Value = TRS
             Cells(Z + 1, 2).Value = PCK
             Cells(Z + 1, 3).Value = STS
             Cells(Z + 1, 4).Value = DES
          End If
        Next

      End If

  Next

End Sub
</code>
Comment: You may want to [avoid select](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba)
Comment: @rodrigo Moraes, Thank you for your help. The code works but it iterates through every single row to check if its visible or not. My worksheet A has thousandths of rows so its very time consuming and sometimes crashes. Is there any way to optimize this?
Comment: @Ivan Gutierres. Maybe we can try another approach, but I have a view on this. 1st way: we can speed up processing turning off calculation, screen updates, events and etc while we doing the code. 2nd way: We can add a sequencial col flag your filter in an auxiliar column, sort it to reduce processing, and sort again composing your table
Comment: But what I truly recommend is to insert a table and start to use ADO to pass SQL Instructions like an Access, so you can make a recordset and treat what you want.

In fact using Excel your table can't be bigger than 1.048.572, so  the processing is relatively fast


The number of scalar additions required to compute $P(QR)$

Question: Let $P$, $Q$, $R$ be matrices of order $3\times5, 5\times7$ and $7\times3$ respectively. What is the number of scalar additions required to compute $P(QR)$?
Do we have any formula to compute this? If we had to square a square matrix of order $n\times n$ how will the results change? Thanks...
Comment: Professor Strang discusses this for nxn matrices at 27:00 in this lcture - http://ocw.mit.edu/courses/mathematics/18-06-linear-algebra-spring-2010/video-lectures/lecture-4-factorization-into-a-lu/ . How will we find for mxn matrices?
Comment: http://en.wikipedia.org/wiki/Coppersmith%E2%80%93Winograd_algorithm
Comment: http://en.wikipedia.org/wiki/Strassen_algorithm
Comment: @Ritu Please give the answers to my below comment.
Answer: Answer = $ 126 $. To get every number in the matrix $QR$, we need $6$ additions and there are $15$ numbers like that. similar calculation for the next step gives $4$ additions repeated $9$ times. So , we need $ 6*15 + 9*4 = 126 $ additions.
Comment: how did we get 6 and 4 here? and is it any formula? What should one understand by the term scalar addition?
Comment: Since Q has 7 columns and R has 7 rows whem we multiply them to get a single entry of QR we have to add 7 elements for that we need 6 additions.
Answer: Consider $2$ matrices of the order m*n and $n*p$. The no. of additions required is given by the formula $m*p*(n-1)$. In the above question P(QR)
no. of additions required for QR would be $5*3*(7-1)=90$
no. of additions required for P(QR) would be $3*3*(5-1)=36$
so total additions required for the above question would be $90+36=126$
Answer: Just an observation is  that .. the dimension of the product Matrix P(QR) is $9(3 \times 3)$ and 9 is dividing 126 ...so from this way can we find the number of scalar addition of the matrix.


Better way to associate ticket quantities with event dates?

Question: I'm fairly new to events in Drupal 7 but I have at least spent a few days now investigating strategies for my use case. Unfortunately, I haven't found a single relevant piece of info.
I have some recurring events that need to have a remaining tickets number associated with each event date. Some of these events are literally movies in a museum and teachers need to be able to see how many tickets are available for each show time when selecting dates and times for their field trips. Thus, movie show times is a useful (and accurate) model for this issue.
Within a single event node it's simple enough to create multiple date fields and multiple remaining tickets fields for the event. However, I've not been able to figure out how to associate a given remaining tickets number with a specific event date. So far, I only have lists of unrelated dates and numbers.
The alternate "solution" I've come up with is to have an event description node and numerous distinct event date (show time) nodes. The event date (show time) nodes would contain the event date and the tickets remaining for that date. However, I can't think of a way of explicitly connecting the event date nodes to the relevant event description node other than also including the node id in the event date nodes (which, for other reasons, is far from ideal).
Does anyone more experienced with events know whether this explicit connection is even likely to be needed? Even better, can anyone point me in a less cumbersome direction (e.g., associating the tickets required numbers with the right dates, all in one node, instead of creating separate event date nodes)?
Thanks so much for any and all assistance you're able to give!!!
James Baker
Answer: If you want to continue down the road you are on now, having an event description node and separate event date nodes, I would recommend you take a look at the References module.
If you want to keep all information within one node for a given movie/event, perhaps take a look at the Field Collection module.  The article Create Multigroups in Drupal 7 using Field Collections may assist you to accomplish this.
Comment: Wow! I'm following the article you referenced to use the Field Collection module and it looks like it's going to work for what I need. Thanks so much for your help! I'll set your response as the answer as soon as I've tested everything out.
Comment: Thanks, @Laxman13. I can't get the data entered into Field Collections to display with views. Getting the [Invalid field name given. in FieldCollectionItemEntity->__construct() ...](http://drupal.org/node/1084268) error. A little concerned about applying the patch from [Comment #24](http://drupal.org/node/1084268#comment-4967014) there. I can't tell to which file the patch should be applied or if the patch will be compatible with future module updates. Any thoughts from anyone experienced with this?
Comment: Unfortunately I don't have any experience with the Field Collections module.  Perhaps someone else can chime in
Comment: Cygwin tells me the patch from [#24](http://drupal.org/node/1084268#comment-4967014) was successfully applied but I'm still receiving exactly the same error. Applied patch to both [7.x-1.0-beta2](http://drupal.org/project/field_collection) (2011-Aug-18) and [7.x-1.x-dev](http://drupal.org/project/field_collection) (2011-Sep-27). Any additional assistance will be greatly appreciated :)
Comment: I ended up going with the approach of separating event dates from event descriptions and having each event date node contain a reference back to the event description via the References module. Thanks again!


Prove that $a_n = 1 + \frac{1}{a_{n-1}}$ with $a_0 = 1$ converges to $\frac{1+\sqrt{5}}{2}$

Question: As the title says, I want to prove that $a_n = 1 + \frac{1}{a_{n-1}}$ with $a_0 = 1$ converges to $\frac{1+\sqrt{5}}{2}$. I've noticed that there's a recurrence formula $a_{n+2} = 2 - \frac{1}{a_n+1}$ and that there are two monotonic sequences in different directions $a_{2n}$ and $a_{2n+1}$. From here I need to show that they converge to the same number and that that number is $\frac{1+\sqrt{5}}{2}$ but I'm not sure how to do that.
Comment: There is a [standard way](https://en.wikipedia.org/wiki/Rational_difference_equation#First_approach) to solve it
Comment: @Marco Finding an explicit form for $a_n$ is not necessary to prove convergence to the limit
Comment: First show they are a cauchy sequence.  That is:  For any $\epsilon > 0$ then there is an $N$ so that if $n,m > M\implies |a_n - a_m|< \epsilon$.  That indicates the sequence most convert to *something*.  Then note that $\lim_{n\to \infty} a_n$ must equal $\lim_{n\to\infty}a_{n+1} = \lim_{n\to\infty}(1 + \frac 1{a_n})$.  Use the idea that if $f$ is continuous that $\lim f(n) = f(\lim n)$ to show that if $\lim_{n\to\infty} a_n = a$ then $ \lim_{n\to\infty}(1 + \frac 1{a_n})=1+\frac 1{\lim a_n}= 1+\frac 1a$.
Answer: A common approach to these questions is as follows: first, find a suitable candidate for the limit under the assumption that the limit exists. Then, show that the sequence converges to this number.
The first of these steps is technically unnecessary for the question as it is presented here, but I think it may be informative in any case, so I present it at the end of my post. Once a limit is hypothesized, there are a few approaches to show that the sequence converges to the limit $L = \frac{1 + \sqrt{5}}{2}$.
Approach 1
Use the theory of fixed-point iteration. In particular, we see that this sequence of the form $a_n = f(a_{n-1})$, where $f: \Bbb R \to \Bbb R$ is the continuous and differentiable given by $f(x) = 1 + 1/x$. We compute $a_2 = 3/2$. We note that
$$
f'(x) = -1/x^2,
$$
and we see that $|f'(x)| < 1$ for $3/2 \leq x \leq 2$, which is a closed interval containing both $L$ and $a_2$. By the Banach fixed-point theorem, we can conclude that $a_n$ must converge to the unique fixed point in this interval, which is to say that $a_n \to L$.
Approach 2
Directly show that $|a_n - L|$ is strictly decreasing. To begin, we first note that $a_n > 0 \implies a_{n+1} > 0$, so that the entire sequence must be positive. Indeed, if $a_n > 0$, then $a_{n+1} = 1 + \frac 1{a_n} > 1 + 0$.
With that, we have the even stronger statement that $a_n \geq 1$ for all $n$ (and $a_n > 1$ for $n \geq 1$).
Now, making use of the fact that $L = 1 + 1/L$ (see approach 1 above or my note at the end), we note that
$$
\begin{align*}
\left|a_{n+1} - L\right|
&= \left|1 + \frac{1}{a_n} - L\right|\\
\\ & = \left|1 + \frac 1{a_n} - \left[1 + \frac 1L\right]\right|\\
\\ & = \left|\frac 1{a_n} - \frac{1}{L}\right|\\
\\ &  = \frac{|L - a_n|}{a_n L}
\leq \frac{|L - a_n|}{L}
\end{align*}
$$
With that, we have shown that $|L - a_{n+1}| \leq \frac 1L|L - a_n|$, where we note that $1/L < 1$. It follows that $|L - a_{n}|$ converges to zero, which is to say that $a_n \to L$, which is what we wanted.

Finding a candidate for the limit
Suppose that $\lim_{n \to \infty} a_n = L \neq 0$. It follows that we can take the limit of both sides of the recurrence relation to get
$$
\lim_{n \to \infty} a_n = \lim_{n \to \infty} \left(1 + \frac 1{a_n} \right)\\
L = 1 + \frac 1L.
$$
As discussed above, we see that $L$ must be a fixed point of the function $f(x) = 1 + 1/x$. Continuing, we have
$$
L^2 - L - 1 = 0\\
L = \frac{1 \pm \sqrt{5}}{2}.
$$
So, there are two candidates for the limit. However, we can rule out the possibility that $L = \frac{1 - \sqrt{5}}{2} < 0$ because this sequence satisfies $a_n > 0 \implies a_{n+1} > 0$. So, the fact that $a_0 = 1 > 0$ implies that the entire sequence is positive and therefore cannot have a negative limit.
Comment: Nice thorough answer! I wonder if there are any qualitatively different (geometric?) approaches.
Answer: We can define $a_n=\frac{b_{n+1}}{b_{n}}$ for some unknown sequence $b_{n}$ such that $b_0=1=b_1$
The equation becomes
$$
\frac{b_{n+2}}{b_{n+1}}=1+\frac{b_{n}}{b_{n+1}}
$$
or
$$
b_{n+2}-b_{n+1}+b_n=0
$$
This is the recurrence relation of the Fibonacci numbers and so we have
$$
b_n=\frac{\varphi^{n}-\psi^{n}}{\varphi-\psi}
$$
where $\varphi$ is the golden ration and $\psi$ its coniugate.
So the original sequence is given by
$$
\lim_{n \to \infty} a_n=\lim_{n \to \infty} \frac{F_{n+1}}{F_n}=\varphi:=\frac{1 +\sqrt{5}}{2}
$$
(see here)
Answer: $a_{n+1}-a_n=\frac{1}{a_n}-\frac{1}{a_{n-1}}=\frac{a_{n-1}-a_n}{a_na_{n-1}}$ for all $n\in \mathbb{N}$.
$a_{n+2}-a_n=1+\frac{1}{a_{n+1}}-a_n=\frac{a_{n+1}+1-a_na_{n+1}}{a_{n+1}}=\frac{a_{n+1}+1-a_n-1}{a_{n+1}}=\frac{a_{n+1}-a_n}{a_{n+1}}$ for all $n\in\mathbb{N}$.
$a_0<a_1,a_2<a_1,a_2<a_3,a_4<a_3,a_4<a_5,a_6<a_5\dots$ and $a_0<a_2,a_3<a_1,a_2<a_4,a_5<a_3,a_4<a_6\dots\Rightarrow1=a_0<a_2<a_4<a_6<\dots<a_5<a_3<a_1$.
So $\{a_{2n-1}\},\{a_{2n}\}$ are convergent. If $a_{2n-1}\rightarrow l\;(\geq1)$ and $a_{2n}\rightarrow m\;(\geq1)$, then $l=1+\frac{1}{m}$ and $m=1+\frac{1}{1}$. Using these we find that $l=m$ and $l=1+\frac{1}{l}\Rightarrow l^2-l-1=0\Rightarrow l=\frac{1+\sqrt{5}}{2}$.
Answer: $a_n=1+\frac{1}{a_{n-1}}$
Let:
$1\le a_{n-1}<2$
$\frac{1}{2}< \frac{1}{a_{n-1}}\le 1$
$\frac{3}{2}<1+\frac{1}{a_{n-1}}=a_n \le 2$
So once $a_k$ is between 1 and 2 for some $k$, it remains within those bounds for all higher $k$.
$-2 < -a_{n-1} \le -1$
$\frac{-1}{2}< a_{n}-a_{n-1}\le 1$
Equality on the right is only achieved for $a_1$ otherwise, the inequality is strict. This means that $a_n$ and $a_{n-1}$ get closer and closer together.

$a_n=1+\frac{1}{a_{n-1}}<a_{n-1}$
$\phi = \frac{1+\sqrt{5}}{2}$
$\psi = \frac{1-\sqrt{5}}{2}$
$a_{n-1}+1<a_{n-1}^2$
$0<(a_{n-1}-\phi)(a_{n-1}-\psi)$
$(a_{n-1}-\psi)$ is always positive.
So $a_k$ increases if $a_k<\phi$ and decreases if $a_k >\phi$
Suppose $0<\epsilon <1, $|a_k-\phi|<\epsilon$
$-\epsilon < a_k - \phi < \epsilon$
$\phi -\epsilon < a_k < \phi + \epsilon$
$\frac{1}{\phi + \epsilon}<\frac{1}{a_k}<\frac{1}{\phi - \epsilon}$
$1+\frac{1}{\phi + \epsilon}<1+\frac{1}{a_k}<1+\frac{1}{\phi - \epsilon}$
$\frac{\phi+\epsilon +1}{\phi + \epsilon}<a_{k+1}< \frac{\phi - \epsilon +1}{\phi - \epsilon}$
$\frac{\phi+\epsilon +1-\phi^2-\phi\epsilon}{\phi + \epsilon}<a_{k+1}-\phi< \frac{\phi - \epsilon +1-\phi^2+\phi \epsilon}{\phi - \epsilon}$
Since $1+\phi=\phi^2$, we can simplify:
$\frac{\epsilon(1-\phi)}{\phi+\epsilon}<a_{k+1}-\phi< \frac{\epsilon(\phi -1)}{\phi-\epsilon}$
$|\frac{\phi-1}{\phi+\epsilon}|<|\frac{\phi-1}{\phi-\epsilon}|$
$\implies \frac{-(\phi-1)\epsilon}{\phi-\epsilon}<a_{k+1}-\phi< \frac{(\phi -1)\epsilon}{\phi-\epsilon}$
$|\frac{\phi -1}{\phi - \epsilon}|<1$
So no matter how close $a_k$ is to $\phi$, it follows $a_{k+1}$ is still closer.
By comparison with a geometric series we establish convergence.


Is it legal to run with your athlete during an Ironman?

Question: I will be cheering on a family member at an Ironman race later this year and as an amateur runner myself, I think it would be fun to run a few miles with him and cheer him on.  I would not take anything from aid stations or run through the finish. Is it against race regulations for a spectator to be on the course in that manner?  Is it bad form even if legal?
(Running with an athlete like this may be confused with pacing?)
From: IRONMAN competition rules:

Section 6.03 FINISH LINE CONDUCT
  Friends, family members, and/or other spectators are not permitted to cross the finish line or
  enter the finish chute with participating athletes. (Please note: IRONMAN desires for each athlete
  to be able to celebrate his/her accomplishment without risking the safety of other Event
  participants, volunteers, and/or spectators). Athletes who choose not to respect the foregoing
  finish line policy will be disqualified.

But I could run part of the course with him?
Comment: Regardless of your intentions, your actions would be that of a pacer. What are the IRONMAN rules regarding pacing? Even if you not really pacing, I suspect you would have to comply to any such rules.
Answer: Certainly you wouldn't be allowed to cross the finish line with them based on the rule you cited, but as ckett said running with them in general could be considered outside assistance as a pacer.
From the Ironman rules:

2.01 (i) Compete without receiving assistance from other parties (other than from Race Referees,
  Race Officials, and other athletes in accordance with Section 2.02). Receiving assistance
  (other than in accordance with Section 2.02) will result in disqualification;

Though it could result in just a 30 or 60 second time penalty if you stop immediately when told.  From appendix A:

If it is possible to amend and return to the
  original situation then a 30 or 60 Second Time
  Penalty (as applicable) Time Penalty will be
  assessed, If not: DSQ

There isn't anything explicitly disallowing it in the rules, so it would be worth asking one of the officials in one of the Athlete Briefing that occurs on the day before the race.  That would be the definintive answer.


Drupal Commerce Custom Sizes

Question: I am creating a Drupal Commerce website to sale Custom Stitched Thobes in which I need to get the Measurement from the customers. I am unable to understand where & how should I add fields to take the measurements for the product he adds to cart.
Actually the idea is to offer some standard sizes like S,M,L or XL in case he don't want the standard sizes he can select Custom in Sizes Drop down, which will show up custom size text fields.
I was looking for a straight forward way to add text fields in Product Type through manage fields and check Enable this field to function as an attribute field on Add to Cart forms. so those fields can be appeared on add to cart form but unfortunately this option is not available for text fields.
Answer: Correct - the way the attributes system works, it requires you to define a SKU for every possible combination - depending on how many measurements options you have, it could be infinite. Instead you should look into line item fields that allow a customer to associate unstructured data with a product when it is added to the cart. This could accommodate both your fixed and variable sizes.
Comment: Its really nice to see you Ryan. Thanks for directing me to a correct path.

Drupal Commerce Custom Sizes


AngularJS Select Box Set Default Selected Value on Document Ready

Question: I have a weird problem when setting the model value of a dropdown on Document ready event. I want Option4 to be selected on page load, However this doesn't seems to be reflected on my view when I do things as follows. Please see below code...
HTML
<select ng-model="search_for" class="form-control" id="search_for">
                    <option value="">-Search For-</option>
                    <option value="1">Option1</option>
                    <option value="2">Option2</option>
                    <option value="3">Option3</option>
                    <option value="4">Option4</option>
</select>

JS
angular.element(document).ready(function () {
$scope.search_for = 1;
}

Even when I do {{search_for}} in html it proves that model value is not set by showing nothing, but shows the value when dropdown value is changed.
What am I doing wrong ?.
Thank You.
Comment: instead of adding it on `document.ready` add at the starting in the controller, since the controller loads prior to view, the model value gets reflected
Comment: any reason why you can't use the "selected" tag provided in normal HTML to set what you want? Since it looks like it's hard-coded to set to a specific option anyway. Or do you just do everything in a new technology you are learning, ignoring all the other, already-built-in and easy to use standards?
Comment: Have you try with ng-init in select box ? otherwise please look here http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g?p=preview
Answer: Instead of adding it on document.ready add at the starting in the controller, since the controller loads prior to view, the model value gets reflected

<!DOCTYPE html>

<select ng-model="search_for" class="form-control" id="search_for">
                    <option value="">-Search For-</option>
                    <option value="1">Option1</option>
                    <option value="2">Option2</option>
                    <option value="3">Option3</option>
                    <option value="4">Option4</option>
</select>

Please run the above snippet
Here is a working Demo
Comment: Thank you so much... !!! it works, but I don't understand why js can't manipulate and reflect the change on document ready. Can you please elaborate more... Cheers !!!
Comment: The document.ready is also triggered only once when you load your index.html. It is not triggered when the partial templates defined in your route configuration are loaded.
Comment: [check this answer](http://stackoverflow.com/questions/17945333/angularjs-document-ready-doesnt-work-when-using-ng-view)
Answer: You need to have ng-app and ng-controller for the app, without using document.ready

var app = angular.module('DemoApp', [])
app.controller('akuaController', function($scope) {
 $scope.search_for = "1";

});

  <link rel="stylesheet" href="style.css" />

  <select ng-model="search_for" class="form-control" id="search_for">
    <option value="">-Search For-</option>
    <option value="1">Option1</option>
    <option value="2">Option2</option>
    <option value="3">Option3</option>
    <option value="4">Option4</option>
  </select>


Multiple values through email in android

Question: I want to send multiple values through EXTRATEXT intent...But I am not able to do it.
Code:
public void onClick(View view) {
                Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                emailIntent.setType("plain/text");
                String mailid="firstname.lastname@example.com";

  emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{mailid});
  emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Delivery Request");
  emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "My address is   "+edittext.getText().toString());

 emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,  "My phone number is "+edittext1.getText().toString());
                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
               }

           });

           Now the problem is that only phone number appears but the address doesnt appear..ie. its taking the second EXTRA_TEXT and not the first one.:(

I want to pass some 5-6 values using EXTRA_TEXT....Is it possible?
Answer: if u use 2 (android.content.Intent.EXTRA_TEXT) it takes last one.
so,
U use the below code for both address and phone number as putextra
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "My address is   "+edittext.getText().toString()+"\n My phone number is "+edittext1.getText().toString());

Comment: yeah i can do that but see I want to put Extra_Text in a loop...i want to do something like: for(i=0; i<B.size();i++) {emailIntent.putExta(android.content.Intent.EXTRA_TEXT,"A[i].ToString()}
Comment: for(i=0; i<B.size();i++) {emailIntent.putExta(android.content.Intent.EXTRA_TEXT,"A[i].ToString()} is it working fine?
Comment: did u try my answer.U got the expected result or not?
Comment: yes i did. But this is not what I want...I want it to be in a loop. And its not working that way.


Minimal polynomial over $\Bbb Q $ of a given root.

Question: Find the minimal polynomial of $\sqrt{2+\sqrt2} $ over $\Bbb Q $
setting $ x=\sqrt{2+\sqrt2} $ we have $x^2 -2= \sqrt2 $ and $(x^2-2)^2-2=0$
i believe this is the desired polynomial but i am not sur ehow to show that it is minimal.
I tried writing $\sqrt{2+\sqrt2} =\frac{-b \pm \sqrt{b^2-4ac} }{2a}$ thinking that it might be a good place to start but in the end  didn't get anywhere with it.
Answer: Note that $(x^2-2)^2-2=x^4-4x^2+2$, which is irreducible by Eisenstein's criterion.
Edit: Irreducible and minimal being equivalent.
If $f$ is a polynomial such that $f(a)=0$ for some $a$, then if it is not irreducible, i.e. $f=gh$, then either $g(a)=0$ or $h(a)=0$, so $f$ isn't minimal.
On the other hand, if $f$ is not the minimal polynomial for $a$, then there is some minimal polynomial $g$, and we have $f=gh+g_0$ for some $h,g_0$ with the degree of $g_0$ less than the degree of $g$. $f(a)=0$ and $g(a)=0$ means $g_0(a)=0$. Since $g$ is minimal and $g_0$ has lower degree, we must have $g_0=0$ so $f=gh$ is not irreducible.
Comment: I wasn't sure "minimal" meant irreducible ???
Comment: @Faust It is one of equivalent definitions. The minimal polynomial is the unique irreducible monic with the given number as a root.
Comment: @Faust I added a few brief lines about why those two are the same.


UIImageView will scale instead of rotation if moved , iOS

Question: hy
i want to make a little animation.the rotation works fine if the image is static.
but when i move my image view it will stretch the image. the image can be moved
whit out a problem if it's not rotated.
<code>-(void)play
{

        CGRect ship=image.frame;
        ship.origin.x=ship.origin.x+move;
        ship.origin.y=ship.origin.y+move2;
        image.frame=ship;
}

-(void)rotate
{
       int degre=180;
       float radian=degre*(3.14/180);
       image.transform =CGAffineTransformMakeRotation(radian);
}
</code>
Comment: Is this your actual code? `CGRect ship=image` looks suspicious. - And use `M_PI` instead of `3.14` !
Answer: When using the transform property you are not allowed to change the position by changing the frame, you have to use the center property.
So this should help:
<code>-(void)play
{
    image.center=CGPointMake(image.center.x + move, image.center.y + move2);
}
</code>
Comment: ship does not have a variable center and if i try in image it can't be manipulated directly... wrote to fast
Comment: works but it centers the image in the middle of the screen and it stays there
Comment: You just interrupted my 2 days of research and understanding why my rotated items could not move, thanks !!!


script php rodando como sudo

Question: Já criei um script PHP que me cria uma pasta dentro do meu diretório home do Linux, porém quero saber agora como mudar seus direitos (rwx) pois a pasta criada tem como proprietário o daemon e o restante do script (chown) não funciona.Por favor, detalhem, pois não tenho muita experiência com o Linux.
Comment: O que tentou fazer? Qual erro deu? Se colocar essa parte do script fica mais fácil alguém te ajudar.
Comment: Bem-vindo ao Stack Overflow em Português! Por favor explique melhor o problema, e se possível inclua um [exemplo de código que reproduza o que está acontecendo](http://pt.stackoverflow.com/help/mcve), pois está ampla demais a sua pergunta. [Veja na Central de Ajuda Como Perguntar](http://pt.stackoverflow.com/help/how-to-ask).
Comment: Você deve explicar se está rodando seu PHP no terminal ou no webserver
Answer: 1º - Não te recomendo a executar scripts pelo php com o sudo, pois como você mesmo disse não tem muito conhecimento em linux, e isso seria uma grande brecha não só em sua aplicação mais em todo o seu S.O..
2º - Você poderia criar uma pasta com permissão global para que todos à acessem, assim acredito que funcionária para você mkdir("nome_diretorio", 0777);
Mais informações sobre permissões no linux no link abaixo
http://www.infowester.com/linuxpermissoes.php
3º - Você pode executar qualquer comando no sistema operacional com o exec ou shell_exec
Mais alguns dados sobre permissões abaixo:
---------   000
r--------   400
r--r--r--   444
rw-------   600
rw-r--r--   644
rw-rw-rw-   666
rwx------   700
rwxr-x---   750
rwxr-xr-x   755
rwxrwxrwx   777
Answer: Você já pode criar a pasta com permissões para todos acessarem:
mkdir("pasta", 0777);

Para executar qualquer comando do linux no PHP como admin, você deve criar um arquivo com a senha do root e passá-lo para o sudo. Assumindo que você tenha salvo esse arquivo no "/var/www/meuprojeto", com o nome de "senha.secret":
exec('sudo -u root -S chown "usuario" "pasta" < /var/www/meuprojeto/senha.secret');

Answer:
Crie seu script PHP sem importar-se com o usuário que executará, usando chmod para alterar as permissões de diretórios.
Execute seu script via linha de comando:
sudo php meuscript.php

Existem muitos "poréns" no uso desta abordagem, mas se você é o root e quer uma script para lhe ajudar a administrar o sistema, OK!
Entretando, possivelmente bash será a melhor linguagem para atingir seu objetivo.
Comment: Com o apoio do pessoal aqui do forum e mais algumas pesquisas consegui notar o erro que estava comentendo e resolvi os problemas até aqui, digo isso pois o projeto continua e talvês venha a ter novas dúvidas. Só para constar  encontrei no Yast o edtor do Sudoers e consegui inserir as linhas que davam permissão para o script do php rodar sem pedir senha e com direitos de sudo, alem é claro de escrever estas linhas de forma correta no php. Grato a todos.
Comment: Algumas destas respostas foi a que mais lhe ajudou? Marque-a como resposta aceita.

script php rodando como sudo


What is the SHA256 that comes on the sshd entry in auth.log?

Question: When logging in via ssh, it can be seen the following on auth.log:
Dec 14 16:29:30 app sshd[22781]: Accepted publickey for dev from XXX.XXX.XX.XXX port XXXXX ssh2: RSA SHA256:pO8i...

I've been trying to figure out what is this SHA256 information, but I couldn't find anything that seems to match. First I thought it could be some information from the client (public key, fingerprint, hashed hostname etc) I'm connecting from, but I didn't find anything to confirm, neither at the server side.
The closest information I've found is here, but I didn't understand when it says "And here is an example using a key for authentication. It shows the kewy (a misspelling, probably) fingerprint as a SHA256 hash in base64.", since I haven't found a corresponding key fingerprint of any kind.
Thank you.
Answer: This is the SHA256 hash for the RSA public key which was used to authenticate the SSH session.
This is how to verify it:
ssh-keygen -lf .ssh/id_rsa.pub

Or, to verify without ssh-keygen:

Remove the ssh-rsa prefix
Decode the key to bytes using base64
Get the SHA256 hash for the key (as bytes, not hex)
Encode the bytes using base64

For example:
cat .ssh/id_rsa.pub    |
    awk '{ print $2 }' | # Only the actual key data without prefix or comments
    base64 -d          | # decode as base64
    sha256sum          | # SHA256 hash (returns hex)
    awk '{ print $1 }' | # only the hex data
    xxd -r -p          | # hex to bytes
    base64               # encode as base64

Comment: It turns out that you can use `ssh-keygen -lf .ssh/id_rsa.pub`
Comment: Just an additional information: the same command works well with authorized_keys:

*ssh-keygen -lf .ssh/authorized_keys*
Comment: I think your comment is a separate and all-round better answer, which you should add separately.
Comment: +1 to adding `ssh-keygen -lf .ssh/id_rsa.pub` as a separate answer.  It is better then manual encoding.
Answer: Had the same question on macOS 10.13.6, where your answer just needed a couple of tweaks:
cat .ssh/id_rsa.pub    |
    awk '{ print $2 }' | # Only the actual key data without prefix or comments
    base64 -D          | # decode as base64
    shasum -a 256      | # SHA256 hash (returns hex)
    awk '{ print $1 }' | # only the hex data
    xxd -r -p          | # hex to bytes
    base64               # encode as base64

Thanks v. much.


Is it possible to define a usable Object Context variable in LINQPad?

Question: I'd like to be able to write against an object context variable within linq pad so the code is identical to what I'll be using in my production code. For instance if my object context variable was 'oc':
oc.Products.Where(p => p.Price > 10m);

Instead of:
Products.Where(p => p.Price > 10m);

Where the object context would be available in a variable name of my choosing instead of not using a local variable for the object context which is the same LINQPad works by default.
Answer: LINQPad subclasses the object context, so you can get to it via the 'this' keyword. Assigning it to a local variable will do what you want:
var oc = this;
oc.Products.Where (p => p.price > 10).Dump();


Add role when logged_in

Question: I want to add a role to the user when they log in for the very first time to their account. Any ideas of how to work this out? Rules maybe?
Thanks,
Answer: Rules only with module logintoboggan. Then you will have Event: when user account is active
With custom module hook_user_login and you must check for custom fields filled only once like timestamp.

Add role when logged_in


How do I classify the extrema found using Lagrange multipliers?

Question: Ok so I have found a bunch of local extrema using the method of Lagrange multipliers. Now, what is the method to classify them as minimum or maximum?
I cant apply the second derivative test out-of-the-box because its not a single function - it is a collection of functions along with various constraints.
Is there a universal algorithm that can solve this or is it necessary to rely on individual human judgement for each specific case?
Comment: Do you mean local max vs. local min? A general solution for twice differentiable objective functions is to compute the Hessian matrix $H$, then compute a basis of the directions that are accessible from your point. This is a basis of the vectors which are orthogonal to $\nabla g_k$ where $g_k$ ranges over all your scalar constraints.
Comment: Say this basis is $x_1,\dots,x_n$. Then if $x_i^T H x_i>0$ for all $i$, then you have a min; if it is negative for all $i$, then you have a max; if it is strictly positive for some $i$ and strictly positive for some other $i$, then you have a saddle point; otherwise this method fails.
Comment: Note that more commonly in multivar calc you are just asking about global max and global min, which can be determined by simply substituting back into the objective function.
Comment: @Ian I would appreciate it if you elaborated about your hessian matrix and orthogonality towards constraints in a post
Answer: There is a second derivative test for constrained extrema. Here's the statement for the case of one constraint $g(x)=c$. Suppose $a$ is a constrained critical point of $f$ on the constraint set $g(x)=c$. Then we have $\nabla f(a)=\lambda\nabla g(a)$ for some scalar $\lambda$. Consider the Hessian matrix $H$ (matrix of second partial derivatives) of $f(x)-\lambda g(x)$, evaluated at $a$. Then if $v^\top Hv>0$ for all $v$ tangent to the constraint hypersurface at $a$, we conclude that $a$ is a constrained local minimum; if $v^\top Hv<0$ for all $v$ tangent to the constraint hypersurface at $a$, we conclude that $a$ is a constrained local maximum. [Interestingly, it does not work with the Hessian of $f$ alone.]
(One proves this by taking a parametrization $\phi$ of the constraint hypersurface near $a$ (say, with $\phi(0)=a$) and realizing that the function $f\circ\phi$ has a standard critical point at $0$, which can be characterized by looking at the Hessian of $f\circ\phi$ at $0$.)
Comment: To clarify. This extension of the second derivative test (the ordinary unconstrained one) is not usually taught in basic calculus classes, right?
Comment: Very much not taught. ;) But it appears as an exercise in occasional more advanced textbooks (including my own *Multivariable Mathematics* book) :P I believe I recall seeing it in some edition of Marsden and Tromba's book, as well.
Comment: Thanks for the help. Also is there an amazon link to this book of yours?
Comment: See my profile on MSE. Thanks. :)


Can't reverse DNS lookup with BIND9

Question: I'm creating an local network bind server.
I wrote this config file
/etc/bind/named.conf.local
include "/etc/bind/zones.rfc1918";
acl localnet {
  192.168.1.0/24;
  127.0.0.0/8;
};
zone "example.local" {
        type master;
        file "/etc/bind/db.example.local";
};

zone "1.168.192.in-addr.arpa" {
        type master;
        file "/etc/bind/db.192.168.1";
};

/etc/bind/db.example.local
$TTL            3600
@       IN SOA  ns.example.local. dns01.example.local. (
                2007112701;     Serial
                3600;         Refresh
                86400;          Retry
                2419200;        Expire
                3600 );       Negative Cache TTL
;
                IN NS   ns.example.local
        IN MX   10  mail01.example.local
@       IN A    192.168.1.108
dns01           IN A    192.168.1.108
ns              IN CNAME dns01
gateway         IN A    192.168.1.1

/etc/bind/db.192.168.1
$TTL    3600
@       IN SOA  ns.example.local. dns01.example.local. (
                2007112702;     Serial
                3600;         Refresh
                86400;          Retry
                2419200;        Expire
                3600 );       Negative Cache TTL
;
    IN  NS      ns.example.local.
200 IN  PTR dns01.example.local.
1   IN  PTR gateway.example.local.

and then /etc/init.d/bind9 restart
and /etc/resolv.conf
domain example.local
nameserver 192.168.1.108

$ nslookup dns01
Server:         192.168.1.108
Address:        192.168.1.108#53

Name:   dns01.example.local
Address: 192.168.1.108
$ nslookup dns01
Server:         192.168.1.108
Address:        192.168.1.108#53

Name:   dns01.example.local
Address: 192.168.1.108

$ nslookup 192.168.1.108
Server:         192.168.1.108
Address:        192.168.1.108#53

** server can't find 18.104.22.168.in-addr.arpa.: NXDOMAIN [#id7e65d6]

What's wrong?
Comment: -1 for not accepting the answer after 2 requests to do so and 4 years.
Comment: @ffffff - Please thank theotherreceive by accepting their answer.  The ettiquite of this site is to accept the answer which helps you resolve your question.  You might like to revisit most of your other questions and accept the answer which helped you resolve that question.  I'm sure the person answering the question would appreciate the recognition for helping you.
Answer: Is that your full /etc/bind/db.192.168.1, cause it doesn't include an entry for 108.
$TTL    3600
1.168.192.IN-ADDR.ARPA       IN SOA  ns.example.local. dns01.example.local. (
                2007112702;     Serial
                3600;         Refresh
                86400;          Retry
                2419200;        Expire
                3600 );       Negative Cache TTL
    IN  NS      ns.example.local.

$ORIGIN 1.168.192.IN-ADDR.ARPA.

108 IN  PTR     dns01.example.local.
1   IN  PTR     gateway.example.local.

Comment: It looks like you have an entry for dns01.zeg.local as 200, surely this should read 108?
Comment: oops! How to resolve?
Comment: Updated answer with suggested changes

Can't reverse DNS lookup with BIND9


The mean weight of 100 bags of rice is 90 pounds and the s.d. is 8 pounds. Bag A weighs 2 s.d. < mean and Bag B weighs 5 pounds > mean. Is A>B?

Question: The average weight of a set X of 100 bags of rice is 90 pounds , and the standard deviation is 8 pounds. Bag A weighs 2 standard deviations below the average weight and Bag B weighs 5 pounds more than Average.
Choose if quantity A or quantity B is bigger , equal or the information provided is not sufficient:
Quantity A: Difference between weight of Bag A and Bag B
Quantity B: The range of weight of bags in set X
Comment: using formula : mean+3*(sd) - mean - 3*(sd) where sd = standard deviation .. i used this formula but the answer said range cannot be calculated..
Answer: Hint:
Without knowing how the data are distributed, how can we determine the range (to calculate quantity B) just from knowing the mean and standard deviation?
So, I feel the answer should be: Cannot be determined.
Comment: We cannot calculate quantity B exactly, but can we establish bounds on it? Clearly $B>0$, otherwise the standard deviation would be $0$. Also $B<90\cdot 100$ (99 bags of weight 0, one bag of weight $90\cdot 100$). Using *all* information in the question (weights are positive, mean=90, sd=8, one bag weighs 90-2 sd, another weighs 90+5), how tight could we make the bounds on B? Tight enough to decide if A is bigger?
Comment: The formula you give, mean+3*(sd) - (mean - 3*(sd)) = 6*sd , is not a formula that gives you the range. Consider $\{0,2\}$: mean=1, sd=$\sqrt{2}$, range=2, 6sd$\neq$range. Or consider the [beta distribution](https://en.wikipedia.org/wiki/Beta_distribution), which has range $[0,1]$ no matter the value of its standard deviation.
Comment: Hey your answer is right but cant we determine the range by using the standard deviation graph? And then using formula : mean+3*(sd) - mean - 3*(sd) where sd = standard deviation? i thought like this but your answer is right i still don't get why we can't calculate range?


Instance of ViewModel is created every time, when using MediatR Publish and Splat in an Avalonia Project

Question: I have a small Avalonia Project and want to use MediatR for Notifications between ViewModels. To use MediatR i have to use the Splat.Microsoft.Extensions.DependencyInjection.
The problem is, every time i use Mediator.Publish to notify the MainViewModel from the StartViewModel a new instance of the MainViewModel is created although it is registerd as singleton.
I think my error is, that the MediatR registration itself creates a new entry in the service collection for the MainViewModel, ignoring the previous registration. But how can i tell MediatR not to create a new instance but using the already registered one.
In the App class i set up DI as folows:
public override void OnFrameworkInitializationCompleted()
{
    _host = Host
        .CreateDefaultBuilder()
        .ConfigureServices((_, services) =>
        {
            services.UseMicrosoftDependencyResolver();
            RegisterViewsAndViewModels(services);

            var resolver = Locator.CurrentMutable;
            resolver.InitializeSplat();
            resolver.InitializeReactiveUI();
            services.AddMediatR(cfg => {
                cfg.RegisterServicesFromAssembly(typeof(App).Assembly);
            });
        })
        .Build();

    Container = _host.Services;
    Container.UseMicrosoftDependencyResolver();

    if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
    {
        desktop.MainWindow = Locator.Current.GetService<MainWindow>();
    }
    else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
    {
        singleViewPlatform.MainView = Locator.Current.GetService<MainView>();
    }

    base.OnFrameworkInitializationCompleted();
}

The Views and ViewModels are registered in MS fashion:
private static void RegisterViewsAndViewModels(IServiceCollection services)
{
    services.AddTransient<MainWindow>();
    services.AddTransient<MainView>();
    services.AddSingleton<MainViewModel>();
}

In the MainWindow i resolve the MainViewModel once in the constructor:
DataContext = Locator.Current.GetService<MainViewModel>();
The MainViewModel itself implements INotificationHandler<ChangeViewModelEvent>:
public ViewModelBase CurrentViewModel
{
    get => _currentViewModel;
    private set => this.RaiseAndSetIfChanged(ref _currentViewModel, value);
}

public Task Handle(ChangeViewModelEvent @event, CancellationToken cancellationToken)
{
    Dispatcher.UIThread.Post(() => CurrentViewModel = @event.ViewModelName switch
    {
        nameof(NewViewModel) => Locator.Current.GetService<NewViewModel>() ??
                                  throw new ServiceNotFoundException(nameof(NewViewModel)),
        _ => CurrentViewModel
    });

    return Task.CompletedTask;
}

And in the StartViewModel i publish the notification:
private readonly IMediator _mediator;

public StartViewModel(IMediator mediator)
{
    _mediator = mediator;
}

public bool StartCommand()
{
    _mediator.Publish(new ChangeViewModelEvent(nameof(NewViewModel)));
    return true;
}

I already tried to change the registration to transient, use IRequest instead of INotification, changed the order of ViewModel and MediatR registrations.
Answer: Ok, so after doing a lot of reading it finally comes down to seperate the view model from the INotificationHandler<ChangeViewModelEvent> and implement a new Handler like this:
    public class ChangeViewModelEventHandler : INotificationHandler<ChangeViewModelEvent>
    {
        public Task Handle(ChangeViewModelEvent notification, CancellationToken cancellationToken)
        {
            var mainViewModel = Locator.Current.GetService<MainViewModel>() ??
                                throw new ServiceNotFoundException(nameof(MainViewModel));
            return mainViewModel.Handle(notification, cancellationToken);
        }
    }

Thats to complex for my needs so i ended in implementing my own, lightweight mediator.


Get parameters from the JS value key

Question: I face the problem and I hope they will help me here with advice.
There is an array of objects. (urlParams.categories)
I want to output using the extension operator (...) not all of these objects in their entirety, but the specific value of these objects by key (id). i.e.: 1, 2, 3, 4, and so on
I can do this using "for in" or "forEach", but I'm want to know if it can be done with (...)
I tried to do it like this:
let urlParams = {
  'categories': [
    { id: '1', name: 'Test' },
    { id: '2', name: 'Test' },
    { id: '3', name: 'Test' },
    { id: '4', name: 'Test' }
  ]
}

console.log(urlParams.categories)
console.log(...urlParams.categories.id)

Comment: No, you can't do that.
Comment: `urlParams.categories.map(cat => cat.id)`
Comment: That requires `urlParams.categories.id` to be an array, but the array is `urlParams.categories`
Comment: [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+get+property+values+from+array+of+object) of [From an array of objects, extract value of a property as array](https://stackoverflow.com/q/19590865/4642212).
Answer: You need to iterate over the categories to get the id:

const urlParams = {
  'categories': [
    { id: '1', name: 'Test' },
    { id: '2', name: 'Test' },
    { id: '3', name: 'Test' },
    { id: '4', name: 'Test' }
  ]
}

console.log(urlParams.categories.map(({id}) => id))
Answer:
I can do this using "for in" or "forEach", but I'm want to know if it
can be done with (...)

No, the ... called Spread. So from the definition on specs, everything you can do like this:
const categories = [...urlParams.categories];

to get an array of categories. After that, you have to use .map or something can loop such as for, forEach, reduce, etc.. to get exactly id of each category.

let urlParams = {
  'categories': [
    { id: '1', name: 'Test' },
    { id: '2', name: 'Test' },
    { id: '3', name: 'Test' },
    { id: '4', name: 'Test' }
  ]
};

const categories = [...urlParams.categories];
const result = categories.map(r => +r.id);
console.log(result);

Get parameters from the JS value key


University hierarchy in drupal 7

Question: I'm completely new to Drupal. I've been reading a lot of questions but I could not find anything that fits my needs. I need to create an internal site for my university.
There is one person that is the university coordinator (UC). This person should be able to add a department coordinator (DC) in a way that there are two fields in the form: department name (text field) and the email of DC. After submitting the form a new user should be created with the username the same as name in the email (before @) with a random password that is sent to the email address. This user should be below UC in the hierarchy. DC then should be able to add institute coordinators (IC) the same way. Each DC should be able to manage their ICs. How can I set-up this scenario? Which modules should I install? Is it possible without writing code?
Comment: Drupal can achieve this functionality, but (more) easily without your exact user interface. For example look at the LDAP module if your users are already in ldap groups and their existance is already in LDAP. To break up the site into sections and groups of users see the Organic Group module. If you can live with how-drupal-does-it largely you dont need to write code. If you want a custom UI and workflow -- then enjoy learning coding your snowflake application.
Comment: Welcome to Drupal Answers! Questions asking to recommend or find a module are off-topic for us. You need to find a module that is closer to your needs; then you can ask how to achieve what you want with that module, or ask in which way that module can be extended to achieve what you want.
Answer:
We need university coordinator role, we can create it in People > Permissions > Roles.
Next, we create department coordinator. We do it just like in first step.
University coordinator can make a new user and set a role to it. So we create user DC, set the e-mail firstname.lastname@example.com and set the password loremipsum. Standalone Drupal has not possibility to generate a random password.

Then, to let department coordinator manage the insitute coordinators you should install Administer Users by Role. One problem - this module don't let you to manage content created by the users.

University hierarchy in drupal 7


ConnectException vs. IOException when wiFi is disabled?

Question: I tried connecting to an IP address (e.g. http://126.96.36.199:8080) and a URL (e.g. http://www.website.com) while my wiFi is disabled. I noticed that if I don't have a wiFi and I tried connecting to an IP address, it gives me a ConnectException error. On the other hand, if I don't have a wiFi and I tried connecting to a URL, it gives me an IOException error. Why am I receiving different Exception for the 2 cases when the only difference is I supplied an IP address for the first one and a URL for the other? Can someone enlighten me on this one? I am asking this for clarification.
Thank you!
Comment: Are you using HttpUrlConnection, HttpClient or another class to connect to the URLs?
Answer: You're getting different errors because different steps are failing.
When you're trying to connect to port 80 of an IP address, it is a connect(2) system call that is failing. There are many different reasons why connect(2) could fail; you'll need to inspect the message from the exception to provide a good error message to the user.
When you're trying to connect to port 80 of a textual address, the libraries will first try to resolve the hostname into an IP address using getaddrinfo(3). The name resolution may or may not fail based on having network access -- if you were trying to connect to localhost, for example, no network access is usually required, as the nameservice lookup can be handled entirely on the local device. Because the nameservice failure happens because you cannot contact a nameserver, it makes sense to give a different error message (and exception), even if the underlying cause is the same for a given set of tests. You might not be able to contact the nameservers for any variety of reasons. Again, you'll need to inspect the message from the exception to give a good error message to the user.
Comment: Thanks for your answer! If I understand your explanation correctly, Android has different steps for connecting to an IP address and a textual address? Since the 2 has different steps, the error message are handled differently? Trying to connect to a textual address means you still have to connect to a nameserver to resolve the ip address. If it wasn't able to retrieve the ip address from the nameserver, a different error message is returned. A ConnectException is only returned if you are already trying to an IP address but fails to establish a connection?
Comment: It isn't specific to Android; it's generic across all devices and platforms that support the TCP/IP family of protocols. The details of the error messages change from platform to platform, but in general you can get the _protocol_-level error quite easily -- translating that to a human-friendly piece of advice such as "Your modem is unplugged" or "The network cable is backwards" or "The WiFi router is down" is immensely difficult.


Erro ao chamar add em um HashSet

Question: Toda vez que tento criar um objeto.add(); e coloco o atributo nele, ele continuar a me dar um erro. Veja o meu código:
public class Agencia {
    private String nome;
    private String endr;
    Set<Conta> listaContas = new HashSet<Conta>();

    private int nrAgencia;

    public Agencia(int pNrAgencia, String pNome, String pEndr){
        this.setNome(pNome);
        this.setEndr(pEndr);
        this.setNrAgencia(pNrAgencia);

        //AQUI ESTA
        //O Netbens me informa que ha um erro, e não consigo resolver
        listaContas.add(pNrAgencia);

    }

 //Outra Classe
 public class Conta {
      Conta(int pnrConta,  double pSaldo, Agencia agencia,Pessoa ptitular){
        System.out.println("Nome:");
        ptitular.setNome(scan.nextLine());

        System.out.println("Endereço:");
        ptitular.setEndr(scan.nextLine());

        this.setNrConta(pnrConta);
        this.setSaldo(pSaldo);

        //Agencia
         System.out.println("Informe o numero da agencia");
        agencia.setNrAgencia(scan.nextInt());
    }

    public Conta() {

    }

Comment: `listaContas` é um `Set`, então você só pode adicionar instâncias de `Conta` nele. Você tentou adicionar `pNrAgencia`, que é um `int` (e não uma `Conta`), por isso o erro.
Comment: no caso irei instanciar da classe conta, dentro da hashset ?
Comment: Você cria uma `Conta` e em seguida adiciona ela no `HashSet`
Comment: tem como fazer um pequeno exemplo simples, pq eu fiz isso e deu erro, possa ser que  eu nao esteja entendendo.
Answer: public class Agencia {
    private String nome;
    private String endr;
    Set<Conta> listaContas = new HashSet<Conta>();

    private int nrAgencia;

    public Agencia(int pNrAgencia, String pNome, String pEndr){
       Conta conta = new Conta();
        listaContas.add(conta);
    //o Set não aceita duplicidade e não garante ordenação
    // e também esta tipado para receber o tipo conta então ele deve receber conta

    }

Comment: eu te amo cara, muito muito muito obrigado
Comment: @Vitor Só um detalhe, `new Conta()` cria uma conta "vazia" (sem os campos preenchidos, portanto sem número, saldo, agência e titular). Faz sentido criar uma conta vazia e adicioná-la em `listaContas` quando vc cria uma agência? Ao criar uma agência, ela pode começar sem nenhuma conta, e `new HashSet` já inicializa `listaContas`, então nem precisaria criar e adicionar a conta vazia. Até mesmo o construtor sem parâmetros é algo a ser avaliado, entenda melhor lendo este link:  https://pt.stackoverflow.com/q/73530/112052
Comment: @Vitor Outro detalhe é que recomenda-se que objetos que são adicionados em um `HashSet` implementem `equals` e `hashcode`. Entenda melhor lendo [aqui](https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/), [aqui](https://pt.stackoverflow.com/q/11108/112052), [aqui](https://pt.stackoverflow.com/q/122978/112052) e [aqui](https://pt.stackoverflow.com/q/111208/112052)

Erro ao chamar add em um HashSet


How common is perfect pitch?

Question: It is said here that 1 in 10,000 people have absolute pitch. I wonder if there is any serious poll that could confirm this.
Do you know any study that could tell how common/uncommon it is to have absolute pitch ?
Comment: It certainly gets expressed much more often among musicians, in my experience.
Answer: Those numbers are a rough estimate, and only applies to US citizens.
Wikipedia has a thorough overview of the relevant information, here. The most salient points:

Absolute pitch seems to be a cognitive act. It's a property of our brains, and not our ears
Most people exhibit some ability or sub-components of absolute pitch
Absolute pitch appears to be trainable to a very high degree. It can be taught/learned.
Different populations have different percent exhibition for absolute pitch - some estimates for chinese speaking populations go as high as 40-50%.

So, two answers to your question:

1/10000 is a rough estimate for US citizens exhibiting absolute pitch
Since absolute pitch is trainable, and most people exhibit some components of it, it's unlikely we can get better than a very rough estimate.
Comment: Just to support this answer: When you've listened to the same song *a million* times, you'll probably find yourself humming it, or "hear it" in your head. When you've done this many times you'll often find that you've remembered the pitch correctly. This is also a great way to practice it - to just regularly check if you're humming the right tone by checking it on the piano
Comment: Most people asking about "perfect pitch" have this idea that it is genetic and innate. The evidence seems to deny this possibility. It is very difficult to disentangle language and training from the phenomenon.
Comment: @MeaningfulUsername: I am absolutely certain your friends who you think exhibit this have training in it. I know non-professional people who play games trying to guess (named) pitch of notes. The fact is that if one has the words to describe the pitch, they have training. The earliest studies in children suggest that (a) people have a natural ability to identify pitch in some manner, and (b) people who are raised without tonal languages gradually "lose" the ability. Now couple that with the answer above regarding trainability.
Comment: My point it that might never know because language and training in and of itself is required to test it: the biological facility is not accessible without priming it. I think this differs quite a bit from your summation?
Comment: Where do you see me denying personal differences in people? This is the typical binary discussion that many people have about these types of things. "Perfect pitch" is distinct from "fast-processing relative pitch" in every single discussion I have seen on the topic, including scholarly articles. "Better at recognizing pitch" is not Perfect Pitch. The topic here is not about actualizing potentials, it is about how common is something that hasn't been established to exist.
Comment: Just to add to horatio's initial comment, I came across a study on perfect pitch among people who learn languages with tones, Chinese and Taiwanese in particular.  It was found that "perfect pitch" was very high among the people tested, even if they had no musical ability or training.  But this does not mean they were not trained.  Their language requires pitch identification and replication for communication.  So, in a sense they were "trained" from infancy.
Comment: @horatio: It is also very hard to deny evidence of it being a "given" ability, with friends having it and so on. As usual, it is a blend. Some people definitely has a natural talent in this area, while some never will obtain it. I have seen no evidence to the contrary.  Like most things, it can be trained, but the starting point is very different for different people.
Comment: I think we can both agree that proving something doesn't exist can be difficult, and you will note that my point was by the time anything concrete can be tested, it is almost too late to know: "it is very difficult to disentangle language and training from the phenomenon."
Comment: @horatio: So the concept of being naturally good at something does not exist? Talent is a myth? My friend and I grew up together, started playing at the same time. He always was better at recognizing pitch. We speak the same language. It is not black and white, but to deny that there are differences in peoples potential is as bad (possibly worse) as saying it is all due to genes.
Comment: @horatio: So your point is that no one has perfect pitch without training? I can buy that. But if someone achieves it with minimal training (just listening to music perhaps) while someone else needs many hours of dedicated training to achieve the same level, it's a matter of semantics. In my view. I guess you can draw a parallel with drawing. You need to train, but some people will advance quickly to levels others will never achieve.
Comment: Ok. There is a possibility that I have learned something from this discussion, and that I see what you mean.
Answer: This is less a music question than a behavioral science question, and there is a self-diagnosed issue with much such research is focused on a sample set that is "WEIRD": Western, educated, industrialized, rich and democratic.
There is no reason to believe that the proportion of people with perfect pitch in a university with researchers studying the brain, which often has a school of music which might attract people with perfect pitch wanting to participate in scientific studies for pizza money, has any relation to the proportion of the same generally.

How common is perfect pitch?


execute a cmd command with java to create a data basse

Question: my CMD command is to create a data basse withe Sqlite3
it's work with CMD but with java it's not
My Code java :
Runtime.getRuntime().exec("cd /");
Runtime.getRuntime().exec("cd C:\Users...");
Runtime.getRuntime().exec("Sqlite3");
Runtime.getRuntime().exec("Sqlite3 DB.db");

Comment: are you trying to run cmd from java.. or is it just about accessing sql in java?
Comment: Doing a `cd` in a subprocess is useless, because its effect is local to the subprocess and you are still at the original working directory when it ends.
Comment: yes i'm trying to run cmd from java
Answer: You're doing it wrong. You do not need to run standalone sqlite application with Runtime.exec. Better use a library the following way.
When you connect to a non-existent SQLite database, SQLite automatically creates a new database. Therefore, to create a new database, you just need to specify the database name and connect to it.
The following program creates a new SQLite database named test.db in the folder c:\sqlite\db.
package net.sqlitetutorial;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author sqlitetutorial.net
 */
public class Main {

    /**
     * Connect to a sample database
     *
     * @param fileName the database file name
     */
    public static void createNewDatabase(String fileName) {

        String url = "jdbc:sqlite:C:/sqlite/db/" + fileName;

        try (Connection conn = DriverManager.getConnection(url)) {
            if (conn != null) {
                DatabaseMetaData meta = conn.getMetaData();
                System.out.println("The driver name is " + meta.getDriverName());
                System.out.println("A new database has been created.");
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ClassNotFoundException {

        // You will probably need to uncomment the following "class.forName"
        // and copy dependency configuration to your pom.xml
        // if you stumble upon "No suitable driver found" error.
        /*
        <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.7.2</version>
        </dependency>
        */
        //Class.forName("org.sqlite.JDBC");
        createNewDatabase("test.db");
    }

}

Source: http://www.sqlitetutorial.net/sqlite-java/create-database/
Comment: but when i do that, and instal the app in partition C:\ it 's dosen't work !! so try to do it like this with cmd command
Comment: What is the exact reason it doesn't work? Any exception thrown by java application? Incorrect path, no access to create or write to file maybe?
Comment: it's say i don't have access permission, but when i instal in partion D:\ it's work
Comment: One last question. After you create this sqlite3 file (no matter, my way or by running external cmd), do you need to operate on it somehow? Do you need to create tables, read and write data from your java code to this database?
Comment: yes of yes of course i need to create the data basse and the tables this in the fisrt time i run my app and after that i do the reading, writing and updates
Comment: Well it obviously means you have no reason to create a database using external tools. You have a library specifically designed to do it. The only thing left is to figure out why your java program doesn't have enough permissions to access file and eventually you will have to figure it out anyway, if you plan to access the database from your program. So I would strongly recommend not to invent the wheel and create database with `java.sql`.


Debian - What to do when upgrading packages and a config file has changes?

Question: I'm new to system administration and I'm helping admin a server for a student group. I was wondering, what is the best practice for when you're upgrading packages and a config file has changes. I've been looking at the differences and then usually just leaving the old version unless it looks like there is something important to add, and otherwise merging the config files manually with kdiff3, but is there a better way to do it?
Also, do I have to backup the old file somewhere myself or does dpkg automatically make a backup? I sometimes I noticed .old files in some directories for old versions of config files.
This issue is complicated by the fact that since I'm new to this group, I don't know why some changes are the way they are, but if in doubt I've been deferring to the existing version.
By the way, I'd like some specificity. Eg, when dpkg prompts you with the whole Y/N/I/O/D/etc thing, what do you do? Do you back up the old file, install the new one, and then merge, or is there a better way to merge the files when you're in that ncurses prompt thing?
Answer: that seems like a reasonable way of doing it.  similar to what i've been doing for about 15 years (been using debian since 1994).  it's always worked for me :)
i start with the basic assumption that if i've modified a config file, then i had a good reason for it, and my changes are likely to be better/more important than anything in the new default config file.
i then examine both my config and the new packaged version and either:

completely ignore any differences because they're either not important or not relevant to my setup.
merge anything useful from the new config into my existing config.
if there's a lot of new stuff and only a small amount of my changes that i want to keep, then i do the reverse and merge my changes into the new config file and then use that.

i don't use any specialised or GUI tools for this.  i just use 'diff -u' and less and vi plus occasionally some of the standard text processing tools like sed or perl. colordiff is nice, too, when the diff output is more than a screenful or so.
Comment: yes, if you choose to replace your current config file, it will be renamed to filename.dpkg-old.   if you choose to keep your current config file, the packaged file will be renamed to filename.dpkg-dist
Comment: By the way, does dpkg automatically stick the new and old files somewhere or does it just delete the old file when you install the new one?
Comment: BTW, this renaming to .dpkg-old and .dpkg-dist is the main reason why run-parts won't, by default, run files with a . in them, otherwise it would end up doing bad things like running both the old and the new version of cron jobs in /etc/cron.*/ which would be ++ungood.
Comment: Just like to ACK this answer, it's exactly what I've done for many years
Comment: Another +1. This approach certainly works well for a single or small number of systems. Anything bigger and you should start looking at configuration management tools.
Answer: Although I agree with Craig Sanders' answer, I have to add one caveat: During many upgrades (usually between releases -- like Hardy --> Intrepid) apt reports config files as changes when I haven't changed them. If I'm confident that I haven't changed a config file, I'll just choose to dump the old one and keep the package maintainer's version.
Answer: Just spotted this post looking for the answer to a similar question of mine.
What I ended up doing after all is choose to open a terminal, do a 3-way merge with meld,
<code>meld file.conf file.conf.dpkg-old file.conf.dpkg-new
</code>
save the result to file.conf and go on with that
Comment: That's an answer to how to merge changes.  The OP is asking about larger issues caused by editing configuration files that are managed by a package management system.
Comment: Heh, at this point I don't even know what I was asking about. Merge tools are useful of course. One thing I've found since I posted this that's quite helpful is etckeeper. At least for smaller systems I see no reason not to use it, it just puts /etc under version control (git in my case) which is pretty handy if you're confused about what changes you've made in the past. The auto commits won't tell you why you did something though.
Answer: Yes the best to do is, IMHO, to get the maintainer version and report in it the customized values.
This way you are ensured to have the very up to date config file, with updated comments, commented out default values and so on.
When you got a confict in the updating process because of a new config file version the best to to is to keep the best between our version and the maintainer one, keep note of the file to review and then manually edit the file to merge th differneces by hand (vimdiff is a very powerful way, but kdiff is a good choice too :)
The very important thing to keep in mind is to avoid having custom config files out of date!
My 2 cents :)
Comment: the trouble with just accepting the maintainer version is that it is FAR more likely to break your currently working setup (because it wipes your hand-edited changes) than keeping your customised version.  it's extremely rare for an upgraded package to have an incompatible new config file (and when they do, the package often has a postinst script to handle it), so keeping your config file is generally safe.  in most cases, your config file will work perfectly well, as is with no extra work required....but the maintainer file will always require editing to bring back your changes.
Comment: Hmm, I should get my vimfoo up to snuff. I've been through vimtutor and it seems fairly nice, but I've been kind of preferring emacs because of elisp and its customizability. But emacs is annoying to run over ssh and a bad connection, whereas vim is not as bad.
Comment: I do not told to barely accept the maintainer file, but to absolutely make every effort in order to keep our customization in sink with it!...  sorry for having been not so clear


by group random effect GAM

Question: I am currently learning how to use GAMs and try to model a species response (resp) to different environmental parameters (x1, x2, x3) that were sampled at different locations (random effect). My understanding is that I should allow each predictor to have its own smoother per species level (by=species) but I struggle to understand what this would do in the random effect term and how to best specify it. The example model is of the form:
gam(resp ~ s(x1, by=species) + s(x2, by=species) +
           s(x3, by=species) + s(location, bs="re")

and I try to understand what is happening if I include either of these three terms:
(1) s(location, bs="re")
(2) s(location, by="species", bs="re")
(3) s(location, species, bs="re")

Answer: Your base model is incorrectly specified; factor by smooths must have the by factor included as a parametric categorical term in the model, hence you need:
gam(resp ~ species +
      s(x1, by = species) +
      s(x2, by = species) +
      s(x3, by = species) +
      s(location, bs = "re")

This allows for the mean of the response in each level of species to be included in the model as a specific term, while the smooths by species, which are centred, are used to model smooth variation about these species specific mean responses.
That said...
s(location, bs = "re")
s(location, bs = "re") would indicate an i.i.d. Guassian random intercept term in the model. In other words we get an intercept for each level of the factor location (and it must be a factor to get this interpretation), and those intercepts are shrunk towards 0 as part of the penalized likelihood used in fitting. This is mathematically the same as including (1 | location) in a mixed effects model using lme4 notation for random effects.
s(location, by = species, bs = "re")
(Note that it is by = species, not "species".) This is the same as the above, except the random effect is nested in the levels of the factor species. What this means practically is that the amount of shrinkage over all the locations can vary between species. This is because each smooth generated by by = species gets its own smoothness parameter, $\lambda$, and it is this that controls the degree of shrinkage (penalisation) that each "smooth" is subject to. We're just using the equivalence of smooths and random effects to fit the equivalence of i.i.d. Gaussian random effects in these GAMs.
s(location, species, bs = "re")
Assuming that both location and species are factors, then you would get a random intercept for the groups formed by the interaction of location and species. Consider the following two factors, each with two levels:
levs <- c("A", "B")
df <- data.frame(f1 = factor(sample(levs, 50, replace = TRUE)),
                 f2 = factor(sample(levs, 50, replace = TRUE)))
with(df, table(f1, f2))

The last bit shows the two-way table
   f2
f1   A  B
  A 17 11
  B 11 11

So we have the four combinations:

"A:A",
"A:B",
"B:A", and
"B:B"

and we can think about the combination of these two factors creating 4 groups. The term s(f1, f2, bs = "re") would then yield a random intercept for these four groups.
Technically, it results in the addition of ~ f1:f2 - 1 columns to the model matrix:
r$> head(model.matrix(~ f1:f2 - 1, data = df))
  f1A:f2A f1B:f2A f1A:f2B f1B:f2B
1       0       0       1       0
2       0       0       1       0
3       0       0       0       1
4       0       1       0       0
5       0       0       1       0
6       0       0       0       1

which we can see as binary indicators for the groups defined by the interaction of the two factors. These columns are associated with a diagonal penalty matrix (which is what achieves the shrinkage): this is a ridge penalty on the coefficients associated with these columns of the model matrix, and which yields i.i.d. Gaussian random effects.
Continuous variables in s(...., bs = "re")
Adding a continuous variable to a random effect spline will get you a "random slope" term. These always go with at least one factor, so we might have
~ s(temperature, group, bs = "re")

with temperature a continuous variable and group a factor (explicitly coded as a factor in R!). Thus we will get terms ~ temperature:group - 1 added to the model matrix of the model, which we will see as a random effect of temperature within each level of the factor group. Again, these columns are associated with a diagonal(ridge) penalty, leading to i.i.d. Gaussian random effects of temperature.
N <- 10
df <- data.frame(group = factor(sample(c("A", "B"), N, replace = TRUE)),
                 temperature = runif(N, 2, 25))
model.matrix( ~ temperature:group - 1, data = df)

which results in
   temperature:groupA temperature:groupB
1            20.24348            0.00000
2            15.38841            0.00000
3             0.00000           11.35646
4            18.29931            0.00000
5             0.00000           11.15989
6             0.00000            4.20421
7            23.05284            0.00000
8             0.00000           13.64325
9             0.00000           16.17145
10            0.00000           18.00376

and hence we get a separate coefficient for each column, and hence a "random slope" for each group, with the diagonal (ridge) penalty shrinking the coefficients for these columns towards zero, with the amount of shrinkage determined during fitting.
Note that with the formulation in {mgcv}, we cannot achieve the same as (1 + temperature | group), which would imply correlated random effects, where the random intercepts for group and correlated with the random slope of temperature for each group. In {mgcv}, the best we can do is
~ s(group, bs = "re") + s(temperature, group, bs = "re")

which yields uncorrelated random effects, which in {lme4} syntax would be
~ (1 | group) + (0 + temperature | group)

and possibly some other shorthand (IIRC?: (temperature || group)).
Comment: That is a fantastic answer! Thank you very much. May I ask one more follow-up question: If no a priori knowledge exists about the random structure in a GAM (whether it should just have a random intercept or a random slope), is it safe to select the random structure by AICc score?
Comment: @Globoquadrina You shouldn't use AICc; AIC for GAMs is problematic and the AIC computed for GAMs in {mgcv} via function `AIC()` includes some correction for smoothness selection and is formulated in a way that is appropriate for smooths. Unless the AICc implementation you are using has those features (and I'm not aware of any) you might get mislead by it. I also come from the school of thought that doesn't like this kind of model selection. If I had reason to include a term in the model it should stay in the model & I report the estimated effects accordingly, even if ~0

by group random effect GAM


how to return the second node of a path in neo4j?

Question: I have a query for finding paths:
MATCH p =(o:Order)-[r:seeks*2..8]->(o:Order)
WHERE o.Name="000089"
  AND ALL(x IN tail(nodes(p))
          WHERE SINGLE(y IN tail(nodes(p))
                       WHERE x=y))
RETURN extract(n IN nodes(p)| n.Name) AS OrderID, length(p)
ORDER BY length(p)

My output is:
OrderID length(p)

[000089, 000091, 000089]                                    2
[000089, 000093, 000090, 000089]                            3
[000089, 000091, 000096, 000095, 000090, 000089]            5
[000089, 000091, 000096, 000097, 000093, 000090, 000089]    6
[000089, 000091, 000098, 000092, 000095, 000090, 000089]    6
[000089, 000093, 000090, 000096, 000097, 000091, 000089]    6
[000089, 000093, 000094, 000092, 000097, 000091, 000089]    6

So, what I also want to is to return the second node on each path like (the nodes marked in bold above):

[000091]
[000093]
[000091]
[000091]
[000091]
[000093]
[000093]
Comment: What is the goal of the second part of your `WHERE` condition, `ALL(x IN tail(nodes(p) WHERE SINGLE(y IN tail(nodes(p)) WHERE x=y))`? As far as I can see, this is already ensured by the `MATCH` clause: `(o:Order)-[r:seeks*2..8]->(o:Order)` -> this makes sure that the start and the end of the path are the same.
Comment: The second part is not to visit a node in a path twice other than the starting and the ending node.
Comment: Neo4j makes sure that it does not use the same relationships twice: see the notes on [uniqueness](https://neo4j.com/docs/developer-manual/3.0/cypher/#cypherdoc-uniqueness). This might work for your use case as well (depending on the details of your data model).
Answer: I created a simple dataset for experimenting:
CREATE
   (o1:Order {Name: '0089'})-[:seeks]->
   (o2:Order {Name: '0090'})-[:seeks]->
   (o3:Order {Name: '0091'})-[:seeks]->(o1)

This an (o1)->(o2)->(o3)->(o1) circle.
Use the nodes function to extract the nodes on the path and index the list to second node. Lists in Cypher are indexed from zero.
MATCH p=(o:Order {Name: '0089'})-[r:seeks*2..8]->(o:Order)
RETURN nodes(p)[1]

Alternatively, you can do it without using a path variable and getting the endNode of the first relationship (note that this will only work for directed relationships):
MATCH (o:Order {Name: '0089'})-[r:seeks*2..8]->(o:Order)
RETURN endNode(r[0])


For $A$ in rational canonical form, find $B$ with $AB=BA$ but for which $B \notin Span\{ A^i \mid 0\leq i \leq n-1\}$

Question: As part of a larger question, I've reached the point where I need to prove the following claim:

Let $\mathbb{F}$ be a field.  Let $A \in M_n(\mathbb{F})$ be in
rational canonical form.  Prove that if $A$ is not a one-block matrix
(one companion matrix), then there exists a $B\in M_n(\mathbb{F})$,
with $AB=BA$ but for which $B \notin Span\{ A^i \mid 0\leq i \leq n-1\}$.

Besides playing around with specific examples and specific $n$, I'm unable to come up with a general way of constructing such a $B$. My question is twofold, with the second one being even more important to me:

What could be such a $B$?
How does one tackle such a question? I used to think that playing around with examples should give sufficient intuition, but I'm often encountering these situations where I'm still none the wiser after doing so (as in this case). I would be extremely grateful if the suggestion for a solution would offer the thought process of how you came up with it too.
Answer: Let $A=C_1\oplus C_2\oplus\cdots\oplus C_r$ where each $\chi_i$ (the characteristic polynomial of $C_i$) divides $\chi_{i+1}$. Let $B=I\oplus0\oplus\cdots\oplus0$. If $B=p(A)$ for some polynomial $p$, then $\chi_2|p$. In turn, $\chi_1|p$ and $p(C_1)=0$. Now we arrive at a contradiction because the first diagonal sub-block of $B$ is $I$.
Comment: Thanks - why must $\chi_2 \mid p$?
Comment: @Anon $C_2$ is a companion matrix. Its characteristic polynomial is precisely its minimal polynomial, which divides every annihilating polynomial.
Comment: Also - would be great to know what led you to this choice of $B$ (some insight into how you started to tackle this question would be really helpful).
Comment: @Anon $p$ doesn't annihilate $A$. It annihilates $C_2$. E.g. when $A$ has only two diagonal sub-blocks, we have $\pmatrix{I\\ &0}=B=p(A)=\pmatrix{p(C_1)\\ &p(C_2)}$. Hence $p(C_1)=I$ and $p(C_2)=0$.
Comment: Yes - thanks! I just realised that's what you meant.


When will a plot of principal components against each other reveal a meaningful correlation?

Question: I read these two threads:
Why are principal component scores uncorrelated?
Questions on PCA: when are PCs independent? why is PCA sensitive to scaling? why are PCs constrained to be orthogonal?
and learned that PC modes are by definition orthogonal and thus uncorrelated. So why do I see people plot PC modes against each other if they're uncorrelated? In what case will e.g. a PC1 vs PC2 plot reveal a meaningful correlation?
Answer: It's true that PCs are orthogonal, implying zero Pearson correlation and no linear relationship between them. However, zero Pearson correlation doesn't generally imply independence. The PCs might be nonlinearly related, reflecting nonlinear structure in the data. For example, consider the 3d 'swiss roll' dataset below (left). Its projection onto the first two PCs (right) shows the spiral structure.

Furthermore, even if the PCs turn out to be independent (which we wouldn't know a priori), plotting them can still reveal something useful about how the data are distributed. For example, consider the clustered 3d dataset below (left). Its projection onto the first two PCs (right) shows the clustered structure.

PCA scatterplots are just low-dimensional visualizations of the data. One use is to learn something about the structure of the underlying distribution. This won't always work; e.g. sometimes the underlying structure can't be adequately captured by low dimensional linear projections. But, it's often a good first-pass attempt. Another use is to visualize how the data are related to some external variable, e.g. by coloring points in the scatterplot according to the variable of interest.
Comment: Thanks for the clear answer. Apparently, I interpreted "no correlation" and "orthogonal" as "independent". Marked as answered
Comment: @Niels glad to help


Apiko - trying to update an existing file

Question: With the Quasar Framework has created a form to add and update files on the server Apiko.
With this code trying to update a file that already exists on the server Apiko - https://gist.github.com/gearmobile/cc7de273d9c526b589e198eb35ff89d6
However the update file on the server Apiko fails, and the browser console there are no errors.
Console Apiko gives this log:
...
[APIKO LOG 11:34:25.093] Checking if a different session token is specified...
[APIKO LOG 11:34:25.093] No session token is specified, going with luYzmm9Dgzte2OKcLvIyN2b4K5c8Ijeu
[APIKO LOG 11:34:25.094] Checking restrictions...
[APIKO LOG 11:34:25.094] This request has passed the restrictions check.
[APIKO LOG 11:34:25.094] Checking parameters...
[APIKO LOG 11:34:25.094] This request has passed the params check.

Help to understand, what is the cause of the error?
Answer: You are using the PUT /files/:id endpoint, which is not implemented in Apiko by default. The reason is that normally to update files you can instead delete an existing one (DELETE /files/:id) and upload a new file (POST /files).
Alternatively, you can create a custom endpoint that would override PUT /files/:id to handle file updates for you.
If you would like to see this feature in Apiko's core, please go ahead and vote here.
Comment: therefore, if I want to make an app which will only use the basic features Apiko, I need to exclude this page from my project?


How could I model a prediction base on current dataset

Question: This is not about asking syntax, but rather asking concept of using R.
Let's assume I am a HR person and I have a huge set of data, for example:
EmployeeID      Date-Join      Date-Terminated      Current Base Pay    Last Increment Date   ManagerID
123             11-Sept-1990   NA                   8,000               1-April-2016          ABC
456             31-Dec-2010    1-May-2016           11,000              NA                    ABC
789             12-May-2010    3-June-2015          3,000               5-Feb-2015            ABC

I wish to analyze the reasons of why employees are leaving the company. For instance, it could be the employee are not happy with the current pay. But the factor however are not limited to the amount purely. The same amount carry different meaning to everyone and every context.
Besides the base pay, there are still a lot of possibilities contributed to the termination. For example, how long has it been since the last promotion/increment? How much is the increment amount? And human factors like the employee is not feeling happy with the manager etc.
So I am confused right now. I have no issue at plotting graphs. But I need guidance in how to combine them to show me some useful picture.
In short, eventually what I wish to see is: when I input a new data set, the program written could predict how likely the employee is about leaving the company.
Answer: Preprocess your dataset to create a labeled dataset as follows, the dataset you are starting with must have both existing employees and the employees already left.
EmployeeID      Years_of_Employment   Base_Pay  Years_Since_Last_Increment JobTitle  Has_Left
123             10                    8000                     1           Manager   0
456             2                     11000                    2           Developer 1

Here the Has_left is the binary response variable (0: the employee has left, 1: the employee is still working) that you are interested to learn from the other feature variables (add some more predictors that you think can have impact on the attrition).
Now use the above dataset to train a logistic regression model. You can use the model to predict the probability that a new employee will leave, given the values of all the dependent feature variables.
Comment: Alright, thanks Sandipan. I will take time to study on your suggestion. :)
Answer: In general, preprocessing your dataset into the suggested form is the first thing you should do. Also, conducting a logistic regression is the method of choice for your research question.
However, since you want to know which independent variables (e.g. base payment or years of employment) have a significant influence on your dependent variable (i.e. staying in or leaving the company), I suggest to use a stepAIC algorithm in order to find the best fitting model. Following this way you could answer questions such as "Are particular managers connected to significantly high leave rates?" or "Does an interaction between base pay and the time since the last increment have an influence on leaving the company?".
In particular you could do something like this:
set.seed(1337)
# load or install MASS (contains stepAIC)
library(MASS)
# dependent variable (0 = has not left the company, 1 = has left the company)
has.left <- sample(rep(c(1,0,1),1000),100)
# independent variables (i.e. possible predictors)
years.of.employment <- sample(rep(c(1,2,3),1000),100)
base.pay <- sample(rep(c(1000,2000,3000),1000),100)
managaer.id <- sample(rep(c(1,2,3),1000),100)
# put everything in a data.frame
df <- data.frame(years.of.employment, base.pay, managaer.id)
# generate a model containing all possible variable interactions (.^2)
model <- lm(has.left~.^2,data=df)
# run algorithm
best.fit <- stepAIC(model)
# show model summary
summary(best.fit)

# OUTPUT
# Residuals:
#   Min      1Q  Median      3Q     Max
# -0.8169 -0.5673  0.2902  0.3723  0.5615
#
# Coefficients:
#   Estimate Std. Error t value Pr(>|t|)
# (Intercept)                   3.488e-01  3.304e-01   1.055    0.294
# years.of.employment           1.469e-01  1.598e-01   0.919    0.360
# base.pay                      2.191e-04  1.571e-04   1.395    0.166
# years.of.employment:base.pay -1.120e-04  7.496e-05  -1.494    0.138
#
# Residual standard error: 0.4834 on 96 degrees of freedom
# Multiple R-squared:  0.03746, Adjusted R-squared:  0.00738
# F-statistic: 1.245 on 3 and 96 DF,  p-value: 0.2977

Briefly explained, including the variables years.of.employment, base.pay as well as their interaction would represent the best fitting model here. Not to mention that this is just to show the basic principle since all data is randomly generated. Please note that you can also manipulate the direction of the stepAIC algorithm (i.e. forward, backward, forward/backward) which leads to different results and depends on both your data and your research question (by default the direction is backward).
Overall, it should further be mentioned that exploratory data analysis should be conducted with caution and you should have hypotheses before testing. However, this is a point which rather goes into a methodological direction.
Comment: Hi, may I ask for a more detail explanation on this line:

`model <- lm(has.left~.^2,data=df)`

'lm' stands for linear model. But I am not sure what is 'has.left~.^2' any why are you writing in such way.
Comment: For calculating a linear model you have to define a model formula. has.left is here the dependent variable while df holds all independent variables (i.e. predictors).  ".^2" just means that you'll include all variables in df as well as all possible interactions (which are two in the given example).
Comment: Wow, now I understood. Thanks a lot! Highly appreciated. :)
Comment: Thanks dude, a very detail explanation. I will take time to study on your suggestion. :)