Find all continuous functions from $ ]0,+\infty[ \to ]0,+\infty[ $ that satisfy $\forall x\in ]0,+\infty[ , f(x) = f(x^a f(x)) $.

Question: Let  $ a > 1 $. Find all continuous functions from $ ]0,+\infty[ \to   ]0,+\infty[ $ that are solutions to the functional equation $\forall x\in ]0,+\infty[ ,  f(x) = f(x^a f(x)) $.
It's easy to see that
all positive constant functions  are solutions
If $f:  ]0,+\infty[ \to   ]0,+\infty[ $  is invertible, the only solution is $ f(x) =\frac{1}{x^{a-1}} $
Some ideas?
Comment: I am familiar with the notation  ℝ_+ meaning (0, ∞). But what does the asterisk superscript mean?
Comment: $x^a f(x)$ is an idempotent function
Comment: Are u sure ? if $h(x)=x^a f(x)$, then $h(h(x))=\frac{(h(x))^{a+1}}{x^a}$
Comment: Right, I misread the question.
Comment: it  means $]0,+\infty[$.  Notation changed
Comment: Another solution: $f(x) = \frac{1}{x^[a-1}} $ if $ x \leq 1 $ and $ f(x) = 1 $ if $ x \geq 1 $
Answer: Claim: The continuous functions satisfying the equation $f(x) = f(x^af(x))$ are exactly the set of functions of the following form for some constants $c_1,c_2$ such that $0\le c_1\le c_2\le \infty$:$$
f(x) =\begin{cases}\frac1{c_1^{a-1}} & x \le c_1 \\ \frac1{x^{a-1}} &x\in(c_1,c_2)\\\frac1{c_2^{a-1}} & x \ge c_2 \end{cases}
$$
This is clearly continuous on $(0,\infty)$ and it satisfies the functional equation trivially for $x\in(c_1,c_2)$. For $x\le c_1$, we note that $c_1\ge \frac{x^a}{c_1^{a-1}}=x^af(x)$ so we have $\frac1{c_1^{a-1}}=f(x)=f(x^af(x))$. Similarly this $f$ works for $x\ge c_2$. (Note: $f$ is constant if $c_1=c_2$, and $f(x) = \frac1{x^{a-1}}$ if $c_1=0$ and $c_2=\infty$.)
To prove the claim, we'll make use of what I'm going to call the reflection princple: If $f$ satisfies the functional equation, then so does $\bar f(x) = \frac1{f(1/x)}$.
Define $h(x) =x^a f(x)$. Then we have $f(x) = f(h(x))$, and $h$ is a continuous function from $(0,\infty)$ to $(0,\infty)$. We will prove the claim as a series of lemmas about $f$ and $h$.

Lemma 1: $h(x)$ is strictly increasing.
Proof: First, we show $h$ is injective. Suppose $h(x)=h(y)$. Then \begin{eqnarray}
&&h(x)=h(y)\\
&\implies& f(h(x))=f(h(y))\\
&\implies& f(x) = f(y)\\
&\implies& \frac{h(x)}{x^a} = \frac{h(y)}{y^a}\\
&\implies& x=y
\end{eqnarray}
Thus $h$ is either strictly increasing or strictly decreasing. If it is decreasing, we may derive a contradiction, because in that case $f(x)=h(x)/x^a$ would also be strictly decreasing (as a product of two decreasing positive functions), and thus in particular $f$ is invertible and therefore $f(x) =\frac1{x^{a-1}}$, which implies $h(x) = x$, which is not decreasing.
Lemma 2: The set of points such that $h(x)=x$ is a closed interval in $(0,\infty)$. [Note: In the subspace topology, $(0,\infty)$ and intervals of the form $(0,b]$ are closed though they are not closed in $\mathbb R$.]
Proof: We use contradiction to prove the slightly weaker claim that if $A<B$ are real numbers with $h(A) = A$ and $h(B)=B$, then there exists $C\in(A,B)$ such that $h(C)=C$.
Suppose $h$ has no fixed points in $(A,B)$. By the reflection principle, we can suppose without loss of generality that $h(x)>x$ for all $x\in(A,B)$. By injectivity and continuity of $h$, we can see that it is a bijection from $(A,B)$ to itself. Furthermore, it is evident that, for each $x\in(A,B)$, the sequence $\{x,h(x),h(h(x)),\dots\}$ converges to $B$. Therefore, for all $x\in(A,B)$, we have $$
f(x) = f(h(x)) = f(h(h(x))) = \lim\limits_{n\rightarrow\infty} f(h^n(x)) = f(B) = B
$$
But this makes $f$ discontinuous at $A$, a contradiction. Therefore $f$ has a fixed point in $(A,B)$.
This implies that, if $A\le B$ are fixed points of $h$, the fixed points of $h$ are dense in $[A,B]$. By continuity of $h$, the set of fixed points is a closed set, and therefore is cannot be anything other than a closed subinterval of $(0,\infty)$.
Lemma 3: $h(x)$ has a fixed point.
Proof: We again prove by contradiction. Suppose $h(x)\ne x$ for all $x$. By the reflection principle, we may suppose without loss of generality that $h(x)>x$ for all $x$. This implies for any $x$ $$
\lim\limits_{n\rightarrow\infty} h^n(x) = \infty
$$
Fix $x_0$ and define $I_n = [h^n(x_0),h^{n+1}(x_0)]$. Let $M=\max_{x\in I} f(x)$. We note that $h(I_{n-1}) = I_n$, thus for each $n$, $f(x)\le M$ for all $x\in I_n$. Because $[x_0,\infty)=\bigcup_{n\ge0} I_n$, we conclude $f(x)\le M$ for all $x\in [x_0,\infty)$. However, this contradicts $h(x)>x$ for all $x$: For $n$ sufficiently large, we have $h^n(M^{-\frac1{a-1}} )\ge x_0$, and thus $$
M^{-\frac1{a-1}} < h(M^{-\frac1{a-1}}) = M^{-\frac a{a-1}}f(M^{-\frac1{a-1}}) = M^{-\frac a{a-1}}f(h^n(M^{-\frac1{a-1}})) \le M^{-\frac a{a-1}} M=M^{-\frac1{a-1}},
$$
a contradiction.
Lemma 4: Suppose $h(B)=B$ and $h(x)\ne x$ for all $x>B$. Then $f(x)$ is constant on $[B,\infty)$.
Proof: By continuity, we have either $h(x)>x$ or $h(x)<x$ for all $x>B$. In the former case, we observe that $h$ is a bijection on $(B,\infty)$, and thus we have a $h^{-1}$ is well defined with $h^{-1}(x)<x$ for all $x>B$. We also note that $f(h^{-1}(x)) = f(x)$ for all $x$.
Pick $\epsilon>0$. Then there exists $B'>B$ such that, for all $x\in(B,B')$, $|f(x) - f(B)|<\epsilon$. If we pick $x>B$ arbitrary, we observe that either $h^n(x)$ decreases to $B$, or $h^{-n}(x)$ decreases to $B$ (depending on whether $h(x)<x$ or $h(x)>x$ for $x>B$). Thus, we have for some $z\in\mathbb Z$, $h^z(x) \in(B,B')$. Therefore $$
|f(x)-f(B)| = |f(h^z(x))-f(B)|<\epsilon
$$
Since $x>B$ was arbitrary, we conclude $|f(x)-f(B)| <\epsilon$ for all $x>B$. Letting $\epsilon$ go to $0$, we conclude $f(x)=f(B)$ for any $x>B$.

Proof of claim: Let $f(x)$ be a continuous function satisfying $f(x)=f(x^a f(x))$ for all $x\in(0,\infty)$. It is straightforward from here to show that $f$ has the desired form. We note that $f(x)=\frac1{x^{a-1}}$ is equivalent to $x$ being a fixed point of $h$. By Lemmas 2 and 3, there exists a closed interval $I$ such that $f(x) = \frac{1}{x^{a-1}}$ for all $x\in I$, and $f(x)\ne \frac{1}{x^{a-1}}$ for all $x\notin I$. By Lemma 4, if $f$ is constant to the right of $I$. Suppose the left endpoint of $I$ is $A>0$. By the reflection principle, we have that $\bar{f}$ is equal to $\frac1{x^{a-1}}$ in the interval $1/I$. Thus, by Lemma 4, $\bar{f}$ is constant for $x>\frac1A$, which implies that $f$ is constant for $x\in(0,A]$. Using continuity of $f$, we can see what the constant values are to the right and left of $I$ and therefore $f$ must have the claimed form for some $c_1,c_2$. Q.E.D.
Comment: Very great proof, thank you very much. It's a challenging functional equation


Error while Installing APK

Question: Today, I have updated my android studio from gradle  2.2.1 to 2.14.1
from that onwards my studio is unable install any apk files in the device.
  it showing the error.
<code>\app\build\outputs\apk\app-debug.apk does not exist on disk.
Error while Installing APK.
</code>
But on the explorer the directory contains apk file. I have tried clean,  rebuild & restared the studio also, but unable to fix. please help me.
Comment: check my answer
Comment: use `2.2.0` .Clean-Rebuild
Comment: please tell me how to change it
Answer: click on option to solve your error
Comment: @kashyap build your project
Comment: Hi Mehra, i have build the project but still i am unable to install the apk file
Comment: Is the filename of apk is same as app-debug.apk ?
Answer: I solved my problem by changing gradle version to previous state. in
File-->project structure-->Project -->Gradle version & Android plugin version.

Error while Installing APK


C# Excel not creating an instance when run outside of debug mode. (IIS instance)

Question: Sorry for the poorly worded title. I have an application that will take in an excel file, make some changes, format the data as a dataset and export to excel in C#. when I run either in debug mode (F5) or with ctrl + F5 it has no problem running. The excel sheet is created, filled, and saved to the proper location. when I set up in instance in IIS to test it outside of this method to simulate a user (same machine, browser, etc), it cannot create the excel application. It does not throw an error, it just simply never creates, fills, or moves to location and then says everything worked. I believe the problem (to the best of my knowledge) is with the code here
<code> Excel.Application excelApp = new Excel.Application();
 excelApp.Visible = true;
</code>
To clarify, my excel import at the top is
<code> using Excel = Microsoft.Office.Interop.Excel;
</code>
This problem is hard to understand without an error output. The best information I can provide is what is provided in event viewer.
In the System View I get an error of
<code> The server {00024500-0000-0000-C000-000000000046} did not register with DCOM within the required timeout.
</code>
And in the Application Viewer I get an error of
<code> Faulting application name: EXCEL.EXE, version: 16.0.9126.2282, time stamp: 0x5b90650a
 Faulting module name: AppVIsvSubsystems32.dll, version: 6.3.9600.18895, time stamp: 0x5a4b127e
 Exception code: 0xc0000142
 Fault offset: 0x0009d4e2
 Faulting process id: 0x13a4
 Faulting application start time: 0x01d45984c26a7014
 Faulting application path: C:\Program Files (x86)\Microsoft Office\Root\Office16\EXCEL.EXE
 Faulting module path: AppVIsvSubsystems32.dll
 Report Id: 001becbd-c578-11e8-80f3-00505689c70f
 Faulting package full name:
 Faulting package-relative application ID:
</code>
Let me know if anymore information is needed or if anything was unclear
Comment: Does your IIS instance run on the same machine as where you made the debug?
Comment: Yes, same machine.
Answer: Try without using interop, and using dynamic variable instead:
<code>Type excelType = Type.GetTypeFromProgID("Excel.Application");
dynamic excelApp = Activator.CreateInstance(excelType);
excelApp.Visible = true;
</code>
Comment: I don't use dynamic almost ever so perhaps I made a mistake, but when adding that I got an error saying

     'System.Reflection.TypeInfo' does not contain a definition for 'Visible'
Comment: Yes Excel is installed.
Comment: Sorry I missed a step!
Answer: you need to use a different library to zip. EPPlus
Comment: What is the reasoning for needing to use a different library to zip?
Comment: @Nick The name is on the library :) to make your job easier.
Comment: @Nick and you don't need to deal with such mistakes.
Comment: I'm not sure if this is the "correct" solution, but this solution did work after implementing EPPlus. For that reason i'll mark this as the solution.
Comment: @Nick you can be sure. Because libraries can handle such thin and small things for you. Otherwise you have to deal with too many settings.


inequality involving heights and bisectors

Question: Let $a,b,c,a \le b \le c$ be the sides of the triangle $ABC$, $l_a,l_b,l_c$ the lengths of its bisectors and $h_a,h_b,h_c$ the lengths of its heights. Prove that:
$$\frac {h_a+h_c} {h_b} \ge \frac {l_a+l_c} {l_b}$$
Comment: Just to make sure:  you are referring to angle bisectors, right? (Not bisectors of the opposite side)
Comment: angle bisectors @Andreas
Answer: Here's a proof.
The formulae for the lenghts of the angular bisectors and the heights are known. (see e.g. https://en.wikipedia.org/wiki/Triangle ). Let $T$ be the area of the triangle. We have
$$ l_a = \sqrt{bc (1 - \frac{a^2}{(b+c)^2})}$$
and
$$h_a = \frac{2 T}{a}$$
and cyclic shifts of those.
With these formulae, the required inequality gets
$$
\frac{1/a + 1/c}{1/b} \geq \frac{\sqrt{bc (1 - \frac{a^2}{(b+c)^2})}
+ \sqrt{ab (1 - \frac{c^2}{(a+b)^2})}}{\sqrt{ac (1 - \frac{b^2}{(a+c)^2})}}
$$
Multiplying  the RHS by
$$1 = \frac{1/\sqrt{abc}}{1/\sqrt{abc}}
$$
gives
$$
\frac{1/a + 1/c}{1/b} \geq \frac{\frac{1}{a}\sqrt{a (1 - \frac{a^2}{(b+c)^2})}
+ \frac{1}{c}\sqrt{c(1 - \frac{c^2}{(a+b)^2})}}{\frac{1}{b}\sqrt{b (1 - \frac{b^2}{(a+c)^2})}}
$$
Due to homogeneity, we can set $b=1$. This gives the condition $a\leq 1\leq c$ and the inequality gets
$$
\frac{1}{a} + \frac{1}{c} \geq \frac{1}{a}\sqrt{
a \frac{
1 - \frac{a^2}{(1+c)^2}
}{
1 - \frac{1}{(a+c)^2}
}
}
+ \frac{1}{c}\sqrt{
c\frac{
1 - \frac{c^2}{(a+1)^2}
}{
1 - \frac{1}{(a+c)^2}
}
}
$$
We now first prove that the first root is less or equal than 1, i.e. we need
$$
{a (1 - \frac{a^2}{(1+c)^2})} \leq
1 - \frac{1}{(a+c)^2}
$$
which can be transformed into
$$
(a+c)^2 (1-a) \geq 1 - a^3 (\frac{a+c}{1+c})^2
$$
The last bracket  can be expanded and it suffices to prove
$$
(a+c)^2 (1-a) \geq 1 - a^3 (1 - 2 \frac{1-a}{1+c})
$$
which shortens to
$$(1+c) a (1-a) \geq 2 a^3 (1-a)$$ or $$(1+c) \geq 2 a^2$$ which is certainly true under the given condition $a\leq 1\leq c$.
Likewise, we  prove that the second root is less or equal than 1, i.e. we need
$$
{c (1 - \frac{c^2}{(1+a)^2})} \leq
1 - \frac{1}{(a+c)^2}
$$
which can be transformed into
$$
(a+c)^2 (1-c) \geq 1 - c^3 (\frac{a+c}{1+a})^2
$$
We can expand the last bracket and it suffices to prove
$$
(a+c)^2 (1-c) \geq 1 - c^3  (1 + 2 \frac{c-1}{1+a})
$$
or in positive terms
$$
(a+c)^2 (c-1) \leq  c^3 -1 +   2 c^3 \frac{c-1}{1+a}$$
Since $a\leq1$, it suffices to prove
$$
(1+c)^2 (c-1)  - c^3 +1 \leq    2 c^3 \frac{c-1}{1+a}$$
or
$$
(1+a)(c^2 - c) \leq 2 c^2 (c^2-c)
$$
which shortens to
$$1+a \leq 2 c^2$$ which is certainly true under the given condition $a\leq 1\leq c$.
Hence both roots are less or equal to 1, which proves the inequality.


Why isn't my Caesar's encryption problem not running?

Question: I'm having problems with running this loop for an assignment for university. It runs the first one giving the first letter correct, but then giving an error because the endindex is out of range somehow. I've tried adjusting multiple things, but it still doesn't work.
This is the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.substring(String.java:1963)
    at Assignment4.Question4.main(Question4.java:18)

My code:
package Assignment4;

import java.util.Scanner;

public class Question4 {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Type a string: ");
    String message = in.nextLine();
    System.out.print("Type a key of the same length: ");
    String key = in.nextLine();
    in.close();

    int messageLength = message.length();

    for (int a = 0, b = 1; a < messageLength && b <= messageLength; a++, b++) {
      key = key.substring(a,b);
      message = message.substring(a,b);
      System.out.print(String.valueOf((char)(message.charAt(0) + Integer.parseInt(key))));
    }
  }

}

Answer: You are overriding the variable key in your loop.
for (int a = 0, b = 1; a < messageLength && b <= messageLength; a++, b++) {
      key = key.substring(a,b);

The first iteration gives you the very first character of the initial value for key and "overrides" key by this character. The next iteration with a == 1 and b == 2 will cause a StringIndexOutOfBoundsException because key has only the length 1.

FYI: The same error will be caused by message.

To solve the problem you'll need additional variables to store the temporary results and the final result.


How to orient towel holders on tile that is not installed straight

Question: I was just about to install some towel holders on tile in the bathroom of our recently purchased house, and noticed that the tile is strangely not installed parallel to the floor and ceiling.  The tile lines slope 3/16" over the two feet of a towel holder, and almost 3/4" over the whole bathroom.  The slant of the tile is not really a problem in itself -- you would not notice with a casual glance.
But I wondered what was the best choice for aligning the towel holders -- level with the floor and ceiling, or aligned with the tile, at an 0.8% slope, or something in between.  It's not a technical question; more a matter of aesthetics or principle.  What would a pro do?
Comment: asking for an opinion is off topic here ... because there is no wrong answer   ... how would you choose the correct answer?
Comment: Think of the person who would be most critical of your work if (s)he found it unsatisfactory.   Tell that person you would very much value their opinion.  Do whatever they say.
Comment: I sort of agree that this is opinion, but another way of asking is, "what would a competent professional do?" (Answer: align with the tiles.)
Answer: .8% won't be noticed by the eye
Align it with the tiles - those make the most definitive line
I installed a closet bar level in a closet that was way out of level and looking at it in relation to the closet made you feel sea sick.


Deriving an expression for an n-th composition of some Mobius transformation

Question: Let $T(z)=\dfrac{1-3z}{z-3}, T^2(z)=T(T(z)),..., T^{n+1}(z)=T(T^{n}(z)),n=1,2....$
Could anyone advise me on how to find an expression for $T^n(z) \ ?$
I'm trying to make use of the fact that there exists constant $k$ such that $\dfrac{T(z)-1}{T(z)+1}=k\dfrac{z-1}{z+1}.$
Answer: You've already had the key in your hand, then it goes like
$$\dfrac{T^2(z)-1}{T^2(z) + 1} = \dfrac{T(T(z))-1}{T(T(z)) + 1} = k\dfrac{T(z)-1}{T(z)+1} = k^2 \dfrac{z-1}{z+1}$$
Similarly by induction you get
$$\dfrac{T^n(z)-1}{T^n(z) + 1} = k^n \dfrac{z-1}{z+1}$$


Prevent deployment of service if supporting services aren't yet deployed with octopus

Question: We have a distributed system with many services which talk to each other.
Sometimes a code change in one service will require a feature to have been deployed in another service.
We use octopus to deploy all the things which is cool but we really want to prevent services from being deployed before the things they depend on are deployed.
Is there a way we can do this with octopus deploy?
For example can I make the nuget package for one service depend on an explicit version range of another package?
Answer: If you don't want to deploy all your projects as one massive deployment with a series of steps that push your different services to different machines, then I don't think there's a built-in way to make your deployments dependent on each other's version numbers like that. (see this uservoice suggestion in Octopus asking for that very feature)
However, I do think that you could write a powershell script that ran as a pre-deployment step and checked the version number of one nuget package against a version range stored in another. Then the ps script could halt or allow deployment accordingly.
Comment: Yeah, I wondered if I was just being cruel and linking you your own request. Upvotin' time I guess!
Comment: Its a shame this isn't in there but good find on the feature request. Its interesting someone just posted that recently (it wasn't me)


Is there a better solution than a lint trap for venting a clothes dryer indoors?

Question: My condo association does not allow installing a dryer vent to outdoors, so I am forced to vent my dryer into a lint trap. Unfortunately the trap I have does not catch all the dust, and the rooms adjacent to it gather visible dust within 2-3 weeks. I make sure to change the water in the trap after every load. Are there traps available that perform better? Are there any additional filters/gadgets that may help with this?
Some additional notes: As much as I would like to set up a vent to outside, it is not an option for me. Humidity is not an issue, as I only dry clothes with no or lowest heat setting, and I do have an a/c register nearby to help provide dry air.
Edit: The dryer is electric. I live in a suburb of Chicago, which may have a different building code than the city itself.
Comment: Agreed. Your condo association is in the wrong here.  Venting a dryer indoors is a very bad practice as it introduces not only lint (a fire hazard) but large amounts of moisture into the inside where it can promote mold growth.
Comment: What you are doing is not up to code (See Chicago Building Code [18-28-504.1](http://www.amlegal.com/nxt/gateway.dll/Illinois/chicagobuilding/division28-mechanicalsystems/chapter18-28mechanicalrefrigerationsyste?f=templates$fn=default.htm$3.0$vid=amlegal:chicagobuilding_il$anc=JD_18-28-504.1)). You should bring this up to the building owner and condo association.
Comment: This has to be a joke!  NO WAY!
Comment: Humidity is an issue regardless of the temperature you use to dry it. And while the A/C can help with that, you're now sending excessive dust and humidity into the A/C ducts which isn't good for the building at all.
Comment: Lung rot from breathing fiber particulate, sounds funny but one of the causes of CPOD. Maybe you need to introduce asbestos into the head offices...
Answer: According to Chicago Building Code

18-28-504.1  Installation.
Clothes dryers shall be exhausted in accordance with the
  manufacturer's instructions. Dryer exhaust systems shall be
  independent of all other systems and shall convey the moisture and any
  products of combustion to the outside of the building.
Exception: Where the make and model of an electric dryer is known
  and the manufacturer's installation instructions do not require
  exhaust, see Article 4, Ventilation for room exhaust requirements.

Venting a dryer inside is a potential fire and mold hazard, and can negatively affect indoor air quality causing sickness (and/or death, maybe).
You should bring this up with the condo association, the building owner, and potentially the building inspector.  A possible down side to this action is, the condo association could ban the installation of dryers altogether.  So you'll want to try and suggest some alternatives.
I'm going to guess, the condo association is worried about the appearance of vents sicking out all over the building.  A potential appeasement would be to select a nice looking vent (voted on by the condo association), and force anybody who installs a dryer to use the same vent.
They may also want all vents to be installed in similar locations, so the vents are uniformly placed on the building.  A good way to insure this would be to install all the vents at once, including installing vents for units without dryers (in which case they should be sealed until in use).
Answer: Just get an electric condenser dryer, we have a Bosch WTW84560GB that is great, it also uses a lot less power than the older models that need venting.
Comment: I'm not sure "Just" is justified.  A condenser dryer will require installing a drain pipe, which is it's own project.  That said, the idea isn't a bad one.
Comment: @The Evil, I never see a condenser dryer that needs a drain pipe, we just have a small easy to remove water tank we have to empty at the same time as cleaning the lint filter.
Comment: I dunno - I guess I'd rather do the bigger hassle up front to avoid the little hassle for the rest of the time I live there. ;)
Comment: @The Evil Greebo, in the UK it is not a hassle to empty the water tank as the dyer is normly next to the kitchen sink, it takes longer to clean the lint filter.
Comment: I like this idea very much. I will look into this style of dryer to see if it will address my problem.
Comment: Condenser dryers can also share the drain tube for the washer.
Answer: Both comments on your question are correct.  Bring this up with your condo supervisor.  If he refuses to do anything about it, I would call the city building inspectors and find out what you can do about this.  All ventilation for dryers should be directed to the outside, because(like what has been said by Tester and Greebo) this promotes a big fire/mold hazzard.  As well, if it gets too bad, and there is enough particulate floating in the air, this can cause a static discharge that could start the fire without there being any danger of having an open flame source in the room where it is venting into.  Call your city building inspector.
Comment: The down side of this approach, is that the condo association could decide to ban dryers in condos altogether.
Comment: "if they were going to be asses". ha ha. They already are!  They want to risk the health of all tenants, so they don't have ugly vents sticking out of the building. Sounds pretty asstastic to me.
Comment: The condo association does not have the authority to supersede the building codes.  Their choices really are either ban dryers or STFU.  If the entire condo community bands together they will have little choice but to fold.
Comment: True, if they were going to be asses like that, they should at least have a community laundry mat for the tennents to use if this is going to be a liability.  I still think that they are putting their tennets in danger by trying to cut corners.  I do not believe that the original inspection of the property allowed for this.
Comment: @The Evil Greebo: There might be a loop hole. If the building and electrical connections predate the code, they may be grandfathered in.  I'm not exactly sure how that works (I'm no lawyer), but I think it would be their only defense.
Answer: As already stated, venting a dryer indoors is illegal and extremely dangerous (especially if it's a gas dryer)...as well as just a huge annoyance (you end up with a humid, dusty room).
What you can do is invest in a Washer/Dryer combo unit that doesn't require venting. It works via dehumidification. It takes longer to wash and dry, but works great:
And I'd do as others have suggested as well...you don't want ANY of the dryers in the building venting to the inside. Force the association to fix this issue for everyone.
Comment: @Tester101, I don't see anythink **unsafe** about vending an any electic dryer indoors.   It will steam up windows, but that is not a **safty** issue.  Anyway the moisture from a dryer is no more then drying the cloths on racks in a house.
Comment: Apologies, 'illegal' may have been a badly chosen word. It's definitely against most (all?) US building codes, however. Gas dryers are also very common here in the states. As for safety, high moisture in most any residence is a health issue as it is an ideal environment for mold and dust mites. On top of that, you're spewing large amounts of fine dust into the room which is a health issue for the lungs (not to mention just a pain in terms of cleaning).
Comment: It is not illegal in the UK, also I have never seen a gas dryer sold for home useage.
Comment: Fair point @walker, but OP is in Chicago. And even though it is not illegal to vent indoors in UK (and likely other places), it is still not safe.


Android 5(HTC) EACCES (Permission denied)

Question: app can't create folder/file on android 5(HTC HTC6525LVW os version: 5.0.1) external storage in directory owned by app.
Parent folder is returned by [getExternalFilesDirs(String type)][1] method.
Sdcard is mounted.
Anyone else having this problem or suggestion how to solve it?
(Unfortunately I don't have this device to test it more)
Edit: From one user I know that prior this bug she encrypted sdcard and then formatted it.
Comment: You should try this again with a phone that's not the HTC with the **exact** same configuration (same USB debugging mode, same installation process, etc.) and see if it's just an android thing or if it's an HTC thing.
Comment: Are you trying to create folder/file from a class from the same package as the class that called `getExternalFilesDirs(String)`?
Comment: @helleye yes, same package
Comment: Have you tried to run on another device with v5.0.1? In general, on which devices and Android versions have you successfully(and not) run your app?
Comment: @helleye problem is only on device specified in my question.
Answer: Some potential ideas as to what caused it:

If the phone is running in USB Storage mode when connected to your computer you can still deploy/debug like normal but write operations will fail
You were missing a permission: in your manifest file you should check to see if you have  <permission name="android.permission.WRITE_EXTERNAL_STORAGE" >
Permissions in the wrong location: make sure that your permission tag (in manifest) is located outside of the application
Writing to the data folder can cause issues like this so make sure you're writing to sdcard and not data

This is everything I could think of. Hope it helps :)
Comment: Thanks for answer but none of these points is true in this case.
Comment: Sorry it didn't help. Not that much to go on :/
Answer: Add permission to your manifest.xml file permissions
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_PHONE_STATE" />

Comment: I have both permission already even when for getExternalFilesDirs, no permission is required.
Comment: Since Android KitKat, calling getExternalFilesDirs() method does not require any permissions.


Finding out the events on a page and what are attached to an element

Question: I'm trying to use firebug to debug some pages. What I want to do is look at what the events are against a particular element. For example : http://jsfiddle.net/2LN5G/, I want to use Firebug and select the "Drag me to my target" and for it to take me to "$( ".drag" ).draggable({" section of the page or the JS file.
Is this possible ?
Answer: This Firefox extension that works with Firebug might be what you need: http://getfirebug.com/wiki/index.php/Firebug_Extensions#Eventbug
Comment: Hi Cody, Thanks for your response. But the EventBug takes me to the Jquery file instead of taking it to my declaraiont (i.e $("drag").draggable({..."
Answer: maybe using fireQuery would give you a more precise answer?


Why does this integral converge for all $s \in \mathbb C$?

Question: I'm trying to understand the proof of analytic continuation of the Riemann zeta function.  These notes (http://math.bu.edu/people/jsweinst/Teaching/MA843/TatesThesis.pdf) have been very helpful.  I'm right at the end of the proof.

Here $\omega(x) = \sum\limits_{n =1}^{\infty} e^{-\pi n^2x}$.  To finish, the proof, we need the fact that that last integral converges for all $s \in \mathbb{C}$, and hence $\Lambda(s) = \pi^{-\frac{s}{2}} \Gamma(\frac{s}{2})\zeta(s)$ admits an analytic continuation to the whole complex plane with poles at $s =0$ and $s = 1$.  Is it obvious that this integral always converges?
Answer: Yes it is obvious that $$F(s) = \int_1^\infty x^{s/2-1} \sum_{n=1}^\infty e^{-\pi n^2 x} dx$$ (and its derivative $F'(s) =  \int_1^\infty x^{s/2-1}\frac{\ln(x)}{2} \sum_{n=1}^\infty e^{-\pi n^2 x} dx$) converges for every $s \in \mathbb{C}$, since for $x > 1$ :
$$\sum_{n=1}^\infty e^{-\pi n^2 x} < \sum_{n=1}^\infty e^{-nx} < \sum_{n=1}^\infty e^{-(n+x)} = e^{-x}\frac{1}{e-1}$$
Hence $F(s)$ is entire, and so is $F(s)+F(1-s) = \pi^{-s/2} \Gamma(s/2)\zeta(s) - \frac{1}{s-1}+\frac{1}{s}$
For a short derivation of $\zeta$'s functional equation and analytic continuation you can look at this question.


Unable to upload image in MEAN-stack app

Question: So I have a mean stack app. At a user's profile page I want them to be able to upload an image.
Now, I start by selecting it in the template, then through the component it reaches the service file where I make a POST request with formData. In the back-end I used Multer middleware to handle the upload, but something goes wrong here. The following is my code on the back-end.
var multer  = require('multer')
var upload = multer({ dest: '../public/uploads/' });

router.post('/uploadProfilePicture/:userId', upload.single('avatar'), function(req, res){
    console.log('entered');
    console.log(req.file);
    console.log(req.body);
    res.status(200).json({
        msg: 'guuud'
    })
});

I mostly just want to check if I reach the back-end. The console gives me the following error:

POST /user/uploadProfilePicture/5aaf1b7c18f2aa3d88e3b59e 500 16.382 ms
  - 1711

There's no console log of entered and neither of the other ones. Something goes wrong between the service and the back-end, but I have absolutely no idea.
Here are the service and other files used for this upload.
Service.component.ts
postFile(fileToUpload: File, userId) {
        const formData: FormData = new FormData();
        console.log(fileToUpload);
        formData.append('fileKey', fileToUpload, fileToUpload.name);
        console.log(formData);

        return this.http.post("http://localhost:3200/user/uploadProfilePicture/" + userId, formData)
            .map(() => { return true; })
            .catch((e) => this.handleError(e));
    }

Here is the page + the results of the console.logs in the service file

profile.component.ts
handleFileInput(files: FileList){
    this.fileToUpload = files.item(0);
    this.uploadFileToActivity();
}

uploadFileToActivity() {
    this.userService.postFile(this.fileToUpload, localStorage.getItem('userId')).subscribe(data => {
        console.log(data)
    }, error => {
        console.log(error);
    });
}

profile.component.html

            Choose File
            <input type="file"
                   id="file"
                   (change)="handleFileInput($event.target.files)">

Edit: The error my server console gives me:
Error: Unexpected field
    at makeError (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\lib\make-error.js:12:13)
    at wrappedFileFilter (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\index.js:40:19)
    at Busboy.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\lib\make-middleware.js:114:7)
    at Busboy.emit (events.js:159:13)
    at Busboy.emit (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\busboy\lib\main.js:38:33)
    at PartStream.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\busboy\lib\types\multipart.js:213:13)
    at PartStream.emit (events.js:159:13)
    at HeaderParser.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\Dicer.js:51:16)
    at HeaderParser.emit (events.js:159:13)
    at HeaderParser._finish (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:68:8)
    at SBMH.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:40:12)
    at SBMH.emit (events.js:159:13)
    at SBMH._sbmh_feed (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\streamsearch\lib\sbmh.js:159:14)
    at SBMH.push (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\streamsearch\lib\sbmh.js:56:14)
    at HeaderParser.push (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:46:19)
    at Dicer._oninfo (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\Dicer.js:197:25)

Comment: The file is appended to the formData object as `fileKey`, but multer expects `avatar`. Not sure if that's what causes the 500 error though. But worth a try.
Comment: your file  may upload on server but it may not add an extension
Comment: var multer = require('multer');
var path = require('path')

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname))
  }
})

var upload = multer({ storage: storage });
Comment: you should use above snippet to upload a file
Comment: `/user/uploadProfilePicture` is the path or `/uploadProfilePicture` ?
Comment: It's /user/uploadProfilePicture. It's in a router file.
Comment: I'll try out the suggestion you just made and tell you how it goes.
Comment: I tried it, but still not working. My server console gives me an error. I'll add it to the original post.
Comment: Is it possible that I need to make adjustments to my server request in my service file?
Comment: I can't kiss you, but if I could I would. Thanks a lot Chris. I changed it to fileKey and now it works :)
Answer: I use this code for video type files and it works fine, Hope it helps you
var storage = multer.diskStorage({
    destination: function (req, file, callback) {

            var fileDest = path.join('../uploads/');
            if (!fs.existsSync(fileDest)) {
                mkdirp(fileDest, function (err) {
                    if (err) {
                        logger.error(err);
                        callback(err, false);
                    } else {
                        callback(null, '../uploads');
                    }
                });
            } else {
                callback(null, '../uploads/');
            }

    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '.' + file.originalname.split('.')[1]);
    }
});

var upload = multer({
    storage: storage,
    fileFilter: function (req, file, callback) {

        // To reject this file pass `false`, like so:
        var sw = 0;
        for (var i = 0; i < config.videoMimeTypes.length; i++) {
            if (file.mimetype === config.videoMimeTypes[i]) {
                sw = 1;
                break;
            }
        }
        if (sw === 0) {
            logger.error('Not allowed file type sent');
            // return callback(new Error('Only video files are allowed!'));
            return callback('Only video files are allowed!', false);
        }

        // To accept the file pass `true`, like so:
        callback(null, true);

    },
    limits: {
        fileSize: config.maxUploadSize
    }
});

app.post('/upload', upload.any(), router.uploader);


Read variable.def as string

Question: I am trying to read variable.def as a string.
et.def?
Type:        str
String form: total energy
Length:      12
Docstring:
str(object='') -> string

when I try to access it:
et.def
  File "<ipython-input-60-028014709411>", line 1
    et.def
     ^
SyntaxError: invalid syntax

fails because Python assumes .def as a function definition. Is there any way to get the string part?
Comment: `getattr(et, 'def')`
Comment: what is `et` referring to?
Comment: @Padraic, et is a numpy array.
Answer: The Python syntax includes several reserved words that look like identifiers but can't be used as such -- this includes def (and also class, if, and several others).
To access data (no doubt built from external sources?) that uses such identifiers as identifiers (e.g, in your case, apparently as an attribute name of whatever object et denotes), built-in functions getattr, setattr, &c, which accept the attribute name as a string (rather than as an identifier, as normal inline syntax does), come in handy (as they do whenever the attribute name is in a variable, etc).
So, in this case,
getattr(et, 'def')

should work for you in accessing that attribute's value.
Comment: @GökhanSever, yes, there are cases in which avoiding reserved words takes time, and also ones in which it's just impossible -- because of a schema defined elsewhere, including such words, which just can't be altered because other code depends on them; in such cases, these not-too-dirty "tricks" come in handy.
Comment: Thanks Dr. Martelli, this solves the problem as 61612 suggested. The other alternative solution is to fix the problem at its root, meaning recompile the model that outputs variable definitions in reserved words. But this requires about a couple of more days of re-running my simulations or altering the netcdf outputs. I am interested in making some automated plots to analyze model output so this will come handy labeling the plots.

Read variable.def as string


Continuous function for $I \equiv \left(x_0 - \frac{1}{n},x_0 +\frac{1}{n}\right)$

Question: Suppose that a function $f\colon \mathbb{R} \rightarrow \mathbb{R}$ is continuous at a point at $x_0$ and that $f\left(x_0\right)>0$. Prove that there is an interval $I \equiv \left(x_0 - \frac{1}{n},x_0 +\frac{1}{n}\right)$, where $n$ is a natural number such that $f\left(x\right)>0$ for all $x$ in $I$. $\left(Hint:\text{Argue by contradiction}.\right)$
I have done this problem on two separate occasions, and have done it incorrectly both times. Can somebody give an outline of the proof. Thanks!
Answer: Hint
If $f$ is continuous at $x_0$ and $f(x_0)>0$ then, by definition, for $\epsilon=1/2 f(x_0)$ there exists $\delta>0$ such that
$$|x-x_0|<\delta \implies |f(x)-f(x_0)|<\frac{f(x_0)}{2}.$$
Edit
Working with your definition. If $f(x)$ is not positive in the interval $ \left(x_0 - \frac{1}{n},x_0 +\frac{1}{n}\right)$ then there exists $ x_n\left(x_0 - \frac{1}{n},x_0 +\frac{1}{n}\right)$ such that $f(x_n)\le 0.$ Now, the sequence $x_n$ converges to $x_0.$ Since $f$ is continuous it is
$$0<f(x_0)=\lim_nf(x_n)\le 0,$$ since $f(x_n)\le 0,\forall n\in\mathbb{N},$ which gives you a contradiction.
Comment: When I did this the only definition of continuous that I had was if $x_n\rightarrow x_0$ then $f\left(x_n\right)\rightarrow f\left(x_0\right).$ Can you think of a way to do it with this approach?


Tomcat 7 - HTTPOnly - Bad Set-Cookie header - No '=' found for token

Question: I found an issue in a client using Tomcat 7.0.50.
It says, while consuming a java WebService from SoapUI:
<code>status HTTP 500 - javax.servlet.ServletException: java.lang.RuntimeException:
Bad Set-Cookie header: JSESSIONID=CDB8F6AAE5CF6DF2FD70359DFF4B7725; Path=/geotrib/; HttpOnly
No '=' found for token starting at position 61(-10001)
</code>
In Tomcat 6 this does not happens, because "httponly" is true by default in tomcat 7.
But how can this be? We are getting this error on the very Tomcat that writes the flag.
Any help is much appreciated.
Best regards,
    Federico.
Comment: First thing I would suggest is to use the latest Tomcat 7.  See if that helps.  After that, update your post with the full HTTP request you're sending and the response that you get.  This should help to replicate and debug this further.
Answer: The problem is your http request/response contains "HttpOnly" in its header. It appears to be that this value is not supported by application servers anymore. In order to fix this I wrote a workaround where "HttpOnly" is removed from the response on a server side.
<code>    String header = resp.getHeader("Set-Cookie");
    if (header != null && header.endsWith("HttpOnly")) {
        resp.setHeader("Set-Cookie", header.substring(0, header.length() - 8));
    }
</code>
But the best solution is to remove "HttpOnly" from the header on the http client side.


Unable to create additional database manually in 11g

Question: When I am trying to create a database in Oracle 11g manually, I'm facing below error.
<code>SQL> create database test
  2  Datafile '/opt/oradata/test/system01.dbf' size 10M
  3  Sysaux datafile '/opt/oradata/test/sysaux01.dbf' size 10M
  4  Logfile '/opt/oradata/test/redo01.log' size 10M,
  5  '/opt/oradata/test/redo02.log' size 10M
  6  Undo tablespace undotbs1
  7  Datafile '/opt/oradata/test/undo01.dbf' size 10M
  8  Default temporary tablespace temp
  9  Tempfile '/opt/oradata/test/temp01.dbf' size 10M;

Error:

SQL> /
create database test
*
ERROR at line 1:
ORA-01092: ORACLE instance terminated. Disconnection forced
ORA-01501: CREATE DATABASE failed
ORA-01519: error while processing file '?/rdbms/admin/doptim.bsq' near line 15
ORA-00604: error occurred at recursive SQL level 1
ORA-01658: unable to create INITIAL extent for segment in tablespace SYSTEM
Process ID: 4562
Session ID: 1 Serial number: 3
</code>
Kindly help.
Comment: Do you really think 10M is enough space for each of those tablespaces? How did you pick those sizes? The 'unable to create extent' message means it ran out of storage space, because SYSTEM is too small. (As are the others, that's just the first one it failed on). Maybe you'd have more luck using DBCA. [Read more](https://docs.oracle.com/cd/E11882_01/server.112/e25494/create.htm). Database creation is off-topic for this site anyway.
Answer: "ORA-01658: unable to create INITIAL extent for segment in tablespace SYSTEM"
If you look at this error it clearly says it's not able to create the initial extent since the size of the extent required is more than the file size. So, it leaves you with the two options
1) create DMT tablespace.
2) Increase the file size (100M rather than 10M).
Thank You,
Sid


how to sort text value word by word

Question: In my problem, each value of a vector is a text composed of multiple words. I try to sort word by word the text. I don't care to sort the vector.
e.g.
vect <- c("tim is a man", "sam was a studend", "my young daughter")

how to get vect arranged like this :
"a is man tim"
"a sam student was"
"daughter my young"

Thanks for your help.
Answer: We can split the string into substring and then do the sort
sapply(strsplit(vect, "\\s+"), function(x) paste(sort(x), collapse=' '))
#[1] "a is man tim"      "a sam studend was" "daughter my young"

Comment: that's perfect ! thank you very much for your very quick and true answer

how to sort text value word by word


Election participation

Question: Current election participation status is:

Election closes in 3 days.
387 voters were eligible, 186 visited the site during the election, 115 visited the election page, and 60 voted

This is about 15% participation - Should we be worried or is this normal?
Answer: Drupal Answers's election is pretty average, even on the high side for visits.

Election
Visited %
Voted %

Mathematics
Unavailable
44%

CS Theory
49%
40%

GIS
49%
38%

WordPress
42%
31%

Physics
41%
27%

TeX - LaTex
35%
23%

SharePoint
32%
22%

Stats
31%
22%

Ask Ubuntu
28%
19%

Apple
25%
16%

Gaming
22%
16%

English
23%
15%

Database Admin.
23%
15%

Photography
23%
15%

Cooking
20%
15%

Electrical Eng.
24%
14%

Game Devel.
23%
13%

Unix & Linux
21%
13%

Bicycles
21%
13%

Programmers
21%
12%

IT Security
19%
12%

Stack Overflow
32%
11%

Pro Webmasters
15%
11%

DIY
16%
9%

Server Fault
15%
8%

Stack Overflow
25%
7%

Android
11%
7%

Super User
11%
5%

Mean
27%
17%

Median
24%
15%

Mode
23%
15%

Election participation


Organising vehicle categories screen?

Question: Currently working on a taxi app and need to organise the vehicles into categories. The user will need to be able to quickly select their desired vehicle while showing passengers & luggage for each vehicle.
The categories:

Standard (Saloon, Estate, Standard MPV, Large MPV)
Premium (Multiple vehicle types)
Executive (Multiple vehicle types)

Any thoughts on how I could clearly show all the vehicles - maybe a carousel? slider?. Keep in mind that a lot of people don't know what the differences are between Saloon, Estate etc.
Comment: Drawing grey scale profile pics of each of the car types should convey enough information to allow most users to distinguish the car types. When you say Multiple Vehicle types do you mean the four types mentioned in brackets after Standard?
Comment: Why do you give the user choice over the vehicle type, rather than just have them specify the number of people that will be travelling and then determine the best car type based on that instead? That way if there is only 1 person travelling but you only have large MPV available at that time you can still allocate that car to the customer. Yes, let them choose Std, Premium and Executive but I'm not sure allowing them to pick a vehicle *type* makes the most business sense.
Answer: Since 99% of your users will simply pick their route and go, your choice for changing the vehicle should be broken out to a separate screen (perhaps using Ajax so a full refresh is not required).
Quote the price, and have 'Standard' listed with a nice visible [Upgrade] button next to it. Clicking that button takes them to a separate screen dedicated to upselling them on a fancier ride. On that screen you can have a set of cards for the different choices (silhouettes as suggested by @LisaTweedie are a good method), but rather than a scrollable list you can lay them all out since your entire interface is temporarily devoted to this choice. Extra room means fewer constraints and its much easier to make it look good and be easy to choose.
Since you were already at the quote screen, you can provide the exact price and pickup times for each choice (no guessing, no approximations) because you already have the customer's route selected.
Answer: I would look to simplicity first:
While you have many types of vehicles, your bullets indicate three distinct purchasing levels:
Standard, Premium, and Executive.
I would first offer these choices as large avenues of discourse.  Since this choice most affects price and other considerations (if I'm understanding correctly) it'll be the highest priority on the customer's mind.  After this choice, I would clear away the other two choices that weren't selected and slide in the sub choices of each.  I would continue the slider motif by presenting the smallest vehicle on the left, moving up to the largest; pictogram style.
Comment: Current Flow for booking a taxi:

1. Pick Up Address
2. Drop Off Address
3. Quote Screen (Price, Vehicle (default - Standard), Additional Comments.

Most users will not need to adjust the vehicle type but if they do want to I need to accomodate for them.

Organising vehicle categories screen?


run the join when the group by value has changed

Question: Hi I am writing the following query and the results are not what I need
Section 1

     select

          case_PrimaryCompanyId as companyid,
          CONVERT(VARCHAR(7),ca.case_createddate, 111) AS Date,
          'Moving Balance' as InvoiceType,
          sum( mb.Amount) as Amount
from  cases as ca

Section 2

left join (
select
    case_PrimaryCompanyId as companyid,
    case_createdDate,
    case_TotalExVat as Amount
from cases  ) mb

on ca. case_primaryCompanyId = mb.companyid
     and ca.case_createdDate >= mb.case_CreatedDate

where
    ca.case_primaryCompanyId = companyid

group by
     case_primaryCompanyId,
     CONVERT(VARCHAR(7),ca.case_createddate, 111)

Ok so the above will get a  list of  data as below and group it by month and year and  aggregate the amount since the  beginning of time.

Date            Actual Amount
20/10/2009      1766.52
07/11/2009      2778.02
14/01/2010     -2700.00
28/02/2010       -78.02

27/05/2010      2489.40
27/05/2010      2491.20
30/05/2010      2494.80

Everything works perfectly , calculating the cummlative value for each month.
until i get to may 2010 and then the moving balance is calculated for each record of may instead of once for may (instead of only once when the group value changes)

Moving Balance Result

Date         Displays            Should be
2009/10       1766.52             1766.52
2009/11       2788.02             2788.02
2010/01         78.02               78.02
2010/02          0.00                0.00

2010/05      22426.20             7475.50

Have Tried
sum(distinct mb.Amount) but that doesnt work
Any ideas would be  really appreciated
Thanks
Rachael
Comment: It looks like you're using SQL Server. Which version?
Answer: If you put the query that produces your result set into the with clause
;with results as
(
     select
          convert(varchar(4),YEAR(date)) + right('00'+convert(varchar(2),MONTH(date)),2) m,
          sum(amount) a
     from
          (-- your results here ) data
     group by YEAR(date), MONTH(date)
)
select
     *,
     (select SUM(a) from results r1 where r1.m<=results.m)
from results
order by m

Comment: Thanks podiluska, Going to look into this , it seems fairly straight forward, never heard of the with clause, Will let you know if it works. Thanks
Comment: Hi Podiluska  I tried that but i am getting the same results , do i need to make the group by result distinct or something ?
Comment: A `group by` result will always be `distinct`, by definition.
Comment: then i am very confused because if there are three records for the month, the sum is calculated 3 times. I dont know why this is happening, as i would have assumed that group by makes everything distinct but my results are still incorrect.
Comment: @Rachsherry I've updated the answer so that it is self contained. You should be able to run that. Where does your code differ?
Comment: Hi Podiluska, What do i put in for (-- your results here) data?
Comment: @Rachsherry Whatever query produces the first set of results, inside the brackets
Answer: Right after much frustration and a few weeks of hair pulling ,
i finally got this problem sorted,
I took out the join and just used a select statement

(
SELECT
       case_PrimaryCompanyId as companyid,
       CONVERT(VARCHAR(7),case_createddate, 111) AS Date,
       case_invoicetype as InvoiceType,
       Sum(case_totalexvat) as Amount
FROM   cases AS ca
WHERE
datediff(m,case_createddate,getDate()) = CONVERT(VARCHAR(7),b.case_createddate, 111) and b.case_primarycompanyid = a.case_primarycompanyid
)PrevSum
from  cases a
where

  CONVERT(VARCHAR(7),a.case_createddate, 111)  > Convert(VARCHAR(7), DATEADD(m, -13, current_timestamp), 111)
group by a.case_primarycompanyid, CONVERT(VARCHAR(7),a.case_createddate, 111)

)
order by Date, InvoiceType


Extract HTML with javascript

Question: Here comes a simple question, for all those who know javascript.
I made an application, which grabs the following code and puts it into a variable:

Af :Af Tho
mas Søgaard Rohde, Berlingske Nyhedsbureau&nbs
p;15. jan. 2012
               |

Danmark

Now, what I want is another variable, containing the DATE of the variable above. So it should be 15. jan. 2012.
How do I do that?
Comment: why do you need a variable that holds 16 jan instead of 15 jan from the data?
Comment: You might want to look for Regular Expressions in javascript. see [this](http://www.regular-expressions.info/javascript.html)
Comment: Thanks! How should the regex look in my situation?
Answer: Don't really understand what you mean by "puts it in a variable" other than to say the markup is a string assigned to a variable like:
var m = '
Af ' +
        ':<\/span>' +
        'Af Thomas Søgaard Rohde, Berlingske' +
        ' Nyhedsbureau ' +
        '15. jan. 2012 | <\/span>' +
        'Danmark<\/span><\/div>';

If that is the case, you can get the date (provided it is exactly in the format shown) using match with a regular expression:
var re = /\d\d?\. [a-z]{3}\. [0-9]{4}/;

alert(m.match(re)); // 15. jan. 2012

However, if you mean it is markup in a page and you are trying to get the text in the span with class section-time, then you can use something like:
// Get all elements with class section-time, use DOM method,
// querySelectorAll or some other means
var el, els = document.getElementsByClassName('section-time');

// Get the date out of each. Use a regular expression as there
// seems to be other stuff in there
var dates = [];
var re = /\d\d?\. [a-z]{3}\. [0-9]{4}/;

for (var i=0, iLen=els.length; i<iLen; i++) {
  el = els[i];
  dates.push((el.innerText || el.textContent).match[0]);
}

Or you could get all such dates in an array using match with the above regular expression on the innerHTML of a common parent element.
Answer: var date = $('.section-time').text();

Using jQuery of course.
Comment: Sorry, but the tool I am using dosen't support Jquery

Extract HTML with javascript


Modern approach to turn by turn instructions

Question: We're working on a turn by turn navigation system. Most of our users are parcel delivery drivers. They use the software 6-8 hours a day for navigation.
So the driver can easily hear 1000 times a day (not exaggerated) a sentence like 'In 100meters turn right'. I would like to have something more varied.
Should I rather keep it 'Short and sweet' like it is or maybe make it a bit more verbose like 'Turn left in 100 meters and then it's only 4 more minutes to your destination'?
Comment: As a student I worked as a parcel delivery driver. When I drove an unknown route I used the navigation too, but I turned off all sound. And often the map without any address loaded in was enough. With just the map I could see street names and know where to go. When I did enter an address, the visual cues were enough for me. Did you do any research to see if "annoying audio cues" are really considered to be a problem?
Comment: I'm not sure that we can provide the right answer for you. You have access to drivers and to the system, so why not create a ton of messages and test test test? Let us know what you find out.
Comment: We have direct contact to about 10drivers that use the app every day (and they channel the feedback of all the other drivers to us, too).
They disliked some audio cues because the text to speech quality was really bad (which is dependent on the devices manufacturer). They were immediately happier when the app said 'please'. But I don't like to say please for something so ordinary.
Answer: The title states you are looking for a Modern solution but the solution has nothing to do with being modern or not. A better question is whether the instructions are usable or not.
The bottom line is you need to ensure the user receives accurate but succinct instructions that help them get to where they need to be without distracting them from the act of driving. Adding additional verbose embellishments will become distracting. Safety first.
Comment: There is a saying that says if something isn't broken then don't fix it.

"In 200 meters turn right" is actually the best instruction for a driver because 200 meters is not very far away and the driver is now supposed to be getting ready to alter their driving in anticipation of the exit from their current road onto another road. It hasn't changed because it is the best instruction, given the circumstances.
Comment: Thanks for your answer. With 'modern' I merely meant that this 'In 200 meters turn right' hasn't changed since the 90s. A time were most software was quite formal and made sure to be technically correct and less about empathising with the user.
Answer: I agree that modern GPS systems are still a bit antiquated when it comes to the voice instructions. The voice usually sounds robotic like a text to speech program from the 1990s. There are many little things about them that make it annoying to deal with all the time.
Many of the names for cities, routes, etc. are often mispronounced. There are many bugs such as one of my GPS' says 9 grams when I am supposed to turn onto 9G. A new voice, combined with improved pronunciation would go a long way. The voice can also be abrupt as well, so having the voice start out more softly, or with another non-vocal cue would help.
Perhaps a very calm tone could alert them that there is a turn ahead so they know to look at the screen. The on-screen instructions could be improved quite a bit, and be updated in real time. The use of more colors, better animation, etc. would be a big improvement. For example, the turn arrow could gently blink as you are approaching your turn. If there are multiple turns close to one another, it should also display at least one turn ahead so the driver has enough time to react.
Another issue is that they give false information. It may say to turn, but in reality, you are staying on the same road, and there is an exit that it gets confused with. They also get very confused with tight turns and cul-de-sacs.
The routing algorithms also have issues. They tend to send you on a wild goose chase on tons of back roads, and sometimes they are unpaved just to save a tenth of a mile or so compared to just staying on the main road. They should be setup in a way that will always try to route main roads, and only go on back roads when is completely necessary. It should also keep track of the number of turns, and reject routes that have excessive turns. The GPS software which is used by some major courier companies knows to avoid certain patterns such as left hand turns because it takes longer to turn left than right. It can also be tuned to avoid traffic lights, school zones, business districts, etc. and stay on the truck route.
It is also difficult to input information into them. The driver should be able to control it all by voice commands. Lets say that they want to go on break and they are looking for a fast food place. They should be able to quickly, and easily add that destination to the route as a waypoint without disrupting the rest of the route. Lets also say that they are 5 miles away from the closest fast food place, and there are still stops along the way. Normal GPS systems will just add the new destination as the next stop. If it does that, that means you will have to backtrack. The algorithm should figure out when the best place to insert that destination. It should also handle multiple stops in the middle, such as for fuel, and food at different locations.
All of these features would be great for consumer models as well. It seems like the GPS market has stagnated quite a bit since many newer cars have them built in. Many others simply rely on their phones.
Comment: Hi, thank you a lot for sharing your insights.
"The GPS software which is used by some major courier companies knows to avoid certain patterns..." do you have more details/examples on this?
Comment: I don't know exact details since it is proprietary technology, but their software can pick the best routes based on traffic, road conditions, etc. The left turn part was done in part to save fuel because the truck has to idle while it waits for an opportunity to turn, which wastes fuel and time. The routes also are set up to service one side of the road at a time, so the courier doesn't have to cross the street. Instead it will have them drive down the road in a loop and only deliver on one side. In the US it would be the right side. In the UK it would be left. There are many others as well.
Answer: I think the sentences should be:

complete (all is necessary);
not more than sufficient;
clear.

A user don't need to hear in this case 100 times "Please", but don't replace "Turn left" with something like "do the same thing", even you think repetition is not so great.


iOS5: UITableView poor scrolling performance

Question: First of all I am getting memory leak while scrolling tableview out of bounds. The same issue as here.
Also, my scroll is fast enough but it 'kind of trembles' while I scroll it. The cells are reusable.
Code:
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    Country *country=[[self.items objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
    CountryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    cell.imageView.image=[UIImage imageNamed:country.countryFlag];
    cell.countryName.text=country.countryName;
    cell.currencyCode.text=country.code;
    cell.currencyOriginalName.text=country.originalUnitName;

    return cell;
}
</code>
App: iOS 5, ARC, Storyboard.
What can be the real reason of this tableView behavior and how to fix it ?
Comment: are the cells using custom height or some other delegate method that has known performance issues?
Comment: Is this really your code, because I can not see where you are creating CountryCell in the first place. You should be checking that cell is not nil and creating a new CountryCell if it is. You should at the very least have to create two cell before cell will no longer return nil (2 if each cell is as big as your table).
Comment: @NathanDay - with storyboards, dequeue always returns a cell, it creates it from the storyboard prototype if it is a new one.
Comment: Have you set the cell ID of your CountryCell nib to "Cell"? Have you registered the nib with registerNib:forCellReuseIdentifier:?
Comment: How big is the country.countryFlag image? Where is that image coming from?
Comment: @ Jesse Naugher No,cells are standard. @sosborn flag image is 100x100 and coming from images folder in sandbox.
Comment: CountryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; It's obvious that I am using subClass called CountryCell. Cell has standard height. Nothing extraordinary in it. This approach worked fine before.
Comment: @Nathan Day Yes. And subclass too.
Answer: If your scrolling is poor in the device, you probably haven't configured your subviews correctly in the prototype. You aren't doing anything expensive in your method above.
Use the Core Animation instrument (device only) - check your frames per second when scrolling. You want as close as 60fps as possible.
Turn on "color blended layers" - anything drawn transparent will be highlighted in red. You want to remove all transparency, if possible, from your cells, and make them all green. This may simply be a matter of setting background colours and the opaque flag correctly in your prototype subviews.
If your images are not the same size as your image view, then you will be resizing every time a cell appears, this is an expensive operation as well.
Comment: To put a finer point on it, there is no obvious reason for this to be slow. There is something else going on not related to this code.
Comment: @jrturton Ok. Can it be the reason of poor performance if every image for cell stored in sandbox is 150x100 and then it getting resized by UIImageView to 38x31 automatically? I frankly to say, don't think that the images are so large, or is it?
Comment: Resizing is expensive. You can comment out that part and see the effect. But you really should be using Instruments instead of guessing.
Comment: Ah ! Crossed comments. You ARE using instruments!
Comment: @jrturton Also, there's an issue with cell.imageView.image=[UIImage imageNamed:country.countryFlag]; line. I've got rid of imageNamed method and now using withContentOfFile: method. Of cause you know the difference, it HAS IMPROVED my performance. Also, I have resized the images and finally got ≈60 fps. Well, now there's another issue: why goddamit my images are so unsharp on Retina screen, but that's another question. Will google for it. Thank you for your answer and teaching me how to check scroll performance in Instruments. That was new for me.


Why is shuffle write huge compared to shuffle read?

Question: Lets say I have a task that joins two dataframes or rdds
<code>dfA: col1, col2
dfB: col1, col3

dfA.join(dfB, dfA.col1=dfB.col1)
</code>
Looking at the executor summary, my max task has 1gb shuffle read and 40gb shuffle write.
There is no imbalance issue, among all the tasks the shuffle reads are similar (900mb - 1gb). I used a salted key technique to make sure the keys are spread out uniformly.
So why the 40x difference on the max task? (col1, col2, col3) is not 40x the input. So where is all that extra data going?
Answer: I figured it out. Its because of the groupBy step I have right after this.
The imbalance is with the groupBy key.


Fixing an inwall toilet constantly flowing

Question: I have a Schwab inwall toilet. Water keeps flowing heavily after flushing.
I took everything out of the wall and found that the reason is because the ?hammer doesn't come back up again, therefore the ?float never thinks that it is full.
The reason it doesn't come up is because the plastic is 'squeaking' where the red circle is in my image.

What I really want to know is whether I have to replace that bit or if there is a way I can loosen it a bit. And if I do have to replace, then which part and what is it called.
Thank you!
Answer: Apparently that joint is wearing out. You may have to replace the whole assembly. The wonders of modern plastic.
As a stop-gap I would try greasing it (not oiling it). With silicone grease. Petroleum products and plastic don't play well together.
Comment: Thank you. Used petroleum jelly and that seemed to do the trick. Also detached the blue from the white hammer, and the extra few millimeters may have meant that it didn't have to be pushed up anymore. All is good.


Trouble installing Matlab 2014b on Ubuntu 14.04

Question: I'm aware of this article: https://help.ubuntu.com/community/MATLAB and have followed the instructions, which didn't help me. EDIT: Only because I'm stupid, the article is great.
I mounted my matlab 2014b-iso (it's named "R2014b_glnxa64.iso", so I'm very much assuming it's the 64-bit version) and ls -l is telling me
total 6334
-r--r--r-- 1 root root    3371 Mär 21  2011 activate.ini
dr-xr-xr-x 7 root root    2048 Sep 16 17:18 archives
dr-xr-xr-x 3 root root    2048 Sep 16 17:15 bin
dr-xr-xr-x 3 root root    2048 Sep 16 17:15 etc
dr-xr-xr-x 5 root root    2048 Sep 16 17:16 help
-r-xr-xr-x 1 root root   10518 Aug  5 02:11 install
-r--r--r-- 1 root root    9365 Jul 26 09:07 installer_input.txt
-r--r--r-- 1 root root 6340999 Sep 12 16:15 install_guide.pdf
dr-xr-xr-x 4 root root    2048 Sep 16 17:15 java
-r--r--r-- 1 root root   82776 Sep 12 15:23 license.txt
-r--r--r-- 1 root root    8300 Sep  8 23:00 patents.txt
-r--r--r-- 1 root root   15779 Sep  8 23:12 readme.txt
dr-xr-xr-x 3 root root    2048 Sep 16 17:15 sys
-r--r--r-- 1 root root     245 Dez 28  2013 trademarks.txt
-r--r--r-- 1 root root      32 Sep 16 17:31 version.txt

so I should have all permissions I need.
However, executing sudo ./install results in
./install: 1: eval: /media/iso/bin/glnx86/install_unix: not found

which is right, since the path is /media/iso/bin/glnxa64/install_unix.
Out of curiosity I tried sudo ./bin/glnxa64/install_unix and got
Error: Cannot locate Java Runtime Environment (JRE).
The directory /media/iso/sys/java/jre/glnx86/jre does not exist.

How can I install matlab!?
Answer: Having looked up the line of code in the install script where glnx86 appears, I got confused first. But now I realized I installed Ubuntu 14.04 32 bit.. Of course, trying to install Matlab 64 bit fails.
Gotta reinstall Ubuntu..
Answer: I encountered an almost identical message
./install: … /bin/unknown/install_unix: command not found

while attempting to install Matlab R2017a on 32-bit Ubuntu 16.04.  For anyone not wanting to install a new operating system, Matlab R2012a supports 32-bit Linux.  I needed to keep my current operating system, and I was able to successfully install R2012a on my machine.


How to change game language?

Question: I'm using the system console with language set to spanish (NTSC) but I like to change the game language to english, is this possible?
Comment: I don't know about SSB specifically, but usually Wii & Wii U games simply follow the system settings.
Comment: Hmmm... I would gladly get rid of that Spanish narrator too :P
Answer: As the SSB Wiki states:

The NTSC version can be set to English, French or Spanish. As with Brawl, the language is dependent on the console's set language and cannot be changed in-game.

How to change game language?


Wordcloud with wordcloud2.js

Question: I need to create a word cloud for my site! I found a javascript tool named wordcloud2.js that performs what I want but...
I found out that the .js doesn't display all the words I pass to the script in the array arr6.
Does anyone know how to fix this problem? I've created (and passed to the script) an array of 20 elements(word + size) but only the first six are visualized.
I don't know why...thanks in advance!
<code>    var arr6=[
         ["Pear", "9"],
         ["Grape", "9"],
         ["Pine", "4"],
         ["Banana", "6"],
         ["Lemon", "9"],
         ["Parigi", "5"],
         ["Apple", "5"]
         ["Mear", "4"],
         ["Torino", "4"],
         ["Mescola", "8"],
         ["Gigi", "6"],
         ["Roma", "9"],
         ["Empoli", "5"],
         ["Mela", "5"]
         ["Alessandro", "9"],
         ["Imola", "4"],
         ["Hp", "4"],
         ["Harry", "6"],
         ["Potter", "9"],
         ["Amsterdam", "5"],
         ["Como", "5"]
        ];
    var options =
    {

    list : arr6,
    gridSize: Math.round(2 *     document.getElementById('canvas_cloud').offsetWidth / 1024),
    weightFactor: function (size) {
    return Math.pow(size, 2) *  document.getElementById('canvas_cloud').offsetWidth / 1024;
    }
  }

    WordCloud(document.getElementById('canvas_cloud'), options);
</code>
Answer: You're missing some commas in your list array. It should be
<code>    var arr6=[
     ["Pear", "9"],
     ["Grape", "9"],
     ["Pine", "4"],
     ["Banana", "6"],
     ["Lemon", "9"],
     ["Parigi", "5"],
     ["Apple", "5"],
     ["Mear", "4"],
     ["Torino", "4"],
     ["Mescola", "8"],
     ["Gigi", "6"],
     ["Roma", "9"],
     ["Empoli", "5"],
     ["Mela", "5"],
     ["Alessandro", "9"],
     ["Imola", "4"],
     ["Hp", "4"],
     ["Harry", "6"],
     ["Potter", "9"],
     ["Amsterdam", "5"],
     ["Como", "5"]
    ];
</code>
Note the comma after the entry for Apple and the entry for Mela.
Answer: WordCloud2.js api [https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md] also has a setting to not draw certain words below a set size. I can't remember if it has a default of 2 or not...
but the "minFontSize" may be set somewhere if you copied the settings from someone else.
but i'm pretty sure @Kaelin has the right idea that your array is just formatted incorrectly and getting truncated.

Wordcloud with wordcloud2.js


ping pong between same framebuffer two color attachments

Question: In order to optimize I'm trying to set up a setup which ping pong between same framebuffer two color attachments to apply some postprocess effects. It seems to work (effects are applied) but concurently I'm getting a lot of strange artifacts like:

blinking squares
borders on depth discontinuities
color spilling on screen (window resize removes it)

Which change or disappear partly when I for example remove one step (one post process effect) from "ping ponging".
If I do this ordinary way using different framebuffers seems to remove them but I'm not 100% sure if it is not a mess in the shaders or something but they seem fine.
In each frame I'm doing ping pong like that:
First step - render to current color attach using other fb texture
fbDeferredLighting->bindFramebuffer(); //fb which has two color attachments
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
effect1->setConstPerFrameUniforms();
//get 0 attachment from fb scene prepass to apply effect and draw on fbDeferredLighting current color attach
effect1->setTextureUniforms(fbScene, 0);
quad->draw();

And then repeating some number of times: swap step and drawing, using same fb swapped attachment:
fbDeferredLighting->bindFramebuffer();
//after swap - now current=1, other=0 or current=0, other=1
std::swap(colorAttachment0Current, colorAttachment0Other);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texturesDiffuse[colorAttachment0Current]->getTextureID(), 0);
glClear(GL_DEPTH_BUFFER_BIT); //only clear depth
effectX->setConstPerFrameUniforms();
//get other color attach and use it to apply effect on current
effectX->setTextureUniforms(fbDeferredLighting , colorAttachment0Other);
quad->draw();

Is this correct?
EDIT:
I wonder, maybe rewrite it to compute shaders, that would simplify things.
Answer: Actually, GL_COLOR_BUFFER_BIT also need to be cleared
After creation of the framebuffer, draw buffer need to be set to:
glDrawBuffer(GL_COLOR_ATTACHMENT0);

and then after each swap:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

instead of only
glClear(GL_DEPTH_BUFFER_BIT);

To clear current attachment 0.
I don't really understand these clearing bits extensively but this seems to fix blinking "chess board" artifact.
Borders seems to be connected with motion blur shader.


Change Kotlin Javascript output directory

Question: I have just started using Kotlin to produce Javascript, but cannot find a way to change the Javascript output directory.
This is specifically for a nodejs target, and using Gradle with Kotlin script.
There is an example given in the Kotlin docs for a browser target:
kotlin.target.browser {
    distribution {
        directory = File("$projectDir/output/")
    }
}

but there does not seem to be an equivalent for kotlin.target.nodejs
Answer: This is now easy (Kotlin 1.40):
https://kotlinlang.org/docs/reference/js-project-setup.html#distribution-target-directory
kotlin {
    js {
        browser {
            distribution {
                directory = File("$projectDir/output/")
            }
        }
        binaries.executable()
        // . . .
    }
}

Comment: This doesn't actually answer the question btw, it was asking about NodeJS exclusively. Anyway, here is my working solution for _my_ issue, based off this answer - https://gitlab.com/-/snippets/2019246. Thanks so much!
Comment: Incredible! I give up and drink coffee, come back 1 hour later and google it again, and here you are! Absolute godsend. I've been scratching my eyes out for a good 4 hours now, and it's a 3-liner.
Comment: whoops.. I was searching for the browser solution myself and this came up as the first result. Didn't read carefully enough. Your snippet looks like it's also browser unless I'm missing something.
Comment: Yep, my snippet also doesn't answer the question :P. It just solves the same problem you had, from what I can see.
Answer: Unfortunately, there are no possibilities to do this with NodeJS. I created an issue - https://youtrack.jetbrains.com/issue/KT-40416.
Comment: Thank you, I'll monitor that


Fancybox won't open from google maps v3 market infowindow

Question: map is now on the link: http://joostudio.info/test/
As you can see, from bottom image fancybox works just fine but when I call it from map infowindow it jus doesn't work.
Here is complete page source code
<!DOCTYPE HTML>

<meta charset=utf-8>
<title>test</title>

<link rel="stylesheet" href="fancybox/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />

How can I simply call fancybox from google maps v3 marker?
Thanks a lot
Answer: The problem is your have given your FancyBox link in your infowindow a class instead of an id
infowindow.setContent('
')

yet you are calling it via an id

The reason the bottom image works is you are using an id there

Answer: look for link below:
Google map + fancybox
http://www.daimlerstr.de/berge/tests/fancyboxtest.html


Wrong window focus behaviour in Unity, but not GNOME Shell

Question: I just upgraded from 11.04 to 11.10, and I'm noticing a strange window behaviour that I can't seem to fix. Basically it seems like all windows have focus, as shown in this screenshot:

It happens almost all the time, but sometimes windows appear as out of focus, and when they are clicked, they stay like that. I tried using GNOME Shell and the problem doesn't exist, so it seems it has something to do with Unity.
Let me know if you need any more info to help me solve this problem. Thanks!
Comment: Is this a common bug? It is extremely annoying, but I see a very little number of complaints. Does it reveal in only some configurations?
Answer: Update:
According to Launchpad bug #770283, this is now fixed in Ubuntu 12.04 with the latest updates.  I've not personally tested it, as I'm now using the open-source drivers, but from what I've read, it fixes the problem.
Original answer:
Sadly, there doesn't seem to be a fix yet.  There is a bug report for Compiz (the window manager running Unity), but no developers have responded.  See Launchpad Bug #856138
I suggest logging in or registering on Launchpad and marking the bug as "Affects me too" (you can also do it by clicking this link)
Do you have an ATI graphics card?  My laptop with an ATI Mobility Radeon HD 4500 Series graphics card has this same issue on 11.10 and 11.04.  However, my NVidia desktop did not experience this glitch, so I'm thinking ATI's driver may be part of the problem.
Comment: Cool, I didn't know you could link to whether or not a bug affects you. Very useful!
Comment: Yes I have a Lenovo T500 with an ATI Mobility Radeon HD 3650. I didn't have this problem in 11.04, and I just installed 11.10 on my desktop (NVidia) and the behaviour isn't happening, so you may be right.
Answer: Seems to be a driver problem (fglrx). A temporary solution might be revert back to the radeon driver.  I was able to solve it that way.
Answer: I have same problems with fglrx and 11.10, and solved enabling again the unity switcher functionality (in compiz>unity). I disabled unity switcher to use classic compiz switcher and it started to fail.
Comment: I've had the Unity switcher enabled all this time, and the window decorations (titlebar, close/minimize/maximize, etc) still freeze up.  Are there any other changes you made?  What graphics card do you have?
Answer: This may be a conflict between Compiz' Viewport Switcher and Unity's default switcher... I disabled the Viewport Switcher in CompizConfig and the problem was resolved.
Comment: I tried disabling the Compiz Viewport Switcher, and still have the same problem.  What graphics card is in your computer?  (I'm curious if it depends upon the graphics card as to what breaks and what works...)


Get calling class name from abstract class in C#

Question: I recently started learning C#, I'm programming in various languages like PHP, JavaScript, Go, Rust, Elixir, a bit of Java and Python.
I always was fascinated by C# and I decided now to give it a go.
So far so good, my process of learning a new language is by trying to replicate a variety of things from other languages, especially from PHP where I'm most strong.
TLTR:
How I could implement this in C#?
<?php
declare(strict_types=1);

abstract class Foo
{
    public static function className(): string
    {
        return static::class;
    }
}

final class Bar extends Foo
{
}

echo Bar::className() . PHP_EOL;

The code above returns "Bar" instead of "Foo" because we are calling the name of the static, where static is the class that we are calling the className method from.
In C# I managed to do that:
using System;
using System.Reflection;

namespace LearningConsole
{
    abstract class Foo
    {
        public static string ClassName()
        {
            return MethodBase.GetCurrentMethod().DeclaringType.Name;
        }
    }

    class Bar : Foo
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Bar.ClassName());
        }
    }
}

But this returns the "Foo" class name instead of "Bar", is there a way to get the name of the class that invoking the ClassName method?
Thank you in advance!
EDIT:
The reason I'm using a static method is that I'm trying to accomplish something similar in C# like this in PHP:
<?php
declare(strict_types=1);

interface Dummy {}

abstract class Base implements Dummy
{
    public static function create(...$args): Dummy
    {
        $callingClass = static::class;
        return new $callingClass(...$args);
    }
}

final class Bar extends Base
{
    protected function __construct() {}
}

final class Foo extends Base
{
    protected function __construct() {}
}

$foo = Foo::create();
$bar = Bar::create();
echo get_class($foo) . PHP_EOL.
     get_class($bar) . PHP_EOL;

The above will output:
Foo
Bar
Maybe in C# that kind of "magic" is considered bad practice, but it could be handy for various occasions.
Thanks!
EDIT 2:
That C# is not working (obviously), but it is my understanding of what could be a good compromise for achieving somehow the above example:
using System;
using System.Reflection;

namespace LearningConsole
{
    interface Dummy
    {
    }

    abstract class Base : Dummy
    {
        public static Dummy Create(Dummy obj, params dynamic[] args)
        {
            var constructor = typeof(obj).GetConstructor();
            constructor.invoke(null, args);
        }
    }

    class Foo : Base
    {
    }

    class Bar : Base
    {
    }

    class Program
    {
        static void Main(string[] args)
        {
            var foo = Base.Create(Foo, null);
            var bar = Base.Create(Bar, null);
        }
    }
}

Thanks!
Comment: The static ClassName is Foo.ClassName, and can never be Bar.ClassName. Even Intellisense in Visual studio says it's Foo.ClassName. This is because static mehods  don't require an instance of the class, and really for statics they just form a part of the name, just like a namespace. To do what you want, you have to implement static ClassName in each class in the hierarchy, but add the new keyword to stop the compiler from complaining, i.e. "public static new string ClassName()"
Comment: Does it need to be a static method?
Comment: You should use `typeof(Bar).Name` instead if you don't hold an instance of that type.
Answer: You can achieve what you are looking for with a little help from generics.  Here is an example
class Program
{
    static void Main(string[] args)
    {
        var foo = Base.Create<Foo>();
        var bar = Base.Create<Bar>();
        Console.WriteLine(foo.GetType().Name);
        Console.WriteLine(bar.GetType().Name);
        Console.ReadKey();
    }
}

public abstract class Base
{
    public static T Create<T>(params object[] args) where T : Base
    {
        return (T)Activator.CreateInstance(typeof(T), args);
    }
}

public class Bar : Base
{

}

public class Foo : Base
{

}

Comment: The (T) before is a type cast.  If you call Activator.CreateInstance(type, args) it returns an object. The (T) casts the object to a type of T. e.g. whatever is passed into the generic as the type.
Comment: I updated my example to add support for passing arguments to the constructor
Comment: wow thanks! I was just about to ask you! Could you explain me (or just give me a link so I can read), previously you had "return Activator.CreateInstance();" Which is ok, I can read that, but this: "return (T)Activator.CreateInstance(typeof(T), args);" is kind of magic, I mean the (T) stuff, so you remove the generic  after the CreateInstance and  you add (T) tuple before Activator
Comment: ah lol, I didn't think about it, it is the same way like PHP typecasting (and other languages as well, I thought it has something to do with tuples but it was simpler than that! Thank you! Until a few minutes ago I thought that this wasn't possible in C#, having a base class is a good compromise! Now if I may ask another question, is it possible to make Create method of Base abstract class not inheritable so Foo and Bar will not be able to use Create method?
Comment: As far as I know there is no way to restrict inheritance of static members in C#. That being said, calling Base.Create() will give you the same thing as calling Foo.Create().  Tools will usually let you know it can be simplified to calling Base
Comment: But isn't it possible to check the calling method, and in the case is not Base class to throw an exception?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/199583/discussion-between-bhmahler-and-panosru).
Comment: That looks cool! (I wish since a long time ago that PHP had generics...) That is basically what I tried to do with Edit 2 of my post, I will try it now! Thanks!
Answer: Thi code does not translate well to C#. You might want to consume it like this
  Console.WriteLine(typeof(Bar).Name);

Having classname as a property is perfectly fine for a non static method/property. If you need the type of a static class you can always go with the example I gave or have that property be non static and in a instanced object
   class Program
    {
        static void Main(string[] args)
        {
            Bar b = new Bar();
            Console.WriteLine(b.ClassName());

        }
    }

    abstract class Foo
    {
        public string ClassName()
        {
            return GetType().Name;
        }
    }

    class Bar : Foo
    {

    }

In the end, even if there's a way to do what you want, you should ask why and I personally think you should do it the C# way. also remembert Type is an object in C# with lots of cools things in it.
if you have an instance you can do
instance.GetType()

if you just have a type you can do
typeof(Bar)

Comment: Thank you for your detailed reply! I have updated my original question to illustrate better what I want to accomplish, but from what I read online I don't think that there is a possible way to do that kind of "magic" in C# even though that C#'s OOP is much more superior than PHP's OOP. I'm working on an alternative way to get a similar effect in C# I will post it in Edit 2 if I manage to make it work as intended.
Answer: In this way you will print: Foo Bar
class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo();
        var bar = new Bar();
        Console.Write(foo.ClassName());
        Console.Write(bar.ClassName());
        Console.ReadKey();
    }
}

class Foo
{
    public string ClassName()
    {
        return GetType().Name;
    }
}

class Bar : Foo
{

}

Answer: The reason for this is Static methods do not work on the instance of the class, they are directly associated with the class itself in your case it id Foo. Here you can access the ClassName method from derived class Bar, but it associated with Foo.
So if you write a static method in the class and compile it, and when you try to view the IL, it will be same as any other class accessing the static member.


Is it true that $\lim_{n\to\infty}E[X_n] = 0$ if $X_n\to 0$ in probability?

Question: Is there any counter example that:
Let $X_1, X_2,\dots$ be a sequence of random variables that converge to $0$ in probability. That is, for any $c > 0$
$$\lim_{n\to\infty} P(|X_n - 0| > c) = 0$$
Then $\lim_{n\to\infty}E[X_n] = 0$ ?
Comment: If your sequence of random variables converges in probability AND is uniformly integrable, then you can conclude convergence of expectation.
Answer: Take $X_n:=n\chi_{(0,n^{—1})}$.
Answer: This is not even true if you assume all the expectations exist!  There need to be some uniform boundedness also.


MVC5 ModelClientValidationRegexRule always failing

Question: In my custom validation attribute I Have the following:
yield return new ModelClientValidationRegexRule(_invalidCharactersErrorMessage, "/^[A-Za-z0-9\\s]+$/i");

It is suppose to accept only letters, numbers and spaces.  Now on the HTML side of things, here is what gets generated:
<input data-val="true" data-val-regex="Only letters, numbers, and spaces are allowed" data-val-regex-pattern="/^[A-Za-z0-9\s]+$/i" data-val-required="Alias is required" id="Alias" name="Alias" placeholder="Alias" type="text" value="" >

When I type in the field, it always gets activated and I see the error message no matter what I type in.  Is my regex wrong or is there something else at play here?  From what I've read online, my regex seems to be correct
Comment: Note that you do not need `/i` at all since you already defined `A-Za-z`. Try passing a simple string pattern `"^[A-Za-z0-9\\s]+$"`.
Answer: Acc. to this resource, the value you pass inside data-val-regex-pattern is a string pattern, not a regex object, and it is already anchored.
So, since you already added lowercase ASCII letters to your character class, you can just use
yield return new ModelClientValidationRegexRule(_invalidCharactersErrorMessage, "[A-Za-z0-9\\s]+");

or (since doubling ^ and $ does no harm), you may also try "^[A-Za-z0-9\\s]+$"
Comment: I tested it and you are correct, I didn't pass the ^ nor the $ and it works.  Thank you!


Powers of matrices with constant diagonals

Question: Consider a square matrix where each ``diagonal'' is  constant, for example
$A= \left( \matrix {
a & b & c & d \cr
e & a & b & c \cr
f & e & a & b \cr
g & f & e & a \cr
}\right)$. Is there a shortcut for finding $A^n$?
Edit
Sufficient Conditions for a power of Toeplitz matrix being Toeplitz
Comment: Jordanize it?${}$
Comment: @GitGud I want it symbolically, that is $a,b,c,\cdots$ are not numbers. And The eigenvalues of the symbolic matrix are not simple expressions.
Answer: These are called Toeplitz matrices.  Powers of Toeplitz matrices are not Toeplitz in general. Suppose your matrix is $m \times m$ with
entries $a_{ij} = f(i-j)$.  The $(i,j)$ element of $A^n$ is the sum of products
$\prod_{k=1}^{n} f(d_k)$ over all $(d_1, \ldots, d_n) \in \{-m+1, \ldots, m-1\}$ such that $\sum_{k=1}^n d_k = j - i$ and all partial sums $1-i \le \sum_{k=1}^r d_k \le m-i$ for $1 \le r < n$.


Why are the limits of the histogram data autodetected as [nan, nan] instead of discarding NaNs?

Question: The following code generates an error
print(g['resp'])
par = {'hist': True, 'kde': False, 'fit': scipy.stats.norm, 'bins': 'auto'}
sns.distplot(g['resp'], color='blue', **par)

31     23.0
32     28.0
33     29.0
34     31.0
35     32.0
36     35.0
37     35.0
38     36.0
39     37.0
40     38.0
41     38.0
42     38.0
43     41.0
44     42.0
45     42.0
46     42.0
47     42.0
48     46.0
49     48.0
50     49.0
51     50.0
52     52.0
53     55.0
54     56.0
55     60.0
56     60.0
57    100.0
58      NaN
59      NaN
60      NaN
61      NaN
Name: resp, dtype: float64
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-42944bf1e405> in <module>
      1 print(g['resp'])
      2 par = {'hist': True, 'kde': False, 'fit': scipy.stats.norm, 'bins': 'auto'}
----> 3 sns.distplot(g['resp'], color='blue', **par)

C:\ProgramData\Anaconda3\lib\site-packages\seaborn\distributions.py in distplot(a, bins, hist, kde, rug, fit, hist_kws, kde_kws, rug_kws, fit_kws, color, vertical, norm_hist, axlabel, label, ax)
    223         hist_color = hist_kws.pop("color", color)
    224         ax.hist(a, bins, orientation=orientation,
--> 225                 color=hist_color, **hist_kws)
    226         if hist_color != color:
    227             hist_kws["color"] = hist_color

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1808                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1809                         RuntimeWarning, stacklevel=2)
-> 1810             return func(ax, *args, **kwargs)
   1811
   1812         inner.__doc__ = _add_data_doc(inner.__doc__,

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in hist(self, x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, normed, **kwargs)
   6589             # this will automatically overwrite bins,
   6590             # so that each histogram uses the same bins
-> 6591             m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
   6592             m = m.astype(float)  # causes problems later if it's an int
   6593             if mlast is None:

C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\histograms.py in histogram(a, bins, range, normed, weights, density)
    708     a, weights = _ravel_and_check_weights(a, weights)
    709
--> 710     bin_edges, uniform_bins = _get_bin_edges(a, bins, range, weights)
    711
    712     # Histogram is an integer or a float array depending on the weights.

C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\histograms.py in _get_bin_edges(a, bins, range, weights)
    331                             "bins is not supported for weighted data")
    332
--> 333         first_edge, last_edge = _get_outer_edges(a, range)
    334
    335         # truncate the range if needed

C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\histograms.py in _get_outer_edges(a, range)
    259         if not (np.isfinite(first_edge) and np.isfinite(last_edge)):
    260             raise ValueError(
--> 261                 "autodetected range of [{}, {}] is not finite".format(first_edge, last_edge))
    262
    263     # expand empty range to avoid divide by zero

ValueError: autodetected range of [nan, nan] is not finite

It looks like the NaN values are causing trouble - how to discard them?
Answer: I think not, so possible solution is Series.dropna for remove missing values:
sns.distplot(g['resp'].dropna(), color='blue', **par)


Does the mining barge expert package allow alpha clones to fly these ships?

Question: Mining barges are locked ships for alpha clones. Not allowed to undock even if the required skills were learned during some earlier subscribed period of time.
With a purchase from the new expert system, though, an alpha clone may temporarily unlock access to mining barge required skills. Are alpha clones then able to undock a mining barge during the duration of their purchase?
Answer: The answer is yes. In this screenshot, the Mining Barge Operations Expert System has a ship unlock tooltip that confirms alpha clones can undock with the ship.


Create a class based on a variable

Question: I have a base class Accounts, that handles all of the information and methods of basic account functions.  Then I have subclasses of Checkings and Savings to handle specific functions for the different classes.  I have an action listener that will add the account,
<code>    addBtn.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            // add the account
            //this is where I am stuck!
            Account account = new Savings(amount);

        }

    });
</code>
and based on a variable in a JComboBox I want to be able to differentiate what kind of class is created.
<code>    //get the types of accounts
    ArrayList<String> accountTypes = Account.getAccountTypes();
    JComboBox box = new JComboBox(accountTypes.toArray());
    contentPanel.add(box);
</code>
What can I do to better handle this?
Comment: Use [Factory method](http://en.wikipedia.org/wiki/Factory_method_pattern)
Comment: Use a simple `if` statement? If combobox value is this then create a new Savings object, else if combobox valus is that create a new Checking object.
Comment: Jesper, I am working on designing my software a little better, I know that a simple switch or if statement will work here, but I want to get in the habit of making it more maintainable.
Comment: the getAccountTypes actually accesses the enum. There is also an account for Cash, and I would like to eventually further add accounts as I build the app, so that is why I wanted to further avoid the if/else structure. Also i'm just not sure how to instantiating a new class without having to do an if/else structure. I'm going to see what I can do with the Factory Pattern though. Thanks Luiggi.
Answer: If you need this only in action listener just put there simple if/else or switch/case. If there is a chance that somewhere else you will need to create objects in similar way read about design patterns like Factory Method.

Create a class based on a variable