A choice question on determinants

Question:
If $A$ and $B$ are square matrices of order $2$, then $\det(A+B)=0$ is possible only when:
  $(a)$ $\det(A)=0$ or $\det(B)=0$$(b)$ $\det(A)+\det(B)=0$  $(c)$ $\det(A)=0$ and $\det(B)=0$ $(d)$ $A+B=0$

I was sure that when $A+B=0$, $\det(A+B)=\det(0)=0$ So the answer is $d$.
But I am not able to show that the other three does not meet the condition.
Please offer your assistance?
Thank you  :)
Comment: This question is broken! Did you translate it into English yourself, perhaps? It's not true that $\det(A+B) = 0$ is possible only when $A+B = 0$. For instance, if $A = 0$ and $B$ is any non-zero matrix with zero determinant, then $\det(A+B) = 0$ but $A+B \ne 0$. (And please don't ask, "Can you prove it?")
Comment: I didnt translate it. It is posted as it is. I agree that "It's not true that $det(A+B)=0$ is possible only when $A+B=0$." But what it means in this context is that **$det(A+B)$ is true when only one among the four options(conditions) is true**. :)
Comment: and Ill change that prove that.
Comment: So instead of "is possible only when", you mean "is always true when". Right? They're not the same!
Answer: All the answers aren't true: counterexample
$$A = \begin{bmatrix}
1 & 0 \\
-1 & 1
\end{bmatrix},
B =  \begin{bmatrix}
-1 & 0 \\
1 & 2
\end{bmatrix}
$$
Comment: To prove that the answers aren't true it suffice to give a counterexample
Comment: Can you prove it ?
Answer: Counterexamples,
case (a),(b),(c) take $A=I,B=-I$
Then $(A+B)=0\Rightarrow \det(A+B)=0$ but $\det(A)=\det(B)=1$
Comment: I get that. But u cant prove it?
Comment: @chndn, providing a counterexample in this case IS proof. Providing a counterexample shows that the relationship is not always true, which is exactly what you want.
Comment: okay thankyou ...  +1 to all
Comment: Counterexample implies that you have to find an exmaple in which the stated condition is not satisfied(this disproves the fact) so there is nothing like proving.
Answer: Hint: consider the counter-example for (a), (b), and (c):
$$A = \begin{bmatrix}
1 & 0 \\
0 & 2
\end{bmatrix},
B =  \begin{bmatrix}
-1 & 0 \\
0 & 1
\end{bmatrix}
$$
Comment: Can you prove it ?

A choice question on determinants


Argument of groupBy's Lambda

Question: Learn You a Haskell shows the groupBy function:
ghci> let values = [-4.3, -2.4, -1.2, 0.4, 2.3, 5.9, 10.5,
                          29.1, 5.3, -2.4, -14.5, 2.9, 2.3]
ghci> groupBy (\x y -> (x > 0) == (y > 0)) values
[[-4.3,-2.4,-1.2],[0.4,2.3,5.9,10.5,29.1,5.3],[-2.4,-14.5],[2.9,2.3]]

In groupBy's first argument, what is the meaning of the lambda's 2 arguments: x and y?
Comment: Are you asking what this expression does, or why there are two arguments in the lambda?
Comment: Could you please tell me both?
Comment: With the function `on` from `Data.Function` you could write `ghci> groupBy ((==) \`on\` (>0)) values` . Maybe its more readable for you.
Comment: possible duplicate of [Haskell: surprising behavior of "groupBy"](http://stackoverflow.com/questions/1316365/haskell-surprising-behavior-of-groupby)
Answer: These are the variables to compare. You know that group puts equal neighbored values together. To decide what a equal value is it uses a compare function. group relies on the instance of your type of the Eq typeclass. But groupBy allows you to choose how to compare the neighbored values.
Answer: If we look at the type of groupBy:
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

The first argument to groupBy is a function that takes two arguments of type a and return a Bool.  You could equivalently write this as
groupBy comparer values where comparer x y = (x > 0) == (y > 0)

The \x y -> part just says that the lambda function takes two arguments named x and y, just like with any other function declaration.
The easiest way to see what this expression does is to just run it:
ghci> groupBy (\x y -> (x > 0) == (y > 0)) values
[[-4.3,-2.4,-1.2],[0.4,2.3,5.9,10.5,29.1,5.3],[-2.4,-14.5],[2.9,2.3]]

If you look closely, you can see that each sublist is grouped by if it's positive or negative.  The groupBy function groups elements of a list by the given condition, but only in sequential order.  For example:
ghci> groupBy (\x y -> x == y) [1, 1, 2, 2, 2, 3, 3, 4]
[[1,1],[2,2,2],[3,3],[4]]
ghci> groupBy (\x y -> x == y) [1, 1, 2, 2, 2, 3, 3, 1]
[[1,1],[2,2,2],[3,3],[1]]

In the second example, notice that the 1s haven't all been grouped together because they aren't adjacent.
Comment: This was helpful, especially the last part where you implemented `group` in terms of `groupBy`.
Answer: In cases like these, it's best to go straight to the source! groupBy is part of Data.List, so you can find it the base package on Hackage. When you don't know what package a function is in, search for the function in Hoogle and click on the name to be taken to the Haddocks on Hackage. When you're looking at Haddock documentation, there will usually be a "Source" link on the righthand side of the function type definition to take you to the definition. Here's the source for groupBy.
I've reproduced the definition here to step through it.
-- | The 'groupBy' function is the non-overloaded version of 'group'.
groupBy                 :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy _  []           =  []
groupBy eq (x:xs)       =  (x:ys) : groupBy eq zs
                           where (ys,zs) = span (eq x) xs

First, the documentation line at the top tells us that groupBy is the non-overloaded version of group, which is a very common pattern in base. You can go check out group to figure out the simplest case of grouping functionality, then you can understand the -By version as allowing you to supply your own predicate (in case you wanted to compare equality differently than the Eq instance for a type, or whatever other operation you're trying to do).
The base case is trivial, but the recursive step might be a little confusing if you don't know what span does (time to hit Hackage again!). span takes a predicate and a list and returns a pair (2-tuple) of lists broken before the first element that doesn't match the predicate (it's like break but (not) negated).
So now you should be able to put it all together and see that groupBy groups elements of a list together by segregating runs of elements which are "equal" to the first element in that run. Note that it is NOT comparing elements pairwise (I was burned by that before) so don't assume that the two elements being passed to the predicate function would be adjacent in the list!
Comment: When you say `it is NOT comparing elements pairwise`, that means elements are **in fact** getting compared in an interleaving fashion, rather than paired up?
Comment: Hm, I'm not sure what you mean by "interleaving". What I meant is that it isn't comparing neighboring elements, it is instead consuming elements that evaluate to true while compared with the first element of the span. E.g., given a predicate like `(<)` and a list like `[1,2,4,3,0,...]` `groupBy` will compare and match `1 < 2`, `1 < 4`, `1 < 3` and then fail on `1 < 0` and begin a new group at the `0` element. This is instead of comparing `1 < 2`, `2 < 4`, `4 < 3`, &c. I expected the latter functionality early in using Haskell and got burned. A good exercise is to implement `pairwiseGroupBy`.
Answer: Let's start with group. This function simply groups together all the adjacent elements that are identical. e.g.,
group [0,1,2,3,3,4] = [[0],[1],[2],[3,3],[4]]

GHC defines group as follows:
group :: Eq a => [a] -> [[a]]
group =  groupBy (==)

That is, the equality test is implicit. The same thing can be written with an explicit equality test using groupBy as;
groupBy (\x y -> x == y) [0,1,2,3,3,4] = [[0],[1],[2],[3,3],[4]]

Now, let's look at how GHC defines groupBy:
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy _  []           =  []
groupBy eq (x:xs)       =  (x:ys) : groupBy eq zs
                           where (ys,zs) = span (eq x) xs

eq is used to split the rest of the list based on comparison with the first element. groupBy is then recursively called on the list of elements that fail the comparison. Note that (x:ys) is a concatenation of the first element, with the list of elements that satisfy the comparison condition. Also, the span function will start the second list at the first element where test condition is not met.
Hence, in the given example, the moment you reach the value 0.4, a new list has to start, since 0.4 will be the first element of zs from the above definition.
Answer: groupBy divides a list into groups according to some "rule". In groupBy (\x y -> x `someComparison` y) someList, x is a first element of the "current" group, y is an element of someList. groupBy traverses someList, so at each step y becomes the next element of someList. The new group started, when the predicate returns False. y becomes the first member of the new group. Iteration continues, the first member of this new group now becomes x, and the next element of someList becomes y.
groupBy does NOT compare elements pairwise (1st with 2nd, 2nd with 3rd, etc), instead it compares each element of the list with the first element of the group currently being filled. Example:
groupBy (\x y -> x < y) [1,2,3,2,1] -- returns: [[1,2,3,2],[1]]

Step by step groupBy:

compares 1 with 2. 1 < 2, thus both numbers go into the same group. Groups: [[1,2]]
compares 1 with 3. 1 < 3, thus 3 goes into the old group. Groups: [[1,2,3]]
compares 1 with 2. 1 < 2, thus 2 goes into the old group. Groups: [[1,2,3,2]]
compares 1 with 1. 1 ≮ 1, thus the new group is formed, and 1 goes as its first element. Groups: [[1,2,3,2],[1]]

Exercise: To understand how groupBy works, try to figure out how the following expressions return their results with pen and paper:
groupBy (\x y -> x < y) [1,2,3,4,5,4,3,2,1] -- [[1,2,3,4,5,4,3,2],[1]]
groupBy (\x y -> x < y) [1,3,5,2,1] -- [[1,3,5,2],[1]]
groupBy (\x y -> x <= y) [3,5,3,2,1,0,1,0] -- [[3,5,3],[2],[1],[0,1,0]]
groupBy (\x y -> x <= y) [1,2,3,2,1] -- [[1,2,3,2,1]]

Again, the key to understand behavior of groupBy is to remember, that at each step it compares the first element of the current group with a consecutive element of the list. The moment predicate returns False, the new group is formed, and the process continues.
To understand why groupBy behaves that way, inspect its source:
groupBy                 :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy _  []           =  []
groupBy eq (x:xs)       =  (x:ys) : groupBy eq zs
                           where (ys,zs) = span (eq x) xs

The key here is the use of span function: span (1<) [2,3,2,1] returns ([2,3,2],[1]). span (eq x) xs in the above code puts all elemets of xs that match (eq x) into the first part of a pair, and te rest of xs into the second. (x:ys) then joins x with the first part of a pair, while groupBy is recursively invoked on the rest of xs (which is zs). That's why groupBy works this strange way.

Argument of groupBy's Lambda


Android - Calendar get (Calendar.WEEK_OF_YEAR) dosen't work

Question: i'm trying to get the total week of an year,
and i use this instruction:
Calendar now = Calendar.getInstance();
         now.set(Calendar.YEAR,annoInizio);
         now.set(Calendar.MONTH,11);
         now.set(Calendar.DATE, 30);

int settTotInizio = now.get(Calendar.WEEK_OF_YEAR);

i print the varibles now and settTotinizio,
and in now the valude of WEEK_OF_YEAR is 40 but in settTotInizio is 1.
I don't understand where i do wrong.
Can someone help me?
This is my logcat:
I/System.out(30038): ,firstDayOfWeek=2,minimalDaysInFirstWeek=0,ERA=1,YEAR=2013,MONTH=11,WEEK_OF_YEAR=40,WEEK_OF_MONTH=1,DAY_OF_MONTH=30,DAY_OF_YEAR=275,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=48,SECOND=49,MILLISECOND=762,ZONE_OFFSET=3600000,DST_OFFSET=3600000]

I/System.out(30038): settTotInizio: 1

Answer: Months are zero-based so setting 11 to month field sets it to December. And 2013-12-30 is week number 1 in your locale.
Why the log prints week 40 first is because after the set() calls the other fields are not yet recomputed from the default current date values. If you switched the ordering of the log prints, you'd get compatible results as get() on a Calendar completes the other calendar fields.
Comment: Thanks now i've resolt! :)


Updating a Google Cloud SQL Database instance

Question: I have a deployed Cloud SQL Database instance running right now and it works fine. I am able to access and use it via my PHP Google App Engine app. I also have a local SQL Database for development.
Locally, I have made some changes to the structure of the database (added new columns) and would like to push those changes to the deployed app.
When I try to do this via the documented method on the App Engine site, I get an error saying the import failed for an unknown reason.
I am using a .sql dump made by PhpMyAdmin and have done this successfully for the initial import. I made sure to include USE DATABASE NAME in the dump.
Any ideas as to why it's failing? What is the best way to update a Cloud SQL Database? Thanks a lot!
Answer: An easy way is to request an IP, whitelist the IP you are connecting from (link) and use the MySQL client (link). Over IP you can also use GUI tools like MySQL Workbench, Toad, SQuirrel SQL and others (link).
Answer: You can set up phpMyAdmin as a different version of your application using the instructions here: https://gae-php-tips.appspot.com/2013/05/26/setting-up-phpmyadmin-on-app-engine/  That would probably be the easiest way of updating a Cloud SQL database...
Comment: I like this option best, but I can't seem to get it to work... I works locally but when I push it to production, the page is blank.
Comment: Razvan's method is probably easier than the one I mentioned


How to get first time from server by php and put in JavaScript

Question: How can I get first time from server by php?
I've tested this code but it does not work. It gets the time but it is not counting? What's the problem?

Comment: What is getting in variable d?
Comment: Is that code from a PHP or a JS file?
Comment: `` gives something like `13, 6, 5, 10, 52, 00`.
Comment: this code id js but it has a short php code inside
Answer: Explanation
The question is why are you using PHP to write a datetime into the Date object in JS?
The PHP will only write out the time at the point at which the page renders, it will never change again.
You are then setting your counter based on a Javascript setTimeout every 1 second, expecting the clock to increment in seconds, but it is always based on the same original time (the page render time) and is always incremented by 1 second.
For example.  The page loads at 12:00:00 on June 3 2013.  Your code looks like this:
d = new Date(13, 6, 3, 12, 0, 0);

at the time the pages loads (if you view source)
1 second later the setTimeout fires and renders the clock at 12:0:01, based on the starting time in the date object.
But your starting time never changes, so each further second that passes and triggers setTimeout will base the calculations on 12:00:00 not the current time
TLDR; and answer
Remove the PHP!
d = new Date();

Alternatively, if you absolutely have to use server time.  You would need to initialise the date object as you have done, but then store a count of how many seconds have passed and calculate the difference
Comment: What if it needs a server time?
Comment: If you **have** to use server time, you would have to initialise the `Date` object with the php, but then you would have to count the number of times that the `setTimeout` triggers so you could base your calculations on an incrementing number of seconds from the original


Finding $\delta$ based on given value of $\epsilon$

Question: Find the largest possible value of $\delta$ such that when $|x-y|<\delta$ we get $|\cos x -\cos y|<\sqrt2$.
I drew the graph of $\cos x$ between $[0,2\pi]$. I then visually realized that the value of $|\cos x-\cos y|$ will be less than $\sqrt 2$ if $x$ and $y$ are in $(-\cos^{-1}(\sqrt2-1),\cos^{-1}(\sqrt2-1))$. So we take $\delta=2\cos ^{-1}(\sqrt2-1)$ and since cosine function is uniformity continues this $\delta $ will work for any $x$ and $y$. Am I correct?
Comment: Since $\cos$ is most sensitive around $\pi/2$, I would say $\cos(\pi/2-\eta)-\cos(\pi/2+\eta)=\sqrt{2}=2\sin(\eta)$ so $\delta=2\eta=\pi/2$
Answer: Using a cosine identity, we have
$\cos x - \cos y = -2\sin \left(\dfrac{x+y}{2}\right) \sin \left(\dfrac{x-y}{2}\right)$
Then, make a change of variables: $u = (x+y)/2$ and $v = (x-y)/2$.
$\cos x - \cos y = -2\sin u \sin v$
So, in the interim, we are searching for the greatest $\delta^*$ such that if $|v| < \delta^*$, we have $|\sin u \sin v| < \sqrt{2}/2$. That is, we are searching for a least upper bounds. So, we look for the smallest possible $v$ such that $|\sin u \sin v| = \sqrt{2}/2$.
Note that $|\sin u \sin v|$ is maximized along the lines $u = \pi/2$ and $u = -\pi/2$, which permits us to write
$|\sin u \sin v| \leq |\sin v|$ (with equality when $u = \pm \pi/2$)
As $\sin v = \sqrt{2}/2$ when $v = \pi/4$, $v = \pi/4$ is our least upper bound $\delta^*$. Thus, if we choose $\delta^* = \pi/4$, we have that
if $|v| < \delta^*$, then $|\sin u \sin v| \leq |\sin v| < \sqrt{2}/2$
As $v = (x-y)/2$, $x-y=2v$, and the corresponding upper bounds $\delta$ for $|x-y|$ gives $\delta = \pi/2$.
Note that if we choose $(x,y)$ such that $|x-y|=\delta = \pi/2$, we have that the points $(x,y) = (3\pi/4,\pi/4)$ and $(x,y) = (-3\pi/4,-\pi/4)$ yield $|\cos x - \cos y| = \sqrt{2}/2$, so we can be sure that this $\delta$ is maximized.
Answer: In a question like this, try testing any proposed solution with actual numbers.
Does it work if $\delta$ is just slightly smaller than the upper bound you gave?
What if $\delta$ is equal to that upper bound?
A calculator will tell you that $\arccos(\sqrt2-1) \approx 1.1437177$
(taking angles in radians),
therefore you propose $\delta \approx 2.2874354.$
As pointed out in a comment already,
the cosine function is steepest around the input value $\frac\pi2,$
so let's try $x = \frac\pi2 - 1.1437,$ $y = \frac\pi2 + 1.1437$
so that $\lvert x - y\rvert = 2.2874 < \delta.$
Then
\begin{align}
\cos\left(\frac\pi2 - 1.1437\right) & \approx 0.910172, \\
\cos\left(\frac\pi2 + 1.1437\right) & \approx -0.910172, \\
\cos x - \cos y & \approx 1.820344 > \sqrt2. \\
\end{align}
Perhaps if you rethink what you "visually realized" you may find your error.
A hint: if you choose $\delta$ correctly, then any interval of width $\delta$ should work, not just an interval of width $\delta$ centered at $0.$
There are intervals $[\theta, \theta + \delta]$ over which the cosine varies more than it does over the interval $\left[-\frac\delta2,\frac\delta2\right].$
Those are the intervals you should be concerned with.

As an aside, I did not even choose the best counterexample above.
A better counterexample is $x = \frac\pi4,$ $y = \frac{3\pi}4.$
Then $\lvert x - y\rvert = \frac\pi2 < \delta$ (according to your choice
of $\delta$)
but $\cos x - \cos y = 2.$
So when looking for counterexamples it may pay to look a little more carefully at what is going on than to just choose something close to the supposed answer.
However, the mindless approach worked out OK in this particular case,
and any counterexample (no matter how ignorantly guessed) is sufficient to disprove the claim.
Comment: Sorry but what does it mean by 'mindless approach' ?
Comment: I mean that I simply looked at your value of $\delta$ and mindlessly chose a number very close to it by truncating the decimal expression. When I did this I was not thinking very much about whether there might be a more powerful counterexample. If the exercise were to find $\delta$ such that $\lvert\cos x-\cos y\rvert<1.9$ then this way of finding a counterexample would have failed, although $x = \frac\pi4,$ $y = \frac{3\pi}4$ would still be a counterexample (provided that you used the same method to find $\delta$).
Comment: In short, simply trying numbers near a supposed answer to a question like this will sometimes detect a wrong answer, but it is not guaranteed to detect all wrong answers. Still, it's an easy thing to try and works in many cases.


Which robust correlation methods are actually used?

Question: I plan to do a simulation study where I compare the performance of several robust correlation techniques with different distributions (skewed, with outliers, etc.). With robust, I mean the ideal case of being robust against a) skewed distributions, b) outliers, and c) heavy tails.
Along with the Pearson correlation as a baseline, I was thinking to include following more robust measures:

Spearman's $\rho$
Percentage bend correlation (Wilcox, 1994, [1])
Minimum volume ellipsoid, minimum covariance determinant (cov.mve/ cov.mcd with the cor=TRUE option)
Probably, the winsorized correlation

Of course there are many more options (especially if you include robust regression techniques as well), but I want to restrict myself to the mostly used/ mostly promising approaches.
Now I have three questions (feel free to answer only single ones):

Are there other robust correlational methods I could/ should include?
Which robust correlation techniques are actually used in your field?
(Speaking for psychological research: Except Spearman's $\rho$, I have never seen any robust correlation technique outside of a technical paper. Bootstrapping is getting more and more popular, but other robust statistics are more or less non-existent so far).
Are there already systematical comparisons of multiple correlation techniques that you know of?

Also feel free to comment the list of methods given above.

[1] Wilcox, R. R. (1994). The percentage bend correlation coefficient. Psychometrika, 59, 601-616.
Answer: Coming from a psychology perspective, Pearson and Spearman's correlation do appear to be the most common. However, I think a lot of researchers in psychology engage in various data manipulation procedures on constituent variables prior to performing Pearson's correlation. I imagine any examination of robustness should consider the effects of:

transformations of one or both variables in order to make variables approximate a normal distribution
adjustment or deletion of outliers based on a statistical rule or knowledge of problems with an observation
Answer: I would recommend you this excellent article published in Science in 2011 that I previously posted here. There is proposal of one new robust measure together with exhaustive and excellent comparison with other ones. Moreover, all measures are tested on robustness. Note that this new measure is also capable to identify more than one functional relation in data and also to identify nonfunctional relationships.
Comment: Specifically, see rebuttals of this approach at: http://statweb.stanford.edu/~tibs/reshef/comment.pdf, http://ie.technion.ac.il/~gorfinm/files/science6.pdf, http://arxiv.org/abs/1301.7745v1
Comment: That article has received a lot of critizism. It seems to be overhyped. Lots and lots and lots of media and PR work, but it seems to fail badly on trivial examples such as ▄▀ which it recognizes as "linear". IIRC their study also was not fair, as in they used ranks for their own method; but compared to pearson instead of spearman correlation.
Comment: Detecting Novel Associations in Large Data Sets
Comment: Can you put the name of the article please? It seems to have disappeared!
Comment: Great! I will take a very close look on that. Looks very promising ...
Comment: The statement "non-functional relationships" I think already gives it away...
Comment: Further adding to what @Anony-Mousse and metaperture stated, it's worth noting that one of their key claims about the advantage of their methods was easily proven not only to be false, but trivially impossible (see metaperture's final link).
Comment: First link is broken. Despite some heavyweight authors, a personal view is to agree that this was over-hyped.
Answer: Kendall's tau is very widely used in copula theory, probably because it is a very natural thing to consider for archimedean copulas. Plots of the cumulative Kendall tau were introduced by Genest and Rivest as a way to choose a model among families of bivariate copulas.
Link to Genest Rivest (1993) paper
Answer: Some robust measures of correlation are:

Spearman's Rank Correlation Coefficient
Signum (Blomqvist) Correlation Coefficient
Kendall's Tau
Bradley's Absolute Correlation Coefficient
Shevlyakov Correlation Coefficient

References:
•   Blomqvist, N. (1950) "On a Measure of Dependence between Two Random Variables", Annals of Mathematical Statistics, 21(4): 593-600.
•   Bradley, C. (1985) "The Absolute Correlation", The Mathematical Gazette, 69(447): 12-17.
•   Shevlyakov, G.L.  (1997) "On Robust Estimation of a Correlation Coefficient", Journal of Mathematical Sciences, 83(3): 434-438.
•   Spearman, C. (1904) "The Proof and Measurement of Association between Two Things", American Journal of Psychology, 15: 88-93.
Answer: Biweight midcorrelation implemented in R (very fast) via WGCNA and in Python (not so fast) via astropy.  That's my go-to for network analysis.
For sparse compositional data, there's also SparCC and FastSpar


C# - using "this" as a parameter to initialize a child class

Question: I want to know that using "this" as a parameter to initialize a child class is a good idea or not? If I want to ask it better, I should ask that in OOP world it's a good idea to access a parent class variable from a child class or not?
Thanks
Comment: Not sure what you mean - can you provide a sample code snippet to illustrate your meaning?
Comment: It depends on what you're doing OP, if it makes sense to do so and it doesn't smell funny the go for it. If you want a more specific answer you're going to have to provide some code.
Comment: Are you talking about inheritance, for example you have a `class Vehicle{}` and a `class Car : Vehicle{}` that inherits from its parent *class*? Or are you talking about object hierarchy, for example a `class Tire {}` with a property `Vehicle Parent` in which you store the reference to the parent *object* that "holds" instances of child *objects*?
Comment: It's fine to access a parent class variable from a child class. How can the child class know what it's suppose to do otherwise? What do you mean by "this"?
Comment: Do you mean to say that you want to pass a this pointer to the base class constructor, or to say that you want to initialize base class variables using the base keyword? Also, in C#, you use base, not this, when you want to initialize parent class variables, if that is what you mean. As others have already said, your question needs clarification.
Comment: +1 for @Izzy, I totaly agree. It depends entirely on the context.
Comment: @Corak I think this is the crutch of the issue.
Comment: It seems that my comment didn't send correctly. any way Thanks for your helps. My question was something like what Knaģis said. It wasn't about inheritance. It was about instances. And as I found from answers it's a normal usage in OOP. Thanks
Answer: It seems that you are planning on doing something like this:
public class MyClass
{
    private OtherClass _someProperty;
    public OtherClass SomeProperty
    {
        get
        {
             if (this._someProperty == null) this._someProperty = new OtherClass(this);
             return this._someProperty;
        }
    }
}

public class OtherClass
{
    private MyClass _parent;
    public OtherClass(MyClass parent)
    {
        this._parent = parent;
    }
}

This is quite standard OOP approach. The one thing you should remember for more advanced scenarios is that now you have a cyclic reference between these two objects and Garbage Collector will not be able to collect either of them while one is still referenced.
Comment: Personally, i prefer to break the cyclic reference by extracting the required members from 'this' and declaring the constructor of the 'child' to only accept what it needs. If it actually needs a reference to its parent object then so be it (consider a linked list)
Comment: About Garbage Collector you're right. It was one of the things that I was worried about.
Comment: Depends what MyClass and OtherClass are doing ... But I would suggest if OtherClass is using properties / methods .. etc of MyClass then proper inheritance should be used instead. Kind of difficult to give a proper answer here.
Answer:
in OOP world it's a good idea to access a parent class variable from a child
  class or not?

This is not an idea, this is like OOP works actualy.
You declare parent class, derive from it child class and from child class you can access parent's public, protected and internal (if child and parent are in the same assembly) members.
This is OOP design for it's excelence.
If you're asking something else, please clarify.
Comment: OP is also talking about using `this` to initialise the child, so OP might not have used inheritance properly, or might be using a strange design pattern, but +1.
Answer: By definition of a child class:

A child class is a class that was derived from another, that will now be the parent class to it.

It sounds like your code looks something like this:
class Parent {}
class Child : Parent {
    Parent m_parent;
    Child(Parent parent){m_parent=parent;}
}

Storing a reference of the parent class is not necessary here; the child class already has access to its member variables. It can even use base when there is ambiguity.
Therefor, using this as a parameter to initialize a child class, to give it access to its parent class, is not a good idea.


Infinite L'Hopital loop

Question: Consider a univariate continuous and differentiable function $f(x)$, such that $f(0)=0$. Additionally, it holds that
$$\frac{d f(x)}{d x}= a \left(\frac{f(x)}{x}\right)^b $$
where $a$ and $b$ are two real, positive constants.

An example of such function, and the one that motivated this question, is
$$ f(L) = A\left( B L^{\rho} + (1-B)K^{\rho} \right)^{\frac{1}{\rho}} $$
for a positive constant $K$, $L \geq 0$, and $\rho<0$ (the latter ensures that $f(0)=0$, which is computed using the limit). The notation correspondence between my function and the general one is $a=A^\rho B$ and $b=1-\rho$.

Say you want to find
$$\lim_{x \rightarrow 0} \dfrac{d f(x)}{d x}  = \lim_{x \rightarrow 0} a \left(\frac{f(x)}{x}\right)^b$$
Because of the assumption $f(0)=0$, this derivative has an undefined expression inside the parenthesis, $\frac{0}{0}$. Thus, you want to use L'Hopital for this. But if you apply L'Hopital to the parenthesis, you get:
$$ \frac{\dfrac{d f(x)}{d x}}{1} $$
Thus, we end up where we started. In other words, we are in an infinite L'Hopital loop. How can we get around it?
Apparently the answer to this limit is $0$, but I fail to see who this is achieved.
PS: a fairly similar question asks for the solution for a particular $f(x)$. I want to know the solution for the general case.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/59771/discussion-on-question-by-luchonacho-infinite-lhopital-loop).
Answer: Suppose that $f\in C^1$, i.e., $f$ is differentiable and the derivative is continuous (this is a small additional assumption).  Moreover, we assume that $\frac{f(x)}{x}\geq0$ for all $x$ so we don't need complex numbers.  Then,
$$
f'(0)=\lim_{x\rightarrow 0}\frac{df(x)}{dx}=\lim_{x\rightarrow 0}a\left(\frac{f(x)}{x}\right)^b=a\left(\lim_{x\rightarrow 0}\frac{f(x)}{x}\right)^b.
$$
Since $f(0)=0$, this equals
$$
a\left(\lim_{x\rightarrow 0}\frac{f(x)-f(0)}{x}\right)^b.
$$
But, we observe that the limit is actually a derivative, so we get
$$
f'(0)=a(f'(0))^b.
$$
Therefore, $f'(0)$ is a root of the polynomial $at^b-t=t(at^{b-1}-1)$ if $b\not=1$ and $x(a-1)$ if $b=1$.  Therefore, if $b\not=1$, then either $f'(0)=0$ or $f'(0)=a^{\frac{1}{1-b}}$.  In the other case $(b=1)$, either $a=1$ as well or $f'(0)=0$.

For example, in the case $a=1$ and $b=1$, then $f(x)=Kx$ satisfies the conditions and the derivative at $0$ is $K\not=0$.
The constant zero function, $f(x)=0$ gives a case where $f'(0)=0$.
And @MarkViola gives the function $f(x)=a^{\frac{1}{1-b}}x$ whose derivative at $0$ is $a^{\frac{1}{1-b}}$.
Comment: It might be instructive to alert the OP and others to an issue here that $f(x)$ must be of the same sign as $x$, else $\left(\frac{f(x)}{x}\right)^b$ is not defined on the reals in general.
Comment: @MarkViola Thanks for the observation, I've made the appropriate change.
Answer: Let $f(x)$ satisfy the first order ordinary differential equation
$$f'(x)-a\left(\frac{f(x)}{x}\right)^b=0\tag 1$$
with initial condition $f(0)=0$, where $a>0$ and $b>0$.

Note that in general $\left(\frac{f(x)}{x}\right)^b\notin \mathbb{R}$ unless $x f(x)\ge 0$. We proceed, therefore, under the assumption that $x\ge 0$ and $f(x)\ge 0$.

CASE $(1)$: $\displaystyle b=1$

If $b=1$, then the general solution to $(1)$ with initial condition $f(0^+)=0$ is $f(x)=Cx^a$ for any value of $x\ge 0$.

Note that the solution is not unique since $C$ is arbitrary.  Furthermore, we maintain the resriciton $x\ge 0$ since in general $f(x)$ is complex for $x<0$ (e.g. for $a=1/2$ and $x<0$, $f(x) =Cx^{1/2}=\pm iC\sqrt{|x|}$

Finally, we find that for $b=1$
$$f'(0^+)=\begin{cases}C&,a=1\\\\0&,a>1\\\\\text{sgn}(C)\,\infty&,0<a<1\end{cases}$$

If $b\ne 1$, then upon dividing both sides of $(1)$ by $(f(x))^b$ and integrating, we find the general solution of $(1)$ is given by
$$f(x)=(ax^{1-b}+C)^{1/{1-b}} \tag 2$$

CASE $(2)$: $\displaystyle 0<b<1$

If $0<b<1$, then the condition $f(0^+)=0$ requires that $C=0$ and we find
$$f(x)=a^{1/(1-b)}x \tag 3$$
Note that the solution given by $(3)$ is also valid for $x<0$.
Finally, taking the derivative yields $f'(x)=a^{1/(1-b)}$ for all $x$ and hence for $0<b<1$
$$f'(0)=a^{1/(1-b)}$$

CASE $(3)$: $\displaystyle 1<b$

If $1<b$, then unless $C=0$, $f(x)$ is not defined, in general, on the reals since $x^{1/(1-b)}$ is not real in general.  Clearly for $x\ge 0$, $\lim_{x\to 0^+}f(x)=0$ when $b>1$.  So, $(2)$ is the general solution to $(1)$ for $b>1$ and $x\ge 0$.
Finally, we have for $b>1$
$$\begin{align}
f'(0^+)&=\lim_{h\to 0^+}\frac{f(h)}{h}\\\\
&=\lim_{h\to 0^+}\frac{(ah^{1-b}+C)^{1/{1-b}}}{h}\\\\
&=\lim_{h\to 0^+} a^{1/(1-b)}\left(1+\frac{Ch^{b-1}}{a}\right)^{1/(1-b)}\\\\
&=a^{1/(1-b)}
\end{align}$$

SUMMARY:

The general solution to $(1)$ with initial condition $f(0^+)=0$ is given by
$$f(x)=\begin{cases}
a^{1/(1-b)}x&,0<b<1, x\in \mathbb{R}\\\\
Cx^a&,b=1,x\ge 0\\\\
(ax^{1-b}+C)^{1/(1-b)}&,1<b, x\ge 0
\end{cases}$$
and the derivative at $0^+$ of $f(x)$ is given by
$$f'(0^+)=\begin{cases}
a^{1/(1-b)}&,b>0, b\ne 1\\\\
C&,b=1, a=1\\\\
0&,b=1,a>1\\\\
\text{sgn}(C)\,\infty&,b=1,0<a<1
\end{cases}$$
Answer: If(!) $f'(0)$ exists, then
$$f'(0)=\lim_{x\to 0}\frac{f(x)-f(0)}{x-0}=\lim_{x\to 0}\frac{f(x)}{x} =\lim_{x\to 0}\left(\frac1af'(x)\right)^{1/b}=\left(\frac 1a\lim_{x\to 0}f'(x)\right)^{1/b}.$$
In particular, $\lim_{x\to 0}f'(x)$ must exist. But then this limit equals $f'(0)$ and we see that
$$ f'(0)=\left(\frac1af'(0)\right)^{1/b}$$
and hence (if $b\ne 1$)
$$ f'(0)= \frac 1{a^{1/(b-1)}}.$$
Comment: @MarkViola That is not true, as per my other comments.

Infinite L'Hopital loop


OpenGL Perspective Looks Off

Question: I'm using the following display code to draw the base of a bare-bones merry-go-round for a project:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, 1.0, 3.0, 7.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 4.0, 3.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0);

GLUquadricObj *obj = gluNewQuadric();
glTranslatef(0, 0, -0.05);
glColor3f(0, 0, 0);
gluCylinder(obj, radius, radius, 0.1, 100, 1);
glColor3f(0, 1, 0);
gluPartialDisk(obj, 0, radius, 100, 1, 0, 90);
glColor3f(1, 1, 0);
gluPartialDisk(obj, 0, radius, 100, 1, 90, 90);
glColor3f(1, 0, 0);
gluPartialDisk(obj, 0, radius, 100, 1, 180, 90);
glColor3f(0, 0, 1);
gluPartialDisk(obj, 0, radius, 100, 1, 270, 90);

glutSwapBuffers();

Now, this more or less works fine. It produces this, which is about what I'm expecting (not to scale):

The issue here is that it just looks bizarre and unrealistic. The center should be in...well, the center, but is instead significantly further "down" the image produced. Rotating the scene confirms that the partial disks are, in fact, the same size and around the same origin. What could be causing this?
Comment: Since when is the center of a circle in perspective, in the center ?
Here is a good explanation: http://illustrationfixation.blogspot.co.at/2011/05/circles-in-perspective-part-one.html
Comment: I guess I should have said "somewhere near the center". Yes, perspective moves it "down" a little, but this just looks wrong.
Comment: Evidently I'm not allowed to edit - looking at that link made me realize that the image produced is backwards. The smaller half should be on "top".
Answer: Well, it turned out to be embarrassingly simple. After looking at KoKuToru's link, It dawned on me that it was actually backwards - that is, the half of the circle that appears larger was on top when it should have been on bottom. With a little experimentation, I found that the culprit was in this line:
gluLookAt(0.0, 4.0, 3.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0);

Specifically, the second parameter. It's positive, which indicates up, rather than down, which is what I really wanted. D'oh.
Answer: If you had camera controls or could rotate it over time you might have a better idea of what was going on.
It looks a little like the cylinder partially obscures the red and yellow bits of the disc.
It seems unlikely but maybe there are further issues with depth testing or back face culling?
glEnable(GL_DEPTH_TEST); //not enabled by default on all OSes
glDisable(GL_CULL_FACE); //just to be sure
glDisable(GL_BLEND); //for good measure

Be careful with the near/far values in the projection - they're pretty close and can easily clip stuff out you don't want. Then again, more than a magnitude of 10,000 apart and you'll hit depth fighting issues.
Comment: I have tried having it rotate over time and it basically looks how you'd expect it to from the above image. It rotates about the corners of the four partial disks. Removing the cylinder shows that it's not covering anything up. I tried your additions anyway but alas, they were no help. In fact, enabling depth testing causes the partial disks to be out of place for some unfathomable reason.
Answer: I'm not sure that this is really the cause of your problem, but I got a strong hunch toward it: You don't supply an aspect ratio that reflects your viewport's aspect ratio.
In gluPerspective the second parameter takes the aspect of the viewport. Somewhere you have a call glViewport(x,y,width,height). You should supply gluPerspective with the ratio of width and height, i.e.
gluPerspective(45.0, (float)width/(float)height, 3.0, 7.0);

Comment: I actually don't have any calls to glViewport - I'm not entirely sure what its purpose is. As for the aspect ratio, it's set to 1 but based on what you're telling me that's right because my viewport is actually 500x500 (I trimmed the rest out of the image).
Comment: @macamatic: The viewport tells OpenGL which rectangular area (in pixels) of the window shall the limits of the NDC volume (i.e. after projection) be mapped to. The default value is the full size of the window **at the moment** the OpenGL context was **bound to that window for the first time**. All subsequent changes of window geometry **do not** automatically reflect on the viewport. Relying on that default behavior is not very reliable, so it's highly recommended you set the viewport at the beginning of your display routine.

OpenGL Perspective Looks Off


Using fancybox how do I link an image title to an html page?

Question: I am an artist that is using fancybox to display my gallery.  I would like people to be able to click the title of each image so that they go to separate html pages unique to each image. I would be grateful for any help.

Comment: Could you please post some code? It would be easier to understand your problem then.
Comment: HTML:
Comment: I need the thumbnail to pull up the regular image with the title underneath as in the code above. What I don't know how to do is get the title text (and only the title text: "Ambergris Caye • 48in X 36in • Oil on Gallery Wrapped Canvas") to link to an html page, i.e., ambergris.html
Answer: You could use (HTML5) data-* attributes in your html to pass the link (and optionally title) to be used in the fancybox title for each image like :

... etc.
Then you could use the jQuery's .wrapInner() method inside the fancybox's afterShow callback to get the info from the data attributes like :
$(".fancybox").fancybox({
    afterShow: function () {
        $(".fancybox-title").wrapInner($("", {
            href: this.element.data("link"), // link to
            title: this.element.data("caption"), // shows tooltip on mouse hover fancybox title
            target: "_blank" // optional opens in a new tab/window
        }));
    }
});

This will wrap the contents of each .fancybox-title (selector) with an  tag and set the relevant attributes (href, title, etc.) you need/want from the data attributes.
See JSFIDDLE
NOTE : the afterShow callback is for fancybox v2.x. If working with v1.3.4, then use onComplete and target the #fancybox-title selector instead.
Comment: WOW, thank you JFK! I appreciate your help and your time!!...  I've been messing with this and I must have something wrong because it's not working for me.  Here is my test link: http://www.jillenglish.com/gallery/test.html
Comment: @Jill : the issue you have is that you are using fancybox v1.3.4 so replace `afterShow` by `onComplete` and `$(".fancybox-title")` by `$("#fancybox-title")` in your custom script.


Why isn't  the node ID available as "replacement pattern" for the title link?

Question: I have a simple view for a node using an "unformatted list" and fields. I want to link the title to another URL and pass the NID. However, as "replacement pattern" I only have the "[title]" token.
When I add the NID field to the view I can link it just fine. What am I missing?
Answer: You've to add the nid field and exclude it from display, after your NID must be before your title and you'll have access to it.
Even, if is not right, normally you'll have it.
Answer: Yvan is right: If you want any link reference, that reference field needs to be added before active (title) field. In that way, you can use "[id]" in your pattern.
Answer: You have to rearrange and place the Nid (Nid) at the top ( first position )


How to load encrypted private key in Node.JS


Wrong path when moving from MAMP multisite to remote website

Question: I have different sites in MAMP, each of them being located in ../htdocs/
i.e. ../htdocs/site1, ../htdocs/site2, ../htdocs/site3, etc.
In some page of site1, I have something like

Petit retour aux sources : comment tout a commencé

Le golfe du Morbihan en 2008

En 2009, cap sur l'archipel de Glénan

Cette année (2010), c'est Bénodet !

Et pourquoi pas Stockholm en 2011 ?

2012, l'année des cairns du golfe du Morbihan

En 2013, tranquillement sur la Vilaine...

Golfe du Morbihan « agayne » en 2014

2015 : encore le Golfe mais en famille

Then, I move site1 to web provider and ../htdocs/site1 becomes www (root of the web site).
And, of course, URLs such as "/site1/node/36" don't work anymore :-(
How can I solve that?
Answer: It sounds like in MAMP you're using one domain, localhost, instead of three separate domains for three separate codebases.
You should set up three domains in MAMP and then you can use relative urls such as "/node/50" instead of "/site1/node/50".
Then your config would be in /sites/default/settings.php, with an included settings.local.php that is git excluded to use different database credentials between the local and production sites.
Multisite is a different set up.
You wouldn't have three separate codebases, such as "/htdocs/site1", "htdocs/site2" and "htdocs/site3".
You would have one codebase such as "htdocs/mymultisite".
With a non-multisite set up with three separate codebases, you would create three hosts in MAMP and then point each docroot to that site's docroot, for example, "/htdocs/site1", "htdocs/site2" and "htdocs/site3".
For a multisite set up, you would use one codebase (such as "htdocs/mymultisite" and create a sites folder for each domain.  First, you would copy example.sites.php to sites.php in the /sites folder of your repo. Then for each host, you would set up a folder with a separate settings.php, for example:
/sites/site1.local/settings.php
/sites/site2.local/settings.php
/sites/site3.local/settings.php

with the folder name corresponding to the domain set up in MAMP.
(With a non-multisite set up with separate codebases, you can just use the /sites/default/settings.php)
For both separate codebases and hosts in mamp, and for multisite with sites folders, it should work to visit each domain, such as site1.local in your browser, the urls will be relative to that URL.
If you are using multisite, when you want to go to production, you can set up a folder for production.  Set up a folder for production:
/sites/mysite.com/settings.php

There is a lot of information about setting up multisite Drupal.


Randomly failing polymer web component test

Question: Yet another attempt to marry Polymer with ES6 classes.
And it almost works except a wct test failing randomly on a polymer component with an imported es6 class (by systemjs). As far as I understand, this happens because the script, containing class definition, gets loaded after mocha executed the test.  The polymer component consists of two parts - html and javascript (to compile latter to es5),
html:
<dom-module id="my-test">
   <template>hello</template>

</dom-module>

javascript:
import {User} from 'elements/model/user.js';

Polymer({
 is: "my-test",

 method: function(){
   console.log("method, user="+this.val);
 },

 ready: function(){
   this.user= new User(); //this.user is randomly undefined
 }
});

This seems to work quite stable in the browser, at least when loaded from localhost. But the only thing which 'fixes' the test is delaying Polymer's ready call:
Polymer.whenReady = function (f) {
   console.log("polymer ready");
   setTimeout(f, 100);// "fix"
   //f();
}

which means at some point all this will fail in browser too (maybe when serving not from the localhost).
I'm thinking about getting somehow to the system-register's promises and making something similar to HTMLImports.whenDocumentReady, but I still don't have clear understanding of how all this works.
So any ideas and suggestions are highly appreciated!
The sample app is on github:
git clone https://github.com/bushuyev/test_test.git
cd test_test
git checkout tags/random_fail
npm install
bower install
gulp wct

To make it succeed more often than fail - change verbose to true in wct.conf.js.
kind of update: How to import system js SFX library
Answer: It's possible to use Polymer, SystemJS and TypeScript (like ES6 but with added Polymer-friendly syntax) together in a very nice way, also handling HTML imports using SystemJS. That does involve a timing issue, and I've published a small shim that first waits from webcomponents.js to load and catches its ready event (before other code gets a chance to see it), then it loads Polymer and finally all other components and TypeScript code. Then it dispatches the event again so Polymer finishes initializing itself.
Here's an article about combining the technologies with the mentioned solution, downloadable code and a demo.


React Native Android is suddenly unable to find google services

Question: Yesterday I was happily compiling my app on both iOS and Android. When I came back nothing worked anymore on Android.

google-services plugin could not detect any version for com.google.android.gms or com.google.firebase, default version: 9.0.0 will be used.
  please apply google-services plugin at the bottom of the build file.

The message is pretty straightforward and I already had to deal with it a couple of times already when installing dependencies into the app. And I always managed to solve this problem. But this time it is showing for absolutely no obvious reason as I didn't touch my android sdk.
Futhermore, my gradle config file has not been touched neither. And below you will see I also have the apply google-services plugin line at the end of the file.
I tried coming back to an older commit, just in case. But things remain the same and I'm a little overwhelmed by the problem right now..
Here is my app/gradle file:
apply plugin: "com.android.application"

import com.android.build.OutputFile

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.myApp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword RELEASE_STORE_PASSWORD
            keyAlias RELEASE_KEY_ALIAS
            keyPassword RELEASE_KEY_PASSWORD
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

configurations.all {
    resolutionStrategy {
        force 'com.google.android.gms:play-services-ads:9.2.1'
        force "com.google.android.gms:play-services:9.2.1"
        force "com.google.android.gms:play-services-location:9.2.1"
        force "com.google.android.gms:play-services-maps:9.2.1"
        force "com.google.android.gms:play-services-gcm:9.2.1"
        force "com.google.android.gms:play-services-analytics:9.2.1"
        force "com.google.firebase:firebase-core:9.2.1"
        force "com.google.firebase:firebase-analytics:9.2.1"
    }
}

dependencies {
    compile project(':react-native-maps')
    compile project(':react-native-linear-gradient')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile project(':react-native-fbsdk')
    compile project(':react-native-firebase-analytics')
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
  from configurations.compile
  into 'libs'
}

apply plugin: 'com.google.gms.google-services'

And here is a screenshot of my android SDK Manager

Does anyone have an idea of what's happening?
Answer: I found the solution to my problem. Actually I don't know why it was working before at all.
But, by reading my code I actually saw that I force a version of Firebase but I never actually compile it... So I removed the force from the configuration and moved my dependence in the dependencies block
I really don't know if this is the right solution
But this fixed my problem:
configurations.all {
    resolutionStrategy {
        force 'com.google.android.gms:play-services-ads:9.2.1'
        force "com.google.android.gms:play-services:9.2.1"
        force "com.google.android.gms:play-services-location:9.2.1"
        force "com.google.android.gms:play-services-maps:9.2.1"
        force "com.google.android.gms:play-services-gcm:9.2.1"
        force "com.google.android.gms:play-services-analytics:9.2.1"
    }
}

dependencies {
    compile project(':react-native-maps')
    compile project(':react-native-linear-gradient')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile project(':react-native-fbsdk')
    compile project(':react-native-firebase-analytics')
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile "com.google.firebase:firebase-core:9.2.1"
    compile "com.google.firebase:firebase-analytics:9.2.1"
}


Aplicação fechando (unfortunately MyApplication has stopped)

Question: Estou fazendo a aplicação abaixo, do curso do Neri, porém quando implemento o código referente ao botão a aplicação fecha sozinha com erro

unfortunately MyApplication has stopped

Se comentar o código do botão, a aplicação roda. Segue o código:
MainActivity
package br.com.calculadora;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.*;

public class MainActivity extends ActionBarActivity {

EditText etNum1, etNum2, etResultado;
double num1, num2, resultado;
Button btSomar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

    etNum1 = (EditText) findViewById(R.id.calculo_numero1);
    etNum2 = (EditText) findViewById(R.id.calculo_numero2);
    etResultado = (EditText) findViewById(R.id.calculo_resultado);

    btSomar = (Button) findViewById(R.id.botao_soma);

    btSomar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            num1 = Double.parseDouble(etNum1.getText().toString());
            num2 = Double.parseDouble(etNum2.getText().toString());
            resultado = num1 + num2;
            etResultado.setText(String.valueOf(resultado));

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }
}

}

fragment_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="br.com.calculadora.MainActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/titulo" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="18dp"
    android:text="@string/text1" />

<EditText
    android:id="@+id/calculo_numero1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView3"
    android:layout_below="@+id/textView3"
    android:ems="10"
    android:inputType="number" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/calculo_numero1"
    android:text="@string/text2" />

<EditText
    android:id="@+id/calculo_numero2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/calculo_numero1"
    android:layout_below="@+id/textView2"
    android:ems="10"
    android:inputType="number" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/botao_soma"
    android:layout_centerVertical="true"
    android:text="@string/resultado" />

<EditText
    android:id="@+id/calculo_resultado"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/calculo_numero2"
    android:layout_below="@+id/textView4"
    android:ems="10"
    android:inputType="number" />

<Button
    android:id="@+id/botao_soma"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/calculo_numero2"
    android:layout_below="@+id/calculo_numero2"
    android:text="@string/button1" />

</RelativeLayout>

log do erro no LogCat:
03-18 16:18:54.339: D/AndroidRuntime(1879): Shutting down VM
03-18 16:18:54.339: W/dalvikvm(1879): threadid=1: thread exiting with uncaught exception    (group=0xb3a75ba8)
03-18 16:18:54.389: E/AndroidRuntime(1879): FATAL EXCEPTION: main
03-18 16:18:54.389: E/AndroidRuntime(1879): Process: br.com.calculadora, PID: 1879
03-18 16:18:54.389: E/AndroidRuntime(1879): java.lang.RuntimeException: Unable to start   activity ComponentInfo{br.com.calculadora/br.com.calculadora.MainActivity}: java.lang.NullPointerException
03-18 16:18:54.389: E/AndroidRuntime(1879):     at    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.os.Looper.loop(Looper.java:136)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.main(ActivityThread.java:5017)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at java.lang.reflect.Method.invoke(Method.java:515)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at dalvik.system.NativeStart.main(Native Method)
03-18 16:18:54.389: E/AndroidRuntime(1879): Caused by: java.lang.NullPointerException
03-18 16:18:54.389: E/AndroidRuntime(1879):     at br.com.calculadora.MainActivity.onCreate(MainActivity.java:39)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.Activity.performCreate(Activity.java:5231)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-18 16:18:54.389: E/AndroidRuntime(1879):     ... 11 more
03-18 16:23:54.839: I/Process(1879): Sending signal. PID: 1879 SIG: 9

Após as alterações sugeridas pelo @ExceptionAI, o código ficou:
MainActivity:
package br.com.calculadora;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.*;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    EditText etNum1, etNum2, etResultado;
    double num1, num2, resultado;
    Button btSomar;

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        etNum1 = (EditText) rootView.findViewById(R.id.calculo_numero1);
        etNum2 = (EditText) rootView.findViewById(R.id.calculo_numero2);
        etResultado = (EditText) rootView.findViewById(R.id.calculo_resultado);

        btSomar = (Button) rootView.findViewById(R.id.botao_soma);

        btSomar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                num1 = Double.parseDouble(etNum1.getText().toString());
                num2 = Double.parseDouble(etNum2.getText().toString());
                resultado = num1 + num2;
                etResultado.setText(String.valueOf(resultado));

            }

        });

        return rootView;
    }
}

}

Segue tb o activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="br.com.calculadora.MainActivity"
    tools:ignore="MergeRootFrame" />

Answer: Tive esse problema e resolvi assim:
/*
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements View.OnClickListener {

Comment: Resolveu meu problema, muito obrigado @Euder
Answer: Você está tentando locatilizar o botão no layout activity_main mas seu botão está no fragmento fragment_main, por isso ele é nulo.
Basta mover seu código do onCreate da activity para o onCreateView do fragmento e utilizar o rootView.
btSomar = (Button) rootView.findViewById(R.id.botao_soma);
Comment: Não estou certo se o método `onCreateView()` é o local mais adequado para mover o código. Esse método não deveria exclusivamente retornar a view que compõe o fragment, de acordo com o ciclo de vida dos fragments?
Comment: @Piovezan Depende. O problema descrito é bem básico, o OP é obviamente iniciante em Android e então descrevi a forma mais simples de resolver o problema, sem entrar em detalhes da melhores prática do uso de fragmentos. Vamos um passo por vez.
Comment: @ExceptionAl, fiz como vc disse, mas o erro persiste, movi todo o código.
Comment: @JamesOrtiz Atualize a pergunta com o novo código e coloque também o xml do seu activity_main. Lembrando que era pra mover apenas o código do botão.
Comment: @ExceptionAl, coloquei o novo código, agradeço pela ajuda!
Answer: Pode ocorrer também quando é escrito uma caractere estranho ao código exemplo:
Implementação incorreta
.....
private String getClassName() {
        String s = getClass().getName();
        return s.substring(s.lastIndexOf(","));
    }
.....

Implementação correta
.....
private String getClassName() {
        String s = getClass().getName();
        return s.substring(s.lastIndexOf(".)); /*Observe que nesta linha
                                        deve ter um ponto em vez da vírgula*/
    }
.....


Showing at least there is a zero inside the unit disk

Question: I'm trying to figure out the following problem
Suppose $f$ is holomorphic on the closed disk $D=\{z \mid |z|\leq 1\}$ and $M>0$ is a constant. If $|f(z)|>M$ for all $z \in \partial D$ and $|f(0)|<M$. Prove that $f$ has at least one zero in int($D$).
It looks like I should apply the maximum modulus principle: Suppose that $f$ has no zeroes. Then we should consider $1/f$...
Comment: You're nearly there.  What can you say about the values of $|1/f|$ on $\partial D$ and at 0?  What does the maximum modulus principle say about $1/f$? You should get a contradiction.
Comment: Compare https://math.stackexchange.com/q/2337956/42969.
Answer: Suppose
$f(z) \ne 0, \forall z \in \text{int}(D); \tag 1$
then since
$\vert f(z) \vert > M, \; \forall z \in \partial D, \tag 2$
we see that
$f(z) \ne 0, \forall z \in D; \tag 3$
it follows that $1/f(z)$ is holomorphic on $D$; furthermore, (2) implies
$\left \vert \dfrac{1}{f(z)} \right \vert = \dfrac{1}{\vert f(z) \vert} < M^{-1}, \; \forall z \in \partial D; \tag 4$
also,
$\vert f(0) \vert < M \tag 5$
implies
$\left \vert \dfrac{1}{f(0)} \right \vert = \dfrac{1}{\vert f(0) \vert} > M^{-1}. \tag 6$
Now from the fact that $1/f(z)$ is holomorphic on $D$ we infer, by the maximum modulus principle, that the maximum of $\vert 1/f(z) \vert = 1/\vert f(z) \vert $ occurs on $\partial D$; but this assertion is in direct contradiction to (4) and (6) combined, which show that $\vert 1/f(z) \vert$ is less at every point of $\partial D$ than at the interior point $0$; thus
$\exists z \in \text{int}(D), \; f(z) = 0. \tag 7$


Slow Google Script - difficulties batching information into an array

Question: I've been struggling with a little project of mine for a while now, and was looking for some assistance. The key issue I believe is simply me not being familiar with array script language and how to approach this. I've tried a few things after researching on here a bit and reading through the Best Practices section, but haven't been able to get it functioning adequately.
My script needs to be able to collect 200 rows x 200 columns of data from a spreadsheet, and depending on the number within each cell, it needs to select the corresponding number of columns next to that number and colour them in.
This was really simple to do with my basic programming knowledge, by just getting it to select each cell, check the number, select that range with an offset and then change the colour and move onto the next cell, however my code is incredibly slow because it does everything within the sheet without batching the data, and can't complete the full range within Google Script's time allowance. Any assistance on speeding it up would be greatly appreciated, as I haven't been able to get this working using arrays.
Here's the code I'm working with currently:
function CreateCalendar() {

  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=ss.getSheetByName('Sheet2');
  var selection=ss.getRange("Sheet2!H2:FC140");
  var columns=selection.getNumColumns();
  var rows=selection.getNumRows();

  for (var column=1; column < columns; column++) {

    for (var row=1; row < rows; row++) {
      var cell=selection.getCell(row,column);
      var cellvalue=cell.getValue();
        if (cellvalue >= 1) {
        var range=cell.offset(0,0,1,cellvalue);
        range.setBackground("blue");
      }
        else {;}
    }
  }
}

Here's a public spreadsheet with confidential info removed and the sheet I'm targeting is Sheet2. Any assistance I could get on this would be greatly appreciated! Thanks
https://docs.google.com/spreadsheets/d/1Oe0aacfSBMmHpZvGPmjay5Q1bqBebnGQV4xlsK8juxk/edit#gid=0
Answer: You need to get rid of the repeated calls to range.getValue(). You can get all of the values for the range in one call & then iterate over that array in-script.
For your script it would look something like this:
function CreateCalendar() {

  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=ss.getSheetByName('Sheet2');
  var selection=ss.getRange("Sheet2!H1:FC140"); // <= include header, but we'll skip it when we get to stepping over the array
  var values = selection.getValues(); // <= get all of the values now in one call
  for (var r=1; r < values.length; r++) {
    for (var c=0; c < values[r].length; c++) {
      if (values[r][c] >= 1) {
        var range=sheet.getRange(r+1, c+8, 1, values[r][c]); // r+1 & c+8 because of array offsets
        range.setBackground("blue");
      }
        else {;}
    }
  }
}

Take a look at Google's documentation: range.GetValues() https://developers.google.com/apps-script/reference/spreadsheet/range#getValues()
Comment: In a GSheet the top-left corner is row 1, column 1, which corresponds to element [0][0] in the 2D array. So to translate from `values[r][c]` to `range(r,c)` we normally need to add 1. In your case we need to add 8 to the column index because your data range begins at column H (the 8th column)
Comment: This worked brilliantly, thank you so much!

Just for clarity, you say "r+1 & c+8 because of array offsets". What does this mean? I understand the error I made in the base code after reading this, but that part is stumping me
Comment: EDIT: Never mind, I understand you're just skipping the header row and hidden columns. Thank you very much!
Answer: How about following sample script? If this is not your expectation, I would like to modify this script.
Sample script :
function CreateCalendar() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=ss.getSheetByName('Sheet2');
  var data = sheet.getRange("H2:FC140").getValues();
  data.forEach(function(e1, i1){
    e1.forEach(function(e2, i2){
      if (e2 >= 1) {
        sheet.getRange(i1+2, i2+8).offset(0,0,1,e2).setBackground("blue");
      }
    })
  })
}

Result (sample) :

If I misunderstand your question, I'm sorry.


Add user email and username under the "View" tab at /user/%

Question: Using Drupal 7 and I would like to display the username and email under the view tab of the /user page.
Out of the box it only shows the user History, which I find a bit meaningles. I think that a user should see all his info under the view tab (including username and email) and then when he wants to edit it he can click on the edit tab.
Would be nice if this could be done with a block or similar so that this does not apply to the admin user.
Thanks!
Answer: You can always create a block through Views and display this information. Here's how to do that:

Create a new view, choose to show "Users" and create only a block.
Add "E-mail" field.
Add "Contextual filter" for the "User: Uid" field.
For filter configuration choose "Provide default value" and then "User ID from URL".
Show the block in content area, and configure it so it's displayed only on specific pages. Enter the aliased path you use for user profiles. For example: profile/*. This is necessary because the system URL for user profile pages is user/[uid], which you cannot distinguish from user/login, user/register and so on.

Do note that this will make the username/email available to everyone who has the permission to view user profiles.
Hope this helps.


Post the same menu as two different blocks?

Question: I have a menu called main-menu.  I want to post it twice as a block: one block with a main-menu in the header, and one block with a main-menu in the footer.  But Drupal 7 will not allow it.  Drupal 7 only allows me to post the block once...either in the header or in the footer.
Is there another way?  If not, I will use Javascript to clone the entire main-menu html node and append to footer node.
Comment: This thread might help: http://drupal.stackexchange.com/questions/9677/place-a-block-in-multiple-regions
Comment: Why don't you simply build two menus (with the same links) and post each one to a different region?
Answer: The Menu Block module will do this.

So… have you ever used the Main and Secondary menu links feature on your theme and wondered "how the hell do I display any menu items deeper than that?"
Well, that's what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
Answer: It seems that the MultiBlock module can do this.

The MultiBlock module solves this problem by allowing you to create multiple block instances of already existing blocks.
Comment: I could not get MultiBlock to work with Drupal 7. I did have success with Menu Block.
Comment: It worked for me, you will just need to create an instance from block page.
Answer: You can do this with the Render API in Drupal 7 quite easily, specifically look at hook_page_alter(). The Render API is a lot like the Forms API, you create content as arrays that describe the content, rather than creating raw HTML. Blocks are now created using these render arrays, which makes them very easy to manipulate from the module or theme layer. You can check out the documentation on the Render API for more details. Also, I found some Drupalcon videos quite helpful:
http://www.archive.org/details/drupalconchi_day3_the_render_api_in_drupal_7 and http://www.archive.org/details/PageRenderDrillDownInDrupal7 are good ones.
In your specific case, you'd implement hook_page_alter() something like this assuming the block is called 'main-menu' and it's in the 'header' region of your page...
function mymodule_page_alter(&$page) {
  // get the block you're after from the $page array
  $menu_block = $page['header']['main-menu'];

  // copy the block to another location in the page array
  $page['footer']['main-menu'] = $menu_block;
}

This code grabs the definition of the 'main-menu' block and copies it to the footer region. This will cause Drupal to print the block twice. This specific example is also shown in at least one of the videos linked to above.
Answer: also you can print the menu block a second time through the template page.tpl.php file or the one what you want to modify...
doing something like this...

            <?php print render($page['menu']); ?>

            .....
            .....page content and content blocks
            .....

            <?php print render($page['menu']); ?>

That should make it, and with css you can make the style Change if needed
.header > .menu{..styles menu header...}
.footer > .menu{..styles menu footer...}

Answer: Menu clone allows you to clone a menu, but adjust it as you like, before creating a block that you can add anywhere in your site. It's a bit more flexible than menu block.


Get users by display name on reference autocomplete field

Question: I need a list of users for a reference autocomplete field. I know about the realname module, but I haven't installed it, neither will I as long as it remains an RC (and I don't need all it provides). Anyway, I copied the code I needed from it and adapted it accordingly.
My users have a first_name and last_name fields. Here is the query I came up with in order to return the JSON for my autocomplete field:
<code>$sql = "SELECT u.uid
        FROM users u
        INNER JOIN users_field_data ud ON u.uid=ud.uid
        LEFT JOIN user__field_first_name fn ON fn.entity_id=u.uid
        LEFT JOIN user__field_last_name ln ON ln.entity_id=u.uid
        WHERE CONCAT_WS(:separator, fn.field_first_name_value, ln.field_last_name_value) LIKE :text OR ud.name LIKE :text";

$uids = \Drupal::database()->queryRange($sql, 0, 10, [
    ':text'      => '%' . db_like($input) . '%',
    ':separator' => ' ',
])->fetchCol();
</code>
Do I have an alternative to this? I would rather not reference individual tables.
Answer: A potentially cleaner/easier way to do that would be to leverage the JSON API.  After you install that module, you should able to make a call to the /jsonapi/user/user endpoint (see the "GET user accounts section on https://www.drupal.org/docs/8/modules/json-api/fetching-resources-get), and parse out the UIDs into the array.


Slider control in .NET 4.0

Question: what is the slider control called in .NET 4.0?
The one which lets you slide a marker and from one end to the other.
Like this:

Can't find it anywhere.
Answer: <code>System.Windows.Controls.Slider (in WPF)
System.Windows.Forms.TrackBar (in WinForm)
</code>

Slider control in .NET 4.0


Como forçar a posição Paisagem/Landscape?

Question: Como forçar a posição Paiagem/Landscape em minha activity para sempre ativa e bloquear a posição Retrato/Portrait.
Quero que meu aplicativo ja inicie em posição paisagem e não possa virar para a posição retrato.
Answer: Na sua activity você precisa colocar o seguinte código no método onCreate:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);

Ficando assim:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sua_activity);

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);

Comment: Obrigado amigo, funcionou 100%
Answer: Olá, isto também pode ser feito no AndroidManifest, não necessitando fazer no código:
    <activity
        android:name="..."
        android:label=".."
        android:configChanges="orientation"
        android:screenOrientation="portrait">


How to fit data when SSE is unreliable

Question: I am trying to estimate the parameter $\theta$ in the following problem.
I generate some noiseless data using: $Y ^{-\theta} = X_1 ^{-\theta} + X_2 ^{-\theta}$, where theta_real is set to a random number from 2 to 5 (my run for this data pulled a value of 4).
#Create some data
theta_real = sample(2:5,1)
X2 = sample(10:100, 100, replace=TRUE)
X1 = sample(10:100, 100, replace=TRUE)
Y <- (log(1/((X1^(-theta_real) + X2^(-theta_real))))/log(theta_real))
df <- data.frame(Y,X2,X1)

I attempt to estimate theta using nls2 in R:
require(nls2)

#For later flexibility
f_form <- function(x,theta) {x^-theta}

#Model Formula
fo <- f_form(Y,theta) ~ ((f_form(X1,theta) + f_form(X2,theta)))

#Evaluate 1000 different values
grid_length = 1000
st1 <- expand.grid(theta = seq(-10, 10, len = grid_length))
res <- nls2(fo,data=df, start=st1,algorithm="brute-force")
summary(res)

The result:
Formula: f_form(Y, theta) ~ ((f_form(X1, theta) + f_form(X2, theta)))

Parameters:
      Estimate Std. Error t value Pr(>|t|)
theta    10.00       6.48   1.543    0.126

Residual standard error: 2.037e-09 on 99 degrees of freedom

Number of iterations to convergence: 1000
Achieved convergence tolerance: NA

While minimizing SSE, theta gets driven to greater and greater negative values. (Notice that the estimate of $\theta = 10$ although the variable theta_real was sampled from the range 2 to 5. For whatever search bounds chosen, this method will always select the greatest theta.) This is because nls2 is minimizing sum square error, and as theta gets modified, the left-hand side of the equation gets transformed leading to the minimization of the SSE.
So how do you find the true $\theta$? Is there a way to minimize SSE relative to the range of values? Or a way to minimize according to correlation in the residuals?
Notes:
I've found that for the currently specified problem, using the inverse function helps, but what if the function is non-invertible (or has no closed form solution or some other issue preventing me from using the inverse)?
I also asked this question slightly differently here but it got closed due to ambiguity so I'm asking a different question.
Answer: This is not a full answer, because I'm not really understanding the question. Obviously, you would do a regression with $Y = (X_1^{-\theta} + X_2^{-\theta})^{-1/\theta}$ in this specific example. Of course, the documentation warns explicitly that nls shouldn't be used (and won't converge) with artificial zero-noise data.
If "the function is non-invertible" you need to give a specific example, because there is no universal solution to the problem.
Your formula for calculating Y is wrong. Either use
Y <- exp(log(1/((X1^(-theta_real) + X2^(-theta_real))))/(theta_real))

or (easier) from above
Y <- (X1^(-theta_real) + X2^(-theta_real))^(-1/theta_real)

Then you should absolutely not use nls2 here. It is intended for solving formulas of the form y ~ f(X). I'm astonished that it works at all, but the statistical output of summary cannot be trusted.
You are doing a simple grid search, which is easy to code in R:
res1 <- sapply(unlist(st1), function(th) {
  c(th, sum((f_form(df$Y, th) - (f_form(df$X1, th) + f_form(df$X2, th)))))
})

plot(res1[1,], log10(res1[2,]), type = "l")

And there you see a nice local minimum of the SSE.
You could now scale the SSE:
res1 <- sapply(unlist(st1), function(th) {
  c(th, sum(((f_form(df$Y, th) - (f_form(df$X1, th) + f_form(df$X2, th)))/f_form(df$Y, th))^2) )
})

plot(res1[1,], log10(res1[2,]), type = "l")

res1[, which.min(res1[2,])]
#[1] 3.993994e+00 4.095345e-05

And of course, you could then use a "real" optimizer.

How to fit data when SSE is unreliable


PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: if

Question: New to SQL and can't figure out why I'm getting the above error in the code.
BEGIN
IF NOT EXISTS(SELECT 1 FROM addresses WHERE address.upper() = 'firstname.lastname@example.com') THEN
    INSERT INTO addresses
                     (id, type, address
                     )
              VALUES ('123', 'UNREGISTERED', 'firstname.lastname@example.com'
                     );

END

Comment: Why do you insert numeric value as string?
Answer: First, PL/SQL does not allow EXISTS as an IF condition.
Second, if you want to prevent duplicates, don't use IF!!! Let the database enforce the data integrity, with a unique constraint or index:
create unique index unq_addresses_addresses on (upper(address));

Third, the function is upper() and it is called as upper(address) not address.upper().
And finally, do you really want addresses to be unique?  It would seem that different users or types might have the same address.
Answer: Aaron try this insert:
INSERT INTO addresses (id, type, address)
SELECT '123', 'UNREGISTERED', 'email@example.com' FROM dual
WHERE NOT EXISTS (SELECT 1 FROM addresses WHERE UPPER(address) = 'firstname.lastname@example.com');


how to measure similarity of two datasets (matrices) of different length

Question: There are related questions being asked already but my problem is i can't find a good method of measuring similarity between two datasets that are represented by various lengths of matrices. For instance, first dataset is a sensor data with x,y,z,gyro,acc features of 1000 records. The second dataset's features are the same but with 1500 records. So how do I compute the similarity between these two.
I've used dynamic time warping (DTW) but not sure about it because it is mostly used for time-based operations but my dataset doesn't contain any temporal info. Also, it doesn't output a score between [0-1], so not sure how to scale it.
I checked Kolmogorov-Smirnov Test, as well, but it can give me the difference between only a particular feature (column) of different size. I thought of measuring the distance for each column separately and summing it up, but haven't tried yet.
Comment: What does "similarity" mean to you in your situation?
Comment: Would anyone suggest using PCA for this purpose? Is there anything wrong with making PCA and use one of the methods mentioned above? @A.Ray
Comment: I want to know whether the datasets were generated by the same user or not
Comment: Would it be enough to see if the variables had similar means, etc?
Comment: There are lot of users, and each user has many features. I need a more robust way because I'll run an algorithm on the users whose data change at different sessions.
Comment: If these are time series data, and you believe same user will generate similar time series, you can use [cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation) as a measure of similarity
Comment: @A.Ray it measures the similarity between vectors, right? Is there a way to use it for matrices?
Comment: Yes it is generally done for vectors, but it is not difficult to extend it to a matrix. For two time series vectors $x,y$ normally we compute cross correlation something like $\sigma_{x,y}(T)=\frac{1}{\sqrt{\sigma_{xx}(0)\sigma_{yy}(0)}}\frac{1}{N-1}\sum (x_{t-T}-\mu_x)(y_t-\mu_y)$. For the matrix case since $x_t,y_t$ are vectors themselves, simply take their inner product. $\sigma_{x,y}(T)=\frac{1}{\sqrt{\sigma_{xx}(0)\sigma_{yy}(0)}}\frac{1}{N-1}\sum (x_{t-T}-\mu_x)^T(y_t-\mu_y)$.
Comment: Another approach maybe compute cross correlation for each row separately. In your case compute 5 cross-correlations for x,y,z,gyro,acc. Then you can compute a weighted sum to find a single cross-correlation. Optimize the weight from a training set.
Comment: Have you looked at mutual information, which is really good for nonlinear comparisons: https://en.wikipedia.org/wiki/Mutual_information
Comment: @theideasmith but mutual information is applicable only if joint PDF is given, so a problem of estimation of PDF arises.
Comment: Ok – so you estimate PDF, big deal. It gives a nice nonlinear correlation metric and is perfect for this kind of data (could also do Kullback Leibler divergence). Alternatively the OP can just throw away 500 datapoints and do a standard cross correlation, or maybe do a sliding window cross correlation. Cross correlation wouldn't account for translation invariance across datasets.
Answer: I think your problem is related to domain adaptation and the term "discrepancy" they use in the literature between two domains.
Check Ben David papers on discrepancy. There is a simplified measure defined as the classification error (or accuracy) of a classifier that discriminates samples of one dataset from the other.
Comment: Lets say you have datasets A and B. You build the new dataset X composed of both A and B with labels a if the data belongs to A and b if data belongs to B. Then you train a classifier on the new dataset that discriminates a from b. you measure abs(2*acc-1) where acc is the accuracy between 0 and 1. If the datasets are similar, you will get 0.5 accuracy for two class classification which is the minimum of the discrepancy defined above. otherwise it will return positive nonzero discrepancy.
Comment: Can you expand a bit your answer?


PHP Require Global Scope

Question: I am having an issue in php... I don't fully understand how the whole require() thing works.  My understanding is that it takes the current class's member variables and makes them global inside the required file.  If this is the case, then why does it not also take the base class's member variables and make them global?
baseclass.php:
class BaseClass {
 var $user;
}

myclass.php:
class MyClass extends BaseClass {
 function doSomething() {
  require "page.php"
 }
}

page.php:
$this->user // <- this is out of scope?

Answer: $this->user is  available. I just tested it.
require() works as if the required file were in the require command's place. Nothing more, nothing less.
In your example, the required file gets the function's scope.
var $varname is old style: In PHP 5, better use one of
public $varname
private $varname
protected $varname

to declare variables.
Comment: On second thought, I'm removing my "not perfect style" remark. Although one could argue that if your methods are so big you need to put them into external files, you have a design problem... But it's not pertinent to the question.
Comment: very interesting, I can do a print_r on the object(with success) outside of the require but if I do it inside I get nothing.
Comment: @DaveC a `print_r($this);` works fine for me from within the include. Can you show the exact code of your included file?
Comment: Your assistance helped me deduce a design flaw, thank you for your assistance.
Answer: I will assume that myclass.php has include of baseclass.php.
when you have include or require(difference is only the type of error they return), php includes and evaluates the specified file(page.php), with scopes of the method you including file from(doSomething();). Therefore I do not see why you would have out of scope issue.

PHP Require Global Scope


Email send action fails: Cron has been running for more than an hour and is most likely stuck

Question: I am maintaining a Drupal 6 installation. The task was to send an email to all registered users. I was using a rule set containing one rule with a default action: "send email to all users of a certain role". The rule set has been scheduled, was executed and deleted from the schedule (automatically like expected), but the task seemed to restart forever in the background: all (or probably a lot) users got the email every hour (6 times until I stoped cron). I use poormans-cron.
Please help with to answer this questions:

I suppose the mails could not be sent (~300 users) in the 60 minutes before the next cron (1h) decided that the job was still not complete and restarted it. Correct?
300 mails in 1 hour should not be a problem, but I saw somewhere, but cannot remind where, that one can set a wait time between sending mails. Is that correct? Please tell if you know where.
Can you think of something else than 1. for the reason? (I used out of the box drupal 6 functions).

The log shows:
error   cron    18/02/2012 - 12:04  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 11:08  Cron run exceeded the time limit and was aborted.
error   cron    18/02/2012 - 11:04  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 10:07  Cron run exceeded the time limit and was aborted.
error   cron    18/02/2012 - 10:03  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 09:07  Cron run exceeded the time limit and was aborted.
error   cron    18/02/2012 - 09:03  Cron has been running for more than an hour and is most likely stuck.
error   cron    18/02/2012 - 09:02  Cron has been running for more than an hour and is most likely stuck.
error   cron    18/02/2012 - 07:50  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 06:46  Cron run exceeded the time limit and was aborted.

Appendix 1, 19.2.2012
I use PHPMailer module to send the emails.
Answer: I think that your PHP configuration is not letting cron finish. Turn off poormanscron, then delete your cron entries in your MySQL database:
DELETE FROM `variable` WHERE name = 'cron_semaphore';
DELETE FROM `variable` WHERE name = 'cron_last';

Then go to admin/reports/status and click on your PHP version to see the output of phpinfo(). What is the max execution time? What is the memory limit? You'll want to change those values to higher numbers, then verify that they are indeed different on this page, then run cron manually at admin/reports/status.
To change these 2 values in PHP, create (or edit) php.ini in the webroot of your site and add (or modify):
max_execution_time = 300
memory_limit = 256M

Obviously feel free to try whatever numbers you'd like here. Ideally you don't want to leave the memory limit very high if you don't need to.
Comment: I ignored your questions about changing the number of emails sent per cron as I do not know how you can set that from within Rules in D6. Perhaps that is not possible.
Comment: Thankyou very much for your advice. The following values are currently outputed by phpinfo: `max_execution_time=600`, `memory_limit=128M`. I will try setting it to 3000 (50min) and 256M. I really hope that it does not load all mails into memory before sending it? ;-)
Comment: Report back about how it goes. Does PHPMailer module handle any kind of queuing, i.e. can you possibly set the number of emails sent per cron run?
Comment: No luck. :-( I deleted the DB entries, raised the execution time/memory limit values. Enabled PHPMailer loging. Now, I will try to find those logs, because there were no additional entries in the watchdog.
Comment: php_error.log is promising: `PHP Fatal error:  Maximum execution time of 600 seconds exceeded in \image.imagemagick.inc on line 162`
Comment: oh. my bad. The log entry is too old to be the reason.
Comment: I was gonna say, imagemagick?! Good luck spikey.
Answer: I found the problem and changed a file in drupal core:
includes/common.inc, line 2714:
function drupal_cron_run() {

  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240); // will return a fatal error, if the script runs more than 4min
  }
...

I changed the set_time_imit(240) line to:
    @set_time_limit(2400);

because sending all mails lasts about 14min.
Thanks anyone for your time.
Spikey
Comment: Alternately you can do this hack in cron.php so at least you can replace the file after an update.


Parse `key1=value1 key2=value2` in Kusto

Question: I'm running Cilium inside an Azure Kubernetes Cluster and want to parse the cilium log messages in the Azure Log Analytics. The log messages have a format like
key1=value1 key2=value2 key3="if the value contains spaces, it's wrapped in quotation marks"

For example:
level=info msg="Identity of endpoint changed" containerID=a4566a3e5f datapathPolicyRevision=0

I couldn't find a matching parse_xxx method in the docs (e.g. https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/parsecsvfunction ). Is there a possibility to write a custom function to parse this kind of log messages?
Answer: Not a fun format to parse... But this should work:
let LogLine = "level=info msg=\"Identity of endpoint changed\" containerID=a4566a3e5f datapathPolicyRevision=0";
print LogLine
| extend KeyValuePairs = array_concat(
    extract_all("([a-zA-Z_]+)=([a-zA-Z0-9_]+)", LogLine),
    extract_all("([a-zA-Z_]+)=\"([a-zA-Z0-9_ ]+)\"", LogLine))
| mv-apply KeyValuePairs on
(
    extend p = pack(tostring(KeyValuePairs[0]), tostring(KeyValuePairs[1]))
    | summarize dict=make_bag(p)
)

The output will be:
| print_0            | dict                                    |
|--------------------|-----------------------------------------|
| level=info msg=... | {                                       |
|                    |   "level": "info",                      |
|                    |   "containerID": "a4566a3e5f",          |
|                    |   "datapathPolicyRevision": "0",        |
|                    |   "msg": "Identity of endpoint changed" |
|                    | }                                       |
|--------------------|-----------------------------------------|

Comment: Great, that helped a lot to get started. I had to change the regexes a bit further, because the real logs contained some quirks that were not present in the example. I'll add another answer with the query I ended up with.
Answer: With the help of Slavik N, I came with a query that works for me:
let containerIds = KubePodInventory
| where Namespace startswith "cilium"
| distinct ContainerID
| summarize make_set(ContainerID);
ContainerLog
| where ContainerID in (containerIds)
| extend KeyValuePairs = array_concat(
    extract_all("([a-zA-Z0-9_-]+)=([^ \"]+)", LogEntry),
    extract_all("([a-zA-Z0-9_]+)=\"([^\"]+)\"", LogEntry))
| mv-apply KeyValuePairs on
(
    extend p = pack(tostring(KeyValuePairs[0]), tostring(KeyValuePairs[1]))
    | summarize JSONKeyValuePairs=parse_json(make_bag(p))
)
| project TimeGenerated, Level=JSONKeyValuePairs.level, Message=JSONKeyValuePairs.msg, PodName=JSONKeyValuePairs.k8sPodName, Reason=JSONKeyValuePairs.reason, Controller=JSONKeyValuePairs.controller, ContainerID=JSONKeyValuePairs.containerID, Labels=JSONKeyValuePairs.labels, Raw=LogEntry