Finding function with an oblique asymptote

Question: Let $f$ be a function, continuous on $\mathbb{R}$, twice differentiable for $x \neq p$ for some $p \in \mathbb{R}$.
We are given that $f(
p) = 0, f(0)=-1$, it has an oblique asymptote $y=2x-1$ as $x \to \pm \infty$ and $\displaystyle\lim_{x \to p}f'(x) = \infty$.
Now, we are asked to find constants $a,b,c,d$ so that $$f(x) = (ax^3 + bx^2+cx+d)^{1/3}$$ satisfies the conditions above. I can find $a$ as $8$ using the oblique asymptote. By $f(0)=-1$, $d$ can be found as $-1$. To find some $b,c$, I plan to check the limit $\lim_{x\to \infty} f(x) -2x = -1$ and use the identity $u^3 - v^3 = (u-v)(u^2 +uv +v^2)$ but it looks messy. How can I find those $b$ and $c$?
Comment: Set the first two coefficients of $ax^3+bx^2+cx+d$ to be the same as $(2x-1)^3=8x^3-12x^2+6x-1$ to get $b$. To get $c$ you need to think about $f'(p)$, as in dfnu's answer.
Answer: Finding $b$ is pretty straightforward.
Using your results, you have
$$f(x) = \sqrt[3]{8x^3+bx^2+cx-1}.$$
Now you can use the fundamental limit
$$\frac{(1+\alpha)^\beta-1}{\alpha} \to \beta\tag{1}\label{1}$$
when $\alpha \to 0$, to get
\begin{eqnarray}
-1 &=&\lim_{x\to \infty} f(x) -2x=\\
&=& \lim_{x\to \infty} 2x\left(\sqrt[3]{1+\frac{bx^2+cx-1}{8x^3}}-1\right)=\\
&\stackrel{\eqref{1}}{=}&\lim_{x\to \infty} 2x\cdot \frac13\cdot\frac{bx^2+cx-1}{8x^3}=\frac{b}{12}.
\end{eqnarray}
Hence $b=-12$.
Since the derivative is
$$f'(x) = \frac{24x^2-24x+c}{3\sqrt[3]{(8x^3-12x^2+cx-1)^2}}$$
the requirement that $f$ is not differentiable in only one point $p$, implies that $$g(x) = 8x^3-12x^2+cx-1$$ has only one real root.
If you want to avoid using Cardano's method to obtain conditions on $c$, you can look analytically for the value of $c$ for which $g(x)$ has a real root with multiplicity $2$, so that we must have
$$\begin{cases}
8x^3 -12x^2+cx -1 = 0\\
24x^2-24x+c = 0.
\end{cases}
$$
Replacing $c=-24x^2 +24x$ in the first equation you obtain
$$16x^3-12x^2+1=(2x-1)^2(4x+1) = 0.$$
By direct check you can see that $c=6$ gives a root $x=\frac12$ with multiplicity $3$, whereas $c=-\frac{15}2$ gives a root $x=-\frac14$ with multiplicity $2$, has required.
In conclusion all the functions
$$f(x) = \sqrt[3]{8x^3-12x^2+cx -1}$$
with $c>-\frac{15}2$ satisfy the requirements.
Comment: Is there any way to not use the fundamental limit?
Comment: Also, can you please explain how do you find this factorization $16x^3-12x^2+1=(2x-1)^2(4x+1) = 0$ without Cardano's method?
Comment: @Ninja You can use the factorization of difference of cubes as you propose, or the method proposed in the comment to OP.
Comment: @Ninja as for the factorization of the polynomial, the roots being rational, you can find them by direct search among $\pm \frac1{q}$, where $q$ is a divisor of $16$.


What function should I use to solve this? Simple question ;)

Question: I need to write a simple function to be implemented in a computer program.
It should have as imput a number from 2 to 9 and gives as output a number from 1 to 5.
When the input is higher 6-7-8-9 the output should be lower 1-2. The opposite when the input is lower.
I can implement a random function inside it.
No need to satisfy any other particular requests. The important is that when I input 9 i got more low numbers as output then when I input 8 and so on.
Thanks!
Sorry if this is a little bit vague!
Comment: Are these numbers required to be integers? Or arbitrary floating point numbers?
Comment: integers :) but I have also a function to round them ;)
Answer: Well, if the inputs are integers, then the solution is simple (provided I've understood you're question properly). Just pick an appropriate sequence $(z_{n})_{n = 2}^{9}$, where each $z_{n} \in \{1,2,3,4,5 \}$ and satisfying all your requirements (looks like it has to be decreasing, at least). Then define the function $f: \{ 2, 3, \ldots, 9 \} \to \{1,2,3,4,5\}$ by $f(n) = z_n$. For instance $(5,4,4,3,2,2,1,1)$ should satisfy your requirements, as far as I can tell. The function is then defined by $f(n) = z_{n}$, so $f(2) = 5, f(3) = 4, f(4) = 4, f(5) = 3, \ldots, f(9) = 1$. It is probably easiest to visualize as
\begin{align*}
& (2,3,4,5,6,7,8,9) \\
& (5,4,4,3,2,2,1,1)
\end{align*}
Each number in the top row is mapped to the one directly under it.
This is also easily implemented in a computer program by using a simple, static array to look up function values. Or did you have something else in mind?
Edit: To add some randomness into the mix, we could, instead of assigning a single number to each input, assign a discrete probability distribution on $\{ 1,2,3,4,5\}$. The idea would then be that the input is paired with a random, uniformly distributed number $r$ on the unit interval $[0,1]$ (you can get these by calling an appropriate random number generator in your program). A discrete probability distribution on $\{1,2,\ldots, 5\}$ is nothing but a function $p: \{1,2,3,4,5\} \to [0,1]$ such that $$ \sum_{n = 1}^{5} p(n) = 1.$$ So, for instance, if the input is $2$, and we want the function to produce the number $5$ half the time, the number $4$, say $40\%$ of the time and the number $3$ $10\%$ of the time, the function $p$ would be
\begin{align*}
& (1,2,\phantom{0.}3\phantom{0},\phantom{0.}4\phantom{0},\phantom{.}5\phantom{5})\\
& (0,0,0.10,0.40,0.5)
\end{align*}
Given an input of $2$, we use the assigned probability distribution and the randomly generated number $r$ to decide what the function value should be.
In this case, we can use the following rules:
$$ f(2) = \begin{cases} 3 & \text{ if } 0 \leq r \leq 0.10, \\\\
4 & \text{ if } 0.10 < r \leq 0.50, \\\\
5 & \text{ if } 0.50 < r \leq 1.
\end{cases}$$
Does this make sense to you? (Notice that the with of the intervals for $r$ is the same as the probability we assigned that particular number; this ensures that the events happen with the correct frequencies).
Edit: I'll add a quick note about implementation too, since the solution, as it stands, may be slightly awkward to deal with. I would suggest that instead of working with the probability distribution directly, use the cumulative probability distribution instead, i.e.
$$ P(x \leq n) = \sum_{i = 1}^{n} p(i).$$ For the distribution above, we would have the cumulative distribution function
\begin{align*}
&(1,2,\phantom{0.}3\phantom{0},\phantom{0.}4\phantom{0},\phantom{1.}5\phantom{0}) \\
&(0,0,0.10,0.50,1.00)
\end{align*}
So, given $r$, you determine $f(n)$ by simply walking this array of numbers in increasing order, and stop when you encounter a cumulative probability P such that $r \leq P$.
Comment: I wanted the function to have some grades of randomness, if I put as input the value 2, the most of times it has to return 5, a little less frenquenlty it should return 4, and rarely 3...
Comment: Ok; I was wondering about that sentence "I can implement a random function inside it". That makes things slightly more complicated (and the result isn't really a proper mathematical function anymore, but that is of no consequence). Let me edit the post a bit.
Comment: @Giorgio: Better?
Comment: Much better :D Thank you!!!
Comment: @Giorgio: You're welcome. I've added a small note about implementation too, which you may (or may not) find helpful.


For a positive integer $n$, $p_n$ denotes the product of the digits of n, and $s_n$ denotes the sum of the digits of n.

Question: For a positive integer $n$, $p_n$ denotes the product of the digits of $n$, and $s_n$ denotes the sum of the digits of $n$. What is the number of integers between 10 and 1000 for which $p_n + s_n = n$ ?
Let $n = xy$ be the two digit number satisfying the given condition.
Given, the product of the digits of $n + \text{sum of the digits of $n$} = n$,
\begin{align}
p_n + s_n &= n\\
xy + x + y &= 10x + y\\
9x – xy &= 0\\
x (9 - y) &= 0.
\end{align}
But $x$ is not zero, because $xy$ is a two digit number.
So, $9 - y = 0 ⇒ y = 9$.
So, $xy$ can be 19, 29, 39, 49, 59, 69, 79, 89, and 99. i.e, 9 numbers.
Let $n = xyz$ be the three digit number satisfying the given condition.
Since $p_n + s_n = n$
\begin{align}
xyz + x + y + z &= 100x + 10y + z.\\
99x + 9y – xyz &= 0.\\
xyz &= 99x + 9y.
\end{align}
Comment: Or note $xyz=99x+9y$ implies $xyz\ge99x$, $yz\ge99$, contradiction.
Comment: Why not just toss it on a computer, and try all the numbers from 10 to 1000?
Comment: Basically these are the only solutions for $S(n)+P(n)=n$. As, if $n$ is a $k$ digit number the equation gives $9^k \geq P(n) \geq 9\sum_{r=0}^{k-1}10^r$. Which is true iff $k=2$.
Answer: Given the conditions, your last equation doesn't have any solution. Let's see.
As $x \neq 0$ let's divide the equation by $x$:
$$yz=99+ \frac{y}{x}$$
Therefore $x |y$.
But for $y=0$ there's no solution, and for $y \neq 0$:
$$yz >99 \Rightarrow y>10 \, \mathrm{or} \, z>10.$$
Which is impossible since $y$ and $z$ are digits.
Answer: Last equation modulo 11 is:
$xyz \equiv 9(11x + y) \equiv 9y $mode$(11)$ so $xz \equiv 9$mode$(11)$ or $z \equiv 9 x^-1$ mode$(11)$. because $x$ and $z$ are digits, we have pairs $(1,9)$, $(2,6)$, $(3,3)$, $(4,3)$,  $(5,4)$, $(6,2)$, $(7,6)$, $(8,8)$, $(9,1)$ for $(x,z)$.
by putting in the original equation we see that there is no solution.


pandas dataframe merge based on str.contains

Question: I have two dataframe that I would like to merge based on if column value from df2 contains column value from df1. I've been trying to use str.contains and series.isin. But no luck so far. Example below.
df1
       Domain              Visits
         aaa                  1
         bbb                  3
         ddd                  5

df2
       Domain                Ads
         aaa.com              2
         bbb                  4
         c.com                3
         e.net                6

Merged Dataframe should be like this
mergeDF
       Domain              Visits       Ads
         aaa.com              1          2
         bbb                  3          4
         c.com                           3
         ddd                  5
         e.net                           6

Thx in advance.
Comment: You are correct, I will fix it. Thank you for catching it.
Comment: Can you double check your output? Shouldn't `dd` have 5 in the visits column, not ads? Also, shouldn't `c.com` have a 3 in the ads, not the visits?
Comment: What should happen to an element in `df2` that does not contain anything from `df1`? What should if multiple elements in `df2` match a given element in `df1`?
Comment: 1. that element will still exist in mergeDF.  2. Great catch, I haven't really thought about it. But I think if multiple elements match, it should sum up the value of both Visits and Ads.  @fuglede
Answer: Setup
We can start by creating a new series which is the row each domain in df2 corresponds to in df1, if such a row exists:
r = '({})'.format('|'.join(df1.Domain))
merge_df = df2.Domain.str.extract(r, expand=False).fillna(df2.Domain)

Our merge_df now looks like this:
0      aaa
1      bbb
2    c.com
3    e.net
Name: Domain, dtype: object

Now we merge. We want an outer merge here, merging our first DataFrame on the Domain column, and our second DataFrame on our merge_df series:
df1.merge(df2.drop('Domain', 1), left_on='Domain', right_on=merge_df, how='outer')

 Domain  Visits  Ads
0    aaa     1.0  2.0
1    bbb     3.0  4.0
2    ddd     5.0  NaN
3  c.com     NaN  3.0
4  e.net     NaN  6.0

Since we stored a separate series to merge on, and didn't modify df2, we are done after this step, and you have your merged DataFrame.
Answer: Try and preprocess df2, to get domain in the same format as df1:
df2['key'] = df2['Domain'].str.extract('(\w+)\.?')

df_out = df1.merge(df2, left_on='Domain', right_on='key', suffixes=('_x',''), how='outer')

df_out['Domain'] = df_out['Domain'].combine_first(df_out['Domain_x'])

df_out = df_out.drop(['Domain_x','key'], axis=1)

print(df_out)

Output:
   Visits   Domain  Ads
0     1.0  aaa.com  2.0
1     3.0      bbb  4.0
2     5.0      ddd  NaN
3     NaN    c.com  3.0
4     NaN    e.net  6.0


Laplace's Method for Integral asymptotes when g(c) = 0

Question: I am using these notes as my reference, but I am running into some questions.
Say I am trying to find, for large $\lambda$
$$I(\lambda)=\int_0^{\pi/2}dxe^{-\lambda\sin^2(x)}$$
This has our maximum at $c=0$, where g(c)=0 and g'(c)$\neq$0.  So when I pull out the $e^{\lambda g(c)}$, that is just 1, so I continue to expand g(x) about x = 0, and then change the bounds from -Infinity to Infinity.
$$I(\lambda)\approx\int_{-\infty}^\infty dx\exp[-\lambda(x^2-x^4/3+...)]$$
To first order, this is just $\sqrt{(\pi/x)}$, but the second order diverges.
The reason this stumps me is because I can find an exact solution that depends on $e^x$ so I am not sure where i am going wrong in computing the behavior.
Comment: Great, glad to help. :) I suggest adding an answer to this question yourself to give the details on your calculation.
Comment: To get the higher-order corrections, or even a full asymptotic expansion, you can follow the suggestion given by [Chappers](http://math.stackexchange.com/a/1476681/5531). Try setting $x = \arcsin \sqrt{y}$ in the original integral, then applying Watson's lemma.
Comment: Instead of $$I(\lambda)\approx\int_{-\infty}^\infty dx\exp[-\lambda(x^2-x^4/3+...)]$$ you actually have $$I(\lambda)\approx\int_{0}^\infty dx\exp[-\lambda(x^2-x^4/3+...)]$$ because of the one-sided maximum at $x=0$.
Comment: Still blows up at infinity
Comment: Perhaps you misunderstood: the idea is that the series in the exponent in the expression I wrote can be truncated at any point. You are not meant to sum the series then integrate from $0$ to $\infty$. You are meant to truncate the series, say just at $x^2$, then integrate.
Comment: True.  However, I am looking for an expression good through second order, so wouldn't I need to keep that term, OR, do I expand the results, (which would be 1/sqrt(x)) to 2 terms?
Comment: You might like to look at these similar questions: [one](http://math.stackexchange.com/q/270628/5531), [two](http://math.stackexchange.com/q/672794/5531), and [three](http://math.stackexchange.com/q/689307/5531).
Comment: So I do the substitution to get

$$I = \int_0^1 \frac{dy e^{-\lambda y}}{2\sqrt y\sqrt{1-y}}$$

But can Watsons be used, because the g(y) blows up to infinity as I get to 0?
Comment: Ignore that last comment, I was able to work through it with Watsons lemma.  Thanks for the help!
Answer: Note that you have an endpoint maximum, and hence the integral should only be one-sided; this is the sort of case where Watson's lemma applies.
Answer: You can take advantage of the symmetry of your integrand to make the maximum point an interior point: $I(\lambda)=\int_0^{\pi/2} e^{-\lambda\sin^2(x)}\,dx ={1\over 2}\int_{-\pi/2}^{\pi/2}e^{-\lambda\sin^2(x)}\,dx$. Laplace's Method then yields $I(\lambda)\sim \sqrt{\pi\over 4\lambda}$. This is consistent with your exact evaluation of $I(\lambda)$ and the known large-$\lambda$ asymptototics for the Bessel function $I_0$: $I_0(x)={e^x\over\sqrt{2\pi x}}+e^x\cdot O(x^{-3/2})$.
Comment: How could I solve for the coefficient on O($x^{-3/2}$)?
Comment: @yankeefan11: wolframalpha will give you the complete asymptotic expansion of $I_0(x)$ for large $x$.
Comment: Im trying to solve for myself :)
Answer: That integral can be computed in a explicit way by using modified Bessel functions of the first kind:
$$ \int_{0}^{\pi/2} e^{-\lambda\sin(x)^2}\,dx = \frac{\pi}{2}e^{-\lambda/2}\,I_0(\lambda/2) \tag{1}$$
then the asymptotic form follows from Hankel's expansion:
$$ \int_{0}^{\pi/2} e^{-\lambda\sin(x)^2}\,dx \approx \sqrt{\frac{\pi}{4\lambda }}\left(1+\frac{1}{4\lambda}\right).\tag{2} $$
Comment: So from Hankel's expansion, do you need to know that it can be explicitly calculated first?
Comment: Well, Hankel's expansion applies to Bessel functions. If you do not know you are dealing with a Bessel function, you may still prove $(2)$ through the usual Laplace method / Watson lemma.


Prove that:$\int_{0}^{1}{x+x^2+\cdots+x^{2n}-2nx\over (1+x)\ln{x}}dx=\ln{\left[\left({2\over \pi}\right)^n(2n)!!\right]}$

Question: Prove that
$$\int_{0}^{1}{x+x^2+x^3+\cdots+x^{2n}-2nx\over (1+x)\ln{x}}dx=\ln{\left[\left({2\over \pi}\right)^n(2n)!!\right]}$$
$n\ge1$
My try:
$${x+x^2+\cdots+x^{2n}\over 1+x}={1\over 1+x}\cdot{x(1-x^{2n})\over 1-x}=x\cdot{1-x^{2n}\over 1-x^2}$$
$${x+x^2+\cdots+x^{2n}-2nx\over 1+x}=x\cdot{1-x^{2n}\over 1-x^2}-{2nx\over 1+x}$$
$$\int_{0}^{1}\left(x\cdot{1-x^{2n}\over 1-x^2}-{2nx\over 1+x}\right)\cdot{1\over \ln{x}}dx$$
I am stuck not quite sure what to do next, please help
Edit
$$\int_{0}^{1}\left(x\cdot{1-x^{2n}\over 1-x^2}-{2nx\over 1+x}\right)\cdot{1\over \ln{x}}dx$$
Comment: Your $\frac{2nx}{1-x^2}$ term should actually be just $\frac{2nx}{1+x}$
Comment: Perhaps somehow using upper/lower Riemann sums would work?
Comment: There is a related work here
http://math.stackexchange.com/questions/1821080/showing-int-01x2n-x-over-1x-cdotdx-over-lnx-ln-left2-over?rq=1
Answer: Hint. One may use the identity

$$
\int_0^\infty \frac{1-e^{-su}}{u(e^u+1)}du=\frac12\log(\pi)+\log \Gamma\left(1+\frac{s}2\right)-\log \Gamma\left(\frac{1+s}2\right), \quad s>0.
$$

proved here. By the change of variable $u=-\ln x$, $x=e^{-u}$, in the preceding integral, one gets
$$
\int_{0}^{1}{x^s-1\over (1+x)\ln{x}}\:dx=\log\left(\frac{\sqrt{\pi}\:\Gamma\left(1+\frac{s}2\right)}{\Gamma(\frac{1+s}2)} \right), \quad s>0,
$$ then rearranging the numerator of the given integral as
$$
\int_{0}^{1}{(x^2-x)+(x^3-x)+\cdots+(x^{2n}-x)\over (1+x)\ln{x}}\:dx,
$$ observing that each term $x^k-x$ rewrites $(x^k-1)-(x-1)$ yields the announced result.
Answer: In THIS ANSWER, I showed that

$$\bbox[5px,border:2px solid #C0A000]{\int_0^1 \left(\frac{x^{2n}-x}{1+x}\right)\,\frac{1}{\log(x)}\,dx=\log\left(\frac{2}{\pi}\frac{(2n)!!}{(2n-1)!!}\right)}$$

We can use this result to evaluate the integral
$$\begin{align}
\int_0^1 \left(\frac{x^{2n+1}-x}{1+x}\right)\,\frac{1}{\log(x)}\,dx&=\int_0^1 \left(\frac{x^{2n+1}-x^2+(x^2-x)}{1+x}\right)\,\frac{1}{\log(x)}\,dx\\\\
&=\int_0^1 \left(\frac{x^{2n+1}-x^2}{1+x}\right)\,\frac{1}{\log(x)}\,dx+\log(4/\pi)\\\\
&=\int_0^1 \frac{x^{2n}-x}{\log(x)}\,dx+\log(4/\pi)-\log\left(\frac{2}{\pi}\frac{(2n)!!}{(2n-1)!!}\right)\tag1
\end{align}$$

The integral on the right-hand side of $(1)$ can be evaluated by enforcing the substitution $x\to e^{-x}$ and evaluating the resulting FRULLANI INTEGRAL.  Proceeding, we have
$$\int_0^1 \frac{x^{2n}-x}{\log(x)}\,dx=\log\left(\frac{2n+1}{2}\right) \tag 2$$

Substituting $(2)$ into $(1)$ reveals
$$\begin{align}
\int_0^1 \left(\frac{x^{2n+1}-x}{1+x}\right)\,\frac{1}{\log(x)}\,dx&=\log\left(\frac{2n+1}{2}\right)+\log(4/\pi)-\log\left(\frac{2}{\pi}\frac{(2n)!!}{(2n-1)!!}\right)\\\\
&= \log\left(\frac{2}{\pi}(2n+1)\right)-\log\left(\frac{2}{\pi}\frac{(2n)!!}{(2n-1)!!}\right) \tag 3\\\\
&=\log\left(\frac{(2n+1)!!}{(2n)!!}\right)
\end{align}$$

Finally, we see that
$$\begin{align}
\int_0^1 \left(\frac{x+x^2+\cdots +x^{2n}-2nx}{1+x}\right)\,\frac{1}{\log(x)}\,dx&=\sum_{k=1}^n \int_0^1 \frac{x^{2k}-x}{1+x}\frac{1}{\log(x)}\,dx\\\\
&+\sum_{k=1}^{n-1}\int_0^1 \frac{x^{2k+1}-x}{1+x}\frac{1}{\log(x)}\,dx\\\\
&=\sum_{k=1}^n\log\left(\frac{2}{\pi}\frac{(2k)!!}{(2k-1)!!}\right)\\\\
&+\sum_{k=1}^{n-1}\log\left(\frac{2}{\pi}(2n+1)\right)\\\\
&-\sum_{k=1}^n\log\left(\frac{2}{\pi}\frac{(2k)!!}{(2k-1)!!}\right)\\\\
&=\log\left(\left(\frac{2}{\pi}\right)^n (2n)!!\right)
\end{align}$$
as was to be shown!
Answer: Hint: We may use the substitution $x\to e^{-x};$
$$I(n) = \int_0^\infty \left( \frac{e^{-2(n+1)t}-e^{-2t}}{1-e^{-2t}} +\frac{2ne^{-2t}}{1+e^{-t}}\right)t^{-1}dt\\ = \sum_{k=0}^\infty \int_0^\infty\left(e^{-2(n+k+1)t} - e^{-2(k+1)t} +2n (-1)^k e^{-(k+2)t}\right) t^{-1}dt$$
and write the previous splitting in terms of $\Gamma-$function


Optimization with LINGO

Question: The Dynamic Programming Problem
I have one optimization problem I am trying to solve with LINGO, I am a beginner with LINGO and I need some help. The question can be accessed by cliking on the 'The Dynamic Programming Problem' link above. Sorry I cant embedd images yet.
I tried to script some code to solve the problem but get syntax errors all the time. Could you give me some hint? Thanks
<code>    sets:

    people/a,b,c,d/: pb;
    trip(people, people): time;

    endsets

    data:

    pb = 1, 2, 5, 10;

    time =

    0   2   5   10
    0   0   5   10
    0   0   0   10
    0   0   0   0;

    enddata

    min = @sum(trip(i,j): time);
</code>
I also tried this but didnt work
<code>   trip/ab, ac, ad, bc, cd/: time;
   solo/a, b, c/: time2;
   link(trip,solo,trip,solo,trip);
   endsets

   data:
   time = 2, 5, 10, 5, 10;
   time2 = 1, 2, 5;

   enddata

   t1 = @sum(trip:solo:trip:solo:trip);

   Min = @sum(link(i));
</code>
Answer: Your first program runs without any syntax errors on my machine.
The only things missing are: "MODEL:" as the first line of the file, and "END" as the last line.
Comment: Thanks but the optimized answer is 17 but the model gives 42. Can I modify it to obtain the correct result?

Optimization with LINGO


Creating a python batch Image operation using ArcCatalog

Question: I'm trying to work out how to create a batch operation tool in ArcCatalog, based on all .img raster files in a directory. I do not need to change the code, but I need to set the correct parameters.

Here's my code:
'''This script uses map algebra to find values in an
    elevation raster greater than a specified value.'''
import os
import arcpy
#switches on Spatial Analyst
arcpy.CheckOutExtension('Spatial')
#loads the spatial analyst module
from arcpy.sa import *
#overwrites any previous files of same name
arcpy.overwriteOutput=True
# Specify the input folder and cut-offs
inDirectory = arcpy.GetParameterAsText(0)
cutoffElevation = int(arcpy.GetParameterAsText(1))
for i in os.listdir(inDirectory):
    if os.path.splitext(i)[1] == '.img':
        inRaster  = os.path.join(inDirectory, i)
        outRaster  = os.path.join(inDirectory, os.path.splitext(i)[0] + '_above_' + str(cutoffElevation) + '.img')
        # Make a map algebra expression and save the resulting raster
        tmpRaster = Raster(inRaster) > cutoffElevation
        tmpRaster.save(outRaster)
# Switch off Spatial Analyst
arcpy.CheckInExtension('Spatial')

In the parameters I have selected:

Input Raster Raster Dataset - direction Input, Multivalue yes
Output Raster Raster Dataset - direction output
Cut off elevation - string, direction input

I add the images I want in the input raster, select the output raster and cut off elevation. But I get the error:

line 13, in
  cutoffElevation =int(arcpy.GetparameterAsText(1)).
  ValueError: invalid literal for int() with base 10

Does anybody know how to fix this?
Answer: You have three input parameters shown in that dialog box screenshot, but only two are described in the script. (The output raster outRaster is being defined in line 15, not as an input parameter.)
The error you're getting is because the output raster (presumably a file path and file name) can't be converted to an integer.
There are two ways to solve that:

Change the input parameters within that tool definition, so you're only feeding in input raster (parameter 0) and cut off elevation (parameter 1).
Change the code so it's looking for the correct parameters that are currently defined -- input raster (parameter 0) and cut off elevation (parameter 2).
inDirectory = arcpy.GetParameterAsText(0)
cutoffElevation = int(arcpy.GetParameterAsText(2))

Either way, you're making sure that the GetParameterAsText command is actually referring to the parameter you really want.


How disable click and hover of certain grid row's during databound event?

Question: In my databound event every globalGroupLevel that is a 0, the row is grey, but I have no idea on the correct way to disable those rows so they can't be clicked and remove the hover, here is my databound event
dataBound: function (e) {
    var data = this.dataSource.data();
    $.each(data,
        function (i, row) {
            if (row.get("globalGroupLevel") === 0) {
                var element = $('tr[data-uid="' + row.uid + '"] ');
                element.addClass("colored-row");
                element.find(".k-hierarchy-cell a").remove();
            }
        });
}

Here are all the ways that I have tried to remove the click event and the hover effect, none of these worked
element.removeClass("k-state-selected");
$(this).unbind('mouseenter mouseleave')
$(this).off('hover');
$(this).unbind('mouseenter mouseleave');
element.unbind('mouseenter mouseleave');
$(this).off('mouseenter mouseleave');
element.canSelect(false);
element.removeClass("tr:hover");
$(this).removeClass("tr:hover");

Answer: For the click event you can set all buttons with the disabled attribute. For hover you can create a new style for the element container, and when the container has the class 'disabled', the child elements will not have the hover.


Django template language include variable

Question: In the include documentation they state that you can include a template contained in a variable.  However they do not explain how to write a template variable.
I am looking to do something like:
{% variable thing %}

 Hello {{name}}

{% endvariable thing %}

{# include the variables #}
{% include thing with name='Chris' %}
{% include thing with name='Julie' %}

Comment: You've misread the documentation. It says you can include a template file using a name taken from a variable, not that the template contents can be in a variable.
Comment: So you have a key named 'thing' in your template context that has a template path like "foo/bar.html"? You have to add that in your view.
Comment: the variable keyword I made up because I'm not sure how to do it.  I want to include the template within the same file, not another file.  I realize I can just put my template in a separate html file and include it in another.  I was trying to avoid doing that since the variable thing will on be used in one file
Answer: Just create the template thing.html:

Hello {{name}}

And then in the main template include it:
{% include 'thing.html' with name='Chris' %}
{% include 'thing.html' with name='Julie' %}

Comment: Is there anyway to create the template thing in the same file?  That is what I am looking for
Comment: Maybe you are better off using a template tag: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags
Comment: Do you want something like jinja macros? http://jinja.pocoo.org/docs/dev/templates/#macros No, Django's built-in template system doesn't support this feature.
Answer: For your example you would need to add a key named 'thing' to your template context in your view. 'thing' would need a value like "foo/bar.html", a path to a template.
return render_to_response('index.html', {
    'thing': 'foo/bar.html'}, RequestContext(request))


If the roots of $x^2+x-1$ are $\alpha$ and $\beta$, find an $eq^{n}$ whose roots are $\alpha^{19}$ and $\beta^{7}$

Question: If the roots of $x^2+x-1$ are $\alpha$ and $\beta$, find an $eq^{n}$ whose roots are $\alpha^{19}$ and $\beta^{7}$
My Procedure
The roots are $$\frac{-b+\sqrt{b^{2}-4ac}}{2a}$$ and $$\frac{-b-\sqrt{b^{2}-4ac}}{2a}$$
$\therefore$ the roots are $\frac{\sqrt{5}-1}{2}$ and $\frac{-\sqrt{5}-1}{2}$
But this on further solution doesn't give a simple answer. I get $$x^{2}-x-\frac{(\sqrt{5}-1)^{12}}{2^{5}}$$
Is there any other simpler way?
Answer: I would guess that the purpose of the question is not to challenge the solver to tedious arithmetic exercise best left to a computer, but rather to encourage the search for a more rapid way of computing powers of roots in the given case, taking advantage of the rather simple coefficients. to this end we should observe, for example that:
since
$$x = 1 - x^2
$$
we have
$$
x^2 = (x^2-1)^2 = x^4 - 2x^2 + 1
$$
i.e.
$$
x^4=3x^2 -1
$$
going one step further
$$
x^8 = (3x^2-1)^2 = 9x^4 - 6x^2 +1 = 21 x^2 -8
$$
after one more step you may calculate, e.g., $x^{19}$ as $x^{16}x^2x$
in fact the roots of the original equation are $\frac1{\phi}$ and $-\phi$ where $\phi$ is the golden section.
the question as posed is ambiguous since there are two ways of assigning these values to the $\alpha$ and $\beta$. but in either case if you compute as above you can then do as Dr  Graubner suggests and form the equation $(x-\alpha^{19})(x-\beta^7)$, or, equivalently, directly use the standard form for a quadratic in terms of the sum and product of the roots


Understanding how many biases are there in a neural network?

Question: I am trying to understand biases in neural nets, but different websites show very different answers.
For example, how many biases is there in a fully connected neural network with a single input layer with 5 units and a single output layer with 4 units? And what about a fully connected neural network with a single input layer with 5 units, a single hidden layer with 4 units, and a single output layer with 3 units?
For example, if I understand this correctly, https://ai.stackexchange.com/questions/17584/why-does-the-bias-need-to-be-a-vector-in-a-neural-network, the answer of the first should be 5 and for the second 4 + 3. Each neuron except for in the input-layer has a bias.
However, at https://ayearofai.com/rohan-5-what-are-bias-units-828d942b4f52, it is explained such that each layer including the input-layer has one bias. So the answer to the example above is one in the first and two in the second.
What is correct? What am I misunderstanding here?
Answer: Each node in the hidden layers or in the output layer of a feed-forward neural network has its own bias term. (The input layer has no parameters whatsoever.) At least, that's how it works in TensorFlow. To be sure, I constructed your two neural networks in TensorFlow as follows:
<code>model1 = tf.keras.models.Sequential([
        tf.keras.layers.Dense(4, activation = 'softmax', input_shape = (5,))])

model2 =  tf.keras.models.Sequential([
        tf.keras.layers.Dense(4, activation = 'relu', input_shape = (5,)),
        tf.keras.layers.Dense(3,activation = 'softmax')])
</code>
Here is the summary of these two models that TensorFlow provides:

The first model has 24 parameters, because each node in the output layer has 5 weights and a bias term (so each node has 6 parameters), and there are 4 nodes in the output layer. The second model has 24 parameters in the hidden layer (counted the same way as above) and 15 parameters in the output layer. Each node in the output layer has 4 weights and a bias term (so 5 parameters per node in the output layer), and there are 3 nodes in the output layer.
Answer: It depends on whether you're counting units or learnable parameters.  In the first example/link, we are counting the parameters, and in the second example we are counting the units.
There's one bias unit per layer.  Including the input ensures that a network with one layer has a bias.


Form Herdado vem sem opção de edição nele todo. Uso C# e VS 2017

Question: Quando crio o Form2 Herdado do Form1, não consigo editar nada nele. Claro que o cadeado na parte esquerda superior tem algo a ver, mas como posso resolver essa situação?
Segue a imagem pra melhor entendimento. Obrigado!
Comment: Olá, considere aceitar uma das respostas se ela lhe foi útil. Se achar que ela está incompleta ou não te atende, faça os devidos comentários para que possam melhorá-la.
Answer: No form pai, vá no controle que deseja que seja alterado, na propriedade modifiers, coloque public.
Answer: O recurso Lock Controls foi ativado em seu formulário.
Ao ativar esta opção, todos os controles ficaram marcados com este cardeado, indicando que não poderá movê-los ou redimensioná-los.
Você poderá bloquear/desbloquear controles individualmente, ou todos simultaneamente.
Ativação/desativação individual

Selecione um controle, e em suas propriedade, altere a opção Locked (Bloqueado).

Ativação/desativação geral

Para ativar/desativar todos os controles use: Menu Format (Formatar) > Lock Controls (Bloqueio de Controles)
Answer: Botão direito no formulário -> Lock Controls


Como faço pra printar a saída em linhas diferentes nesse código?

Question: #Divisores I#

def divisores(num):
    for i in range(1, num//2+1):
        if num % i == 0:
            yield i
    yield num

num = int(input())
print(list(divisores(num)))

A resposta está saindo na mesma linha, queria q elas ficassem uma abaixo da outra, mas não consigo.
Comment: Guilherme, dá uma [pesquisada no site](https://pt.stackoverflow.com/search?q=%5Bpython%5D+or+%5Bpython-3.x%5D+print+linha) pois já tem bastante conteúdo sobre isso. ;)
Comment: Uma possibilidade é `for x in lista: print(x)`.
Comment: Complicando: `print('\n'.join([str(i) for i in list(divisores(num))]))`
Answer: Para você resolver esta questão você pode utilizar o seguinte código:
def divisores(n):
    for i in range(1, (n // 2) + 1):
        if n % i == 0:
            yield i

num = int(input())
for j in divisores(num):
    print(j)

Segundo a documentação yield é uma expressão de rendimento que serve como função geradora e, dessa forma, só pode ser usada no corpo de funções.
Quando uma função geradora é chamada, é retornado um iterator conhecido como gerador. Desse modo o gerador controla a execução da função geradora. Nesse momento é executado a primeira expressão de rendimento sendo em seguida, sua atividade é suspensa, retornando dessa forma o valor da expression list. Em seguida o processo é refeito até ser concluída toda as operações.
Observação
Este código serve para calcular os DIVISORES PRÓPRIOS de um número.
Agora, se você deseja calcular os DIVISORES NATURAIS de um número, você pode utilizar o seguinte código:
def divisores(n):
    for i in range(1, n + 1):
        if n % i == 0:
            yield i

num = int(input())
for j in divisores(num):
    print(j)


Fetch data based on key

Question: <code>{ "Labels": [ {"Test": 99.25341796875, "Name": "Skateboard" }, { "Test": 9.25341796875, "Name": "Sport" }, { "Test": 49.24723052978516, "Name": "People" }]}
</code>
I need to remove the Testtag on basis of below conditions
if Test value >50 then replace Test=Major
if Test value <50 then replace with Test=Minor
so here output requested is like below.
<code>{ "Labels": [ {"High": 99.25341796875, "Name": "Skateboard" }, { "Low": 9.25341796875, "Name": "Sport" }, { "Low": 49.24723052978516, "Name": "People" }]}
</code>
Comment: Please update your code in question so that it is easy to read
Comment: are you serializing this content into objects at all? like in Java or C#?
Comment: Thanks Alex for formatting. I need it in Perl/Unix.
Comment: #!/usr/bin/perl

use JSON;
use Data::Dumper;
$json = '{ "Labels": [ {"Confidence": 99.25341796875, "Name": "Skateboard" }, { "Confidence": 9.25341796875, "Name": "Sport" }, { "Confidence": 49.24723052978516, "Name": "People" }]}';

$text = decode_json($json);
print  Dumper $text;

$key = "Confidence";
if (exists($text{$key}))
{
  print "Found Confidence\n";
  #sed i need to apply using chekcing condition of Confidence < 50 or >50 and replace tag with monor and major
}
else
{
  print "Could not find Confidence";
}

This is what i did so far. Pl suggest
Answer: jq solution:
<code>jq '.Labels |= map(.[(if .Confidence > 50 then "High" else "Low" end)]= .Confidence | del(.Confidence))' yourfile.json
</code>
The output:
<code>{
  "Labels": [
    {
      "Name": "Skateboard",
      "High": 99.25341796875
    },
    {
      "Name": "Sport",
      "Low": 9.25341796875
    },
    {
      "Name": "People",
      "Low": 49.24723052978516
    }
  ]
}
</code>
Comment: @PraveenPokharia, I'm not Alex
Comment: I am not able to redirect the output of above command to a file. Please suggest. It is displaying on the screen.
Comment: i tried it but it is not working..
jq '.Labels |= map(.[(if .Confidence > 50 then "High" else "Low" end)]= .Confidence | del(.Confidence))' $filename.json > $filename1.json
Comment: it is making a file but the content has not changed which we changed with the jq :). pl suggest so that same output which is coming above from ur query preserve in the file.
Comment: I got the output but it is in 1 file. i have applied for loop to iterate the 10 files and redirected the json o/p of 10 files in 1 file due to which it looks clumsy.

Fetch data based on key


Multi bitrate live HLS with FFmpeg on Windows

Question: I am trying to encode a live stream into Apple HLS for iPhone on windows. I was looking at different options and wowza can do it, but doesn't support CDN distribution of HLS as far as I can see. Plus it costs a lot of money.
What I did find was this site: http://www.espend.de/artikel/iphone-ipad-ipod-http-streaming-segmenter-and-m3u8-windows.html
I can now set up a single bitrate stream easily, but my goal is an adapive multi-bitrate live stream. Is it possible? For VOD content it can easily be accomplished with creating the different qualities then linking to them in a new m3u8, but how would this be done in live?
I can of course set up three quality live streams and link to them in an m3u8, but how will I get them GOP-aligned in this case?
My initial thought was to have one ffmpeg instance create all qualities and re-stream those outputs to new ffmpeg-instances that just remux and pipe to the segmenter. But I would need some way of streaming locally between instances. Can that be done?
If anyone has a nice solution to this, or can link to other software capable of live HLS on windows, I would appreciate any input.
Have a great day!
Regards
Carl
Answer: Just to let people know, I ended up using http://www.ioncannon.net/projects/http-live-video-stream-segmenter-and-distributor/ on a linux virtualbox and it works great. I had trouble compiling it, but there were a couple of forks that fixed those problems.
Comment: @Agzam Did you compiled!? I still can't compile it!
Comment: @Nioreh Which forks fixed compile problems?! Which one is the best?!


How to add an id to markers if it's not built into the gem?

Question: I grabbed the code from the wiki for "Adding an id to markers and access them later."
It looks like this:
markers = ... // Fetch markers
Gmaps.store.markers = markers.map(function(m) {
  marker = handler.addMarker(m);
  marker.serviceObject.set('id', m.id); // You can add other attributes using set
  return marker;
});
handler.bounds.extendWith(Gmaps.store.markers);
handler.fitMapToBounds();

In my controller, I tried adding the id to the available attributes for the map markers
 def map_markers model
   Gmaps4rails.build_markers(model) do |item, marker|
     marker.lat item.lat
     marker.lng item.long

     marker.id item.id

     marker.picture marker_picture(:real_estate)
     marker.infowindow string
   end
 end

I kept getting an error because id is not an attribute made available to the build_markers method. You can only set lat, lng, title, infowindow, and picture according to https://www.omniref.com/ruby/gems/gmaps4rails/2.0.4/symbols/Gmaps4rails::MarkersBuilder#line=21
How do you pass the id to the view for each marker if you can't do it by default in the Gmaps4rails.build_markers method?
Comment: and server side: `marker.json({ id: item.id})`
Comment: what about `marker.id =  m.id;` instead of `marker.serviceObject.set('id', m.id);`
Comment: for the records: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Json-builder
Answer: As told in the wiki, you can add your own json stuff through a hash like:
marker.json({ id: item.id})


Using pmap to parallelize fitting linear mixed models in Julia

Question: I am trying to use Julia to fit a set of different linear mixed models to the same dataset using pmap (Mac OSX 12.6.3, Julia 1.9). I can successfully fit a linear mixed model and run pmap using a native function, like pmap(sqrt, 1:100). I wrote a function called fit_mm that takes as input a string that refers to a column of my dataset, a basic formula to update, and the dataset called df. I can run this using map successfully. However, when I try to use pmap, I get the following error.
julia> # Run map
       pmap(x -> fit_mm(x, baseFormula, df), covs[1:10])
ERROR: On worker 3:
KeyError: key StatsModels [3eaba693-59b7-5ba5-a881-562e759f1c8d] not found

Here's the summarized code I am using

using Distributed
@everywhere using MixedModels
@everywhere using DataFrames
@everywhere using DataFramesMeta
@everywhere using CategoricalArrays
@everywhere using CSV
@everywhere using Term
@everywhere using StatsModels
@everywhere using DelimitedFiles

addprocs(2)

# Function to update formula
@everywhere begin
    function fit_mm(testVar, f, data)
       ....
    end
end

# Load data of interest...
# Run map
pmap(x -> fit_mm(x, baseFormula, df), covs) # covs is the list of variables I want to use to modify baseFormula and df is the data

Comment: Please post a minimum reproducible example (https://stackoverflow.com/help/minimal-reproducible-example). In your case the problem seems to be in including the `StatsModels` package. So, do not truncate the `using` statement either and show all packages so that others may reproduce your error.
Comment: Thank you @loonatick. I edited the question as suggested
Comment: That's better, but still not reproducible since you left out the definition of `fit_mm`
Comment: Instead of `@everywhere begin function` you can just write  `@everywhere function`. As mentioned by others it is not possible to provide the answer without a minimal piece of code that replicates the error. Maybe make some small simple dataframe that shows this behaviour?
Answer: I apologize for not providing a reproducible example this time. I will make sure to do so next time I ask a question. Anyway, I just wanted to let everyone who might read this that I solved the issue in the hopes it can help someone. As I closed and/or re-started Julia, I noticed that the error message kept changing in the worker that had a problem (I had four workers, and sometimes the error was assigned to worker 2, sometimes to worker 3, and so on) and the package that was not found. I finally figured out that if the addprocs(2) command creates the workers, then I should create the workers before declaring the use of packages or functions so the packages and functions could be loaded into all workers. So I moved the addprocs statement right after declaring the use of Distributed package. So the final code was
using Distributed

addprocs(2)

@everywhere using MixedModels
@everywhere using DataFrames
@everywhere using DataFramesMeta
@everywhere using CategoricalArrays
@everywhere using CSV
@everywhere using Term
@everywhere using StatsModels
@everywhere using DelimitedFiles

... and then the rest of the code.

This led to the code running without a problem.


Page not found error when creating a simple module

Question: I have my first module in drupal 8 with three files in modules section of my drupal:
hello_world.routing.yml:
hello_world:
    path: '/hello/world'
    defaults:
        _controller: '\Drupal\hello_world\Controller\HelloWorldController::hello'
    requirements:
        _permission: 'access content'

hello_world.info.yml: ( in modules/hello_world/src/Controller directory)
name: Hello World!
type: module
description: Say Hello World
package: Custom
core: 8.x

HelloWorldController.php:

namespace Drupal\hello_world\Controller;

class HelloWorldController {

    public function hello() {

        return array(
                '#title' => 'Hello World!!!',
                '#markup' => 'Here is some content.',
            );
    }
}

?>

however, when I press clear all caches button and run code again. I just have Page not found problem.
Comment: An obvious question but have you definitely enabled the module? In your message you also say you have your hello_world.info.yml
 in "modules/hello_world/src/Controller" it should be in the root of your hellow_world module folder. Or was that just a mistake and you meant your controller is in there
Comment: The YML pasted above, the indentation looks a little off and there are other oddities like the closing PHP tag, etc. Is the URL in the browser correct? The route has it defined at just `/hello/world` but the browser URL is `/drupaltest/hello/world` - or do you have Drupal installed in a subdirectory?
Comment: Thank you for response. I do not know where should I put my modules folder. I thought that it should be in modules sub folder after root folder.
Comment: I just put HelloWorldController.php in modules/hello_world/src/Controller. my yml files are in hello_world folder
Comment: HelloWorldController.php is in : C:\xampp\htdocs\drupaltest\modules\hello_world\src\Controller  ,               yml files are in hello_world folder
Answer: hello_world.info.yml sould be in modules/hello_world/
then check if the hello_world is enabled and rebuild cache
Comment: Yes. I did do it.  I have C:\xampp\htdocs\drupaltest\modules\hello_world and inside of hello_world folder I have  three mentioned above files. where is root? should I change  my direction? I just download drupal 8, change its name to drupaltest and put it on my htdocs of xmapp
Comment: thank you. it is work now. I rebuilt  the module again and reinstall module again


Let $L/Q$ be a field extension. Let $\sigma\in\textrm{Aut}_Q(L)$. Let $f(x) \in Q[x]$ be a polynomial. Show that $f(σ(α)) = σ(f(α))$ for all $α ∈ L.$

Question: Let $L/Q$ be a field extension. Let $\sigma\in\textrm{Aut}_Q(L)$. Let $f(x) \in Q[x]$ be a polynomial. Show that $f(σ(α)) = σ(f(α))$ for all $α ∈ L.$
The statement is obviously true for $α ∈ Q$ because $\text{Aut}_Q(L)$ fixes $Q$. However, I don't know how to extend the conclusion to other elements in $L$.
Comment: Extend it to monomials and then to $f(x)=a_nx^n+\cdots +a_0$.
Comment: You may try first with $f(x) = 2 x^2+1$
Comment: Start from the R.H.S.- use the fact that $\sigma(xy)=\sigma(x)\sigma(y)$ and $\sigma(x+y)=\sigma(x)+\sigma(y)$- then, finally, use the fact that $\sigma$ fixes $Q$.
Answer: Write $f(x)=\sum_{i=0}^na_ix^i$ with $n\in\Bbb N$ and $a_i\in Q$.
Then for every $\alpha\in L$ we have
\begin{align}
\sigma(f(\alpha))
&=\sigma\left(\sum_{i=0}^na_i\alpha^i\right)\\
&=\sum_{i=0}^na_i\sigma(\alpha)^i\\
&=f(\sigma(\alpha))
\end{align}
Comment: Beautiful proof! Thanks so much!


node.getRevisionCreationTime equivalent in views

Question: This question is somewhat related to Comparing node creation and modification dates in twig I asked earlier.
For the website in question, we agreed to the following semantics of the various dates related to a node (in our case, blog posts):

Creation date: The date the note was created.
Changed date: The date when any of the node's modifiable settings were changed.
First publication: The date the node was first published (using Drupal module Publication Date).
Publication date: The date a new revision of the node has been created - in other words, the current revision's date.

In rendering the content, all is well when using node.getRevisionCreationTime for the publication date in the relevant twig templates and display modes.
However, I what certain blocks and views to order the blog posts by publication date as defined above.
I fail to find the right settings when defining the view - I find the Views user interface incredibly complicated and not intuitive at all. In my (perhaps naive) assumption, using the Content Revision field Changed or Authored on as sufficient, but I suspect that that doesn't always relates to the current revision.
See the attached screenshot on how I have defined the view:
UPDATE: An example:
The above view (with some filtering on example name) gives the following result:

Taking a screenshot when editing the node I get this:

So far, so good: Node creation, publication and changed times all match. But look at the "Revision created" and "Revision changed" dates - they match the corresponding node times!
Checking the node's revisions, I see that the current revision's date (which date exactly? Created? Changed? Something else?) is 12 June 2018 - but nowhere to be found in my view - see screenshot:

The revision date 12 June 2018 is the date I want to fetch as the "Publication date" explained above.
How do I do that in a view?
Please help!
TIA,
Michel
Answer: I found the answer eventually:
The crucial thing to do was to built the query starting with content revisions rather content. Rather unintuitively - creating a relationship the other way around does NOT get you to where you need to get in this situation!
To create a view listing the node's title, creation date, changed date, first publication, and publication date (the creation date of the current revision, follow these steps, and then add/remove as required:

Create a view showing content revisions of type all as follows, creating a page for easier review:

Remove the field "Content revision: Changed (Changed)" as this is not what we are interested in.
Add a relationship to Content as seen in the screenshot below:

This is one of the #DrupalWTF moments - where's the crucial documentation that allows me to select the correct relationship!?
There are apparently two RDBMS foreign key relationships you can use to join revisions and content:
a. Via content revision foreign key to the id of the node this revision belongs to - this is the first content relationship, and
b. Via revision id referenced as foreign key from the content table as current node - this is the second content relationship shown above in the screenshot.

For whatever reason you cannot reach the creation date of a revision when joining via the first content relationship, #Drupal, #WTF?
Require the relationship for all results, and change the administrative title if you wish:

Add a filter criterion to show only blog posts
The relationship shows revisions for all content types, so we need to filter for content type blog post (Yours may be different). This is pretty straightforward, see the following screenshots:
a. Select the filter criterion:

b. Configure the filter:

Add the various date related fields
This is repetitive; to add the fields select them all in the "Add field" form, and configure them all the same way:

(Content) Authored on,
(Content) Changed,
(Content) Published on,
(Content revision) Revision create time

Here are the screenshots:

and

Et voila, all fields present as required.
Now you (I) can go to town for formatting and sorting.


a simple loop with data.table

Question: I want to do a simple loop using data.table. I have 20 dichotomous (0,1) variables (from var_1 to var_20) and I would like to do a loop for this:
dat[var_1==1, newvar:=1]
dat[var_2==1, newvar:=2]
dat[var_3==1, newvar:=3]
...
dat[var_20==1, newvar:=21]

My main problem is I don't know how specify i (i.e. var_1==1, var_2==2...) using a loop.
Below a short example:
var_1  <- c(1, rep(0,9))
var_2  <- c(0,1, rep(0,8))
var_3  <- c(0,0,1, rep(0,7))
dat  <- data.table(var_1, var_2, var_3)

dat[var_1==1, newvar:=1]
dat[var_2==1, newvar:=2]
dat[var_3==1, newvar:=3]

Any ideas about how to do this with a loop?
Thanks!
Answer: Something like this will work.
nams <- names(dat)
for(n in seq_along(nams)){
  nam <- nams[n]
  char <- sprintf('%s==1',nam)
  dat[eval(parse(text=char)), newvar := n]
}
dat
var_1 var_2 var_3 newvar
1:     1     0     0      1
2:     0     1     0      2
3:     0     0     1      3
4:     0     0     0     NA
5:     0     0     0     NA
6:     0     0     0     NA
7:     0     0     0     NA
8:     0     0     0     NA
9:     0     0     0     NA
10:    0     0     0     NA

Answer: To take advantage of data.table class it is better to set key.
dat[ ,newvar:= NA_integer_]
for(i in ncol(dat)) {
 setkeyv(dat, names(dat)[i])
 dat[J(1), newvar:=i]
}

Comment: Thank you. Do you know how to do that newvar:=1L increases from 1 to the number of variables (e.g., newvar should be equal to 2 for var_2, 3 for var_3, and so on). It is also possible that some variables have a value 1 simultaneously, in that case, I would like to impute just the bigger value (e.g., a case has var_1=1 and var_3=1, I would like to get newvar=3).
Comment: The code above should do this. I would be interested in the performance of repeatedly setting keys compared to sequential but single vector scans on large data.tables
Comment: @WojciechSobala Usually it is better to setkey but setkey has to read every value in the column (scan) in the process of sorting it. So in the special case of a single scan for a single value on a single column, a vector scan should be faster than setkey+join. Worth testing though, I haven't tested that myself.

a simple loop with data.table


Check javascript for missing ";" before compression

Question: I'm doing some optimizations and decided to compress my javascript files using YUI Compressor. The problem is, that some code lines are missing ";" at the end, since javascript allows that and developers do not look too much at this.
Is it going to be a problem when code is compressed? If it is, is there a way to check javascript for lines that are missing ";"?
Comment: I'm not familiar with YUI Compressor, but if it changes the semantics of syntactically valid javascript, then it's broken...
Comment: If you remove newlines in semicolon-less JavaScript it will break.. without the compressor being broken. Besides that, IMO JavaScript where semicolons are not used properly is broken.. they should really screw backwards compatibility and enforce semicolons.. or at least add a mode to enforce it (does `use strict;` already do that?)
Comment: @ThiefMaster I find it a shame that so many people believe that semi-colons somehow reduce the number of problems in code or that ASI is somehow hard to "get right". I can count the number of semi-colons in my code on my fingers. A JavaScript tool that does not understand JavaScript is simply broken. A program who uses semi-colons "because they need to be there" is just as broken. (I'm not against coders who use semi-colons in JavaScript, just those who can't appreciate *others* writing in a semi-colon-free style).
Answer: jsLint can check your code for that. And yes it will most likely cause issues unless the compressor actually contains a JavaScript parser and actively fixes missing semicolons.
Comment: @ThiefMaster You are falsely assuming that lack of semi-colons makes for "crappy code". It does not. Crappy code is crappy code -- semi-colons or not (or "passing" jsLint or not, for that matter). Good code is good code -- semi-colons or not.
Comment: @ThiefMaster That problem is actually mis-attributed to being a problem with ASI. The problem is really that `return` is a "restricted production" (there are 5 of them) -- the *exact same issue would exist without ASI*. Here is a *good* explanation of the problem, along with how to write safe semi-colon free code when a line may continue an expression: [JavaScript Semicolon Insertion Everything you need to know](http://inimino.org/~inimino/blog/javascript_semicolons). See the "Misconceptions" section at the bottom.
Comment: yup jsLint will check for that. It will also hurt your feelings(first quote jsLint.com) ;)
Comment: jsLint doesn't only complain about missing semicolons but other things which might actually mean the code is crappy. But IMO omitting semicolons makes code kind of crappy.
Comment: @ThiefMaster Besides "so and so (insert famous name in JavaScript) says so", can you give one good reason why lack of semi-colons "makes code crappy"? I bet I can counter it with a case against semi-colons. (Btw: If ASI makes codes "cryptic" or "ambiguous" then there is *already* a problem with the code independent of ASI).
Comment: I can give you a reason why the automatic semicolon insertion javascript uses internally sucks: http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/
Comment: @ThiefMaster accepting your answer - precisely what I was looking for :)
Answer: According to this SO answer, YUI Compressor can handle it.
Comment: According to docs ( http://developer.yahoo.com/yui/compressor/#using ):  Preserve unnecessary semicolons (such as right before a '}') This option is useful when compressed code has to be run through JSLint (which is the case of YUI for example). So, this does not do...
Answer: I've done a simple test on three JavaScript compressors: Yuicompressor, Yuglify and Google Closure Compiler. On my PC with Ubuntu 12.10, I've downloaded the binaries of every compressor, and then tested this file on every one of them:
function dbz(){
    var goku = 1
    var vegeta = 2
    var freeza = 3
    console.log(goku + vegeta + freeza)
}
dbz()

And here is the results:
Yuicompressor (2.4.7):
function dbz(){var b=1;var c=2;var a=3;console.log(b+c+a)}dbz();

Yuglify (0.1.2):
function dbz(){var e=1,t=2,n=3;console.log(e+t+n)}dbz();

Closure-Compiler (version 20121212 revision 2388):
function dbz(){console.log(6)}dbz();

Althought this is a very simple example, all of then worked fine on lines with missing semicolons. All of them detected lines without semicolons at the end, added it and removed the line break afterwards.
Answer: You could always use regexp to match for newlines that dont have a ; before them, and naturally make exceptions for stuff like empty lines, )} etc.
But to be honest, if it really doesn't already do this sort of thing automatically, seems like it really is broken \ plain bad.
Comment: Not the best idea to use a regular expression for this sort of thing (in general :-), but you may be interested in [how jsmin works](http://www.crockford.com/javascript/jsmin.html). It won't correctly minify all code, but it does a fair job at most code and explains the (*text replacement*) rules as well as notes some limitations with the approach. Welcome to SO.
Comment: Well explained there. I'm actually using it already with one of my Drupal sites, but haven't read how it actually works. Thanks for the welcome!


Graph-Theory: Find matching in bipartite graph

Question:
Let $G=(V,E)$ be a graph such that $V=X\cup A\cup B$ . $X,A,B$ are independent sets and pairwise disjoint. Suppose that $|X|=63,|A|=|B|=9$, the degree of every vertex in $A\cup B$ is 7, and every vertex in $X$ has exactly 1 neighbor in $A$ and 1 neighbor in $B$. Prove there is $Y \subset X, |Y|=9$ such that for every $v\in A\cup B$ there is $y\in Y$ such that {v,y}$\in E$.

I've realized that every vertex in $A\cup B$ has exactly 7 neighbors in $X$, and that G is bipartite graph. I've tried to find $Y \subset X, |Y|=9$ such that if we'll look at the graph $G'=(A\cup B\cup Y,E')$ when every vertex in $Y$ appears twice in G', it will have a perfect matching. How can I show that?
Thanks
Comment: There seems to be a typo -- the set $Y$ whose existence is to be proved is never mentioned again.
Comment: I corrected it, tahnks
Comment: Is G a simple graph?
Comment: yes, it's a simple graph
Answer: By counting the number of edges between $A$ and $X$, we can first see that $X$ can be partitioned into 9 sets of size 7 each, say $R_1,R_2,\ldots,R_9$ such that each $R_i$ is the neighborhood of one element of $A$. Similarly $X$ can also be partitioned into $S_1,S_2,\ldots,S_9$ such that each $S_i$ is the neighborhood of one element of $B$.
Now we must find a set $T$ of 9 elements such that $T$ intersects all the $R_i$s and all the $S_i$s. To do this, make the auxiliary bipartite graph $H$ with one set of vertices being the $R_i$s and the other set being the $S_i$s and an edge between $R_i$ and $S_j$ if $R_i \cap S_j \neq \emptyset$. Consider the neighborhood of any $k$ $S_i$s. This should have size at least $k$ because their union has exactly $7k$ elements and hence is present in at least $k$ of the $R_i$s. Thus by Hall's theorem, $H$ has a perfect matching and we can pick one element from each of the intersections of the matched sets to obtain $T$.


Vue transition animation with router-view only works for the first transition

Question: I want to make transitions between my navbar elements, so i'm using router-links. The transition works fine for the /about section, but for the others it completely stops working. If i'm on /something and return to /about, the transitions also works, but for other routes it doesn't.
Any advice of what i can do?

App.vue

<template>

    <Navbar/>

      <router-link to="/about"/>
      <router-link to="/experience"/>
      <router-link to="/education"/>
      <router-link to="/contact"/>

    <Transition name="slide-fade" mode="out-in">
      <router-view/>
    </Transition>

</template>

router.js

const routes = [
    {
        path:'/about',
        name: 'About',
        component: About
    },
    {
        path:'/experience',
        name: 'Experience',
        component: Experience
    },
    {
        path:'/education',
        name: 'Education',
        component: Education
    },
    {
        path:'/contact',
        name: 'Contact',
        component: Contact
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

export default router

Answer: Solved it! Had to change my router-view tag for this:
<router-view v-slot="{ Component, route }">
      <Transition name="fade" mode="out-in">

          <component :is="Component"></component>

      </Transition>
    </router-view>

Shoutout to the original solution https://stackoverflow.com/a/70042452/18184367
Comment: Yes! This also saved my problem. The key was to add `:key:route.name` thank you!
Comment: bad decision if u want to use nested routes, they will be blink


Operator Convergence in Hilbert space

Question: I'm wondering if you can check my work and provide help on part of this problem. Here's the question: Let $H$ be Hilbert and $(\phi_n)$ an orthonormal basis. Let $(a_j)$ be a sequence of nonnegative reals such that $a_j \to \infty$. Define $T_n(t) \in B(H)$ by
$$
T_n(t)[u] = \sum_{j=1}^n e^{- a_j t} \langle \phi_j, u \rangle \phi_j
$$
(a) Show that $(T_n(t))_{n=1}^\infty$ converges to some $T(t) \in B(H)$ for any fixed $t \in [0,\infty)$. What is the type of convergence?
(b) Does the limit $T(t)$ converge as $t \to 0$? what is the type of convergence?
Here's my work: It is clear that $\sum_{j=1}^\infty e^{- a_j t} \langle \phi_j, u \rangle \phi_j$ is a bounded linear operator:
$$
\left\| \sum_{j=1}^\infty e^{- a_j t} \langle \phi_j, u \rangle \phi_j \right\|^2 = \sum_{j=1}^\infty | e^{-2 a_j t} | \langle \phi_j, u \rangle|^2 \le \sum_{j=1}^\infty | \langle \phi_j, u  \rangle|^2 = \|u\|^2 < \infty
$$
and linearity is trivial. Also $T_n(t) \to T(t)$ uniformly. Consider $\|u\|=1$, then
$$
\|T(t)  - T_n(t) \|_{op} \le
\left\|  \sum_{j=n+1}^\infty e^{- a_j t} \langle \phi_j, u \rangle \phi_j  \right\|^2
=  \sum_{j=n+1}^\infty |e^{- a_j t}|^2 | \langle \phi_j, u \rangle|^2
\le  \sum_{j=n+1}^\infty | \langle \phi_j,u \rangle|^2 \stackrel{n \to \infty}{\longrightarrow} 0
$$
For part (b), from LDCT we have $\lim \limits_{ t \to 0}  \sum_{j=1}^\infty e^{- a_j t} \langle \phi_j ,u \rangle \phi_j =  \sum_{j=1}^\infty \langle \phi_j, u \rangle \phi_j = u$ so $T(t) \to I$ as $t \to 0$.
But I'm uncertain about the type of convergence here since operator, strong, and weak convergence were defined for sequences of operators... not something like this.
Does my work look OK for  (a) and part of (b)? Also, if you see a better/slicker way to get these results let me know. Studying for an exam.
Answer: The first inequality in your operator norm convergence does not hold (an operator does not necessarily achieve its norm, and even if it did your $u$ would depend on $n$ and $t$). But you have
\begin{align}
\|[T(t)-T_n(t)]u\|^2&=\|\sum_{j=n+1}^\infty e^{-a_jt}\,\langle \phi_j,u\rangle\,\phi_j\|^2=\sum_{j=n+1}^\infty e^{-a_jt}\,|\langle\phi_j,u\rangle|^2\\ \ \\
&\leq \sum_{j=n+1}^\infty |\langle\phi_j,u\rangle|^2\xrightarrow[n\to\infty]{}0.
\end{align}
This shows strong operator convergence. When $t=0$, you cannot do better than that, because $\|T(0)-T_n(0)\|=1$ (it is a projection) for all $n$.
When $t>0$, the exponentials play a role. We have
\begin{align}
\|[T(t)-T_n(t)]u\|^2&=\|\sum_{j=n+1}^\infty e^{-a_jt}\,\langle \phi_j,u\rangle\,\phi_j\|^2=\sum_{j=n+1}^\infty e^{-a_jt}\,|\langle\phi_j,u\rangle|^2\\ \ \\
&\leq \|u\|^2\,\sum_{j=n+1}^\infty e^{-a_j t}.
\end{align}
As $u$ is arbitrary, the above shows that, for $t>0$,
$$
\|T(t)-T_n(t)\|_{\rm op}^2\leq \sum_{j=n+1}^\infty e^{-a_j t}.
$$
Since $a_n\to\infty$ the series is convergent, and so $T_n(t)\to T(t)$ in norm.
Regarding $T(t)$, your argument shows that $T(t)\xrightarrow[t\to 0]{}I$ in the strong operator topology. Note that
\begin{align}
\|[T(t)-I]\phi_k\|^2&=\sum_{j=1}^\infty (1-e^{-a_j t})\,|\langle \phi_j,\phi_k\rangle|^2=1-e^{-a_kt},
\end{align}
which implies that $\|T(t)-I\|_{\rm op}=1$ for all $t>0$.
Comment: Excellent -- thanks for the quick answer. Can you explain again why my operator norm inequality doesn't hold? I don't see why I can't use my above argument with the tail of a convergent series tending to zero. Also, going from $\sum_{j=n+1}^\infty e^{-a_jt}\,|\langle\phi_j,u\rangle|^2
\leq \|u\|^2\,\sum_{j=n+1}^\infty e^{-a_j t}$... are you simply using Parseval's here?
Comment: The operator norm is a supremum, which is not always attained. The inequality that always holds is precisely the opposite one to the one you wrote: $$\|Tu\|\leq\|T\|_{\rm op}\,\|u\|.$$ In the inequality you ask about, I'm using Cauchy-Schwarz: $$|\langle\phi_j,u\rangle|^2\leq\|\phi_j\|^2\,\|u\|^2=\|u\|^2.$$
Comment: Ah, some foolish mistakes on my part. Thanks again for the help, you gave a great explanation
Comment: Glad I could help :)

Operator Convergence in Hilbert space


Formato da data no php

Question: Como mudar o formato da data de 2016-2-26 para 26/02/2016.
Já tentei utilizar o format, mas não deu certo.
Comment: O ideal é que coloque o código que já tentou
Answer: <?php
$time = strtotime('2016-2-26');

$data_formatada = date('d/m/Y',$time);

echo $data_formatada;

Vai imprimir:

26/02/2016
Answer: Jeito mais simples de fazer, trabalhando como String, transformando a data em um array com explode. Não sei se te ajuda ou se queria trabalhar como data mesmo. Segue abaixo:
<?php

$data = '2016-2-26';
$array = explode('-', $data);
$data = $array[2].'/0'.$array[1].'/'.$array[0];
print($data);

Caso não seja isto, informe que posso apagar a resposta.
Comment: Encontrei essa forma:

date('d/m/Y',  strtotime($var))

Formato da data no php


Where should i place my function stage.fullScreenSourceRect using if else statement?

Question: Where should i place my function stage.fullScreenSourceRect using if else statement?
im trying to calcualte device display ratio & positioning the movieclip as per device ratio. i.e if display ratio is 16:9 800 x 450 will positioned n centre.
no error in code. but if else does not working.
<code>    stage.displayState = StageDisplayState.FULL_SCREEN;
    stage.align = StageAlign.TOP_LEFT;
    stage.scaleMode = StageScaleMode.NO_SCALE;
    //stage.fullScreenSourceRect = new Rectangle(0,0,800,600);
    //stage.fullScreenSourceRect = new Rectangle(0,0,800,535);
    //stage.fullScreenSourceRect = new Rectangle(0,0,800,450);

//calcualting device display ratio & positioning the movieclip as per device ratio.
//i.e if display ratio is 16:9 800 x 450 will positioned n centre.

var scrnratinum:Number;
scrnratinum=(stage.stageWidth/stage.stageHeight);
//for 4:3 i.e 1.3
if (scrnratinum<=1.20 && scrnratinum>=1.39)
{
    stage.fullScreenSourceRect = new Rectangle(0,0,800,600);
}
//for 3:2 i.e 1.5
if (scrnratinum<=1.40 && scrnratinum>=1.49)
{
    stage.fullScreenSourceRect = new Rectangle(0,0,800,535);
}
//for 16:9 i.e 1.8
if (scrnratinum<=1.60 && scrnratinum>=1.79)
{
    stage.fullScreenSourceRect = new Rectangle(0,0,800,450);
}

var scrnratio:TextField = new TextField();
scrnratio.text = "Screen Ratio  " + scrnratinum.toFixed(2);
scrnratio.width = 400;
scrnratio.height = 600;
scrnratio.x = 300;
scrnratio.y = 300;
addChild(scrnratio);

//this is the movieclip being loaded. its actual w x h is 800 x 600.
var bringclip = new emptyclip();
addChild(bringclip);
bringclip.x= ((stage.stageWidth)/(2));
bringclip.y= ((stage.stageHeight)/(2));
</code>
Answer: I believe you set the if case wrong. Are you trying to do this ?
<code>if (scrnratinum>=1.20 && scrnratinum<=1.39)
{
    stage.fullScreenSourceRect = new Rectangle(0,0,800,600);
}
//for 3:2 i.e 1.5
if (scrnratinum>=1.40 && scrnratinum<=1.49)
{
    stage.fullScreenSourceRect = new Rectangle(0,0,800,535);
}
//for 16:9 i.e 1.8
if (scrnratinum>=1.60 && scrnratinum<=1.79)
{
    stage.fullScreenSourceRect = new Rectangle(0,0,800,450);
}
</code>


Kotlin ImageView Problem With GetView Function Type Mismatch

Question: I have having problems on the fourth line. In my code, getLogo returns an integer (ID) of an image. I now want to use the drawable ID for the image and put in in a ImageView with the specified id. However, on the left hand of the equal sign, I am getting the error of variable expected and on the right side it says Type Mismatch ... Required: ImageView Found: Int.
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    val layoutInflator = LayoutInflater.from(context)
    val row = layoutInflator.inflate(R.layout.layoutlistviewloan, parent, false)
    row.findViewById<ImageView>(R.id.institutionImage) = loansModel.loan[position].institution.getLogo()
}

Answer: findViewById() is a function that returns a View (in this case you're saying it's an ImageView). It's not a variable (val or var) that you can assign a value to.
I'm guessing you want to find that ImageView in the layout, and then set it to display your drawable ID. So you need to chain a setImageResource call to the ImageView after you grab it
row.findViewById<ImageView>(R.id.institutionImage).setImageResource(drawableId)

you could stick the "getting the drawable ID" code in there as the setImageResource parameter
row.findViewById<ImageView>(R.id.institutionImage).setImageResource(loansModel.loan[position].institution.getLogo())

but personally I'd just set that as a variable to make it more readable instead of doing too much in one line (it can get confusing!)
val logoId = loansModel.loan[position].institution.getLogo()
row.findViewById<ImageView>(R.id.institutionImage).setImageResource(logoId)


How to add a class or id wrapper to a

Question: I added a footer to a view and I need to give this footer a wrapper class or id. How can I accomplish with this?
Answer: You  an can put HTML in there, just make sure you choose an Input Format (Text Formats in D7) that allows you to use the HTML tags you'll be putting in there.
Answer: $('#yourfooter').addClass('yourClass');

Or views-view--YOURVIEWNAME.tpl.php and you can add you class there.
Do you want to give it to the footer or to the field?
You can even write in the field
it is easier to smash an atom than a prejudice.

Answer: You can also theme this footer using the oft forgotten cascading properties of CSS, eg, if your view is named foobarbaz:
 .view-foobarbaz .view-footer {
    color: red;
    font-weight: bold;
 }

will make all the footer text bold and red.

How to add a class or id wrapper to a


Declared property with enums?

Question: I want to have a property such as color, which only accepts a certain set of colors.
I was hoping to do something like this:
properties: {
    color: {
        type: String,
        enum: ['red', 'blue']
    }
}

I cannot find anything about support for enums within declared properties.  Is the only way to implement this by manually checking the values against my set of accepted values?
Answer: There's no built-in support for enums, but you could do this with an observer:
properties: {
  color: {
    type: String,
    default: 'red',
    observer: '_enumColor'
  }
},
_enumColor: function(newValue, oldValue) {
  var validColors = ['red','green','blue'];
  if(validColors.indexOf(newValue) === -1) {
    // Put the color back, and maybe throw in a line to throw an error
    this.color = oldValue;
  }
}

Declared property with enums?


Recording HTTP in Python with Scotch

Question: I am trying to record HTTP GET/POST requests sent by my browser using the library scotch.
I am using their sample code: http://darcs.idyll.org/~t/projects/scotch/doc/recipes.html#id2
<code> import scotch.proxy
 app = scotch.proxy.ProxyApp()

 import scotch.recorder
 recorder = scotch.recorder.Recorder(app, verbosity=1)

 try:

     from wsgiref.simple_server import WSGIServer, WSGIRequestHandler

     server_address = ('', 8000)
     httpd = WSGIServer(server_address, WSGIRequestHandler)

     httpd.set_app(app)

     while 1:
        httpd.handle_request()

 finally:

    from cPickle import dump
    outfp = open('recording.pickle', 'w')
    dump(recorder.record_holder, outfp)
    outfp.close()

    print 'saved %d records' % (len(recorder.record_holder))
</code>
So I ran above code, went over to google chrome, and visited a few sites to see if that would get recorded.
However, I do not see how the code should terminate. It seems that there has to be an error in httpd.handle_request() for the code to terminate.
I tried a variation of the code where I removed the try and finally syntax, and changed the while condition so that the loop ran for 30 seconds. However, that seems to be running forever as well.
Any ideas on how to get this working? I am also open to using other python libraries available for what I am trying to do: record my browser's GET/POST requests, including logons, and replay this within python.
Thanks.
Comment: Did you change the proxy settings in the browser? Do you see that this code is running?
Comment: Hey, I did not change any proxy settings on the browser (I guess because there were no instructions on this). I guess my knowledge is lacking in regards to how this library works. And yes, the code was running on pyscripter according to the status bar. Any help would be appeciated, or a point in the right direction where I can read about proxies and how this all works.
Answer: Correct me if I'm wrong, but you're trying to log the activity of your local browser by setting a local proxy.  If this is the case your browser needs to go through your proxy in order for your proxy server to log the activity.
The code that you've provided sets a proxy server at localhost:8000, so you need to tell your browser about this.  The actual setting depends on the browser, I'm sure you'd be able to google it easily.
When I've asked to check if the code is running I actually mean whether your local proxy accepts some kind of request from the browser. Do you see the 'saved records' print out of your code at some point?
Comment: Hey Alex, yes you are right about what I am trying to do. I changed firefox's proxy to 8000 (tools -> options -> advanced -> network tab -> settings) ~ [screenshot](http://imgur.com/qJ6pvUl). It seems the code is getting stuck on this line: httpd.handle_request(). I guess because it isn't seeing any activity on port 8000? I refactored the code to make it simpler to debug: http://pastebin.com/frSu0edL (this is what I am running atm and it runs forever).
Comment: Hey, it works! I added the localhost address 127.0.0.1 for the HTTP Proxy address and I get some of my activity recorded. I'm sure with fiddling around I can figure out the rest. Thanks a lot bro! I would upvote but not enough karma atm. Will upvote when I am able.

Recording HTTP in Python with Scotch


Create a Term Queue on views

Question: I have a views showing some selected terms of a vocabulary. The Views block is created using Taxonomy Terms as content(show). It showing order by the terms tree. But my client want to sort it as their business policy(most popular on top).
Is there any way to sort the terms like custom way as node queue.
Please suggest me any module, hooks or other custom solutions.
Here is my views settings :

Thanks in advance.
Note that I want to sort the terms Not the entities tagging with it.
I have installed nodequeue and smartqueue but unable to achieve the requirment.
Answer: Views Aggregation to count nodes tagged by terms
You can use Views Aggregation to count the number of nodes that each tag is assigned to, and use that as the Sort criteria.

In the Views of type Taxonomy term filter all the terms you're interested about. Add a Name Field to show the term name (you probably already have that covered)
Add a Relationship to the content that the terms are related to Content using field_yourname
Turn on Aggregation (Under Advanced, third column)
Add a Sort criteria Content: Title, (it will automatically use the Relationship from above), Sort descending and adjust its Aggregation settings to Count DISTINCT (if you allow nodes to use multiple terms then Count will count them more than once)

Your terms list will be sorted by the number of nodes tagged by each term in your Views results.
Views Summary for single value fields
If your Taxonomy term reference Field allows for only one value you can use Views summary in a Contextual filter to count the nodes tagged with a term.
You can do it from Taxonomy term Views or Content Views.

If starting from Taxonomy term Views you can use the above steps,
only instead of using Aggregation add a new Contextual filter Name from Taxonomy term Category and configure it to display a Summary:
When the filter value is NOT available
Display a summary
Sort order Descending
Sort by Number of records
Format List
Base path (you must enter the Page path if this isn't the first Page Display in your Views)
Display record count with link

This way you get a list of Taxonomy terms with node count next to them. When you click on them you go to another page listing the actual Fields you set up in Views (you'll probably want to list Content: Title here).
It's a similar procedure to do that from Content Views type.

You'll want to add a Relationship to the relevant Taxonomy field (Taxonomy term referenced from field_yourname),
then add a Contextual filter for Taxonomy term: Name, use the Relationship and configure it to display as a Summary.
Answer: Yes, you can add a sort option for Taxonomy term (weight), then they can reorder the terms on the taxonomy's overview page, e.g. /admin/structure/taxonomy/manage/VOCABULARY_ID/overview), or, if that's not sufficient, there's the Entityqueue module.
Comment: There are at most 100 terms with 3rd level child. And it might be increase. So change the weight value is not a suitable. Will looks into the Entity Queue.
Comment: Entityqueue  Worked for me.
Thank you very much. @sonfd
Answer: To sort Category terms list created using views. We can use  EntityQueue.
To do that We need to install the EntityQueue module. Then add a entity Queue for taxonomy terms from : admin/structure/entityqueue
Then add term items to the queue as we want to sort.
From here we can shuffle the queue or change the sorting. After that we need to add  an Entityqueue relationship to our view, and adding a sort for Entityqueue position.
That way we can achieve the sorting as provided on entity queue.
Note that: We need to make sure the term on the queue list is exist on output of the view.

Create a Term Queue on views


Invertible 1D map cannot be chaotic

Question: In a compendium I have on chaos theory it is claimed, but not proven, that an invertible 1D map $x(k+1)=f(x(k))$ cannot be chaotic, since it will not display sensitivity on initial conditions.
I assume then that they claim that the Lyapunov exponent for such a map is necessarily negative (for all initial conditions). How can one show this?
Typically we define the Lyapunov exponent as $$\lambda = \lim_{n \to \infty} \frac{1}{n}\sum_{k=0}^{n-1}\ln |f'(x(k))|. $$
It is not apparent to me how we can infer $\lambda < 0$ by knowing that $f$ is invertible.
Answer: Looking at the Lyapunov exponents or sensitivity on initial conditions alone alone won't suffice. For example for $f(x)=5x$, you obviously have $λ=\ln(5)$ (which is the correct result) and sensitivity on initial conditions.
However, this example is also not chaotic – the dynamics is not bounded. A typical chaotic dynamics achieves the combination of boundedness and a positive Lyapunov exponent by stretching on the local scale (positive Lyapnov exponent) and folding on the scale of the attractor/state space (boundedness). And the latter operation is not invertible.
A little bit more formal: Suppose $f$ is piecewise continuous, invertible, and chaotic with its dynamics bounded to the interval $I$. Then for every $k$, we can divide $I$ into non-overlapping intervals $I_1, …, I_n$ such that $f^k$ is continuous on the inside of each of them. For these, we have
$$|R| = \sum_{j=1}^n \left | I_j\right|.$$
Since $f$ is non-invertible, the $f(I_1), …, f(I_n)$ must be non-overlapping and we have:
$$\sum_{j=1}^n \left | \,f^k(I_j)\right| ≤ |R|.$$
Now if $|f'(·)|>1$ on some interval $J$, then $|f(J)| > |J|$. More generally, if $\sum_{k=0}^{n-1} \ln \left( \left |\, f'(\,f^k(·)) \right | \right ) > 0$ on $J$, then $|f^k(J)| > J$. If the dynamics is supposed to have a positive Lyapunov exponent, the aforementioned expanding of intervals must apply on average (and for sufficiently high $k$), i.e.:
$$
\sum_{j=1}^n \left | I_j\right|
< \sum_{j=1}^n \left | \,f^k(I_j)\right|
.$$
Putting the three equations together, we achieve the reductio ad absurdum:
$$
  |R|
= \sum_{j=1}^n \left | I_j\right|
< \sum_{j=1}^n \left | \,f^k(I_j)\right|
< |R|
.$$
Comment: Thanks! You mean to assume that $f$ is invertible and not non-invertible, right? Ok, I understand your argument and I know a bit about the intuition behind this "stretch and fold". Is there however a more rigorous mathematical argument, specifically justifying the second inequality?
Comment: @ÉtienneBézout: *You mean to assume that $f$ is invertible and not non-invertible, right?* – Indeed, amended. — *Is there however a more rigorous mathematical argument, specifically justifying the second inequality?* – I tried to expand my reasoning of this part, but I am afraid that going further will expand things considerably.
Comment: Alright, thanks!

Invertible 1D map cannot be chaotic


Can we use double accidentals in figured bass?

Question: I've composed the following figured bass example:

It modulates from E to F and therefore needs several chromatic alterations. But my question is on the final beat of the third measure: if I want a B♭-minor chord here, is this the correct figured bass? As I see it, there are at least three possibilities for how to handle this chord:

Write it as I have; the ♮5 lowers F♯ to F♮ and the ♭♭3 lowers the D♯ to D♭.
Use a system where the figured bass shows the literal accidentals, not the adjustments from the key signature; in this system, ♮5 would give me F♮ and ♭3 would be enough to suggest D♭.
Use ♮♭3 to indicate first a change from the key signature's D♯ to D♮ and then a move from D♮ to D♭.

What would be the correct approach here? Ideally I would have a citation from a published figured bass manual (perhaps Heinichen?).
I've never seen a double accidental in a published figured bass before, likely because that repertoire doesn't often get this chromatic. As such, I'm uncertain how best to notate this.
Comment: It looks like you're already in the new key in bar 3, why not change keysigs there? Or is it just a temporary modulation?
Comment: You start off in E major. Why aren't you using an A sharp minor chord in that position?
Comment: I think you have added one too many flats on the 3.  Shouldn't it just be a 'b' to make it a Db note?
Comment: @Dekkadeci It's functioning as iv in the new key.
Comment: @Jomiddnz That's basically my question!
Comment: I agree with LS07. otherwise the bb3 should be o.k.
Comment: @LSM07 Fair point, but I'd prefer not to change key signatures. This is less a full-blown modulation and just a temporary tonicization of F.
Answer: This is a cut and paste answer so please consider double checking my source, I could have taken this paragraph out of context. The frustrating thing is there are no musical illustrations regarding figures with double sharps/flats to go with the rule! I scanned the other pages but could not find an example. Anyhow, your first choice matches up with Albrechtsberger.

https://books.google.com/books?id=kjoDAAAAQAAJ

...page 35 or 36 in the Google book.

EDIT
I was able to find a double sharp figure further into the book. The illustration shows both the accidental in the figured bass and in a full notated chord. The figure and notation accidentals match...

I think this makes Albrechtsberger's meaning clear, and it is the meaning I original thought he meant. Whatever accidental would be used in notation, that will be the accidental to use on a figure for a 3 interval.

That example from p.56 isn't a double flat/double sharp, but it shows a flat in the key signature being raised. In notation that change is achieved with a natural sign. In the bass figure it is not a case of using sharp to mean "raise by a half step" but instead it matches the accidental of the staff notation.
I didn't find a double flat example, but I imagine it would follow the same course and that Richard's 3 would seem to follow Albrechtsberger.
Comment: I literally couldn't have asked for a more clear citation. Great detective work!
Comment: So you suggest that writing ♮5 indicates lowering F# by a semitone to F, while ♭♭ lowers D# by a whole tone to D♭ (@Richard first choice)?! I don't believe the quoted paragraph supports this!
Comment: @Richard but this quotation doesn't answer the question.  For all we know, Albrechtsberger is thinking of, for example, figuring a minor third above G flat when the key signature is G flat major.  The figure that Albrechtsberger would have chosen for this example isn't at all clear.
Comment: @phoog, I went back searching in that Google book and I think I found a clarifying example. It is with a double sharp, not flat, but it included the bass figure and the chord fully notated. I added the examples to my answer.


limit unreserved concurrency of a lambda function

Question: I don't find the AWS documentation very clear on this, but it seems like there is no way to limit the unreserved concurrency of an AWS Lambda function. Instead it requires a reserved concurrency, which has to be provisioned and therefor comes at an additional costs.
Is that correct?
And even when I try to add a concurrency configuration it fails to apply it for the "$LATEST" version. Why is that?
resource "aws_lambda_provisioned_concurrency_config" "deliver" {
  function_name                     = aws_lambda_function.deliver.function_name
  qualifier                         = aws_lambda_function.deliver.version
  provisioned_concurrent_executions = 1
}

Answer: Reserved concurrency doesn't have to be provisioned. If you only set reserved_concurrent_executions on the lambda_function resource, instead of creating a aws_lambda_provisioned_concurrency_config resource, then it will simply limit the amount of concurrency for the function. This will also guarantee that the other functions in your account don't use up your Lambda concurrency account limits in a way that prevent this function from executing.
The reserved_concurrent_executions property controls the concurrency limit feature.
The aws_lambda_provisioned_concurrency_config resource controls the provisioned concurrency feature.
Comment: Perfect! Thanks! I knew I must be missing something simple.
Answer: I believe Reserved Concurrency will do what you're looking for. You can also use autoscaling to control the level of provisioned concurrency (and perhaps even Reserved Concurrency?) based on utilisation.
But you can't allocate provisioned concurrency on an alias that points to the unpublished version ($LATEST).
Answer: If your Lambda is being used specifically to process SQS messages, a MaxConcurrency property can be specified on the SQS Event Source properties. This helps to prevent re-queued and DLQ'd messages by limiting the number of in flight messages rather than terminating Lambda instances.
The was added in January 2023 and is documented in the AWS Blogs. Note that this only applies to SQS triggered lambdas and is applied per SQS event source -- Subscribing the lambda to multiple SQS queues will be limited per queue, not function.


It fails to compile a c++ map structure as map >

Question: I have a code in c++ with stl map with the second parameter defined as a pair
int keys[10] = {1, 1, 1, 2, 3, 4, 5, 7, 6, 6};
char s[5];
map< unsigned int, pair<string, int> > tmpMap;

for (int i=0; i<10; i++)
{
  if (tmpMap.find(keys[i])==tmpMap.end())
  {
    sprintf(s, "%i", keys[i]);
    tmpMap.insert(make_pair(keys[i], make_pair(s, 1)));
  }
  else tmpMap[keys[i]].second++;
}

for (map< unsigned int, pair<string, int> >::iterator it=tmpMap.begin();   it!=tmpMap.end(); ++it)
{
cout << (*it).first << "  " << (*it).second << endl;
}

But it fail to compile, it said, no match operator <<. But (*it).first and (*it).second are just string and int, why it doesn't work?
Comment: Wouldn't (*it).first be an unsigned int, and (*it).second be pair?
Answer: That's not true, first is an unsigned int, while second is a pair<string,int> because the iterator of a map doesn't give you directly the pair but the couple key,value.
I guess you should do
pair<string,int> pair = (*it).second;
cout << pair.first << "  " << pair.second << endl;

Comment: Add `&` to it to avoid copying: `pair &pair = (*it).second;`
Comment: I'm thinking he might want to use the reference of (*it).second, unless performing a copy every time is ok.
Comment: Yes, it's a waste of copy indeed.
Comment: Better yet `pair &pair = it->second;` which is clearer
Comment: Thank guys. I think I misunderstand the usage of the iterator. I thought it gives the value each time. Anyway, thanks for your help.
Answer: Your (*it).second is pair , you need to have
cout << (*it).first << "  " << (*it).second.first << " " <<
(*it).second.first << endl;

This is since when iterating over map, you get pair, then first is the key and second is the value - in your case a pair also.


Criar botão via código

Question: É possível criar um Button por meio do código, ao invés do modo design (xml)?
Por exemplo: Vou criar uma tela com um EditText, digitar um número, e clicar em um Button.
Após isso, será criado x (número digitado) EditText abaixo do botão.
Comment: Já deu uma olhada na documentação oficial do Google ? É muito boa, acho que você conseguirá tirar sua dúvida !
Comment: Sim, já olhei e não achei nada específico a respeito :/
Answer: Primeiramente você precisa definir onde irá colocar seu botão (um container, por exemplo):
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_teste"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Texto" />

    <FrameLayout
        android:id="@+id/container_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Após isso, em seu código você pode adicionar um Button para este container:
FrameLayout container = (FrameLayout) findViewById(R.id.container_button);

//Criando um botão passando o contexto
Button button = new Button(this);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
button.setText("Algum texto");

//Adicionando o botão na tela
container.addView(button);

Comment: Deu certo. Muito obrigado

Criar botão via código


How to make simple python generator from nested generator, "Generator in Generator"?

Question: I'm tring to solve "EULER's conjecture on sums of like powers" problem for fun. Fun.

My goal is below.

use multicores
memory efficiency

I almost finished, But generator part is problem.
my code is below.
from pqdm.processes import pqdm # this is parallel package.
from itertools import combinations_with_replacement, chain
from math import pow

max_iter = 1+4
max_a = 1000
nk_pairs = {
    (combinations_with_replacement(range(1, max_a), r=n), k)
    for k in range(1, max_iter)
    for n in range(1, k+1)
}
# ↑↑↑↑↑↑↑ this line is the problem.

def clear_root(val, k):
    """ define val is k power of integer """
    _ = pow(val, 1/k)
    if int(_) == _:
        return True
    return False

def func(array, k):
    sum_ = sum([pow(x, k) for x in array])
    if clear_root(sum_, k):
        return array, k

pqdm(nk_pairs, func, n_jobs=24)

All combinations are generated by generator, but, nested generator doesn't fit for parallel functions.
How can I make this nested generator to un-nested?
Comment: You don't have **any** generator, let alone a nested one. What are you referring to? And what do you mean with "simple" generator?
Comment: `return int(_) == _`
Comment: Also, `clear_root` is broken in its current state. Consider that due to floating point rounding errors, the result of `pow(4**3, 1/3)` is actually `3.9999999999999996`. It will return `False`, yet the input is definitely a power of 3.
Comment: Can you show for a simple example what you want to get as result for `nk_pairs`?
Comment: The paper talks about nth powers. You use kth powers. I find that a bit confusing.
Comment: "memory efficiency" -- right now it's still queueing tasks here (after 5 minutes, but that might be OS-caused) and the Python process already consumes over a gigabyte. And all this memory usage is not really helping improve performance (like sparing a few kilobytes to cache all the powers, so you don't recalculate that all the time).
Answer: pqdm doesn't recognize nested iterators/generators. To make that work you would need to build a single generator as shown below (for sample max_a = 100):
from pqdm.processes import pqdm # this is parallel package.
from itertools import combinations_with_replacement, chain
from math import pow

max_iter = 1+4
max_a = 100

def nk_pairs_gen():
    for k in range(1, max_iter):
        for n in range(1, k + 1):
            for c in combinations_with_replacement(range(1, max_a), r=n):
                yield (c, k)

def clear_root(val, k):
    """ define val is k power of integer """
    _ = pow(val, 1/k)
    return int(_) == _

def func(arr, k):
    if clear_root(sum(pow(x, k) for x in arr), k):
        return arr, k

res = pqdm(nk_pairs_gen(), func, n_jobs=12, argument_type='args')

Note, that res would contain a lot of None values as returned by func function, to filter them out use:
res = list(filter(None, pqdm(nk_pairs_gen(), func, n_jobs=12, argument_type='args')))

The output:
QUEUEING TASKS | : 4598121it [01:34, 48869.83it/s]
PROCESSING TASKS | : 100%|██████████| 4598121/4598121 [11:28<00:00, 6679.72it/s]
COLLECTING RESULTS | : 100%|██████████| 4598121/4598121 [01:09<00:00, 65887.49it/s]

Update:
Considering that pqdm might in classical way pass each single combination to a separate process, which is not efficient, a more optimal way would be to yield the entire set of combinations for a given k passed to a processing function modified for multiple combinations (run in a separate process). Sample on max_a = 200:
max_iter = 1+4
max_a = 200

def nk_pairs_gen():
    for k in range(1, max_iter):
        for n in range(1, k + 1):
            yield (combinations_with_replacement(range(1, max_a), r=n), k)

def clear_root(val, k):
    """ define val is k power of integer """
    _ = pow(val, 1/k)
    return int(_) == _

def main_func(combs, k):
    return [(c, k) for c in combs
            if clear_root(sum(pow(x, k) for x in c), k)]

res = list(chain.from_iterable(pqdm(nk_pairs_gen(), main_func, n_jobs=12, argument_type='args')))
print(res[:30])

QUEUEING TASKS | : 10it [00:00, 530.94it/s]
PROCESSING TASKS | : 100%|██████████| 10/10 [00:57<00:00,  5.73s/it]
COLLECTING RESULTS | : 100%|██████████| 10/10 [00:00<00:00, 202623.38it/s]
[((1,), 1), ((2,), 1), ((3,), 1), ((4,), 1), ((5,), 1), ((6,), 1), ((7,), 1), ((8,), 1), ((9,), 1), ((10,), 1), ((11,), 1), ((12,), 1), ((13,), 1), ((14,), 1), ((15,), 1), ((16,), 1), ((17,), 1), ((18,), 1), ((19,), 1), ((20,), 1), ((21,), 1), ((22,), 1), ((23,), 1), ((24,), 1), ((25,), 1), ((26,), 1), ((27,), 1), ((28,), 1), ((29,), 1), ((30,), 1)]

Comment: An optimization: `n_jobs=1`. That seems to be ~200 times faster for me.
Comment: On Windows with Python 3.7, this still spews out a lot of errors due to missing `if __name__ == '__main__':` for the last line...
Comment: So... amusingly, it might be better to leave their "nested generator", the one thing they complain about, as it is. And change their `func` instead. So that each process builds arrays itself instead of expensively having them sent (I think that's what's happening if you use `n_jobs` > 1).
Comment: @KellyBundy, I'm already testing that version on `max_a = 1000`, but it doesn't seem to run fast
Comment: Maybe try just 150. That should be enough to find the paper's counterexample.
Comment: Yeah, IMHO it schedules the jobs at too fine a granularity (one iteration of the generator at a time?), which I'd imagine will also involve a lot of overhead in progress reporting.
Comment: Oh, I misread their nk_pairs, I thought it's finer granularity than it is. It only has 10 elements. And likely the "largest" one would dominate the time. So it should be finer than that, but less fine than the current answer.
Comment: @KellyBundy, bigger chunks (combinations) version on `max_a = 200` runs comparatively good, but really starts slow down when progressing `max_a` with  another `+100`s
Comment: I suppose this is not really about how to optimize it, but if you move the `pow(x, k)` from `func` to the inner loop of `nk_pairs_gen`, you avoid a lot of redundant recalculations, and even a naive single-threaded implementation takes slightly below 40% of the original time. | Also, since the conjecture only applies for `n > 2`, the generator only needs to consider `k` in `range(3, max_iter)`. Along the same note, it applies to **sums**, so `n` should start at `2` instead of `1` (avoiding all the false positives, although those were a good indicator of the brokenness of `clear_root`).
Comment: Ah, and since we also only want to provide a counter-example, then there's no point for `n` to run all the way to `k`... so `for n in range(2, k)`.
Comment: Now, if I rewrite `clear_root` to something like this: `return round(pow(val, 1/k))**k == val`, which might not be optimal, but actually returns the right result... I'm at about 2 minutes on a 10 year old CPU (i7-4930k), running single threaded (no pqdm).
Comment: @DanMašek, `round` might not put much accuracy to the result. `int(np.cbrt(7) ** 3) == np.cbrt(7) ** 3` would still give `False` (if OP really considers only integer `kth` root of sum)
Comment: Sorry, you lost me there. I also don't see how that example is relevant -- we're checking whether `val` (the sum) is a `k`th power of some integer, right? I suppose an epsilon compare might be better, this was a clumsy way of avoiding it.