How to test if a NavigationView menu item is disabled or enabled with Espresso?

Question: I have a NavigationView with a menu where some menu items should be disabled when a user is not logged in:
private void setupNavigationViewMenu(boolean isUserLoggedIn) {
    Menu menu = mNavigationView.getMenu();
    menu.findItem(R.id.item_charge_cards).setEnabled(isUserLoggedIn);
    menu.findItem(R.id.item_charge_sessions).setEnabled(isUserLoggedIn);
    menu.findItem(R.id.item_invoices).setEnabled(isUserLoggedIn);
}

I want to create an Espresso test, which will assert that the menu items are really disabled.
I have written the following test, but it's failing:
@Test
public void navigationMenuItems_AreDisabled() {
    openNavigationDrawer();
    onView(getNavigationItemWithString(R.string.navigation_view_item_charging_cards))
            .check(matches(not(isEnabled())));
    onView(getNavigationItemWithString(R.string.navigation_view_item_charging_sessions))
            .check(matches(not(isEnabled())));
    onView(getNavigationItemWithString(R.string.navigation_view_item_invoices))
            .check(matches(not(isEnabled())));
}

public static Matcher<View> getNavigationItemWithString(String string) {
    return allOf(isAssignableFrom(AppCompatCheckedTextView.class), withText(string));
}

The stacktrace:
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'not is enabled' doesn't match the selected view.
Expected: not is enabled
Got: "AppCompatCheckedTextView{id=2131624121, res-name=design_menu_item_text, visibility=VISIBLE, width=651, height=126, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=0.0, text=Laadpassen, input-type=0, ime-target=false, has-links=false, is-checked=false}"
...

Do you have any suggestions how to write the correct test?
Answer: A NavigationView menu item is not a single view, but a ViewGroup, so the enabled status is applied to NavigationMenuItemView, not AppCompatCheckedTextView. In order to fix your test, you must use the following Matcher to find the correct layout in the view hierarchy:
public static Matcher<View> getNavigationItemWithString(String string) {
    Matcher<View> childMatcher = allOf(isAssignableFrom(AppCompatCheckedTextView.class), withText(string));
    return allOf(isAssignableFrom(NavigationMenuItemView.class), withChild(childMatcher));
}


Can we use perceptron training algorithm to train a single neuron with sigmoid activation?

Question: The perceptron training algorithm is summarized as:

Apply the inputs and calculate the output $ y $
Compare with the desired output yd and calculate error $e = y-y_d$
Update the weights based on the error: $w_t = w_{t-1} + \eta ex$

I studied this for perceptron with step activation and found many examples of the training process for that like AND gate and OR gate.
The question now is: can we use this to train a single neuron with sigmoid activation? Or we must use the gradient descent.
I searched many times and found no answer to this.
I think that the samples that should be classified as one of the two classes (output = 0 or 1) will be trained successfully. However, I'm not sure about the samples that lie between the two classes (0 < output < 1). I am not sure about this and I have no proof.
Answer: Assume you use a sigmoid neuron with binary cross entropy loss:
$$H(y)=y_d\log y+(1-y_d)\log(1-y)$$
where $y=\sigma(w^Tx)$. The gradient wrt $w$ would be:
$$\begin{align}\frac{\partial H}{\partial w}&=\frac{\partial H}{\partial y}\frac{\partial y}{\partial w}=\left(\frac{y_d}{y}-\frac{1-y_d}{1-y}\right)y(1-y)x\\&=(y_d(1-y)-(1-y_d)y)x\\&=(y_d-y)x\end{align}$$
When we substitute into the gradient descent rule, we have the following update equation:
$$w_t=w_{t-1}-\eta {\partial H \over {\partial w}}=w_{t-1}+\eta(y-y_d)x$$
which is the update rule you have for the Perceptron algorithm. In other words, if you use the Perceptron algorithm together with sigmoid activation, instead of heaviside step, you end up using gradient descent algorithm on binary cross-entropy loss function.


Interpreting significance of predictor vs significance of predictor coeffs in multinomial logistic regression

Question: I have a multinomial logistic regression with dependent variable valued in {-1,0,1} (reference category is 0) and a number of continuous and discrete predictors. After running the regression a continuous predictor of interest ('size') has a Type 3 analysis of effects p-value of 0.0683, and the two coefficients (corresponding to outcomes of -1 and 1) have p-values of 0.8786 and 0.0220 respectively.
I read somewhere that one should only look at the significance of the coefficients if the predictor itself is significant at the chosen level. Is this right? My naive sense is that the predictor is borderline (taking alpha=0.05 for argument's sake), and that 'size' has a significant relationship to outcome=1 but not to outcome = -1. I would say that the significance of the relationship to outcome=1 is not terribly strong, but that is ok for the application in mind (or at least, with the indirect data I am forced to use)
Comment: You might more detail about what your goals are.  In general, like @rolando2 I encourage emphasizing predictions and confidence intervals rather than hypothesis tests.
Answer: The p-value itself cannot tell you how strong the relationship is, because the p-value is so influenced by sample size, among other things.  But assuming your N is something on the order of 100-150, I'd say there's a reasonably strong effect involving Size whereby as Size increases, the log of the odds of Y being 1 is notably different from the log of the odds of Y being 0.  As you indicate, the same cannot be said of the comparison of Y values of -1 and 0.
You are right in viewing all of this as somewhat invalidated by the overall nonsignificance of Size (depending on your alpha, or criterion for significance).  You wouldn't get too many arguments if you simply declared Size a nonfactor due to its high p-value.  But then again, if your N is sufficiently small--perhaps below 80 or 100--then your design affords low power for detecting effects, and you might make a case for taking seriously the specific effect that managed to show up anyway.
A way around the problem of relying on p-values involves two steps.  First, decide what range of odds ratios would constitute an effect worth bothering with, or worth calling substantial.  (The trick there is in being facile enough with odds to recognize what they mean for the more intuitive metric of probability.)  Then construct a confidence interval for the odds ratio associated with each coefficient and consider it in light of your hypothetical  range.  Regardless of statistical significance, does the effect have practical significance?
Comment: @rolando2 - p-values are not "useless", but its more that this uncritical use of 5% as some sort of global cut-off is what is wrong.  If used properly (i.e. based on sufficient statistics, varying the significance level with the sample size and with the relative costs of false rejection and false acceptance) p-values are quite an efficient way to communicate your results.
Comment: In that last paragraph aren't you effectively arguing against any use of p-values?  Why, then, use a hypothesis test at all?  Why not just estimate the effect sizes and be done with it?
Comment: I stop short of calling *p*-values completely useless.  I do advocate for the use of other methods, esp. when I hear people struggling with hypothesis testing and when they seem to have been taught such testing in the flawed way that I and many of us seem to have been taught.  I've commented on this elsewhere on the site so I won't repeat too much of my views here.


complex numbers inequality

Question: Let $z\in \mathbb{C}$ such that |z|=1. Prove that $|1+z|+|1+z^2|+|1+z^3|\geq2$
I have tried using the triangle inequality by grouping the first and last module after expending $|1+z^3|$ and then grouping it all with $|1+z^2|$. I arrived at $$|z^3+z^2+z+1+2|=\left|\frac{1-z^4}{1-z}+2\right|$$
How do I prove that this is greater or equal than 2?
Answer: Hint: We have
$$2=(1+z^3)+(1+z^2)-z^2(1+z)$$
Comment: No; simply use  the fact that if $a,b,c$ are complex numbers we have $|a+b+c|\leq |a|+|b|+|c|$
Comment: Put $a=1+z^3$, $b=1+z^2$, $c=-z^2(1+z)$, and apply the inequality above.

complex numbers inequality


Synthetic basis and analytic basis

Question: Definition of "Synthetic Basis":
Let $X$ be a set!
Let $\mathscr{B}$ be a subset of $P({X})$ satisfying below two conditions:
(i) $X\subset \bigcup \mathscr{B}$
(ii) $\forall A,B\in \mathscr{B}, \exists \mathscr{A}\subset \mathscr{B}, \bigcup \mathscr{A}=A\cap B$
========
Question1:
Let $X$ be a set and $\mathscr{B}_1$ and $\mathscr{B}_2$ be distinct synthetic bases for $X$.
I have proven that $\tau_i\triangleq \{\bigcup \mathscr{A} \subset X|\mathscr{A} \subset\mathscr{B}_i\}$ are topologies on $X$.
I believe $\tau_1$ and $\tau_2$ are not necessarily the same, but i'm not sure. Is there any simple example?
Question 2:
Munkres, Topology p.80 : Let $X$ be a set and $\mathscr{B}$ be a basis for a topology $\tau$ on $X$. Then $\tau$ equals the collection of all unions of elements of $\mathscr{B}$.

I don't get this statement. If the author meant "analytic basis", then it's just the definition, that is, it should not be a theorem. So i guess he meant
"Synthetic basis". However, if he really meant that is this theorem true? How?
Answer: Here are two examples of synthetic bases on $\mathbb{R}$ which generate different topologies:

$\mathscr{B}_1 = \{ ( a , b ) : a < b \in \mathbb{R} \}$.
$\mathscr{B}_2 = \{ [ a , b ) : a < b \in \mathbb{R} \}$.
$\mathscr{B}_3 = \{ \{ a \} : a \in \mathbb{R} \}$.

The topology generated by $\mathscr{B}_1$ is the usual (Euclidean metric) topology on $\mathbb{R}$.  The topology generated by $\mathscr{B}_2$ is the Sorgenfrey topology (or lower-limit topology).  The topology generated by $\mathscr{B}_3$ is the discrete topology on $\mathbb{R}$.
There are simpler examples (since any topology is also a base for itself, and so any two distinct topologies on the same set will be bases for different topologies).

Munkres seems to define the topology generated by a base $\mathscr{B}$ slightly differently, opting instead to define it to be $$\tau = \{ U \subseteq X : ( \forall x \in U ) ( \exists B \in \mathscr{B} ) ( x \in B \subseteq U ) \}.$$  This is easily seen to be equivalent to the definition you have given, and the Theorem you mention is essentially just a formal statement of this fact.

Synthetic basis and analytic basis


Iniciação com Arduino

Question: Tenho conhecimentos em programação web e mobile.
Tenho interesse enorme em aprender Arduino e integrar minhas criações na placa à sistemas web e mobile.
A minha dúvida é:
Vale a pena mexer com Arduino?
E se, por exemplo, no Arduino eu criar algo associado à minha residência (luzes, temperatura...), o Arduino que comprei vai ser usado para somente isso?
Se eu quiser fazer outro projeto (novo), para outra finalidade, preciso de outro Arduino?
Answer: Primeiro ponto: Não precisa de outro Arduino pra carregar outro código na placa, basta plugar ele na máquina e, no software que pode ser baixado gratuitamente na web, clicar no botãozinho de -> para enviar o código para a placa

Segundo ponto: Sim vale a pena para quem está começando a aprender uma linguagem de baixo nível(aquela linguagem que conversa diretamente com o hardware, sem necessitar de um so para interpretar os comandos)
Mesmo para pegar alguns conceitos de elétrica(componentes) e mecânica e etc, abre as portas pra quem está com vontade de partir para sistemas embarcados.
Comment: qual a diferença de arduino e rasperypi?
Comment: @RafaelAcioly nunca tinha ouvido falar, mas pelo que procurei me informar, aparentemente se trata de um mini-computador(uma plaquinha de menores proporcoes, e logicamente com um poder de processamento menor, com tudo que e necessario onboard) integrado com um microcontrolador, com isso facilita em muito a vida de alguns desenvolvedores que "gostam" da interface habitual de SO's pra trabalhar com um microcontrolador integrado

Iniciação com Arduino


Weight a rating system to favor items rated highly by more people over items rated highly by fewer people?

Question: Thanks in advance for bearing with me, I am not a statistician of any kind and don't know how to describe what I'm imagining, so Google isn't helping me here...
I'm including a rating system in a web application I'm working on. Each user can rate each item exactly once.
I was imagining a scale with 4 values: "strongly dislike", "dislike", "like", and "strongly like", and I had planned on assigning these values of -5, -2, +2, and +5 respectively.
Now, if every item was going to have the same number of ratings, then I would be quite comfortable with this scoring system as clearly differentiating the most liked and least liked items. However, the items will not have the same number of ratings, and the disparity between the number of votes on different photos may be quite dramatic.
In that case, comparing the cumulative scores on two items means that an old item with a lot of mediocre ratings is going to have a much higher score than an exceptional new item with many fewer votes.
So, the first obvious thing I thought of us to take an average... but now if an item has only one rating of "+5" it has a better average than an item that has a score of 99 "+5" ratings and 1 "+2" rating. Intuitively that isn't an accurate representation of the popularity of an item.
I imagine this problem is common and you guys don't need me to belabor it with more examples, so I'll stop at this point and elaborate in comments if needed.
My questions are:

What is this kind of problem called, and is there a term for the techniques used to solve it? I'd like to know this so I can read up on it.
If you happen to know of any lay-friendly resources on the subject, I'd very much appreciate a link.
Finally, I'd appreciate any other suggestions about how to effectively collect and analyze this kind of data.
Answer: One way you can combat this is to use proportions in each category, which does not require you to put numbers in for each category (you can leave it as 80% rated as "strongly likes").  However proportions do suffer from the small number of ratings issue.  This shows up in your example the Photo with 1 +5 rating would get a higher average score (and proportion) than one with the 99 +5 and 1 +2 rating.  This doesn't fit well with my intuition (and I suspect most peoples).
One way to get around this small sample size issue is to use a Bayesian technique known as "Laplace's rule of succession" (searching this term may be useful).  It simply involves adding 1 "observation" to each category before calculating the probabilities.  If you wanted to take an average for a numerical value, I would suggest a weighted average where the weights are the probabilities calculated by the rule of succession.
For the mathematical form, let $n_{sd},n_{d},n_{l},n_{sl}$ denote the number of responses of "strongly dislike", "dislike", "like", and "strongly like" respectively (in the two examples, $n_{sl}=1,n_{sd}=n_{d}=n{l}=0$ and $n_{sl}=99,n_{l}=1,n_{sd}=n_{d}=0$).  You then calculate the probability (or weight) for strongly like as
$$Pr(\text{"Strongly Like"}) = \frac{n_{sl}+1}{n_{sd}+n_{d}+n_{l}+n_{sl}+4}$$
For the two examples you give, they give probabilities of "strongly like" as
$\frac{1+1}{1+0+0+0+4}=\frac{2}{5}$ and $\frac{99+1}{99+1+0+0+4}=\frac{100}{104}$  which I think agree more closely with "common sense".  Removing the added constants give $\frac{1}{1}$ and $\frac{99}{100}$ which makes the first outcome seem higher than it should be (at least to me anyway).
The respective scores are just given by the weighted average, which I have written below as:
$$Score=\begin{array}{1 1} 5\frac{n_{sl}+1}{n_{sd}+n_{d}+n_{l}+n_{sl}+4}+2\frac{n_{l}+1}{n_{sd}+n_{d}+n_{l}+n_{sl}+4} \\ - 2\frac{n_{d}+1}{n_{sd}+n_{d}+n_{l}+n_{sl}+4}
-5\frac{n_{sd}+1}{n_{sd}+n_{d}+n_{l}+n_{sl}+4}\end{array}$$
Or more succinctly as
$$Score=\frac{5 n_{sl}+ 2 n_{l} - 2 n_{d} - 5 n_{sd}}{n_{sd}+n_{d}+n_{l}+n_{sl}+4}$$
Which gives scores in the two examples of $\frac{5}{5}=1$ and $\frac{497}{104}\sim 4.8$.  I think this shows an appropriate difference between the two cases.
This may have been a bit "mathsy" so let me know if you need more explanation.
Comment: Very nice non-technical answer, and an approach I wouldn't have thought of myself. I'd only add that it's possible to add any number of fake 'observations' to each category instead of 1, including non-integer numbers. This gives you flexibility to decide how much you want to 'shrink' towards zero the scores of items with few votes. And if you happen to want an technical-sounding description of this method, you could say you're performing a Bayesian analysis of data from a multinomial distribution using a symmetric Dirichlet prior.
Comment: While they may seem like "fake" observations, they do have a well defined meaning when it is +1 (as opposed to +2 or higher, which really are "fake" numbers, or numbers from a previous data collection).  It basically describes a state of knowledge that it is *possible* for each category to be voted for, *prior* to observing any data.  This is precisely what the flat prior on the (N-1) simplex does.
Comment: One more observation, for future people who find this post: In implementing this in my model I took the final score and multiplied it by 20, which gives a range of -100 to 100 from worst to best possible score (though I suppose technically those are limits you can't ever quite reach, but you get the idea). This makes the output for users in my app very intuitive!
Comment: That was a bit "mathsy" for me, and initially I didn't understand the formula, but I read it carefully about three times and it clicked! This is *exactly* what I was looking for, and your explanation was very clear, even for someone who isn't a mathematician or statistician at all. Thank you very much!
Comment: @probabilityislogic: surely any strictly positive parameters for the Dirichlet prior describe that all the probabilities are strictly between 0 and 1? And this argument suggests setting them to 2/m, where m is the number of categories, rather than 1: http://en.wikipedia.org/wiki/Rule_of_succession#Generalization_to_any_number_of_possibilities
Comment: @onestop - I would argue against the wiki page that you describe is only considering the case when 1 of 2 possible outcomes can happen.  So *if* we were indifferent between "strongly like" and everything else (the other three categories *combined*), then we are *not* indifferent between "strongly like" and "like".  But the question as posed clearly give *four* categories, not two, and from the information in the question there is no *a priori* reason to favour any one rating.  I'll have another think about it, because the issue may be more subtle (e.g. why not use the reference prior?).
Comment: Okay, I've had a bit of a think and basically using the $Dir(k,\dots,k)$ prior to give posterior of $Dir(k+n_1,\dots,k+n_m)$.  The [wiki page][1] [1]:http://en.wikipedia.org/wiki/Dirichlet_distribution#Aggregation shows that collapsing categories, you just add the parameters. This means that collapsing to 2 categories gives you a Beta posterior. so the denominator will be the sum of all dirichlet parameters $n_1+\dots+n_m+mk = n+mk$ and the numerator will be the sum of all the categories labelled "success" which will be of the form $s+ck$ where c=number of categories for "success".
Comment: ... continuing, this means the probability of success is given by $\frac{s+ck}{n+mk}$.  So setting $k=\frac{2}{m}$ gives $\frac{s+\frac{2c}{m}}{n+2}$.  Now if m is "evenly divided" as the wiki page says, then 2c=m and we are left with the original rule of succession.  So what does this mean for the uniform prior (k=1)?  To me, it means that *mere knowledge of the existence of more than two possible categories (that we consider them possible is essential to this argument) represents important information about an equal aggregation of them*.  more later
Comment: ...continuing again... So what state of knowledge does the constant $\frac{2}{m}$ represent?  Here's what I think.  It represents that we are only know that one category in the "success" labeled group, and one category in the "failure" group are *possible*, the remaining $m-2$ categories *we are not even sure that these categories are possible and will only consider them possible after observing them*.  This easily generalizes to a new constant $\frac{q}{m}$ where there are $q$ categories *possible* and $m-q$ categories where we are not sure of even the possibility that they exist.
Comment: ...continuing again (apologies for the lengthy "comment")... Note that changing from $2$ to $q$ changes the probability to $\frac{s+\frac{q}{m}}{n+q}$.  One thing I have wondered with this argument, is do we need to specify which categories within "success" are they ones we are willing to assume are *possible a priori*?  Or can we just say "one of them, but not sure which" and then spread this out "evenly" over the aggregated categories?  If we can, then this gives an interpretation of the Jeffreys prior as assuming that we consider *only one outcome possible, but not sure which one* or $q=1$.
Comment: Apologies, I made a small error in the above comment, the probability should be $\frac{s+\frac{cq}{m}}{n+q}$ instead of $\frac{s+\frac{q}{m}}{n+q}$.
Comment: @probabilityislogic: Trés, trés informatif! What if providing _any_ rating is considered "success"? I presume the same logic holds, no? Also, do You have any insight on how to perform such a calculation if, instead of "like" and "dislike" and etc., the rating is any numerical value on a scale from, say, 0-9, including fractions? Does some sort of integral apply?
Answer: I'd take a graphical approach.  The x-axis could be average rating and the y could be number of ratings.  I used to do this with sports statistics to compare the contribution of young phenoms with that of veteran stars.  The nearer a point is to the upper right corner, the closer to the ideal.  Of course, deciding on the "best" item would still be a subjective decision, but this would provide some structure.
If you want to plot average rating against another variable, then you could set up number of ratings as the third variable using bubble size, in a bubble plot--e.g., in XL or SAS.


Qual a diferença entre NULL e null?

Question: Existe alguma diferença entre o NULL (escrito em maiúsculo) e null (escrito em minúsculo) no PHP?
Eu sei que consigo usar os dois tipos, mas existe alguma regra de nomenclatura dessas palavras?
Answer: Em linhas gerais, não existem diferenças. O NULL é case insensitive - não sensível a maiúsculas e minúsculas. Na própria documentação é dito isso:

Existe apenas um valor de tipo nulo, e essa é a constante case insensitive NULL.

O mesmo vale para o TRUE e FALSE. Como dito também na documentação, ambos são case insensitive:

Para especificar um booleano literal, utilize as constantes TRUE ou FALSE. Ambas são case insensitive.

Então você pode usar qual é mais conveniente, ou a que você tem mais familiaridade.

As PSR's comentam sobre isso. Apesar de serem apenas um guia de estilo e não regras para serem impostas, elas recomendam que:

As palavras chave do PHP devem estar em minúsculas. As constantes do PHP true, false e null devem estar escritas em minúsculas.

Também temos uma pergunta respondida sobre isso no nosso Grande Irmão SO.

Qual a diferença entre NULL e null?


Cron Run and Cache

Question: I'm running Drupal 7.25 on my Ubuntu server. I have a process that is kicked off by user interaction (form) that needs to run in the background. I currently have cron.php being run every minute via crontab. I read this article:
http://www.metaltoad.com/blog/how-drupals-cron-killing-you-your-sleep-simple-cache-warmer
Does running cron.php still clear cache in D7?
Comment: A lot of modules use "lightweight cron" which only do specified lightweight tasks if you have something that needs to be checked every minute. Check out the Scheduler module.
Answer: If you take a look at system_cron(), you will see
$cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
foreach ($cache_tables as $table) {
  cache_clear_all(NULL, $table);
}

Reading the docs for cache_clear_all($cid, $bin):

$cid: If set, the cache ID or an array of cache IDs. Otherwise, all cache entries that can expire are deleted. The $wildcard argument
  will be ignored if set to NULL.

This means that a full cache clear won't be done, but entries that are older than their TTL are removed from the cache.
However, {cache_page} uses CACHE_TEMPORARY for the TTL (see drupal_page_set_cache(), so these will be removed each cron run.  Though the code support it, I have never seen anything other that a -1 in the exipres column in {cache_page}, no matter what the TTLs on the performance settings are.
Comment: Everyone interested should read the comments at http://www.metaltoad.com/blog/how-drupals-cron-killing-you-your-sleep-simple-cache-warmer, search for the comment "This is incorrect. This call" by Moshe Weitzman.
Comment: This answered my question as to why my cache wasnt expiring even with low values, without running cron....
Answer: Yes, running cron.php still clear cache, as running the cron will call system_cron which calls "cache_clear_all" method:
$cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
foreach ($cache_tables as $table) {
  cache_clear_all(NULL, $table);
}

Comment: Thanks! Now I can set back my crontab so I'm not killing my site every minute ;)

Cron Run and Cache


A good Open Source book on Analytic Geometry?

Question: Hi my course specifically talks about :
Cartesian and Polar Coordinates in 3 Dim, second Degree eqns in 3 vars, reduction to canonical forms, straight lines, shortest distance between 2 skew lines, Plane, sphere, cone, cylinder, paraboloid, ellipsoid,hyperboloid of one and two sheets and their properties.
This is merely indicative, and I would really like if the book talks about these (atleast) and some more. Would appreciate if it contained solved examples and exercise problems as well
Help Much Appreciated,
Soham
Comment: "Open" means free on-line?
Comment: yes indeed... thats what I meant
Comment: In that case, find a textbook whose copyright has expired.  Probably Google Books has it on-line!  Plus: topics like the ones you mention were more commonly seen 50 years ago than nowadays anyway.
Comment: @GEdgar Can you give me names of a few books to get started, copyright or no copyright. I will try to get hold of it from the used book stalls nearby at a cheap price
Answer: There are a huge number of older classics freely available on the internet, such as (google "last name" and "title" together to find them):
Maxime Bocher, Plane Analytic Geometry (1915)
Maria M. Roberts and Julia T. Colpitts, Analytic Geometry (1918)
William F. Osgood and William C. Graustein, Plane and Solid Analytic Geometry (1922)
Lewis Parker Siceloff, George Wentworth, and David Eugene Smith, Analytic Geometry (1922)
The following School Mathematics Study Group texts from the 1960's may also be of use:
Analytic Geometry, Student Text, Part 1. Revised Edition
Analytic Geometry, Student Text, Part 3. Revised Edition
Since you seem especially interested in 3-dimensional analytic geometry, you'll also want to google (in google-books) for books with "solid analytic geometry" in their titles.
(added next day) This morning I looked through the books I have at home and came up with the following additional suggestions (definitely not all the relevant books that I have, as I have a large number of old math books):
N. J. Lennes and A. S. Merrill, Plane Analytic Geometry (1929)
Virgil Snyder and C. H. Sisam, Analytic Geometry of Space (1914)
V. A. Ilyin and E. G. Poznyak, Analytic Geometry (1984, MIR Publishers)
Joseph H. Kindle, Schaum's Outline of Theory and Problems of Plane and Solid Analytic Geometry (1950)
John M. H. Olmsted, Prelude to Calculus and Linear Algebra (1968)
William H. McCrea, Analytical Geometry of Three Dimensions (1960; Dover edition 2006)
Barry Spain, Analytical Conics (1957; Dover edition 2007)
Of all the books I've listed, my guess is that Kindle's book and Olmsted's book would be best for you. These two books should fit together well for self-study, since Kindle is more old-fashioned in style (with a huge number of problems) and Olmsted is more modern in style (with fewer problems, but much more careful text writing). ["Modern" means heavy use of set notation, functions as certain sets of ordered pairs, etc.]
Answer: I found a good book buy George Simmons- A treatise on the analytical geometry to be helpful.
Comment: author is George Salmon


Ruby grep with line number

Question: What could be the best way of getting the matching lines with the line numbers using Ruby's Enumerable#grep method. (as we use -n or --line-number switch with grep command).
Comment: I'd be interested in knowing your use case for this.
Comment: I'm curious why `\`grep -n target file_to_search\`` isn't good enough. It'll be extremely fast and supports all of grep's features.
Comment: @the Tin Man: Yeah that's true, but I'd like to have a ruby solution for platform independence.
Comment: @Phrogz: My use case is i am picking a particular pattern from erb files.
Answer: Enumerable#grep doesn't let you do that, at least by default. Instead, I came up with:
text = 'now is the time
for all good men
to come to the aid
of their country'

regex = /aid/

hits = text.lines.with_index(1).inject([]) { |m,i| m < [["to come to the aid\n", 3]]

Comment: +1 as I found this answer is closest to the one I was looking for. I had to change it a bit to make it 1.8.7 compatible. Later I found it'd be great, for my requirement, if the result comes as a hash, having line numbers as keys and lines as values. I'm putting that as an answer for the record.
Comment: It helps us a lot if you know what you want before writing the question, and ask for that. Your end result would have been trivial to add and then would have been exactly what you were looking for. And, actually, my answer would have been better.
Comment: Couldn't agree more the Tin Man. But you know, sometime you refine your idea after walking a good amount of steps towards the solution :)
Answer: maybe something like this:
module Enumerable
  def lgrep(pattern)
    map.with_index.select{|e,| e =~ pattern}
  end
end

Comment: It throws away the second arguments (it's not needed). If I had omitted it, e would have turned into an array of both args.
Comment: I'm just curious about this `|e,|` notation you're using. What exactly does this mean?
Answer: This isn't elegant or efficient, but why not just number the lines before grepping?
Comment: +1 This is a perfectly good, common-sense answer. Don't do it again. :-)
Answer: You can kludge it in Ruby 1.8.6 like so:
require 'enumerator'
class Array
  def grep_with_index(regex)
    self.enum_for(:each_with_index).select {|x,i| x =~ regex}
  end
end
arr = ['Foo', 'Bar', 'Gah']
arr.grep_with_index(/o/) # => [[0, 'Foo']]
arr.grep_with_index(/a/) # => [[1, 'Bar'], [2, 'Gah']]

Or if you're looking for tips on writing a grep-like utility in Ruby.  Something like this should work:
def greplines(filename, regex)
  lineno = 0
  File.open(filename) do |file|
    file.each_line do |line|
      puts "#{lineno += 1}: #{line}" if line =~ regex
    end
  end
end

Answer: >> lines=["one", "two", "tests"]
=> ["one", "two", "tests"]
>> lines.grep(/test/){|x| puts "#{lines.index(x)+1}, #{x}" }
3, tests

Answer: To mash up the Tin Man's and ghostdog74's answers
text = 'now is the time
for all good men
to come to the aid
of their country'

regex = /aid/

text.lines.grep(/aid/){|x| puts "#{text.lines.find_index(x)+1}, #{x}" }
# => 3, to come to the aid

Answer: A modification to the solution given by the Tin Man. This snippet will return a hash having line numbers as keys, and matching lines as values. This one also works in ruby 1.8.7.
text = 'now is the time
for all good men
to come to the aid
of their country'

regex = /aid/

hits = text.lines.each_with_index.inject({}) { |m, i| m.merge!({(i[1]+1) => i[0].chomp}) if (i[0][regex]); m}

hits #=> {3=>"to come to the aid"}

Answer: Put text in a file
test.log
 now is the time
 for all good men
 to come to the aid
 of their country

Command line (alternative of grep or awk command )
ruby -ne ' puts $_  if $_=~/to the/' test.log

Try this also
ruby -na -e ' puts $F[2] if $_=~/the/' test.log

Similarly
ruby -na -e ' puts $_.split[2] if $_=~/the/' test.log

This is similar to awk command.
Answer: Another suggestion:
lines.find_index{ |l| l=~ regex }.
Comment: This is more elegant than any of the other solutions. Wish I could upvote. Stack Overflow needs to be more dynamic and adaptable to changing times/paradigms.

Ruby grep with line number


Is it possible to synchronize publish status between translations?

Question: Having 'Enable Translation' checked for a content type, is it possible to synchronize the publish status between all the translations in Drupal 8?
Comment: I think you mean you don't want to translate the publish status field?
Comment: Yes exactly, if one translation is disabled, I need the rest to be disabled too.
Comment: So you mean how to make the "Published" field not translatable, so it's the same for all translations?
Comment: Yes, that's what I mean
Answer: You can't control the translation configuration of base fields such as the publish status field from the content type configuraton, so go to

Administration >> Configuration >> Regional and language >> Content
  language

and uncheck the publish status field for your content type:

[ - ]  Published

Now the publish option will be available only in the original language of the node and is then applied to all translations.
Comment: Great, that's what I needed and I couldn't find where to set it up. Thanks a lot @4k4


Laravel: How to change return value of controllermethod in vendor/laravel/jetstream without editing vendor files

Question: I want to edit what a controllermethod returns, but don't want to edit the vendor file directly because it can undo my changes obviously. I'm not sure how to make these edits happen though:
I want to change this file:
vendor/laravel/jetstream/src/Http/Controllers/Inertia/UserProfileController.php
From this:
public function show(Request $request)
{
    $this->validateTwoFactorAuthenticationState($request);

    return Jetstream::inertia()->render($request, 'Profile/Show', [
        'confirmsTwoFactorAuthentication' => Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm'),
        'sessions' => $this->sessions($request)->all(),
    ]);
}

To this:
public function show(Request $request)
{
    $this->validateTwoFactorAuthenticationState($request);

    return Jetstream::inertia()->render($request, 'Profile/Show', [
        'confirmsTwoFactorAuthentication' => Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm'),
        'sessions' => $this->sessions($request)->all(),
        'video' => $request->user()->video <-- added this line
    ]);
}

Comment: Wasn't Jetstream publishing their controllers? But ok, let's say they're not. 1) Create your own controller. 2) `extend` that `ProfileController` from Jetstream. 3) put your own `show` function inside your own controller. By extending their controller and using the `show` function, you're overriding their show function
Answer: create a new controller that extends the one you need to override.
then use your controller instead
<?php

namespace App\myController\Path;

use namespace\of\original\controller;

class CustomUserProfileController extends UserProfileController
{
    public function show(Request $request)
    {
        $this->validateTwoFactorAuthenticationState($request);

        return Jetstream::inertia()->render($request, 'Profile/Show', [
            'confirmsTwoFactorAuthentication' => Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm'),
            'sessions' => $this->sessions($request)->all(),
            'video' => $request->user()->video <-- added this line
        ]);
    }
}

now you can use your own controller in any place you want


Decreasing trend in residual vs fitted value plot

Question: Here is my residual vs fitted value plot. It shows a decreasing trend. Can someone explain to me what could cause this to happen and how do I correct my model to produce a better fit? I am fitting something like lm(y~x1+x2)
Comment: Is there correlation present in the residuals? Check `acf(mod$residuals)`.
Answer: A hidden binary variable can explain this.
Your model is
$$y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \varepsilon$$
and it assumes that the error terms $\varepsilon$ average zero and do not seem to be associated with either $x_1$ or $x_2.$ This plot indicates this assumption is not true: the $\varepsilon$ values appear to decrease as $y$ increases and they jump around, apparently at random, by an amount around $6$ for the values of $y$ greater than $30$ or so.
If we re-express the errors $\varepsilon$ as the sum of another variable $z$ and whatever else is left, and suppose that $z=6$ for about half of the observations where $y$ exceeds $30$ and $z=0$ otherwise, and assume we can observe $z,$ then the new model is
$$y = \alpha_0 + \alpha_1 x_1 + \alpha_2 x_2 + \alpha_3 z + \delta.$$
Fitting it would (a) account for the strip of points high in the upper left of the plot and (b) allow the coefficients $\alpha_0, \alpha_1,$ and $\alpha_2$ to accommodate the consistent linear downward trend evident in the plot.
As a demonstration, here is code that generates random values according to the second model but fits them according to the first model and the second model.  The code displays a column of residual-vs-fitted plots (one for each model), repeating this three more times to give us a sense of what is random and what is baked into the data generation process.  Qualitatively they do an excellent job of reproducing your plot: the only noticeable aspect not included in this simulation is the presence of three outlying values in your plot (one near (33,1) and other two labeled "1074066" and "512803").

Here is the code showing explicitly what is going on.
n <- 150    # Size of dataset
alpha <- 4  # Shape of x1 distribution
mu <- 20    # Mean of x1 distribution

set.seed(17)
par(mfcol=c(2,4))
replicate(4, {
  x1 <- rgamma(n, alpha, alpha / mu)  # Generate the x1 values
  x2 <- rexp(n)                       # Generate smaller x2 values
  y0 <- x1 + x2
  z <- ifelse(y0 > 30 & runif(n) <= 0.5, 6, 0)
  y <- y0 + z + runif(n)              # Generate the response with uniform error

  fit.1 <- lm(y ~ x1 + x2)
  # summary(fit.1)
  fit.2 <- lm(y ~ x1 + x2 + z)
  # summary(fit.2)

  plot(fit.1, which=1, main="Model 1")
  plot(fit.2, which=1, main="Model 2")
})
par(mfcol=c(1,1))

What you might do about this depends on whether you can observe $z.$  If you can, then include it in the model.  If you cannot, you might try to predict its values from other variables you do have.  As a start, you can separate your residuals into two groups according to whether they lie along the upper line of points or lower line in the plot, then display the distributions of all other variables, one at a time, broken into these two groups.  Any variable that exhibits a clear shift in location between the groups will help predict $z.$  You would need to include such a variable--let's call it $x_3$--in a nonlinear model in the form
$$y = \alpha_0 + \alpha_1 x_1 + \alpha_2 x_2 + \alpha_3\mathcal{I}(x_3 \le \tau) + \delta$$
where $\mathcal{I}$ is the binary indicator (it creates the 0/1 variable $z$) and $\tau$ is a threshold to be estimated.  Such a model can be fit in various ways; a quick way is to perform a search over a reasonable range of $\tau,$ fitting a standard linear model with least squares for each value of $\tau$ you inspect.
Comment: How does the solution change if instead of using linear regression, I am using a random forest or some other non-linear algorithm for prediction? s it possible to incorporate these trends directly in the model?


How to handle blog tags in a contrib theme?

Question: In blog or blog-like sites, taxonomy is often used for tags and categories.
In Drupal 6, node.tpl.php files could use the $taxonomy variable if they needed access to an array of unrendered taxonomy links associated with the current node. This variable was often assumed by contrib themes to contain the post tags and\or categories, and it was rendered accordingly.
In Drupal 7, $taxonomy is no longer available.
What's the alternative? How should themers handle taxonomy? In particular, how should contrib themes do it, in order to maximally preserve visual compatibility with the 6.x version?
BTW, the bit about that in the "converting themes to Drupal 7" guide is probably incorrect.
Answer: To print the the default taxonomy field separate from the other content:
<?php

    hide($content['field_tags']);
    print render($content);

    print render($content['field_tags']);

?>

This will only handle the default "tags" taxonomy. To follow discussion of an easier way to accomplish this, see this issue.
Answer: We can use taxonomy-term.tpl.php in our theme to theme the display of terms. Below are term related variables,

$term_url: Direct URL of the current term.
$term_name: Name of the current term.
$name: the (sanitized) name of the term.
$content: An array of items for the content of the term (fields and
description). Use render($content) to print them all, or print a subset such as render($content['field_example']). Use hide($content['field_example']) to temporarily suppress the printing of a given element.


Erlang : How to force domain name on a cluster node?

Question: I would like to start a cluster node on a dedicated server.
However When I start it with this command line :
erl -pa ebin -name myserver -setcookie abc

It starts with a certain domain name:
Erlang R15B (erts-5.9) [source] [64-bit] [smp:16:16] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9  (abort with ^G)
(firstname.lastname@example.com)1>

I would like it to start on another domain name like : firstname.lastname@example.com
Answer: you can specify the domain as part of -name
> erl -pa ebin -name email@example.com -setcookie abc
Erlang R15B (erts-5.9) [source] [64-bit] [smp:4:4] [async-threads:0] [kernel-poll:false]
...
(email@example.com)1> node().
'firstname.lastname@example.com'


How to find multiple values in column

Question: I have problem with matching in excel file. Let me explain it on an example:
<code>COL1 COL2    COL3 COL4 COL5
AA11 First   AA11 ???? ???
BB22 First   BB22
AA11 Second
BB22 Third
</code>

COL1 - User's indexes
Col2 - User's groupName
Col3 DISTINCT user's indexes
Col4,5... Values that i'm looking for

I'm looking for formulas for following cases:
Column 4: IF user with index COL3 has groups(COL2) 'FIRST' AND 'SECOND' add value = 'LEVEL1'
Column 5: IF user with index COL3 has groups(COL2) 'FIRST' AND 'THIRD add value = 'LEVEL2'
Comment: Have you tried `VLookup`?
Comment: No i did not, i will check it.
Comment: What do you mean by `add`? I am just asking because it seems as if you are trying to add a certain value to another cell. Yet, any Excel formula can only - as a result of its calculation - show a certain value. Yet, it cannot change a value nor can it change the value in another cell.
Comment: EDIT: Smit - i think it won't help me, because VLookup can return only return value that i don't need. I want to find multiple values and if they match some conditions return specific value.
Comment: Ralph add - write, put, whatever - just write a specific value in blanc cell.
Answer: I would use COUNTIFS wrapped in an IF:
Column 4:
<code>=IF(SUM(COUNTIFS(A:A,C1,B:B,{"First","Second"}))>=2,"Level 1","")
</code>
Column 5:
<code>=IF(SUM(COUNTIFS(A:A,C1,B:B,{"First","Third"}))>=2,"Level 2","")
</code>
Comment: I will check it, but i think it is the answer for my question. Thanks Scott!
Comment: @hakobot just remember to come back and mark as correct if it works.
Comment: Scott Carner - i just checked - it does work! Thank you one more time!

How to find multiple values in column


The discrete random variable only takes the values $0$, $1$ and $2$. Moreover you know that $P(X=0)=P(X=2)$ and $P(X=1)=0.57$.

Question: The discrete random variable only takes the values $0$, $1$ and $2$. Moreover you know that $P(X=0)=P(X=2)$ and $P(X=1)=0.57$.
Determine the value of $Var(X)$. Round your answer to two decimal numbers.
MY WORKING
I know that $Var(X)=E(X^{2})-E(X)^{2}$; Where:
$E(X)=0P(X=0)+1P(X=1)+2P(X=2)=0.57+2P(X=2)$
$E(X^{2})=0^{2}P(X=0)+1^{2}P(X=1)+2^{2}P(X=2)=0.57+4P(X=2)$
Now I don't know how to go further since I don't know the value of $P(X=2)$. Can anyone help me. I will really appreciate it.
Comment: They are equal as per question, right?
Comment: $P(X = 0) + P(X = 2) = 1 - 0.57$
Comment: System of equations. Two unknowns: $P(X = 0)$ and $P(X = 2)$. Two equations: @MathLover 's two comments.
Comment: Also you have a typo in $E(X^2)$. $P(X=4)$ should be $P(X=2)$.
Comment: Still It's not clear to me how do I find value of $P(X=2)$ from $P(X=0)+P(X=2)=0.43$ .
Comment: Yes I got the point. Thanks for your addition sir.
Answer: $P(X=0)+P(X=1)+P(X=2)=1$
$P(X=0)=P(X=2)$ and $P(X=1)=0.57$
$2\cdot P(X=2)+0.57=1\Rightarrow2\cdot P( X=2)=0.43$
$\Rightarrow P(X=2)=0.215$


Flutter: Some emoji display incorrectly on iOS

Question: In my Flutter project, I use this function for displaying emoji
String unicodeToString(String unified) {
  return String.fromCharCodes(unified.split('-').map((e) {
    return int.parse(e, radix: 16);
  }));
}

Then, if I call it with a list of Unicode codepoints, it should spit out an emoji character.
Now, in my database (a big JSON), there are several emoji I just can't get displayed correctly on iOS.
Specifically there seems to be some issues with kiss and couple with heart emoji.

1F469-200D-2764-FE0F-200D-1F48B-200D-1F468 (Kiss woman man)
1F468-200D-2764-FE0F-200D-1F48B-200D-1F468 (Kiss man man)
1F469-200D-2764-FE0F-200D-1F48B-200D-1F469 (Kiss woman woman)
1F469-200D-2764-FE0F-200D-1F468 (Couple with heart woman man)
1F468-200D-2764-FE0F-200D-1F468 (Couple with heart man man)
1F469-200D-2764-FE0F-200D-1F469 (Couple with heart woman woman)

If I plug the one to the mentioned function,
unicodeToString('1F469-200D-2764-FE0F-200D-1F48B-200D-1F469')

it displays like that on iOS.

If I use software keyboard, search for that specific emoji and type it, same issue appears.
Codepen:
https://codepen.io/johnnycook-the-bashful/pen/WNOOvOd
Flutter 2.2.2,
iOS 14.5
Comment: I think the used logic is working properly. It just converts the string to a list of integers and displays char from that. The issue also happens if I simply use the iOS software emoji keyboard and put the char there without any custom logic. Curiously, all the 'family' emoji work.
Comment: BTW, pasting ❤ in Visual Studio Code breaks up the same way (which is in Electron; though it works in Slack which is also Electron). It does not when you paste into Xcode or SublimeText). As you suggest, this has nothing to do with unicodeToString; the same thing occurs if you replace that with the emoji itself as a string in your codepen code. It's clearly an issue in Flutter itself. (If you search for ZWJ in the Flutter issues list, you'll see they've had lots of problems over the years.)
Comment: My suspicion is your display logic. How are you putting this on the screen? Are you further parsing the returned string in any way? These are double-ZWJ expressions, and it's possible that you have a parser that doesn't understand that. (It's possible that parser is in Flutter; I don't know Flutter, but I do know iOS and Unicode). If it's related to multiple ZWJ, then family emoji might also have trouble. You should test 1F469-200D-1F469-200D-1F467-200D-1F466. It should display .
Comment: Ok, thank you for the suggestion. For now, I just removed those six emoji from db.
Answer: I checked your code on codepen, everything is perfect.
That simply means IOS operating system doesn't support that Unicode.
No workaround for now, but below is an alternative solution.
Use the flutter emoji picker on the pub, it supports both Android and IOS.
That is the Material design and Cupertino
https://pub.dev/packages/emoji_picker_flutter
Comment: Why do you believe iOS doesn't support this emoji? It's available in the keyboard (and my tests with SwiftUI display these without trouble). I don't know anything about how Flutter handles ZWJ emojis, but there's no reason to believe this is an OS issue.
Comment: No, iOS supports that emoji. It even displays it correctly in different apps. I already tried the mentioned emoji_picker_flutter and other packages. Same issue everywhere. My guess is Flutter itself causes the issue. And yes, on Android and web it works ok.


How can I use a collection class as a static resource in silverlight

Question: I have a simple class named Customer with 2 properties.
public Name {get;set;}public LastName {get;set}
Then I made a collection class named CustomerList with only one public property named Customers
public class CustomerList
{
    public List<Customer> Customers { get; set; }

    public CustomerList()
    {
        Customers = new List<Customer>();
        Customers.Add(new Customer() { Name = "Foo", LastName = "Bar" });
        Customers.Add(new Customer() { Name = "Foo1", LastName = "Bar1" });
    }
}

Now I want to use this class as a static resouce in XAML.
  <UserControl.Resources>
  <customers:CustomerList x:Key="CustomersKey">
  </UserControl.Resources>

and then use it in a ListBox
 <ListBox x:Name="lvTemplate" ItemsSource="{Binding Source={StaticResource CustomersKey}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBox Text="{Binding Name}"/>
                    <TextBox Text="{Binding LastName}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

if I set the ItemsSource in code behide, after instantiating the class, all work fine. If I try to set it from XAML and the static resource Nothing happens. not even if I use the {Binding Path=Customer.Name} or {Binding Path=Name}.
Clearly I miss something...
Answer: Since the CustomerList isn't actually the list of items (does not implement IEnumerable), you need to specify what property inside the object you want to use as ItemsSource.
<ListBox ItemsSource="{Binding Path=Customers, Source={StaticResource CustomersKey}}">

Comment: Oh! I was trying to use the path inside the DataTemplate... This was my mistake. Thank you for the answer.


Retrieving main route table from Vpc construct with AWS CDK

Question: I am creating a default VPC using AWS CDK, and I want to update the main route table the Vpc construct creates with a Name tag. Below is the sample code of how I'm creating the VPC:
from aws_cdk import aws_ec2 as ec2
from constructs import Construct

class Vpc(Construct):
    def __init__(self, scope: Construct, construct_id: str,  **kwargs):
        super().__init__(scope, construct_id)

        vpc = self.create_vpc()

        # TODO: Add Name tag to main VPC route table here

    def create_vpc(self) -> ec2.Vpc:
        vpc_name = "TEST-VPC"

        vpc = ec2.Vpc(
            self, 'VPC',
            cidr='10.10.0.0/24',
            vpc_name=vpc_name
        )

        return vpc

Is it possible to get the main route table and tag it?
Comment: @maafk It will create a route table for each subnet, but it creates a default route table for the VPC which is marked as the main route table.
Comment: Can you clarify what you mean by "main VPC route table"?  CDK will create a route table for each subnet created (in this case 2 public and 2 private).
Comment: @JeffCoe Did you ever find a solution to this? I'm trying to do something similar as well.
Comment: @bearrito - Unfortunately, I have not. I would assume we'd be able to do it if we fell back to the level 1 constructs which isn't exactly desirable.
Comment: @JeffCoe I actually took some advice I read elsewhere and decided to use the individual subnet tables. There are some arguments against using the main route table.
Answer: Perhaps this doesn't strictly answer the question, but it's a viable solution for anyone that needs to add a route to subnets using CDK.
const vpcPeerConnectionId = 'hard-coded-id'
const vpcCidr = '10.22.0.0/16'
this.vpc.privateSubnets.forEach((subnet, index) => {
  let routeTableId = subnet.routeTable.routeTableId
  new CfnRoute(this, 'PrivateSubnetPeeringConnectionRoute' + index, {
    destinationCidrBlock: vpcCidr,
    routeTableId: routeTableId,
    vpcPeeringConnectionId: vpcPeerConnectionId
  })
})

Example uses a VPC Peering connection. For other uses see this document:
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CfnRoute.html
Answer: For those that want to create a subnet and have it use the default VPC Route Table, you need to use the low level construct:
new cdk.aws_ec2.CfnSubnet(
        this,
        `subnet-name-id`,
        {
          vpcId: vpcId,
          cidrBlock: props.cidrRange,
          availabilityZone: az,
        }
      );


Proof of Euler's formula for connected planar graphs with linear algebra

Question: Euler's formula states that if a finite, connected, planar graph is drawn in the plane without any edge intersections, and v is the number of vertices, e is the number of edges and f is the number of faces (regions bounded by edges, including the outer, infinitely large region), then
$$ v − e + f = 2 $$
-Wikipedia, Planar graph.
There are many proofs exist to the above result. One e-page that surmise many of them is well known, and could be found here - http://www.ics.uci.edu/~eppstein/junkyard/euler/all.html.
Yesterday I have been watching lecture 12 in linear algebra by Gilbert Strang, MIT. He introduced some application of the four fundamental subspaces, and one of them were Euler's formula, but I couldn't to follow his explanation this time.
Can someone sketch me a proof of Euler's result in linear algebra terms?
Thank you.
Comment: For those not wanting to watch: he derives Euler's formula by interpreting the kernel of the transpose of a graph's oriented incidence matrix as counting faces.
Comment: When in the video does he mention it?
Comment: He mention it in 39:20.
Answer: Let $G$ be a connected and planar graph, where each edge is assigned an (arbitrary) orientation.  Let $m = E$ denote the number of edges, and let $n = V$ denote the number of columns.  The incidence matrix of $G$ is the $m \times n$ matrix $A$ for which
$$
A_{ij} =
\begin{cases}
-1 & \text{edge $i$ leaves node $j$}\\
1 & \text{edge $i$ enters node $j$}\\
0 & \text{otherwise}
\end{cases}
$$
Note: The incidence matrix is usually defined to be the transpose of this matrix (as it is defined here for example), but we'll stick to Strang's convention.
With that, Strang tries to convince us of the following:

Claim: $\operatorname{rank}(A) = n-1$
Claim: $\dim N (A^T)$ is the number of (internal) "faces" of the graph $G$.  In the usual notation, $\dim N (A^T) = F-1$.

To prove the first claim, we see that the pivot columns upon row-reducing $A^T$ produce a spanning tree of $G$. Alternatively, it suffices to note that since $G$ is connected, $N(A)$ must be the space spanned by $(1,\dots,1)$.
The second result is not strictly "proven", but it is convincingly argued with Strang's example.
With that, the dimension formula yields
$$
N(A^T) = m - r(A^T) \implies\\
F - 1 = m - (n - 1) \implies\\
F - 1 = E - (V - 1) \implies\\
V - E + F = 2
$$


TryParse works with var but not with object in C#?

Question: Check this out. I want to write the following program: if you input a double or an integer increase it by 1, but if you input a string, append an asterix at the end. So I decided to do a int.TryParse and a double.TryParse.
Console.WriteLine("Enter something:");
object firstTry = 0;
object secondTry = 0;

bool ifInt = int.TryParse(Console.ReadLine(), out firstTry);
bool ifDouble = Double.TryParse(Console.ReadLine(), out secondTry);

In this case both TryParse are underlined, and I get a message that object cannot be converted to int, which in my opinion is illogical since object can be any type... Or, evidently, I'm wrong...
P.S. I dont have that problem when I use var, but I still wanna know whats the difference between the two types in this case.
Comment: @KevinM1: casts and ref parameters don't play well together.
Comment: Also, it sounds like you *don't* want to do `Console.Readline` twice (you would get two different lines). Instead, assign the result of *one* call to a variable, and then re-use it for the three cases.
Comment: Anything (everything) is an object, but not all objects are ints, or floats, or strings, or whatever else.  That's why you're getting the error.  You'll need to cast.
Answer: int.TryParse expects a variable of type int, when you specify var, it is implicitly typed and compiler consider it as int because of the assigned value.
See: var (C# Reference)

Beginning in Visual C# 3.0, variables that are declared at method
  scope can have an implicit type var. An implicitly typed local
  variable is strongly typed just as if you had declared the type
  yourself, but the compiler determines the type.

var i = 10; // implicitly typed
int i = 10; //explicitly typed

For your double.TryParse to succeed you need need secondTry defined as:
var secondTry = 0d; //or 0.0

or
double secondTry;

Answer: var is called implicitly typed varables. It is actually a syntatic sugar of c# compiler. Behind the hood it is actually Int32 in your case.
object version fails because TryParse expects out int as parameter but you're trying to pass out object, same thing applies to Double version also.
More info about var keyword can be found here
Answer: You can pass an int to anywhere that takes an object because the compiler would automatically "box" the int as an object and then pass that object instead. The other way around is not true. You can not pass an object to anywhere that takes int. For value type, you have to explicitly cast it, for example:
object o = 0;
some_function_that_takes_int((int)o);

This works fine if o indeed has an int value. However if you have code like this:
object o = "hello";
some_function_that_takes_int((int)o);

Then it will compile fine but at runtime the code (int)o will throw out an exception because it can't cast a string into an int.
The reason that the compiler can automatically box an int into an object because that will never fail. It doesn't do the other way around because it would fail in the code demonstrated above.
For reference argument, such as ref or out argument as in your code, I don't think you can even use explicit cast. This is because an address of the int value is required.
var will not have any problem because var just tell the compiler to automatically choose a type. In your case the compiler will choose "int". So everything is int if you use var. However if you explicitly define your variable as "object", then your argument is "object" and TryPase wants an "ref int". They are incompatible so it won't work.
Hope this helps.
Answer: A declaration on the form object foo; declares a reference of object type, which can be anything in .NET since all types derive from object.
var on the other hand is just a way to tell the compiler to figure out itself what it should write there. So var foo = 7 will cause foo to become an int. That's why it works with var but not with object because with var the type of the variable is int.
Answer: Your firstTry and secondTry variables must match their respective out parameters:
int firstTry = 0;
double secondTry = 0;

bool ifInt = int.TryParse(Console.ReadLine(), out firstTry);
bool ifDouble = Double.TryParse(Console.ReadLine(), out secondTry);

In general when declaring a variable that will be used with an out parameter, you have to declare its specific type. If you instead write:
var firstTry = 0;
var secondTry = 0;

the compiler will infer that secondTry is an int - which isn't what you want. You could of course write:
var firstTry = 0;
var secondTry = 0.0;

and now the compiler will infer double for secondTry. However I find such code too clever, and prefer to be more explicit when declaring variables used in out parameters.


clamd says socket in use by another process but I can't find one

Question: I'm running CentOS 5.3 (Final) and using rpmforge I installed clamd and prereqs ok. I started clamd and ran a freshclam all ok. But if I run "clamd PING" or clamd /path/to/file I get

ERROR: LOCAL: Socket file /var/run/clamav/clamd.sock is in use by another process

Further detail below but I'm at a loss where to go from here now, any advice anyone?
[root@main ~]# clamd PING
ERROR: LOCAL: Socket file /var/run/clamav/clamd.sock is in use by another process

[root@main ~]# clamd -V
ClamAV 0.97.6/15499/Wed Oct 24 11:02:00 2012

[root@main ~]# ps -ef | grep clam
clamav    2744     1  0 14:28 ?        00:00:00 clamd
root      3932  3541  0 14:36 pts/0    00:00:00 grep clam

Installed Packages
Name       : clamd
Arch       : x86_64
Version    : 0.97.6
Release    : 1.el5.rf
Size       : 582 k
Repo       : installed
Summary    : The Clam AntiVirus Daemon
URL        : http://www.clamav.net/
License    : GPL
Description: The Clam AntiVirus Daemon

here's the config:
##
## Example config file for the Clam AV daemon
## Please read the clamd.conf(5) manual before editing this file.
##

# Comment or remove the line below.
#Example

# Uncomment this option to enable logging.
# LogFile must be writable for the user running daemon.
# A full path is required.
# Default: disabled
LogFile /var/log/clamav/clamd.log

# By default the log file is locked for writing - the lock protects against
# running clamd multiple times (if want to run another clamd, please
# copy the configuration file, change the LogFile variable, and run
# the daemon with --config-file option).
# This option disables log file locking.
# Default: no
#LogFileUnlock yes

# Maximum size of the log file.
# Value of 0 disables the limit.
# You may use 'M' or 'm' for megabytes (1M = 1m = 1048576 bytes)
# and 'K' or 'k' for kilobytes (1K = 1k = 1024 bytes). To specify the size
# in bytes just don't use modifiers.
# Default: 1M
LogFileMaxSize 0

# Log time with each message.
# Default: no
LogTime yes

# Also log clean files. Useful in debugging but drastically increases the
# log size.
# Default: no
#LogClean yes

# Use system logger (can work together with LogFile).
# Default: no
LogSyslog yes

# Specify the type of syslog messages - please refer to 'man syslog'
# for facility names.
# Default: LOG_LOCAL6
#LogFacility LOG_MAIL

# Enable verbose logging.
# Default: no
#LogVerbose yes

# Log additional information about the infected file, such as its
# size and hash, together with the virus name.
#ExtendedDetectionInfo yes

# This option allows you to save a process identifier of the listening
# daemon (main thread).
# Default: disabled
PidFile /var/run/clamav/clamd.pid

# Optional path to the global temporary directory.
# Default: system specific (usually /tmp or /var/tmp).
TemporaryDirectory /var/tmp

# Path to the database directory.
# Default: hardcoded (depends on installation options)
DatabaseDirectory /var/clamav

# Only load the official signatures published by the ClamAV project.
# Default: no
#OfficialDatabaseOnly no

# The daemon can work in local mode, network mode or both.
# Due to security reasons we recommend the local mode.

# Path to a local socket file the daemon will listen on.
# Default: disabled (must be specified by a user)
LocalSocket /var/run/clamav/clamd.sock

# Sets the group ownership on the unix socket.
# Default: disabled (the primary group of the user running clamd)
#LocalSocketGroup virusgroup

# Sets the permissions on the unix socket to the specified mode.
# Default: disabled (socket is world accessible)
#LocalSocketMode 660

# Remove stale socket after unclean shutdown.
# Default: yes
FixStaleSocket yes

# TCP port address.
# Default: no
#TCPSocket 3310

# TCP address.
# By default we bind to INADDR_ANY, probably not wise.
# Enable the following to provide some degree of protection
# from the outside world.
# Default: no
#TCPAddr 127.0.0.1

# Maximum length the queue of pending connections may grow to.
# Default: 200
MaxConnectionQueueLength 30

# Clamd uses FTP-like protocol to receive data from remote clients.
# If you are using clamav-milter to balance load between remote clamd daemons
# on firewall servers you may need to tune the options below.

# Close the connection when the data size limit is exceeded.
# The value should match your MTA's limit for a maximum attachment size.
# Default: 25M
#StreamMaxLength 10M

# Limit port range.
# Default: 1024
#StreamMinPort 30000
# Default: 2048
#StreamMaxPort 32000

# Maximum number of threads running at the same time.
# Default: 10
MaxThreads 50

# Waiting for data from a client socket will timeout after this time (seconds).
# Default: 120
ReadTimeout 300

# This option specifies the time (in seconds) after which clamd should
# timeout if a client doesn't provide any initial command after connecting.
# Default: 5
#CommandReadTimeout 5

# This option specifies how long to wait (in miliseconds) if the send buffer is full.
# Keep this value low to prevent clamd hanging
#
# Default: 500
#SendBufTimeout 200

# Maximum number of queued items (including those being processed by MaxThreads threads)
# It is recommended to have this value at least twice MaxThreads if possible.
# WARNING: you shouldn't increase this too much to avoid running out  of file descriptors,
# the following condition should hold:
# MaxThreads*MaxRecursion + (MaxQueue - MaxThreads) + 6< RLIMIT_NOFILE (usual max is 1024)
#
# Default: 100
#MaxQueue 200

# Waiting for a new job will timeout after this time (seconds).
# Default: 30
#IdleTimeout 60

# Don't scan files and directories matching regex
# This directive can be used multiple times
# Default: scan all
#ExcludePath ^/proc/
#ExcludePath ^/sys/

# Maximum depth directories are scanned at.
# Default: 15
#MaxDirectoryRecursion 20

# Follow directory symlinks.
# Default: no
#FollowDirectorySymlinks yes

# Follow regular file symlinks.
# Default: no
#FollowFileSymlinks yes

# Scan files and directories on other filesystems.
# Default: yes
#CrossFilesystems yes

# Perform a database check.
# Default: 600 (10 min)
#SelfCheck 600

# Execute a command when virus is found. In the command string %v will
# be replaced with the virus name.
# Default: no
#VirusEvent /usr/local/bin/send_sms 123456789 "VIRUS ALERT: %v"

# Run as another user (clamd must be started by root for this option to work)
# Default: don't drop privileges
User clamav

# Initialize supplementary group access (clamd must be started by root).
# Default: no
AllowSupplementaryGroups yes

# Stop daemon when libclamav reports out of memory condition.
#ExitOnOOM yes

# Don't fork into background.
# Default: no
#Foreground yes

# Enable debug messages in libclamav.
# Default: no
#Debug yes

# Do not remove temporary files (for debug purposes).
# Default: no
#LeaveTemporaryFiles yes

# Detect Possibly Unwanted Applications.
# Default: no
#DetectPUA yes

# Exclude a specific PUA category. This directive can be used multiple times.
# See http://www.clamav.net/support/pua for the complete list of PUA
# categories.
# Default: Load all categories (if DetectPUA is activated)
#ExcludePUA NetTool
#ExcludePUA PWTool

# Only include a specific PUA category. This directive can be used multiple
# times.
# Default: Load all categories (if DetectPUA is activated)
#IncludePUA Spy
#IncludePUA Scanner
#IncludePUA RAT

# In some cases (eg. complex malware, exploits in graphic files, and others),
# ClamAV uses special algorithms to provide accurate detection. This option
# controls the algorithmic detection.
# Default: yes
#AlgorithmicDetection yes

##
## Executable files
##

# PE stands for Portable Executable - it's an executable file format used
# in all 32 and 64-bit versions of Windows operating systems. This option allows
# ClamAV to perform a deeper analysis of executable files and it's also
# required for decompression of popular executable packers such as UPX, FSG,
# and Petite. If you turn off this option, the original files will still be
# scanned, but without additional processing.
# Default: yes
ScanPE yes

# Executable and Linking Format is a standard format for UN*X executables.
# This option allows you to control the scanning of ELF files.
# If you turn off this option, the original files will still be scanned, but
# without additional processing.
# Default: yes
ScanELF yes

# With this option clamav will try to detect broken executables (both PE and
# ELF) and mark them as Broken.Executable.
# Default: no
DetectBrokenExecutables yes

##
## Documents
##

# This option enables scanning of OLE2 files, such as Microsoft Office
# documents and .msi files.
# If you turn off this option, the original files will still be scanned, but
# without additional processing.
# Default: yes
ScanOLE2 yes

# With this option enabled OLE2 files with VBA macros, which were not
# detected by signatures will be marked as "Heuristics.OLE2.ContainsMacros".
# Default: no
#OLE2BlockMacros no

# This option enables scanning within PDF files.
# If you turn off this option, the original files will still be scanned, but
# without decoding and additional processing.
# Default: yes
#ScanPDF yes

##
## Mail files
##

# Enable internal e-mail scanner.
# If you turn off this option, the original files will still be scanned, but
# without parsing individual messages/attachments.
# Default: yes
ScanMail yes

# Scan RFC1341 messages split over many emails.
# You will need to periodically clean up $TemporaryDirectory/clamav-partial directory.
# WARNING: This option may open your system to a DoS attack.
#      Never use it on loaded servers.
# Default: no
#ScanPartialMessages yes

# With this option enabled ClamAV will try to detect phishing attempts by using
# signatures.
# Default: yes
#PhishingSignatures yes

# Scan URLs found in mails for phishing attempts using heuristics.
# Default: yes
#PhishingScanURLs yes

# Always block SSL mismatches in URLs, even if the URL isn't in the database.
# This can lead to false positives.
#
# Default: no
#PhishingAlwaysBlockSSLMismatch no

# Always block cloaked URLs, even if URL isn't in database.
# This can lead to false positives.
#
# Default: no
#PhishingAlwaysBlockCloak no

# Allow heuristic match to take precedence.
# When enabled, if a heuristic scan (such as phishingScan) detects
# a possible virus/phish it will stop scan immediately. Recommended, saves CPU
# scan-time.
# When disabled, virus/phish detected by heuristic scans will be reported only at
# the end of a scan. If an archive contains both a heuristically detected
# virus/phish, and a real malware, the real malware will be reported
#
# Keep this disabled if you intend to handle "*.Heuristics.*" viruses
# differently from "real" malware.
# If a non-heuristically-detected virus (signature-based) is found first,
# the scan is interrupted immediately, regardless of this config option.
#
# Default: no
#HeuristicScanPrecedence yes

##
## Data Loss Prevention (DLP)
##

# Enable the DLP module
# Default: No
#StructuredDataDetection yes

# This option sets the lowest number of Credit Card numbers found in a file
# to generate a detect.
# Default: 3
#StructuredMinCreditCardCount 5

# This option sets the lowest number of Social Security Numbers found
# in a file to generate a detect.
# Default: 3
#StructuredMinSSNCount 5

# With this option enabled the DLP module will search for valid
# SSNs formatted as xxx-yy-zzzz
# Default: yes
#StructuredSSNFormatNormal yes

# With this option enabled the DLP module will search for valid
# SSNs formatted as xxxyyzzzz
# Default: no
#StructuredSSNFormatStripped yes

##
## HTML
##

# Perform HTML normalisation and decryption of MS Script Encoder code.
# Default: yes
# If you turn off this option, the original files will still be scanned, but
# without additional processing.
#ScanHTML yes

##
## Archives
##

# ClamAV can scan within archives and compressed files.
# If you turn off this option, the original files will still be scanned, but
# without unpacking and additional processing.
# Default: yes
ScanArchive yes

# Mark encrypted archives as viruses (Encrypted.Zip, Encrypted.RAR).
# Default: no
ArchiveBlockEncrypted no

##
## Limits
##

# The options below protect your system against Denial of Service attacks
# using archive bombs.

# This option sets the maximum amount of data to be scanned for each input file.
# Archives and other containers are recursively extracted and scanned up to this
# value.
# Value of 0 disables the limit
# Note: disabling this limit or setting it too high may result in severe damage
# to the system.
# Default: 100M
#MaxScanSize 150M

# Files larger than this limit won't be scanned. Affects the input file itself
# as well as files contained inside it (when the input file is an archive, a
# document or some other kind of container).
# Value of 0 disables the limit.
# Note: disabling this limit or setting it too high may result in severe damage
# to the system.
# Default: 25M
#MaxFileSize 30M

# Nested archives are scanned recursively, e.g. if a Zip archive contains a RAR
# file, all files within it will also be scanned. This options specifies how
# deeply the process should be continued.
# Note: setting this limit too high may result in severe damage to the system.
# Default: 16
#MaxRecursion 10

# Number of files to be scanned within an archive, a document, or any other
# container file.
# Value of 0 disables the limit.
# Note: disabling this limit or setting it too high may result in severe damage
# to the system.
# Default: 10000
#MaxFiles 15000

##
## Clamuko settings
##

# Enable Clamuko. Dazuko must be configured and running. Clamuko supports
# both Dazuko (/dev/dazuko) and DazukoFS (/dev/dazukofs.ctrl). DazukoFS
# is the preferred option. For more information please visit www.dazuko.org
# Default: no
#ClamukoScanOnAccess yes

# The number of scanner threads that will be started (DazukoFS only).
# Having multiple scanner threads allows Clamuko to serve multiple
# processes simultaneously. This is particularly beneficial on SMP machines.
# Default: 3
#ClamukoScannerCount 3

# Don't scan files larger than ClamukoMaxFileSize
# Value of 0 disables the limit.
# Default: 5M
#ClamukoMaxFileSize 10M

# Set access mask for Clamuko (Dazuko only).
# Default: no
#ClamukoScanOnOpen yes
#ClamukoScanOnClose yes
#ClamukoScanOnExec yes

# Set the include paths (all files inside them will be scanned). You can have
# multiple ClamukoIncludePath directives but each directory must be added
# in a seperate line. (Dazuko only)
# Default: disabled
#ClamukoIncludePath /home
#ClamukoIncludePath /students

# Set the exclude paths. All subdirectories are also excluded. (Dazuko only)
# Default: disabled
#ClamukoExcludePath /home/bofh

# With this option you can whitelist specific UIDs. Processes with these UIDs
# will be able to access all files.
# This option can be used multiple times (one per line).
# Default: disabled
#ClamukoExcludeUID 0

# With this option enabled ClamAV will load bytecode from the database.
# It is highly recommended you keep this option on, otherwise you'll miss detections for many new viruses.
# Default: yes
#Bytecode yes

# Set bytecode security level.
# Possible values:
#       None - no security at all, meant for debugging. DO NOT USE THIS ON PRODUCTION SYSTEMS
#         This value is only available if clamav was built with --enable-debug!
#       TrustSigned - trust bytecode loaded from signed .c[lv]d files,
#                insert runtime safety checks for bytecode loaded from other sources
#       Paranoid - don't trust any bytecode, insert runtime checks for all
# Recommended: TrustSigned, because bytecode in .cvd files already has these checks
# Note that by default only signed bytecode is loaded, currently you can only
# load unsigned bytecode in --enable-debug mode.
#
# Default: TrustSigned
#BytecodeSecurity TrustSigned

# Set bytecode timeout in miliseconds.
#
# Default: 5000
# BytecodeTimeout 1000

Comment: I read elsewhere a similar issue was caused by /tmp being chmod 660. I've checkedd /var/tmp and it's 777 with stickybit so should be ok.
Answer: It seems that you misunderstood the documentation. After clamd is started it accepts commands on the socket that it opens. What clamd PING does is try to start another instance of clamd, which did not work because there is one instance running already.
If you want to send commands to the clamd process, you should connect to the socket and send your commands. Like this:
$ echo PING | nc -U /var/run/clamav/clamd.sock
PONG

According to the documentation, you can also prefix the commands with "n" if you are writing them in your terminal, so clamd knows for sure that the end of the line is the end of the command.
$ echo nPING | nc -U /var/run/clamav/clamd.sock
PONG

Comment: correcting the command gave the same response as you "PONG" so it looks like clamd is ok afterall. Means my actual problem maybe in perl. I'm trying to use perls File::VirusScan using the Daemon::ClamAV::Clamd but it reports back: ",error,Did not get ping response from clamd" so I manually tested and, here we are. Thanks I'll have to post elsewhere for the perl problem
Comment: @chutz this command with : echo ping | netcat -u /var/run/clamav/clamd.sock delivers "could not resolve host" here - (with Manjaro - need then to change firewall to deny instead to reject ?) ...
Comment: @dschinn1001, that is a capital `-U` ("Use UNIX domain socket"), and what you tried is a lowercase `-u` ("UDP mode"). Also, keep in mind that there are many, many versions of netcat and not all of them support the `-U` option.
Comment: the clamd socket may be named clamd.ctl instead of clamd.sock (it is named this way under LinuxMint)


Making icon for a Windows Form: How to make it show up correctly?

Question: OK, so I have built a Windows Form application.  I now want an icon for it.  So I use the Icon Editor built into Visual Studio 2012.  Draw it all out to look nice and purdy.  Once I am done, I have a .ico file and I make it the default icon for the project, and also the icon for the one WinForm in the application.
Unfortunately, it does not show up as I have created it!  It is displayed as the default icon file as it existed before I modified it in the icon editor.  It's a 32x32 4 bit icon.  If I change the extension to .bmp it shows up as the default.
It looks like the VS icon editor is editing something else, not the appearance of the icon.  Can someone tell me what I am doing wrong?
I used to have a progam called IconArt that would create icons that looked like icons when I used them in VS.  IconArt is now abandonware and won't run on my 64bit Windows workstation.
Answer: Since I didn't get any answers within the time I was hoping, I posted this question also in the MSDN Visual Studio forum, and got a good answer that I thought I should post here.  Credit to Reed Copsey, Jr, for the answer!
This is it:

You'll need to put your design in all of the different versions.  ICO
  files contain multiple versions of the same image, for different
  screen resolutions.
My personal preference is to not use VS - there's an ICO plugin for
  Paint.Net (all free) which allows you to make a single image
  (typically 256x256), and save multiple versions within an ICO file in
  one shot.  It's very useful for building icons.
See
  http://forums.getpaint.net/index.php?/topic/927-icon-cursor-and-animated-cursor-format-v37-may-2010/
  for the plugin.

Since I am a Paint.Net user, the plugin sounded like a great idea, and I tried it.  Bingo!  This works very nicely.


Fourier analysis, second derivative

Question: I'm stuck with a part of a question, I've come to the part where $y''(t) = y(t+\pi)$, the solution says that this is equal to putting $y(t)=C$, where $C$ is a constant, I cannot understand how they do this, any help at this point is greatly appreciated!
Comment: notice that the solution is supposed to be 2pi-periodic!
Comment: Maybe add the rest of your question for context?
Comment: "fourier-analysis" ? So you are supposed to write the Fourier transform of $y''(t)$ and $y(t+\pi)$
Comment: I didnt know what subject to put this under, probably I took the wrong, I just want to know how they know that y''(t)=y(t+pi) -->y(t)=C
Answer: Try taking two derivatives of $y(t+\pi)$, you'll get that $y''(t+\pi) = y(t)$, so $y^{(4)}(t) = y(t)$ (using $2\pi$ periodicity).  This is a constant coefficient linear homogenous ODE, so assume that $y = re^{\lambda t}$, get that the characteristic equation is $\lambda^4+1 = 0$, so we get that solutions are of the form $\pm 1$, and $\pm i$.
So, we have that $y = c_1 e^{x}+c_2e^{-x}+c_3e^{ix}+c_4e^{-ix}$ is a solution.
This isn't yet $2\pi$ periodic (the last two terms are, but the first two aren't).  To make it periodic, we can set $y(t+2\pi) = y(t)$.  This gives us that:
\begin{align*}
c_1e^{x+2\pi}+c_2e^{-x-2\pi}+c_3e^{ix+2\pi i}+c_4e^{-ix-2\pi i} & = c_1e^x+c_2e^{-x}+c_3e^{ix}+c_4e^{-ix} \\
c_1e^x(e^{2\pi}-1)+c_2e^{-x}(e^{-2\pi}-1) & = 0 \\
c_1e^{2x} & =c_2\frac{1-e^{-2\pi}}{e^{2\pi}-1}
\end{align*}
In the above, we have that the only $c_1,c_2$ such that this is true is $c_1 = c_2 = 0$.  So, we get that for $y$ to be $2\pi$ periodic, we need $y(x) = c_3e^{ix}+c_4e^{-ix}$.
This means that $y''(x) = -c_3e^{ix}-c_4e^{ix} = -y(x)$
So, if we want $y''(t) = y(t+\pi)$ then we have that $-y(t) = y(t+\pi)$ or $$c_3e^{ix}+c_3e^{ix+i\pi}+c_4e^{-ix}+c_4e^{-ix-i\pi} = c_3e^{ix}(1+e^{i\pi})+c_4e^{-ix}(1+e^{-i\pi})$$
But, we have that $e^{i\pi} = e^{-i\pi} = -1$, so we have that $y = 0$ is our solution.
Finally, I've managed to forget the constant of integration this entire time, so our solution should really be $y = C$.

Fourier analysis, second derivative


Why doesn't my Chrome Profiler show proper retaining paths for my objects, and why are my objects never released?

Question: I am trying to debug memory leaks in my webapp.
I take snapshots of the heap and compare different heaps.
I found out that some of my objects are being references somewhere.
However, all of my objects are being retained through objects that looks internal to me, eg:

As you can see, this SectionNavView object is being referenced by a few methods that I have created: cleanUp, hide, isShown, etc. using my local variable that, but these methods are being referenced from something that I do not control: idToWrappedObject. Sometimes, there's another intermediary - a injectedScript object.
If my objects are only being referenced form internal V8 references, shouldn't they be released before the profiler takes a snapshot during its GC?
Comment: If they are being referenced from something you do not control, it may have circular references that you cannot remove.
Answer: This simply means that you've used console.log. So the VM keeps a reference to your objects in order to allow you to inspect them later. You can either stop using the console or just clear it every time you take a heap snapshot.
You can reproduce it with the following steps:

Open new tab
Open console (clear it, if there is anything)
Take heap snapshot 1
Type console.log({ foo:'bar' }) in the console
Take heap snapshot 2
Clear the console
Take heap snapshot 3

Then view the results:

Open the comparison view between snapshot 2 and snapshot 1; you'll find the { foo: 'bar' } object

Open the comparison view between snapshot 3 and snapshot 2; you'll find the same object now displays a delta of -1, meaning it was garbage-collected after you cleared the console

Finally, you may also see "Global handles" and then "GC roots" in the retaining tree paths, beside _idToWrappedObject and InjectedScript. I'm not sure how this applies to the definition of GC roots but clearing the console does allow garbage collection.
Comment: I didn't even consider the possibility that console.log might have any implication on the heap snapshots. +1 just for that. Will retest and keep you posted. awesome.
Comment: Thank you a lot. I just cleared the last memory leaks I thought I had thanks to you.


How to add a custom Save &  button to Node Add/Edit form?

Question: I added the following code in hook_form_alter() and I get my button on the Add/Edit node form:
$form['actions']['save_add_lesson'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Add a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_node_form_submit'), /* NEED this */
  '#weight' => 1000
);

But, clicking the button doesn't seem to hit hook_node_submit() or hook_node_insert(). I'm assuming I'm missing a hook or something in the button creation...anyone have any ideas?

Then added this function:
function mymodule_node_form_submit($form, &$form_state) {
  // Do stuff before saving the node

  // Call this to save the node
  node_form_submit($form, $form_state);

  // Do stuff after saving the node
}

Comment: Try making it a `submit` instead of a `button`, that normally does the trick for me
Comment: Sounded like it would work, but it didn't :( I updated the code above to reflect the changes...
Answer: Got it :D
Adding
'#submit' => array('mymodule_course_form_submit'),

To the submit button worked. Like this:
$form['actions']['save_add_lesson'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Create a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_course_form_submit'),
  '#redirect' => 'node/add/lesson',
  '#weight' => 1000
);

function mymodule_course_form_submit($form, &$form_state) {
    $nid = mymodule_node_save_no_redirect($form, $form_state);

    $form_state['redirect'] = 'node/add/lesson';
    unset($_GET['destination']);
    drupal_static_reset('drupal_get_destination');

    if($nid != -1) {
        $_SESSION['mymodule_course_nid'] = $nid;
        drupal_redirect_form($form_state);
    } else {
        // Failed to save Course...notify user
        drupal_set_message('Failed to save Course Content', 'error');
    }
}

Comment: works like a charm, but an interesting part is missing here **mymodule_node_save_no_redirect**, i used these two lines for that `$node = node_form_submit_build_node($form, $form_state);
  node_save($node);`
Answer: There is also a good Content Type: Extras module for that + many more options:

Set default values for common content type settings (see below) - you
can still override the defaults per content type
'Save and New' button to add new nodes of the same type right after saving
'Save and Edit' button to save a node and continue working on it (great for long posts so you don't have to worry about losing all of  your information).
User permissions for content type duplicated on content type add/edit page
Sets a maximum length (26 characters) for 'Add new field' and 'Add new group' (if field_group module is enabled) machine names to prevent submitting the form and getting an error message
Add a 'Save' button to the top of the 'manage fields' form
Auto-populate new field machine name, new group machine name, and existing field label on manage field forms
Add a 'Cancel' button to node edit forms
Ability to set node title visibility when viewing node
Ability to hide title of front page (takes precedence over content type setting)
Ability to add form submission buttons to top of 'Manage fields' content type forms and/or node edit forms.
Ability to remove body field on content type creation.
Ability to set description field in content type edit form to required.

Set defaults for:

Title field
   Preview button
'Save and New' button (with configurable text)
'Save and Edit' button (with configurable text)
Published
Promoted to front page
Sticky at top of lists
Create new revision
Display author and date information
User permissions
Node title visibility per content type
Comment: I saw this, but there is some extra workflow stuff that I need beyond simply Saving and creating a new node ;)
Answer: The following code worked for me to add a second button on a form that saves and creates another item, instead of going straight to see the new node.
function MYMODULE_MYFORMID_form_alter(&$form, &$form_state, $form_id){
  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & Create Another Item'),
    '#access' => TRUE,
    '#submit' => array('MYMODULE_node_form_submit'),
    '#redirect' => 'node/add/new-node-item',
    '#weight' => -30,
  );
}

function MYMODULE_node_form_submit($form, &$form_state) {
 if ($form_state['nid']) {
   $form_state['#redirect'] = 'node/add/new-node-item';
 }
}

See https://www.drupal.org/node/290462.


tablesorter pager.js is not working

Question: I have successfully added the tablesorter.js library to a table in my drupal website but when I try to add the pager, the input and select Html that I add do not show up.  I add this HTML

    <form>

        <input type="text" class="pagedisplay"/>

        <select class="pagesize">
            <option selected="selected"  value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option  value="40">40</option>
        </select>
    </form>

but something in the drupal site makes the select options and the input options disappear from the final page.
Answer: I had to add the form and form elements as a Form under the src/ directory and call it with
 $form= \Drupal::formBuilder()->getForm('Drupal\pup_viewfiles\Form\PagerForm', $extra);

tablesorter pager.js is not working