Calling a Clojure function with named parameters from a hash map

Question: I would like to be able to pass named parameters to a function from a hash map. Let's say I have a function like this:
(defn foo [a & {:keys [b]}] (println a b))

I want to be able to call it with parameters coming from a map. I know I can do it like this:
(apply foo 1 (mapcat identity {:b 2}))

But surely there must be a more idiomatic and less clunky way to do this, right?
Answer: Nope, there is no other less clunky way. It would be better to make your foo to take a hash-map as parameter and pattern match on it for keys:
(defn foo [a {:keys [b]}] (println a b))
(foo 1 {:b 2})

Comment: `(foo 1 :b 2)` feels much more idiomatic than `(foo 1 {:b 2})`, at least from the Clojure code I've read.
Answer: No, there isn't. But you may use concat directly instead of doing it through mapcat:
(apply foo 1 (apply concat {:b 2}))

You may also use ->> macro to make it clearer (though not shorter):
(->> {:b 2}
     (apply concat)
     (apply foo 1))

Comment: I like applying `concat`, thanks. Using the threading operator actually makes it less clear, at least to me. :)


Customizando temas para API 9 e 10 do Android

Question: Tenho um App que roda a parti da API 9 ate 23 do android, no entanto as cores do texto ficam diferente das cores setadas, o correto seria Toolbar Azul com texto branco. O problema ocorre apenas nas API 9 e 10.

E o style é o seguinte:

Alguma solução para este problema?
Desde já grato!
Answer: Eu aconselho usar uma Toobar, por que é bem mais prático e fácil.
Nos seus layouts coloque:
  <android.support.v7.widget.Toolbar
        android:id="@+id/toobar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:theme="@style/toobarStyle"
        android:elevation="3dp"
        />

No seu style coloque:
<resources>

No arquivo color use:
<resources>
  <color name="colorPrimary">sua cor</color>
  <color name="colorPrimaryDark">sua cor</color>
  <color name="colorAccent">#fff</color>
</resources>

No onCreate das suas activitys coloque:
    Toolbar toobar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toobar);

Comment: Vou fazer algumas alterações no style, e já estou usando a Toolbar. Valeu pelo o empenho! :D


How to add users under a specific role

Question: We have 4 type of users -
Admin   -  can view and manage all other users
Parent  -  Can view and manage students but own child
Teacher -  Can view and manage students assigned to him
Student -  Can view and manage own profile & details

So it's clear that everything is around students can be accessed by 3 other roles as per rules.
I am trying with different role and users modules but not getting exactly how to setup this structure in drupal.
I am sure there is definitely a way to do this because it's a general requirement and drupal has a way to implement this. But I am newbie and trying from couple of hrs but not able to set this.
Anyone please guide me on this or share any link where I can get exact information regarding this.
Thanks is Advance
Answer: I assume you use something like Entity reference to add children to parents and to teachers.
I don't think that default Drupal supports this kind of user permissions. As I couldn't find any modules for this functionality, you probably need to do some coding.
The easiest approach would be altering the user/%uid/edit menu item with a custom access callback in a custom module. This ensures users can only access the user edit pages matching your criteria:
function MYMODULE_menu_alter(&$items) {
 if (isset($items['user/%user/edit'])) {
   $items['user/%user/edit']['access callback'] = '_mymodule_user_edit_access';
  }
}

function _mymodule_user_edit_access($account) {
  global $user;

  // May edit own profile
  if ($account->uid == $user->uid) {
    return TRUE;
  }

  // Check if $user has permissions to edit $account
}

The access callback should check if the $user has role Teacher or Parent and if it is referencing to the $account->uid.
Edit:
I just realize you also need to manage profile view rights, this could be done with the same hook, on path user/%user.

How to add users under a specific role


Create a Huge Problem

Question: I am wondering if any problems have been designed that test a wide range of mathematical skills. For example, I remember doing the integral $$\int \sqrt{\tan x}\;\mathrm{d}x$$ and being impressed at how many techniques (substitution, trig, partial fractions etc.) I had to use to solve it successfully.
I am looking for suggestions/contributions to help build up such a question. For example, one problem could have as its answer $\tan x$ which would then be used in the integral, and something about the answer to the integral could lead into the next part.
The relevant subjects would be anything covered in the first few years of an undergraduate degree in mathematics.
The main reason I ask is that I want to work on developing some more integrated ways to practice mathematics "holistically" which I feel is very lacking in the current educational model.
Comment: @GitGud I don't just want a standard multistep problem, I am looking for problems that force the student to use an extremely wide range of mathematical skills and facts in an integrated way.
Comment: Prove Fermat's last theorem.
Comment: I am think of roughly: Calculus up to multivariable, Linear Algebra, Abstract Algebra, Statistics/Probability, some Logic, etc. Basically anything not pushing into graduate level. I have nothing too definite in mind.
Comment: What is covered in the first few years of an undergraduate degree?
Comment: How does what you ask differ from the typical multistep problem? And if it doesn't differ, what is the point of the question exactly? You could just open a few books to find such problems. My questions aren't meant as critics, I really can't understand what you're looking for.
Comment: Compute without CAS
$$
\operatorname{sign}(\tan(2^{100}))
$$
Comment: @Norbert Degrees or radians?
Comment: @Oliver, radians of course
Answer: I don't know this is eligible answer or not but I think it's worth being shared. This solution I made when trying to evaluate
$$
\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx
$$
on Brilliant.org. These are the methods I use to evaluate that integral and post it there as a solution.

Method 1:
Consider the function $f(t)=e^{-a|t|}$, then the Fourier transform of $f(t)$ is given by
$$
\begin{align}
F(\omega)=\mathcal{F}[f(t)]&=\int_{-\infty}^{\infty}f(t)e^{-i\omega t}\,dt\\
&=\int_{-\infty}^{\infty}e^{-a|t|}e^{-i\omega t}\,dt\\
&=\int_{-\infty}^{0}e^{at}e^{-i\omega t}\,dt+\int_{0}^{\infty}e^{-at}e^{-i\omega t}\,dt\\
 &=\lim_{u\to-\infty}\left. \frac{e^{(a-i\omega)t}}{a-i\omega} \right|_{t=u}^0-\lim_{v\to\infty}\left. \frac{e^{-(a+i\omega)t}}{a+i\omega} \right|_{0}^{t=v}\\
&=\frac{1}{a-i\omega}+\frac{1}{a+i\omega}\\
&=\frac{2a}{\omega^2+a^2}.
\end{align}
$$
Next, the inverse Fourier transform of $F(\omega)$ is
$$
\begin{align}
f(t)=\mathcal{F}^{-1}[F(\omega)]&=\frac{1}{2\pi}\int_{-\infty}^{\infty}F(\omega)e^{i\omega t}\,d\omega\\
e^{-a|t|}&=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{2a}{\omega^2+a^2}e^{i\omega t}\,d\omega\\
\frac{\pi e^{-a|t|}}{a}&=\int_{-\infty}^{\infty}\frac{e^{i\omega t}}{\omega^2+a^2}\,d\omega.\tag1
\end{align}
$$
Now, rewrite
$$
\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx=\frac{1}{2}\int_{-\infty}^{\infty}\frac{\mathbb{Re}\left(e^{2ix}\right)}{x^2+2^2}\,dx.\tag2
$$
Comparing $(2)$ to $(1)$ yield $t=2$ and $a=2$. Thus,
$$
\begin{align}
\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx &=\frac{1}{2}\frac{\pi e^{-2\cdot|2|}}{2}\\
&=\frac{\pi}{4e^4}\\
\end{align}
$$

Method 2:
Note that:
$$
\int_{y=0}^\infty e^{-(x^2+4)y}\,dy=\frac{1}{x^2+4},
$$
therefore
$$
\int_{x=0}^\infty\int_{y=0}^\infty e^{-(x^2+4)y}\cos2x\,dy\,dx=\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx
$$
Rewrite $\cos2x=\Re\left(e^{-2ix}\right)$, then
$$
\begin{align}
\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx&=\frac{1}{2}\int_{-\infty}^{\infty}\frac{\cos2x}{x^2+4}\,dx\\
&=\frac{1}{2}\int_{-\infty}^{\infty}\int_{y=0}^\infty e^{-(x^2+4)y}\cos2x\,dy\,dx\\
&=\frac{1}{2}\int_{y=0}^\infty\int_{x=-\infty}^\infty e^{-(yx^2+2ix+4y)}\,dx\,dy\\
&= \int_{y=0}^\infty e^{-4y} \int_{x=-\infty}^\infty \frac{1}{2} e^{-(yx^2+2ix)}\,dx\,dy.
\end{align}
$$
In general
$$
\begin{align}
\int_{x=-\infty}^\infty e^{-(ax^2+bx)}\,dx&=\int_{x=-\infty}^\infty \exp\left(-a\left(\left(x+\frac{b}{2a}\right)^2-\frac{b^2}{4a^2}\right)\right)\,dx\\
&=\exp\left(\frac{b^2}{4a}\right)\int_{x=-\infty}^\infty \exp\left(-a\left(x+\frac{b}{2a}\right)^2\right)\,dx\\
\end{align}
$$
Let $u=x+\frac{b}{2a}\;\rightarrow\;du=dx$, then
$$
\begin{align}
\int_{x=-\infty}^\infty e^{-(ax^2+bx)}\,dx&=\exp\left(\frac{b^2}{4a}\right)\int_{x=-\infty}^\infty \exp\left(-a\left(x+\frac{b}{2a}\right)^2\right)\,dx\\
&=\exp\left(\frac{b^2}{4a}\right)\int_{u=0}^\infty e^{-au^2}\,du.\\
\end{align}
$$
The last form integral is Gaussian integral that equals to $\sqrt{\dfrac{\pi}{a}}$. Hence
$$
\int_{x=-\infty}^\infty e^{-(ax^2+bx)}\,dx=\sqrt{\frac{\pi}{a}}\exp\left(\frac{b^2}{4a}\right).
$$
Thus
$$
\frac{1}{2}\int_{x=-\infty}^\infty e^{-(yx^2+2ix)}\,dx=\frac{1}{2}\sqrt{\frac{\pi}{y}}\exp\left(\frac{(2i)^2}{4y}\right)=\frac{1}{2}\sqrt{\frac{\pi}{y}}\exp\left(-\frac{1}{y}\right).
$$
Next
$$
\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx=\frac{\sqrt{\pi}}{2}\int_{y=0}^\infty \frac{\exp\left(-4y-\frac{1}{y}\right)}{\sqrt{y}}\,dy.
$$
In general
$$
\begin{align}
\int_{y=0}^\infty \frac{\exp\left(-ay-\frac{b}{y}\right)}{\sqrt{y}}\,dy&=2\int_{v=0}^\infty \exp\left(-av^2-\frac{b}{v^2}\right)\,dv\\
&=2\int_{v=0}^\infty \exp\left(-a\left(v^2+\frac{b}{av^2}\right)\right)\,dv\\
&=2\int_{v=0}^\infty \exp\left(-a\left(v^2-2\sqrt{\frac{b}{a}}+\frac{b}{av^2}+2\sqrt{\frac{b}{a}}\right)\right)\,dv\\
&=2\int_{v=0}^\infty \exp\left(-a\left(v-\frac{1}{v}\sqrt{\frac{b}{a}}\right)^2-2\sqrt{ab}\right)\,dv\\
&=2\exp(-2\sqrt{ab})\int_{v=0}^\infty \exp\left(-a\left(v-\frac{1}{v}\sqrt{\frac{b}{a}}\right)^2\right)\,dv\\
\end{align}
$$
The trick to solve the last integral is by setting
$$
I=\int_{v=0}^\infty \exp\left(-a\left(v-\frac{1}{v}\sqrt{\frac{b}{a}}\right)^2\right)\,dv.
$$
Let $t=-\frac{1}{v}\sqrt{\frac{b}{a}}\;\rightarrow\;v=-\frac{1}{t}\sqrt{\frac{b}{a}}\;\rightarrow\;dv=\frac{1}{t^2}\sqrt{\frac{b}{a}}\,dt$, then
$$
I_t=\sqrt{\frac{b}{a}}\int_{t=0}^\infty \frac{\exp\left(-a\left(-\frac{1}{t}\sqrt{\frac{b}{a}}+t\right)^2\right)}{t^2}\,dt.
$$
Let $t=v\;\rightarrow\;dt=dv$, then
$$
I_t=\int_{t=0}^\infty \exp\left(-a\left(t-\frac{1}{t}\sqrt{\frac{b}{a}}\right)^2\right)\,dt.
$$
Adding the two $I_t$s yields
$$
2I=I_t+I_t=\int_{t=0}^\infty\left(1+\frac{1}{t^2}\sqrt{\frac{b}{a}}\right)\exp\left(-a\left(t-\frac{1}{t}\sqrt{\frac{b}{a}}\right)^2\right)\,dt.
$$
Let $s=t-\frac{1}{t}\sqrt{\frac{b}{a}}\;\rightarrow\;ds=\left(1+\frac{1}{t^2}\sqrt{\frac{b}{a}}\right)dt$ and for $0<t<\infty$ is corresponding to $-\infty<s<\infty$, then
$$
I=\frac{1}{2}\int_{s=-\infty}^\infty e^{-as^2}\,ds=\frac{1}{2}\sqrt{\frac{\pi}{a}}.
$$
Thus
$$
\begin{align}
\int_{y=0}^\infty \frac{\exp\left(-ay-\frac{b}{y}\right)}{\sqrt{y}}\,dy&=2\exp(-2\sqrt{ab})\int_{v=0}^\infty \exp\left(-a\left(v-\frac{1}{v}\sqrt{\frac{b}{a}}\right)^2\right)\,dv\\
&=\sqrt{\frac{\pi}{a}}e^{-2\sqrt{ab}}\\
\end{align}
$$
and
$$
\begin{align}
\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx&=\frac{\sqrt{\pi}}{2}\int_{y=0}^\infty \frac{\exp\left(-4y-\frac{1}{y}\right)}{\sqrt{y}}\,dy\\
&=\frac{\sqrt{\pi}}{2}\cdot\sqrt{\frac{\pi}{4}}e^{-2\sqrt{4\cdot1}}\\
&=\frac{\pi}{4e^4}.
\end{align}
$$
It took me hours to make a solution using method 2 because almost no one on that site knows Fourier transform (it is understandable since most of the user there are only school students, so they know nothing about this method) so I made a solution using standard methods. Other methods to solve it is using contour integral or residual theorem, but I'm not familiar with those methods.
Comment: Have you posted this comment to wrong answer?
Comment: @Tunk-Fey You have written $u=x+\frac{b}{2a}\;\rightarrow\;du=dx$ $\int_{x=0}^\infty \exp\left(-a\left(x+\frac{b}{2a}\right)^2\right)\,dx=\exp\left(\frac{b^2}{4a}\right)\int_{u=0}^\infty e^{-au^2}\,du.$ Should not it be $\exp\left(\frac{b^2}{4a}\right)\int_{u=\frac{b^2}{4a}}^\infty e^{-au^2}\,du.\\$
Comment: @user334639 The fishyness in the substitution can be fixed by integrating $x$ from $-\infty$ to $\infty$ (it is an even function in $x$, so $\int_{0}^{\infty} = \frac{1}{2}\int_{-\infty}^{\infty}$). And the formula for Gaussian integration works even when $a$ is complex (which I did not know when I made the comment above).
Comment: Agree with @ArchismanPanigrahi, the substitution from x to u is fishy, even more so when u is not real and you use Gaussian integral after that.
Answer: In terms of an integral question, I tried to come up with a double integral for my students that would test many first year integral techniques. It requires both integration by parts and multiple subsitutions, as well as an understanding of double integral regions. Here it is -
Sketch the region below $y=\sqrt{\sin x}$ and above $\displaystyle y=\frac{2x}{\pi}$ in the first quadrant. Find and mark the lower intersection point, $a$, and the upper intersection point, $b$. The volume under the surface $f(x,y) = y$ over the region is given by
$$
V=\int\limits^b_a \! \int\limits_{ 2x/\pi}^{\sqrt{\sin x}} y \ \mathrm{d}y \, \mathrm{d}x,
$$
where $a$ and $b$ are the intersection points of the curves. Evaluate this double integral. Verify your result by switching the order of integration. Show all working.
Answer: One thing is when the answer to the first parts leads into the next parts as you said, and I don't have experienced that, in particular.
One different thing is an exercise like the integral in your example, where several techniques must be applied in succession in order to solve. Thinking to this second model, comes to my mind the differential equation
$$y''+3y'=t+2e^{-3t}$$
from an assignment back from my yr1 at BEng degree course.
Here the student must in succession:

solve the homogeneous equation;
solve $y''+3y'=t$ (with a polynomial in mind);
solve $y''+3y'=2e^{-3t}$, knowing how to face the fact that $-3$, in the exponent, is also a root of the characteristic equation;
apply superposition to express the complete solution.

Not trivial: if I had to solve your integral and my ODE in a test or exam, I would probably fail the year at Uni. Jokes (?) aside you can find other examples, more interesting than this one, in derivates, integrals and equations, where 3-4 different concepts/notions must be applied to really complete the task.

Integrals at pages 5, 6 and 10 of this exercise paper need 2-3 notions (rather than a single one) to be applied in order to solve, even if I'd say they are not huge problems.

Create a Huge Problem


Latin Squares - Proving the Unique number of Sudoku that can be generated

Question: I recently read that the Sudokus are just Latin Squares for $n  = 9$. I know that proving the number of Latin Squares is considered difficult to generalize in terms of $n$. I would like to know if there is any method of proving the unique number of Sudokus taking a special case for $n = 9$.
The Wikipedia page on Latin Squares shows that for $n = 9 , number\ of\ possible\ Latin\ Squares = 5524751496156892842531225600$. I would like to know different possible methods used to arrive at the answer (e.g using Brute-force , or generating for the reduced Latin-Squares or any other combinatorial method).
PS: I have also read this question asked here and the paper referred by the answer. I am not able to understand why the method fails for $n>11$. Even the OEIS page does not have sequences for $n>11$
Answer: Sudokus are a proper subset of the Latin squares of order $9$, as they have the added restriction of the $3 \times 3$ boxes.  Thus, all sudokus are Latin squares, but not all Latin squares are sudokus.  As with Latin squares, there is no computer-free proof that these numbers are correct.  Typically, these are checked by performing independent computations (possibly by slightly different methods).
That being said, most of the searching can be eliminated by identifying symmetries.  Both Latin squares, in general, and sudokus have "symmetries", which can be exploited to give a significant reduction in the search space.  In a Latin square, for instance, we can permute the rows arbitrarily to give another Latin square (so it'd be a waste of time to count all of these separately).  I'm not particularly familiar with the methods used in enumerating sudokus, but a website by Jarvis (and the linked papers) offers much detail into his enumeration method.
There are $R_9=377597570964258816$ reduced Latin squares of order 9.  I don't think any computer ever has counted from 1 to $R_9$, let alone play around with Latin squares at each step.  Thus, it's safe to say a brute force enumeration is completely out of the question.
To date, the easiest way to find $R_9$ is to use Sade's method which I mention in my answer to the linked question.  Sade's method is the only feasible way for order $10$ or greater.  Unfortunately, Sade's method was published only in a very obscure paper and is hard to obtain.  But I describe it in great detail in my survey paper (here).
Roughly speaking, Sade's method saves an enormous amount of time by identifying Latin rectangles that have the same number of completions, and clumping them together.  We then count the number of ways of extending each equivalence class by one row, then identify which of these extended Latin rectangles admit the same number of completions, and so on recursively.
(Note: In an earlier version of this post, I claimed it was the only way for $9 \times 9$ squares, but there is actually another way in this case.)
For $9 \times 9$ Latin squares, it's possible to iterate through representatives of the 19270853541 main classes of Latin squares on a computer, and at each step calculate the size of the autoparatopism group $\mathrm{Par}(L)$.  The total number of $9 \times 9$ Latin squares is thus \[\sum_L \frac{6n!^3}{|\mathrm{Par}(L)|},\] where the sum is over the 19270853541 representatives.  Generating these representatives can be done via the "canonical construction path" described in:

B. D. McKay, Isomorph-free exhaustive generation, J Algorithms, 26 (1998), 306-324.

See this paper for more details (including the relevant definitions: "main class" and "autoparatopism"):

B. D. McKay, A. Meynert, W. Myrvold, Small Latin squares, quasigroups, and loops. J. Combin. Des. 15 (2007), 98-119.

Sade's method for $12 \times 12$ Latin squares would work fine, if we had a sufficiently powerful computer with enough memory (and the budget to use it, and know-how to program it efficiently).  I think it's safe to say we (as a species) could find this number in the next 100 years or so (I'm hoping to see $R_{12}$ before I die).
Note that the number of Latin squares grows quite fast.  Most people think $n!$ grows quickly.  Well, Smetaniuk showed that $L_{n+1} \geq (n+1)!\ L_n$ (where $L_n$ counts non-reduced Latin squares).  The sheer number of Latin squares is the obstacle here.

B. Smetaniuk, A new construction of Latin squares. II. The number of Latin
  squares is strictly increasing, Ars Combin., 14 (1982), pp. 131-145.
Comment: $R_9 \approx 3e17$. That's no longer an "absurdly large" number for tasks that are parallelizable. The [fastest supercomputer](http://i.top500.org/system/177556) runs 20,000 Terraflops, ie $2e16$ floating point operations in one second.
Comment: @NickAlger Given the operation rate you indicated, what is a reasonable estimate for the duration of computing 12 x 12?


Image flashing on mouse over

Question: I have an image from a map and I have several other images from few regions (which are blue) on the image map. The other images represent the blue regions that should show on mouse over. But I have a problem. When I put the mouse over the regions on the image map, they start flashing. For example, I want to activate the blue region WITHOUT THE FLASHING onmouseover and onmousemove when I hover over the specific region. I'll put a .gif picture(the cursor is not showing) to show what I'm having problem with when i get the mouse cursor over the image and I'll post the code also to see if there's anything missing or has to be changed.
Picture:blue regions flashing onmouseover
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<title></title>
<%--<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" />--%>

<%--
--%>

<form id="form2" runat="server">
    <asp:PlaceHolder ID="PlaceHolder1" runat="server">

        <map name="the_world_map" id="the_world_map">
            <area shape="poly" coords="167,335,168,321,166,318,161,313,156,308,148,308,146,304,143,302,137,301,136,293,133,283,130,277,127,273,127,270,129,266,133,261,133,253,132,248,128,242,124,240,121,240,118,243,114,248,108,254,100,258,94,261,92,261,91,268,87,274,83,279,81,281,81,286,81,291,81,295,75,298,69,304,67,308,66,316,69,318,79,319,86,319,88,321,91,324,94,326,100,325,102,322,103,317,100,315,95,314,88,312,85,308,87,303,90,300,94,297,98,294,104,293,109,293,113,295,119,303,124,311,127,318,130,327,131,335,132,338,135,336,140,332,144,331,148,331,151,333,155,336,162,336,167,335" href="Default2.aspx" id="area_resen" alt="Resen" />
            <area shape="poly" coords="171,45,167,47,161,47,162,50,167,50,167,53,164,55,157,64,161,68,169,88,172,89,175,102,175,105,179,105,180,109,187,116,187,118,202,121,202,124,212,124,216,121,216,116,245,116,253,113,255,110,254,104,253,103,259,103,265,104,269,105,272,103,272,95,274,90,277,87,282,86,285,84,287,78,288,76,280,75,274,74,270,72,265,67,263,63,257,63,254,60,251,57,250,56,247,57,241,56,237,55,234,52,229,49,227,44,227,38,231,35,233,33,231,31,226,29,225,28,225,21,220,20,216,22,213,24,212,26,210,28,207,28,205,26,202,26,200,28,199,31,196,33,192,39,188,43,189,45,189,47,185,50,179,52,175,52,172,50,171,47,171,45" href="Default2.aspx" id="area_skopje" alt="Skopje" />
            <area shape="poly" coords="397,47,388,47,383,56,384,61,384,66,382,70,379,71,375,71,375,76,373,82,372,88,372,94,377,96,389,109,408,109,409,98,405,92,409,89,406,80,412,80,421,77,424,74,423,68,429,66,425,63,415,53,398,53,397,47" href="Default2.aspx" id="area_kocani" alt="Kocani" />
        </map>

resen

skopje

kocani

    </asp:PlaceHolder>
</form>

Answer: On your hover images, add the usemap to use the same map. That way they won't trigger a mouseout event when they are displayed.
See this fiddle: http://jsfiddle.net/NPFWm/4/

<map id="theMap_map" name="theMap_map">
    <area shape="poly" coords="1,1,1,50,50,50,50,1,1,1" id="area1" style="background: #FF0000;" href="#" />
</map>

Comment: I changed my mouseout event with yours and it works (without flashing), but because I'm new with javascript, I don't understand what you meant by duplicating the area over top of the id. Can you tell me what should I add to accomplish that? And yes, the image became a square area, meaning when I put the cursor out of the whole image map, then the blue region stops showing.
Comment: @user1408956 I updated my answer with a new / easier solution.

Image flashing on mouse over


Show error in function if some other function has not run before it

Question: I have two functions in C library that I am making.
One is a setup function, other is a function that does some operations. I want the second operations function to print an error if the setup function has not run before it.
What would be the best way to do this?
Here is what I have in my mind, but I am not sure if that is how it is done.
The setup function:
void setup_function()
{
    #ifndef FUNCTION_SETUP
    #define FUNCTION_SETUP
    a_init();
    b_init();
    c_init();
    #endif
}

And the operations function:
bool operations()
{
    #ifdef FUNCTION_SETUP
    try
    {
        /* My code */
        return true;
    }
    catch (...)
    {
        Serial.println("Error in operations");
        return false;
    }
    #elif Serial.println("Function not setup. Please use setup_function() in void setup()");
    #endif
}

Comment: C or C++? Also read the tags' descriptions! As a new user, also take the [tour] and read [ask].
Comment: Those are two different languages, despite their similarities.
Comment: I understand that. I will modify my question.
Comment: The normal way to do this is through documentation, not through software. "Before this function is executed, you must execute function x()".  This is a super common scenario, since pretty much every single C module has some manner of init function. Other than that, you _could_ use some status variable local to the library but that shouldn't be necessary. You can assume that the user of your lib has RTFM you provided in form of function use comments in the header file.
Comment: Is there a different way of doing it in C than C++? I mentioned both because my project contains both. But if that is not possible then C only.
Comment: You could let the `n_init()` functions change a global variable, that `operations()` checks. If the global variable hasn't changed from some default value (0) then the inits were not run.
Comment: this looks like an X->Y problem. what do you want to achieve with guards inside functions? it doesn't determine if the setup function was executed, only whether it seen by the compiler
Comment: @Lundin I understand that it is usually mentioned in documentation, and I have done that. But I want it to show an error in case the user doesn't follow the documentation anyway. I see that the recommended way is to use a global bool flag, and that makes sense.
Comment: @Neil assert looks like something I could benefit from. I will try that as well.
Comment: We normally don't use exception handling nor `assert` in embedded systems programming. You'll need a custom error handler suitable for the specific hardware (to print on UART, or a LCD or whatever).
Comment: Sequence verification you're expecting is a typical task for Unit Tests. For instance GTest has dedicated `InSequence` type which assures that `EXPECT_CALL`s are checked requiring the defined order. VectorVAST also allows to create SequenceTests for exactly this purpose.
Answer: #ifndef only checks whether this function was defined somewhere for the compiler and won't affect runtime.
best way to do this is through use of a global variable that changes value once the setup function is executed. if you're defining these functions in classes you could use static data member and setup function
Answer: C has a pre-processing command #error that can be used to trigger a stop to the compiling. However, the compilation unit is processed in order, not ran. Some programmes need to just run to see, (which is related to the halting problem.)
The idiomatic way to to runtime checks is with assert, as in this C99 example. (You would #include <cassert> in C++.)
#include <stdbool.h>
#include <assert.h>

static bool is_setup; // Can be optimized away with -D NDEBUG.

static void setup_function(void) {
    assert(!is_setup && (is_setup = true));
}

static bool operations(void) {
    assert(is_setup);
    return true;
}

int main(void) {
    //setup_function(); // Triggers `assert` if omitted.
    operations();
    return 0;
}

However, C++ has techniques that encourage RAII; when possible, one should generally use this to set up an object on acquisition and manage the object throughout it's lifetime.


Printing Scrolled Divs

Question: I have a web page that displays a long line graph inside a div with overflow-x: scroll.
This works well as a web page allowing the use to scroll back and forward through the graph.
However, when printing the page the scroll position is reset to zero.
Is there a way to overcome this?
Answer: I think you're going to have to specify an alternate CSS for printing where you somehow need to remove the overflow:
<link rel="stylesheet" type="text/css" href="sheet.css" media="print" />

However, maybe there is an approach with JavaScript or even Flash? If I understand correctly, you only want to have a part of the graph printed (the one "selected" by the user?) and not the full one? I'm pretty sure that's not possible with plain HTML/CSS, but I strongly believe that Flash or maybe JavaScript/AJAX (to only load a part of the image at a time) can solve it.
Answer: You can't do this in plain CSS -- you will have to reimplement the scrolling using your Javascript UI library of choice to get what you want.
The user state of the scrollbar isn't used when printing (think about it, if you're scrolled 3 screens down a page and hit "print" does it make sense for the browser to only print the part of the document that's in your window at the time?). However, if you use JS, which actually manipulates the DOM (i.e. sets the x-position offset to -293 if the person has scrolled right 293 pixels, just like style="left: -293px; overflow: hidden;" in CSS), then it will show up as such in printed documents.
My suggestion is, unless the graphs are very wide, just skip all of this nonsense and use a printer stylesheet with width: 100% for the graph's
 so the graph just shrinks to page width.
Answer: A simple approach would be to have some javascript which posts back to your page with the user's selected scroll position on a link saying something like 'setup for printing'. Then the server side returns a page with the graph relatively positioned at the scroll position with overflow:hidden to clip the graph appropriately.
Of course this would not work for users with javascript disabled - if you want to support this you would need the user to specify the scroll position in something like a text input element and submit button which you hid with javascript when enabled.
Answer: You need to temporarily turn the scroll position of the parent into a negative margin of the child, and put that parent as overflow:hidden.
Here's how to do it in Javascript (which is the only way, css cannot do that)
Note that you will need something to execute printDone() after the printing to restore everything as normal. You could trigger it with a wheel event e.g. because the user will only have a problem when trying to scroll. Or you can just put a button as I did, and show it only when printGo() is called.

Print

I'm done printing!

        Hello this is my content.

Printing Scrolled Divs


Linear Regression with Time Series Data

Question: I am in the process of completing an applied econometrics project and want to find the effects of my chosen independent variables (fertility, gender wage gap, years of schooling, etc) on my dependent variable (female labour participation rate).
I have 30 annual observations for each variable.
At first, I tried to find if a cointegrating relationship existed but there is none.
Would it be suitable to continue my project using OLS regression?
In addition to checking for autocorrelation, what else should I look out for?
Comment: Endogeneity could be a problem...
Answer: OLS assumes that your dependent variable is independent across your observations. In other words, if you perform OLS you're assuming female labour participation at year 1 is independent from year 2. This assumption is likely wrong when you're dealing with time series data like this.
When you have dependence in your dependent variables, this is called autocorrelation. There are sets of models called autoregressive models that can handle this. These models will outperform OLS when you have autocorrelation.
Comment: The error terms being independent is equivalent to the DV being independent when the IV are treated as fixed.
Comment: IMO fixed independent variables is a pipe dream infesting stats books. All estimation procedures depend on how the samples are distributed. What's your opinion @Richard ?
Comment: I don't think the first sentence is correct. Independence is usually assumed for error terms, not the dependent variable. [Wikipedia](https://en.wikipedia.org/wiki/Ordinary_least_squares#Classical_linear_regression_model) (scroll down to "Time series model") might not be the most reliable source when it comes to statistics, but it does not have any assumptions on the dependent variable besides stationarity and ergodicity.
Comment: The caveat *when the IV are treated as fixed* was worth mentioning. Also, IV here stands for *independent variables*, right? (I am more used to seeing IV in the context of *instrumental variables*.)
Comment: @CagdasOzgenc, I guess I have to agree. I wish I knew econometrics better to really grasp how serious the problem is in practice.

Linear Regression with Time Series Data


On affine local properties

Question: In learning the third section First Properties of Schemes of the second chapter of Hartshorne, I heard someone mentioned Nike's lemma (I don't know if I spell the name right): if a scheme $X$ has a property $P$ affine locally (i.e. there is an affine open cover $ \{ \operatorname{Spec}A_i \}$ of $X$, such that each $\operatorname{Spec}A_i$ has property $P$), then for every affine open cover $\{\operatorname{Spec}B_j\}$, each $\operatorname{Spec}B_j$ has property $P$. Is the statement correct? Is it right? Will someone be kind enough to give me some referrence on this lemma or say something on this (the proof, the applications, etc)? Thank you very much!
Comment: This depends on the property in question, but for most natural ones (e.g. being a finitely generated algebra over some base) it is true, and is a consequence of the "affine communication lemma" in Ravi Vakil's notes, for instance.
Answer: I believe that Nike's Lemma is Prop. 5.3.1 of Ravi Vakil's notes, namely the statement that the intersection of two affine opens can be covered by open sets that are simultaneously distinguished in both of the original affine opens --- see e.g. this post on Ravi's blog.  The actual statement that  you give in your post is not this result, but rather is an application of this result --- it is the affine communication lemma mentioned by Akhil Mathew in his comment above, which is Lemma 5.3.2 of Ravi's notes.  This lemma has many applications, which you can find by looking through Ravi's notes.

Regarding the origin of the name:
Nike is Vinayak "Nike" Vatsal, and the name the Nike trick for what is Ravi's Lemma 5.3.1 was coined by some of his fellow grad students while he was a grad student at Princeton (I think after he pointed it out during their joint study group on Hartshorne's book).  It was used (for example) under this name in Brian Conrad's algebraic geometry course at Harvard in the late '90s, and thus gained some currency among the current generation of American algebraic geometers (including Ravi Vakil).
Comment: For posterity: this is proposition 5.3.1. (pg. 157) in the most [recent](http://math.stanford.edu/~vakil/216blog/FOAGoct2415public.pdf) set of Vakil's notes; the affine communication is on the next page.

On affine local properties


Analyse ACF and PACF plots

Question: I want to see if I am on the right track analysing my ACF and PACF plots:

Background: (Reff: Philip Hans Franses, 1998)

As both ACF and PACF show significant values, I assume that an ARMA-model will serve my needs
The ACF can be used to estimate the MA-part, i.e q-value, the PACF can be used to estimate the AR-part, i.e. p-value
To estimate a model-order I look at a.) whether the ACF values die out sufficiently, b.) whether the ACF signals overdifferencing and c.) whether the ACF and PACF show any significant and easily interpretable peaks at certain lags
ACF and PACF might suggest not only one model but many from which I need to choose after considering other diagnostic tools

Having that in mind, I would go ahead and say that the most obvious model seems to be ARMA (4,2) as ACF values die out at lag 4 and PACF shows spikes at 1 and 2.
Another way to analyze would be an ARMA(2,1) as I see two significant spikes in my PACF and one significant spike in my ACF (after which the values die out starting from a much lower point (0.4)).
Looking at my in-sample-forecast results (using a simple Mean Absolute Percentage Error) ARMA (2,1) delivers much better results then ARMA(4,2). So I use ARMA(2,1)!
Can you confirm my method and findings of analyzing ACF and PACF plots?
Help appreciated!
EDIT:
Descriptive Statistics:
count  252.000000
mean    29.576151
std      7.817171
min     -0.920000
25%     26.877500
50%     30.910000
75%     34.915000
max     47.430000

Skewness of endog_var: [-1.35798399]

Kurtsosis of endog_var: [ 5.4917757]

Augmented Dickey-Fuller Test for endog_var: (-3.76140904255411, 0.0033277703768345287, {'5%': -2.8696473721448728, '1%': -3.4487489051519011, '10%': -2.5710891239349585}

Time-Series:

Residuals (ARMA (2,1):

ACF/PACF of Residuals:

EDIT II:
Data:
14.37561
23.95561
25.41561
13.88561
23.31561
33.12561
35.30561
35.78561
37.21561
35.23561
37.34561
38.28561
39.03561
36.34561
39.08561
39.34561
38.80561
40.10561
34.13561
35.42561
27.29561
34.13561
39.89561
47.77561
40.57561
36.15561
33.66561
30.97561
24.90561
23.41561
0.31561
8.45561
37.36561
33.40561
13.97561
11.62561
35.07561
36.15561
37.09561
36.95561
37.85561
32.31561
35.41561
36.35561
37.34561
35.90561
37.40561
36.44561
37.37561
36.16561
35.24561
38.47561
39.18561
39.61561
29.55561
35.50561
38.05561
40.32561
44.39561
37.65561
46.27561
29.41561
40.41561
33.44561
37.04561
35.34561
25.24561
30.23561
15.40561
26.79561
35.38561
40.22561
43.14561
36.96561
41.93561
11.30561
6.87561
32.92561
34.54561
38.27561
36.40561
25.44561
37.26561
26.39561
31.13561
35.90561
38.41561
33.66561
33.16561
31.96561
30.34561
37.77561
32.25561
33.21561
38.37561
36.63561
40.78561
35.60561
36.37561
34.42561
42.67561
33.40561
31.49561
24.81561
23.82561
37.34561
30.73561
21.04561
18.20561
27.36561
18.49561
25.41561
27.92561
29.42561
25.91561
27.56561
28.69561
29.89561
31.47561
29.34561
25.35561
21.98561
28.61561
33.87561
20.07561
27.36561
26.48561
20.37561
22.33561
28.52561
21.24561
10.77561
18.69561
30.19561
33.89561
29.81561
27.55561
22.37561
20.32561
22.43561
31.89561
32.10561
27.67561
36.93561
36.51561
26.96561
21.27561
34.68561
34.13561
35.80561
25.38561
33.42561
9.28561
8.70561
30.36561
30.29561
29.56561
28.41561
33.40561
18.47561
16.48561
18.51561
26.35561
25.40561
19.92561
21.26561
10.90561
32.71561
26.71561
29.99561
28.87561
28.55561
14.07561
10.97561
24.92561
26.40561
21.40561
29.08561
30.18561
30.27561
16.15561
21.96561
32.29561
29.57561
30.24561
30.82561
28.83561
27.30561
26.53561
28.39561
29.76561
29.50561
31.81561
34.79561
24.14561
31.34561
33.14561
35.04561
33.20561
33.53561
35.28561
29.84561
35.02561
33.63561
35.65561
35.73561
35.35561
37.18561
27.38561
34.40561
33.69561
29.05561
34.55561
31.76561
30.91561
34.70561
35.87561
28.31561
30.39561
28.03561
30.72561
30.57561
23.93561
25.11561
32.15561
26.74561
28.76561
32.49561
34.79561
27.90561
33.05561
29.50561
31.67561
34.36561
36.88561
32.31561
26.24561
26.66561
33.59561
37.64561
38.26561
36.20561
33.27561
29.94561
29.19561
27.41561
37.24561
36.26561
30.84561
35.46561
32.24561
31.44561
33.40561
30.71561
33.03561
36.43561
33.44561
22.32561
18.65561
31.97561
27.00561
29.66561
30.76561
33.44561
29.19561
12.32561
33.41561
37.13561
33.43561
37.35561
40.17561
29.38561
19.70561
35.44561
30.48561
30.72561
16.09561
30.82561
30.55561
34.38561
35.45561
34.87561
33.78561
33.87561
29.83561
26.35561
26.44561
28.72561
30.85561
28.18561
12.18561
31.82561
18.01561
27.57561
29.38561
20.32561
22.36561
34.01561
34.40561
20.23561
-0.57439
9.87561
29.55561
31.01561
30.00561
28.12561
13.47561
7.42561
22.01561
20.38561
27.57561
31.54561
29.90561
16.40561
21.27561
26.22561
31.47561
31.11561
32.97561
32.34561
29.36561
32.40561
31.16561
32.05561
31.78561
32.34561
33.87561
31.80561
29.90561
30.09561
32.36561
28.15561
26.30561
15.32561
31.03561
33.47561
33.44561
33.71561
28.30561
12.70561
10.17561
43.96561
9.58561
35.38561
33.82561
41.37561
33.40561
33.64561
20.30561
27.85561
29.01561
32.36561
28.33561
29.90561
27.19561
0.39561
8.40561
0.24561
11.87561
29.15561
20.40561
0.42561
29.29561
23.39561
19.36561

Comment: Data look a bit left-skew, perhaps nonstationary. It looks to me like there's some potential issues with the residuals, perhaps even conditional heteroskedasticity.
Comment: In my opinion the skewness suggests anomalous values (pulses) which can only be confirmed by analysis of the original data.
Answer: The sole reliance on the ACF and PACF using tools suggested in the mid 60's is sometimes but seldomly correct except for simulated data. Model Identification tools like AIC/BIC almost never correctly identify a useful model but rather show what happens when you don't read the small print regarding the assumptions. I would suggest that you start as simply as possible BUT not too simply and estimate a tentative model ; AR(1) as suggested by Glen_b . The residuals/analysis from this tentative model can be used to compute yet another ACF and PACF suggesting potential model augmentation or model simplification. Note that interpretation ala your references REQUIRE that the current series/residuals are free of any deterministic structure i.e.  Pulses, Level Shifts, Local Time Trends and Seasonal Pulses and furthermore that the series has constant error variance and that the parameters of the tentative model are invariant over time. If you wish you can post your data and I will attempt to help you form a useful model.
EDIT AFTER DATA WAS REPORTED :
365 values were delivered and analyzed, yielding the following AR(1) model with identified Pulses and 2 Level Shifts . . note that this had been a popular guess . The residuals from this model are plotted here . There is a suggestion of variance hetero-scedasticity but this is a symptom and one needs to find the correct cure which we will ultimately find. Proceeding the acf of the residuals shown here  exhibits a suggestion of model inadequacy. A closer look at the table of the acf of the residuals is here  suggesting structure at lags 7 and 14. Putting the the two clues together ( sample size of 365 and significant weekly i.e. lag 7 structure ) I decided to investigate whether or not this was indeed daily data. New users often omit very important information when they define their data on the mistaken premise that the computer should be smart enough to figure everything out. Note that the lag 7 and lag 14 clues were swamped in the OP'S ACF and PACF plots. The presence of deterministic structure in the residuals increase the error variance thus suppressing the acf. Once the outliers/pulses/level shifts were identified the acf revealed the presence of an autoregressive structure /daily indicators which then needed to be accounted for.
I then analyzed the data allowing the software to proceed with the clue that it was daily data. With only 365 values it is not possible to properly construct models containing seasonal/holiday predictors BUT that is possible with more than 1 year of data.
The model that was found is presented here  containing 5 daily dummies , two Level Shifts , a number of pulses and an arima model of the form (1,0,0)(1,0,0) . The plot of the residuals no longer evidences the non-constancy structure as a better model is in place. . The acf of the residuals is much cleaner . The Actual /Cleansed graph highlights the unusual pulse points.  . THe lesson here is that when one analyzed the data without the critical piece of information that it was a daily time series there were a ton of pulses reflecting an inadequate representation (or perhaps the advanced knowledge of the daily clue ) . The Actual/Fit and Forecast is presented here .
It would be interesting to see what others would do with the same data set. Note that all  analyses were conducted in a hands-free mode using software that is commercially available.
Comment: early morning mis read ... Don't normally see the lag(0) in my graphs
Comment: It tricked me at first as well.
Comment: Thanks for your answer. As someone without experience in the field of time-series forecasting it is hard to fully understand the procedure of choosing the right model as there is no officially right way to go. Unfortunately i am not allowed to post my raw data. I hope that the additional information is useful (see 'EDIT:')
Comment: You can scale/mask your data before you present it. Looking at the plot it appears there might be some unusual values which if untreated downwards biases the acf and the pacf incorrectly suggesting sufficiency. There is a visual suggestion of a downwards trend followed by no trend but that is just a guess at this moment.
Comment: i just added some data which you might use..
Comment: Thanks for your valuable information. You are right, the time series is based on daily values.
Comment: there is no better method BUT one need to use the ACF.PACF of the outlier adjusted series see https://stats.stackexchange.com/questions/317734/interrupted-time-series-analysis-arimax-for-high-frequency-biological-data/317804#317804 for @Adamo's wise words because the original data/acf.pacf are tarnished by the anomalies .
Comment: @IrishStat You said: "The sole reliance on the ACF and PACF [...] is seldomly correct [...] Model Identification tools like AIC/BIC almost never correctly identify a useful model."
If one has a series with no innovations, variance changes, or breaks that change parameters, is there a published method that is better than using ACF, PACF, and AIC?
Answer: It looks to me like you're counting the spikes at lag 0.
Your PACF shows one reasonably large spike at lag 1, suggesting AR(1). This will of course induce a geometric-like decrease in the ACF (which, broadly speaking, you see). You seem to be trying to fit the same dependence twice - both as AR and MA.
I'd have just tried AR(1) on that to start with and seen if there was anything left worth worrying over.
Comment: Peter; my answer had a typo in it (I had AR(1) correct in the last para, but typed MA(1) in the second paragraph), which is fixed now.
Comment: Thanks for your answer. Counting from lag 0 is of course a cardinal mistake! I tried AR(1) and the result was not as good as ARMA(2,1)!
Comment: It may well be the case that it's not as good - nevertheless, the AR(1) would be the place to start. What did the PACF of residuals look like, for example? What does the original series look like? There's much that might be going on that can't be gleaned easily from an ACF and PACF of the data.
Comment: Thanks. I posted some additional information which might lead to new insights.
Answer: Looking at your ACF and PACF is useful in the full context of your analysis as well. Your Ljung-Box Q-statistic; p-value; confidence interval, ACF and PACF should be viewed together. For instance the Q test here:
acf, ci, Q, pvalue = tsa.acf(res1.resid,
  nlags=4, confint=95,  qstat=True,
  unbiased=True)

Here - our Q test for autocorrelation is an overall gut check of our graphical interpretation.
Draft notes on Time Series analysis in Statsmodels:
http://conference.scipy.org/proceedings/scipy2011/pdfs/statsmodels.pdf

Analyse ACF and PACF plots


How do I design a reward function given two parameters

Question: We want to design a reward function R(x, y) where $x \in [0, 1]$ and $y \in (0, 10000)$ such that x is the dominant term when its value is close to or equal to 1, whereas y is dominant when x is small.
The problem I'm trying to solve is that given pairs $(x_1, y_1), (x_2, y_2), ...$, I want to select the best pair. Ideally, the best pair should be one with x = 1, and y = 10000. We care about x more when it's very close to 1, and in this case y can be ignored. On the other hand, when x is not close to 1, we want to have a tradeoff between x and y.
Answer: Try $x + (1-x)y$.  You can make it more complicated in many ways e.g. $x^a + D*(1-x)^b y^c$, but start simple.


Grafana OAuth: Self Signed Certificate

Question: Brief

I am running Grafana on Docker
I am connecting Keycloak with Grafana for signin
I have followed all steps at https://grafana.com/docs/grafana/latest/auth/generic-oauth/ and it works fine

Problem

For HTTPS I have a self signed certificate at Keycloak
At djnago I have this as REQUESTS_CA_BUNDLE=path_to_ca

Within Grafana I am forced to set GF_AUTH_GENERIC_OAUTH_TLS_SKIP_VERIFY_INSECURE=true as I cannot find a way to mention CA path
Is there any way to set CA file path?
Comment: Update: I am running Grafana on Docker
Answer: Grafana backend is written on Golang, which tries to use system CA certificates - https://golang.org/src/crypto/x509/root_linux.go:
// Possible certificate files; stop after finding one.
var certFiles = []string{
    "/etc/ssl/certs/ca-certificates.crt",                // Debian/Ubuntu/Gentoo etc.
    "/etc/pki/tls/certs/ca-bundle.crt",                  // Fedora/RHEL 6
    "/etc/ssl/ca-bundle.pem",                            // OpenSUSE
    "/etc/pki/tls/cacert.pem",                           // OpenELEC
    "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
    "/etc/ssl/cert.pem",                                 // Alpine Linux
}

So just try to add your own custom CA used for Keycloak to your system CA certs.
Comment: I am using Grafana Docker, would that mean any thing different?
Comment: No, also Grafana image contains own CA certs. It is the same - "mount" correct CA certs to the correct path in the container.
Comment: When configuring alert contact points, a contact point with a self signed root CA will trigger this error failing to post the webhook.
Adding root CAs may vary slightly across distros.
Copy the cert to /etc/pki/ca-trust/source/anchors
Then run sudo update-ca-trust extract
This should update the files in /etc/pki/ca-trust/extracted/... which are typically linked back to /etc/pki/tls/certs
Cert not a root CA will fail to be extracted
You can verify your root CA prior with OpenSSL openssl x509 -noout -text -in  | grep --after-context=2 "X509v3 Basic Constraints" | grep "CA:TRUE"

Grafana OAuth: Self Signed Certificate


Rails Console não carrega os métodos e classes da minha aplicação, por que?

Question: Eu tenho um model chamado Person, quando abro o Rails Console e tento atribuir-lo à uma variável qualquer, recebo isso:
user.localapp (test) $ rails c
Loading development environment (Rails 4.2.0) (Ruby 2.2.0)
localapp> a = person.first
NameError: undefined local variable or method `person' for main:Object
from (irb):1

Alguém sabe porque?
Answer: person é uma variável que não existe. Você tem de chamar o método da classe:
person = Person.first

Isso vai te trazer a primeira Person do seu banco de dados.
Comment: Vlw deu certinho!
Answer: Use Person (primeira letra maiúscula) ao invés de person (primeira letra minúscula)
a = Person.first

Comment: Vlw deu certinho!


PROBLEMA COM FGETS no C

Question: #include <stdio.h>
#include <stdlib.h>

/*definir operador lógico para chuva (1 para TRUE e 0 para FALSE) */

#define TRUE (1==1)
#define FALSE (!TRUE)

struct eventos_atm_st {
float temp;
float press;
int chuva;
int mm_prec;
char nome[200];
};

typedef struct eventos_atm_st eventos;

void ler_estrutura(eventos *dados){
printf("Qual temperatura?\n");
scanf("%f", &dados->temp);
printf("Qual pressao?\n");
scanf("%f", &dados->press);
printf("choveu?\n");
scanf("%d", &dados->chuva); /*definir 1 para true e 0 para false */
printf("Qual mm_prec?\n");
scanf("%d", &dados->mm_prec);
printf("Qual nome?");
fgets(dados->nome,200,stdin); /*problema, está ficando algum "lixo de memória" que não deixa meu fgets capturar o nome*/

}

int main(){

eventos node[3];
int i;

for(i=0;i<3;i++){
ler_estrutura(&node[i]);
}

return 0;
}

Comment: Primeiro, [não misture `fgets` com `scanf`](https://pt.stackoverflow.com/a/87974/132). Depois, [veja aqui como resolver isso](https://pt.stackoverflow.com/q/69093/132).
Comment: Ah, e só para esclarecer. Não fui eu quem negativou você. Pelo contrário, considero a sua dúvida válida.
Answer: Como Resolver
Esse problema é causado pelo próprio funcionamento de scanf. Para resolvê-lo, basta modificar este trecho de código:
scanf("%d", &dados->mm_prec);
printf("Qual nome?");
fgets(dados->nome,200,stdin); /*problema, está ficando algum "lixo de memória" que não deixa meu fgets capturar o nome*/

para:
scanf("%d", &dados->mm_prec);
fflush(stdin);
printf("Qual nome?");
fgets(dados->nome,200,stdin); /*problema, está ficando algum "lixo de memória" que não deixa meu fgets capturar o nome*/

A função fflush serve para limpar um fluxo de dados, no caso o fluxo stdin, que é o fluxo do qual você quer ler os dados necessários para o funcionamento do programa. Ao usar fflush antes de fgets, você estará limpando o lixo criado por scanf.
O que ocasiona o problema?
O problema está na própria função scanf. Analise, por exemplo, a seguinte chamada para a função scanf:
scanf("%d", &variavel);
Faz exatamente o que você pediu: Ela lê inteiros: Números que você digitar em stdin. Por isso, quando você digita:
450
E aperta enter, qual foi a string criada nesse processo? Oras, se scanf só lê os números que foram digitados pelo usuário, ela obtem os seguintes caracteres de stdin:
4, 5 e 0
Mas ela ignora o seguinte caractere, que não é um número:
\n
É isso mesmo! Quando você aperta a tecla enter para que scanf realize sua leitura, scanf ignora o enter inserido em stdin. Portanto, o stdin passa de:
450\n
Para:
\n
Assim, quando fgets for ler a string que o usuário supostamente deveria ter digitado, ele já encontra o caractere de nova linha \n em stdin, que foi deixado para trás por scanf. Desta forma, fgets é basicamente "ignorado" pelo seu código. É por isso que você deve usar fflush após scanf: Para limpar esses resquícios deixados por scanf.
Comment: Muito obrigado!!!
Comment: Fico contente por ter ajudado! Se tiver dúvidas, é só perguntar

PROBLEMA COM FGETS no C


Unique Linear Map- Linear Algebra

Question: Let $E = {e_1, . . . , e_n}$ be a basis for $\mathbb{R}^n$
, and let $v_1, . . . , v_n$ be arbitrary vectors in
$\mathbb{R}^m$.
Prove that there is a unique linear map $T : \mathbb{R}^n \rightarrow \mathbb{R}^m$ such that $T(e_i) = v_i$ for all $i = 1, . . . , n$
This feels like such a trivial question just what's the point of it?
I didnt really know what to do but after stumbling around for a few mins not knowing what exacly I was trying to show-
You can work backwords to $T(\lambda_1e_1+\lambda_2e_2+...+\lambda_ne_n)=\lambda_1v_1+\lambda_2v_2+...+\lambda_nv_n$.
Which apparently is enough to show that you have found a linear map- why? All I did was play with properties of linear transformations.
Main Question:
I reckon the key reason of this is that $E = {e_1, . . . , e_n}$ is a basis and you can represent every vector in $\mathbb{R}^n$ as $\lambda_1e_1+\lambda_2e_2+...+\lambda_ne_n$ for arbitrary $\lambda_i$.
$\lambda_1v_1+\lambda_2v_2+...+\lambda_nv_n$ is a vector in $\mathbb{R}^m$ since each $v_i$ is in $\mathbb{R}^m$
So you have a map which is linear and takes every vector in $\mathbb{R}^n$ to one in $\mathbb{R}^m$ .
Is this the reason? Or am I misunderstanding the crux of why $T(\lambda_1e_1+\lambda_2e_2+...+\lambda_ne_n)=\lambda_1v_1+\lambda_2v_2+...+\lambda_nv_n$ constitutes a proof that I have found a linear map $T : \mathbb{R}^n \rightarrow \mathbb{R}^m$.
Second Question:
I now wish to show that this linear map is unique
Assume there exists another linear map $S$.If it must satisfy the properties stated in beginninig then there is no choice but for $S(\lambda_1e_1+\lambda_2e_2+...+\lambda_ne_n)=\lambda_1v_1+\lambda_2v_2+...+\lambda_nv_n$ to hold.
Since $S(v)=T(v)$ for all $v$ in $\mathbb{R}^n$ they are same linear transformation and so T is unique.
Is this fine also?
If not I would really appreciate feedback on it and better/correct solutions. Thanks
Comment: How are $n$ and $m$ related? Is $n<m$ or $n\geq m$ or what?
Comment: @CC0607 does it really matter? The question doesnt specify anyway
Answer: You are exactly right. You have defined $T:\mathbb{R}^n\to\mathbb{R}^m$ as:
$$T(\lambda_1e_1+\cdots\lambda_ne_n) = \lambda_1 T(e_1)+\cdots+\lambda_n T(e_n) = \lambda_1v_1+\cdots+\lambda_nv_n,$$
which by definition makes it linear. You proof that $T$ is unique is correct also. What you haven't checked is if your mapping is well defined (although it'll probably hardly take you any time). That is, if $v=w$, then $T(v)=T(w)$.
The important idea to take away from this question is that any linear transformation between finite dimensional vector spaces is uniquely determined by where it sends the basis vectors.
Furthermore, if $V$ and $W$ are finite dimensional vector spaces, such that
$$\dim{V}=\dim{W}=n,$$
and
$$B_V = \{v_1,...,v_n\}\quad\text{and}\quad B_W=\{w_1,...,w_n\}$$
are bases for $V$ and $W$ respectively, then defining $T(v_j) = w_j$ automatically makes $T$ an isomorphism.
Comment: How do I show it's well defined? Prove that if $v= $ $\lambda_1e_1+\lambda_2e_2+...+\lambda_ne_n$ and $w=v $Then it must also be written uniquely in the same way as $\lambda_1e_1+\lambda_2e_2+...+\lambda_ne_n$ since $E$ is a basis. Proof: Assume $w= $ $\mu_1e_1+\mu_2e_2+...+\mu_ne_n$ Then $(\lambda_1-\mu_1)e_1+(\lambda_2-\mu_2)e_2+...+(\lambda_n-\mu_2)e_n=0$. Since $E$ is a basis and $e_i$ are linearly indep. Then $\lambda_i=\mu_i$ QED. So clearly both $T(v)$ and $T(w) $ map to $\lambda_1v_1+\lambda_2v_2+...+\lambda_nv_n$
Comment: @Arcane1729 That is perfect. Nice job.
Answer: I want to point that it is a very general fact:
Let $A$ be a commutative ring. For any free $A$-module $L$, with basis $(e_i)_{i\in I}$ ($I$ finite or not) and for any $A$-module $E$, then
\begin{align*}\mathcal L_A(L,E)&\longrightarrow E^I\\
f&\longmapsto \bigl(f(e_i)\bigr)_{i\in I}
\end{align*}
is an isomorphism of $R$-modules.
The proof is strictly the same as  for vector spaces over a field. The only difference is in the applications, since, unlike vector spaces, modules do not necessarily have a basis.
Comment: Ah I am but a humble first year undergrad haha- rings and modules is next year. I am sure it will be interesting to come back and understand
Comment: As I didn't know you grade level, I just wanted  to show the more general context, not to give a real proof. That said, once you know what is a module over a ring, it is the same proof as for vector module. Incidentally, the difference between modules and vector spaces, is that scalars are in a ring instead of being in a field, say $\mathbf R$ (i.e. you do not always have inverses for non-zero elements).

Unique Linear Map- Linear Algebra


How to upgrade angular version while keeping angular/cli one

Question: I'm struggling to install the right version of angular, I often get errors like This version of CLI is only compatible with Angular versions ^11.0.0-next || >=11.0.0 <12.0.0, but Angular version 9.1.1 was found instead.
I installed angular using npm -g install @email@example.com (as package.json of the project said was necessary), but when i do ng --version in the project, I have
Angular CLI: 11.2.1
Node: 14.15.5
OS: win32 x64
Angular: 9.1.1

I don't really understand what's going on, any help would be greatly appreciated
Answer: You can update angular CLI globally

uninstall CLI

npm uninstall @angular/cli -g

install CLI to specific version

npm install @angular/cli@~9.1.0 -g

Comment: Doesn't work, I somehow still have the same error message in my project
Comment: if it not work you can update your angular project, https://angular.io/cli/update
Comment: I could, but since it's a group project, I would rather not force everyone to update to a newer version if i'm the only one facing the issue


mysql interrupt myisamchk and re-run it later?

Question: I'm running myisamchk to one table using SSH terminal on my laptop, I need to leave soon and it seems like it's taking a bit longer then I expected, is there a way to sort of interrupt it and re-run it under screen or something?
Answer: You can't move a process into a screen session, but you can background it and then disown the process with disown <pid>, which will stop the process from dying when you logout.
SEE ALSO
bash(1)
Comment: how do I do that?
Comment: Answer updated.
Answer: You basically can't, as it wasn't started under a utility such as screen or nohup; the process is locked into your tty at this point and can't be transferred to another as myisamcheck has no built-in facility for pausing it's operation mid-run. I've often wished I could do this with many tasks that I didn't realize were going to take hours...


Why do AES decryption methods take IVs as arguments

Question: I'm still new to encryption in general, and I understand why an IV is necessary, but isn't the IV embedded in the encrypted data? Thus, shouldn't any decryption implementation first extract the IV from the data rather than needing to have it supplied?
The reason I assume the IV is embedded in the data is because certain libraries/tools do not require that it be supplied, for instance CryptoJS for JavaScript: CryptoJS.AES.decrypt("U2FsdGVkX1/l3HWODO9GX23rvF0KHmDR6z8XTpYYpe8=", "password").toString(CryptoJS.enc.Utf8));
and openssl: echo "U2FsdGVkX1++pGg+oWqZbIjccV1NiV2pc1QrQtw0wp4=" | openssl aes-256-cbc -d -a -pass pass:password
and really any actual app that does AES encryption, like TrueCrypt.
Libraries that seem to require the IV:

mcrypt for PHP: https://www.php.net/manual/en/function.mcrypt-decrypt.php
SymmetricAlgorithm in .Net: http://msdn.microsoft.com/en-us/library/79w421xb%28v=vs.110%29.aspx

am i getting something confused?
Comment: A *common* *convention* is to prepend the IV onto the start of the encrypted data. That doesn't mean its the only way that the decrypting side can or will obtain IV data, nor that the encrypting side will automatically do that. If you only support reading the IV inline with the encrypted data, then some users may be forced to allocate buffers and copying data around just to satisfy your library that insists that the IV must be at the start of the data.
Comment: @Damien_The_Unbeliever Well... that's a nice answer, in a comment. Care to post it so I can up-vote and take this off the unanswered list?
Comment: @Duncan - I posted the comment whilst trying to decide on a close reason. I still haven't picked one, but it still feels (to me) like it's not a good fit for SO, being as it's more about language/library design.
Comment: Yeah I thought about posting this in Information Security, but I decided I was really asking about the object models which is more of a programming thing.
Answer: No, the IV may be derived as well. The only reason to include the IV with the ciphertext is when the key is reused for encryption and when the IV cannot be derived. It is common but not standardized or required to prefix it if it is present. But that's when you need the IV, so it's the de-facto standard none-the-less.
In your OpenSSL example a random salt is used to generate a key from a password. In that case the salt is different for each encrypt, so the key is random as well. In that case an randomized IV is not needed, although it can (and will be for OpenSSL) derived from the salt and password as well.
Other protocols contain a counter, and in that case a single block encrypt over the counter can be used to create an IV for CBC mode encryption. As long as the counter stays the same at sender/receiver, there is no need to send the IV.
And there are plenty cryptograhic implementations that get it wrong and don't use a random IV for CBC mode. PHP mcrypt_encrypt is special in the sense that it even requires an IV for ECB mode, which is then thouroughly ignored as ECB does not use an IV anywhere in the algorithm.
Comment: I don't understand why there would be a "convention" to prepend the IV, thus modifying the actual contents of the data, thus breaking the standard?
Comment: You have to store it somewhere if you cannot regenerate it; which standard would you break? It's not standardized to put it in front, but that does not mean that it is standardized *not* to put it in front.
Comment: I just thought that the standard would cover the actual contents of the encrypted file. I guess it's supposed to be more flexible than that... But to me it seems like it just makes it so one encryption library can't talk to another, which would be the point of having standards in the first place...
Comment: If you want to have standard message format, use CMS, PGP or XML encryption. Of course, not every language/runtime has support for those, but the standards are in place. It's just the low level encryption schemes without container format that suffer from these kind of issues.
Comment: having explored this further, my problem was that i did not understand that since AES is fast, a password (that i can remember) will never have enough entropy to not be solved with brute force. so while my question was a programming question, my problem was an information security/cryptography one.
Comment: Glad you seem to understand that now...that's pretty important to realize :)


Drupal 8, The file used in the Image field may not be referenced

Question: I am using managed file type to upload image in my custom form (Drupal-8). I am able to retrieve the given image while editing by using the below code
<code>$form['image_field'] = array(
   '#type' => 'managed_file',
   '#title' => t('Image'),
   '#default_value' => array($fid),
);
</code>
While i am trying to save once edit, i am getting the "The file used in the Image field may not be referenced." error.

Please let me know to over come this error and let me what this error trying to convey.
Answer: Check \Drupal\file\Element\ManagedFile for answer, it appears that your file is being saved as permanent, but there is no entry in file_usage table:
<code>if ($file = File::load($fid)) {
      if ($file->isPermanent()) {
        $references = static::fileUsage()->listUsage($file);
        if (empty($references)) {
          // We expect the field name placeholder value to be wrapped in t()
          // here, so it won't be escaped again as it's already marked safe.
          $form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
        }
      }
    }
</code>
If you want to store your files permanently, you need to make sure they've got usage entries, to do so, you can tweak you form submit handler a little bit, here's some quick example:
<code>// get file fid wherever it is
$values = $form_state->getValues();
$fid = $values['my_file_field'];

// call file usage service and load file
$file_usage = \Drupal::service('file.usage');
$file = File::load($fid);

// set file status permanent
if(!$file->isPermanent()){
  $file->setPermanent();
}

// check file usage , if it's empty, add new entry
$usage = $file_usage->listUsage($file);
if(empty($usage)){
  // let's assume it's image
  $file_usage->add($file,'mymodule','image',$fid);
}
$file->save();
</code>


How can I use webform to upload assets and create a project that can be assigned to different users

Question: I am trying to put together a creative request form that a client would fill out. A studio manager would then follow up and assign to a project manager. I am using webform and rules as a starting point with the possibility of using Open Atrium.
Answer: if you want client submissions to become content I recommend EntityForm Then you could use for example the Workbench module to assure the content is moderated by a manager into approval.
You likely want your content type to show limited items to the client and then more options to the manager. I would try to do this with the Field Permissions module.
Lastly you could automate sending emails and stuff on some events if you want using Rules.


trouble with JavaScript innerHTML to image replacement

Question: I am new to JavaScript and am doing a project for a class. I want to create an Easter egg somewhere on the page that when clicked changes the whole page code to a single image. This is my code just to test out the concept:

The button below changes the whole page.

    <button type = "button" onclick = "changePage()">Click Here</button>

The content isn't replaced by the image stop.jpg, however when I change the line to:
document.getElementById("all").innerHTML = "
Whatever
";

The code changes to the simple heading with no problems. Any idea why?
Answer: Didn't you notice that quotes are repeating? You should wrap your img with another quotes:
''

Or escape them
""

Answer: The problem is with your quoting. The double quotes around the stop.jpg URL are ending the string that begins with <img. You need to use single quotes or escape the quotes:
document.getElementById("all").innerHTML = "";

document.getElementById("all").innerHTML = "";

Didn't you get a syntax error in the Javascript console? Or notice the changed color in SO's syntax highlighting?
Comment: Oh OK. Wow I feel uneducated now. I don't know why I didn't think of that. Thanks, works now! :D
Comment: Haha sorry, just commented on the first one I read. Thanks to you both! And no I didn't get a syntax error, I'm simply using Notepad++ to create/edit my files.
Comment: You should have gotten a syntax error when you tried to load your page. Don't you check the Javascript console in the browser when you're trying to debug Javascript?
Comment: No, I don't know about the javascript console. When I said I'm new, I meant like just started using JavaScript this morning. lol


Mostrando o resultado de acordo com o carregamento e não esperar a finalização do script pra exibir os resultado na tela

Question: A minha dúvida é a seguinte: o código está funcionando como esperado o problema quando eu coloco uma lista grande de email (100) a página fica toda em branca "Carregando" e só me retorna o resultado depois que o script termina de ser executado,  preciso de uma solução que me possibilite me mostrar o resultado conforme o loop e passando na tela.
Pensei em utilizar o jQuery para poder automatizar enviando 1 por 1 e ir mostrando o resultado penso que dessa forma o servidor não vai sobrecarregar.
Não sei o que fazer agora, mas preciso de uma ajuda de pelo o menos saber o que pesquisar e qual função devo utilizar para ir carregando os dados dinamicamente.
O código é esse aqui abaixo:
 $email = explode("\n", $to);
 $headers .= "From: ".$nome." <".$de.">\r\n";
 $message = stripslashes($message);

 $i = 0;
 $count = 1;
 while($email[$i]) {
     $ok = "Ok!";
     if(mail($email[$i], $subject, $message, $headers))
       echo "Aguarde: $count ".$email[$i]." Email Enviado

";
     else
       echo "Aguarde!: $count ".$email[$i]." Email não enviado.

";
     $i++;
     $count++;
 }
 $count--;
 if($ok == "ok")
   echo "";

Comment: Um jeito de resolver de forma simples é executar o envio dos emails em background por meio de cron/schtask e, a cada envio guardar o resultado numa base de dados. Por meio de outro script faria as consultas via ajax. Dá para ver tudo em "tempo real" com um pequeno delay. O problema é a enorme quantidade de requisições. Para reduzir esse consumo, usa-se técnicas de long-polling mas para esse caso onde os emails tem que ser enviados o mais rápido possível, vai dar na mesma. Talvez melhor uma regra onde espera enviar uns 20 ou 50 e retornar então o resultado desse grupo numa única requisição.
Answer: Se a intencão fôr ir vendo cada mail que foi enviado no lado do cliente então uma solução é jQuery/JavaScript usando AJAX para controlar a velocidade de envio. Por exemplo enviando um novo email a cada sucesso do pedido AJAX anterior, ou até mesmo criando um curto tempo de espera entre cada envio.
Nesse cado seria necessário ter os emails numa array por exemplo no lado do cliente, ou ter somente o numero total de mails e ir enviando pedidos ajax com o numero que deve ser enviado a cada vez.
Assim no PHP seria importante exportar uma variável global com os mails ou com o numero máximo:
<?php echo ''; ?>

e num ficheiro PHP á parte (que seria para tratar os pedidos ajax):
if (!isset($_POST['nr'])) die('Erro no pedido ajax');
$i = $_POST['nr'];
if(mail($email[$i], $subject, $message, $headers))
     echo "Aguarde: $count ".$email[$i]." Email Enviado

";
 else
     echo "Aguarde!: $count ".$email[$i]." Email não enviado.

";

E a parte do jQuery/JavaScript seria algo como:
var totalMails = 100; // isto vem do PHP
function enviarPedido(nr) {
    $.ajax({
        type: "POST",
        url: "enviador.php",
        data: {
            nr: nr
        }
    }).done(function (msg) {
        $('#div_resultado').append(msg);
        if (totalMails > 0) enviarPedido(totalMails--);
    });
}
enviarPedido(totalMails--); // assim começa em 100 e vai diminuindo até 0

Answer: Esse é um exemplo bem fácil de interpretação e adptação. Veja:
<?php
    ob_implicit_flush(true);
    set_time_limit(0);
    $results=1200;
    for($i=0;$i<1200;$i++)
    {
        ob_start();
        echo $i;
        sleep(1);
        ob_end_flush();
        ob_flush();
    }
?>


Is standard deviation relative to the mean?

Question: I am working with real estate asset values and prices are in millions of \$.
Typical commercial Asset values are \$10m, \$12m, \$15m, \$9m. Would my standard deviation in this case also be in millions and would it be relative to the mean?
I typically hear 1/2/3 std deviations, so wanted to confirm how std is expressed for large values such as asset prices.
Comment: Standard deviations aren't relative to anything!  Although it's common to *compute* them with formulas involving mean centering, they can be computed without reference to the mean at all: and that demonstrates the mean is not an essential feature of the SD.
Answer: Standard deviation is just the number outputted by that $s=\sqrt{\dfrac{1}{n-1}\sum_{i=1}^n(x_i-\bar x)^2}$ formula. If it's in the millions, so be it.
(There are other ways to calculate standard deviation, but this is the most common.)
What you hear is when people use standard deviation as a unit. If the standard deviation is a million, then two standard deviations above the mean is two million above the mean.
Comment: @kms If the variable is in *millions of dollars* (say), then yes, the standard deviation you calculate will also be in *millions of dollars*. It's a measure of spread - of 'typical distance' values are apart (but not the actual average distance between values). It's not added to the mean unless you choose to add it to the mean. Why would you be doing that?
Comment: Yeah, when I calculate it using that formula, it's is in millions. However, i was wondering if that's how it's expressed as well. Do I say std of 3 million?
Comment: No, it's just 3 standard deviations, the value of which happens to be a million. It's a measure of how far from the mainstream you are. Being a million above average might sound like a lot, but if you have a standard deviation of a million and a normal distribution, you are not that far above average relative to the variability of the distribution.


C: read json array using fscanf

Question: I have an JSON array of arbitrary length in a file like this:
[ 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18 ]
I want to get the integers and store them in an new array.
I tried using fscanf(f, " [ %d , ", data); to capture the first integer but the fscanf returned -1 (using gcc on Ubuntu terminal).
Is the format specifier wrong? How to skip the square brackets and use comma to separate different integers?
My code here:
typedef struct {
    int *data;
    unsigned int len;
} intarr_t;

intarr_t *intarr_load_json(const char *filename) {

    if (filename == NULL) {
        return NULL;
    }

    FILE *f = fopen(filename, "r");

    if (f == NULL) {
        printf("file open failed\n");
        return NULL;
    }

    int char_input = 0;
    int count = 0;
    int num_count = 0;

    //count the # of numbers in the file by counting # of ","
    while ((char_input = fgetc(f)) != EOF) {
        if (char_input == 44) {
            count++;
        }
    }

    num_count = count+1;

    printf("num_count is %d\n", num_count);

    intarr_t *intarr_loaded_json = malloc(sizeof(intarr_t));

    if (intarr_loaded_json == 0) {
        return NULL; // intarr_loaded_json malloc failed
    }

    if (num_count == 0) {
        intarr_loaded_json->len = num_count;
        intarr_loaded_json->data = NULL;
        return intarr_loaded_json;
    }

    intarr_loaded_json->len = num_count;
    intarr_loaded_json->data = malloc(sizeof(int) * num_count);

    if (intarr_loaded_json->data == 0) {
        printf("Malloc failed\n");
        return NULL;
    }

    int a = 0;
    int b = 0;
    int i = 0;
    //char temp;
    int value = 0;

    //printf("a is %d\n", a);

    if ((a = fscanf(f, "[ %d , ", intarr_loaded_json->data + i) > 0) {
        printf("got first number\n");
        i++;
    }

    //printf("temp is %c\n", temp);
    printf("a is %d\n", a);

    while ((b = fscanf(f, " , %d", intarr_loaded_json->data + i)) == 1) {
        i++;
        printf("do while loop %d th time\n", i);
    }

    printf("b is %d\n", b);
    // printf("intarr_loaded_json->len is %d\n", intarr_loaded_json->len);

    return intarr_loaded_json;

    fclose(f);
}

Comment: Welcome to Stack Overflow.  Please read the [About] and [Ask] pages soon, but more urgently, read about how to create an MCVE ([MCVE]).  What you've provided is too fragmentary for much analysis to be possible.  We need more information to help you — help us to help you by providing it.
Comment: In general, trailing white space on a `scanf()`-family format specification is a bad idea.  However, it is not formally incorrect, and should work.  What is surprising is the use of `*data` — you've not shown how `data` is defined.  It would be more normal to use `&data`, or just `data`.  To use `*data` implies that the code was passed a pointer to a pointer, allocated space for the data, and now initializes that in the shown call to `fscanf()`.  But something went wrong and `-1` was reported — that means EOF or a hard error was detected (is `f` initialized correctly?).
Comment: Use some JSON library. Like [jansson](http://www.digip.org/jansson/) or many others
Comment: Thanks for adding the code.  The problem was unsolvable with the original two lines of code; with the full code, it is not too hard to spot the problem.  That's why the MCVE is important.
Comment: data is the pointer to an array previously malloc'd (apologize for the careless mistake). f is a stream initialized by fopen correctly.
Answer: You read through the file as far as EOF in order to count the number of commas.  You never rewind the file, so you're at the end of file when you start trying to read the [, and fscanf() correctly returns EOF (aka -1 — technically, EOF can be any negative number, but in practice it is always -1).
Add rewind(f); before trying to read the data a second time.
Or, better, don't do the counting up front — allocate more space as needed, usually doubling the size of the allocated array each time you need more space to avoid quadratic copying behaviour.
There could be other problems — more serious than the use of if (char_input == 44) instead of if (char_input == ',') or the misplaced and non-reachable fclose(f);.  But the primary one is you've read to EOF and you don't rewind before trying to reread the data.
Comment: It worked. I used realloc() instead of counting # of integers. Thank you for pointing to my errors and providing strategy

C: read json array using fscanf


Windows equivalent of file .netrc on Unix?

Question: On Unix, we can specify the ftp username/password in ~/.netrc file and next time onwards, there is no need to specify username/password while ftping to any machine provided the credentials for that machine exists in ~/.netrc file.
It's very helpful especially if you need to login to multiple machines may times lets say for monitoring purposes.
Can any one please suggest if there is any equivalent of this on Windows?
Answer: If you can get away from FTP and use SFTP instead, then you can use public key authentication and store your public key (found at ~/.ssh/id_rsa.pub) on the server in ~/.ssh/authorized_keys.
Comment: Definitely the way to go if your have the choice.
Comment: If ssh is enabled,i can go for SFTP using Public key authentication.
But the problem is that ssh is not enabled on all machines
Answer: I'm not aware of Windows FTP client having a similar functionality to the UNIX .netrc file (although I've been wrong before, just ask the wife :-).
I've always had my scripts store the user name and password in a secure file and constructed an equally secure command script on the fly, using the -n and -s option of ftp, such as:
ftp -n -sgo.ftpcmds machine.com

and the go.ftpcmds contains (with suitable values of <username> and <password>):
user <username> <password>
ascii
get myfile.txt
quit

This allows me to automate all sorts of FTP tasks. If you want to automate logging in for an interactive task, just leave off the quit at the end - it will leave you logged in.
I'm not sure I understand your comment on using FTP to log in and monitor log files - surely you'd be logging in with telnet and its brethren rather than using FTP for that purpose.
Answer: This is a shortcoming of the FTP client that comes with Windows.  There are plenty of other FTP clients for Windows that allow you to save your passwords.
Comment: I know many graphical based FTP clients allows you to save passwords in windows.
But is there any command-line based ftp client in windows that remembers passwords as i need to issue the ftp commands from within the VIM editor.
Comment: If you can install Cygwin and use that, the .netrc should work just as it does on Linux.
Comment: Good suggestion.Haven't thought about this and will give a try.
Answer: Windows uses _netrc in the %HOME% environment. Just change the file name from .netrc to _netrc.


Prove that $f$ determines a continuous map $\tilde{f}: \mathbb{R}P^2 \to \mathbb{R}^4$

Question:
Let $\mathbb{S}^2$ denote the unit sphere in $\mathbb{R}^3$. Let $f:\mathbb{S}^2 \to \mathbb{R}^4$ be defined by $f(x,y,z)=(x^2-y^2,xy,yz,zx)$.
Prove that $f$ determines a continuous map $\tilde{f}: \mathbb{R}P^2 \to \mathbb{R}^4$ where $\mathbb{R}P^2$ is the real projective plane. $\tilde{f}$ is a homeomorphism onto a topological subspace of $\mathbb{R}^4$.

I know $\mathbb{R}P^2$ is homeomorphic to the quotient space $\mathbb{S}^2/R$ where $R$ identifies each pair of antipodal points in $\mathbb{S}^2$. Then I have a quotient map $p:\mathbb{S}^2\to \mathbb{R}P^2$. Then $\tilde{f}=fp^{-1}$?
Answer: Check that $f(x,y,z)=f(-x,-y,-z)$, and use the universal property of the quotient.
In particular, any map $f:X \to Y$ where $x \sim y \implies f(x)=f(y)$, then $f$ induces a unique continuous map $\tilde f: (X/\sim )\to Y$, where the quotient map followed by $\tilde f$ is the same as $f$.
You should verify that $\tilde f$ is injective (when is $f(x)=f(y)$?)
To see that it is an open mapping, note that $\tilde f$ is a continuous bijection from a compact space to a Hausdorff space so it admits continuous inverse.
Comment: Then to prove $\tilde{f}$ is a homeomorphism onto a topological subspace of $\mathbb{R}^4$, I need prove $\tilde{f}$ is open mapping. How to prove that $\tilde{f}$ is open mapping without knowing what it looks like?
Comment: @Kenneth.K see my edit.


How to catch softwareupdate output

Question: I'm trying to catch the output of the softwareupdate command under OS X.
softwareupdate -l >> somefile does only catch the first few lines (Software Update Tool Copyright 2002-2012 Apple Inc. Finding available software), the rest is missing (No new software available.) I need it for a bash script.
Current catching code:
    update=$(softwareupdate -l);
Any help is appreciated.
Answer: Try redirecting stderr messages as well. Command substitution only captures output sent to stdout (fd 1; stderr = fd 2).
update=$(softwareupdate -l 2>&1)

How to catch softwareupdate output


How to have live wallpaper open directly from the market?

Question: Is it possible to configure my project manifest, so that when a user presses "open" on the android market, my live wallpaper is applied straight away? Some users don't seem capable of figuring out that they need to apply a wallpaper after install.
Comment: In the worst case, you can always include an Activity with the MAIN/LAUNCHER intent-filter that sets the wallpaper and then exits.
Answer: Unlike a static wallpaper, live wallpapers cannot be set programmatically, so the user will need to select it from the live wallpaper gallery manually. So all you can do really is add some instructions to your wallpapers description on the Android Market or add an Activity that will show an instruction popup and direct you to the live wallpaper gallery.
Comment: Is it really possible to set wallpaper now when Jelly Bean is here? Can you please check this one out? http://stackoverflow.com/questions/13683464/set-live-wallpaper-programmatically-on-rooted-device-android


Como posso especificar um valor de "transition" a ser animado quando uso "transform"?

Question: NO css, podemos usar a propriedade transition para definir um efeito de transição quando algumas das propriedades de um elemento forem mudadas.
Exemplo:

.box{
    transition: all 1s linear;
    background-color: purple;
    height: 200px;
    box-sizing:border-box;
}

.box:hover{
    background-color: #add555;
    box-shadow: 0 0 10px 10px #000 inset;
}

No caso acima, utilizei a opção all, onde todas as propriedades são afetadas pelo transition.
Porém, é possível também definir quais e como algumas propriedades são alteradas.
Por exemplo:
.box:hover{
     transition: opacity 2s linear, background-color .2s ease;
 }

Observe que defini apenas opacity e background-color no exemplo acima.
Porém estou com um problema.
Tenho uma div que desejo animar a sua aparição através de transform: scale(1). Porém essa mesma div tem uma propriedade dentro de transforma, que é translate(-50%, -50%).
Assim:

.box{
  height: 100px;
  background-color: pink;
  position:fixed;
  width:200px;
  height:200px;
  left: 50%;
  top: 50%;
  transform: scale(1) translate(-50%, -50%);
  transition: transform 1s linear;

 }

.box:hover{
      transform:scale(0) translate(-50%, -50%);
 }

Preciso animar o transform, porém somente o scale, não quero animar o translate. Tem como fazer isso em css?
Pois depois que adicionei o translate, a animação não ficou como eu gostaria. No caso, tem que ser mais ou menos assim:

.box{
  height: 100px;
  background-color: pink;
  position:fixed;
  width:200px;
  height:200px;
  left: 30%;
  top: 30%;
  transform: scale(1);
  transition: transform 1s linear;

 }

.box:hover{
      transform:scale(0);
 }

Observe que nesse exemplo acima, o scale fez com que o objeto diminuísse para o centro, e não para o lado direito.
Como posso fazer isso em css?
Comment: Acho que esse é um caso para se usar `animation` e não `transition`.
Comment: exato, use animation e depois responda sua própria pergunta com o resultado, caso tenha conseguido :D
Answer: Tente usar
transform-origin: bottom right;

Answer: Tente algo com transition-property:
div {
    -webkit-transition-property: width, height; /* Safari */
    transition-property: width, height;
}

ou defina regras mais especificas:
.box>div {...} /** seleciona apenas a primeira div filha de .box **/
Answer: Se eu entendi direito, você gostaria de personalizar o scale de um jeito e o translate de outro correto?
Você pode fazer isto através de keyframes, você define cada keyframe do jeito que desejar, e após isto através de animation você diz como cada uma deve se animar.
.box{
    height: 100px;
    background-color: pink;
    position:fixed;
    width:200px;
    height:200px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.box:hover{
    animation: animateScale 5s linear, animateTransform 2s linear;
}

@keyframes animateScale {
    0% { transform: scale(1); }
    100% { transform: scale(0); }
}

@keyframes animateTransform {
    100% { transform: translate(-50%, -50%); }
}

e se você desejar animar somente uma você cria uma, e diz que somente esta irá animar
.box{
    height: 100px;
    background-color: pink;
    position:fixed;
    width:200px;
    height:200px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.box:hover{
    animation: animateScale 5s linear;
}

@keyframes animateScale {
    0% { transform: scale(1); }
    100% { transform: scale(0); }
}

E dentro de cada {} do @keyframe você pode dar quantos comandos quiser
@keyframes animateScale {
    0% { transform: scale(1); }
    100% {
             transform: scale(0);
             background-color: red;
         }
}

Imagino que isso resolva :D


Stuck in a finite summation in a physics problem.r³/(r-1)²

Question: Actually it was not a hard problem as seen from physics point of view, just some application of Coulomb's law (multiple charge system) but it finally ended up as the summation of:-
$$
\sum_{r=2}^n \frac{(r+1)^3}{r^2}
$$
I tried to open things up but it finally took me to summation of $\frac{1}{r^2}$ and $\frac{1}{r}$, and I know they can be solved but it's too much for my level I guess (as I am a JEE aspirant). Is there any other way to solve the summation?
Comment: If the expression [Wolfram](https://www.wolframalpha.com/input/?i=sum+from+r%3D2+to+n+of+%28r%2B1%29%5E3+%2F+r%5E2) gives is any indication, there is a (sort of) closed form, but it's not going to be easy to obtain:

$$3H_n + H_n^{(2)} + \frac 1 2 (n^2 + 7n - 16)$$

And even then, that's not really a "closed form" to some extent, since the $H_n$ (the harmonic numbers) are given by

$$H_n = \sum_{k=1}^n \frac 1 k$$

and the generalized ones by

$$H_n^{(m)} = \sum_{k=1}^n \frac{1}{k^m}$$
Answer: We have:
$$\frac{(r+1)^3}{r^2}=\frac{r^3+3r^2+3r+1}{r^2}=r+3+\frac{3}{r}+\frac{1}{r^2}$$
Thus:
$$\sum_{r=2}^n \frac{(r+1)^3}{r^2}=\sum_{r=2}^n \bigg( r+3+\frac{3}{r} \frac{1}{r^2} \bigg)$$
$$\sum_{r=2}^n \frac{(r+1)^3}{r^2}=\sum_{r=2}^n r +\sum_{r=2}^n 3 +3 \sum_{r=2}^n \frac{1}{r} + \sum_{r=2}^n \frac{1}{r^2}$$
$$\sum_{r=2}^n \frac{(r+1)^3}{r^2}=\bigg( \frac{n(n+1)}{2}-1 \bigg) +3(n-1) +3 \sum_{r=2}^n \frac{1}{r} + \sum_{r=2}^n \frac{1}{r^2}$$
$$\sum_{r=2}^n \frac{(r+1)^3}{r^2}=\frac{n^2+7n-8}{2}+(3H_n-3)+(H_n^{(2)}-1)=\frac{n^2+7n-16}{2}+3H_n+H_n^{(2)}$$
Now, it is not possible to get the exact values for $H_n$ and $H_n^{(2)}$, but for large $n$, you can approximate:
$$\lim_{n \to \infty} H_n - \ln{n} = \gamma = 0.577 \ldots \implies H_n \approx \ln{n}+ \gamma$$
$$\lim_{n \to \infty} H_n - \frac{\pi^2}{6}=0 \implies H_n^{(2)} \approx \frac{\pi^2}{6}$$
Hence, we have:
$$\sum_{r=2}^n \frac{(r+1)^3}{r^2} \approx \frac{n^2+7n-16}{2}+3 \ln{n} + 3 \gamma + \frac{\pi^2}{6}$$
As $n$ gets really large, the difference between the LHS and RHS tends to $0$. This shows that we have a really good approximation.


Dynamic route's controller method not firing

Question: I'm trying to use the Background Image module, but there seems to be a problem with the dynamic route it registers for generating CSS. I've been debugging it, but I have run into a wall. It's basically a duplicate of the core Image module's routing setup, so I'm not sure what's wrong, but the controller method never fires; the controller isn't even instantiated. Here's the config file:
route_callbacks:
  - '\Drupal\background_image\Routing\BackgroundImageRoutes::routes'

Here's the routes method:
  public function routes() {
    error_log('Router::routes');
    $routes = [];
    // Generate background image CSS files. If clean URLs are disabled the
    // files will always be served through the menu system. If clean URLs are
    // enabled and the file already exists, PHP will be bypassed.
    $directory_path = $this->streamWrapperManager->getViaScheme('public')->getDirectoryPath();

    $routes['background_image.css'] = new Route(
      '/' . $directory_path . '/background_image/css/{background_image}/{scheme}/{file}',
      [
        '_controller' => '\Drupal\background_image\Controller\BackgroundImageCssController::deliver',
      ],
      [
        '_access' => 'TRUE',
      ]
    );
    error_log(print_r($routes, true));
    return $routes;
  }

Here's the $routes object:
Array
(
    [background_image.css] => Symfony\Component\Routing\Route Object
        (
            [path:Symfony\Component\Routing\Route:private] => /sites/default/files/background_image/css/{background_image}/{scheme}/{file}
            [host:Symfony\Component\Routing\Route:private] =>
            [schemes:Symfony\Component\Routing\Route:private] => Array
                (
                )
            [methods:Symfony\Component\Routing\Route:private] => Array
                (
                )
            [defaults:Symfony\Component\Routing\Route:private] => Array
                (
                    [_controller] => \Drupal\background_image\Controller\BackgroundImageCssController::deliver
                )
            [requirements:Symfony\Component\Routing\Route:private] => Array
                (
                    [_access] => TRUE
                )
            [options:Symfony\Component\Routing\Route:private] => Array
                (
                    [compiler_class] => Symfony\Component\Routing\RouteCompiler
                )
            [compiled:Symfony\Component\Routing\Route:private] =>
            [condition:Symfony\Component\Routing\Route:private] =>
        )
)

If I try to hit a URL such as /sites/default/files/background_image/css/3/public/dq5DbF1hqHxkHXGiHSl9yuXubPox08bOX6nE12gX2h0.css?p2aptq (which the module correctly generates when I've got a background image set up on the site) I get a 404 error and nothing in the error log.
I'm using docker4drupal and have checked the nginx config and am 99% sure that's not the issue (there are no rules for /sites/default/files/ and I do see the 404 in the nginx log.)
Why doesn't the dynamic route work as it should, and as it doesn't for the Image module?
Comment: Welcome to Drupal Answers! I am not sure I understand what you mean by _implementing the Background Image module_: That module already has a Drupal 8 version. Do you mean you are trying to use the module in a site?
Comment: Yes, I'm just trying to get the module working and this routing issue appears to be the culprit. Sorry if that wasn't clear. The question is about Drupal's routing system (I didn't want to post a module-specific question here.)
Answer: Well, I'm an idiot. The problem was nginx after all. There actually was a block to handle CSS/JS assets that was preventing the dynamic route from executing because of a lack of physical files. I had to place the following above that rule:
location ~ ^/sites/.*/files/background_image/ {
    try_files $uri @drupal;
}

Here's the offending rule:
location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|xml|otf|ttf|eot|woff|woff2|svg|svgz)$ {
    expires 30d;
    tcp_nodelay off;
    open_file_cache off;
    open_file_cache_valid 45s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;

    location ~* ^.+\.svgz$ {
        gzip off;
        add_header Content-Encoding gzip;
    }
}

I found the solution after searching for relevant issues on other modules that generate dynamic files, such as imagecache, which led me to the official nginx Drupal guide. Definitely a learning exercise.