How to add column for every month and generate number i.e. 1,2,3..etc

Question: I have a huge csv file of dataframe. However, I don't have the date column. I only have the sales for every month from Jan-2022 until Dec-2034. Below is the example of my dataframe:
import pandas as pd

data = [[6661, 'Mobile Phone', 43578, 5000, 78564, 52353, 67456, 86965, 43634, 32546, 56332, 58944, 98878, 68588, 43634, 3463, 74533, 73733, 64436, 45426, 57333, 89762, 4373, 75457, 74845, 86843, 59957, 74563, 745335, 46342, 463473, 52352, 23622],
        [6672, 'Play Station', 4475, 2546, 5757, 2352, 57896, 98574, 53536, 56533, 88645, 44884, 76585, 43575, 74573, 75347, 57573, 5736, 53737, 35235, 5322, 54757, 74573, 75473, 77362, 21554, 73462, 74736, 1435, 4367, 63462, 32362, 56332],
        [6631, 'Laptop', 35347, 36376, 164577, 94584, 78675, 76758, 75464, 56373, 56343, 54787, 7658, 76584, 47347, 5748, 8684, 75373, 57573, 26626, 25632, 73774, 847373, 736646, 847457, 57346, 43732, 347346, 75373, 6473, 85674, 35743, 45734],
        [6600, 'Camera', 14365, 60785, 25436, 46747, 75456, 97644, 63573, 56433, 25646, 32548, 14325, 64748, 68458, 46537, 7537, 46266, 7457, 78235, 46223, 8747, 67453, 4636, 3425, 4636, 352236, 6622, 64625, 36346, 46346, 35225, 6436],
        [6643, 'Lamp', 324355, 143255, 696954, 97823, 43657, 66686, 56346, 57563, 65734, 64484, 87685, 54748, 9868, 573, 73472, 5735, 73422, 86352, 5325, 84333, 7473, 35252, 7547, 73733, 7374, 32266, 654747, 85743, 57333, 46346, 46266]]

ds = pd.DataFrame(data, columns = ['ID', 'Product', 'SalesJan-22', 'SalesFeb-22', 'SalesMar-22', 'SalesApr-22', 'SalesMay-22', 'SalesJun-22', 'SalesJul-22', 'SalesAug-22', 'SalesSep-22', 'SalesOct-22', 'SalesNov-22', 'SalesDec-22', 'SalesJan-23', 'SalesFeb-23', 'SalesMar-23', 'SalesApr-23', 'SalesMay-23', 'SalesJun-23', 'SalesJul-23', 'SalesAug-23', 'SalesSep-23', 'SalesOct-23', 'SalesNov-23', 'SalesDec-23', 'SalesJan-24', 'SalesFeb-24', 'SalesMar-24', 'SalesApr-24', 'SalesMay-24',  'SalesJun-24', 'SalesJul-24']

Since I have more than 10 monthly sales column, I want to loop the date after each of the month sales column. Then, the first 6 months will generate number 1, while the next 12 months will generate number 2, then another 12 months will generate number 3, another subsequent 12 months will generate number 4 and so on.
Below shows the sample of result that I want:

Is there any way to perform the loop and adding the date column beside each of the sales month?
Answer: Here is the simplest approach I can think of:
for i, col in enumerate(ds.columns[2:]):
    ds.insert(2 * i + 2, col.removeprefix("Sales"), (i - 6) // 12 + 2)

Answer: Here's a little solution : (I put the year unstead of your 1, 2, ... incrementation since i thought it is more representative, but you can change it easily)
idx_counter = 0
for idx, col in enumerate(ds.columns):

    if col.startswith('Sales'):
        date = col.replace('Sales', '')
        year = col.split('-')[1]
        ds.insert(loc=idx + 1 + idx_counter, column=date, value=[year] * ds.shape[0])
        idx_counter += 1

output:
     ID       Product  SalesJan-22 Jan-22  SalesFeb-22 Feb-22  SalesMar-22 Mar-22  SalesApr-22 Apr-22  ...  SalesMar-24 Mar-24  SalesApr-24 Apr-24  SalesMay-24 May-24  SalesJun-24 Jun-24  SalesJul-24 Jul-24
0  6661  Mobile Phone        43578     22         5000     22        78564     22        52353     22  ...       745335     24        46342     24       463473     24        52352     24        23622     24
1  6672  Play Station         4475     22         2546     22         5757     22         2352     22  ...         1435     24         4367     24        63462     24        32362     24        56332     24
2  6631        Laptop        35347     22        36376     22       164577     22        94584     22  ...        75373     24         6473     24        85674     24        35743     24        45734     24
3  6600        Camera        14365     22        60785     22        25436     22        46747     22  ...        64625     24        36346     24        46346     24        35225     24         6436     24
4  6643          Lamp       324355     22       143255     22       696954     22        97823     22  ...       654747     24        85743     24        57333     24        46346     24        46266     24

Answer: This should do the trick.
import math
new_cols = []
old_cols = [x for x in df.columns if x.startswith('Sales')]
for i, col in enumerate(old_cols):
    new_cols.append(col[5:])
    if i < 6:
        val = 1
    else:
        val = ((i+6)/12)+1
    df[col[5:]] = math.floor(val)

df[['ID', 'Product'] + [x for y in zip(old_cols, new_cols) for x in y]]

Answer: Here is a vectorial approach (using insert repeatedly is inefficient):
# convert (valid) columns to datetime
cols = pd.to_datetime(ds.columns, format='Sales%b-%y', errors='coerce')
# identify valid dates
m = cols.notna()
# get year
y = cols[m].year
# calculate number (1 for first 6 months, then +1 per 12 months)
num = ((cols[m].month+12*(y-y.min()))+5)//12+1

# slice dates columns, assign the number, rename
df2 = (ds.loc[:, m].assign(**dict(zip(ds.columns[m], num)))
         .rename(columns=lambda x: x[5:])
       )

# get new order of columns
idx = np.r_[np.zeros((~m).sum()), np.tile(np.arange(m.sum()), 2)+1]
# concat and reorder
out = pd.concat([ds, df2], axis=1).iloc[:, np.argsort(idx)]

print(out)

output:
     ID       Product  SalesJan-22  Jan-22  SalesFeb-22  Feb-22  SalesMar-22  Mar-22  SalesApr-22  Apr-22  SalesMay-22  May-22  SalesJun-22  Jun-22  SalesJul-22  Jul-22  SalesAug-22  Aug-22  Sep-22  SalesSep-22  Oct-22  SalesOct-22  SalesNov-22  Nov-22  Dec-22  SalesDec-22  Jan-23  SalesJan-23  Feb-23  SalesFeb-23  SalesMar-23  Mar-23  Apr-23  SalesApr-23  SalesMay-23  May-23  SalesJun-23  Jun-23  Jul-23  SalesJul-23  SalesAug-23  Aug-23  Sep-23  SalesSep-23  SalesOct-23  Oct-23  Nov-23  SalesNov-23  Dec-23  SalesDec-23  Jan-24  SalesJan-24  Feb-24  SalesFeb-24  Mar-24  SalesMar-24  Apr-24  SalesApr-24  May-24  SalesMay-24  SalesJun-24  Jun-24  SalesJul-24  Jul-24
0  6661  Mobile Phone        43578       1         5000       1        78564       1        52353       1        67456       1        86965       1        43634       2        32546       2       2        56332       2        58944        98878       2       2        68588       2        43634       2         3463        74533       2       2        73733        64436       2        45426       2       3        57333        89762       3       3         4373        75457       3       3        74845       3        86843       3        59957       3        74563       3       745335       3        46342       3       463473        52352       3        23622       4
1  6672  Play Station         4475       1         2546       1         5757       1         2352       1        57896       1        98574       1        53536       2        56533       2       2        88645       2        44884        76585       2       2        43575       2        74573       2        75347        57573       2       2         5736        53737       2        35235       2       3         5322        54757       3       3        74573        75473       3       3        77362       3        21554       3        73462       3        74736       3         1435       3         4367       3        63462        32362       3        56332       4
2  6631        Laptop        35347       1        36376       1       164577       1        94584       1        78675       1        76758       1        75464       2        56373       2       2        56343       2        54787         7658       2       2        76584       2        47347       2         5748         8684       2       2        75373        57573       2        26626       2       3        25632        73774       3       3       847373       736646       3       3       847457       3        57346       3        43732       3       347346       3        75373       3         6473       3        85674        35743       3        45734       4
3  6600        Camera        14365       1        60785       1        25436       1        46747       1        75456       1        97644       1        63573       2        56433       2       2        25646       2        32548        14325       2       2        64748       2        68458       2        46537         7537       2       2        46266         7457       2        78235       2       3        46223         8747       3       3        67453         4636       3       3         3425       3         4636       3       352236       3         6622       3        64625       3        36346       3        46346        35225       3         6436       4
4  6643          Lamp       324355       1       143255       1       696954       1        97823       1        43657       1        66686       1        56346       2        57563       2       2        65734       2        64484        87685       2       2        54748       2         9868       2          573        73472       2       2         5735        73422       2        86352       2       3         5325        84333       3       3         7473        35252       3       3         7547       3        73733       3         7374       3        32266       3       654747       3        85743       3        57333        46346       3        46266       4


MySQL's max_questions error is being thrown even for 1 query when the limit is 18000

Question: I've been working on this problem for a few hours now and I'm close to jumping from the Heroku platform purely out of frustration.
I have a simple web app running on Heroku which uses PHP and MySQL with Silex and AngularJS. The MySQL DB (running on ClearDB's service) has two tables: one is empty while the other has one row of data. When the app loads, I use AJAX and try to load the one row of data I have.
This instantly lead to the DB throwing the error:
<code>An exception occurred while executing 'SELECT idcourse_master FROM course_master WHERE stat='1' ORDER BY idcourse_master DESC LIMIT 0,100':

SQLSTATE[42000]: Syntax error or access violation: 1226 User 'ba53d3edafdd3c' has exceeded the 'max_questions' resource (current value: 18000)
</code>
It says 18000 now after I upgraded by ClearDB account thinking I probably didn't have enough usage limits to make the app work. But, now that I'm monitoring it and logging to see how many requests are made and queries are executed, I can see that it's literally stopping at the first one.
I googled around and read the solution to the opposite of this problem; people were exceeding the limit. I haven't even run a query yet.
I also assumed I had some code error and decided to connect remotely to the DB from MySQL Workbench. I ran one select statement on the table that has the one row of data and I received the same error.
I'm at my wit's end. Any help would be appreciated! Thanks in advance!
Answer: Found the issue. I had a looping issue in one of my queries that was forcing Silex to continuously execute the same query on an empty table. It took me a long time to trace and figure this out.


Indexing aggregate function in SQL

Question: I have the following SQL query which I want to optimize using indexing.
select    ean,   count(nif)
from    produto   P,   fornece_sec   F where    P.ean   =   F.ean
group   by    P.ean
having    count(nif)   >   1

Makes sense to use an index for nif?
Comment: Please tag your DBMS
Comment: Add some sample table data and the expected result (as formatted text, not images.)
Comment: Please learn how to use modern explicit `JOIN` syntax rather than the ancient and outdated implicit joins in the `WHERE` clause
Comment: I got this question as part of an assignment. The teacher made that query,it is so badly written that I can't even run it on my database, and asked to write indexes. And my doubt is should I index nif, and if yes, what type of index? Hash or b-tree? Clustered or Unclustered? Note that only one of nine possible values satisfies the query.
Answer: First, learn how to write queries correctly using explicit join syntax:
select P.ean, count(nif)
from produto P join
     fornece_sec F
     on P.ean = F.ean
group by P.ean
having count(nif) > 1;

Then -- assuming that all eans in fornece_sec are also in produto -- you don't need the join, because you are aggregating by the join key.  So, you can simplify this to:
select F.ean, count(F.nif)
from fornece_sec F
group by F.ean
having count(F.nif) > 1;

For this version of the query, you can use a covering index:  fornece_sec(ean, nif).

Indexing aggregate function in SQL


Slightly more general method to check whether or not $ax^2+bx+c$ will ever generate a perfect square integer?

Question: I have already looked at this post and this post but can't seem to apply completing the square to some cases because the numbers become non-integers.
Given a quadratic equation of the form $$f(x)=ax^2+bx+c$$
$$a,b,c \in \mathbb{Z}$$
$$ a, b, c \neq 0,$$
How can I determine whether or not $f(x)$ will ever yield a value that is a perfect square integer?
The second post I linked has a method of completing the square for equations of the form $4x^2+4kx-p$ which is slightly too specific for my case, but has led me on the right track.
Based on this comment by Andre Nicholas, it appears to be difficult to tackle this problem in the general case for arbitrary $a, b, c$, so I will place some constraints:
In addition to $a, b, c \neq 0$, assume the following:

$a$ is always a product of two perfect square integers and is therefore always a perfect square itself (i.e., $a = m^2n^2 = (mn)^2$)
$a,$ $b,$ and $c$ need not divide one another, but $gcd(a,b,c)$ is always a perfect square $\gt 1$
$c$ is never a perfect square so the trivial case $f(0)$ will never be a perfect square

Take, for example,
$$f(x)=810000x^2-45642249684x+642606171242553$$
$$g(x)=810000x^2-45641877084x+642981810606444$$
$$h(x)=810000x^2-45642751884x+642957163366248$$
The question is, which of these functions will yield a perfect square for at least one $x$, and which will not?
By brute force computation, I have found that $f(29136) = 387846209529$ and $\sqrt{387846209529}=622773$ (perfect square). I failed to find values of $x$ for which $g(x)$ and $h(x)$ yield positive squares, but that does not necessarily mean that there do not exist any, since I only iterated from $x=1$ to $x=10000000$.
I am not sure how (or if it's even possible) to mathematically prove that these functions cannot possibly yield perfect square solutions. Brute force iteration might be able to prove that a perfect-square solution exists, but it cannot disprove the existence of a solution because you cannot iterate to infinity.
I have tried to complete the square as suggested in the linked posts, but am not sure how to evaluate the rewritten quadratic with non-integers.
$$f(x) = 810000x^2-45642249684x+642606171242553$$
$$=$$
$$810000(x-\frac{140871141}{5000})^2-(\frac{1267840269}{50})^2+642606171242553$$
How do I proceed from here to determine whether or not $f(x)$ has any $x$ yielding a perfect square, similar to the $(2n+a+m)(2n+a−m)=b$ method in one of the comments on the 2nd post? The comment author mentions that once in that form, $b$'s prime factorization will yield all perfect-square solutions. However, I am not sure how to extract such a $b$ from the complete-the-square above.
Note: I am not extremely well-versed in math, so I do not fully understand some of the topics mentioned in those other posts like Pell's equations, Cayley-Hamilton theorem, etc.
Comment: Solving $x^2-dy^2=n$: if $d$ is a square, this reduces to factoring $n$, which is simple conceptually but can be difficult as a practical matter if $n$ is large. If $d$ is not a square, and $n$ is "small" (I think that means if $n<2\sqrt d$, but I may be misremembering), then solutions come from the continued fraction expression for $\sqrt d$ – again, conceptually simple, but can be computationally challenging for large $d$. If $n$ is not small, things get more difficult. The standard reference is Chrystal's Algebra.
Comment: I had asked a similar question before. https://math.stackexchange.com/questions/3831521/method-for-solving-diophantine-equation-ax2-bx-c-y2

Essentially, the method is to solve the Diophantine Equation $y^2 = ax^2 + bx + c$ by transforming it to a Pell Equation and using one of the methods for solving Pell Equations.
Comment: @JohnOmielan : yes, indeed.
Comment: @vvg Thanks for linking your question. I am wondering, do you think the constraints I placed on $a,b,c$ make the equation in my case any easier to solve than the general case for arbitrary $a,b,c$? The 2nd post provides a quick method for $4x^2+4kx-p$ and mine is something like $4jx^2+4kx-p$. Also, looking at your question it seems you are actually attempting to solve the equation. I am content with a method that only says "yes" or "no" to a quadratic yielding perfect squares; I am not bent on actually solving for the particular $x$ that generates a perfect square.
Comment: Multiply by $4a$ and you get $(2ax+b)^2+4c-b^2=4ay^2$$ or $$u^2-4ay^2=4c-b^2,$ where $u\equiv b\pmod{2a}.$ Obviously, if $b$ is even, we can cancel a factor of $4.$
Comment: @vvy Note we can use the result in your [question](https://math.stackexchange.com/q/3831521), i.e., $X^2-dY^2=n$ where $n=b^2-4ac$ and $d=a$. This is because, with $a=(mn)^2$ being a perfect square, the left side is a difference of squares which can be factored to get $(X-mnY)(X+mnY)=b^2-4ac$. Also, FYI, I believe you technically *only* get a [Pell's equation](https://en.wikipedia.org/wiki/Pell%27s_equation) if $d$ is *not* a perfect square (although the article only explicit states this for where your $n$ is $1$, I believe that restriction also applies to the general case).
Comment: @ThomasAndrews I cannot seem to get that expression to work with the $f(x), g(x), h(x)$ from my post. Can you briefly explain how you derived that?
Comment: @JohnOmielan That is actually good, since I have a poor grasp of Pell Equations and it appears that $X^2-dY^2=n$ cannot be solved efficiently in poly-time anyway.
Comment: @vvg I saw that you had an answer about modular tests that has since been deleted. The time complexity of this method is of particular interest to me. I am not too familiar with the theory behind this, but are you aware of the exact relation between the magnitudes of $a, b, c$ and potentially how many primes I would have to test before finding some $p$ such that no $x \in \mathbb{F}_p$ yields a quadratic residue $ax^2+bx+c \pmod p$? As far as I can tell, this method might grow exponentially with larger and larger coefficients.
Answer: If you want to check for existence of integer solutions, you can try modular tests. i.e. if $y^2 = ax^2 + bx + c$ has integer solutions then the equation also holds modulo $p \in \mathbb{P}$.
i.e.,
$$
\forall p \in \mathbb{P}, y^2 \equiv ax^2 + bx + c \pmod{p}
$$
If we first transform the equation into Pell form using the transformation in this question, i.e.,
$$
X = 2ax + b, \\
Y = 2y
$$
to get
$$y^2 = ax^2 + bx + c \rightarrow X^2 - dY^2 = n$$
where $$n = b^2 - 4ac \text{ and } d = a$$
then, we can check if $X^2 \equiv n \pmod{d}$. When $d$ is small or easily factored, this is viable. We could also check $X^2 - dY^2 \equiv 0 \pmod{n}$ if $n$ is small or easily factored or if $d$ is a perfect square.
This is called the Hasse Principle

the Hasse principle, is the idea that one can find an integer solution to an equation by using the Chinese remainder theorem to piece together solutions modulo powers of each different prime number.

Example:
Consider the second equation listed in the question:
$$y^2=810000x^2-45641877084x+642981810606444$$
WolframAlpha gives the answer that this equation has no integer solutions. Let us see what our approach gives us.
We have $a = 810000, b = -45641877084, c = 642981810606444$. We apply the transformation
$$
X = 2ax + b = 2*810000x + b = 1620000x -45641877084, \\
Y = 2y
$$
to get
$$
X^2 - dY^2 = n
$$
where
$$
\begin{align}
d & = a = 810000 = 900^2, \\
n & = b^2 - 4ac \\
& = (-45641877084)^2 - 4 \times 810000 \times 642981810606444 \\
& = -80122613914216944
\end{align}
$$
So, we need to solve
$$
\begin{align}
X^2 - 900^2Y^2 & = X^2 - (900Y)^2 \\ & = -80122613914216944
\end{align} \tag{1}
$$
Unfortunately, we cannot use the modulo $d$ trick because $d$ itself is a perfect square. So, $\forall p \in \mathbb{P}$, we will have solutions to $(X-900Y)(X+900Y) = uv \equiv -80122613914216944 \pmod{p}$. So, we cannot use that.
Instead, we use the fact that $(X-900Y)(X+900Y) = uv = -80122613914216944$ and we factor the RHS. Then we can solve for $X,Y$ using the divisors of $-80122613914216944$ (there are 720 divisors in this case).
The only integer solutions to $X,Y$ in Eqn. (1) are:
$$
\begin{matrix}
X = 1620000x -45641877084 & Y=2y & x & y \\
-13738445457084 & ±15264939400 & -8508695.885 & ±7632469700 \\
-45642237084 & ±50714572 & -56348.21862 & ±25357286 \\
-3718037916 & ±4143108 & -30469.08333 & ±2071554 \\
-1606902084 & ±1812936 & -29165.91307 & ±906468 \\
1606902084 & ±1812936 & -27182.08333 & ±906468 \\
3718037916 & ±4143108 & -25878.91307 & ±2071554 \\
45642237084 & ±50714572 & 0.222222222 & ±25357286 \\
13738445457084 & ±15264939400 & 8452347.889 & ±7632469700 \\
\end{matrix}
$$
So, even though $X,Y$ are integers, the original variables $x, y$ do not have any integer solutions.
The only caveat with this method is we need to factor $n$ and if $n$ is large, this is going to be very slow. (I used WolframAlpha to get the integer solutions to Eqn. 1.)
Prologue:
Just to illustrate how we can use the modulo trick for Pell equations where $d$ is not a perfect square, consider the example Pell equation $$X^2 - 5Y^2 = 23.$$
Taking modulo $5$ we get $X^2 \equiv 3 \pmod{5}$.
But the only squares modulo $5$ are $$0^2 \equiv 0, 1^2 \equiv 1, 2^2 \equiv 4, 3^2 \equiv 9 \equiv 4, 4^2 \equiv 16 \equiv 1 \pmod{5}$$
i.e.,
$$X^2 \in \{0, 1, 4\} \pmod{5}.$$
Therefore, there are no modular solutions for $X^2 \equiv 3 \pmod{5}$ and that implies there are no integer solutions for $X$ by the Hasse principle.
Comment: @J W: I had given an answer (https://math.stackexchange.com/q/4592541) to a somewhat related question. In cases where your polynomial is monic i.e., $a=1$, you can use that result from Masser. (Reference in cited answer). For general quadratic polynomials, you need to solve a variant of Pell equations.
Comment: Thank you! I have implemented this method and it works well enough for my purposes. However, it is quite slow sometimes. Are you aware of a way to quickly check whether or not $ax^2+bx+c$ will be a perfect square given a particular value of $x$ without actually plugging in $x$ and testing the square root? Square root and square root w/remainder become very expensive operations as the numbers get larger. I am hoping to be able to speed up this process by efficiently being able to check if $f(x)$ will be a perfect square for given $x$ without naively plugging and checking.


using default depth buffer in off-screen framebuffer

Question: I'm trying to implement Weighted, Blended Order-Independent Transparency
There are three passes:

3D opaque surfaces to a primary framebuffer
3D transparency accumulation to an off-screen framebuffer
2D compositing transparency over the primary framebuffer

I need to test transparent objects against default depth buffer. I created a framebuff for transparency pass and also created a depth buffer for maybe I can copy default depth to this buffer if this is the only way. But I don't know how to do that because I created depth buffer with GL_DEPTH_COMPONENT24 but I don't know default depth format.
Is it possible to bind default framebuffer's depth buffer to another framebuffer? If not, how can I copy default depth to another depth buff, or what is best way to do this?
Answer:
Is it possible to bind default framebuffer's depth buffer to another framebuffer?

First, you "attach" images to framebuffers. You "bind" objects to the context; you "attach" objects to other objects.
Second, no, you cannot attach images of the default framebuffer to anything.

If not, how can I copy default depth to another depth buff, or what is best way to do this?

You render to your own depth buffer entirely. Just copy/render the image data out to the default framebuffer when its time to display it.
Comment: @recp: Yes, you could. Or you could just render to your own image and *not* have to do a copy. Why pick the slower option?
Comment: what about `glBlitFramebuffer`? Can't I copy default framebuffer's images or depth to another framebuffer with it?
Comment: "Why pick the slower option?" maybe this is what I was looking for. I don't know which one is faster so I tried to save texture space. As a solution I will render opaque objects to another framebuff and share its depth buffer with transparency framebuff, this seems better way and fits with your answer I guess


F#+.Net, calculation error using the System.Math.Floor function

Question: here's a function I wrote to print every digit of a float number in F#:
let rec TestFloor (fnum:float) =
    let floor = System.Math.Floor(fnum)
    printfn "fnum:%f floor:%f" fnum floor
    if floor > 0.0 then TestFloor((fnum - floor) * 10.0)

Anyway the result is strange, for example:
> TestFloor 1.23;;
fnum:1.230000 floor:1.000000
fnum:2.300000 floor:2.000000
**fnum:3.000000 floor:2.000000**
fnum:10.000000 floor:9.000000
fnum:10.000000 floor:9.000000
fnum:10.000000 floor:9.000000
fnum:10.000000 floor:9.000000
fnum:10.000000 floor:9.000000
fnum:10.000000 floor:9.000000
fnum:10.000000 floor:9.000000
fnum:10.000000 floor:9.000000
fnum:9.999998 floor:9.000000
fnum:9.999982 floor:9.000000
fnum:9.999822 floor:9.000000
...

At the fourth line the floor of 3.0 turned out to be 2.0 which is strange. The following computations are all going wrong. I'm wondering what's happening there?
Thanks!

Edit 2
@ sepp2k
This is the result after using %.30f:
> TestFloor 1.23;;
fnum:1.230000000000000000000000000000 floor:1.000000000000000000000000000000
fnum:2.300000000000000000000000000000 floor:2.000000000000000000000000000000
**fnum:3.000000000000000000000000000000 floor:2.000000000000000000000000000000**
fnum:9.999999999999980000000000000000 floor:9.000000000000000000000000000000
fnum:9.999999999999820000000000000000 floor:9.000000000000000000000000000000
fnum:9.999999999998220000000000000000 floor:9.000000000000000000000000000000
fnum:9.999999999982240000000000000000 floor:9.000000000000000000000000000000
fnum:9.999999999822360000000000000000 floor:9.000000000000000000000000000000

As you can see at the fourth line fnum is 3.00... and the floor value is 2.00..

Edit 3 - Solved
Thank you all, now I understand what the problem is about.
Answer: This is just one of those rounding issues you get with floating point arithmetic. You will find its representation is 2.99999... probably infinitely recurring. The call to printfn clearly rounds this up to the expected representation, but floor still sees this as 2.99999...
This is exactly the sort of problem that the decimal type exists to solve, so if we rewrite to use decimal, we obtain the correct result:
let rec TestFloor dnum =
    let fl = floor dnum
    printfn "fnum:%f floor:%f" dnum fl
    if fl > 0.0M then TestFloor((dnum - fl) * 10.0M)

This gives:
> TestFloor 1.23M;;
fnum:1.230000 floor:1.000000
fnum:2.300000 floor:2.000000
fnum:3.000000 floor:3.000000
fnum:0.000000 floor:0.000000
val it : unit = ()

Of course, you can stick with float, but add a very small tolerance value to ensure that these corner cases are always just a little above the expected value, rather than just a little below, eg:
let rec TestFloor fnum =
    let fl = floor (fnum + 0.00000000001)
    printfn "fnum:%f floor:%f" fnum fl
    if fl > 0.0 then TestFloor((fnum - fl) * 10.0)

Which gives the same result as above.
Comment: Thanks Chris, now I understand how and why!
Answer: Presumably the value of fnum is something like 2.9999999999999999999 and printfn just rounds that to 3.0 when displaying it. Try to increase the number of displayed digits with something like %.30f instead of %f.
Comment: OK, here's the result using %.30f:

>TestFloor 1.23;;

fnum:1.230000000000000000000000000000 floor:1.000000000000000000000000000000
fnum:2.300000000000000000000000000000 floor:2.000000000000000000000000000000
fnum:3.000000000000000000000000000000 floor:2.000000000000000000000000000000
...
as you can see, when fnum = 3.00..., the floor is 2.00...
Comment: @Eric.By: Then try even more digits.
Answer: Even though you get 3.00000... at max decimal precision, there might still be a rounding. Let's not forget the value is stored in binary, and a rounding is always needed for printing purposes (binary to decimal).
The answer is, although your value prints as 3.0000..., it is actually less than 3. Adding more decimal digits won't cut it.
Consider this code:
> let num = 3.0 - 2.**(-51.);;
> printfn "%.30f" num;;
3.000000000000000000000000000000
> floor num;;
val it : float = 2.0


Multiple downloading display in notification bar and also in activity

Question: Right now in my application downloading code is working but when i download multiple files it download randomly not in queue, i need it download in queue and this current download is not displaying in notification bar only display in activity.
    I want to know how to possible multiple downloading with displaying in notification bar and also display progress bar in current activity.
    Thank you
Answer: Looper
By using looper you download multiple file in queue one by one.
Steps 1: Lets create DownloadThreadListener.java interface which will be used to get thread updates.
package com.example.looper;
public interface DownloadThreadListener {
   void handleDownloadThreadUpdate();
}

Steps 2: Lets now create a class named DownloadTask.java which will simulate the downloading. We will be using random time sleep to simulate the download time.
package com.example.looper;
import java.util.Random;
import android.util.Log;
/**
 * This is not a real download task. It just sleeps for some random time when
 * it's launched. The idea is not to require a connection and not to eat it.
 *
 */
public class DownloadTask implements Runnable {
   private static final String TAG = DownloadTask.class.getSimpleName();
   private static final Random random = new Random();
   private int lengthSec;
   public DownloadTask() {
      lengthSec = random.nextInt(3) + 1;
   }

   @Override
   public void run() {
      try {
         Thread.sleep(lengthSec * 1000);
         // it's a good idea to always catch Throwable
         // in isolated "codelets" like Runnable or Thread
         // otherwise the exception might be sunk by some
         // agent that actually runs your Runnable - you
         // never know what it might be.
      } catch (Throwable t) {
         Log.e(TAG, "Error in DownloadTask", t);
      }
   }
}

Steps 3: Now lets create the thread subclass which will act as pipeline. First we will call Looper.prepare() to make this Thread act as pipeline. Next new Handler() will be called to handle message queue on this thread. Finally Looper.loop() will be called to start running the message loop. New tasks will be added using enqueueDownload(final DownloadTask task).
package com.example.looper;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public final class DownloadThread extends Thread {

   private static final String TAG = DownloadThread.class.getSimpleName();
   private Handler handler;
   private int totalQueued;
   private int totalCompleted;
   private DownloadThreadListener listener;
   public DownloadThread(DownloadThreadListener listener) {
      this.listener = listener;
   }

   @Override
   public void run() {
      try {
         // preparing a looper on current thread
         // the current thread is being detected implicitly
         Looper.prepare();

         Log.i(TAG, "DownloadThread entering the loop");

         // now, the handler will automatically bind to the
         // Looper that is attached to the current thread
         // You don't need to specify the Looper explicitly
         handler = new Handler();

         // After the following line the thread will start
         // running the message loop and will not normally
         // exit the loop unless a problem happens or you
         // quit() the looper (see below)
         Looper.loop();

         Log.i(TAG, "DownloadThread exiting gracefully");
      } catch (Throwable t) {
         Log.e(TAG, "DownloadThread halted due to an error", t);
      }
   }

   // This method is allowed to be called from any thread
   public synchronized void requestStop() {
      // using the handler, post a Runnable that will quit()
      // the Looper attached to our DownloadThread
      // obviously, all previously queued tasks will be executed
      // before the loop gets the quit Runnable
      handler.post(new Runnable() {
         @Override
         public void run() {
            // This is guaranteed to run on the DownloadThread
            // so we can use myLooper() to get its looper
            Log.i(TAG, "DownloadThread loop quitting by request");

            Looper.myLooper().quit();
         }
      });
   }

   public synchronized void enqueueDownload(final DownloadTask task) {
      // Wrap DownloadTask into another Runnable to track the statistics
      handler.post(new Runnable() {
         @Override
         public void run() {
            try {
               task.run();
            } finally {
               // register task completion
               synchronized (DownloadThread.this) {
                  totalCompleted++;
               }
               // tell the listener something has happened
               signalUpdate();
            }
         }
      });

      totalQueued++;
      // tell the listeners the queue is now longer
      signalUpdate();
   }

   public synchronized int getTotalQueued() {
      return totalQueued;
   }

   public synchronized int getTotalCompleted() {
      return totalCompleted;
   }

   // Please note! This method will normally be called from the download
   // thread.
   // Thus, it is up for the listener to deal with that (in case it is a UI
   // component,
   // it has to execute the signal handling code in the UI thread using Handler
   // - see
   // DownloadQueueActivity for example).
   private void signalUpdate() {
      if (listener != null) {
         listener.handleDownloadThreadUpdate();
      }
   }
}

Steps 4: Now add full functionality to MainActivity.java . Here also we will create handler so that we can post events on main thread.
package com.example.looper;

import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity implements DownloadThreadListener,
      OnClickListener {

   private DownloadThread downloadThread;

   private Handler handler;

   private ProgressBar progressBar;

   private TextView statusText;

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

      // Create and launch the download thread
      downloadThread = new DownloadThread(this);
      downloadThread.start();

      // Create the Handler. It will implicitly bind to the Looper
      // that is internally created for this thread (since it is the UI
      // thread)
      handler = new Handler();

      progressBar = (ProgressBar) findViewById(R.id.progress_bar);
      statusText = (TextView) findViewById(R.id.status_text);

      Button scheduleButton = (Button) findViewById(R.id.schedule_button);
      scheduleButton.setOnClickListener(this);
   }

   @Override
   protected void onDestroy() {
      super.onDestroy();

      // request the thread to stop
      downloadThread.requestStop();
   }

   // note! this might be called from another thread
   @Override
   public void handleDownloadThreadUpdate() {
      // we want to modify the progress bar so we need to do it from the UI
      // thread
      // how can we make sure the code runs in the UI thread? use the handler!
      handler.post(new Runnable() {
         @Override
         public void run() {
            int total = downloadThread.getTotalQueued();
            int completed = downloadThread.getTotalCompleted();

            progressBar.setMax(total);

            progressBar.setProgress(0); // need to do it due to a
                                 // ProgressBar bug
            progressBar.setProgress(completed);

            statusText.setText(String.format("Downloaded %d/%d", completed,
                  total));

            // vibrate for fun
            if (completed == total) {
               ((Vibrator) getSystemService(VIBRATOR_SERVICE))
                     .vibrate(100);
            }
         }
      });
   }

   @Override
   public void onClick(View source) {
      if (source.getId() == R.id.schedule_button) {
         int totalTasks = new Random().nextInt(3) + 1;

         for (int i = 0; i < totalTasks; ++i) {
            downloadThread.enqueueDownload(new DownloadTask());
         }
      }
   }
}

Steps 5: Add Vibrate permission
<uses-permission android:name="android.permission.VIBRATE" />

Original Post Complete tutorial here.


How to fix attic door which doesn't shut completely

Question: Check pictures here
My attic door(with ladder) won't shut completely.check link.
I found a couple of discussion forums where the suggestion was to adjust springs. But I don't know
exactly how to do that. Can someone explain with pictures?
Comment: Pics of your door as closed as it will get. Then open it and give us an overview pic, then detail pics of the springs & spring mount points. Maybe find the brand name of the door (then search the mfgr to see if they can tell you how to adjust it). Pics straight up each side to see if there's something bent somewhere. The more detail you give, the more likely you are to get a good, detailed answer. The less detail you give, the more likely you are to get wild guesses.
Comment: Your picture shows an attic door in the ceiling that is not completely closed. On the other side of the door are springs that act as a counterbalance and keep it closed, those are what need adjusting, it probably has a set on the left an another on the right. I am assuming none of the support structure has been bent or moved. Since all attic doors are not all the same why burn our time taking a guess just post pictures of what you have, it helps us help you.
Comment: Maybe the hinges have developed a problem.  Maybe the ladder isn't folding or closing all the way and is getting in the way.   Maybe there is some object keeping it from closing.  Maybe there is a clip or latch to hold it closed that isn't working.   Maybe it is held closed by the force of springs that need adjusting.   You need to do some initial diagnosis.
Comment: Check all the screws/bolts to ensure they are tight.
Comment: @Gil - I shared link to my pictures.
Comment: @FreeMan - I shared link for pictures.
Comment: @jsotola - I provided link to the pictures. Because of size limitations I shared link to my Google drive.
Comment: @jsotola - sorry for that. I didn't realize that upload was still in progress. You can check it now.
Comment: @user2716454 maybe the pivot points are attached too far to back
Answer: Be careful with those springs! I got stitches in my head watching my brother monkey with an attic door just like that one. The bar went flying upward and cracked me right in the side of my head. The springs are deigned and attached by the door manufacturer and should be perfectly fine and able to hold the door shut.
The door is rubbing against something. Go into the attic with a good flashlight and examine everything over and over until you find what is hitting where. It could be a combination of things.
It could be the door itself is rubbing the opening. It could be the arms or the springs touching the door. It doesn't take much to keep a cheap attic door from staying all the way shut, but once you get everything straight, the arms not bent, the opening aligned properly with the door, then it should stay shut.
This is a door like any other door. Time and moisture warps and moves things. But unlike a typical wooden door, you cannot shave the door to stop it from rubbing. That's why I mentioned adjusting the hole if needed. The door attaches on the one back. You can insert a shim on one side or the other.
That is another thing: The hinge side of the door could be twisted a little downward. If it is, then the door will not shut all the way. The door cannot go past 90 degrees against the hinge. You can use screws to suck in the top of the framing member that the door is attached to.
Answer: Inspect and adjust, but leave the springs attached to the door.
Comment: Good advice above. Don't forget to check for a latching mechanism that might be misaligned.
Answer: Mine are similar but not as much opening, springs are OK. Looks like stair rails warped slightly pushing the end open. I added weather stripping foam the fill the gap. I plan to make a small truss to pull the open end of the door closed.
Comment: What's your actual solution here? Weatherstripping? A truss (whatever that means)? Please clarify.
Comment: It is weather stripping at this time.
Comment: Seems that would make the problem worse by introducing more friction and enforcing a gap.
Answer: I see a lot of good advice. Could also be humidity; in the summer months when it gets hot & humid, my front door sticks from expansion. Just something else to consider. possibly You could help it close by forcing it up if that's the issue.
Comment: So "push on it"?
Comment: Yeah as simple as it sounds. My front door as i've said expands in the summer months and I have to use a little force to open and shut it. Obviously I don't mean that you get up on a ladder and shoulder it up with all your might, just see if it will stay up with a little force.
Answer: One hack is just to find an old unused key with a hole in it and screw it to the outside door frame 6 inches from the pull string on side of door that won't close(see photo).  Screw it down tightly enough to hold the door closed but loosely enough to turn. Turn key towards door to hold door up. Turn key away from door to allow door to drop.
Door is high and somewhat heavy so a ladder may be required to lift door high enough to turn key. Alternately instead of ladder a rod of some kind(sawed off broom stick handle for example) may be used to push up against the door to fully close it with one hand so you can turn the key with the other hand and get the door to stay closed. This may be more convenient since rod may be left near door and doesn't need to be opened and closed like ladder does.  You can paint the key white to make it less obvious if desired(see photo).  You won't be able to get approval from home inspector but door will stay closed.
Comment: It sounds to me like your suggestion is A) push the door harder to close it, then B) use a door knob to latch it, though you're suggesting using a key(?) instead of a standard door knob... An [edit] to include a sketch and/ or rewording your answer to make it more clear would really help a lot.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Added picture above and revised procedure description.  Thanks for suggestions.


Can a mini-widespread 3-hole sink faucet with 4-inch spread be replaced by centerset or widespread?

Question: We have bathroom sink faucets where the centers of the hot and cold handles are 4 inches apart, which means it is a mini widespread faucet. They need to be replaced. There are fewer good choices for affordable mini widespread faucets, so can they be replaced alternatively by a regular widespread or a centerset faucet instead? Centersets are made with both handles and the spout all mounted on the same flat bottom metal piece, and the sink the holes are cut into is slightly curved (see photo), however we do have another similar sink which does have a centerset faucet working fine.
Alternatively we may be interested in a widespread fixture. They typically say to use them for a range of 6 to 12 inches (sometimes explicitly saying not to use it for a 4-inch spread). But would it still work? The sink is over a cabinet, and the hoses are typically flexible, so I don't know what the reason would be that it couldn't work, but I'd like to check before ending up with an unusable faucet.
I found that according to a post on Faucet Shower Guide:

[Y]ou can replace a centerset faucet with widespread faucet. If you have proper space in the bathroom sink then do three holes for the widespread faucet and now you can easily replace the faucet. At the time of replacement measure faucet size, it is 4-inch or 8-inch. Replace it with the same so you don't need to do any extra work for installation.

However I was confused by that and am not sure what it's saying.
Comment: I googled bathroom faucets and got 4" spreads.
Comment: Maybe it would help if you'd link to one of the faucets you've found that claims a 6" minimum spread. In my experience you can put most on a 4" spread.
Comment: @isherwood In our house with the bathroom sinks, some of them have an 8 inch spread and some have a 4-inch spread. The faucets for three distinct holes listed online, as per their description, seem to exclude use on the 4-inch spread. We actually do have a third bathroom where it appears to be a 4-inch spread of 2 handles and the spout all mounted on a single metal structure and it is on a similar looking sink, so perhaps we should get a replacement like that rather than looking for one that more matches the current old faucets we need to replace?
Comment: @isherwood I'm having a hard time pasting into the comments but you can look on Amazon for "8 inch 3 hole widespread bathroom faucet with metal pop up drain by Phiestina" - that was the one I was looking at, but the other 3 hole faucets that weren't mounted together said the same thing.
Comment: @isherwood Trying to find other faucets, the TimeArrow TAF830Y-CP actually even explicitly says not to use it for 4-inch spreads.
Comment: @JimStewart ok I found https://faucetshowerguide.com/widespread-vs-centerset-faucets/ which explains the difference in the two types of faucets. Generally 4 inch ones are mounted together though it seems. The old faucets seem to be "mini widespread".
Comment: Revised my question based on what I read.
Comment: It sounds like you are getting bathroom faucets confused with kitchen faucets. Your cast iron sink with a porcelain glaze may be drilled out at the risk of cracking the porcelain.
Comment: @EdBeal Can you elaborate? Widespread, mini-widespread, and centerset faucets are all types that can be used in bathrooms.
Comment: Not seen a mini on a kitchen and I have remodeled quite a few homes.
Comment: @EdBeal I'm not asking for a kitchen, I'm asking for a bathroom.
Comment: Sure get a big one and a tile hole saw and a metal cutting saw and give it a go. After cracking the porcelain you can get a sink that matches the fixture you want. If the mfg states it won't fit they are warning you. Note the tile saw will cut the porcelain and a metal one will cut the cast but there is a large risk for even a pro.
Answer: The problem with a traditional widespread faucet would normally be the sheer physical size. You will probably find that the girth of the spout where it meets the deck will interfere with the handle escutcheons/trim. However, if you find one that fits there should not be a problem.
Centerset lavs are typically fine to use where a mini-widespread was installed. In fact, the mini-widespreads are a (relatively) new type of product to give consumers a more decorative option for sinks originally designed for the formerly "standard" 4" centerset lav.


Strange new rules added to my iptables config... Was my server hacked?

Question: Today, I listed my iptables for a routine check -- and discovered two strange UFW rules that I don't remember setting up myself, referring to two specific IP addresses that I can't identify:
-A ufw-before-input -d 184.108.40.206/32 -p udp -m udp --dport 5353 -j ACCEPT
-A ufw-before-input -d 18.104.22.168/32 -p udp -m udp --dport 1900 -j ACCEPT

This is kind of scary. Did someone manage to hack into my server and add these rules? If not, what happened?
(And if some malicious agent did hack into my firewall, why would they use ports 5353 and 1900, that aren't being forwarded by my router??)
Answer: Quoting man ufw:
NOTES
       On installation, ufw is disabled with  a  default  incoming  policy  of
       deny,  a  default forward policy of deny, and a default outgoing policy
       of allow, with stateful tracking for NEW connections for  incoming  and
       forwarded  connections.  In addition to the above, a default ruleset is
       put in place that does the following:

       [ ... ]

       - ACCEPT mDNS (zeroconf/bonjour/avahi 184.108.40.206 for IPv4 and ff02::fb
       for IPv6) for service discovery (INPUT)

       - ACCEPT UPnP (22.214.171.124 for IPv4 and ff02::f for IPv6) for ser‐
       vice discovery (INPUT)

So these two rules you are seeing are part of ufw's default settings and allow mDNS and UPnP services to work.
Comment: Aha! Right, I should have checked the manpage. Thanks for the clarification!
Answer: Googling says that those IP addresses are related to Simple Service Discovery Protocol (SSDP)/uPnP and iTunes.  So it is likely that these rules are related to software you installed and relate to sharing information on a LAN. whois doesn't return any information for either IP.
See
https://stackoverflow.com/questions/12483717/what-is-the-multicast-doing-on-224-0-0-251
and
https://wiki.wireshark.org/SSDP


Alsamixer missing controls after upgrade from 10.04 to 12.04

Question: We previously loaded Ubuntu 10.04 on our Q7 intel platform + custom hardware that uses the Intel HDA sound card.  Sound worked well.
We changed to 12.04 yesterday and have output (speaker) sound, but no "line" input sound.  Interestingly, alsamixer is now missing the control labeled "digital" under 10.04.  There is a new SPDIF control present in 12.04 but it has neither mute nor sliders;  It's just  there.
Another interesting tidbit, if it helps, the sound test built into the sound control will play "Left front", but not "right front", even though the stereo outputs are connected together and tied to one speaker.
I have already done a alsactl init followed by a reboot.
Here is the current output of amixer.
<code>Simple mixer control 'Master',0
  Capabilities: pvolume pswitch penum
  Playback channels: Front Left - Front Right
  Limits: Playback 0 - 31
  Mono:
  Front Left: Playback 31 [100%] [0.00dB] [on]
  Front Right: Playback 31 [100%] [0.00dB] [on]
Simple mixer control 'PCM',0
  Capabilities: pvolume penum
  Playback channels: Front Left - Front Right
  Limits: Playback 0 - 255
  Mono:
  Front Left: Playback 217 [85%] [-7.60dB]
  Front Right: Playback 217 [85%] [-7.60dB]
Simple mixer control 'Line',0
  Capabilities: pvolume pswitch penum
  Playback channels: Front Left - Front Right
  Limits: Playback 0 - 31
  Mono:
  Front Left: Playback 0 [0%] [-34.50dB] [off]
  Front Right: Playback 0 [0%] [-34.50dB] [off]
Simple mixer control 'Mic',0
  Capabilities: pvolume pswitch penum
  Playback channels: Front Left - Front Right
  Limits: Playback 0 - 31
  Mono:
  Front Left: Playback 0 [0%] [-34.50dB] [off]
  Front Right: Playback 0 [0%] [-34.50dB] [off]
Simple mixer control 'Mic Boost',0
  Capabilities: volume penum
  Playback channels: Front Left - Front Right
  Capture channels: Front Left - Front Right
  Limits: 0 - 3
  Front Left: 0 [0%] [0.00dB]
  Front Right: 0 [0%] [0.00dB]
Simple mixer control 'IEC958',0
  Capabilities: cswitch cswitch-joined penum
  Capture channels: Mono
  Mono: Capture [on]
Simple mixer control 'Beep',0
  Capabilities: pvolume pswitch penum
  Playback channels: Front Left - Front Right
  Limits: Playback 0 - 31
  Mono:
  Front Left: Playback 0 [0%] [-34.50dB] [off]
  Front Right: Playback 0 [0%] [-34.50dB] [off]
Simple mixer control 'Capture',0
  Capabilities: cvolume cswitch penum
  Capture channels: Front Left - Front Right
  Limits: Capture 0 - 31
  Front Left: Capture 16 [52%] [12.00dB] [on]
  Front Right: Capture 16 [52%] [12.00dB] [on]
Simple mixer control 'Capture',1
  Capabilities: cvolume cswitch penum
  Capture channels: Front Left - Front Right
  Limits: Capture 0 - 31
  Front Left: Capture 0 [0%] [-12.00dB] [on]
  Front Right: Capture 0 [0%] [-12.00dB] [on]
Simple mixer control 'Capture',2
  Capabilities: cvolume cswitch penum
  Capture channels: Front Left - Front Right
  Limits: Capture 0 - 31
  Front Left: Capture 3 [10%] [-7.50dB] [on]
  Front Right: Capture 3 [10%] [-7.50dB] [on]
Simple mixer control 'Input Source',0
  Capabilities: cenum
  Items: 'Mic' 'Line'
  Item0: 'Line'
Simple mixer control 'Input Source',1
  Capabilities: cenum
  Items: 'Mic' 'Line'
  Item0: 'Mic'
Simple mixer control 'Input Source',2
  Capabilities: cenum
  Items: 'Mic' 'Line'
  Item0: 'Mic'
</code>
Suggestions anyone?
Answer: I know I had a very low right channel after initial install until I adjusted the mixer settings and it seemed to suddenly come to life. have you adjusted ALL of the mixer settings?


Sublime Text 2: can't create symlink to subl, says "bin/subl: No such file or directory"

Question: I've downloaded and installed Sublime text 2. I am following the directions here:  but I am stuck at this part:
The first task is to make a symlink to subl. Assuming you've placed Sublime Text 2 in the Applications folder, and that you have a ~/bin directory in your path, you can run:
ln -s "/Applications/Sublime Text " ~/bin/subl
However, when I do this it tells me /Users/User/bin/subl: No such file or directory.
What should I do?
Thanks!
Comment: Here are another instructions for this matter: http://opensourcehacker.com/2012/05/11/sublime-text-2-tips-for-python-and-web-developers/
Answer: I'd recommend adding it to your local bin:
ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

Edit: Make sure your local bin directory exists before running this command:
mkdir /usr/local/bin

Comment: I've got "ln: /usr/local/bin/subl: No such file or directory"
Comment: @onmyway133 does your bin directory exist?
Comment: This worked for me but had to run as `sudo ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl`
Comment: Thanks, this worked for me. I don't fully understand why yet, but I found [this](https://unix.stackexchange.com/a/4194/302720) useful in explaining some context
Answer: I add my sym links to /usr/local/bin, for Sublime Text 3 I set mine up like so:
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

Then you can open up the current directory list using:
subl .

If you find subl abbreviation annoying as some people I know seem to do, then change it to 'sublime'
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/sublime

And call it using:
sublime .

Comment: `ln: /usr/local/bin/: No such file or directory`
Comment: I followed this entire procedure, but `subl .` results in: `-bash: subl: command not found`
Answer: Alternatively, you can run this:
sudo ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" /bin/subl

Note: The above snippet puts the symlink in /bin/subl rather than ~/bin/subl.
Comment: what's the difference between adding a tilde? (~)
Comment: @ayjay the tilde references your home directory. So /bin/subl starts at the root of your system, while ~/bin/subl starts at your home directory - it's a shortcut for the directory (on a Mac) /Users/
Answer: and that you have a ~/bin directory in your path
First, you need that directory for the ln command to work, and eventually, it will need to be in your path to do whatever it is you are trying to do.
To make the directory:
mkdir ~/bin
Adding it to your execution path is trickier, but there are plenty of resources available.
Comment: This was my issue here.
Answer: Following Simon's example above, For Sublime Text 3, here is what worked for me:
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

Please note, to install (on Mac OS Sierra 10.12.6)  in /usr/local/bin sudo was required.
Comment: This is confirmed working with ST3 and OS X 10.15.3 - with sudo and `/usr/local/bin/subl`
Answer: Info

OS: Mac OSX High Sierra 10.13.6 (17G65)
Sublime Version: Version 3.1.1 Build 3176

I took the command from SublimeText website
Got An Error
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" ~/bin/subl
ln: /Users/jkirchoff/bin/subl: No such file or directory

Did Some Checking
Just to make sure the path exists.

NOTE: the "'s allow the space in the path.

ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"
ln: ./subl: File exists

Compared Note from this page
What @NotSimon wrote on this page, Then Ran:
ln -s "/usr/local/bin/subl"
ln: ./subl: File exists

and then followed the rest.
The Complete Line that worked for me:

    ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

Success
Now I can run subl as a command in Terminal!
This command opens the directory as a "Project" in SublimeText.
subl ~/Desktop

Optional

 I followed the SublimeText recommendation & added this to my
 ~/.bash_profile.

The command works without it, just following guidelines.

echo "export EDITOR='subl -w'" >> ~/.bash_profile
Answer: Just remove tilde ~ from ~/bin/subl
Answer: If you're using mac terminal,
just replace "Sublime Text 2.app"
with "Sublime\ Text\ 2.app/" anywhere within the command.
That should do it.


Put the numbers $1,2,...,\frac{n(n-1)}{2}$ on the edges of $K_n$ satisfying any given path or cycle of length $3$ is $a,b,c$ then $(a,c)|b$?

Question: Is it possible to put the numbers $1,2,...,\frac{n(n-1)}{2}$ on the edges of $K_n$ satisfying any given path or cycle of length $3$ is $a,b,c$ then $(a,c)|b$ ?
We see that if one has $3$ vertices $u,v,w$ such that the edge $uv$ is even and the edge $vw$ is odd, then every edge containing the vertex $w$ is odd. I've been approaching this direction but haven't gotten anywhere yet, looking forward to hearing everyone's suggestions. Thanks very much !!
Comment: Is it only one of the possible assignments of $a, b, c$ that have to satisfy $(a, c)\mid b$, or all six? For instance, is $1, 2, 4$ a legal triangle because $(1, 2)\mid 4$, or illegal because $(2, 4)\nmid 1$?
Comment: @Arthur    $1 2 4$ is invalid because $2$ is not divisible by $(4,1)$ If $1 2 4$ is not a triangle then the path here can be $1 2 4$ or $4 2 1$ . If $1 2 4$ is $3$ sides of a triangle, then there are $6$ paths from $1 2 4$ in all.
Answer: It is impossible for $n \ge 4$.
Pick any integer $k$ such that $2k \le \binom n2 < 3k$. Then no matter which edges get the labels $k$ and $2k$, there will be a path or cycle on which the labels are $(k, x, 2k)$ for some $x$.
However, there is no possible $x$ which is divisible by the GCD of $k$ and $2k$, because $k$ and $2k$ are the only labels divisible by $k$, so this path will not satisfy the condition we want.
Comment: Right. One of the ways to be more careful is to specify that we choose $k = \lfloor \frac{n(n-1)}{4}\rfloor$. Then it will be true for all $n$ that $2k \le \binom n2$, but we will only have $\binom n2 < 3k$ for $n\ge 4$ (which takes some checking, but not a lot).
Comment: it is used that $k\ge2$, in fact $\binom n2 < 3k$ and $n\ge4$ implies that $k\ge3$. (OTOH, if $n=3$ then there is no integer $k$ such that $2k \le \binom n2 < 3k$, just clarifying your proof for myself, and for the record.)


Centroid Root Locus

Question: I can't figure out how to find the root locus centroid for the poles of this simple equation in a positive feedback system.
$$
H(s)=\frac{s}{s^2+3s+1}
$$
I have read in many places that the centroid is found by this formula:
$$
c=\frac{sum(P)-sum(Z)}{p-z}
$$
The transfer function poles are:
$$
p1=-1.5+\frac{\sqrt{5}}{2} \\
p2=-1.5-\frac{\sqrt{5}}{2}
$$
So the centroid should be:
$$
c=\frac{-1.5+\frac{\sqrt{5}}{2}-1.5-\frac{\sqrt{5}}{2}-0}{2-1}=-3
$$
However, in this video
https://youtu.be/eyb_RzOnfGY?t=559 , and also Matlab says that the right answer for the centroid is c=-1.
What I am doing wrong in the calculation?
Please!
Comment: I figured out that the break out and break in points can be calculated by N(s)D'(s)-N'(s)D(s)=0, if we assume that H(s)=N(s)/D(s). This equation lead us to s=+1 and -1, which is right. However, the equation for the centroid shouldnt work also?
Comment: A center will appear only with two poles and only one zero.
Answer: Centroid is -3. However, since the relative degree of this system is 1 you don't need to compute the centroid, for we know there is only one branch that goes to infinity, and it goes to whether $+\infty$ or $-\infty$ in the real line. What has made you confused about -1 is that this point is one of the breakpoints but not the centroid.
Answer: Wouldn't the centroid be at -3?  Ill put it in MATLAB and see what I get (dont have enough rep to add comments) EDIT: This seems right to me, I noticed you only have H(s), do you know if there was any G(s)? I tried to click the link to the video and it wouldn't load, best of luck.
$$ c = \frac{-1.5 + \frac{\sqrt5}{2} -1.5 - \frac{\sqrt5}{2} - 0}{1}$$
$$ c = \frac{-3}{1} = -3$$
Comment: I'm sorry, I meant -3, I forgot the "-". I will fix it right now :).
As we are dealing with positive feedback you have to make a root locus of -H(s).
>> rlocus(-H);

Thanks for answering.

Centroid Root Locus


Is it OK to call HTTP endpoints in an Angular service constructor?

Question: In the Angular documentation, there is the following tip about code in a component constructor (second paragraph emphasized by me):

Call it in ngOnInit
While you could call getHeroes() in the constructor, that's not the best practice.
Reserve the constructor for simple initialization such as wiring
  constructor parameters to properties. The constructor shouldn't do
  anything. It certainly shouldn't call a function that makes HTTP
  requests to a remote server as a real data service would.
Instead, call getHeroes() inside the ngOnInit lifecycle hook and let
  Angular call ngOnInit at an appropriate time after constructing a
  HeroesComponent instance.

What about for services? Is it also bad to have an HTTP call (just the launch of an async request where the Observable is stored locally) in the constructor? Services don't have an ngOnInit() event, so what would the best practice for Services be?
Answer: I bet that you can find some examples of where constructor can be used with no harm but as a rule of thumb and best practice use "angular constructor" for it aka ngOnInit lifecycle hook.
Sometimes using constructor can be impossible or requires additional work. For example, you need to fetch data from backend using service because if @Input() data. Inputs are not bound during javascript object construction, but they are available in ngOnInit
Moreover what if you want to unit test your component/service? You create new instance for every test (thus invoking a constructor) and you are making additional calls to mocked http backend, or even worst - to live one.
Comment: I understand that for a **Component** you want to use `ngOnInit` instead of the constructor. Services don't have `@Input` parameters or lifecycle hooks (that I know of). What would the best practice be for **Services**?
Comment: @DanielGray Services are always used by someone. You inject them in a component or in Effects (when you use Redux/NGRX for app-state management)
Comment: @theTypan I consider your usecase simple enough to hand over the Observable to the actual using Component and use async-Pipe in there which then deals all further handling regarding closing etc.
Comment: @Antoniossss You have done a good job of explaining this. However, I think the question would have been more clear if an example was given. In my case, I have cart service. I store my cart items in the DB so I am making an API call to retrieve cart items. So in my service, I have a variable for `items: Array = []`. I would like to make an http call and call `setItems()` methods in the constructor to fetch and set the items. Is this preferred?


Calculate the lim $\lim_{x\to 1} \frac{ \sqrt{x} - 1}{\sqrt[3]{x} - 1}$

Question: $$
\lim_{x\to 1} \frac{ \sqrt{x} - 1}{\sqrt[3]{x} - 1}
$$
I multiply it with:
$$
\frac{ \sqrt{x} + 1}{\sqrt{x} + 1}
$$
And I get :
$$
\lim_{x\to 1} \frac{ \sqrt{x}^2 - 1^2}{(\sqrt[3]{x} - 1) * (\sqrt{x} + 1)}
$$
But the solution is still division by 0 and not possible, so I think I've made a mistake somewhere..
Comment: See also the questions [1624766](http://math.stackexchange.com/questions/1624766/how-do-i-simplify-and-evaluate-this-limit),
[877128](http://math.stackexchange.com/questions/877128/evaluate-lim-x-to-1-frac-sqrt3x-1-sqrtx-1) and [1434528](http://math.stackexchange.com/questions/1434528/evaluating-lim-x-to-1-left-frac-sqrt3x-12-sqrtx-2-right).
Comment: From that step, you can apply L'Hopital's rule.
Comment: @mathlove sorry about that, typo while writing... fixed. :)
Comment: @IanColey What exactly is that rule?
Comment: See: http://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule#General_form
Comment: @IanColey I did apply it and I get a weird result (1/2 * x^(-1/2) -1) / (1/3 * x^(-2/3) - 1)
Comment: You should apply it to your second result, so that your numerator is the derivative of $x-1$ which is just $1$.
Answer: Hint $\ $ Let $\ X = x^{1/6}.\ $ Then it is $\ \dfrac{X^3-1}{X^2-1} = \dfrac{X^2+X+1}{X+1},\ $ no longer indeterminate.
Comment: @user95523 Well in all honesty, neither did I. But I guess that's how math is.
Comment: Looks like a good answer to me, compared to others.. however to solve problems in this way, you need way too much experience and knowledge in math.
Comment: +1 for being nice and elegant. @user95523 This is more of a simple substitution, you don't need too much experience to use it.
Comment: @Link you're correct, I don't need much experience to use it, but I wouldn't have thought of it myself.. usage is very easy to understand :)
Answer: You basically want to insert $1$ written as a "conjugate" that removes the radical divided by itself. For $\sqrt{x}-1$ it is $\sqrt{x}+1$, for $\sqrt[3]{x}-1$ it is $\sqrt[3]{x^2}+\sqrt[3]{x}+1$. So you get
\begin{align}
\lim_{x\to1}\frac{\sqrt{x}-1}{\sqrt[3]{x}-1}&=
\lim_{x\to1}\left((\sqrt{x}-1)\frac{\sqrt{x}+1}{\sqrt{x}+1}\right)
  \left(\frac{1}{\sqrt[3]{x}-1}
    \frac{\sqrt[3]{x^2}+\sqrt[3]{x}+1}{\sqrt[3]{x^2}+\sqrt[3]{x}+1}\right)
\\[2ex]
&=\frac{x-1}{\sqrt{x}+1}\frac{\sqrt[3]{x^2}+\sqrt[3]{x}+1}{x-1}
\end{align}
and the indetermination goes away.
It's the same as Bill Dubuque's answer, actually, but without substitution.
Answer: Here is a version computationally close to L'Hospital's Rule, though it does not mention him. Note that
$$\frac{\sqrt{x}-1}{\sqrt[3]{x}-1}= \frac{\frac{\sqrt{x}-1}{x-1} }{\frac{\sqrt[3]{x}-1}{x-1}   }.\tag{1}$$
If we look at the expression on the right of (1), we see that the limit as $x\to 1$ of the top is by definition the derivative of $\sqrt{x}$ at $x=1$. Similarly, the limit of the bottom is the derivative of $\sqrt[3]{x}$ at $x=1$. Compute these derivatives, using the ordinary "Power Rule."
Answer: Hint: $$\frac{ \sqrt{x} - 1}{\sqrt[3]{x} - 1} =\frac{3}{2} \cdot \frac{ e^\frac{\ln x}{2} - 1}{\frac{\ln x}{2}} \cdot \left( \frac{ e^\frac{\ln x}{3} - 1}{\frac{\ln x}{3}}\right)^{-1} $$
Comment: Wait, what? Where did that come from, sir?
Comment: Majority of people underestimate power of well known limits and tries to bash limit with L'Hospital Rule instead of sit and think for a while. I'm sure you know that $\lim \frac{e^x-1}{x} = 1$ as $x$ goes to $0$ and following trick: $\sqrt{x} = x ^ {\frac{1}{2}}= e^{\frac{\ln x}{2}}$
Comment: Yes, I'm aware sqrt(x) = x^(1/2) but I dont know how do we get the other one e^(lnx/2)
Comment: Emm $e^{\ln x} = x$
Answer: Hint: You are looking to apply L'Hopital's Rule.
 This rule basically states the following:
$$\lim_{x\to 1} \frac{f(x)}{g(x)} = \lim_{x\to 1} \frac{f'(x)}{g'(x)}$$

Note: you can keep applying this rule multiple times, so it can go on and on until you get the value of the limit.

So keep calculating the limit of the derivative until you get one that is not division by zero or undefined, that value is the answer is the limit of your original question.
Comment: Yes, I've tried using that rule, but the result ends up so weird with many fractions and hard to continue.
Comment: @user95523 did you try it more than once? i.e. Do it on your result again.
Comment: Yes, I've tried doing it multiple times, I keep getting fractions over and over..


Connect 1/2" Polyflex tube to hose bib

Question: I have a length of 1/2" ADS Polyflex tube that I'd like to connect to a hose bib. What adapters do I need to get this job done?
This is the tube https://www.homedepot.com/p/Advanced-Drainage-Systems-1-2-in-x-100-ft-IPS-125-psi-NSF-Poly-Pipe-X2-50125100/205903467

My preferred hose bib is the Sharkbite Garden Valve for the simple reason that it comes with convenient screws for mounting to a post or the side of a raised bed. The Sharkbite website indicates that the product is "Compatible with PEX, copper, CPVC, PE-RT and SDR-9 HDPE pipe." Would that work with the ADS Polyflex tube which is labeled SIDR-15?
https://www.sharkbite.com/us/en/brass-push-to-connect/valves/outdoor-hose-valves/garden-valve

Other options I'm considering is finding some way to transition to something like a segment of PVC between the tubing and the hose bib or using a different bib and transitioning to NPT threaded adapters.
What do you all recommend?
Answer: That type of poly pipe uses insert barb fittings (typically available in brass or plastic - a few stainless steel options may now be out there in the lead-free era) and stainless-steel worm-drive hose clamps (use two per barb for best results. Put the screw parts of the two clamps on opposite sides for best results.)
As far as I'm aware you'd have to transition to pipe threads, which will connect directly to a normal hose bib or boiler drain, or you'd have to adapt from threads to a compatible pipe type to use your preferred Sharkbite bib.
Comment: Your solution worked. I was able to find a barbed-to-threaded adapter and then transitioned to pex. I initially resisted doing this because pex is not UV resistent but instead I will just build a little box to shield it from the sun.

Connect 1/2" Polyflex tube to hose bib


multiple array to dataframe pandas

Question: So, I am iterating through a dictionary and taking a bunch of values out as a array -  Trying to make a Dataframe with each observation as a separate row.
X1 =[]
for k,v in DF_grp:
    date = v['Date'].astype(datetime)
    usage = v['Usage'].astype(float)
    comm = v['comm'].astype(float)
    mdf = pd.DataFrame({'Id' : k[0],'date':date,'usage':usage, 'comm':comm})
    mdf['used_ratio'] = ((mdf['used']/mdf['comm']).round(2))*100
    ts = pd.Series(mdf['usage'].values, index=mdf['date']).sort_index(ascending=True)
    ts2 = pd.Series(mdf['used_ratio'].values, index = mdf['date']).sort_index(ascending=True)
    ts2 = ts2.dropna()
    data = ts2.values.copy()
    if len(data) == 10:
        X1 =np.append(X1,data, axis=0)
        print(X1)

[0,0,0,0,1,0,0,0,1]
[1,2,3,4,5,6,7,8,9]
[0,5,6,7,8,9,1,2,3]
....

similarly, so the question is how do I capture all these arrays in a single DataFrame so that it looks like below:
[[0,0,0,0,1,0,0,0,1]] --- #row 1 in dataframe
[[1,2,3,4,5,6,7,8,9]] --- #row 2 in dataframe

If the same task can be divided further ?
There are more thank 500K arrays in the dataset.
Thank You
Answer: I hope below mentioned code helps you:
arr2 = [0,0,0,0,1,0,0,0,1]
arr3 = [1,2,3,4,5,6,7,8,9]
arr4 = [0,5,6,7,8,9,1,2,3]

li = [arr2, arr3, arr4]
pd.DataFrame(data = li, columns= ["c1", "c2", "c3", "c4", "c5","c6", "c7", "c8", "c9"])

You can make it more dynamic by simply creating one temp_arr and appending that array to list. and creating data frame from generated list of arrays. Also, you can add name to columns(shown above) or avoid naming them(just remove column detailing). I hope that solves your problem
Comment: Edited the Question now, I have more than 500K arrays.
Comment: So to understand it correctly, you have 500, 000 arrays with each array having how many elements?
Comment: the number of elements are different but currently Im looking at just with len == 10.
Answer: Declare an empty dataframe in second line i.e. below X1=[] with code df = pd.DataFrame(). Next, inside your IF statement pass the following after appending values to X1:
df = pd.concat([df, pd.Series(X1)]).T

Or,
df = pd.DataFrame(np.NaN, index=range(3), columns=range(9))
for i in range(3):
    df.iloc[i,:] = np.random.randint(9)    # <----- Pass X1 here
df
#     0 1   2   3   4   5   6   7   8
# 0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0
# 1 7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0
# 2 8.0 8.0 8.0 8.0 8.0 8.0 8.0 8.0 8.0

Comment: Thanks, I had tried a similar approach but his breaks at the transpose with  --- 'Reindexing only valid with uniquely valued Index objects'
Comment: then declare a dataframe with known `shape` and `NaN` values. Later use `iloc` command to fill it. Cut the unnecessary rows later.
Comment: Could you provide an example, I did not get it.
Comment: check my modified answer. If you know the number of arrays beforehand then pass the value inside `index=range(NUMBER_OF_ARRAYS)`
Comment: Tried above now the error is   --   ' only size-1 arrays can be converted to Python scalars'

multiple array to dataframe pandas


FOR /D terminates with failure (...unexpected at this time)

Question: I have a .bat file with these lines executed by Jenkins CI job. It should remove all subdirectories in specified directory except two matching IF conditions.
SET EXPORT_ROOT=C:\WWW\LocalUser\myfolder
SET EXPORT_BUILD_ROOT=%EXPORT_ROOT%\build
SET EXPORT_BUILD_PATH=%EXPORT_BUILD_ROOT%\26
SET LAST_EXPORT_BUILD_PATH=C:\WWW\LocalUser\myfolder\build\25

cd %EXPORT_BUILD_ROOT%
FOR /D %G IN (*) DO (
    IF NOT ("%EXPORT_BUILD_ROOT%\%G" == "%LAST_EXPORT_BUILD_PATH%") IF NOT ("%EXPORT_BUILD_ROOT%\%G" == "%EXPORT_BUILD_PATH%") (
        rd /s /q "%G"
    )
)
cd "%DEPLOY_DIR%"

In Jenkins CI log a see:
C:\WWW\LocalUser\myfolder\deploy>cd C:\WWW\LocalUser\myfolder\build
G" == "C:\WWW\LocalUser\myfolder\build\57") IF NOT ("EXPORT_BUILD_PATHG" ) ) was unexpected at this time.

C:\WWW\LocalUser\myfolder\build>FOR /D G" == "C:\WWW\LocalUser\myfolder\build\57") IF NOT ("EXPORT_BUILD_PATHG" ) )

Build step 'Execute Windows batch command' marked build as failure
Answer: You need to change it more like this:
FOR /D %%G IN (*) DO (
    IF /I NOT "%EXPORT_BUILD_ROOT%\%%G"=="%LAST_EXPORT_BUILD_PATH%" (
        IF /I NOT "%EXPORT_BUILD_ROOT%\%%G"=="%EXPORT_BUILD_PATH%" RD/S/Q "%%G")
)

The positioning of your parentheses being important as well as the doubling of the % in a batch file meatvariable.
Answer: FOR /D %G IN (*) DO (
    IF NOT "%G" == "%LAST_EXPORT_BUILD_PATH%" IF NOT "%G" == "%EXPORT_BUILD_PATH%" (
        rd /s /q "%G"
    )
)

Each %G referring to the metavariable (loop-control variable) must be %%G


dns brocken, what's archive.ubuntu.com IP

Question: I've installed xenial in a container and for some reason dnsmasq got left out. Now I can't update or install packages. I tried to edit /etc/apt/sources.list and edit the repo addresses to include the IP addresses. However I couldn't find out the IP address of archive.ubuntu.com. I tried with ping, traceroute, dig, even wget and all report different addresses and none of those work (not even through the browser). Can anybody tell me what the correct IP address is?
Answer: Have you already tried this IP for Ubuntu?
Comment: Yes that's it! Tanks you very much!


Solving several linear equations

Question: The title might not be too descriptive; I'm not sure how to classify this question.
I have a set of linear equations of the form $$c_iA_i + p_iB_i = E$$ where $A_i$, $B_i$ and $E$ are 3 by 1 column vectors and $c_i$ and $p_i$ are scalars. As the subscripts indicate, I have $n$ such linear equations, where all the scalars and vectors except $E$ change with each one. Another limitation is that all I know for each set of linear equations is $A_i$ and $B_i$, and I want to find $E$.
Is there a method for solving these equations?
EDIT
The equation above is a simplification of the equation $$R^T_pT_D = c_iA_i - p_iR_DB_i$$ where $R^T_p$ is the inverse of a rotation matrix, $T_D$ is a translation vector and $R_D$ is another rotation matrix. I am interested in finding the rotation matrix $R_p$. Again, this equation describes the relationship between two homogenious points ($A_i$ and $B_i$) in 3D space, where the z component is 1 (i.e., the c and p scalars project the points to somewhere in the 3D space other than (x, y, 1)). I have n point-pairs A and B.
Comment: In your edit, what is "again" referring to? There was no indication in the original question that the $z$-component of $A_i$ and $B_i$ is $1$.
Comment: the again was meant to indicate that the A and B in the second equation are the same as the A and B in the first equation. Sorry if I didn't phrase myself clearly.
Answer: This is a homogeneous system of $3n$ linear equations for the $2n+3$ variables $c_i$, $p_i$ and the $3$ components of $E$. In general, for $n\ge3$ the trivial solution (all variables $0$) will be the only solution. If $n<3$, or if the equations happen to be linearly dependent and allow non-trivial solutions, you can find them by subtracting $E$ on both sides and writing out the $n$ $3$-component equations as $3n$ equations. Note that since the system is homogeneous, if there are non-trivial solutions, there's a whole vector space of them.

Solving several linear equations


Trivial representation of $SL_n$ in $V(\alpha_1)\otimes \cdots \otimes V(\alpha_m)$

Question: Suppose $\alpha_1,\cdots, \alpha_m$ are partitions of lenght at most $n$ with $c = \frac{1}{n}\sum_s\sum_i \alpha_s(i)$ an integer. If the representation of $SL_n$ $V(\alpha_1)\otimes \cdots \otimes V(\alpha_m)$ contains the trivial representation, then as a representation of $GL_n$ it contains the representation $(\wedge^n \mathbb C^n)^{\otimes c}$.
I don't understand why the power of the determinant representation is $c$.
Thanks!
Answer: Thinking of this as a $\mathrm{GL}_n$ representation, the product $V(\alpha_1) \otimes \cdots \otimes V(\alpha_m)$ will decompose into irreducibles $V(\lambda_1) \oplus \cdots \oplus V(\lambda_M)$ where each partition $\lambda_i$ has exactly $cn$ boxes. Since any power of the determinant representation is a partition with $n$ rows and some number of columns, it follows that it must have $c$ columns. Upon restriction to $\mathrm{SL}_n$, any power of the determinant representation becomes trivial.
Comment: I found a so complicated solution! xD Thanks for this one!


How can I gain access to an asynchronous response in synchronous code?

Question: I've got a web page where I need a user to click the save button to save the content of the form back to the web server.
Part of the save is a check of items which may require a prompt to the user that allows them to confirm, edit and reorder items in a javascript popup.
If the prompt is required, I need to be able to access the response from the user, i.e. was the confirm or the cancel button clicked, if the cancel button was clicked, the save process must be stopped, if the confirm button was clicked the save process must continue:
Psuedo code for synchronous behaviour:
function SaveData()
{

    if (itemsRequireValidation)
    {
        if (RESPONSE_CANCEL == ConfirmationDialog.Show()) {
            return;
        }
    }

    ProcessConfirmData(ConfirmationDialog.OutputData);

    //...Do the rest of the save process
}

Given that:

The confirmation dialog is a Javascript object that builds some HTML output, there is asynchronous behaviour introduced by way of the fact that we cannot really continue the process until the user clicks either the confirm or the cancel buttons contained within the dialog.
That blocking code to make the Javascript wait until the user clicks one or the other will have negative behaviour that could either crash the browser or prevent the user from even clicking either of the buttons.

How can I go about refactoring this to take into account the fact that the dialog box is essentially asynchronous, but I need to process the user interaction as if it were synchronous?
I think really I just need to look at this from another point of view that right now I'm not seeing.
Answer: Use callbacks.  Make your ConfirmationDialog allow callback functions as options, it can call those functions when the user responds.
function SaveDate() {

  function HandleSave() {
    // process rest of save
  }
  if (itemsRequireValidation)
  {
    ConfirmationDialog.Show({
      RESPONSE_CANCEL: function() {
         // cancelled, do nothing
      },
      RESPONSE_OK: function(output) {
        ProcessConfirmData(output);
        HandleSave();
      }
    });
  } else {
    HandleSave();
  }
}

Comment: The bit I'm missing is that the dialog may not need to be called... then what?
Comment: Oh, I think I just caught on, I pass in the "Save" function for the RESPONSE_OK method, but if the dialog doesn't get called, I just call the save function directly.  Colour me dumb... must be Monday morning :P
Comment: @BenAlabaster - Sorry, was expanding my answer as you were commenting - this look about right?
Comment: Yeah, that would work, just totally couldn't see the forest for the trees this morning :P
Comment: @BenAlabaster - Hey, it made my Jury Duty this Monday more interesting... ;)
Comment: P.S. Thanks, I appreciate the response
Comment: @gnarf You're doing this during jury duty? HAHAHA! That's awesome. Plead guilty for me :P
Comment: @BenAlabaster - Jurors don't plea, they listen and decide... *raises eyebrow*
Answer: I don't get why the dialog would be asynchronous. I guess I don't really understand what you're asking... In my view, it's simple:

user clicks SAVE
save routine checks for validation
if needed, popup is generated, save is abandoned (nothing is asynchronous yet)
when user confirms selection in popup, or popup is not needed, then initiate AJAX stuff.

Unless you are doing validation server-side, in which case,

user clicks SAVE
validation routine initiates AJAX, with success callback to, let's say, validationResponse
validationResponse gets a response saying whether save succeeded, or further edits are necessary
if not, you're done, stuff is saved
if further edits are necessary, give the user a chance
when user confirms the edits, redo from step 2.
Comment: The 'popup' is likely handled in JavaScript as HTML added to the document.  Waiting for the user to click on some HTML element is going to be asynchronous, in that it will only get called at some later event.  Sure, if they use the ugly JavaScript `confirm()` popup, its synchronous.
Comment: @gnarf Your first assumption was correct, and I agree, the confirm() popup is ugly.  I avoid that at all costs, to the point that I don't even use it for basic confirm/cancel (which in this case it's far beyond.
Comment: Of course it's ugly, wasn't even suggesting that. What I'm saying is, if you show the edit window, you aren't saving any more - save is abandoned for now, until such time the user submits the new form. Upon that time you are starting a new asynch cycle.
Comment: You missed the point of my comment on asynchronicity - it was asynchronous in terms of user interaction rather than the save process.  When the dialog is displayed, it's a non-blocking call to display the dialog, thus I was thinking I needed to pause the save routine until the response was received.  However, I understand your interpretation now +1


How do I find the probability of these independent events

Question: The following is taken from the ETS math review for the GRE:
Let A, B, C, and D be events for which P(A or B)=0.6, P(A)=0.2, P(C or D)=0.6, and P(C)=0.5 The events A and B are mutually exclusive, and the events C and D are independent.
Find P(D).
I'd appreciate it if someone could show me how to solve this. The answer is given as 0.2, but I don't know how it's arrived at. Thanks!
Comment: Do you know what it means for $A$ and $B$ to be mutually exclusive?  What about for $C$ and $D$ to be independent?
Answer: Using the independence of $C$ and $D$ we have that
$$
P(C)P(D)=P(C\cap D)=P(C)+P(D)-P(C\cup D).
$$
Use this to find $P(D)$. You don't need to involve $A$ and $B$ to find $P(D)$.
Answer: This is a question from the GRE practice book and the answer is not $0.1$, so the logic for the previous answer given ([edit LL:] by
user90188) its not correct. I'm almost sure the answer is:
b) $P(C\text{ or }D) = P(C)+P(D)-P(C\text{ and }D)$ since independent events may be NOT mutually exclusive events.
\begin{align}
P(C\text{ or }D) &= P(C)+P(D)-P(C)*P(D)    \\
0.6 &= 0.5+P(D)-0.5*P(D)     \\
0.6-0.5&=P(D)-0.5*P(D)    \\
0.1&=P(D)-0.5*P(D)    \\
0.1&=P(D)(1-0.5)    \\
0.1/(1-0.5)&=P(D)    \\
0.1/0.5&=P(D)    \\
0.2&=P(D)    \\
\end{align}
Comment: "so the logic for the previous answer given its not correct" Sorry?
Answer: P(c∩d)= 0 as they are independent so
p (c∪d)= p(c)+p(d)-P(c∩d)
so p(d)= 0.6-0.5
p(d)=0.1
Comment: $P(C\cap D)$ is not necessarily zero for independent events. I think you're confusing independent with mutually exclusive.


SignalR and AngularJS directives

Question: every one. I figure out what is the reson of my recent problem, but now I need an advice how to fix that. The error occurs while I'm trying to start SignalR javascript client (with using https://github.com/JustMaier/angular-signalr-hub) for ng-init directive.
Here is the error:
Error: SignalR: Connection must be started before data can be sent. Call .start() before .send()
at Object.signalR.fn.signalR.send (localhost:4745.lan/Scripts/jquery.signalR-2.1.1.

When I use SignalR script for ng-click everithing is ok. Here is just a test app:
angular.module('app', ['SignalR'])
.factory('SomeService', ['$rootScope', 'Hub', function ($rootScope, Hub) {

//declaring the hub connection
var hub = new Hub('myHub', {

    //client side methods
    listeners: {
        'doAction': function (message) {
            alert(message);
            console.log("It works");
            $rootScope.$apply();
        }
    },
    //server side methods
    methods: ['someAction'],

    //handle connection error
    errorHandler: function (error) {
        console.error(error);
    }

});
var load = function () {
    console.log(hub);

    hub.someAction(); //Calling a server method
};

return {
     loadSomeMethod: load
};
}])
   .controller('appController', ['$scope', 'SomeService', function ($scope, SomeService) {
    $scope.callMethod = SomeService.loadSomeMethod;
    $scope.text = "Index from Angular";
  }]);

View page
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

{{text}}

<input type="button" name="GreetAll" value="Greet All" ng-click="callMethod()" />

@section scripts
{
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jquery.signalR")
@**@
@Scripts.Render("~/bundles/angular")
@Scripts.Render("~/bundles/angular-resource")
@Scripts.Render("~/bundles/angular-signalr-hub")
@Scripts.Render("~/bundles/App")
@*@Scripts.Render("~/bundles/AppNew")*@
}

Answer: You're calling the load method before the server is fully started. the SignalR hub is started asynchronously, this means you have to ensure it has started before calling methods on it.
I had a look at the signalr hub class you're using. It puts the promise from the start method on the returned object. You can access it via hub.promise. Register a callback to e notified when the connection started successfully:
hub.promise.done(function(){
    // connection established
    // call your hub method here
});

You can't call the hub methods synchronously from your controller, instead you need to provide a promise to the controller. The controller can then register a callback to that promise and call the hub methods. Of course there are numerous other possible solutions (like using angularjs eventing) but in the end it boils down to this: you can't call methods on the hub directly at initialization time in the controller.

SignalR and AngularJS directives


Decomposition of Representations of $S_n$

Question: Let $\lambda,\mu$ be a partitions of $n$, $T^\lambda$ the set of $\lambda$-tabloids and
$\varphi^\lambda:S_n\to GL(\mathbb{C}T^\lambda)$ be the permutation representation and $\psi^\mu:S_n\to GL(S^\mu)$ the Specht representation.
I know that $\varphi^\lambda=\psi^\lambda\oplus\bigoplus_{\mu\trianglerighteq\lambda}m_\mu\psi^\mu$, my question is, how can I compute the $m_\mu$ in specific cases?
For example, if $\lambda=(3,1^2)$ then $\varphi^{(3,1^2)}=\psi^{(3,1^2)}\oplus m_{(5)}\psi^{(5)}\oplus m_{(4,1)}\psi^{(4,1)}\oplus m_{(3,2)}\psi^{(3,2)}$ and we can use the degrees using the hook length formula to get an equation for the $m$'s:
$$20=\deg\varphi^{(3,1^2)}=\deg\psi^{(3,1^2)}+m_{(5)}\deg\psi^{(5)}+m_{(4,1)}\deg\psi^{(4,1)}+m_{(3,2)}\deg\psi^{(3,2)}=6+m_{(5)}\cdot 1+m_{(4,1)}\cdot 4+m_{(3,2)}\cdot 5$$
but that gives 9 (I think, haven't computed them all) possible solutions for $(m_{(5)},m_{(4,1)}, m_{(3,2)})$. I also tried to use Frobenius reciprocity to compute the different multiplicities, but I couldn't come up with a way to write the different representations as inductions or restrictions.
Answer: You appear to want the multiplicities of Specht modules in the permutation module. These are given by Young's rule, and appears in all standard sets of lecture notes and books about symmetric groups. The coefficients $m_{\lambda,\mu}$ in the decomposition are equal to the number of semistandard tableaux of shape $\lambda$ and type $\mu$, and are called the Kostka numbers.
Wikipedia has a write-up about it.
Comment: Hey, sorry for being ambiguous. I slightly edited the question to make it clearer. I saw Young's rule in a few lecture notes I found online, but all of them omitted the proof which leads me to believe that there is a more elementary approach to this problem. I am not looking for a general formula, just a method that allows one to compute the multiplicities in a given example (like the one in my question).
Comment: @14159 The proof is about two pages, and is elementary. Young's rule gives you an expression for the coefficients. In a specific case you can simply work out the permutation character, compute the character table and take inner products if you want. But there is no secret simpler way to do things than Young's rule that we don't tell people about.


Find all the possible values of $\int_{\gamma} \frac{1}{z^2+1}dz$

Question: a) Let $D = \{z\in\mathbb{C}: z \neq \pm i\}$ and let $\gamma$ be a closed contour in D. Find all the possible values of $\int_{\gamma} \frac{1}{z^2+1}dz$.
b) If $\sigma$ is a contour from  0 to 1,, find all possible values of $\int_{\sigma} \frac{1}{z^2+1}dz$
I am stuck on a) I am not sure which $\gamma$ to choose. (I cannot use the Residue theorem, I did not learn it yet)
but for b) I chose $\sigma(t) = t$ for $t \in [0,1]$ which then when I solved the integral I got $\int_{\sigma} \frac{1}{z^2+1}dz = \pi/4$
Comment: @pop Part a) requires the Residue Theorem. Why do you say you cannot use it?
Comment: Where is this problem from? I expect the author of the problem expects the reader to use the residue theorem, since it seems unavoidable...
Comment: Partial fractions is your friend. And homotopy.
Comment: You don't get to choose $\gamma$, do you? You have to find all possible values of the integral - there will multiple different values depending on what $\gamma$ is, no? So, do you have the residue theorem at hand?
Comment: @runway44 perhaps, not that is why I am stuck. I am doing this problem without knowledge of Residue Theorem
Comment: @ndhanson3 I did not learn it yet
Comment: Well, it is easily answered with the Residue Theorem, and I believe cannot be answered fully without it. Part b) uses the Fundamental Theorem of Calculus (or maybe called Fundamental Theorem of Complex Line Integrals).
Comment: For part a, consider a few cases: where $\gamma$ encloses none, each individually, or both of the singularities of the integrand
Comment: @runway44 The textbook is Complex Analysis Second Edition by Ian Stewart and David Tall. The Residue Theorem is mentioned 4 chapters later than this problem
Comment: @pop Ah, winding number is presented separately. You'll use the theorem relating the integral over closed contours to the points outside of the domain $D$.
Answer: Note that$$\frac1{z^2+1}=\frac{i/2}{z+i}-\frac{i/2}{z-i}.$$So,$$\oint_\gamma\frac1{z^2+1}\,\mathrm dz=2\pi i\left(\frac i2\operatorname{ind}_\gamma(-i)-\frac i2\operatorname{ind}_\gamma(i)\right).$$Since each of the numbers $\operatorname{ind}_\gamma(-i)$ and $\operatorname{ind}_\gamma(i)$ can be any integer, $\oint_\gamma\frac1{z^2+1}\,\mathrm dz$ can be any integer multiple of $\pi$.
Comment: how did you go from the integral to the right hand side?
Comment: I used the definition of winding number:$$\operatorname{ind}_\gamma(a)=\frac1{2\pi i}\oint_\gamma\frac{\mathrm dz}{z-a}.$$


Is there any browser plugin or js library that allows rotate 3D DWG objects?

Question: Have you seen somthing like this?
I tryed http://www.autodwg.com/dwg-viewer/dwgviewx.htm, but it seems it supports just 2D objects
Another problem is taht it should work under IE8.
Answer: There is a library called Three JS, you can find it here http://threejs.org/
But basically you need to convert the file to a obj extension.


Which stars can I travel to?

Question: Once I select a ship, I can't send to any star, only certain stars. The rule seems to be that I can't travel more than a certain distance from the nearest colony or outpost. Scouts seem to be able to go farther than other ships. What distance can I travel, exactly? What are the rules?
Answer: It's based on your refuelling range, which starts out at 4 parsecs with the Standard Fuel Cell technology and goes up with further fuel cell technological advances.  The refuelling range prevents you from travelling to any destination that's not in the given range of one your colonies or outposts.  However, it doesn't directly limit the distance your ships can travel. For example, a ship can always travel between two of your colonies regardless of the distance between them.
Scout ships can travel farther, an additional 50%, because they're outfitted with Extended Fuel Tanks. It's possible to add this system to other ship designs, but because of the large amount of space it takes it's generally only useful for scouts.
Comment: @JackM Not that I know of, though you usually don't care unless you have a ship at star A. You can however find out if a planet is in range of your colonies or not by viewing the list of planets and filtering by "Planets in Range".
Comment: Is there any way to find out the distance between two stars in parsecs other than putting a ship at star A and hovering the mouse over star B?

Which stars can I travel to?


Button onClick Call Java Method Until Certain Result

Question: I'm completely new to the Spring framework (and most web development in general), but I'm trying to hook up some heavy Java backend code to a new Spring and JSP project. My Controller's handleRequest() is kicking off a long running worker thread before it returns my request.jsp ModelAndView object. After that I'd like to be able to still interface with this Controller from my JSP form to be able to call isThreadDone() in the Controller whenever a button in the form is clicked. Based on three different results, I then redirect accordingly. Is this possible with my current approach? This seems to violate some of the Spring MVC approach, but I can't think of a good way to do this that I can wrap my head around. If anything is way off here, please excuse my ignorance. Thanks in advance.
Answer: Well, anything is possible, right? Based on what you've provided, you can just keep a reference to the thread--maybe in the HttpSession--so that when a new request comes in from clicking the button, you can query it and return an appropriate response.
Comment: I thought about that, but it seems like a workaround rather than a solution. If that's the best way though, then that's the best way. Thanks for your help!
Comment: @Matt: What concerns you about it? If you define your scenario a little more clearly, maybe a more appropriate solution will appear.
Answer: Take a look at the Spring @Async annotation.  If you annotate a Service-layer bean with that annotation, it then runs in its own thread, allowing your Controller thread to run without interruption after calling the Service method.  Have that thread is set a value held at the Class level for the Service via synchronous methods, and your Controller code can just check those toggles at will to see if the process is done or not.  Something like:
@Service
public myServiceClass {
   private boolean isDone = false;
   public synchronized void setIsDone(boolean isDone) {
      isDone = isDone;
   }
   public synchronized boolean getIsDone() {
      return isDone;
   }
   @Async
   public void myServiceMethod() {
      ...long-running stuff...
      setIsDone(true);
   }

In the Controller:
@Controller
class MyController {
   @RequestMapping
   public kickOffHandlerMethod() {
      myServiceClass.myServiceMethod();
      }
   }
   @RequestMapping
   public dependentHandlerMethod() {
      if(myServiceClass.getIsDone()) {
         ...do something...
      }
   }
}

If more than one request might kick off the process, then I would save each isDone toggle in a HashMap with some kind of identifier.  Then the threads would update individual toggles, one for each request.