Prove that the vectors $v_1,v_2,\ldots,v_k \operatorname{span}R^n$ if and only if $[v_1]_B,[v_2]_B,\ldots,[v_k]_B \operatorname{span}R^n$.

Question: From section on Change of Basis

$\longrightarrow$ Assume the vectors $v_1,v_2,\ldots,v_k\operatorname{span}R^n$, we must show that $[v_1]_B,[v_2]_B,\ldots,[v_k]_B\operatorname{span}R^n$.  We can write the vectors in $R^n$ as linear combinations of the coordinate vectors $[v_1]_B,[v_2]_B,\ldots,[v_k]_B$.
This is as far as I can get.  I have trouble proving things, I don't know how to.  I can't seem to prove any of the exercises I am faced with.  Are there any strategies to learn proofs?
Comment: Assume they do not form a basis (ie there is a null linear combination), then prove that B is not a basis.
Answer: First you need to make sure you are clear on definitions.

"The vectors ${\bf v}_1,{\bf v}_2,\ldots,{\bf v}_k$ span ${\Bbb R}^n$" means: for every vector ${\bf w}$ in ${\Bbb R}^n$ there exist scalars $\lambda_1,\lambda_2,\ldots,\lambda_k$ such that
  $$\lambda_1{\bf v}_1+\lambda_2{\bf v}_2+\cdots+\lambda_k{\bf v}_k={\bf w}\ .$$

The coordinate vector of ${\bf v}$ in ${\Bbb R}^n$ with respect to the ordered basis $B=\{{\bf b}_1,{\bf b}_2,\ldots,{\bf b}_n\}$ for ${\Bbb R}^n$ is the vector
  $[{\bf v}]_B=(x_1,x_2,\ldots,x_n)$ such that
  $${\bf v}=x_1{\bf b}_1+x_2{\bf b}_2+\cdots+x_n{\bf b}_n\ .$$

Next you will need a result about the connections between coordinate vectors.
Lemma.  If $B$ is an ordered basis for ${\Bbb R}^n$ and ${\bf v}_1,{\bf v}_2$ are vectors in ${\Bbb R}^n$ and $\lambda_1,\lambda_2$ are scalars, then
$$[\lambda_1{\bf v}_1+\lambda_2{\bf v}_2]_B
  =\lambda_1[{\bf v}_1]_B+\lambda_2[{\bf v}_2]_B\ .$$
Proof.  Write $[{\bf v}_1]_B=(x_1,\ldots,x_n)$ and $[{\bf v}_2]_B=(y_1,\ldots,y_n)$.  By definition this means that
$${\bf v}_1=x_1{\bf b}_1+\cdots+x_n{\bf b}_n\quad\hbox{and}\quad
  {\bf v}_2=y_1{\bf b}_1+\cdots+y_n{\bf b}_n\ .$$
Therefore
$$\lambda_1{\bf v}_1+\lambda_2{\bf v}_2
  =(\lambda_1x_1+\lambda_2y_1){\bf b}_1+\cdots
    +(\lambda_1x_n+\lambda_2y_n){\bf b}_n$$
and so
$$\eqalign{[\lambda_1{\bf v}_1+\lambda_2{\bf v}_2]_B
  &=(\lambda_1x_1+\lambda_2y_1,\ldots,\lambda_1x_n+\lambda_2y_n)\cr
  &=\lambda_1(x_1,\ldots,x_n)+\lambda_2(y_1,\ldots,y_n)\cr
  &=\lambda_1[{\bf v}_1]_B+\lambda_2[{\bf v}_2]_B\cr}$$
which proves the result claimed.  An almost identical proof shows that the same relationship holds for any linear combination of $k$ vectors.
Now we can begin the proof that you need.  Note that it is an "if and only if" statement, so there are two things to prove.
First suppose that
$$[{\bf v}_1]_B,\ldots,[{\bf v}_k]_B\quad\hbox{span}\quad {\Bbb R}^n\ .
  \tag{$*$}$$
We have to prove that ${\bf v}_1,\ldots,{\bf v}_k$ span ${\Bbb R}^n$.  So, let ${\bf w}$ be in ${\Bbb R}^n$; then $[{\bf w}]_B$ is also in ${\Bbb R}^n$.  From $(*)$, there exist scalars $\lambda_1,\ldots,\lambda_k$ such that
$$[{\bf w}]_B=\lambda_1[{\bf v}_1]_B+\cdots+\lambda_k[{\bf v}_k]_B\ .$$
By the lemma we have
$$[{\bf w}]_B=[\lambda_1{\bf v}_1+\cdots+\lambda_k{\bf v}_k]_B$$
and so
$${\bf w}=\lambda_1{\bf v}_1+\cdots+\lambda_k{\bf v}_k\ .$$
We have shown that any ${\bf w}$ in ${\Bbb R}^n$ can be written as a linear combination of ${\bf v}_1,\ldots,{\bf v}_k$, and so by definition, these vectors span ${\Bbb R}^n$.
Secondly, suppose that
$${\bf v}_1,\ldots,{\bf v}_k\quad\hbox{span}\quad {\Bbb R}^n\ ;\tag{$*{*}$}$$
we have to prove that $[{\bf v}_1]_B,\ldots,[{\bf v}_k]_B$ span ${\Bbb R}^n$.  So, let ${\bf x}=(x_1,\ldots,x_n)$ be in ${\Bbb R}^n$ and write
$${\bf w}=x_1{\bf b}_1+\cdots+x_n{\bf b}_n\ .$$
By assumption $(*{*})$, there exist scalars $\lambda_1,\ldots,\lambda_k$ such that
$${\bf w}=\lambda_1{\bf v}_1+\cdots+\lambda_k{\bf v}_k\ .$$
Putting all these facts together, using the lemma and the definitions, we have
$$\eqalign{{\bf x}
  &=[{\bf w}]_B\cr
  &=[\lambda_1{\bf v}_1+\cdots+\lambda_k{\bf v}_k]_B\cr
  &=\lambda_1[{\bf v}_1]_B+\cdots+\lambda_k[{\bf v}_k]_B\ .\cr}$$
We have shown that any ${\bf x}$ in ${\Bbb R}^n$ can be written as a linear combination of $[{\bf v}_1]_B,\ldots,[{\bf v}_k]_B$, and so by definition, these vectors span ${\Bbb R}^n$.  This completes the proof.
Answer: Assuming that $\left[ \vec{x} \right]_B$ is the coordinate vector with respect to $\vec{x}$, here is a small hint. The map $\left[ \cdot \right]_B$ is linear, i.e., for $\alpha \in \mathbb{R}$ and $\vec{v} , \vec{w} \in \mathbb{R}^n$
$$ \left[ \alpha \vec{v} + \vec{w} \right]_B = \alpha \left[ \vec{v} \right]_B + \left[ \vec{w} \right]_B $$
This should get you somewhere, if not, just comment and I can keep leading you in the right direction. The above equation is sometimes called the Linearity of Coordinates.
I might also help to know that $\left[ \cdot \right]_B$ is a one-to-one map.
Here is a edit to finish why the above works.
Let us assume the set of vectors $ \{ \vec{v}_i \} $ span $\mathbb{R}^n$. Then for a vector $\vec{t} \in \mathbb{R}^n$, we have
$$ t = c_1 \vec{v}_1 + c_2 \vec{v}_2 + \cdots + c_n \vec{v}_n \; \; \; \; \; c_i \in \mathbb{R} $$
Then,
$$ \left[ \vec{t} \right]_B = \left[ c_1 \vec{v}_1 + c_2 \vec{v}_2 + \cdots + c_n \vec{v}_n \right]_B $$
$$ = c_1 \left[ \vec{v}_1 \right]_B + c_2 \left[ \vec{v}_2 \right]_B + \cdots + c_n \left[ \vec{v}_n \right]_B $$
where the equality comes from the linearity of coordinates. We see that for any arbitrary vector $\vec{t} \in \mathbb{R}^n$, $\left[ \vec{t} \right]_B$ can be written as a linear combination of the vectors $ \{ \left[ \vec{v}_i  \right]_B \}$ Thus, these span $\mathbb{R}^n$.
One can go further to proof that if $\{ \vec{v}_i \}$ are a basis, then so are $\{ \left[ \vec{v}_i \right]_B \}$.
Comment: This does not help.  A little too technical
Answer: More generally, let $E$ be a vector space of dimension $n$ over the scalar field $F$, and let $(e_1, ..., e_n)$ be the canonic basis of $E$.
By definition, the vectors $(a_1, .., a_k)$ are called linearly independent if
$$
\forall (\lambda_1, .., \lambda_k)\in F^k,\quad \sum_i \lambda_i a_i = 0 \implies \lambda_i = 0\ \forall i \tag{1}
$$
Now let's assume that $(v_1,...,v_n)$ and $(b_1, ..., b_n)$ are both basis of $E$ (ie the subspace they generate is $E$, ie they "span" $E$). Each $v_k$ can be decomposed on the canonic basis $(e_1,..,e_n)$, meaning that it can be expressed as a linear combination of these vectors.
Now, if $(b_1,..., b_n)$ is a basis of $E$, then each $v_k$ can also be expressed as a linear combination of these vectors. This is what you wrote "$[v_k]_B$":
$$
\forall k,\quad \exists (\mu_{k,1}, ..., \mu_{k,n})\neq (0,...,0)\in F^n\ \big/\ v_k = [v_k]_B = \sum_i \mu_{k,i} b_i \tag{2}
$$

The proof then proceeds by showing that the family $([v_1]_B,...,[v_n]_B)$ is linearly independent, and since it is maximal (ie contains $n$ vectors in a vector space of dimension $n$) it forms a basis. To do that, let's assume that they are not linearly independent. Then by $(1)$, we could find $(\lambda_1, ..., \lambda_n)\neq(0,...,0)$ such that
$$
\sum_k\lambda_k [v_k]_B = 0 = \sum_k\lambda_k \sum_i \mu_{k,i} b_i = \sum_i \left( \sum_k \lambda_k\mu_{k,i} \right) b_i
$$
which would mean that we found a null linear combination of $b_i$s, proving that they are not linearly independent, which contradicts our assumptions.
The reverse is exactly the same since we can swap $(b_1,...,b_n)$ with $(e_1,...,e_n)$.
Comment: I'm sorry, I do not understand this proof.  I do not know what the variables you have are supposed to represent.
Comment: Clearer now? This is basic linear algebra.
Answer: So this might be a more appropriate solution given what you've learned, if you're doing a usual intro linear algebra course:
We know that a collection of vectors $\mathbf{v}_1,\mathbf{v}_2,...,\mathbf{v}_k$ span $\mathbb{R}^n$ if and only if the matrix $V = [\mathbf{v}_1 \; \mathbf{v}_2 \; ... \;\mathbf{v}_k]$ is onto, which means every equation of the form $V\mathbf{x} = \mathbf{b}$, where $\mathbf{b} \in \mathbb{R}^n$, has some solution $\mathbf{x}$ in $\mathbb{R}^m$.
Now, what about the vectors $[\mathbf{v}_1]_{B},[\mathbf{v}_2]_{B},...,[\mathbf{v}_k]_{B}$? We know that we can obtain a vector in $B$ coordinates by multiplying by a certain matrix, namely $[\mathbf{v}_i]_{B} = P_{B}^{-1}\mathbf{v}_i$, where $P_{B}$ denotes the matrix whose columns are the basis vectors in $B$. ($P_{B}$ is the 'change-of-coordinates' matrix).
It follows that the matrix $\tilde{V} = [[\mathbf{v}_1]_{B} \; [\mathbf{v}_2]_{B} \; ... \;[\mathbf{v}_k]_{B} ]$ is given by the equation $\tilde{V} = P_{B}^{-1}V$. You now need to show that $\tilde{V}$ is onto, so pick $\mathbf{b} \in \mathbb{R}^n$. We want to solve the equation:
\begin{align}& \tilde{V}\mathbf{x} = \mathbf{b} \\
\Leftrightarrow & P_{B}^{-1}V\mathbf{x} = \mathbf{b} \\
\Leftrightarrow & V\mathbf{x} = P_{B}\mathbf{b} \end{align}
We know that the last equation has a solution since $V$ is onto, which completes the proof.
Comment: I think using inverse matrices is a joke. If you're using the inverse matrix $P_B^{-1}$ it means you already know what an isomorphism is. If you already defined what an isomorphism is, then there is nothing to prove at all since the rank of $V$ is the rank of $\tilde{V}$. Logically speaking, you're using concepts that cannot be defined without the property that you're trying to prove, in order to prove this property. This is tautological. The question is basic, you have to use basic tools only.
Comment: I'm not sure I understand your comment- You're saying my argument is "Change of basis is an isomorphism" followed by "Isomorphisms preserve the rank of vectors", but then you claim that I can't define 'isomorphism' without the property that I'm trying to prove? I'm not sure I agree with that. An invertible matrix can be defined completely algebraically. It's not my favorite definition, but it's usually the first one students see.
Comment: Well I might be wrong, but before writing $P_B^{-1}$ as if it obviously made sense, I'd like to see how you could prove it exists without using a reasoning that could also prove that a change of basis preserves the rank (which is my understanding of the original question)?


Finding the probability of a Type II error or the power, as specified

Question:
For the given significance test, determine the probability of a Type
  II error or the power, as specified.
Suppose we wish to test $H_{0}: p = 0.5$ against $H_{1}: p < 0.4$ using $α = 0.05$.
  If $p$ is actually equal to $0.4$, what is the probability of a type II
  error assuming $n = 150$?

How do i find the probability of a Type II error?
I've only managed to find the z-score to be -2.45, and its corresponding p-value to be 0.0071. Thanks.
Comment: Please double-check the question you quote. Is the alternative supposed to be $p< 0.40$ rather than $p<40$?
Comment: @Glen_b I was given exactly $H_{1}: p < 40$, but i wouldn't rule out a typo in the question, and it actually does make sense. Are you able to derive the answer from these information?
Comment: If it is really 40 (meaning that $p$ is not a proportion as it appears to be), we'd need to to know more about the circumstances (what's the model here?). If it's $0.4$ and $p$ is a proportion then yes, it's a reasonably straightforward binomial calculation.
Answer: In order to calculate the power of an alternative hypothesis, one should first formulate it as a simple hypothesis: For example, $H_1:p<40$ is a complex hypothesis as it refers to multiple possible values of $p$. A simple hypothesis would be something like $H_1:p=39.9$.
The process of calculating the power (for simple hypotheses) is as follows:

Identifying the discussed probability (preferably normal or approximated to normal)
Building the Likelihood Ratio Test
Extracting the test statistic $T(x)$ from the LRT
Formulating the test shape, something like $\delta(x):T(x)>c$ or $\delta(x):T(x)<c$
Solving the equation $P_{H_0}(\delta(x))=\alpha$ in order to find the critical value $c_\alpha$, which will make the equation $P_{H_0}(T(x)\leq c_\alpha)=1-\alpha$ hold (this is just an example for the case of $\delta(x):T(x)>c$).
Finding the power by solving the equation $\pi=1-\beta=P_{H_1}(T(x)>c_\alpha)$

Please note that $P_{H_0}$ refers to the distribution under the null assumption whereas $P_{H_1}$ refers to the distribution under the specified alternative.
Comment: i haven't reach that high of a level, and I believe my question requires simple calculation. Is there a more direct way to find the probability of the type II error?
Comment: A type II error (true negative) requires specifying a simple alternative and of course knowing the underlying distribution.
Comment: ah i see, thanks. From the method given above, is it possible to derive the value from only the information I gave in the question? (because that's what i'm given)
Comment: If we assume the question discusses binomial distribution and (as noted before) $H_1:p<0.4$ (which makes more sense) then the answer is yes, using the normal approximation.
Comment: i've did some research and they requires the standard error to find the test II error. Mind sharing how you would approach this question?
Comment: Use the normal approximation to binomial, which sets $\mu=n\cdot p, \sigma^2=np(1-p)$. See more [here](https://onlinecourses.science.psu.edu/stat414/node/179)


Rerouting requests from site.org/old to site.org/new in nginx

Question: I have a site deployed at www.site.org. I have routes at www.site.org/old/article and I want to automatically redirect people to www.site.org/new/article. Ideally this would work as a wildcard to capture anything and not just article.
I'm not great at Nginx so any advice would be useful on best practices. I have seen a few people do it with location blocks with a mixture of return 301 woven in as well as straight up rewrites.
Answer: Assuming you want an HTTP 301 permanent redirect rather than serving the old URL like it is a new one, use
rewrite ^/old(/.*) /new$1 permanent;

If I am wrong and you want to serve both /old/article and /new/article the same way without a redirection, use the same rewrite rule without the permanent flag (should be placed at the server context, not the location one!):
rewrite ^/old(/.*) /new$1;


Function keys get stuck (stay pressed)

Question: I made Ctrl + Shift + X start a function using AutoIt, but using this the Ctrl and Shift keys get stuck held down. Inserting {CTRL up} and {SHIFT up} has no effect. Why does this happen?
My AutoIt script :
$dll = DllOpen("C:\Windows\System32\user32.dll")
Global Const $keys[8] = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0x5b, 0x5c]
;0xa0   LSHIFT
;0xa1   RSHIFT
;0xa2   LCTRL
;0xa3   RCTRL
;0xa4   LALT
;0xa5   RALT
;0x5b   LWIN
;0x5c   RWIN

HotKeySet("{PAUSE}", "stop")
HotKeySet("^X", test)
Opt("SendKeyDelay", 0)
Opt("SendKeyDownDelay", 0)

While True
    Sleep(500)
WEnd

Func test()
    Send("The control and shift keys are going to be stuck down at the end of this.")
    Send("{ENTER}")
    Send("{ENTER}")
    Send("PlaceHolder,")
    Send("{ENTER}")
    Send("PlaceHolder")
    Send("{TAB}")
    Send("{HOME}")
    Send("{LCTRL up}")
    Send("{RCTRL up}")
    Send("{LSHIFT up}")
    Send("{RSHIFT up}")

    Call("UnstickKeys")
EndFunc

Func UnstickKeys()
    For $vkvalue In $keys
        DllCall($dll, "int", "keybd_event", "int", $vkvalue, "int", 0, "long", 2, "long", 0) ;Release each key
    Next
EndFunc

Func stop()
    Exit
EndFunc   ;==>stop the script

Comment: @Stavm Controlled endless loops are great things...how else would I keep my script alive?

I've always used an endless loop with AutoIT to keep the script running, otherwise it runs once. This endless loop stops as soon as I hit the pause/break key.
Comment: not sure about Autoit, but from what i know it acts like VBA\VB6 , this means

While True
    Sleep(200)
WEnd

is your potential problem. endless loops are never a good thing. specially ones that hold the thread.
Answer: I modified your test function below. This solution has a problem because to run the function again you will need to let go of shift and ctrl and repress them. You can remove the dll call from your code. I also disabled the ^X hotkey while the function is being called. It's just safer that way.
Func test()
  Hotkeyset("^X")
  Send("The control and shift keys are going to be stuck down at the end of this.")
  Send("{ENTER}")
  Send("{ENTER}")
  Send("PlaceHolder,")
  Send("{ENTER}")
  Send("PlaceHolder")
  Send("{TAB}")
  Send("{HOME}")

  send("{CTRLDOWN}")
  send("{CTRLUP}")
  send("{SHIFTDOWN}")
  send("{SHIFTUP}")
  Hotkeyset("^X", "test")
EndFunc

Function keys get stuck (stay pressed)


Xcode 7 'CrashReporter does not contain bitcode' linker error

Question: I am directly linking PLCrashReporter in my iOS app without using any external tool and now when I try to compile it on Xcode 7 I get link error:

ld:
  '.../CrashReporter.framework/CrashReporter(libCrashReporter-iphoneos.a-armv7-master.o)'
  does not contain bitcode. You must rebuild it with bitcode enabled
  (Xcode setting ENABLE_BITCODE), obtain an updated library from the
  vendor, or disable bitcode for this target. for architecture armv7

Where do I get the updated framework or the sources to compile them with bitcode enabled and get rid of the error without disabling bitcode for the full project?
Comment: Did you try disabling bitcode on the project?
Comment: I prefer not as they are a new asset to improve the experience for the users, yet I found the sources and recompiling them.
Comment: Most of libraries are not updated with bitcode which are coming form Xcode 7. so for now to remove this waring we need to disable it from setting. Find solution form here http://stackoverflow.com/a/32710815/3647325
Comment: It may be so, but how do I update the PLCrashReporter framework to use bit code without having to disable it everywhere, or get an already compiled framework so configured? As said, trying to compile the source on XCode 7 is a nightmare.
Comment: No one want disable to use bitcode, Everyone want to do things better, but until PLCrashReporter doesn't update their framework to make compatible  with bitcode,  you have to disable it.
Comment: That is what I did in fact, but I already miss the possibility of checking the crashes of the app; this of course until such a service is directly offered by Apple.
Comment: For checking crashes of app with exact line responsible for crash, you can also use Crash Reports tool offered by Apple starting from Xcode 6 and thats really great.
Answer: I ended up addressing this by building PLCrashReporter 1.2.1 from source.  This version is the minimum that has had Xcode 7 and iOS9 fixes merged.
The source is obtained from here: PLCrashReporter 1.2.1
Unzip the downloaded 1.2.1 source into a folder.
Pull the Xcode project inside that folder up within Xcode and add the following to the Custom Compiler Settings "Other C Flags" section of the project build settings: -fembed-bitcode
Next add the following to the Custom Compiler Settings "Other Warning Flags" section of the project build settings: -Wno-error=unused-command-line-argument
Then close the project from the Xcode GUI.   The custom settings are necessary because we are going to build from the command line using xcodebuild to avoid the PLCR deprecation errors, and when doing so the default is only -fembed-bitcode-marker when building a framework this way.  We are overriding the default behavior, and need to suppress the hard stop warning this causes.
Lastly, from a terminal window prompt within the folder where the zip file of the source including the xcode project file is located run the following:
xcodebuild -configuration Release -target 'Disk Image'
This will run the build and leave the framework in ./build/Release/PLCrashReporter-1.2.1/iOS Framework
Now, these steps will produce a bitcode enabled framework, but third party crash reporting is incompatible with bitcode (when the App Store recompiles you have no way to get the symbol file from that on the fly build).
Comment: @SyedAbsar disabling bitcode is/was necessary because the symbolication in any such third party crash reporter library depends on synergy with the dSYM at local build time.  With bitcode enabled you have a remote rebuild time dynamic added.  You may be able to download the appropriate dSYM in this situation, and if so you can leave it enabled.  But if not, you have to disable to symbolicate any reports.
Comment: I executed this suggestion and in fact a framework was produced and I could then import in my project. Yet when I try to archive I get: ld: file is universal (5 slices) but does not contain a(n) armv7k slice: /Users/fbartolom/Documents/cocoa applications/inArrivoHD/CrashReporter.framework/CrashReporter file '/Users/fbartolom/Documents/cocoa applications/inArrivoHD/CrashReporter.framework/CrashReporter' for architecture armv7k
As for the third party tools I use QuincyKit that is compiled with my app and so it should also be bitcode enabled.
Comment: Yet, after adding this option on Xcode and repeating the procedure, it compiles and archives fine. Now I am trying to submit the app to th store and I hope to have the same luck.
Comment: When you submit to App Store be sure to uncheck the "Include bitcode" box at the bottom when using this framework.
Comment: As amato of fact I followed drshock's suggestion and managed to have both my app and PLCrashReporter with Bit Code enabled - I prefer to follow Apple's suggestions as soon as possible. I am now trying to submit the binary still getting Cannot Verify client error 3000.
Comment: @Fabrizio Bartolomucci, I would suggest validating the ipa from Xcode Organizer, then exporting the binary from Xcode (again with bitcode unchecked) for app store type, and instead submitting the ipa binary using Application Loader [link] https://itunesconnect.apple.com/apploader/ApplicationLoader_3.0.dmg
Comment: The issue was due to the fact I missed the update to Xcode 6.1 and so I could not install on my IOS 9.1 device an so I copied the relative platform from the beta version. This action in some way made iTunes connect assume Xcode itself was a beta version. Anyway now I delete the full installation and reinstalled Xcode for the AppleStore and that specific error had been overcome, unfortunately been overcome by an even more cryptic one: "An error occurred uploading to the iTunes Store"
Comment: Hi again, as you may see at: http://stackoverflow.com/questions/33476627/missing-required-architecture-x86-64-in-libmumblekit-a-3-slices I have a similar problem with another library I was not able to fix by your suggestions alone. Could you please gently help? Perhaps the issue may be solved by turning MumbleKit in a framework, bu I have no idea about how to do it.
Comment: @drshock i'm trying to understand, why to uncheck the include bitcode?
Comment: Works! Hang up problem under iOS 9 on iPad Air 2 went away :-)
Answer: There is 2 options.
1. Download PLCrashReporter sources and compile it whit bitcode enabled, and use that in your project.
2. Disable bitcode for your target
Go to your target's Build Settings tab, search for Enable Bitcode set value to NO.
Comment: To the reverse, I enabled bitcode for PLCrashReporter by taking advantage of the answer below.
Answer: This worked for me, in order to include Rollbar framework in my project:
Within my workspace, I first select my project from the Project Navigator -> my project's target -> Build Settings -> Enable Bitcode = NO

Then I select the PODS from the Project Navigator -> Rollbar Target -> Enable Bitcode = NO
Answer: Experienced same issue. I built the crash reporter framework from source using
https://www.plcrashreporter.org/code

Open it in Xcode
Select the 'CrashReporter' target with the red bullseye.
Build it

Then search in ~/Library/Developer/Xcode/DerivedData/CrashReporter-xxxxxxx to get the .framework bundle
Comment: Yes, in fact by doing in this way it compiles without errors. Now I am trying with bitcode enabled.
Comment: Unfortunately when I tried submitting my app the same problem surfaced again. When I now try to compile it again I now get:
ld: warning: object file (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_macosx.a(cf.o)) was built for newer OSX version (10.6) than being linked (10.5)
ld: warning: object file (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_macosx.a(arclite.o)) was built for newer OSX version (10.6) than being linked (10.5)
Answer: Unfortunately the issue presented itself again. Also when I try to compile again I get:

ld: warning: object file
  (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_macosx.a(cf.o))
  was built for newer OSX version (10.6) than being linked (10.5) ld:
  warning: object file
  (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_macosx.a(arclite.o))
  was built for newer OSX version (10.6) than being linked (10.5)

Moreover if I set enable bit code at the project level I get an immediate error:
target 'CrashReporter-MacOSX-Static' has bitcode enabled (ENABLE_BITCODE = YES), but it is not supported for the 'macosx' platform
What should I do to produce the framework with bitcode enabled?


IV-RE xtoverid testing both IV validity and RE vs FE?

Question: I am running an xtivreg, re and an xtoverid afterwards.
My understanding of the help file and what I found online is that xtoverid basically compares IV-RE with FE (augmented RE).
The test statistic I get is tiny and therefore p-value massive (0.8 to 0.9).
My plan was to first test for endogeneity and then afterwards test either the RE-IV or RE versus the respective FE or FE-IV. However, the test seems to combine this into one. So does that imply that both the instruments are valid as well as that RE preferable to FE? I find that hard to believe because the FE results differ massively.
Comment: well, there is the first formatting error. First line of what I wrote is missing. "Hi, thanks for taking the time and" sorry
Comment: might also be relevant to know that if I do not use instruments, the hausman test clear prefers the FE model
Answer: The command xtoverid is a test of overidentifying restrictions. When you apply this after xtivreg this is a test for whether your instruments are valid. It does not at the same time whether you should use fixed or random effects but you can use this test also for this purpose but separately. This is because testing fixed versus random effects is similar to testing orthogonality conditions as in the instrumental variables case.
For your problem what you optimally would do is:

compare fixed and random effects using the Hausman test
for this example say you choose fixed effects; if you are in doubt about endogeneity you can again use the Hausman test to compare fixed effects versus fixed effects with instrumental variables (the instrumental variables regression is consistent whether or not you have an endogeneity problem whilst the usual fixed effects regression is only consistent under exogeneity); use xtoverid afterwards to check whether your instruments are valid
if they are valid you are done; if they are not valid you need to find a better instrument and then compare fixed effects versus fixed effects with the new instrument. Perhaps you were just rejecting normal fixed effects in step 2 because your first instrument was bad

Here is some code for you to try out:
webuse nlswork
tsset idcode year

// the standard Hausman test (assumes homoscedasticity of the residuals)
xtreg ln_wage tenure age, fe
est store fe

xtreg ln_wage tenure age, re
est store re

hausman fe re, sigmaless

// the test rejects the null that differences in FE and RE are not systematic, so you should use FE

// the xtoverid command is also a Hausman test which you can use without assuming homoscedasticity, e.g. if you want to correct for autocorrelation by clustering on the id variable
xtreg ln_wage tenure age, re cluster(idcode)
xtoverid

// now run the IV fixed effects regression
xtivreg ln_wage age (tenure = south union), fe i(idcode)

// check whether the instruments are valid according to the test
xtoverid

// compare the results with fixed effects; Hausman rejects that the difference between IV fixed effects and fixed effects is not systematic so it's better to use IV (assuming that your instruments are valid)
est store ivfe
hausman ivfe fe

Comment: thanks a lot for that great answer, I will work through that!
Comment: If this was helpful to you, you may consider to accept this answer for your question. You can do so by ticking the check mark underneath the voting buttons :) If you have any further questions about this please feel free to ask.
Comment: I worked through your example and then tried it on my own data. When I do the FE-IV I get the error message: equation exactly identified. Well, I have two instruments as in your example so I should not get that message. Any idea what is going on? I tried it with and without controls same story.
Comment: nevermind, obviously it does not work. One of my instruments is at the higher level and therefore drops out.
Comment: @Andy Could you please let me know who to deal with autocorrelation and heteroskedasticity issues while there is a large N, small T panel data? Really, I used xtreg with vce (robust) option but again I checked for autocorrelation. There is still problematic.Thanks


How to create Zip in Yii2

Question: I have tried to create zip file using PHP ZipArchive in Yii2. But it show me error in my code .. I couldn't found my error ...
public actionZip(){
          $zip = new ZipArchive();
          print_r($zip);
          exit;
          $zip->close();
      }

Answer: Thanks Stack overflow but i found the answer of this question
public actionZip(){
                  $zip = new \ZipArchive();
                  print_r($zip);
                  exit;
                  $zip->close();
                   }

How to create Zip in Yii2


How to display images in WebBrowser control?

Question: After doing
<code>HtmlElementCollection es = webBrowser1.Document.GetElementsByTagName("input");
HtmlElement ele = es[5];
ele.InvokeMember("Click");
....
</code>
after click webrowser1 do not display google verification image, but after webbrowser1 refresh (F5) display
how to solve this problem?
Answer: in VS2010 webbrowser works correctly


knockoutjs data saving UI issue

Question: In my web app while I am updating some data I need to show some loading spinning gif in the web page.
This is my code.
This is my html code

<button data-bind="click: createNew">Save</button>

In my knockoutjs model I have this
self.isWaiting = ko.observable(false);

self.createNew = function () {
            this.isWaiting(true);
                        $.getJSON("/Admin/Material/GetFolders", function (allData) {
                            this.isWaiting(true);
                            var mappedFolders = $.map(allData, function (item) { return new Folder(item); });
                            self.folders(mappedFolders);
                            this.isWaiting(false);
                        }).success(function () { this.isWaiting(false); }).error(function () { }).complete(function () { this.isWaiting(false); }); ;
        };

I have property called isWaiting. Before I call the server I am setting it to true. In completion and successive method I am setting it back to false.
So based on that my spinning wheel should appear and disappear.
But this is not working.
Thanks In Advance
Answer: this will have another context inside the createNew and callback functions. You should use self instead of this for accessing view model's property:
self.createNew = function () {
    self.isWaiting(true);
    $.getJSON("/Admin/Material/GetFolders", function (allData) {
        self.isWaiting(true);
        var mappedFolders = $.map(allData, function (item) { return new Folder(item); });
        self.folders(mappedFolders);
        self.isWaiting(false);
    }).success(function () {
        self.isWaiting(false);
    }).error(function () {})
    .complete(function () {
        self.isWaiting(false);
    });
};

knockoutjs data saving UI issue


Criar acesso FTP para um diretório virtual na Azure

Question: Tenho um Aplicativo Web na Azure e criei uma pasta interna como diretório virtual para que um desenvolvedor terceirizado implante um sistema contratado.
Estou com grande dificuldade em criar um FTP que tenha acesso somente ao diretório /comercial dentro da hospedagem.
Alguém sabe como criar essas credenciais ?
Answer: A Azure não implementa o protocolo FTP nos seus websites. A ferramenta é outra. Chama-se WebMatrix.
Você pode baixá-la aqui.

EDIT
Acho que esta resposta defasou. Agora existe uma maneira de publicar via FTP também, mas não recomendo para o ASP.NET MVC porque boa parte das configurações automáticas são feitas pelo Web Deploy.
Comment: Cigano, Azure WebApp implementam SIM FTP em seus websites. As publicações podem ser feitas via FTP, WebDeploy ou Implementação Contínua a partir do VSTS, GitHub, DropBox, OneDrive, etc. Aqui tem um exemplo de [Publicação no Azure via FTP](https://azure.microsoft.com/pt-br/documentation/articles/web-sites-php-mysql-deploy-use-ftp/)
Comment: @ThiagoLunardi Obrigado pelo link. Atualizei a resposta.
Comment: Legal, Cigano, tirei o downvote. Porém, as configurações automática também funcionam quando se faz deploy via FTP. O Visual Studio primeiro faz o build em release, aplica todas as configurações de pré compilação e transformação de *.configs, cria um pacote publicável e sobe esse pacote via FTP. O processo realmente é PIOR - não me agrada -, mas o produto final que é entregado é exatamente o mesmo do WebDeploy.
Comment: @ThiagoLunardi Quase. O cabeçalho de migração automática do Entity Framework é colocado pela interface do Publish. Dá pra colocar manual também. Eu não queria ir muito a fundo nesta resposta porque sai muito do propósito da pergunta. Apenas comentei por causa da tag, que está como ASP.NET MVC.
Answer: Daniel,
O serviço de Azure WebApp fornece sim suporte à publicação via FTP, porém ele te dá acesso à toda a área de publicação e não tem suporte para especificar acesso à um pasta específica.
O que é recomendado fazer neste seu cenário é criar dois serviços de WebApp:

SuaAppPrincipal.azurewebsites.net
SuaSolucaoTerceirizada.azurewebsites.net

E então você organiza seus endereços com subdomínios.

www.dominioprincipal.com.br
solucaoterceirizada.dominioprincipal.com.br

Agora, para atender algo do tipo dominioprincipal.com.br/solucaoterceirizada, apenas se a terceirizada te enviar os fontes, vocês podem fazer o merge das duas aplicações e subir em uma única hospedagem.
Porém, por ser terceirizada, eu prefiro o primeiro cenário, assim a solução terceirizada - que, teoricamente, você não tem controle como a forma que foi desenvolvida - irá rodar sob um host independente da principal. Assim, se ela tiver algum problema e cair, não irá derrubar junto a app principal. E vice-versa.
Comment: Concordo com sua solução inclusive pratico ela em outros casos, mas especificamente neste precisava ser publicado em /solucaoterceirizada.
A solução foi criar um processo em minha aplicação onde ele pode realizar o upload diretamente para dentro da pasta, mesmo com os riscos.
Answer: Enfim, a Azure não permite criar um usuário para uma subpasta.
Foi necessário criar um recurso em minha aplicação em que a pessoa pudesse fazer o upload do projeto em .zip e o processo descompactava dentro da pasta.
Problema resolvido.


Is this the oldest top ten in history?

Question: So we're all surprised that we haven't had a young teenager shake the game for a while now but only one person under 25 in the top ten! The combined age of the top ten is 289 with an average of 29!
My question is if this is the oldest top ten of the ATP ranking in history, both in terms of the average and combined age.
Comment: Just to save other people doing the work, could you clarify whether this is male or female?
Comment: @PhilipKendall Male.
Answer: According to the blog Where is the next generation in men's tennis? (Wayback Machine) written by John Burn-Murdoch (FT Data) in November 2015:

The average age of the ATP top 10 is 29.7 — the highest it has ever been — with an unprecedented five of its current members aged over 30.

Here is a graph provided in the blog showing average age of Top 10 since 2000:

Although they do not provide the data used for that stat, I am inclined to believe the claims from that article. So it really seems that we are close to the historical peek.

My personal guess is that the average age might have dropped recently, after David Ferrer (34) got out of Top 10. And then it dropped again a bit after relatively young Dominic Thiem (22) entered Top 10, following French Open - where he reached his first Grand Slam semifinals.
The last ranking in which David Ferrer was in Top 10 is from May 5 2016. If the calculations here are correct, the average age in top 10 from that date was 30.15.
Comment: Very strong and interesting reply
Comment: Next year, the average age will be 30 and both Novak and Murray entering 30 !
Answer: This article articulates your point and provides some of the data you might be looking for with both the male (ATP) and female (WTA) tours.
As of now (July 2016) there is only one teenager ranked inside the top 50 in the world on the ATP World Tour - Alexander Zverev at a ranking of 28. Dominic Thiem is also currently a notable youngster since he is ranked #8 at the age of 22. Both Zverev and Thiem have jumped to their current career-high rankings recently though, so they are not likely to factor into many "average age" calculations done on the age of top 10 or top 50 players unless those calculations were performed on recent rankings data.
As an avid fan and follower of the sport of Tennis, I can say that the trend of the top players being older in age does not surprise me that much given the relatively recent advances in many areas of the sport in regards to fitness, strategy, strings and global competition. These are all things that get tweaked and refined to perfection over years of trial and error. Not to mention players adjusting to the demands the sport puts on them by the media, long schedule and travelling all over the world.
Fitness
Given the ridiculously long schedule Tennis players endure, today's top players are training year-round. They've also put in the time to know exactly how much to train without over-training and have developed highly specific training routines that science has shown to benefit the skills in demand for tennis players like optimal breathing patterns (no joke), balance, hand-eye coordination, core strength & stability, etc. Today's top players are also making use of recovery techniques that weren't known of or available to top players in the past such as ice baths, oxygen rich recovery chambers, Kinesio tape and more.
Strategy
Younger players don't have the benefit of a sort of wisdom that older players have obtained from having already played on the tour for years. The more matches and different opponents you have under your belt, the more you know about an opponent's tendencies (and weaknesses). The more veteran players are also more likely to have a coach helping them scout opponents. Tennis is also a sport where knowing yourself well is a benefit to the mental aspect the sport brings with it. Knowing your own tendencies and bad habits are key in helping you avoid mistakes. In pro tennis the margins between victory and defeat are commonly so thin that the player usually making fewer mistakes determines the winner and loser.
Strings
Luxilon and polyester strings have changed the way players can hit the ball - especially on the service return - without worrying as much about the ball going out. These strings didn't hit the market until the late 90's - right when players like Federer and Roddick started their professional careers.
Global Competition
Tennis has players hailing from many more countries now than it used to. Back in the 80's and 90's, tennis players from Serbia hardly existed, let alone atop the rankings. Now you have the top player in the world being Serbian as well as multiple players in the top 100 from smaller European countries like Serbia, Portugal, Czech Republic and Croatia, as well as Asian countries like Japan and China starting to produce top players (e.g Kei Nishikori). Although I don't have any hard evidence backing up my opinion on this - I think this makes it tougher for young pros to reach the top of the rankings as they have more travelling and conditions to acclimate to on their ascent to the top. Big tournaments in cities like Shanghai, Beijing, and Tokyo are also now a thing that didn't exist in pro tennis a couple of decades ago.
Comment: Great essay. Read it twice-and-a-half. Found nothing that actually puts a yes or no to the question asked. Even the article linked only gives three data for each of men's and women's top ten's average age, and still doesn't outright say that's the highest ever.
Comment: When will someone younger win a Major or even a Master ? Of course, the likes of Nishikori and Raonic are no longer young. So, now I'm forced to use the word younger to describe them. When will someone below the generation of Federer-Rafa-Djokovic-Stan-Tsonga-Murray etc. win a slam or consistent Majors ? Will Raonic win Wimbeldon ?
Comment: @user230452 - it's all just speculation of course, but I don't really see many potential major champions in the younger group right now. Raonic could win a major if he plays great and gets some breaks as far as his draw goes. The best of the younger group so far appears to be Dominic Thiem, but I think he still has a couple of years to go at least until he's contending for a major or even making the finals of one. To be honest, I'd rather see some more veteran players win a major that, in my opinion, are deserving of one such as Berdych, Ferrer, and Tsonga - maybe even Gasquet.
Comment: Of those named, only Tsonga has the ability to win a slam but not consistently. All three have been in Major finals. But, Gasquet to my knowledge hasn't. Gasquet and Nadal were at a comparable level when they were teenagers. I don't know how he got left so far behind. The lack of young talent is alarming. I don't see anybody stopping Djokovic from completing 300 weeks at #1 although I am worried about his health after the way he lost to Querry.
Comment: @Nij It's ok. He tried his best. No need to downvote :)
Comment: @Nij - perhaps you would like to provide a concrete answer with data backing it up then?

Is this the oldest top ten in history?


Commerce: adding +/- buttons to the Quantity field

Question: I am working on a site that uses the Commerce module for a web store. The design specifies that the user's cart overview page should allow them to increase and decrease the quantity of a particular item using plus/minus buttons. However, as far as I can see the only option for a quantity field is a bare text field (in commerce/config/line-items/product/fields). I've searched for solutions online, but apart from the Commerce Extra module (which is in alpha, and does not allow for vertically-stacked buttons as per the design) I'm coming up blank.
Is there an 'accepted' way to add these buttons to the quantity field, or am I missing something in my configuration?
Comment: To be honest, that image just looks like a styled select box to me. Have you got confirmation that it needs to be a +/- box?
Comment: Unfortunately, yes; I checked with the designer. They thought it was trivial to do.
Answer: Commerce Kickstart has that.
We use the jquery_ui_spinner library, extracted in our libraries folder.
We declare the library in a hook_library implementation:
<code>/**
 * Implements hook_library().
 */
function commerce_kickstart_product_ui_library() {
  $libraries['jquery_ui_spinner'] = array(
    'title' => 'jQuery Spinner',
    'website' => 'http://github.com/btburnett3/jquery.ui.spinner/',
    'version' => '1.8',
    'js' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.min.js' => array(),
    ),
    'css' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.css' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget'),
    ),
  );
  return $libraries;
}
</code>
Then in our hook form alter we attach the library:
<code>function commerce_kickstart_product_ui_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['#attached']['library'][] = array('commerce_kickstart_product_ui', 'jquery_ui_spinner');
  }
}
</code>
and finally in our JS file we do:
<code>(function ($) {

  // Add a spinner on quantity widget.
  Drupal.behaviors.quantityWidgetSpinner = {
    attach: function ( context, settings ) {
      $('.form-item-quantity input').spinner({
        min: 1,
        max: 9999,
        increment: 'fast'
      });
    }
  }
})(jQuery);
</code>
Comment: Your method isn't working for me. Spinner is not applying to my quantity input, though all libraries connected well.
Answer: This functionality is also provided by the Commerce Extra module, it works just right.
Comment: it not working via composer for drupal 9


Two visible states

Question: I'm struggling with two visible states. WIth thE UI this is not possible.
I have an extended text/html field, which shall be visible if the following conditions match:
Scenario 1:
System checked AND System everything except Google Kalender and Miscellaneous selected AND branch is NOT Gesundheit... ist.
Scenario 2:
Website checked AND System 2 everything except Google Kalender and Miscellaneous selected AND branch is NOT Gesundheit... ist.
That's what I've tried, but it doesn't work:
  - ':input[name="requirements__[System]"]':
      checked: true
    ':input[name="branch"]':
      '!value': 'Gesundheit, Fitness, Ärzte, Kliniken, Labore & Sozialwesen'
    ':input[name="system_"]':
      value: null
      pattern: ^(Gastronovi|OpenTable|Petleo|Resmio|Seatris)$
  - or
  - ':input[name="requirements__[Website]"]':
      checked: true
    ':input[name="branch"]':
      '!value': 'Gesundheit, Fitness, Ärzte, Kliniken, Labore & Sozialwesen'
    ':input[name="system_2"]':
      value: null
      pattern: '^(Aleno|Best Western Hotels Resort|Calendly|Dirs 21|HotelNetSolutions|OpenTable|Quandoo|Tablebooker|Terminland|Vioma)$'

Comment: Does it matter if the pattern is in quotes or not?
Comment: If I just use one condition it works, but I am not able to put the two conditons for the visible states together.  I use the following for test:
`
':input[name="requirements__[System]"]':
      checked: true
    ':input[name="branch"]':
      '!value': 'Gesundheit, Fitness, Ärzte, Kliniken, Labore & Sozialwesen'
    ':input[name="system_"]':
      value: null
      pattern: ^(Gastronovi|OpenTable|Petleo|Resmio|Seatris)$
`
Answer: I have an old project of mine with complex conditions. There the YAML is written just a little bit different. In your case it would look like this (you see the extra line-break?):
-
  ':input[name="requirements__[System]"]':
    checked: true
  ':input[name="branch"]':
    '!value': 'Gesundheit, Fitness, Ärzte, Kliniken, Labore & Sozialwesen'
  ':input[name="system_"]':
    value: null
    pattern: ^(Gastronovi|OpenTable|Petleo|Resmio|Seatris)$
- or
-
  ':input[name="requirements__[Website]"]':
    checked: true
  ':input[name="branch"]':
    '!value': 'Gesundheit, Fitness, Ärzte, Kliniken, Labore & Sozialwesen'
  ':input[name="system_2"]':
    value: null
    pattern: '^(Aleno|Best Western Hotels Resort|Calendly|Dirs 21|HotelNetSolutions|OpenTable|Quandoo|Tablebooker|Terminland|Vioma)$'

Comment: Thanks, I tried this, but it doesn't work.

Two visible states


Generate file path for created file so it can be downloaded

Question: I'm writing a module based on this Jeff Geerling post that will allow the user to use a form to select some data, and then use the Batch API to generate a large .csv file with the desired data and download it from the browser. I have the form and batch processing working fine, but I can't figure out how to determine the path for the created file, as referenced in this code snippet:
/**
 * Interim download step for downloading CSV file.
 */
function MYMODULE_download_csv_file_interim($list_id) {
  global $base_url;

  if (empty($_SESSION['csv_download_filename']) || empty($_SESSION['csv_download_file'])) {
    return t('Please visit your list subscribers page to begin a list download.');
  }

  $list = node_load($list_id);

  // Redirect to the download file.
  $redirect = base_path() . 'path/to/download/csv/' . $list_id;
  drupal_add_js('setTimeout(function() { window.location.href = "' . $redirect . '"; }, 2000);', 'inline');

  $download_link = l(t('click here to download the file'), 'path/to/download/csv/' . $list_id);
  $output = '
' . t('Your subscriber list is now ready for download. The download should begin automatically. If it does not begin downloading within 5 seconds, please !download_link.', array('!download_link' => $download_link)) . '
';
  $output .= '
' . l(t("← Back to %list subscribers", array('%list' => $list->title)), 'node/' . $list_id . '/subscribers', array('html' => TRUE)) . '
';
  return $output;
}

At this point in the code, $_SESSION['csv_download_file'] is tmp/my_file.csv. I've tried to figure how to make this a valid url for downloading the file, but can't. For instance, I've tried using file_create_url(), but it just returns the same path.
What do I need to use to make this a valid URL to pass to the browser?
Answer: /tmp is outside of webroot so apache (or whatever) can't serve files from there.
You have 2 options:

Move the file from /tmp to your public files directory. This will mean anyone will have access to it (if they know the url). See file_unmanaged_move().

Eg.
$source = '/tmp/my_file.csv';
$destination = 'public://csv/my_file.csv';
file_unmanaged_move($source, $destination);

Stream the file to the browser via php. This means only people who can access your php script can get access to the file.

Eg.
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=my_file.csv');
return readfile('/tmp/my_file.csv');

Answer: The solution to my problem actually came in modifying this line:
$redirect = base_path() . 'path/to/download/csv/' . $list_id;

to point to another page instead of a file. I actually was already doing what Felix suggested above, and am using readfile() in this function:
function mymodule_download_csv_file() {
  // For added security, make sure the beginning of the path is the same as that
  // returned by file_directory_temp() (to prevent users from gaining access to
  // arbitrary files on the server).
  if (strpos($_SESSION['csv_download_file'], file_directory_temp()) !== 0) {
    return 'Access denied.';
  }

  // Add HTTP headers for CSV file download.
  drupal_add_http_header('Content-Type', 'text/csv; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $_SESSION['csv_download_filename'], TRUE);

  // Allow caching, otherwise IE users can't dl over SSL (see issue #294).
  drupal_add_http_header('Cache-Control', 'max-age=300; must-revalidate');

  // Read the file to the output buffer and exit.
  readfile($_SESSION['csv_download_file']);
  exit;
}

So the trick was simply to add a menu item for this function, and then change the line above to point to the defined URL for this function.


Como transformar um texto selecionado para caixa baixa no VSCode?

Question: Gostaria de transformar um trecho de código em caixa baixa no VSCode. Obter um efeito similar ao do CTRLSHIFTY do Eclipse?
Algo que seja semelhante ao gif abaixo:
Comment: A que eu conheço é selecionar o texto, `Ctrl+Shift+P` e digitar "lower" (ou upper), aparecendo a opção "Transform to Lowercase". Serve?
Comment: @Woss, o problema é texto não sequencial =/ Estou tentando ver aqui como cadastrar os atalhos, mas não estou conseguindo acessar o `settings` em modo plano, só através da GUI
Comment: Não sei se entendi o "texto não sequencial" xD
Comment: É um trecho de SQL em que os padrões da empresa dizem "nomes em minúsculo" e "palavras chaves do SQL em maiúsculo". Meu arquivo por hora está todo em caixa alta, então queria mudar o nome das colunas/tabelas para minúsculo, mas não tipos de colunas nem o `CREATE TABLE`.
Comment: Eu consegui fazer o meu _binding_, mas devo dizer que a GUI é horrível. Vou ver se consigo acessar algum modo mais textual de se fazer as coisas
Comment: Se te conforta, o Datagrip tem essa opção nas configurações (https://i.stack.imgur.com/TyQFX.png) e basta utilizar `Ctrl-Alt-L` para formatar o arquivo completo xD
Comment: @Woss, conforta bastante! Mas teria de mudar toda a as pergunta para se adequar a isso
Answer: Cara o VS Code tem uma forma de pesquisar e substituir strings usando regex aqui tem um artigo que pode te ajudar nisso https://dev.to/rfornal/vs-code-search-and-replace-regex-mn2

Mas como não manjo de Regex aqui tem um exemplo manual. Mas só consegui fazer com uma string por vez... Vale lembrar que vc pode tb definir se quer usar o case sencitive na substituição

Criando um Atalho
Vc  pode  criar um atalho de teclado para transforma o que estiver selecionado para Upper, ou Lower Case conforme imagem abaixo. Basta vc entrar nos Settings e procurar por Keyboard Shortcut
Comment: Não consegui fazer a letra específica mudar de caso. o `\U` no replace que eu esperaria que fizesse o trabalho não o fez =/
Comment: @JeffersonQuesado editei com a opção de vc criar um atalho, ai basta vc selecionar e usar o atalho, só que vc vai ter que fazer um Atalho para Upper e outro para Low
Answer:
Selecione o texto a ser transformado. Use Ctrl + L para selecionar
toda a linha;
Abra Mostrar todos os comandos. Linux e Windows: Ctrl + Shift + P,
Mac: ⇧⌘P;
Digite o comando, por exemplo: lowercase, uppercase, titlecase;
Aguarde o preenchimento automático;
Pressione Enter.


Proof that $\int_{-1}^{1}\sqrt{1-x^2}dx=\frac{\pi}{2}$?

Question: In my textbook appears that $\displaystyle\int_{-1}^{1}\sqrt{1-x^2}dx=\frac{\pi}{2}$
But where does this equation come from?
Comment: How do you define $\pi$?
Comment: I had no doubt that you were referring to [this](http://en.wikipedia.org/wiki/Pi), but for many this integral would be the definition of $\pi/2$, and hence of $\pi$. I figure you want some long chain of equalities, starting on the left side of what you wrote and ending up on the right. What should the penultimate expression look like?
Comment: @Garmen: that's not a definition. Those digits had to have come from somewhere. (As Dylan and the others say, since the integrand is a semicircle, and with the interpretation of the integral as an area, you have a basic definition of $\pi$.)
Comment: @DylanMoreland $\pi$ is the mathematical constant $3.141592\dots$
Comment: I did a grammatical edit.  In English one may say "This comes from X" or "Where does this come from", or "This came from X" or "Where did this come from", but never "Where does this comes from" or "Where did this came from".
Answer: The equation $y = +\sqrt{1 - x^2}$ for $-1\leq x\leq1$ describes the top half of a circle of radius $1$. The area between this curve and the $x$-axis is therefore $\pi/2$. On the other hand, you can compute the area under this curve by doing the integral $$\int_{-1}^1 \sqrt{1 - x^2}\,dx.$$
Answer: Those "area" answers are probably the best ones.  On the other hand, if $\pi$ is defined in some way other than area, we can pursue the standard trigonometric substitution: $x = \sin \theta$, $-\pi/2 \le \theta \le \pi/2$ to get:
$$\begin{align}
\int_{-1}^1\sqrt{1-x^2}\,dx &= \int_{-\pi/2}^{\pi/2} \cos^2\theta\,d\theta
= \int_{-\pi/2}^{\pi/2}\frac{1+\cos(2\theta)}{2}\,d\theta
\\
&=\frac{1}{2}\int_{-\pi/2}^{\pi/2}d\theta + \frac{1}{2}\int_{-\pi/2}^{\pi/2} \cos(2\theta)\,d\theta
\\
&= \frac{\pi}{2} + 0 = \frac{\pi}{2} .
\end{align}$$
Answer: Not the "cleverest" method, like the above, - but works!
$$\int_{-1}^1 \sqrt{1-x^2} \ dx$$
To compute that integral, one may substitute $x=\sin{t}$, and get:
$$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \sqrt{1-\sin^2{t}} \ d(\sin{t})=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \cos{t}\cos{t} \ dt=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \cos^2{t} \ dt$$
$$\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \cos^2{t} \ dt=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\frac{1+\cos{2t}}{2} \ dt=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\frac{dt}{2}+\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\frac{\cos{2t}}{2}=$$
$$= \frac{\pi}{2}+\frac{1}{2}\sin{t}\cos{t}{\huge{|}}_{-\frac{\pi}{2}}^{\frac{\pi}{2}}=\frac{\pi}{2}+0=\frac{\pi}{2}$$
Answer: $f(x)=\sqrt{1-x^2}$ is the graph of the upper half of the circle $x^2+y^2=1$. To see this, just square both side.
Thus,
$$\int_{-1}^1 \sqrt{1-x^2}dx$$
is the integral which represents the area under half of circle of radius 1. That is the are of half disk, thus $\frac{1}{2} \pi 1^2$


Splitting value of a dictionary into two dataframe columns based on a comma in the value

Question: Hi I have a dictionary below,
I want to split the dictionary value into two based on a comma present in the dictionary value, and then store the result in a new dataframe as follows:
For a particular dictionary entry, lets say the first one in our case:
(1, 5) - this is the key, and should be column 1 in a new dataframe
(2,) - this is extracted from the value (pre-comma), and should be column 2 in the dataframe
1.0 - this is extracted from the value (post-comma), and should be column 3 in the dataframe
The same process should be repeated for all (4 in this case) key value pairs in the dictionary.
If rules is the name of the dictionary,
I know I can access rules.keys(), and rules.values(), but what I do not understand is how do I access the comma split values in the dictionary because when I try something like rules.values() [1], it throws an error.
{(1, 5): ((2,), 1.0),
 (2, 5): ((1,), 1.0),
 (4,): ((2,), 1.0),
 (5,): ((1, 2), 1.0)}

Output DF:
Col 1       Col2        Col3
(1, 5)      (2,)        1.0
(2, 5)      (1,)        1.0
(4,)        (2,)        1.0
(5,)        (1, 2)      1.0

Comment: Can you post the output DF?
Comment: I just posted it, thanks
Answer: Using a list comprehension.
Ex:
import pandas as pd

data = {(1, 5): ((2,), 1.0), (2, 5): ((1,), 1.0), (5,): ((1, 2), 1.0), (4,): ((2,), 1.0)}
df = pd.DataFrame([[k] + list(v) for k, v in data.items()], columns=["Col_1", "Col_2", "Col_3"])
print(df)

Output:
    Col_1   Col_2  Col_3
0  (1, 5)    (2,)    1.0
1  (2, 5)    (1,)    1.0
2    (5,)  (1, 2)    1.0
3    (4,)    (2,)    1.0


Ansible yaml to xml

Question: I am trying to create xml file with yaml playbook.
XML should looks like this:
<accessControl>
  <ipRanges>
    <ipRange>
      <ip>
        <int>00</int>
        <int>00</int>
        <int>00</int>
        <int>000</int>
      </ip>
      <mask>
        <int>255</int>
        <int>255</int>
        <int>255</int>
        <int>0</int>
      </mask>
    </ipRange>
    <null/>
  </ipRanges>
</accessControl>

I have no idea how to create ansible task providing multiple identical tags (< int >). I am looking for something loop like or there is another way?
Edit:
I.E I have XML like this:
<accessControl>
  <ipRanges>
    <ipRange>
    </ipRange>
    <null/>
  </ipRanges>
</accessControl>

And I need to add IP and MASK into  tag to achieve:
<accessControl>
  <ipRanges>
    <ipRange>
      <ip>
        <int>127</int>
        <int>0</int>
        <int>0</int>
        <int>1</int>
      </ip>
      <mask>
        <int>255</int>
        <int>255</int>
        <int>255</int>
        <int>0</int>
      </mask>
    </ipRange>
    <null/>
  </ipRanges>
</accessControl>

I can provide IP and Mask in list, dict, tuple - it does not matter.
For a sake of this question lets say it will be like this: ['127.0.0.1', '255.255.255.0']
Comment: Where does the data come from? You want "to create XML file". What is the input?  Your question will be closed if you don't [edit] the question and provide [mre].
Comment: This requirement is well suited for [templates](https://docs.ansible.com/ansible/2.9/modules/template_module.html) -- specifically a Jinja (`.j2`) file rendered in combination with the template module.
Answer: For example, given the data
ip: ['127.0.0.1', '255.255.255.0']

the template
shell> cat test.xml.j2
<accessControl>
  <ipRanges>
    <ipRange>
      <ip>
{% for item in ip %}
{% if loop.index is odd %}
{% for i in item.split('.') %}
        <int>{{ i }}</int>
{% endfor %}
{% endif %}
{% endfor %}
      </ip>
      <mask>
{% for item in ip %}
{% if loop.index is even %}
{% for i in item.split('.') %}
        <int>{{ i }}</int>
{% endfor %}
{% endif %}
{% endfor %}
      </mask>
    </ipRange>
    <null/>
  </ipRanges>
</accessControl>

and the task
    - template:
        src: test.xml.j2
        dest: test.xml

give
shell> cat test.xml
<accessControl>
  <ipRanges>
    <ipRange>
      <ip>
        <int>127</int>
        <int>0</int>
        <int>0</int>
        <int>1</int>
      </ip>
      <mask>
        <int>255</int>
        <int>255</int>
        <int>255</int>
        <int>0</int>
      </mask>
    </ipRange>
    <null/>
  </ipRanges>
</accessControl>

You can use slice notation instead of even/odd index testing
      <ip>
{% for item in ip[0::2] %}
{% for i in item.split('.') %}
        <int>{{ i }}</int>
{% endfor %}
{% endfor %}
      </ip>
      <mask>
{% for item in ip[1::2] %}
{% for i in item.split('.') %}
        <int>{{ i }}</int>
{% endfor %}
{% endfor %}
      </mask>

Ansible yaml to xml


How to aggregate outputs from a dynamically generated set of projects into a single folder

Question: I need to collect into a single folder all test assemblies, with their dependencies, and configuration files. The process should preserve the directory structure from the output of each test project. We have a solution that requires manually attaching test projects to a master project, but our solution has far too many projects for this to be maintainable. These should be located automatically based on naming convention (x.UnitTest.csproj, y.IntegrationTest.csproj).
For background, we are working with a build system that passes artifacts (binaries, etc) between agents. We are compiling on one agent, and testing on other agents. The massive duplication of assemblies between test projects is slowing the build process down.
What I have done:
1) I have a csproj that references most of the test projects. This gets binaries and dependencies into one folder.
2) I am able to identify all files to copy using this
<CreateItem
  Include="%(ProjectReference.RootDir)%(ProjectReference.Directory)$(OutDir)*.config">
<Output TaskParameter="Include" ItemName="TestConfigurationFiles"/>
</CreateItem>

<Copy
        SourceFiles="@(TestConfigurationFiles)"
        DestinationFolder="$(OutDir)">
</Copy>

I've attempted most obvious things, such as

MsBuild task: RebaseOutputs attribute, overriding the OutDir property. I can provide the msbuild task with a dynamically generated set of outputs, but can only build them in their default folder.
Hooking into the TargetOutputs of
msbuild task gives only the primary
output assembly (without
dependencies).
I experimented with "Copy Always" for
configuration files. This puts them
in the output directory of the
dependent project as "app.config" not
"dllname.config", and not in the
final project.

Solutions that could make this better might include

Provide an example of adding to the projectreference item array dynamically, before compilation.
Use msbuild TargetOutputs to create a list of all files in the folder (instead of just the primary output) and copy to a destination folder.

Today I'm using msbuild 3.5. Ideally the solution would work with msbuild 3.5. We are transitioning to .NET 4 / MsBuild 4 soon, so, if must be done in .Net 4, that is fine.
Answer: Have you considered flattening the folder structure when you export your artifacts?
Something like:
src/*.UnitTest*/bin/**/*.* -> /testlibs
src/*.IntegrationTest*/bin/**/*.* -> /testlibs

Comment: I need to maintain the folder structure.


Estou a obter este erro Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Question: Tudo estava a funcionar, mas depois de alguns tempos comecei a receber constantemente este erro:

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

O servidor mysql parece estar constantemente a cair.
Depois eu reinicio e ele ao fim de algum tempo cai novamente.
Comment: Amadeu, sua aplicação esta encerrando as conexões com o MySQL após usa-las? Isso pode ser limite de conexão.
Comment: Testou se o servidor MySQL está em execução?
Comment: Ele tinha caido, mas parece estar sempre caindo
Comment: Ele não estava em execução,ai reiniciei. Parece que algo está a fazer ele constantemente cair
Comment: Precisa checar se não tem corrupção em alguma tabela ou base de dados. Seria o caso de você [edit] a pergunta e por o máximo de detalhes possíveis, pois como está, precisariamos fazer diversas perguntas aqui nos comentários até conseguirmos entender o problema. Se você puder complementar a pergunta com tudo que já testou e tentou, seria bom. Aqui tem umas dicas: [Ask]
Comment: Eu reinicie tudo e parece estar a funcionar, mas eu ja tinha feito antes então eu imagino que dentro de algum tempo isto vai voltar a cair novamente
Comment: Como você faz a conexão??? LocalHost ou 127.0.0.1?
Comment: Ok o que eu fiz foi aumentar a memória ram e troquei o processador para um mais rápido e pronto isso funcionou.
Answer: Ok o que eu fiz foi aumentar a memória ram e troquei o processador para um mais rápido e pronto isso funcionou. Não tive mais nenhum problema depois destas alterações.


Maximizing Cronbach alpha to select the number of variables that define a given construct

Question: I can't seem to find this anywhere on the internet or in my books. I'm putting together a construct for an underlying variable.
Is it acceptable to have a construct with two variables if that produces a bigger Cronbach alpha than the construct with 3 variables in a professional statistical analysis?
Using 2 variables seems a bit on the low side, but it produces better results.
Comment: If alpha is low when you have 3 items, that's an indication that your items don't go together that well. If it is much higher when you drop one item, that's an indication of which item was problematic. Some latent variables are hard to measure; but maybe you can come up with a third variable that works well.
If you give us context, maybe someone here can help.
Comment: Are you saying that the research that supported a 3 item scale did not hold up when you replicated it?  If so, why not.  What Ns were involved in the two research studies?  In any case, I would not discard a two item scale out of hand.  Do you know if this two item scale correlates with any other variables of interest (i.e., construct validity or criterion-related validity)?
Comment: The contruct originally consisted of these three variables. Apparently it doesn't measure what I want all that well. Can I still use it as a construct if it just has two variables? Is it common for a construct to only consist out of 2 variables?
Comment: @JoelW. asks good questions.
Answer: The unstandardized Cronbach's alpha on two items does not make much sense, see e.g. The reliability of a two-item scale: Pearson, Cronbach, or Spearman-Brown? (International Journal of Public Health 58(4):637-642). You can also think in terms of of item correlation with the total score when correcting for overlap, see, e.g., W. Revelle's textbook on psychometrics (chapter 7). As for a good reference, I would recommend Test theory: A unified approach, by R.P. McDonald (1999), who suggested 3 items per dimension for uncorrelated factor models, IIRC, which is also handy when it comes to estimate the parameters of a CFA, and Psychometric Theory, by Nunally and Bernstein (1994).
Beware also that using a statistic like "alpha if item is deleted" without cross-validation is proned to over-fitting (the alpha is already a lower bound for reliability, but sample reliability may appear higher than population-level reliability when further capitalizing on chance), notwithstanding the fact that constuct coverage (or validity) may be quite poor when using only two items.


"Refresh" do fragment co listview

Question: Tenho um Fragment que, clicado num RadioButton, é calculado uma rota, após este calculo de rotas, é mostrado um ListView com os resultados.
Ao clicar na outra opção deste radiobuttom, é novamente calculada as rotas e mostrado os novos resultados.
Problema:
Ao subir estes novos resultados, os antigos, não são retirados da tela.
Como posso remove-los e colocar somente os novos resultados?
Fragment:
public class ResultsFragment extends Fragment implements ListView.OnItemClickListener {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String RESULTS_JSON = "results_json";
    public static final String GENERIC_ROUTE_ID = "generic_route_id";
    public static final String IS_RIDER = "is_rider";

    private String mResultsJson;
    private String mResultsJson2;
    private int mGenericRouteId;

    private urMainOnActionPerformed mListener;

    private RouteResultsAdapter mAdapter;

    private ArrayList<Route> mResults;

    @BindView(R.id.results_label)
    TextView mResultsLabel;

    @BindView(R.id.date_container)
    RelativeLayout mDateContainer;

    @BindView(R.id.pick_date_search)
    TextView mDate2;

    @BindView(android.R.id.list)
    public ListView mListView;

    private boolean isRider;
    private Calendar selectedDate = Calendar.getInstance();

    private DatePickerDialog mDatePickerDialog;

    public ResultsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param resultsJson Parameter 1.
     * @return A new instance of fragment ResultsFragment.
     */
    public static ResultsFragment newInstance(String resultsJson, int genericRouteId
            , boolean isRider) {
        ResultsFragment fragment = new ResultsFragment();
        Bundle args = new Bundle();
        args.putString(RESULTS_JSON, resultsJson);
        args.putInt(GENERIC_ROUTE_ID, genericRouteId);
        args.putBoolean(IS_RIDER, isRider);
        fragment.setArguments(args);
        return fragment;
    }

    public void setResults(String json) {
        mResultsJson = json;
        ArrayList<Route> routes = Route.buildRouteArrayFromJsonString(mResultsJson);
        routes = Route.buildRouteArrayFromJsonString(mResultsJson);
        routes.clear();
        mResults = Route.orderRouteArrayByHavingCar(routes);
        mDate2.setText(TimeUtils.getDayOfWeekFromDate(getContext(), SearchRideType.getInstance().getDate()));
        if (mResults != null) {
            mAdapter = new RouteResultsAdapter(mResults, getContext(), isRider);
            mListView.setAdapter(mAdapter);
            mListView.setOnItemClickListener(this);
            mResultsLabel.setText(mResults.size() + " " + getString(R.string.results));
        }

    }

    public void setGenericRouteId(int id) {
        mGenericRouteId = id;
    }

    public void setIsRider(boolean isRider) {
        this.isRider = isRider;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mResultsJson = getArguments().getString(RESULTS_JSON);
            mGenericRouteId = getArguments().getInt(GENERIC_ROUTE_ID);
            isRider = getArguments().getBoolean(IS_RIDER);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_display_results, container, false);
        ButterKnife.bind(this, view);
        if (mResultsJson != null) {
            setResults(mResultsJson);
        }
        mDateContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatePickerDialog = new DatePickerDialog(getContext(), R.style.MyDatePickerStyle, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        Calendar date = Calendar.getInstance();
                        date.set(year, monthOfYear, dayOfMonth);
                        if (!SearchRideType.getInstance().getDate().equals(date)) {
                            SearchRideType.getInstance().setDateTime(date.getTime());
                            mDate2.setText(TimeUtils.getDayOfWeekFromDate(getContext(), date.getTime()));
                            mListener.recalculateSuggestions();
                        }

                    }
                }, SearchRideType.getInstance().getCalendar().get(Calendar.YEAR), SearchRideType.getInstance().getCalendar().get(Calendar.MONTH), SearchRideType.getInstance().getCalendar().get(Calendar.DAY_OF_MONTH));
                mDatePickerDialog.show();
            }
        });
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        showItemAndAction(parent, view, position, id);
    }

    public void showItemAndAction(AdapterView<?> parent, View view, int position, long id) {
        if (mListener != null) {
            mListView.smoothScrollToPosition(position);
            Route route = mResults.get(position);
            if (!route.ride.isRideTimeValid()) {
                Toast.makeText(
                        getActivity(), getString(R.string.ride_time_passed), Toast.LENGTH_SHORT).show();
            } else if (SearchRideType.getInstance().isDriver() || route.getUser() != null && route.getUser().hasCar()) {
                mListView.setSelection(position);
                route.setGenericRouteId(mGenericRouteId);
//                mListener.showAskRideFragment(route);
                RelativeLayout mActionButton = (RelativeLayout) view.findViewById(R.id.action_button);
                mActionButton.setVisibility(View.VISIBLE);
                setActionButton(mActionButton, route);
            } else if (isRider || route.getUser() != null && !route.getUser().hasCar()) {
                mListView.setSelection(position);
                route.setGenericRouteId(mGenericRouteId);
//                mListener.showAskRideFragment(route);
                RelativeLayout mActionButton = (RelativeLayout) view.findViewById(R.id.action_button);
                mActionButton.setVisibility(View.VISIBLE);
                setActionButton(mActionButton, route);
            } else {
                Toast.makeText(
                        getActivity(), getString(R.string.has_no_car), Toast.LENGTH_SHORT).show();
            }

        }
        ((RouteResultsAdapter)parent.getAdapter()).notifyDataSetChanged();
    }

    public void setActionButton(RelativeLayout actionButton, Route route) {
        setActionButtonLayout(actionButton);
        setActionButtonListener(actionButton, route);
    }

    public void setActionButtonLayout(RelativeLayout actionButtonLayout) {
        if (actionButtonLayout != null) {
            ImageView icon = (ImageView) actionButtonLayout.findViewById(R.id.icon_action_button);
            TextView label = (TextView) actionButtonLayout.findViewById(R.id.action_button_label);
            if (isRider) {
                label.setText(getString(R.string.request_ride));
                icon.setImageResource(R.drawable.ic_person_white);
            } else {
                label.setText(getString(R.string.offer_ride));
                icon.setImageResource(R.drawable.ic_driver_white);
            }
        }
    }

    public void setActionButtonListener(RelativeLayout actionButton, final Route route) {
        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onAskOrOfferRideRequested(
                        route.ride,
                        isRider ? "ask" : "offer",
                        route.getGenericRouteId()
                );
            }
        });
    }

    @OnClick(R.id.map_button)
    public void onMapClick() {
        mListener.showMap();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof urMainOnActionPerformed) {
            mListener = (urMainOnActionPerformed) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnConfirmRoutineFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public void requestLayoutForListView() {
        if (mResults != null) {
            mAdapter = new RouteResultsAdapter(mResults, getContext(), isRider);
            mListView.setAdapter(mAdapter);
        }
    }
}

Adapter:
public class RouteResultsAdapter extends BaseAdapter {

    ArrayList<Route> mData;
    Context mContext;
    private boolean isRider;

    public RouteResultsAdapter(ArrayList<Route> routes, Context context, boolean isRider){
        mData = routes;
        mContext = context;
        this.isRider = isRider;

    }

    @Override
    public int getCount(){
        return mData.size();
    }

    @Override
    public long getItemId(int position){
        return position;
    }

    @Override
    public Route getItem(int position){
        return mData.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        RouteResultViewHolder holder;
        if(convertView == null){
            holder = new RouteResultViewHolder();
            convertView = ((LayoutInflater)
                    mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.fragment_display_results_item,null);
            holder.username = (TextView)convertView.findViewById(R.id.username);
            holder.companyPosition = (TextView)convertView.findViewById(R.id.company_position);
            holder.profilePic = (ImageView)convertView.findViewById(R.id.profile_image);
            holder.hour = (TextView)convertView.findViewById(R.id.hour);
            holder.resultBackground = (RelativeLayout)convertView
                    .findViewById(R.id.result_background);
            convertView.setTag(holder);
        }else{
            holder = (RouteResultViewHolder)convertView.getTag();
        }
        holder.fillHolder(getItem(position),mContext,isRider);
        loadBitmapFromUser(getItem(position).getUser(),holder.profilePic);

        return convertView;
    }

    public static class RouteResultViewHolder{
        TextView username;
        TextView companyPosition;
        TextView hour;
        ImageView profilePic;
        RelativeLayout resultBackground;

        public void fillHolder(Route item,Context context, boolean isRider){
            if(item!=null){
                User user = item.getUser();
                if(user!=null){
                    username.setText(user.getName());
                    companyPosition.setText(user.getJob());
                    if(item.ride!=null){
                        hour.setText(item.ride.getStartTimeStampString());
                    }else{
                        hour.setVisibility(View.GONE);
                    }
                    if(isRider) {
                        if (user.hasCar() && item.ride.isRideTimeValid()) {
                            resultBackground.setBackgroundDrawable(
                                    context.getResources().getDrawable(R.drawable.display_results_selector));
                        } else {
                            resultBackground.setBackgroundColor(context.getResources()
                                    .getColor(R.color.grey));
                        }
                    }
                }
            }
        }
    }

    public void loadBitmapFromUser(User user, final ImageView mProfileImage){
        if(ConnectionUtils.isNetworkAvailable(mContext)){
            Ion.with(mContext)
                    .load(user.getPhotoUrl())
                    .asBitmap()
                    .setCallback(new FutureCallback<Bitmap>() {
                        @Override
                        public void onCompleted(Exception e, Bitmap result) {
                            if (e != null) {
                                e.printStackTrace();
                            }
                            if(mProfileImage != null) {
                                mProfileImage.setImageBitmap(result);
                            }
                        }
                    });
        }else{
            ConnectionUtils.showConnetionError(mContext, 1);
        }
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }
}

Answer: Suponha que seu ListView exibe alguns dados armazenados em um ArrayList.
Depois de alterar o conteúdo do ArrayList, você precisa dizer a lista que a fonte dos dados tinha mudado e ele precisa redesenhar próprio para mostrar os novos dados.
Então, esse é o lugar onde notifyDatasetChanged() que verifica se há mudança na sua lista e logo é redesenhado sua lista:
adapter.notifyDataSetChanged();

O método notifyDataSetChanged é responsável por avisar que houve
  mudança nos dados que estão no Adapter.
Comment: então, este método está no meu adapter. Eu havia colocado esta chamada em vários lugares no código para a verificação, mas não obtive sucesso.
Answer: Resolvi passando por um metodo que verifica se é o mesmo fragment e se deve ou não ser removido e inflado novamente. Assim ele carrega os dados novos.

"Refresh" do fragment co listview


How to overload ofstream operator in c++?

Question: I'm trying to overload an operator so I can write it into a file I created:
typedef struct Square {
    pawn *pawns[2] = { nullptr,nullptr };
}square;

class game {

    player players[2];
    score score1 = 0, score2 = 0;
    square board[10][10];

public:
    //constructor
    friend class ofstream& operator<< (ofstream& out, game curr)
    {
        for (int i = 0; i <= 20; i++)
        {
            out << "=";
        }
        for (int index = 0; index < 10; index++)
        {
            out << '\n';
            for (int j = 0; j <= 10; j++)
            {
                out << "| ";
            }
            out << index << '\n';
            for (int i = 0; i <= 20; i++)
            {
                out << "=";
            }
        }
        out << '\n';
        for (int index = 0; index < 10; index++)
        {
            out << " " << index;
        }
        return(out);
    }

I mainly get Error C2676 :

Severity    Code    Description Project File
Error       C2676   binary '<<': 'ofstream' does not define this operator or a conversion to a type acceptable to the predefined operator

What am I doing wrong?
Comment: Looks like you are trying to define the freestanding function within the declaration of it being a friend function.
Comment: um it's actually a function I've already written and copied inside, is it possible to write functions inside operator overloading?
Comment: 1) `friend class ofstream& operator<<` What does `class` mean in the operator declaration? Why did you put it there? 2) "_what am I doing wrong?_" `operator<<` needs to be implemented as a function (opposed to a method of a class). I assume that you must've heard that, since you _tried_ to mark the "function" as a friend.
Comment: In the declaration of the `<<` operator, change `game curr` to `const game& curr` and change both occurrences of `ofstream` to `ostream`.
Answer: The word class in the line
friend class ofstream& operator<< (ofstream& out, game curr)

is not correct.
Remove that.
Also,

change ofstream to std::ostream so you can use any std::ostream, not just std::ofstream.
Change the second argument type to a const&.

friend std::ostream& operator<< (std::ostream& out, game const& curr)
{
   ...
}

It will be better to move the implementation of the function out of the class definition. It will allow you to implement it in a .cpp file.
For that, I suggest:
// Declare the class
class game;

// Declare the funtion
std::ostream& operator<< (std::ostream& out, game const& curr);

// Make the function a friend of the class.
class game
{
   ...
   friend std::ostream& operator<< (std::ostream& out, game const& curr);
};

// Define the function outside the class definition.
std::ostream& operator<< (std::ostream& out, game const& curr)
{
   ...
}

Comment: If properly declared and accessible, all functions are usable from other functions.  Operator functions are no different.   The reason you've had problems is that the operator function was not properly declared, so the compiler rejected it.
Comment: can it be used thourgh other classes? what I mean is that I want class A to use a function which get class Game and ofstream, and use this operator, is it possible? or the operator needs to be loaded on class A...
Comment: @AmitBL, I think you are asking whether you can use `game g; std::cout << g << std:;endl;`. The answer to that is "yes". If you are asking something different, please clarify.
Comment: I've overloaded the above operator in Class Game.
I want to this this Opeator inside a function of Class FileUtils,
is it possible?
Answer: 1)  Remove class from the line friend class ofstream& operator<< (ofstream& out, game curr).
2)  Add an #include <iostream> somewhere above this declaration.
3)  Remove using namespace std (since your code is a class definition, which often properly belongs in a header file if you want to use your class types in multiple source files,  and using namespace std is bad practice in a header file)   and replace all instances of ofstream with std::ostream.
4)   (Optional, but good practice). Change the second argument of operator<<() to be a const reference.
Your question was a bit misleading, as the code sample refers to types that are not defined anywhere.   In future, provide a MCVE


Is it possible for baseball teams to use draft picks in trades?

Question: The Toronto Blue Jays took away catcher Russell Martin in free agency from the Pittsburgh Pirates after the Pirates made Martin a "qualifying offer"  As a result, the Blue Jays lose a first-round draft pick, and the Pirates get a compensating pick in the "sandwich" round between the first and second rounds.
My understanding is that teams are now allowed to use so-called "compensating balance" picks in trades. I was wondering if the Pirates could also "trade back" the draft pick they get from the Blue Jays using one of two mechanisms. (Say the Pirates trade the draft pick and a prospect for a player.)
Mechanism 1 works only if the Pirates have to file for the compensating pick. Then the Pirates could say to the Blue Jays, we'll give you prospect X for player Y, and in addition, we'll let the deadline pass for filing for the compensation pick, meaning that you get to keep yours. (This mechanism doesn't work if the Blues Jays lose, and the Pirates gain, the draft pick "automatically.")
Mechanism 2 is a player to be named later PBNL. That is, the Pirates trade the prospect and a PBNL to the Blue Jays for the player. On draft day, 2015, when the Pirates are about to make their compensating pick, the Blue Jays tell them who to pick, and the Pirates hand him over as the PBNL.
Can a draft pick be "traded" using either or both of those two mechanisms?
Answer: I think there is some confusion here between "compensation" and "competitive balance" picks.
Compensation picks are awarded to teams that lost a free agent that they extended a "qualifying offer" to. The "qualifying offer" is calculated annually. For the 2014-15 offseason, it is $15.3 million. The compensation picks occur at the end of the first round. The signing team forfeits its first pick (unless within the first 10 picks of the draft).
Note that under the old rules, the departed team received the forfeited pick as well, but this changed starting with the 2013 draft.
Competitive balance picks consist of upto 6 picks each between the first and second rounds of the draft. The competitive balance picks are awarded via lottery. The lottery consists of the ten lowest revenue teams and the ten smallest market teams. Teams that fall into both categories may be selected for two picks (see Miami in 2013).
Competitive balance picks (and the money allocated for those picks) are the only draft picks that can be traded under the current MLB rules.
MLB trade rules state that players cannot be traded in the same year that they are drafted. Often a trade will include a PTBNL with the understanding between the teams that the player was a recent draftee who can only be officially traded once that window is over. I am unaware of any case where a team has actually drafted a player with the intention of trading him to a specific team. It may have happened but was not announced.


Classe java com float e int

Question: Estou desenvolvendo um projeto MVC com Java para web utilizando eclipse.
Na tabela produto de banco de dados está assim
       create table Produto
(
    Idproduto int identity primary key,
    Nome varchar(40),
    Preco decimal(6,2),
    Categoria int,
    Estoque int

    )

}
Tenho uma classe chamada produto
public class Produto {

private int Idproduto;
private String Nome;
private float Preco;
private int Categoria;
private int Estoque;
public int getIdproduto() {
    return Idproduto;
}
public void setIdproduto(int idproduto) {
    Idproduto = idproduto;
}
public String getNome() {
    return Nome;
}
public void setNome(String nome) {
    Nome = nome;
}
public float getPreco() {
    return Preco;
}
public void setPreco(float preco) {
    Preco = preco;
}
public int getCategoria() {
    return Categoria;
}
public void setCategoria(int categoria) {
    Categoria = categoria;
}
public int getEstoque() {
    return Estoque;
}
public void setEstoque(int estoque) {
    Estoque = estoque;
}
public Produto() {
    super();
    // TODO Auto-generated constructor stub
}
public Produto(int idproduto, String nome, float preco, int categoria, int estoque) {
    super();
    Idproduto = idproduto;
    Nome = nome;
    Preco = preco;
    Categoria = categoria;
    Estoque = estoque;
}

Função inserir produto
public void Inserirproduto(Produto produto) {

        try {
            Connection con = conectar();
            CallableStatement cls = con.prepareCall("{call Inserirprodutoadm(?,?,?,?)}");
            cls.setString(1, produto.getNome());
            cls.setFloat(2, produto.getPreco());
            cls.setInt(3, produto.getCategoria());
            cls.setInt(4, produto.getEstoque());
            cls.execute();
            con.close();
        } catch (Exception e) {
            System.out.println("Erro" + e.getMessage());
        }
    }

Quando chamo essa classe no controller com os tipos de dados int e float ele não reconhece

Como faço para os tipos int e float ser reconhecidos quando chama a classe ?
Comment: Opa, voocê precisa dar um parse nessa: Integer.parseInt(str);
Float.parseFloat(str);
Comment: Valeu amigao. Deu certo aqui. Obrigado
Answer: Basta fazer um parse, exemplo:
produto.setPreco(Float.parseFloat(request.getParameter("Preco")); //para Float
produto.setCategoria(Integer.parseInt(request.getParameter("Categoria"))) // Para Int

Classe java com float e int


False proof about entire functions !?

Question: I often run into problems when i consider entire functions as Some sort of " polynomial of infinite degree ". Yet I do not know why most of the time.
It seems intuitive. Apart from the exp function not having a zero ofcourse.
Here is an example.
Let $f(z)$ be an analytic function such that $| f(0) | > 0$ and $| f(1)| > 1$.
Now consider the arguments below that give a false proof.
Let $n$ be the " degree " of the polynomial of infinite degree. We take the limit as n Goes to infinity.
Let us try to find ( complex) solutions $r$ such that
$$|r| > 1$$
$$ f(r) = 0 $$
We argue as follows :
Thus, let us assume $|r|\ge 1$. Since
$$ f(r) =
a_0 + a_1r + \cdots + a_{n-1}r^{n-1} + r^n =0
$$
then
$$
r = -\frac{a_0}{r^{n-1}} - \frac{a_1}{r^{n-2}} - \cdots - a_{n-1}.
$$
By taking absolute values and using the triangular inequality, we obtain
$$
|r| \le \frac{a_0}{|r|^{n-1}} + \frac{a_1}{|r|^{n-2}} + \cdots + |a_{n-1}|.
$$
Finally, using that $|r|\ge 1$ (so that $\frac{1}{|r|}\le 1$), we obtain the required upper bound
$$
|r| \le |a_0| + \cdots + |a_{n-1}|.
$$
Since when $ n$ Goes to infinity then $n-1$ Goes to infinity as well and
$$ \infty >> |a_0| + \cdots + |a_{\infty}| >= |f(1)| > 1$$
$$| r | \le |a_0| +  \cdots << \infty $$
But this would imply there is boundary on the zero's of $f(z)$.
In fact in the case when $f(z)$ has infinitely many zero's they all belong within an absolute value ; there making the function no longer analytic !!
This is clearly a wrong proof.
But why ???
Comment: As is so often the case, the error is that you have simply spoken of "letting $n$ go to infinity" without explaining what that actually means rigorously or how it would imply any of the things you are claiming.
Comment: I don't get it. Two people have given you very good reasons why this proof-sketch cannot work, and indeed, it can't work because the conclusion you draw is false. Why do you keep trying to explain why it's a good idea? Is there an actual question here that *could* have an answer that would satisfy you? A proof is wrong because one step does not follow from another, or because the logic has holes in it, so you've gotten two good answers to the question you asked. So again: is there some sort of answer that *would* satisfy you?
Comment: As to the second line, if you considered the zeroes of the Taylor polynomial of $e^x$, the real roots approach $-\infty$ as you approach $e^x$.
Comment: It is unclear  that what *statement* one is proving in the post.
Comment: @Simple art : yes I am aware of that , but that kinda justifies Some limit processes to exp and its zero's but ofcourse makes all formula's for the number of zero's or the value of zero's etc wrong - since there is no finite one -. At best we get a division by 0 hinting at infinity ...
Comment: @Eric yes certainly but we know an entire function is the limit of its Taylor polynomials and also that lim ( A + B + ... ) is not NEC equal to lim A + lim B + ... So that does not explain all.
Comment: Also we know lim a_n = lim a_{n-1}
Answer: You have started by assuming $r$ is a zero of the polynomial $$g_n(z)=a_0 + a_1z + \cdots + a_{n-1}z^{n-1} + z^n.$$  You prove some statements that are true about any such root.  Then you "take the limit as $n\to\infty$", and seem to be concluding that similar statements must be true of any zero of the function $f(z)=\sum_{k=0}^\infty a_kz^k$.  This doesn't follow at all though.  If $r$ is a zero of $f(z)$, then it is probably not a zero of $g_n(z)$ for any $n$ (let alone for all $n$), so what you have proven about zeroes of $g_n(z)$ does not tell you anything about $r$ (at least not in any obvious way).
Moreover, it is not even true that $g_n(z)$ converges to $f(z)$ as $n\to\infty$.  What is true is that $f_n(z)=a_0 + a_1z + \cdots + a_{n-1}z^{n-1}$ converges to $f(z)$, but $g_n(z)=f_n(z)+z^n$ will be very far from $f_n(z)$ if $|z|>1$ and $n$ is large.  So even as a nonrigorous heuristic argument, you are doing the wrong calculation.

False proof about entire functions !?


Generating Image from text in php - not generating on my online host?

Question: I'm generating an image out of text using php. My code works perfectly on my localhost and the text is generated fine. However on my online host it doesn't generate the whole text just bits and pieces of it. Like if I were to pass the text 'This is some text' to it - it would generate just maybe an S or t.
The code is fine as it works perfectly on my localhost but doesn't run on the online host. It cant be that gd isnt on the host else it would not even generate part of the image.
WHats going on here :(

UPDATE
This is the GD CONfig on teh server - I don't think there is anything wrong with it
<code>gd
GD Support  enabled
GD Version  bundled (2.0.34 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.2.1
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support     enabled
PNG Support     enabled
WBMP Support    enabled
XBM Support     enabled
</code>
I'm just turning email addresses and fone numbers into one image. Heres an image of what the text should look like:

But this is what its rendering on the online:

UPDATE
I just found out something weird. If I try to create an image out of the text 'P P' it should create the following image which it does on my localhost.

But on the online server its creating the image as so - the space is humongous and distorted. Could this be a hint as to why is it not rendering the text as it should.

Please guys I need help here urgently :(.
Comment: What operating system on the server?
Comment: Can you provide example images? One correct and one broken?
Comment: I added the pictures! Please tell me whats wrong here!
Answer: see if the GD library  is install in server Correctly
Answer:
Is the proper font installed on the host?
Is the content-encoding of the image set properly?
Answer: Compare your local phpinfo() to the live phpinfo() and look for differences.
Turn on full error reporting in the image generation script:
<code> ini_set("display_errors","2");

 error_reporting(E_ALL);
</code>
Then run it directly by pointing your browser at the URL that renders the image.
Comment: DOne that but can't seem to find any errors being reported :( - check my post for update!