spark data read with quoted string

Question: i am having the csv data file as given below
each line is terminated by a Carriage Return('\r')
but certain value of  text are multilined field having line delimiter as line feed ('\n'). how to use spark data source api option to handle these issue.
with enter image description here
Comment: Did you checked this https://stackoverflow.com/questions/45274559/spark-read-csv-file-with-quote
Answer: Spark 2.2.0 has added support for parsing multi-line CSV files. You can use following to read a csv with multi-line:
<code>val df = spark.read
  .option("sep", ",")
  .option("quote", "")
  .option("multiLine", "true")
  .option("inferSchema", "true")
  .csv(file_name)
</code>

spark data read with quoted string


If Matrix A, B are similar, is the sum of the diagonals equal?

Question: Given Matrix $A \sim B$ , can the sum of the diagonals be equal?
E.g
$$
A = \begin{bmatrix}
0 & 2 & -3  \\
-1 & 3 & -3 \\
1 & -2 & a  \\
\end{bmatrix},\qquad\qquad
B = \begin{bmatrix}
1 & -2 & 0  \\
0 & b & 0 \\
0 & 3 & 1  \\
\end{bmatrix}
$$
Why $A \sim B$ can result $0+3+a=1+b+1$?
Comment: **Welcome to Mathematics Stack Exchange!** A quick [tour](https://math.stackexchange.com/tour) will enhance your experience. Here are helpful tips to [write a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960) and [write a good answer](https://stackoverflow.com/help/how-to-answer).
Answer: $\newcommand{\tr}{\operatorname{tr}}$
The sum of the numbers on the diagonal of a matrix $A$ is called the trace of $A$ which is denoted by $\tr(A)$. The trace of a product of three square matrices of the same size $A,B,C$ satisfies $$\tr(ABC)=\tr(BCA),\qquad \text{(cyclicity)}$$ Then if $A$ and $B$ are similar matrices, i.e. there exists an invertible matrix $P$ such that $A=PBP^{-1}$, then we have that $$\tr(A)=\tr(PBP^{-1})=\tr(BP^{-1}P)=\tr(BI)=\tr(B)$$
Answer: Alternatively, you can note that similar matrices must have the same characteristic polynomial, and thus the same eigenvalues. The sum of the eigenvalues is the trace of the polynomial, so any two similar matrices must share the same trace.


Suppose that $f:\mathbb C \to \mathbb C$ is an analytic function. Then $f$ is a polynomial if...

Question: Suppose that $f:\mathbb C \to \mathbb C$ is an analytic function. Then $f$ is a polynomial if (select all that apply):
(A) For any point $a\in \mathbb C$, if $f(z)=\sum_{n=0}^\infty a_n(z-a)^n$ is a power series expansion at $a$, Then $a_n=0$ for atleast  one $n$.
(B) $\lim _{\left|z\right|\to \infty }\left|f\left(z\right)\right|=M$
(C) $\lim _{\left|z\right|\to \infty }\left|f\left(z\right)\right|=\infty $
(D) $\left|f\left(z\right)\right|\le M\left|z\right|^{n\ }$ for $|z|$ sufficiently large and for some $n$.
I know that (B) is false and (C) is true. I can prove it. (D) is also true. How do I prove (A) is true? Given in the Answer key that (A) is true.
For any point $a\in \mathbb C$, if $f(z)=\sum_{n=0}^\infty a_n(z-z_o)^n$ is a power series expansion at $a$, Then $a_n=0$ for at least  one $n$.
Consider the power series with $a_{2n+1}=0$ and $a_{2n}=1$ this is not a polynomial. How do (A) is true?
Comment: How did you prove (b) is false?
Comment: Note that (A) says that for any point the series expansion has a vanishing term. You have exhibited an example for which that happens in one point, so it does not follow that the associated series is a polynomial.
Comment: https://math.stackexchange.com/questions/1361377/lim-limits-z-to-infty-fz-infty-show-that-f-is-a-polynomial @mheldman
Comment: @Unknownx well, that question says that if the limit is infinity along every path then it is a polynomial. This is not the same as saying that if the limit of the magnitude exists then it is not a polynomial. Remember if (B) holds then $f$ is a bounded, analytic function
Answer: For A, Consider $$B:=\{z\in \Bbb C: f^{(n)}(z)=0\;\text{for some}\; n \in \Bbb N \}=\bigcup_n\{z\in \Bbb C: f^{(n)}(z)=0\}$$
Here $B$ is uncountable. That means, atleast one set in the union is uncountable. Thus, $\exists k$ so that $\{z: f^{(k)}(z)=0\}$ is uncountable, so it has limit point in $\Bbb C$ and hence result follows!
Comment: Alternatively, since $B=\mathbb{C} $ by hypothesis, we can use the Baire category Theorem and then the identity Theorem.
Comment: Is it follow from the fact that every infinite set has a limit point?
Comment: Yes! and by identity theorem f is a polynomial of degree less than or equal to k
Answer: $B$ is true, by Liouville's theorem.
$A$ is sufficient (see the other answer).
$C$ is apparently true (see the link in the comments).
For $D$ it means $\mid f(z)\mid=O(\mid z^n\mid)$.  It's sufficient. See this.
Comment: (A) He wants the series expansion **at any point** having at least one zero coefficient. It means that given $z_{0}$, $f^{n}\left(z_{0}\right)=0$ for at least one $n$. $\cos z$ doesn't have this property.

For (C), note that $\lim_{x\rightarrow-\infty}e^{x}=0$, so I can't see how $e^{z}$ diverges in all directions in the complex plane.
Comment: https://math.stackexchange.com/questions/1361377/lim-limits-z-to-infty-fz-infty-show-that-f-is-a-polynomial
Comment: Ok.  I blew it.  @Unknownx


What does attributte section mean in UEFI memmap?

Question: When I call memmap in the UEFI shell, I got two different attributes like the following:
Shell> memmap
Type       Start            End              # Pages          Attributes
Available  0000000080000000-00000000CFFFFFFF 0000000000050000 000000000000000E
Available  0000002000000000-000000237FFFFFFF 0000000000380000 000000000000000F

The problem is that I cannot use the second region of memory whose attribute marks as 000000000000000F. I've already registered that part of memory to my page table. But, my OS will panic when I convert a physical address from that region to a virtual address.
So, my problem is:

What does the attribute means?
How can I change the attribute so that I can use that part of memory?
Comment: The attribute values are shown in the `EFI_MEMORY_...` macros in "include/linux/efi.h" in the kernel source.
Comment: Attribute definition could be found in UEFI spec section 7.2, or P166 of [UEFI spec 2.8 Errata A](https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_A_Feb14.pdf)
Answer: The memmap command displays the memory map that is maintained by the UEFI environment by listing the contents of EFI_MEMORY_DESCRIPTOR for each memory region.
typedef struct {
 UINT32                 Type;
 EFI_PHYSICAL_ADDRESS   PhysicalStart;
 EFI_VIRTUAL_ADDRESS    VirtualStart;
 UINT64                 NumberOfPages;
 UINT64                 Attribute;
} EFI_MEMORY_DESCRIPTOR;

The Attribute field of a memory region describes the bit mask of capabilities for that memory region, and not necessarily the current settings for that memory region.
//*******************************************************
// Memory Attribute Definitions
//*******************************************************
// These types can be "ORed" together as needed.
#define EFI_MEMORY_UC            0x0000000000000001
#define EFI_MEMORY_WC            0x0000000000000002
#define EFI_MEMORY_WT            0x0000000000000004
#define EFI_MEMORY_WB            0x0000000000000008
#define EFI_MEMORY_UCE           0x0000000000000010
#define EFI_MEMORY_WP            0x0000000000001000
#define EFI_MEMORY_RP            0x0000000000002000
#define EFI_MEMORY_XP            0x0000000000004000
#define EFI_MEMORY_NV            0x0000000000008000
#define EFI_MEMORY_MORE_RELIABLE 0x0000000000010000
#define EFI_MEMORY_RO            0x0000000000020000
#define EFI_MEMORY_SP            0x0000000000040000
#define EFI_MEMORY_CPU_CRYPTO    0x0000000000080000
#define EFI_MEMORY_RUNTIME       0x8000000000000000

Full details about each of these attributes can be found in the UEFI Specification Section 7.2 under GetMemoryMap.
The only difference in attribute value between your two memory regions is EFI_MEMORY_UC, i.e. memory is not cacheable.


How can I prove this sequence convergent?

Question: I am trying to prove the sequence $(u_n)$ so that $u_1=1$ and $u_{n+1}=1+\dfrac{1}{u_n}$ is convergent. With some first items, I guess that the subsequence $(u_{2n})$ is decreasing and the subsequence $(u_{2n-1})$ is increasing, but I can't proof this. How can I proof?
Comment: You are dealing with the sequence of the convergents of the continued fraction of the golden ratio $\varphi=\frac{1+\sqrt{5}}{2}=1+\frac{1}{\varphi}$.
Answer: Hint: We can write
$$u_{3} = 1 + \frac{1}{1 + \frac{1}{u_1}} = 1 + \frac{u_1}{u_1+1} =
\frac{u_1+1}{u_1+1} + \frac{u_1}{u_1+1}
= \frac{2u_1+1}{u_1+1}$$
$$u_{4} = 1+\frac{u_1+1}{2u_1+1} =
\frac{2u_1+1}{2u_1+1} + \frac{u_1+1}{2u_1+1} =
\frac{3u_1+2}{2u_1+1}$$
$$u_{5} = 1 + \frac{2u_1+1}{3u_1+2} =
\frac{3u_1+2}{3u_1+2} + \frac{2u_1+1}{3u_1+2} =
 \frac{5u_1+3}{3u_1+2}$$
Notice a pattern? You can prove it using induction!
Comment: Nơ I can't see genal formula to proof by induction.
Comment: You see that it is the Fibonacci numbers, right? What I'm doing in each of these cases is expanding the $1$ as the denominator of the other fraction. I guess I'll elaborate with an extra step.
Comment: Yes. Thank you very much.
Comment: Also, you can simplify the proof with some loss of generality using $u_1=1$. Does this edit clear things up?
Comment: Yes. Thanks again.
Answer: First, solve your recurrence for its limit by writing $L=1+\frac 1L$.  Now you can look at the distance from $L$ by writing
$$u_{k+1}-L=1+\frac 1{(u_k-L)+L}-L$$
and note that if $u_k \lt L, u_{k+1} \gt L$ and vice versa.  This shows the even terms are bounded below by $L$ and the odd terms are bounded above by $L$.
Now plug the definition for $u_k$ in terms of $u_{k-1}$ into the above and show the distance on the left is decreasing toward zero for the even terms and increasing toward zero for the odd terms.
Answer: I want to show another possible approach.
Consider $f(x) = 1 + \frac{1}{x}$ for $x>0$. $f$ is clearly decreasing.
Thus $f \circ f$ is increasing.
We also have $u_1=1$, $u_2 = 2$, $u_3 = \frac{3}{2} > u_1$ and $u_4 = \frac{5}{3} < u_2$.
Since $u_{n+2} = f(f(u_n))$ it's very easy to see (by induction and using $f \circ f$ increasing) that $u_1 < u_3 < u_5 < \ldots$ and that $u_2 > u_4 > u_6 > \ldots$!
Let's call $\varphi = \frac{1+ \sqrt{5}}{2}$ the fixed point of $f$. Again by induction on $n$, it's easy to verify that $u_{2n+1} < \varphi < u_{2n}$ for any $n \in \mathbb{N}$.
Now because of boundness in the right direction both $u_{2n}$ and $u_{2n+1}$ converge. Let's call $l$ and $m$ the two limits. We have (since $u_{n+1} = f(u_n)$ and $f$ is continuous) $l = f(m)$ and $m = f(l)$.
Thus $lm = l+1$ and $lm = m+1$. So $l=m$ and $l= \varphi$.
Therefore the sequence converges to $\varphi$
Comment: I can' find general formulas of u_2n and u_2n-1. Can you help me?


CDN Image Redirects (avoiding redirect loop w/ htaccess)

Question: I have everything up and running on AWS Cloudfront CDN, the only issue I've hit is regarding my image files. They all display as wanted, but the old versions don't force redirect.
For example:
An image @ http://domain.com/images/image.jpg will direct and display at http://cdn.domain.com/images/image.jpg, but the previous version without the subdomain is accessible too.
I know it sounds a little tedious, but all the "juice" that was going to the previous image isn't going to the new image because it's not forcing that redirect. Ideally anytime I put http://domain.com/images/image.jpg in the browser I'd want it to redirect to http://cdn.domain.com/images/image.jpg. Every fix I've found online will create a loop though since it doesn't read whats before domain.com.
I know there's a solid way of doing this redirect in htaccess to just the jpegs in the images folder that aren't already redirected to the cdn. subdomain, but I can't find it anywhere online.  Any help would be immensely appreciated.
Answer: Try adding this to the document root of domain.com
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.+\.(png|gif|jpe?g))$ http://cdn.domain.com/$1 [L,R=301]

Comment: The `^` in front of domain ensures that it is the beginning of the match. `cdn.domain.com` will not match that regex
Comment: I used your code and adjusted it to...    `RewriteEngine On    RewriteCond %{REQUEST_URI} !^domain\.com$ [NC]    RewriteRule ^(.+\.(png|gif|jpe?g))$ http://cdn.domain.com/$1 [L,R=301]`   Seems to be working - Does that make sense to you though? I don't want to break anything inadvertently.
Comment: That seems perfect outside of the ^domain\.com on the second line (& ] at the end, which I know was just a typo). I think that's whats creating a loop since both 'cdn.domain.com' & 'domain.com' would be redirected. Regex is definitely not my forte, but is there a way to explicitly redirect only if the 'cdn' isn't already there?


Geometry question using tangents and Pythagorus

Question: The pic below shows my exercise. BA is a tangent and equal to 12, R = 4.5. I need to find DC and AC.

The pic below shows what I came up with so far:
I know that AD is 15, since ∢DBA = 90.
What I though to do next is to add BC cause ∢BCD = 90 and i can use Pythagorus, but the calculation dont come up right...please just give me a hint..tnx

Answer: You can use Pythagoras on each of $\triangle BCD$ and $\triangle BCA$ and subtract the equations from each other.
Or you can use the Power of a Point theorem which says that in your picture $(AC) (AD) = (AB)^2$.
Answer:
Using your own picture with joining $BC$.
Do you see that $\triangle BCD$ is inscribed in semi-circle? What can you infer from that? $\angle BCD=90^ \circ$, right?
Now it means $\angle BCD=90^\circ$.
$\therefore$ You can use Pythagoras theorem.
$BC$ is common, you can express $BC^2=BD^2-DC^2$. Also $BC^2=BA^2-CA^2$. Now equate them both.
$9^2-x^2=12^2-(x-15)^2 \implies 81-x^2=144-(x^2+225-30x)$, can you solve this?


Exercise with field extensions

Question: In a field with characteristic other than 2, if we have two elements in our field, $a,b \in F$ such that $F(\sqrt{a})= F(\sqrt{b})$ and $[F(\sqrt{a}):F]=[F(\sqrt{b}):F]=2$
Then we can deduce that $ab \in F^2$
I am not sure how to do this. How do we know that  $ab \in F^2$ ? Why is this true?
Answer: Note that since $F(\sqrt{a})=F(\sqrt{b})$ and both are of degree $2$, then we can express $\sqrt{a}$ as $\sqrt{a}=r+s\sqrt{b}$ for some $s,b\in{F}$. Squaring both sides we get
$$a = r^2 + s^2b + 2rs\sqrt{b}.$$
That means that $2rs=0$, and since the characteristic is not $2$, then $rs=0$, so $r=0$ or $s=0$.
Can you take it from there?
Comment: I can take it partly from there. If r=0 then a=bs^2 so then ab=(sb)^2, and we are done, right?
Comment: I am less sure about the s=0 case.
Comment: @EricJames: That would mean $a=r^2$, but then $\sqrt{a}=\pm r\in F$. Is that possible?
Comment: Ah, I see. Thank you for the help!

Exercise with field extensions


Can you change the DirectoryIndex of specific directories?

Question: I know that you can use DirectoryIndex example.html in .htaccess, but what I need is to change the index for specific directories, like so:
DirectoryIndex /ex/index_file.html

or
DirectoryIndex /ex2/index_file2.html

Is there a way that you can accomplish this? I don't want to rename the file I'm trying to do this for to index.html because that's not what it is. You are required to login first, and if you're not it will redirect you; but I think that looks sloppy.
Comment: I mean like, say I have 2 separate directories. `dir1` and `dir2`. For `dir1` I want the DirectoryIndex to be `example.html` and for `dir2` I want the DirectoryIndex to be `another_example.html`. Does that help?
Comment: Oh got it I guess you can read the answer down there, I guess it should solve
Answer: You can create an .htaccess in each directory that you want a different directory index in. The .htaccess in the ex directory should contain:
DirectoryIndex index_file.html

But the on in ex2 should contain:
DirectoryIndex index_file2.html

You can also use <Directory> in the .htaccess in your web root as long as you are allowed to override this:
<Directory ex>
   DirectoryIndex index_file.html
</Directory>

<Directory ex2>
    DirectoryIndex index_file2.html
</Directory>

Comment: This solved my question. :) I thought you might be able to do that, I guess I should've tried before posting the questions; oh well. Thanks for the help!


Lotus Notes Traveler server did not respond within the allotted time frame

Question: I have Lotus Notes Traveler 126.96.36.199 Build 201411031333 running on Lotus Domino server Release 8.5.3FP6 November 21, 2013 on a Windows/64 (2 Processors) platform  This server is dedicated for Traveler only, no other addons like Sametime or other is installed on this pc.
Problem is When I access Traveler via mobile or browser, it usually gives me following error (sometimes after succesfull login and sometimes always)
Lotus Notes Traveler server did not respond within the allotted time frame.

and on Server I can see errors like following
JVM: Traveler: Lotus Traveler task did not respond within the allotted time frame (55,000 milliseconds) for action GET and operation key

It happens very frequently, So far I have tried various suggestions available on the different forums example:
Started Traveler with Defrag ...
Added the following lines to the Notes.ini to bind the ip (as suggested at some blog)
NTS_IPC_TCP_Port=50125,192.168.1.1
NTS_IPC_TCP_Port2=50126,192.168.1.1
Added the following line to the servlet.properties file (in Server Data folder). (as suggested at some blog)
Text
ntstimeoutsyncas=230000
But no use still getting errors and timeout frequently.The server is for Local LAN connected users which are directly connected on same subnet without any firewall, also it is serving external internet base mobile users as well. Sometimes the page opens perfectly without delay, but most of time it gives timeout error. when there is timeout error, all mobile devices are unable to synch. After few retries they somehow manage to sync sometime.
I have disabled the Symantec Antivirus and backup exec agent as well but no use.
The real problem comes when I have to register new device by visiting traveler portal like http://traveler_server/traveler and it gives time out several times :(
When i restart the traveler server, it works fine for few minutes, then it starts making problem.
this is traveler status command output
[0230:07A9-0C3C]  There have been 9 device sync failures for reasons other than the server is too busy.
[0230:07A9-0C3C] The overall status of Lotus Notes Traveler is Yellow.
its green when i restart the server, but then goes to yellow after few minutes.
Answer: Run the following command's from the Domino console:
Tell HTTP Quit
Tell Traveler Quit
Load Traveler -defrag


Como esconder barra lateral e vertical com CSS

Question: Gostaria de esconder essas duas barras (Vertical e Horizontal), configurei meu arquivo .css com as definições abaixo, mas não estão funcionando:
@charset "UTF-8";

section#conteudo{
  width: 1000px;
  margin:  auto;
}

iframe#frameEspecificacoes{
  width: 400px;
  height: 280px;
  border: none;
  overflow: hidden;
}

iframe#frameEspecificacoes::-webkit-scrollbar {
  display: none;
}

Comment: Tentaste usar `overflow: hidden;`?
Comment: É o que estou usando em iframe#frameEspecificacoes. E não dá certo.
Comment: O elemento que contêm o iframe tem que ter o `overflow:hidden` tambem
Comment: Não funcionou, acabei de adicionar...
Comment: Verifica qual elemento está com as barras de rolagem, pois certamente não é o iframe, como Section tem largura de 1000px verifica se o elemento Pai do Section não é o que está estourando.
Comment: Comigo também não funcionou nesse exercício, talvez não seja a melhor forma, mas só consegui esconder a barra de rolagem usando o parâmetro/atributo (scrolling="none") dentro da tag iframe. Ex.:
Comment: Também só consegui acrescentando scrolling="no" na tag
Answer: É necessário verificar qual elemento está estourando, ou seja, tendo sua largura/altura excedida pelo tamanho do conteúdo, e aplicar overflow: hidden; a esse elemento:

body {
 overflow: hidden;
}

section#conteudo{
 width: 1000px;
 margin: auto;
 overflow: hidden;
}

iframe#frameEspecificacoes{
  background: #AAA;
 width: 400px;
 height: 280px;
 border: none;
 overflow: hidden;
}

iframe#frameEspecificacoes::-webkit-scrollbar {
 display: none;
}

Comment: Não está estourando, acredito eu, porque o width está em 900px, do conteúdo restante da página, olhando melhor o que me parece está acontecendo é o não reconhecimento do ::-webkit-scrollbar, que o código fica com cor branca, como se não estivesse sendo reconhecido. Será?
Answer: Boa noite galerinha, fiz esse curso e passei pelo mesmo problema, já dei uma resposta aqui no fórum para incluir  na página specs.html.
Hoje vim dar a resposta ainda melhor, a solução "semanticamente correta" que é insirir
body {
overflow-x: hidden;
overflow-y: hidden;
}

no css da página google-glass.html.


UIView transitionFromView change view heigh

Question: I am using this code to change between 2 UIView:
UIViewAnimationOptions animationType = UIViewAnimationOptionTransitionFlipFromLeft;

[UIView transitionFromView:self.playlistTableView toView:self.playerView duration:0.5 options:animationType completion:^(BOOL finished){
     [self.containerView sendSubviewToBack:self.upperView];
     [self.containerView sendSubviewToBack:self.playerView];

     self.isPlaylistVisible = !self.isPlaylistVisible;
     isControlsHidden = NO;
}];

And i noticed a strange behavior, that when i made the flip the height of the self.playerView loosing 20px and after one second it's increase back to the normal frame size.
I try to change the animationType to UIViewAnimationOptionLayoutSubviews and now when i change between the view this behavior is not occur.
Any idea what can be the issue?
Comment: Check autoresizing. View's autoresizingMask first of all. And autoresizesSubviews property of self.containerView.
Comment: What should i set as autoresizesSubviews?
Comment: autoresizesSubviews = NO. autoresizingMask = UIViewAutoresizingNone.
Answer: Please try this code.
        [self.upperView setHidden:YES];
        [self.playerView setHidden:NO];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:containerView cache:YES];
        [UIView setAnimationDuration:1.0];
        [UIView commitAnimations];
        [containerView addSubview:self.playerView];

For getting reverse case
    [self.upperView setHidden:NO];
    [self.playerView setHidden:YES];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:containerView cache:YES];
    [UIView setAnimationDuration:1.0];
    [UIView commitAnimations];
    [containerView addSubview:self.upperView];


Posterior formula for classifier training

Question: In an introductory video on Bayesian methods for classification (see reference at the end), the lecturer explains that training involves the computation of the following posterior distribution:
$$
P(\theta|X, y) = \frac{P(y|X,\theta)P(\theta)}{P(y|X)}
$$
To make sure we're on the same page, the terms are:

$\theta$ are the parameters we're trying to learn
$(X, y)$ are the data (X are the feature vectors, y are the labels)
$P(\theta)$ is the prior belief in the parameters (e.g. that they're around 0 and so on)

The lecturer claims that this is an application of Bayes' rule, which I'm not able to verify. Could you point me in the right direction? Here's what I'm doing:
$$
\begin{align}
    P(\theta|X, y) &= \frac{P(\theta, X, y)}{P(X, y)} \text{(conditional prob. definition)}\\
    & = \frac{P(\theta, X, y)}{P(y, X)} \text{(conjunction commutes)}\\
    & = \frac{P(\theta, X, y)}{P(y|X)P(X)} \text{(chain rule)}\\
    &= \frac{P(y|X, \theta)P(X, \theta)}{P(y|X)P(X)} \text{(chain rule)}\\
    &= \frac{P(y|X, \theta)P(\theta|X)P(X)}{P(y|X)P(X)} \text{(chain rule)}\\
    &= \frac{P(y|X, \theta)P(\theta|X)}{P(y|X)} \text{($P(X)$s cancel)}\\
\end{align}
$$
Not only does this not coincide with the lecturer's formula, the term $P(\theta|X)$ seems even more difficult to compute than $P(\theta|X,y)$ because we can't look at the ground truths $y$ in computing $\theta$ anymore. Regardless of whether this last observation is true, I'm primarily interested in a derivation for the lecturer's formula.
Thanks for your time.
References
Bayesian Methods for Machine Learning, Coursera, Week 1, "Bayesian approach to statistics".
Answer: \begin{align}
P(\theta|X,y)&=\frac{P(\theta, y|X)}{P(y|X)}\\
&=\frac{P(y|X,\theta)P(\theta)}{P(y|X)}
\end{align}
$X$ is always in the conditional part in both sides of the expression so there is no reason to find a joint distribution involving $X$.
Your derivation is also correct. The prior information is however independent from $X$(hence called 'prior'). So $P(\theta|X) = P(\theta)$.
Comment: Thank you very much. Unable to vote this up due to lack of reputation, but I appreciate the thoughtful response. (I should probably spend some time doing exercises with conditional probabilities: those inferences aren't obvious to me, e.g. that $P(\theta|X, y) = \frac{P(\theta,y|X)}{P(y|X)}$.)
Comment: This is basically the definition of conditional probability. You don't necessarily have to take all variables and divide their joint distribution by the distribution of all the variables on the "given side" of the probability(as you did in your first step above). It is possible to just apply the rule on a subset of the variables, as long as you leave the rest in the conditioning side. Also, as I said, your derivation is also correct. Please accept the answer if you feel that I have answered your question


What data structure would you use to implement a dictionary?

Question: So I had an interview question about what data structure I would use to implement a dictionary. I said a map because you can enter the word and get the definition in return.
The follow up question was what data structure I would use to implement a system where the user only wanted to lookup a certain number of the starting letters of a word (i.e the first 3 letters) such that the user can get a list of, for example, all the words in the dictionary that start with fic.
I said something about a binary tree but really I had NO idea; the interviewer said the answer was TYPEAHEAD, something like what Microsoft Visual Studio's intellisense does. I had no idea what that was and I have tried to look it up on google but am getting some weird search results. Even though I have no idea what this is and never used it before it is definitely an interesting question.
Does anyone know how to do this? What kind of data structure and what would be the implementation method?
Edit: I'm confused why this is being closed. Is this not a programming question?
Comment: TYPEAHEAD is not the name of a standard data structure of which I am aware.  The interviewer was full of it unless the question was specific to a technology stack that offers such a data structure.  For what it's worth, though, you should look for a tree-based data structure called a "trie".  That's how I'd guess intellisense is in fact implemented.
Comment: I would imagine it would still be a map, and you would use specialized sort and find predicates to get the keys ranges you want.
Answer: Use Trie, a type of tree. Follow this link for solution and better understanding: Trie
Comment: This isn't a link-only answer.  It is an acceptable attempt to answer the question, but it is very sparse on details.  The bigger problem is that this whole question is too broad and opinion based.


Select and Input different heights/text indent

Question: On this page, there's a text indent/white space on the select before the option.
The CSS for both is:
input, select {
margin: 0px;
height: 38px;
border: 0;
padding: 0 0 0 15px;
}

I changed the default select to remove the FF drop down which may have affected it:
select {
border-radius: 0;
-webkit-appearance: none;
-moz-appearance: none;
text-indent: 0.01px;
text-overflow: '';
appearance: none;
}

Any ideas appreciated.
Edit: I got the height the same by adding this to the select and input:
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;

PS the question is and was clear, unless you don't speak English.
Comment: Where is the question in this post? Please revise.
Comment: possible duplicate of [Issue with Input & Select tag height in form](http://stackoverflow.com/questions/9767612/issue-with-input-select-tag-height-in-form)
Comment: PS! The question is and was **not clear**, regardless of language preferences.
Answer: So I got the the PC and checked out the CSS in the developer console:
I found that turning off the float:left on the span within your submit button fixed the vertical alignment and height of the items
(Either change the CSS from affecting all #search-bar span or add one for button.span to float:none)
Instead of setting height:38px on the select and input, set their padding to something like padding: 5px 0px 5px 0px; and leave their height at default
That fixes your text alignment problem in firefox
I see you've updated your code - these mods were done on your original so I don't know if they still hold. Might help you along though
(Oh, and your current white-space issue is cause by the padding 0 0 0 15px; - it's the 15px that's adding it)
Comment: Sorry, but this answer surely demonstrates a very poor effort into help the user, you just tell him a standard answer. It seems that you don't want to help, but want to be the fastest gun.
Comment: Actually he was asking for any ideas, and adding a css reset is what I would do when faced with his problem if I couldn't see what was happening in firebug. He gave no indication as to what he had tried already, and I thought this could help him with his debugging.
Comment: As I see, the OP seems to already have a css reset in his page: `@import "/css/css_reset.css";`
Comment: At least it contributed to a cleaner question. I would have just commented but at the time did not have the rep to do so. Should I remove the answer?
Comment: The new answer I think it's more accurate and now you're giving a factible option to the OP. I will remove the -1. Thanks for your efforts.


Time series analysis of image metadata

Question: The data set that I have—a user's corpus of photos with time taken and an array of locations in each of them. Location is a bit hierarchical in nature, thus an array, like country, state, county, place.
Between two users, I'm trying to find an image from user A which is closest(most relevant recommendation on the basis of time and location) to one from user B.
The approach I'm taking is to convert each photo of user A(and B) into a vector with one coefficient representative of time and one representative of location and then choose between Euclidean distance or hamming distance to find the closest.
I need a few suggestions here:

I'm currently deriving the time coefficient using the following method. Plot images taken on each day against time. The image coefficient of each images is the number of images taken on the day/daily average
I need alternative recommendations, like standard deviation, or any thing else. The intuition is, that image relevant in terms of time (which it is if the user has taken higher than average number of images on a day).
For location, I'm doing a similar thing, calculating the importance of a location, by number of times the particular location is observed/total number of locations. This I'm doing for all the elements in the array. Now how do I combine these numbers to get one representative number? Is there a different formula I should be using?
Finally, assuming that we have a vector of time and location, is euclidean distance a better representation than hamming distance?

Any help with the thinking will be highly appreciated.
Comment: Your questions seem objectively unanswerable because you haven't yet described what "closest" is intended to mean.  Could you elaborate on that?
Comment: @whuber Closest in this case means most relevant in terms of time and location. Let's say most recommendable against the first image. I'm adding this to the question.
Comment: The trick is to clarify what you might mean by "most relevant" so it can be quantified.  That's not something that can be done through statistical analysis: you have to tell us what "relevant" means and how one distance might be "better" than another.
Comment: @whuber so let's imagine this to be a simulation of private image sharing. If I share an image with you, what would be the most relevant image to share in return. That's my definition of relevant. Does it help?
Comment: I'm sorry, it doesn't help in the least.  Maybe "relevance" for me means an image of the same people; maybe it means an image with the same background; maybe it means an image taken at the same time of day; *etc.*  What this demonstrates is that "relevant" is a highly personal and subjective concept.  Unless you can communicate clearly what you mean by it, your question won't be answerable.
Answer: Let me assume from your question "Between two users, I'm trying to find an image from user A which is closest(most relevant recommendation on the basis of time and location) to one from user B." that the content of the photo is irrelevant from the scoring.
You could use simple least square regression using dummy variables for each dates and location, sort the coefficients and classify individual by their highest few coefficients.
Most locations and dates that are not included in the data set will be 0, and should not appear in the model, and at most you will have n parameters for n locations (this can be also grouped as street - town - country).
For the 'importance of location' by frequency of the photo, the dummy variable coefficient will be adjusted accordingly when you include an interaction term, such as (time * location). Only take coefficients, and
Alternatively, you could implement a classification method according to scoring?
This way will be less exact in matching coinciding events, such as 2016 Christmas eve in Vegas. However, this way you can match similarities between the 'days of week' 'time of the day' such as Friday evenings can be isolated.
First method would be more appropriate for suggesting a restaurant that could be available to both parties, finding a person who was in an event at certain day as we have more resolution.
The second method can be used in context where the matching is for somewhat  broader preference or personal patterns for example date matching.
Hope my 2 cents helps!!
Comment: Welcome to stats.SE!  Please take a moment to view our [tour].  Your fourth paragraph seems to be missing a thought—it would be helpful if you edited your answer to complete it..

Time series analysis of image metadata


Can't get i18n-js working with firebase functions

Question: I have set up a minimal working example of i18n-js:
<code>// located in: src/i18n.ts
const i18n = require('i18n-js')

i18n.locale = 'en'
i18n.fallbacks = true
i18n.translations = {
  en: {
    hello: 'Hello',
  },
  es: {
    hello: 'Hola',
  },
  fr: {
    hello: 'Bonjour',
  },
}

exports.i18n = i18n
</code>
When I try to use it in a firebase functions as follows, I get the error below.
<code>// located in: src/testFunction/testFunction.ts
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
const i18n = require('../i18n')
admin.initializeApp()

const testFunction = functions.https.onCall(
  async (
    data: {dummyVar: string},
    context
  ) => {
    console.log(i18n.t('hello'), dummyVar)
  }
)

export default testFunction
</code>
<code>// located in: src/index.ts

import testFunction from './testFunction'

exports.testFunction = testFunction
</code>
Error Message:
<code>functions: Failed to load function definition from source: FirebaseError: Failed to load function definition from source: Failed to generate manifest from function source: SyntaxError: Unexpected token 'export'
</code>
Do you have an idea?
Answer: I didn't manage to find a solution using i18n-js. So I switched to i18next, which now works fine!


Bulk read in pymongo loop

Question: currently, using pymongo, I'm iterating through a very large mongodb collection like this:
client = MongoClient(config.get('db','url'))
db=client.mydatabase
incomings = db.incoming.find()

for incoming in incomings:
    do something with incoming

Instead, with each loop iteration, I would like to read a certain amount of dicts/documents at once, so I won't get dict after dict from the database, but rather a set of dicts like this: [{...},{...},{...},...]
I'm aiming to reduce the load on the database. If with the use of the cursor it's already ideal, then I'm fine with my current solution.
BTW, the incoming collection is being pounded with hundreds of documents per second, it serves as a permanent buffer for incoming zmq messages.
Can you provide me with any performance improvement considerations, especially for my case with many data coming in and out?
With storing data, I'm already buffering using insert_many instead of single inserts, and of course data is leaving the collection by using delete_many.
Answer: If you're seeing a performance bottleneck, consider using a replicaset; once set up, do your reads from a secondary database (set your read preference to secondaryPreferred).
Comment: this does  not answer the question asked
Comment: Thank you very much, it absolutely makes sense to scale, the load on each server will say thank you to such a decision. And I say thank you to you!

Bulk read in pymongo loop


Getting the trailing slash back in ExpressionEngine 2?

Question: I have just upgraded from EE 1 to EE 2 and I am struggling with some of the changes. For example, the fact that EE no longer outputs a trailing slash on its urls is making a mess of a lot of my links where I had depended on constructions like EE generated url + additional segment. Finding and editing all places where I have done that would be a small nightmare considering the size and setup of my site. Is there any way to hack EE to get back the old behaviour?
Comment: Looks like {path=} and {url_title_path} rely on `$this->EE->functions->create_url($path)`, so that might be a place to hack an extra slash in. However i would recommend a search and replace in the templates above hacking core EE.
Comment: can you explain a bit more "constructions like EE generated url + additional segment"?
Comment: For example, I had an issue with a template where I was using the Tags module and I needed to setup a link like this:"{path='Characters/Season'}/{websafe_tag}/". Originally, I did not need the / before {websafe_tag} since the first part of the url was generated with a trailing slash. So I have depended on that in a lot of instances.
Comment: I would go for a search and replace if I knew off the top of my head all the various combinations where I've used a similar construction, but we're talking templates built up over 6 years and about 400 of them, so it is daunting to say the least. I will take a look at that function, thank you. :)
Answer: For some the trailing slash addition mentioned might cause conflicts with some forms. Adding the following to check if the request is a GET might be safer.
# Add a trailing slash to paths without an extension
RewriteCond %{THE_REQUEST} ^GET
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule ^(.*)$ $1/ [L,R=301]

Comment: I've finally had time to test this and I am a bit mystified as to how this actually works. With it added to my .htaccess, if I click a link on one of my pages, the new page still loads without a trailing slash.
Answer: There is an .htaccess solution to this, which I've used in my older EE sites because of this issue exactly.
Add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule ^(.*)$ $1/ [L,R=301]

Source: http://devot-ee.com/articles/item/simple-htaccess-for-expressionengine-sites
However, since it's there by default in EE2, you might want to do the OPPOSITE and remove the trailing slash via .htaccess so you don't have to manually add/delete/whatever. If you decide on that, here's the code:
Remove Trailing Slash
RewriteCond %{HTTP_HOST} !^\.yoursite\.com$ [NC]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

Source: http://ee-spotlight.com/tips/a_standard_htaccess_file_with_expressionengine
Comment: The problem isn't so much at the end of URLs, unfortunately, it is when I end up with a missing trailing slash inside of a URL. I have posted an example in an earlier comment which I hope illustrates what I mean. The .htaccess solution sounds great for normalising the end of URLs to either have or not have a trailing slash, but it doesn't seem like it could solve the missing slashes within URLs.


How to create json file path with variable in Python3?

Question: I am trying to write cookies to a json file.
cookies = web.get_cookies()
with open('test.json', 'w') as outputdata:
    json.dump(cookies, outputdata)
sleep(5)

Which writes cookies to test.json.
I am trying to create a cookie file for each user and each website visited such as.
cookies/{user}/{website}.json

'w' should create a file if it does not exist. But instead of the file being created I am getting error file does not exist.
I have defined the variables, printing user shows the username.
When manually creating the file such as test.json in the first example the script works.
How can I create the file at the path with variables?
Thank you
Answer: 'w' does create a file provided the containing directory exists.
You could ensure that the directory exists with os.makedirs:
# create directories if required without error if they exist
#  thanks to exists_ok=True
os.makedirs(f'cookies/{users}', exist_ok=True)
with os.open(f'cookies/{users}/{website}.json':
    ...


Is Cloud Computing really here?

Question: I have been hearing this term quite a lot. I have a bunch of mini questions that I would like to ask.

Are business really ready for cloud computing?
Do consumers have the appropriate resources to consume services from the cloud?
Is this technology prone to more attacks?
Some think cloud computing is just another over hyped term thats going to fizzle out. True?
As a developer what different do I need to do?

I am really looking forward at the responses.
Comment: I will close the discussion as soon as I get a general opinion. I am not looking for a long discussion. Abiding to the rules from StackOverflow rules for posting.
Comment: As opposed to it being "There".  I think this question could be worded better.
Answer: What people think of right now as cloud computing, especially the Amazon/Google/Microsoft offerings, are really just glitzy ways of abstracting traditional hosting.  It's just that somehow when you say "cloud" people think it's okay to put data online that would normally have been kept in-house.
Real cloud computing would also mean your app is also distributed across the host's datacenters, such that a user on the other side of the country or even across the ocean can be served by the nearest node (as defined by whatever routing mechanism their isp uses) with no extra work on your part, and if one node goes down there are still several others handling the app.
You can do that now, but you have to set it up yourself- there's no service that will automatically "put your web site/service in the cloud" any more than you would if you just hosted a web site with Rackspace.
The closest thing currently out there is the SaleForce platform.  Using that system, you don't worry about instances, memory, or database size or activity.  You just build your app and salesforce worries about making it scale.  If your app works and is good and people know about it you'll have paying customers, and salesforce will serve them the data no matter where they are.  That fact that the users must subscribe to salesforce is just a business model issue and isn't relevant to the technology involved.
Comment: Azure still just boils down to lettings microsoft be your host rather than someone like Rackspace- it still just boils down to glitzier virtual server hosting.
Comment: Exactly. I'm ready for this fad to be over.
Comment: Even rackspace differentiates between cloud hosting and traditional (virtual, dedicated, co-location).
Comment: There are now a number of services that will automatically scale your applications: Google's App Engine, Heroku, Rackspace Cloud Sites, ...
Answer: I think in the late 70s it was called time-sharing :)
Answer: I work for Salesforce.com and we also have what we call a "cloud computing" platform called Force.com aimed at data-centric business applications. But I think in general you can't get too caught up in the terminology. The real trends out there are people moving to the web as an application deployment model (i.e. software as a service) - this has been going on for a while, but what we're seeing is that people are also looking to the more progressive players in that space (like Google and us) to give them more than just hardware. They're looking for these players to help them build applications quicker by relying on a bunch of building blocks and services that offload more of the low-level stuff and enable developers to focus on the important parts of their applications. Just my two cents.
Answer: 1) They've been using it for years, so I'm thinking yeah.
2) They have web browsers, so yeah.
3) O yes my brothers.
4) The vogue for the term, where it's used like it has some kind of cosmic significance that "Web 2.0" and "software as a service" didn't, is definitely overdone and will fizzle, and it really can't happen too soon.
5) Assuming what you've been doing is use the best methods you can find to accomplish what you need to get done, nothing.
Answer: From my understanding of cloud computing (which is barely anything at the present time), I don't think there's an awful lot of differences between the "cloud" and the way a lot of us do things already - we request data from a service provider, that provider gives us the information which may be stored in disparate resources around the internet or it may be hosted on their own servers, we don't care. All we care is that we requested data, and they give it to us... like a Google search, who really knows what goes on behind the closed doors of Google except their design and development team.
There are some useful applications of this cloud notion though, the relationship between SO and Gravitar and OpenID for your avatars and login to StackOverflow.  Disparate resources on the internet all functioning together to give a cohesive product.
There's also the storage mechanism that you can subscribe to with your iPhone (for those of us that have the iPhone) - it allows all your data and files to sit out there somewhere on the internet and when you need access to it your iPhone tells Apple that you want your file and miraculously that file appears on your iPhone.
So there are applications of cloud usage out there today that are being used.  How useful I would consider that depends on how I could conceivably write software to leverage that.  There are many useful applications for this.
Is the technology more prone to attacks?  Well like any technology, if you don't take the necessary steps to secure it, then sure.  It depends on the architecture of your cloud.
In answer to those that think it's just the latest buzz word, there are many useful applications of this technology that will leverage it.  Whether that becomes mainstream is another question.
As a developer, you really need to evaluate whether this approach is useful for the project you're on and can be leveraged effectively - just like any other technology.  If it is useful and can leverage it effectively, then use it.  If you can't, then don't.
Answer: Check out this blog post by Matt Cutts.  He ran some software to monitor how much of his time is spent using various software applications.  He found that he spent 96% of his time in a browser.  His conclusion was

When 96% of your computer time is
  spent in a browser, that's living in
  the cloud.

Matt Cutts is not exactly typical -- he works for Google -- but still, he's an interesting data point.
Comment: I guess ... But "living in the cloud" just sounds so vapid. I dunno. It is about the same as some cashier saying 96% of his time is spent on a cash machine.
Answer: I have always had my own opinion about what cloud computing means and I don't know if it would be considered "right", but considering other buzzwords like "Web 2.0", it could be a pretty broad subject. In my opinion it is the idea that all your information would be available over any device, in an intuitive way. So you wouldn't feel tied to once PC or device because your experience would be carried from place to place via the internet.

To answer your questions:
Is Cloud Computing really here?
I say no, because from my personal experience I feel like i'm tied down to data on my PC and my phone. I don't feel like when moving from device to device that it knows me. And while there are ways to achieve this effect, there seems to be no industry stadard and things just seem messy.
Are business really ready for cloud computing?
I'm no business man at all, but I am willing to bet that businesses are not really ready for this, I doubt most CEO's even understand the concept fully, at least the ones that are not in the hardware/software industry.
Do consumers have the appropriate resources to consume services from the cloud?
I don't think so because like I mentioned there is no standard, and things are messy, and a lot of the consumers are not tech savvy I would guess.
Is this technology prone to more attacks?
Probably because of the widespread distribution of personal data that comes with it.
Some think cloud computing is just another over hyped term thats going to fizzle out. True?
False. Well, for the most part, the buzz surrounding it may die after it becomes more common. In my opinion I think its an awesome concept that just needs to be implemented correctly.
As a developer what different do I need to do?
I am probably not qualified to answer this question ;-). I would think a single developer wouldn't need to change, but collaborate with others to build the proper frame work for this concept to really come true. I think this can only become a reality from he industry wide point of view.
Answer: Yes, I think that businesses are ready for cloud computing, or could become ready very quickly (in terms of infrastructure).  Businesses are always ready to save money and carry less risk, so assuming the business model works out for customers of a cloud, then I expect that we'll see more and more businesses transitioning to this way of working.
Consumers certainly do have the resources.  Anyone who has used Amazon, for example, has used a cloud service (they've "productized" the cloud they were using internally and made it available for public use as well).  Anyone who has used the K9 web filter has used a cloud service.  They're more prevalent than most people realize, and for the most part are intended to be rather transparent.
I see a mixed potential for resilience against attacks.  Being "in the cloud" almost by definition means that to shut down a service there are many more points of contact that would have to be taken out (strength in numbers).  On the other hand, there are potentially more points of entry into a system, which could mean more potential for attack.
Cloud computing is probably here to stay, due to its inherent flexibility and the ability to implement the underlying infrastructure using fairly inexpensive components.  The hardest part to get right is the software that runs the whole thing, but there are companies out there who are already doing it well.
As a developer, I recommend watching the publicly available cloud resources (Amazon, Google, Microsoft, etc.) to see what commonalities there are and to see how the market share ends up shaking out (to determine what your focus might be).  As far as I know, they all provide APIs and documentation to make use of their clouds as simple as possible, so start with reading up on what's out there.
I hope this helps!
Answer: The short answer is "The cloud computing is here to stay"  That is definitely an all know answer.

Are business really ready for cloud computing?

Business and continues businesses need to be agile and adapt to technology, principally if they main focus is technology.  That those not mean every business is ready, but their success will probably mean getting ready.

<code>* Do consumers have the appropriate resources to consume services from the cloud?
</code>

Many people are consuming services from the cloud long ago.  Any of the google and yahoo services are being consume by the consumer.  Cloud computing puts all the power into normal developers and business people.

<code>* Is this technology prone to more attacks?
</code>

As any new technology, it will be a curve of no attacks (is new) then you will get some attacks and people getting profit defending from those "bad people".  I don't think this particular technology will be prone to more, is just until in balance.

<code>* Some think cloud computing is just another over hyped term thats going to fizzle out. True?
</code>

This is probably true.  At some point you will just not know that you are using it, because the great next thing will be on top of it.

<code>* As a developer what different do I need to do?
</code>

If a biologist find a new specie, then 1000s of biologists around the work have plenty to do.  They need to run all the studies ran in other spices, found all there special things.  The same happens here.  You see it, take your specialization, and apply it here.  It could turn out to be pretty good for you, at least in knowledge for the future.
I hope this is helpful.
Comment: Wha?  You might want to clean this up some.
Answer: I think Cloud is evolving to not necessarily mean deployed to a public infrastructure.  Private clouds are gaining traction, just as intranets followed the internet.
A big difference "Cloud" can bring is the management of resources.  Having the ability to treat a large volume of commodity based hardware as a single, or reduced set of entities, as well as having facilities to move these resources to where they are needed much more easily, to get better utilization.  Today's traditional VM's can be lacking in that area.  The process to move large numbers of machines from one computing need to another can be tedious.
There is also the concept of automated failover, so that work performed is not lost during a hardware failure.

Is Cloud Computing really here?


Create personality quiz

Question: i'm looking for solution on how to create personality quiz. The Quiz module doesn't have an option to label answers - I need to find the most popular label checked and not the total amount of points.
It could be like this: 2 questions, 3 answers each. Each answer for each question has labels: "label one", "label two" and "label three" and they are randomized. I answer both questions and get "label two=2", which is the most popular label and therefore I am forwarded to node2 with some description.
Is it possible to do this with forms?
Answer: The webform module would work for you. It gives you a nice interface to fetch the results so you can do some meaningful post analysis on your results too.
Comment: it doesn't look like it would be possible to create actions depending on the answer - if it would be possible, i could redirect the person to particular node depending on his answer result, but it is not possible to do with webform.
Comment: You can use Webform module, Rules module, Webform_rules module all together to create what to do automatically after submission on different answers.
Answer: Someone wrote a great module for it
Personality Test

This module allows you to easily create a personality test that visitors can take.
After you installed it a new node type becomes available, when you create a node of this type you can add questions and their possible answers; you can also define a score for each answer.

Create personality quiz


Projection onto a subspace of $\mathbb{R}^n$

Question: Suppose $\mathcal V\subset \mathbb{R}^n$ is a subspace and $\vec{x}\in\mathbb{R}^n$. I want to show there is a unique way to write $\vec{x}$ as a sum of two vectors $\vec{x}=\vec{x}^{\parallel}+\vec{x}^{\perp},$ the first of which lies in $\mathcal{V}$ and the second of which is orthogonal to every member of $\mathcal{V}.$
This is a simple problem but I'm just wondering if a step in the proof in my book is wrong.
The proof begins by letting $Y=\{\vec{y}_1...,\vec{y}_k\}$ be an orthonormal basis for any $k$-dimensional subspace $\mathcal V$ of $\mathbb{R}^n.$ We then must show that there exists a unique choice of scalars $a_1, ... , a_k\in\mathbb{R}$ such that if we define $\vec{x}^{\parallel}=a_1\vec{y}_1+...+a_k\vec{y}_k$ and $\vec{x}^{\perp}=\vec{x}-\vec{x}^{\parallel}$ then $\vec{x}^{\perp}$ is orthogonal to every vector in $\mathcal{V}.$ However, the next step of logic is what I don't understand.

Because the inner product is bilinear, that is the same as saying that $\vec{x}^{\perp}$ is orthogonal to every element of the basis $Y$ of $\mathcal{V}$.

To me, it seems that if $\vec{x}^{\perp}$ is orthogonal to every element of $\mathcal{V}$, then certainly it's orthogonal to the basis elements $Y$ since they are elements of $\mathcal{V}$. However, the book appeals to bilinearity. The only way I could see that being relevant if is we let $\vec{v}$ be an arbitrary element of $\mathcal{V}$ so that $\vec{v}=c_1\vec{y}_1+...c_k\vec{y}_k$ for some $c_1, ..., c_k\in\mathbb{R}$; then $$\langle\vec{x}^{\perp},\vec{v}\rangle=0\iff\langle\vec{x}^{\perp},c_1\vec{y}_1+...+c_k\vec{y}_k\rangle=c_1\langle\vec{x}^{\perp},\vec{y}_1\rangle+...+c_k\langle\vec{x}^{\perp},y_k\rangle=0$$
but the latter does not imply $\langle \vec{x}^{\perp}, \vec{y}_i\rangle=0$ for each $i$ up to $k$ as far as I can see.
So what did the author mean by appealing to bilinearity?
To be clear, this is in Chapter 1 Section 2 of Kristopher Tapp's Differential Geometry of Curves and Surfaces textbook.
Comment: It means $ \langle x,y \rangle $ is linear by as function of x and function of y
Comment: I guess I'm not seeing where you're misunderstanding lies. How does what you have written at the end of your question not imply that $\langle \vec{x}^{\perp},\vec{y_i}\rangle=0$ for all $i$?
Comment: @Volk because, well, why would it? Each of the dot products doesn't even have to be positive a priori.
Answer: Let us write $x \perp y$ for $\langle x, y \rangle = 0$. The important equivalence here is:
$$u \perp \mathcal{V} \iff u \perp y_i \text{ for each } i = 1, \dots, k,$$
where the left side means that $u$ is perpendicular to every element of $\mathcal{V}$.
Now since each $y_i \in \mathcal{V}$, the $\implies$ direction does not require anything specific about the definition of orthogonality.
But you need bilinearity to go the other way (to be pedantic, only the linearity in the second variable): expand an arbitrary $v \in \mathcal{V}$ as $\sum c_i y_i$ and write
$$\langle u, v \rangle = \sum c_i \langle u, y_i \rangle = 0.$$
As you note, if you know that $u \perp v$ for a specific $v$, ie a specific choice of $c_1, \dots, c_k$, that does not imply that $u \perp y_i$ for each $i$.
But the above equivalence means that to check a tentative decomposition $x = x^\parallel + x^\perp$ has the required properties, it suffices to check that $x^\perp \perp y_i$ for the basis elements $y_i$ (and $x^\parallel \in \mathcal{V}$, which is equivalen to saying that $x^\parallel$ is of the form $\sum a_i y_i$). Since $y_i$ are chosen to be orthonormal, you can now check that $a_i = \langle x, y_i \rangle$ is the unique choice of $a_i$ that makes this work, which therefore gives the unique such decomposition of $x$.
Comment: Yep this is exactly what I was looking for. Thank you. I forgot the other direction is essentially the "uniqueness" bit huh?
Comment: A unique way to write $\vec{x}$ as the sum of the two vectors.
Comment: @BiftonMifts rewrote the answer to be more explicit and added an explanation of the uniqueness


Trigger cache clearing on table crud operation in linq to sql

Question: I have a method that gets all the records from a particular database, then stores it in the cache.  The next time that method is called, it first checks the cache to see if it can simply return a cache version, if that cache object hasn't been expired.
Question: how do I trigger a method everytime dataContext.SubmitChanges() is called?  For example, if I get all the books from the Book table and store it in Cache["AllBooks"], I want this cache object to be cleared on any crud operations related to the Book table.
What I'm currently doing:
var b = dataContext.Books.Where(x => x.BookId == 4).SingleOrDefault();
b.Title = "new title for book w/ id of 4";
dataContext.SubmitChanges();
ClearBookCache();

later...
private void ClearBookCache() {
    CustomCachingSystem.Clear["AllBooks"];
}

What I want: the ClearBookCache() to be automatically triggered on any Book table crud operations, vs. me having to remember to call it everytime I do a crud operation on the Book table.
Note: I wouldn't want that ClearBookCache() method to be called if I do a crud operation on a table that's unrelated to the Book table.
I hope this makes sense!
Comment: All CRUD operations? More like CUD - without the read part, isn't it?
Answer: You could use the SqlDependency Class. Basically, it will let you detect changes to the queried data (if you use M$ SQL Server 2005+).
You may want to look into Service Broker technology (if you use M$ SQL Server 2005+).
Detecting it directly in your application probably won't be enough - you won't be able to detect any changes that were performed outside of your application.
Answer: Take a look at DataContext.GetChangeSet() - you could inherit from DataContext and override the SubmitChanges methods to clear the relevant caches based on the ChangeSet contents and then call MyBase.SubmitChanges(...).
Comment: However, Jaroslav's comment is of course very valid - this won't pick up on any changes made by e.g. triggers, not will you be 'doing the right thing' with the cache if other users are modifying data you have cached.


If I save created view and visit the view page it showing only filter field

Question: I am new to drupal and I am trying to create view for my content type, I followed the steps using a tutorial but I am not able to see the preview of the created content view if I save and visit the view page it showing only filter field. Please help me.
I have used the following method to create the view.
1) click on view and Add new name.
2) enter the name and in the show field selected the content then i specified my created content in type of field, and newest first in the sorted by field.
3) selected the table format.
4) added the fields of specified content with the help of search box where in i have given the content name so all related fields show up.
5) added the filter field from specified content.
Comment: Are you sure there is content of this particular content type?
Comment: @Aparna: yes I am very sure,I have created the content type with all those specified fields.
Comment: try only adding the content title if it works then there must be some dependency with one of the fields you have added.
Comment: if I select content title, it showing some other content type title. I am not getting specified content title. Please assist me on this from long time  I am trying on this.
Comment: have you added any relationship in the view? one more thing try adding age as field in field list.
Comment: no age is some other content field , now when i selected the field from specified content filter field is also not showing of, i have added the one more screen shot please take a look
Comment: i think you have  added some **Contextual filters** as relationship, thats y **Preview with contextual filters:** textbox will show in preview area. Please check it again.
Comment: @Abin: i have not added any contextual filters.
Comment: Can you pls chk inside that **Advanced** tab..
Comment: @Abin: i have posted the screen shot of it, i have not added any contextual filter
Answer: I think you set  "age expose field  required" it cause in first load nothing show up till user enter something in filter.
try it with removing "Required" checkbox.
Comment: Hai Zhilevan, i have not mentioned it as required, dont know where iam doing mistake its becoming nightmare to me.
Comment: @kashish dont worry I am here to help you ;) ,  tell me if you enter something in age the apply  results showed up?
Comment: @kashish dont forget close question (with accept)
Comment: @ Zhilevan: sure ):
Comment: @kashish tnx ;)


Is there any equivalent to Marshal in c# to Java?

Question: Is there any Native Android Java/Kotlin equivalent to C#'s IntPtr and Marshall?
IntPtr unmanagedMemory = Marshal.AllocHGlobal(length);
Marshal.Copy(source, sourceIndex, unmanagedMemory, length);
object returnValue = Marshal.PtrToStructure(unmanagedMemory, destinationType);
Marshal.FreeHGlobal(unmanagedMemory);

Comment: [`sun.misc.Unsafe`](http://www.docjar.com/html/api/sun/misc/Unsafe.java.html) has methods that do things like that. I don't know if it's available in Android though.
Comment: I don't know, but does [GraalVM](https://docs.oracle.com/en/graalvm/enterprise/21/sdk/index.html?org/graalvm/nativeimage/UnmanagedMemory.html) help?
Answer: There is no possible way to do this with Android. Even in my personal experience I tried with sun.misc.Unsafe, but that does not even helped me.


cant understand how each method works here

Question: I'm trying a simple thing with each & setTimeout function. I want the letters of a name will appear distinctively & at separate(gradual) time. Suppose, letters of NAZ should appear this way, first N second A last Z. but, here I can see output is AZN then ZNA then NAZ. What I feel, I've a wrong comprehension of how 'each' works actually. but, the output in console is shown exactly as I intended. Have a look at this.
    $('div.promise').each(function(index, promise){
        setTimeout(function()

            {
                $('.showPromise').append(promise);
                console.log($(promise).text());

$('.promise').css({"display":"block"})},1000*(index+2));

});}

https://jsfiddle.net/sanje/425konu3/17/
How can I show the output as shown in console? & why all the divs appear altogether at certain time? Please help me find out the mistake. Thanks!
Answer: The problem is following statement inside your setTimeout:
$('.promise').css({"display":"block"})

It makes all div's with class promise visible together. You should use this instead:
$(promise).css({"display":"block"})

var showAnimation=function(){

  $('div.promise').each(function(index, promise){
   setTimeout(function(){
     // $('.showPromise').append(promise);
     console.log($(promise).text());
         $(promise).css({"display":"block"})
      },1000*(index+2));
   });//each()
  }//showAnimation()
$('button').on('click', showAnimation);
.promise {
  display: none;
  padding: 10px;
}

.showPromise {
  background-color: red;
  margin: 10px;
  display: flex;
  height: 100px;
  width: auto;
}

.as-console-wrapper{display: none !important;}

<button>call</button>

N

A

Z

Answer: You are setting display on the whole class each time. You need to only show each instance in the loop. you can simplify and do that using show().
The append() part doesn't really make much sense either so I removed it

var showAnimation = function() {

  $('div.promise').each(function(index, promise) {
    setTimeout(function() {
        $(promise).show();
      }, 1000 * (index + 2));
  });
}
$('button').on('click', showAnimation);
.promise {
  display: none;
  padding: 10px;
}

.showPromise {
  background-color: red;
  margin: 10px;
  display: flex;
  height: 100px;
  width: auto;
}

<button>call</button>

N

A

Z

Comment: Okay, I've got the point. But just one more thing, while preserved the old wronged code, why it appeared AZN ZNA NAZ? why not this NAZ NAZ NAZ? Thanks in advance!
Comment: Not sure what you are expecting. There is only one letter in each `promise` element
Answer: @charlietfl Perhaps, I could figure out what's happened here. Please have a look at the existing code
    $('.showPromise').append(promise);
    $('.promise').show();},1000*(index+2));
https://jsfiddle.net/425konu3/20/

output:
AZN (shows then hides)
ZNA (shows then hides)
NAZ (persists)
I asked what's hack here, why not NAZ NAZ NAZ. It turns out that as append moves the selected element as the last child & all the divs are available to display right at the moment by virtue of $('.promise').show(), they are shown up altogether in a manner that the first div is appended as last while the next adjacent div sits at 0 index & the rest sits next to it.
First time, N appends(last index), A(index 0), Z(index 1), so AZN appears.
Second time, A appends(last index), Z(index 0), N(index 1), so ZNA appears.
Last time, Z appends(last index), N(index 0), A(index 1), so NAZ appears.


Differential geometry vs Riemannian geometry

Question: I'd like to know the relation between differential geometry and Riemannian geometry.
exactly what makes them different?
Is one an special case of another? exactly how?
Comment: I think maybe what you say is definition of "differential topology". @rubikscube09
Comment: Wikipedia article on Riemannian geometry provides a good description: Riemannian geometry is the branch of differential geometry that studies Riemannian manifolds, smooth manifolds with a Riemannian metric, i.e. with an inner product on the tangent space at each point that varies smoothly from point to point. This gives, in particular, local notions of angle, length of curves, surface area and volume. From those, some other global quantities can be derived by integrating local contributions.
Comment: Riemannian geometry is studying a differentiable manifold which is endowed with a Riemannian metric. then is there such a definition for Differential geometry such that it be evident from terms that riamannian geo is an special case of differentiable geo? @rubikscube09
Comment: Well yes, differential geometry is the study of differentiable manifolds. A differentiable manifold is something (say a surface) that locally ''resembles" $\mathbb{R}^n$ and has a differential structure on it, by which we mean you can define functions on the surface and define their derivatives in a meaningful way.
Answer: You can say that

Riemannian geometry
Lorentz geometry
Symplectic geometry
Poisson geometry
Contact geometry
Complex geometry
Kähler geometry

and others are instances of differential geometry, which is the study of differentiable manifolds. You have several possibilities of geometric structures to equip your manifold with, and each one gives a "subarea" of differential geometry.
Comment: So what is a "geometric structure" ? is it a privileged tensor field on manifold (as for example in the case of riemannian, symplectic and some others) ? or group structure of lie groups also counted? have we a exact definition for a structure to be "geometric"? (geometric in the sense that we discuss: its presence turns our subject to differential geometry)
Comment: If I recall correctly, there is one general notion of "geometric structure" corresponding to a reduction of the structure of the frame bundle of a manifold from ${\rm GL}(n,\Bbb R)$ to some subgroup of it. For example, a Riemannian metric is a reduction of ${\rm GL}(n,\Bbb R)$ to ${\rm O}(n,\Bbb R)$, a symplectic form is a reduction of ${\rm GL}(2n,\Bbb R)$ to ${\rm Sp}(2n,\Bbb R)$, and so on. But I haven't studied details of that yet.


How to make swell effect on electric guitar?

Question: The effect I'm thinking of is when you don't hear the pick attack as you play a note, but you hear the note afterwards as it seems to get louder before decaying.
I suppose you can mimic this with a volume pedal but that seems a bit difficult. What are some good ways to make this effect?
Comment: It's often referred to as a [volume swell](http://en.wikipedia.org/wiki/Volume_swell).
Comment: try chords of orion tutorial https://www.youtube.com/watch?v=hoFPxldU1BQ
Answer: Often called violining, either use the swell (volume) pedal or the volume pot on your guitar. Strat style guitars are pretty good for this, as Leo thought to put the volume control quite close to the strings/bridge, so a little finger can roll from palm to tip as you pluck the string. Then it gets rolled off again the opposite way, ready for the next note. Here's a video clip demonstrating this technique. On Teles and particularly things like Les Pauls and 335s, with the volume pot situated a way away from the strings, it's not so convenient.Some pedalboards have an inbuilt effect, but it's more controllable and effective when you do it for yourself.
Comment: On Teles, you can reverse the control plate, then swap the pots, and achieve the same result. Steve Morse and many others have done this with great success.
Comment: +1, Nice bit of history on Leo & the Strat. Thank you. Also I would like to note that the guitar volume swell version assumes that your pots are clean and move without any noise. When clean and applied to a repeating delay line (2 to 5 seconds), this can be a beautiful way to layer diads, triads, and other chords.
Comment: A lot of tele players emulate a pedal steel with the volume pot in its original wiring, so it's doable with a stock one too.
Answer: One way to get this effect is with an envelope filter. Then you will get it automatically, as the volume starts at 0 when the string is plucked, and then increases (with the correct settings).
Comment: @filzilla: The filter is triggered by the tone, so you don't have to keep time. I believe the effect is usually done with the volume pot, so it might not be the exact same effect, but I've got similar tones with an envelope.
Comment: Can one get the envelope filter to automatically trigger on the pick attack or does the guitarist need to follow the beat (period) of the filter?
Comment: The boss slow gear (SG-1) is by far the most widely known device for this.
Answer: Another option would be to use an EBow (Electronic Bow).  As its names suggests, this device can be used to create bowing effects like a violin or cello.
Answer: I'm a Tele player, and I learned the trick from Danny Gatton's Hot Licks instructional tape, where he showed how to cut away some of the attack with volume swells, and also tone swells. He did this on a Tele with standard control plate setup. Simply, you wrap your pinky around the volume knob.
(Jeff Beck uses a tone swell for the train horn lick at the intro to the Yardbirds' "Train Kept A' Rollin'".)
I went to a reversed control plate (volume, tone, switch instead of switch, volume, tone) so I can reach these knobs more easily. I still do that, but lately, I've taken to using a Morley volume pedal to do this, so I have fewer things going on with my hands.
Answer: One technique that hasn't been mentioned is acoustic feedback.  It's probably less tricky with double-coil pickups which are less prone to magnetic feedback bypassing the strings altogether.


the converse of Schur lemma

Question: I am interested in the converse of the following form of Schur's lemma:
Lemma. (Schur) A group $G$, a $\mathbb{C}$-vector space $V$ and a homomorphism $D : G \rightarrow \operatorname{GL}(V)$ are given. Suppose that $D$ is a irreducible reprsentation. If a linear map $T : V \rightarrow V$ commutes with $D(g)$ for all $g \in G$, then $T$ is some scalar multiple of the identity operator.
Edit) What I want to prove or disprove is the converse of the above:
Suppose that the representation $D : G \rightarrow \operatorname{GL}(V)$ is reducible. Then there is a linear map $T : V \rightarrow V$ which is not a scalar multiple of the identity such that $T D(g) = D(g) T$, $\forall g\in G$.
When $G$ is a finite group or a compact Lie group, this trivally holds, because every reducible representation of $G$ is decomposable (i.e. fully reducible); if $W \leq V$ is a subspace invariant under $D : G \rightarrow \operatorname{GL}(V)$, then we can find an invariant subspace $U \leq V$ satisfying $V = W \oplus U$, and $T=\pi_W+2\pi_U$ commutes with every $D(g)$ but is not a scalar multiple of the identity. ($\pi$: projection operators)
QUESTION. But what if $G$ is a general group, which admits reducible but indecomposable representations? Does the converse of Schur lemma still hold?
Comment: There is no need to do the $2\pi_U$ trick (unless you want not linear maps but isomorphisms): you can simply take $T=\pi_W$.
Comment: You are completely right.
Comment: (In the algebra case, see http://mathoverflow.net/questions/2328/when-does-the-converse-to-schurs-lemma-hold)
Comment: In the case of a reductive algebraic group in positive characteristic (which is analogous to the compact Lie group case), this fails for a large class of modules. More precisely, the modules induced from $1$-dimensional representations of the Borel have $1$-dimensional space of endomorphisms (due to Frobenius reciprocity), but they are generally not irreducible.
Answer: Let $A=\left(
\begin{array}{cc}
 1 & 1 \\
 0 & 1 \\
\end{array}
\right)$ and $B=\left(
\begin{array}{cc}
 2 & 0 \\
 0 & 1 \\
\end{array}
\right)$, let $F$ be the free group on generators $a$ and $b$, and consider the representation of $F$ on $\mathbb C^2$ which maps $a$ and $b$ to $A$ and $B$. This has trivial endomorphism ring, so in particular it is indecomposable, yet it is not simple: the vector $(1,0)$ spans a proper submodule.
Comment: Notice that $BA=A^2B$, so you can factor this representation to get one of the [Baumslag–Solitar group](http://en.wikipedia.org/wiki/Baumslag%E2%80%93Solitar_group) B(1,2) and in fact that is a faithful representation, see http://mathoverflow.net/questions/119719/when-is-a-baumslag-solitar-group-linear

the converse of Schur lemma


Executing the program after the "fork part"

Question: in my program, I use in main function fork to create 2 processes. Child process do something and parent process is forked again and his child calls another function. Both functions writes to 1 file and all works fine.
What I need is to write something to the end of file, after both functions and all processes (both functions create processes) finish.
I tried to write fprintf command everywhere in main and it allways writes somewhere in the middle of file, so I think that the main propably runs parallelly with the 2 functions.
I tried to use semaphore
   s = sem_open(s1, o_CREATE, 0666, 0);
in this way: In the end of each function I wrote sem_post(s) and in main I put sem_wait(s); sem_wait(s); and after this i wrote fprintf command, but it also didn't work.
Is there some way how to solve this?
Thanks
Comment: using `fork` is not *parallel processing* - that is incorrect terminology.
Answer: I think you're looking for the wait function. See this stack overflow question: wait(NULL) will wait for all children to finish wait for a child process to finish (thanks Jonathan Leffler). Call wait in a loop to wait for all children processes to finish. Just use that function right before you write to the file in your parent process.
You can also read about the waitpid function if you want to wait for a specific process instead of for all the processes.
Edit:
Alternatively, you can actually use semaphores across processes, but it takes a little more work. See this stack overflow answer. The basic idea is to use the function sem_open with the O_CREAT constant. sem_open has 2 function signatures:
sem_t *sem_open(const char *name, int oflag);
sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);
From the sem_open man page:

   If O_CREAT is specified in oflag, then two additional arguments must
   be supplied.  The mode argument specifies the permissions to be
   placed on the new semaphore, as for open(2).  (Symbolic definitions
   for the permissions bits can be obtained by including <sys/stat.h>.)
   The permissions settings are masked against the process umask.  Both
   read and write permission should be granted to each class of user
   that will access the semaphore.  The value argument specifies the
   initial value for the new semaphore.  If O_CREAT is specified, and a
   semaphore with the given name already exists, then mode and value are
   ignored.

In your parent process, call sem_open with the mode and value parameters, giving it the permissions you need. In the child process(es), call sem_open("YOUR_SEMAPHORE_NAME", 0) to open that semaphore for use.
Comment: Note that [`wait()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html) waits for one child to die.  You have to use it in a loop to wait for all children to die.  `int corpse; int status; while ((corpse = wait(&status)) != -1) printf("PID %d exited with status 0x%.4X\n", corpse, status);`.  There's still room for angst over signal handling and the like; you can make that more sophisticated if you like.
Comment: Might help to give a brief summary of what each of answers convey rather than dumping links.
Comment: I am not sure, but I think that I have it exactly as you wrote it. I have it like:
main:
sem_t *s;
s = sem_open(s1, O_CREAT, 0666, 0);
sem_close(s);
s = sem_open(s1, O_RDWR);

function 1 and two:
sem_t *s;
    s = sem_open(s1, O_RDWR);

"s1" Is a macro.


What is the best spot to strike a tennis ball?

Question: As seen in the image below, there are several "sweet spots" on a tennis racket.
Before seing this picture, I always strived to hit the ball in the center of the racket, which seem to feel the nicest, however after seeing this diagram, and practicing bouncing the ball onto the racket in various positions, It seems the yellow area shown below does have more rebound.
Therefore, I ask the question, is it better to master  striking the ball in the center of the racket or the yellow spot shown in the picture below, or somewhere else entirely, for optimum performance?
Answer: I think there is no correct reply always true for this question, but I bolted the most one according to your image.
Anyway you can use this hint to understand the meaning of the points:

Point 1 is the Center of Percussion (COP in your image) and offers the least amount of initial shock to the hand when struck. Shock is generally accepted as being potentially most harmful to player's arms.
Point 2 is the Nodal Point (Node in your image) and produces the least amount of vibration when struck. Frame vibration is what players feel after ball contact in certain more flexible rackets.
Point 3 is the area of Maximum Coefficient of Restitution, or a racket's power (Best bouce in your image) and the exact position depend on several factors (racket's weight, balance, length, headsize and string tension).

Here and also here you can find a deep explanation of this topics with physics details
Comment: Thanks, where do professional tennis players try to hit?  At least shock, or most power?
Comment: @Mew In my opinion there is no absolutely true answer to this question, I think it depends on the player and the type of shot
Answer: There is no right or optimal place to hit a ball on the tennis racket that applies to everyone. Everyone plays differently and looks to get a different type of result out of each shot.
I'm definitely no expert on the physics of tennis, but I can tell you from experience, where on your racket you should aim to hit the ball.
The part labeled Node, is probably the best for when you your trying to roll a nice spin ball off your racket.
The part labeled COP, is the opposite, and should be used when hitting a slice ball.
However, while the bottom area of the racket (labeled Best Bounce in your image), is usually used for a flat ball because the ball doesn't need much room to roll on your racket, I would stay away from it in many cases. If you're a player who enjoys smacking that ball when you're on the offensive, then go ahead. But it's not always the best for Touch. That area of the racket is usually unpredictable and isn't optimal for a volley or drop shot.
When hitting a serve, just anywhere in the middle of the racket is fine. It all really depends on where you're placing it anyways.
In the end, don't try to base your tennis off of science and physics. It can only help so much, and feel is the best way to truly learn. Besides, nobody is perfect and can hit those exact areas on the racket every time. I would just try to drill as much as possible, until you develop your own areas for hitting the ball.


Alterar nomes das colunas utilizadas para guardar o timestamp

Question: Quando armazeno ou edito dados em uma tabela pelo laravel este cria um timestamp que utiliza os campos created_at e updated_at
Porém tenho que armazenar os dados em uma tabela compartilhada com outro sistema, e esta utiliza outra nomenclatura para armazenar estes dados.
Sem ser a solução de setar o timestamp = false e na hora de armazenar eu mesmo adicionar o timestamp lá.
No próprio model tem como eu setar o nome do creted_at e updated_at para outro?
Answer: Achei este exemplo na documentação do Laravel e deu certo

If you need to customize the names of the columns used to store the timestamps, you may set the  CREATED_AT and UPDATED_AT constants in your model:

class Flight extends Model
{
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';
}


Sort Node Queries by an entity reference field within a field collection item

Question: I am trying to fetch a list of nodes of a particular content type, alongside their field-collection items. The code below works perfectly for my use case.
<code>    function report_cards_get_term_data($type, $term, $session, $student_id, $class){
    $resarr = array();
    $query = db_select('node', 'n');
    $query->join('field_data_field_term', 'ft', 'n.nid = ft.entity_id');
    $query->join('field_data_field_session', 'dfs', 'n.nid = dfs.entity_id');
    $query->join('field_data_field_admission_number', 'rn', 'n.nid = rn.entity_id');
    $query->join('field_data_field_result', 'fr', 'n.nid = fr.entity_id');
    $query->join('field_data_field_class', 'cg', 'n.nid = cg.entity_id');
    $query->join('field_data_field_subject', 'cfs', 'cfs.entity_id = fr.field_result_value');
    $query->join('field_data_field_exam_score', 'ces', 'ces.entity_id = fr.field_result_value');
    $query->join('field_data_field_first_ca', 'cfc', 'cfc.entity_id = fr.field_result_value');
    $query->join('field_data_field_second_ca', 'csc', 'csc.entity_id = fr.field_result_value');
    $query->fields('cfs');
    $query->condition('n.type', $type);
    $query->condition('field_term_value', array('1st Term', '2nd Term', '3rd Term'), 'IN');
    $query->condition('field_session_target_id', $session);
    $query->condition('field_class_target_id', $class);
    $query->condition('field_admission_number_target_id', $student_id);
    $query->addExpression('cfc.field_first_ca_value + csc.field_second_ca_value + ces.field_exam_score_value', 'total');
    //$query->orderBy('cfs.field_subject_target_id->weight', 'ASC');
    $report_card = $query->execute();
}
</code>
However, i need to sort the result alphabetically by the entity reference name (taxonomy term) called "Subject". The entity reference is a field within the field collections. I know i can use "$query->orderBy()" but i can't get it to work. That's why it was commented out in the given code above.
Thank you for your suggestions.
Comment: If i uncomment the $query->orderBy(), it will order by the subject term id, but we dont want the term id. We want to use the term name to sort
Answer: Solved it myself. I added one more join,
<code>$query->join('taxonomy_term_data', 'fee', 'cfs.field_subject_target_id = fee.tid');</code>
Then order by
<code>$query->orderBy('fee.name', 'ASC');
</code>
Then the result was ordered alphabetically by the taxonomy name.