Showing that a Gamma distribution converges to a Normal distribution

Question: Consider $G = \operatorname{Gamma}(p)$. As $p$ goes to $\infty$, the Gamma becomes more and more bell-shaped. How do I show that $\frac{G - p}{\sqrt{p}} \to Z \sim N(0,1)$ as $p \to \infty$?
I started with the CDF of the Gamma and began taking the limit, but it got very messy.
Comment: Have you considered using the MGF? (or the CF) . It's often a convenient strategy. Perhaps consider a Taylor-type expansion.
Comment: @StubbornAtom it doesn't help that Z is used to represent two distinct things in the question. It would be necessary to fix that first
Comment: Alternative to using MGF, you can write $G_p$ as being equal in distribution to the sum of $p$ i.i.d $exp(1)$ random variables. The result is then immediate by CLT.
Comment: The brute-force analysis isn't that difficult if you plan it out.  Expand the log of the (unnormalized) PDF of $Z$ in a Maclaurin series.  It will equal $$f_Z(z) = -\frac{1}{\sqrt p} + \left(\frac{1}{2p} - \frac{1}{2} \right)z^2 + O(p^{-1/2})O(z^3).$$ Thus its exponential is $e^{-z^2/2}$ times an expression that is very close to $1.$ Justify taking the limit under the integral sign and you're done.
Comment: I have not. My instructor suggested this as a fun practice problem using only the CDF and PDF.
Comment: @Ferdi You're always free to use any resources you like to answer a question.  It's a bit of a curiosity that the *statement* of the present question *answers* the one on the Math site and the statement of the one on the Math site answers the present question!
Comment: @purpleostrich you can (and this may be what StubbornAtom is hinting at), write down the density of the standardized gamma variate, and then consider what happens to the density as the shape parameter becomes large (or, as may be more convenient) to look at its log. Such an approach may require some care if you want it to be more than motivation of the result.
Comment: I was asking the exact form of the density of the Gamma(p) random variable. Regardless, working with MGFs would be the easier route.
Comment: @glen_b Following up on StubbornAtom's comment, it appears working with the integral PDF for the Gamma is quite messy.
Comment: Could you confirm that the pdf of the Gamma(p) variable is

$$f(x)=\frac{e^{-x}x^{p-1}}{\Gamma(p)}\mathbf1_{x>0}\quad,\,p>0\qquad?$$
Comment: With only one parameter, that would be the intent, yes.
Comment: @purpleostrich Working with the CDF at least would be messy because we have an incomplete gamma function at hand.
Comment: Apparently this question has already been answered on a sister side (Mathematics stack exchange). You can find the solution here: [Proof verification that gamma distribution converges in distribution to a standard normal. Shorter solution?](https://math.stackexchange.com/questions/2139370/proof-verification-that-gamma-distribution-converges-in-distribution-to-a-standa) Shall I copy the solution and write it down here?
Comment: Xiaomi your result with CLT is very easy, thanks. Taking the sum of the independent exponentials is a great idea.
Comment: @whuber: Sorry I should have asked that on meta. Thank you for converting it to a comment.
Comment: The CLT is useful for answering the question on the Math site, because it indicates what the standardizing values ought to be.  But for answering this one you either need a relatively strong version of the CLT (for differently distributed variables) or you have to be content with taking the limit over a lattice of values of $p.$ Using the exponential distribution limits you to integral values of $p,$ which isn't quite enough to draw the conclusion you want.
Comment: @whuber are they not all identically distributed if they come from independent Exp(1)?
Comment: They are--but then you're stuck with values of $p$ that are positive integers.  That says absolutely nothing about non-integral values of $p$!   One way out is to represent a $\Gamma(p)$ random variable as the sum of $\lfloor p\rfloor$ exponential variables and a $\Gamma(p - \lfloor p\rfloor)$ variable: and therein lies the problem with the usual Central Limit Theorem, because it does not have an exponential distribution.
Comment: Hmm... I'm still not really sure how I would show this simply @whuber Is there perhaps a good way to show that for high enough p that a p between two integer p's produces an almost identical curve?
Comment: There is.  Letting $f_p$ be the density function of $(G-p)/\sqrt{p},$ you could expand the log ratio of $f_{p+\epsilon} / f_p$ around $(y,p)=(0,\infty)$ as $$\log(f_{p+\epsilon}(y) / f_p(y))=\frac{\epsilon}{2}\left(2 p^{-2} + y p^{-3/2}\right) + O(y^2)O(p^{-3/2}).$$Use this to show that for suitably large $p,$ the graphs are extremely close for all sufficiently small $|y|$ (where almost all the probability is located) and for $|\epsilon| \le 1.$
Comment: Answer given as part of this [answer](https://stats.stackexchange.com/a/330952/99274).
Answer: This answer is part of a previous answer with a link here. That portion of the previous answer is copied over here so that one can see that the question above has been answered, however, as the answer here formed only part of an answer to a different question, it might not have been noticed in the different context of the question above. Text as follows:
A more direct relationship between the gamma distribution (GD) and the normal distribution (ND) with mean zero follows. Simply put, the GD becomes normal in shape as its shape parameter is allowed to increase. Proving that that is the case is more difficult. For the GD, $$\text{GD}(z;a,b)=\begin{array}{cc}
&
\begin{cases}
 \dfrac{b^{-a} z^{a-1} e^{-\dfrac{z}{b}}}{\Gamma (a)} & z>0 \\
 0 & \text{other} \\
\end{cases}
\,. \\
\end{array}$$
As the GD shape parameter $a\rightarrow \infty$, the GD shape becomes more symmetric and normal, however, as the mean increases with increasing $a$, we have to left shift the GD by $(a-1) \sqrt{\dfrac{1}{a}} k$ to hold it stationary, and finally, if we wish to maintain the same standard deviation for our shifted GD, we have to decrease the scale parameter ($b$) proportional to $\sqrt{\dfrac{1}{a}}$.
To wit, to transform a GD to a limiting case ND we set the standard deviation to be a constant ($k$) by letting $b=\sqrt{\dfrac{1}{a}} k$ and shift the GD to the left to have a mode of zero by substituting $z=(a-1) \sqrt{\dfrac{1}{a}} k+x\ .$ Then $$\text{GD}\left((a-1) \sqrt{\frac{1}{a}} k+x;\ a,\ \sqrt{\frac{1}{a}} k\right)=\begin{array}{cc}
 &
\begin{cases}
 \dfrac{\left(\dfrac{k}{\sqrt{a}}\right)^{-a} e^{-\dfrac{\sqrt{a} x}{k}-a+1} \left(\dfrac{(a-1) k}{\sqrt{a}}+x\right)^{a-1}}{\Gamma (a)} &  x>\dfrac{k(1-a)}{\sqrt{a}} \\
 0 & \text{other} \\
\end{cases}
 \\
\end{array}\,.$$
Note that in the limit as $a\rightarrow\infty$ the most negative value of $x$ for which this GD is nonzero $\rightarrow -\infty$. That is, the semi-infinite GD support becomes infinite. Taking the limit as $a\rightarrow \infty$ of the reparameterized GD, we find
$$\lim_{a\to \infty } \, \frac{\left(\frac{k}{\sqrt{a}}\right)^{-a} e^{-\frac{\sqrt{a} x}{k}-a+1} \left(\frac{(a-1) k}{\sqrt{a}}+x\right)^{a-1}}{\Gamma (a)}=\dfrac{e^{-\dfrac{x^2}{2 k^2}}}{\sqrt{2 \pi } k}=\text{ND}\left(x;0,k^2\right)$$
Graphically for $k=2$ and $a=1,2,4,8,16,32,64$ the GD is in blue and the limiting $\text{ND}\left(x;0,\ 2^2\right)$ is in orange, below


Weird characters in log file during outage (^@^@)

Question: We have apache serving files and proxying requests through to our api and today there was a new thing in the logs that I can't explain.
I'm investigating an issue that caused downtime and looking at the access logs I can see the last request and the first one that worked after it got back online but in between there's a couple lines with @s and ^s that I can't explain. I'm looking for a an explanation of what could have caused these characters to be printed in the middle of the access log.
The only thing I can guess is there was a hardware error that could somehow have corrupted the next entry that was in the middle of being written in that file. Not sure what else I can look for here?
[29/May/2020:12:04:00 +0000] "PUT /api/orders/2657675?cacheBuster=1590753840180 HTTP/1.1" 200 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
[29/May/2020:12:17:47 +0000] "GET /favicon.ico HTTP/1.1" 200 5430 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 13_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/79.0.3945.73 Mobile/15E148 Safari/604.1"

Answer: ^@ is a typical visualization of the NUL (0x00) byte.
It's almost certainly the tool that you use to display the file that is visualizing a sequence of NUL bytes as this sequence of ^@, while the file itself has no ^ or @ characters there.
(Typically inverted colors are used for such visualizations of otherwise unprintable characters, just to highlight that there is something special going on.)
Probably this log file was being written just as the machine was abruptly turned off, leading to the file ending up with a sequence of NUL bytes at the very end as a result of some filesystem specific handling of a write operation that was interrupted part-way through.
Comment: Thanks for that explanation. It was what we were thinking as well but that first line there in your answer is very helpful, thanks!


Problem with upgrading because an unmigrated module

Question: I am trying to migrate a Drupal 8 site to Drupal 9. Though most of the migrations have gone easily, this site breaks because it uses the Video module, which hasn't been updated for Drupal 9.
Specifically, the problem happens when I try to run drush updb. I geet this error message.

Unable to determine class for field type 'video' found in the 'field.storag  e.paragraph.field_video_item' configuration

What would the steps needed to by-pass the problem be?
The module seems quite abandoned; I don't keep my breath waiting Drupal 9 version to be created.
Answer: I assume you are talking about the Video module.
For any module that does not have a Drupal 9 release, you basically have three options, in order of difficulty (easy to hard):

Find patches/a fork of the module (usually in the issue queue) that supports Drupal 9.
Update the module to be compatible with Drupal 9 yourself.
Find a replacement module that is compatible with Drupal 9 and migrate your data to that, then uninstall the incompatible module.

For #1, looking through the issue queue, there are a few patches you could try:

https://www.drupal.org/project/video/issues/3137499
https://www.drupal.org/project/video/issues/3174989
https://www.drupal.org/project/video/issues/3101969

For #3, Drupal now has excellent Media support in core, so if possible, I would try to migrate your video data to core media, as that would guarantee you an easy upgrade path to Drupal 10 and beyond.
Answer: Well, I got over the problem by just marking the video module Drupal 9 compatible. It probably isn't very good/healthy a solution but got me over the obstacle and I can try to implement now the similar functionality with Media core support.
As I haven't worked earlier with the site I have to find out how heavily the video module is used in the site but at least so far hasn't hit my head into a stone.
If someone comes here but doesn't know how to mark the module Drupal 9 compatible it's by adding the following line to the video.info.yml
core_version_requirement: ^8 || ^9

Of course, that doesn't actually mean that the module works, only that Drupal thinks it has found a compatible version of the module and can go on updating the database.
Thanks Patrick for the pointer
hank


What would be a general meaning of logarithm in real world? In physics? In geometry?

Question: For example, we all know how enormous and wide spread the application of derivatives can be. Speed-acceleration, curve-tangent and so on. Any dynamic system has their particular examples.
Is there a similar examples for logarithm? What comes to your mind?
I can only think about tree-related situations. Like, building a tree with n leafs, it will consist of log(n) levels. And other cases, with diviving and branching.
I would appreciate to see any ideas :)
Comment: Look a little harder: https://en.wikipedia.org/wiki/Logarithm#Applications
Comment: Try looking at Wikipedia for a start.
Comment: @JpMcCarthy sure I did, nothing general there
Comment: Slide rules !!!
Comment: How many bytes are needed to store an arbitrary integer between 0 or 1000000? Take logarithm with base 2.
Answer: The logarithm is the inverse of the exponential function, so any practical problem that require exponential , also require logarithm.
There a lot of such problems. As starting examples You can search for:
radioactive decay ( in physics)
Interest rate ( in economy)
Population grow ( in biology)
And note also that logarithms was the instrument of calculus before computers.  E.g. : almost all the astronomical knowledges about the orbits of planets of the 1700-1800 and beginning 1900, comes from calculations made by means of logarithms.
Comment: Those are good examples to think about, thank you
Comment: And more: the sensibility of our senses is logarithmic. The scale of sound intensity ( decibel) is logarithmic. The scale of stars brightness (magnitude) is logarithmic.


OpenCV for Unity3D: Xcode signing error for opencv2 lib

Question: I would need help to solve the error, Xcode is firing, when building the application, which includes the OpenCV library for Unity.
Error loading /var/containers/Bundle/Application/AAD49F35-2BE7-432D-85D1-81B2489C23F5/ubs.app/Frameworks/UnityFramework.framework/UnityFramework:  dlopen(/var/containers/Bundle/Application/AAD49F35-2BE7-432D-85D1-81B2489C23F5/my.app/Frameworks/UnityFramework.framework/UnityFramework, 265): Library not loaded: @rpath/opencv2.framework/opencv2
Referenced from: /private/var/containers/Bundle/Application/AAD49F35-2BE7-432D-85D1-81B2489C23F5/my.app/Frameworks/UnityFramework.framework/UnityFramework
Reason: no suitable image found.  Did find:
/private/var/containers/Bundle/Application/AAD49F35-2BE7-432D-85D1-81B2489C23F5/my.app/Frameworks/UnityFramework.framework/Frameworks/opencv2.framework/opencv2: code signature in (/private/var/containers/Bundle/Application/AAD49F35-2BE7-432D-85D1-81B2489C23F5/my.app/Frameworks/UnityFramework.framework/Frameworks/opencv2.framework/opencv2) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed.
I tried to enable "disable library validation" in the signing settings for each target. Also under the UnityFramework build target I set the opencv.framework to "embed without signing".
Not sure what Apple needs to make this run. It seems they changed something again (I build the application months ago without problems).
Thank you very much!
Answer: For all those guys who had the same problem:
In my case I could fix it in xcode with:

In the section "Frameworks, Libraries, and Embedded Content" you´ll have to include the opencv2.framework by your own. It wount appear, if you search it on the "+" list, so you will have to click the "+" and add it manualy with the Add Other dropdown menu on the bottom. Search for the opencv2.framework folder in the build folder under frameworks -> OpenCVForUnity -> Plugins -> IOS -> opencv2.framework. Select this folder, add it and chose "Embed & Sign" in XCode.

In the build settings disable "Enable Bitcode" for each Targets.

Of course check for the camera (Yes), microphone (depend on your app) and localization (depend on your app) permissions in the p.list file.

Hope this helps if you had the same problem.
Best,
Thomas
Comment: This worked for me after trying a lot of solutions, thank you.
Answer: An issue for Catalin and Big Sur is that he .a file is automatically removed unless you go to Mac System Preferences and allow it in Security + Privacy


How do I make Excel NOT convert the dates to date format

Question: I did this table in Excel, but this is really frustrating: in certain cells, unpredictable to me, it doesn't let me just write 01/03/2019. Instead, it automaticly transforms it to 1/3/19. To be honest, I don't mind the first part; the real issue is that I need it to be 2019, and not 19, since I'm saving it in .csv format and not keeping it in .xlsx.
Therefore, what I need is a way to make Excel maintain exactly what I wrote without transforming it in Date format (changing it to General just gives that format with the number of days since 1900, 43468), or at least, I need the year to stay as 2019.
This is the colum with the dates:
1
19/05/2009
2
19/05/2010
3
19/05/2011
4
19/05/2012
5
19/05/2013
6
19/05/2014
7
19/05/2015
8
19/05/2016
9
19/11/2016
10
16/11/2018
11
20/12/2018
12
"01/03/2019"
13
17/7/2019
14
"12/09/2019"
15
30/10/2019
16
"12/12/2019"
17
"11/1/2020"
18
19/02/2020
19
20/04/2020
20
17/05/2020
21
13/06/2020
22
"02/07/2020"
23
13/08/2020
24
13/09/2020
25
15/10/2020
26
15/11/2020
27
19/09/2009
28
19/01/2010
29
19/09/2010
30
19/11/2010
31
19/03/2011
32
19/05/2011
33
19/09/2011
34
19/05/2012
35
19/09/2012
36
19/05/2013
37
19/10/2013
38
19/05/2014
39
19/05/2015"
40
19/05/2016
41
19/11/2016
42
19/01/2019
43
19/08/2020
44
19/10/2008
45
19/01/2009
46
19/04/2009
47
19/07/2009

I temporariyl put in quotation marks (") as placeholders, because they keep the text to be converted to Date, but I don't want to keep them.
Comment: Change the format to dd/mm/yyyy.
Comment: It already is.... At least, that's how I meant it...
Comment: Oh, that's why... It's the ones that can be interpreted as mm/dd/yyyy by Excel...
Answer: If you put a ' (quote) string before anything and it gets displayed as a string.
Comment: I know it does; that's why I put it. WHat I want is to NOT put anything and just have the date there.
Answer: Ok, based on a comment from @BigBen, I got it: I selected the cells and did Format Cells (Format > Cells or Right Click and it's almost at the bottom or Cmd + 1. Then I wen to Date and selected the format 3/14/2012 instead of *3/14/12.


Wave tool used to evaluate web content for accessibility issues giving Broken ARIA reference errors

Question: I am trying to fix Broken ARIA reference errors notified by Wave tool in chrome for my custom module web pages and Drupal 8 core login form. Sample error in login form is mentioned below for username field. How to fix these issues. For every user control I have this site wide.
Error at username text box:
*aria-describedby="edit-name--description", aria-required="true"
(An aria-labelledby or aria-describedby reference exists, but the target for the reference does not exist.)
I am not able to find aria-describedby attribute itself in the code for the controls. So, I am not sure how to fix them.
Answer: The attribute is only added if the element has a description. This is the code from the FormBuilder that does it:
// Add the aria-describedby attribute to associate the form control with its
// description.
if (!empty($element['#description'])) {
  $element['#attributes']['aria-describedby'] = $element['#id'] . '--description';
}

The idea being that when the input is rendered in form-element.html.twig, the description is rendered alongside it with a matching ID. For example this is how the core stable theme handles it:
{% if description_display in ['after', 'invisible'] and description.content %}

    {{ description.content }}

{% endif %}

So it seems likely there aren't that many possible sources for the problem. These are the only ones I could come up with:

You're using a core theme, or a derivative of one which still renders the description in form-element.html.twig, and something in the system is setting the description display to a value other than 'after' and 'invisible', causing it not to be rendered.
You're using a non-core theme, which overrides form-element.html.twig, and doesn't render the description.
Something in the system is changing either the value in the input's aria-describedby attribute, or the ID of the description element in the element template, causing them not to match.
Some combination of the above.

Hopefully that's enough to go on.
Comment: My case is the second one.  Can you suggest what should I be looking into to fix this.


como imprimir tabela em duas colunas?

Question: Tenho uma tabela com mais linhas que cabem em uma página A4, mas, se dividida em duas podem ser impressas em uma página, com duas colunas.
Já consultei outros sites e obtive ajuda, mas não resolveu.
Anexo o código que utilizei em minha tentativa.
Se puderem me ajudar, agradeço muito.

`Sub ImprimeLista()

'Imprime Lista do Mercado

Dim BlocPrint As Range
Dim FirstRow As Integer
Dim LastRow As Integer
Dim LastCol As Integer

    Sheets("Compras").Select

    Cells(1, 1).Select

    LastCol = ActiveSheet.Cells(4, 1).End(xlToRight).Column
    FirstRow = Selection.Row
    LastRow = Cells(Rows.Count, LastCol).End(xlUp).Row

    Set BlocPrint = Range(Cells(FirstRow, 1), Cells(LastRow, LastCol))

    With ActiveSheet.PageSetup
        BlocPrint.Select
        .FitToPagesWide = 1
        .FitToPagesTall = 2
        Selection.PrintOut Copies:=1, Collate:=True
        Range("A1").Select
    End With

End Sub

Comment: Oi Bautto! Como vai? Por favor, poderia inserir uma imagem mostrando como a sua planilha está estruturada, indicando, principalmente, qual é a última linha preenchida para que eu possa te ajudar? Obrigada!
Comment: Olá, Andréa. Segue o link para o arquivo.
Comment: Nele tem 2 planilhas, a primeira (Tabelão) é a entrada de dados e a segunda(Compras) é a que preciso imprimir, que resume os itens a serem comprados. Agradeço seu interesse. https://www.sendspace.com/file/ivezqi
Comment: Oi! Eu testei o código na planilha que você me enviou e a tabela foi impressa em uma única página. Eu testei duas vezes: na primeira eu não alterei as configurações padrão da impressão e, na segunda, eu alterei e nos dois casos o resultado foi o mesmo. Você esperava algum resultado diferente? https://www.sendspace.com/file/zula7n
Comment: A impressão sai em uma única página. O que quero é que saia em duas colunas, pois em uma só fica muito reduzida a impressão, dificultando a leitura. Estou tentando fazer uma rotina para dividir a impressão, por exemplo, imprimir as primeiras 60 linhas em uma coluna e as restantes em outra, mas estou encontrando dificuldade na configuração da impressora pelo VBA.
Answer: Oi!
Eu fiz uma leve gambiarra, mas acredito que traz o resultado desejado.
Como, pela configuração da impressão, não é possível ajeita para que imprima duas colunas, a minha ideia foi criar uma aba auxiliar em que a lista de compras seja copiada e impressa tal como desejado.
Segue o código:
Sub ImprimeLista()

'Imprime Lista do Mercado

Dim BlocPrint As Range
Dim FirstRow As Integer
Dim LastRow As Integer
Dim LastCol As Integer
Dim W       As Worksheet
Dim WB      As Worksheet

Application.DisplayAlerts = False

    Sheets("Compras").Select

    Cells(1, 1).Select

    LastCol = ActiveSheet.Cells(4, 1).End(xlToRight).Column
    FirstRow = Selection.Row
    LastRow = Cells(Rows.Count, LastCol).End(xlUp).Row

    'Adiciona uma nova aba e copia a tabela para ela
    Sheets.Add After:=Sheets(Sheets.Count)
    ActiveSheet.Name = "Impressão"
    Set WB = Sheets("Impressão")
    Set W = Sheets("Compras")

    W.Select

    'Seleciona a primeira metade
    Set BlocPrint = W.Range(Cells(FirstRow, 1), Cells((LastRow / 2), LastCol))
    BlocPrint.Select
    Selection.Copy
    WB.Select
    WB.Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False
    Application.CutCopyMode = False

    'Seleciona a segunda metade
    W.Select
    Set BlocPrint = W.Range(Cells((LastRow / 2), 1), Cells((LastRow), LastCol))
    BlocPrint.Select

    Selection.Copy
    WB.Select
    WB.Range("G4").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False
    Application.CutCopyMode = False

    'Coloca um cabeçalho na segunda coluna
    WB.Range("A1:E3").Select
    Selection.Copy
    WB.Range("G1").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    Range("A1:E1").Select

    'Ajeita as colunas com produtos
    WB.Range("A:A").EntireColumn.AutoFit
    WB.Range("G:G").EntireColumn.AutoFit
    WB.Columns(6).ColumnWidth = 2

  'Configura a impressão
   With ActiveSheet.PageSetup
        WB.Select
        WB.Range("A:G").Select
'        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = False
        Selection.PrintOut Copies:=1, Collate:=True
        Range("A1").Select
    End With

    'Seleciona a planilha Compras e exclui a planilha Impressão
    W.Select
    W.Range("A1").Select
    WB.Delete

Application.DisplayAlerts = True

End Sub

O resultado final foi esse: https://www.sendspace.com/file/6psv97
Espero que resolva.
Comment: Andréa, bom dia. Gostei muito de sua solução, principalmente por usar o VBA. Eu já tinha arrumado também uma alternativa, porém o que fiz foi bem manual, transcrevendo a fórmula que compila a lista para a outra metade da planilha, e dividindo as linhas, sem programação VBA. Resolveu também, mas seu trabalho ficou ótimo. Grato pelo auxílio.

como imprimir tabela em duas colunas?


Why would R-Squared decrease when I add an exogenous variable in OLS using python statsmodels

Question: If I understand the OLS model correctly, this should never be the case?
<code>trades['const']=1
Y = trades['ret']+trades['comms']
#X = trades[['potential', 'pVal', 'startVal', 'const']]
X = trades[['potential', 'pVal', 'startVal']]

from statsmodels.regression.linear_model import OLS
ols=OLS(Y, X)
res=ols.fit()
res.summary()
</code>
If I turn the const on, I get a rsquared of 0.22 and with it off, I get 0.43. How is that even possible?
Answer: see the answer here Statsmodels: Calculate fitted values and R squared
Rsquared follows a different definition depending on whether there is a constant in the model or not.
Rsquared in a linear model with a constant is the standard definition that uses a comparison with a mean only model as reference. Total sum of squares is demeaned.
Rsquared in a linear model without a constant compares with a model that has no regressors at all, or the effect of the constant is zero. In this case the R squared calculation uses a total sum of squares that does not demean.
Since the definition changes if we add or drop a constant, the R squared can go either way. The actual explained sum of squares will always increase if we add additional explanatory variables, or stay unchanged if the new variable doesn't contribute anything,


Formatar data no Android e SQLite

Question: Estou com dificuldade em fazer o processo de setar a data atual do meu banco SQLite no atributo tipo java.util.Date do meu objeto.
A data do SQLite vem no formato "yyyy-MM-dd". Estou tentando converter para o formato aceito no tipo java.util.Date e que me permita utilizá-lo no meu Adapter porém ao rodar a aplicação está me retornando um erro dizendo que a data está nula. Realmente quando debuguei o App vi que a data não está sendo setada.
Segue a parte do código.
        Date data = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        String dataTeste = cursor.getString(1);
        try {
            data = dateFormat.parse(dataTeste);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        v.setDataVenda(data);

Obs: Na variável dataTeste o valor que está sendo preenchido é "2015-11-15".
Answer: Mude a linha que estabelece o formato:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Coloquei no GitHub para referência futura.

Formatar data no Android e SQLite


Nginx check for HttpGzipModule

Question: I have nginx+passenger on my vps but I think I don't have the HttpGzipModule installed, two questions:

How to verifiy if it is installed?
How to install it, have I to install nginx again? Is there a procedure to follow for a newbie?
Comment: What distro are you using?
Answer: If you haven't installed nginx with some very specific configurations, then there are pretty good chances that gzip module is already installed, as it comes under the core modules and installed by default.
This command will list all the configured modules:
nginx -V
But the main thing is that, byt default it is not on. You need to put the following configuration to enable it.
Use this in your ngnix config file, which usually is present at /etc/nginx/nginx.conf
gzip  on;
gzip_vary on;
gzip_proxied any;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/javascript text/xml application/xml application/rss+xml application/atom+xml application/rdf+xml;
gzip_buffers 16 8k;
gzip_disable "MSIE [1-6].(?!.*SV1)";

This should enable the gzip support in your nginx.
You can check the same by using the Firebug/curl and checking the headers and it should show something like this:
Accept-Encoding: gzip,deflate
Content-Encoding: gzip

Nginx check for HttpGzipModule


Which variables to keep in my analysis based on loadings from PCA?

Question: Could someone please explain me how I should decide which variables to keep in my analysis based on loadings from PCA. The output is:
    Comp.1     Comp.2    Comp.3  Comp.4     Comp.5
a   0.0281003 0.37882295 0.2935517 0.02025596 0.11199220
b   0.2019940 0.21168386 0.2398182 0.37883484 0.03540004
c   0.2545871 0.20163264 0.1459563 0.07187896 0.39797528
d   0.2774044 0.05867002 0.1859529 0.06134311 0.41428056
e   0.2379143 0.14919053 0.1347208 0.46768713 0.04035192

Importance of components:
                      Comp.1    Comp.2    Comp.3     Comp.4     Comp.5
Standard deviation     1.5809667 1.0987927 0.8806842 0.63815856 0.33218647
Proportion of Variance 0.4998911 0.2414691 0.1551209 0.08144927 0.02206957
Cumulative Proportion  0.4998911 0.7413602 0.8964812 0.97793043 1.00000000

Does this mean that variable a is not important and I can drop it? Is there any method for making this decision?
Comment: Too scarce information (and effort). Keep for what? "Interpretation" - in what sense? Important - how? Please pardon me for an advice for you to read some textbook on PCA first.
Comment: It's hard to give advices without knowing why you want to drop any variables at all. But note that variable `a` contributes strongly to PC2, which has variance comparable to PC1.
Answer: Generally this depends on what type of data you are looking at. I would find similar studies in your field and cite them as examples of where to choose loading cutoffs. In environmental data which is very noisy, these limits tend to be lower whereas in controlled laboratory experiments they will be higher. Generally a loading cutoff should eliminate several of the variables from a PC but you don't have that many to begin with.
Based on the standard deviation it looks like PC1 and PC2 could be considered significant, with a contributing strongly to PC2 (relative to the other variables). Let's say you chose your cutoff as $.25$ - PC1 would be related to variables c and d, while PC2 would be related to variable a alone. In other words, you should not throw a away - it looks like it has a potentially strong association with PC2 and has the highest loading value of any variable on the first two PCs.
Answer: Without any other information, yes, if you need to drop a variable, that would be $a$.
However, in order to really know, you need e.g. confidence intervals. You could obtain those from a jack-knifing procedure. If your confidence intervals cross zero, you have reason to remove those corresponding variables.


JQuery if statement is not running

Question:  $("input[type=checkbox]").click(function(){
    alert("clicked");
    if($('#result').html().length) {
           $('button[type="submit"]').attr('disabled','disabled');
        } else { $('button[type="submit"]').removeAttr('disabled'); }
  });

The above code my if statement is not running.
If I run the if statement in console it run fine but as soon as I nest it in the click function. the alert shows up but the my submit box is not greyed out.
Anyone know whats wrong with my code.
Comment: Is it wrapped with a `$(document).ready()`, what element is `#result`? Is the `alert()` executed?
Comment: Try using `prop` method:

     `$('button[type="submit"]').prop('disabled', true);`
Comment: if i run the code separately in console it works. But as soon as I nest the codes this part doesn't run $('button[type="submit"]').attr('disabled','disabled');
Comment: Can you create a jsFiddle showing the problem?
Answer:
Make sure you wrapped your code in jQuery ready
If $(selector) doesn't match any DOM node it will return undefined when calling .html. Therefore remove the .length. (undefined.length -> throws an error)
Also change .html to .text. You can add $.trim() if you will remove whitespaces.
Use prop instead of attr if you are using jQuery 1.6 or higher.

jQuery(function($) {
    $("input[type=checkbox]").click(function(){
        alert("clicked");
        if( $.trim($('#result').text()) ) {
            $('button[type="submit"]').prop('disabled', true);
        }
        else {
            $('button[type="submit"]').prop('disabled', false);
        }
    });
});

You can minimize your code to this:
jQuery(function($) {
    $("input[type=checkbox]").click(function() {
        // Make sure myTest is an boolean:
        var myTest = Boolean( $.trim($('#result').text()) );
        // Send myTest as 2th argument:
        $('button[type="submit"]').prop('disabled', myTest);
    });
});

Comment: Could be taken a little further: `$('button[type="submit"]').prop('disabled', function(){ return Boolean($.trim($('#result').text())) ? true : false; });` (But I'd think that `!!$.trim(/*...*/)` would be about as reliable/easy.)
Comment: @DavidThomas I used `Boolean()` to not take focus off the main part of the script. I think that `!!` wouldn't be that clear for all.
Answer: use this
if($('#result').text()=='') $('button').prop('disable',true);
else $('button').prop('disable',false);

JQuery if statement is not running


Find relevant string within string

Question: I want check whether particular string is present within string or not. And i want to get position matching.
For Eg:
$actual_string = "red";
$searching_string = "green red yellow";

As we know , above searching string "red" matches with actual string, and position matched is 7th(including space).
$output = 7;//red matched at 7th position

Is is possible to get above requirement? Please help
Comment: The amount of sarcasm in these comments is too dam* high
Comment: @DKasipovic Almost nothing is impossible for PHP(and other language). If there is no strait way , start a long way. For this , I'll go with explode(split strings into array) then search if 3arrays in order have r,e,d. That's TOTALLY POSSIBLE
Comment: @PoomrokcThe3years you got me now. I really do not have appropriate response.
Comment: @All , be nicer to this question please.
Comment: Hai to all thanks for your valuable comments. I think there is no way to get solution for this :(. Googled a-lot. Any other ways to do this?
Comment: @ThangapandiyanMD: see if you can get something with [strpos with regex](http://stackoverflow.com/questions/8609765/using-regex-in-a-string-for-strpos)
Answer: Try with strpos like
echo strpos($searching_string, $actual_string);

But it will consider the string position that starts from 0.So you need to +1 for the position to get the correct position.
Comment: Thanks for your answer, it does't worked in my case. Because above returns only full word is matched.In my case,any searching string which matches within actual string.
Best eg: $actual_string = "red/blue/green";
         $searching_string = "green black";
Comment: @ThangapandiyanMD, then your question is not clear enough. This answer is correct for what you asked. Your comment here only confuses matters.

Find relevant string within string


$1 + \frac 64 + \frac {14}8 + \frac {30}{16} + \ldots$

Question: I have to calculate the sum upto n terms of the following:
$$1 + \frac 64 + \frac {14}8 + \frac {30}{16} + \ldots$$
I found the general term as:
$$T_n = \frac {an^2+bn+c}{2^{n}},$$ where a, b and c are determined as follows:
$$a+b+c=2; 4a+2b+c=6; 9a+3b+c=14.$$
Solving and applying:
$$T_n = \frac {2n^2-2n+2}{2^{n}} = \frac {n^2-n+1}{2^{n-1}}.$$
Now, how to compute:
$$\sum_{k=1}^{n} \frac {k^2-k+1}{2^{k-1}}$$
Comment: The general term of your series seems wrong
Answer: The general term of the sum is wrong check for $k=4$ for example, actually the sum of the $N$ first terms is :
$$1 + \frac 64 + \frac {14}8 + \frac {30}{16} + \ldots=\sum_{k=1}^{N} \frac {2^{k+1}-2}{2^k}=\sum_{k=1}^{N} \frac {2(2^{k}-1)}{2^k}\\=\sum_{k=1}^{N} \frac {2^{k}-1}{2^{k-1}}=\sum_{k=1}^{N} 2-\sum_{k=1}^{N} \frac {1}{2^{k-1}}=2N+\left(\frac 1 2\right)^{N-1}-2$$
Comment: Should it be $2N+(\frac{1}{2})^{N-1}-2$?
Comment: @SquirtleSquad Thanks :)
Answer: How about choosing $$T_n=\frac{\frac23n^3-2n^2+\frac{16}3n-2}{2^n}$$ whose elements match the few elements you mentioned and $$\sum_{n=1}^{\infty}T_n=14.$$
Here is an interesting discussion.


How to add Shipping method for commerce flat rate module?

Question: i am working on drupal commerce's "shipping" part, i want to create two methods for shipping as
1.Free Shipping
2.Express 2-day Shipping
for USA .
For "free shipping" condition is if order total is greater than $100 then we can use "free shipping" else it should apply rate $4.
for "Express 2-day Shipping" condition is if order total is less than $140 then we  can cost $12 else it is free.
Answer: The Rules module integrates with Drupal Commerce in order to handle this type of requirement. There are many video tutorials available that explain how to setup various shipping rules.
There is also a module called Conditional Rules that may be useful if you need to have branching logic in your rules.
In this case I think you would only need two rules:

Conditions: type of shipping == "Free shipping" AND order total > $100 Actions: shipping cost = $0
Conditions: type of shipping == "Express" AND order total > $140 Actions: shipping cost = $0

You would set the default pricing for the "Free shipping" to $4 and the for the "express" to $12. The default prices would be overridden by the Rules in those two cases.
Comment: its require $ to cents change


Subfields of $\mathbb{Q}(\sqrt{2},\sqrt{3})$

Question: Suppose one doesn't know any Galois theory, but they are familiar with the basic theory of field extensions. Then how would one justify the following picture?

I'm pretty sure they're just saying these are the known subfields, and there could be more but they just write down those ones (which seems weird, which is why I'm asking). Or have they deduced that this is a comprehensive list of subfields just by using basic theory? This occurs on page 573 of Dummit and Foote's Abstract Algebra.
Answer: $\mathbb{Q}(\sqrt{2},\sqrt{3})=\{a+b\sqrt{2}+c\sqrt{3}+d\sqrt{6} : a,b,c,d\in \mathbb{Q}\}$
Take some arbitrary element and show that this has to be in one of those specified fields...
The point is that whether the choosen element has contribution from $\sqrt{2}$ or $\sqrt{3}$ or $\sqrt{6}$
Take $a+b\sqrt{2}+c\sqrt{3}+d\sqrt{6}$

suppose $b=c=d=0;a\neq 0$ then we just have $a$ so this element is in $\mathbb{Q}$
suppose $a=c=d=0;b\neq 0$ then we just have $b\sqrt{2}$ so this element is in $\mathbb{Q}(\sqrt{2})$
suppose $a=b=d=0;c\neq 0$ then we just have $c\sqrt{3}$ so this element is in $\mathbb{Q}(\sqrt{3})$
suppose $a=b=c=0;d\neq 0$ then we just have $d\sqrt{6}$ so this element is in $\mathbb{Q}(\sqrt{6})$

Doing similar calculations as taking only two/three/four of $a,b,c,d$ being non zero would conclude there is no other field.
Comment: This shows that those are subfields, but it does not show that there are no more...
Comment: @SamNead But it's easy to see that there is no other non-trivial subfields of these three fields because they are quadratic extensions of $\mathbb{Q}$.


How to Check if other page field value is empty using jquery

Question: I'm getting all contacts from Mysql db and then showing it on html row.  Each row has onClick() method After click on each row it will show a details of contact to the right side of all contacts.
showing All contacts:
echo "
";
echo "$companyName	";
echo "$family_name	";
echo "$given_name	";
echo "$department	";
echo "$title	";
echo "
";

This getDetails() call the getContactDetails.php (Contact Details) page. In this page I've a field called Note where user can enter notes.
So now I want to show a Confirm message to the user Only if user write something on Enter Note box but click other row (all contacts) without save this Enter Notes
Confirm mesaage will be : Do you want to save this Notes box before you go to other Contact ? Yes Or No. If Yes then saveNote() will be call otherwise it will load the new contact row.
I've no idea how can I do this using Jquery or Javascript ? Do you have any idea or solution ? Thank you.
getDetails() function:
function getDetails(id) {
            id = id;
            $.ajax({
            type:"post",
            url:"getContactDetails.php",
            data:"id="+id,
            success:function(res){
                $('#visiable').show();
                $('#notebox_visiable').show();
                $('#thirdBox').show();

                $('#all_contact_details').html(res);
                showthirdbox(id);
                //showNotexBox(id);
                //showAllNotesBox(id);
                }
           });
}

getContactDetails.php page have Note field:

    Enter Note

    <form action="" method="post" id="showNotesBox" name="notebox">
    <input type="hidden" value="<?php echo $id; ?>" name="cdid" id="cdid"/>

    <textarea name="contentText" id="contentText"  cols="35" rows="4" placeholder="enter note"></textarea>

    <input type="submit" value="Save" name="submit" class="submit" id="addNewNotes"/>

    </form>

Home page view after click on a row (All contacts) :
Comment: You could do this: add an `onchange` handler to the note box. In that handler, set an custom attribute to the text field, something like `$(notebox).attr('change','yes')`. Then in the `onclick` of your contact list, before you change anything, check if the notebox has an attribute `change=yes` and display your messge.
Comment: @Michel Thanks for your response. Can you show me how exactly to do it ?
Answer: Here you can use jQuery Change function to do this.
For example,
<input id="field" type="text" value="abcd">
Link

For the above html code the jQuery code is following
$(document).ready(function(){
$("#pid").click(function(){
  $("#field").change(function(){
    alert("The text has been changed.");
  });// end of change
});// end of click function
});//end of document

Answer: change only triggers on blur, so as long as the user stays in the textbox there is nothing to do.
jQuery change()
Attach a change event handler:
$("#contentText").change(function() {
    $("#contentText").attr("ididwritesomething","yep");
    }

In the save button remove the attribute jQuery removeAttr()
$("#contentText").removeAttr("ididwritesomething");

In the click handler for your contact list, check if the attribute is set (from this question):
var attr = $("#contentText").attr("ididwritesomething");
if (typeof attr !== typeof undefined && attr !== false && attr=="yep"){
       //do you want to save?
}


Solve the comparison

Question: I have difficulties with these type of problems:
Solve the comparison: $\displaystyle67x + 17 \equiv 0\pmod{28}.$
I'm sure it is something very simple but I'm stuck on it more than $2$ hours :( .
Any help would be greatly appreciated.
Answer: As $67\equiv11\pmod{28}$
$$67x+17\equiv0\pmod{28}\iff 11x+17\equiv0\iff11x\equiv-17\equiv11\pmod{28}$$
$$\iff x\equiv1\pmod{28}$$
Using property $\#12$ of this and as $(11,28)=1$
Comment: lol that was really fast. I get it. thank you :)
Comment: @MathError, My pleasure. Hope I could make the idea clear

Solve the comparison


Should I downvote valid answers to off-topic questions

Question: Off-topic questions (accounting, elementary homework, etc.) regularly get detailed answers, usually correct ones. Obviously this rewards the OP of the off-topic question and may attract more off-topic questions. (There are several users who are trying to outsource their econ course here.)
Should I downvote correct answers to off-topic questions as a disincentive or is that going too far?
Answer: My gut feeling would be no. But then I read this:
Should one downvote answers to off-topic questions?
It seems like the accepted approach in the broader SE community is that answers to off-topic questions should be downvoted. In particular, this answer seems persuasive.
Since there is no obvious reason why Econ.SE should diverge from the network-wide convention, my suggesion would be to downvote answers on off-topic questions.
Comment: Excellent links. As this is a meta discussion I will wait a few days and then accept the answer with most votes.
Answer: Downvoting correct answers because you do not like the question is not ever appropriate.  If you believe the question is not off-topic, vote to close or move the question.  That's what that option is for.  If others agree with you, the question will be closed or moved.  Otherwise you are downvoting good answers to questions that others think are fine.
Despite the opinion ubiquitous gives that this practice is the consensus on other forums, I have not seen it anywhere but here. The fact that we can find people who say they do it elsewhere doesn't mean it's the consensus and it certainly doesn't mean it's the right thing to do.
Considerations:

Downvoting an answer sends a signal that the answer, not the question, is bad. The purpose of downvotes is to say (to the OP) that the answer is bad in some way.  Standard practice that I have seen on StackExchange is to upvote helpful answers, leave answers that are right but not the best alone and downvote only when an answer is wrong.  If you downvote a correct answer, the OP and others reading the question will likely think the answer is wrong and actually be harmed my the question, rather than helped.
The line between "on-topic" and "off-topic" questions is blurry.  That seems to be especially true in the econ stack exchange.  Most questions here are either requesting help on homework (whether at the undergraduate or Ph.D. level) or are people who are not economists asking big picture questions.  Either one could easily be viewed as on or off topic.  If there is insufficient agreement to close the question, then penalizing people who think the question is valid and try to help is counterproductive.
Downvoting answers will do little or nothing to improve the quality of new questions.  Off-topic questions pretty much universally come from people who don't spend much time in the forum.  Dinging people who answer questions you consider off topic will not affect the people who are the source of these questions.
Penalizing good answers harms the community. The purpose of StackExchange is to help people.  For this we need a community of experts answering questions.  Trying to coerce experts into not answering certain types of questions by giving negative feedback to good answers encourages these experts not to participate on other questions.  This behavior makes StackExchange a less productive place, to say nothing of being rude.
Downvoting answers breaks the logic of moved questions.  The most blatantly off-topic questions often are on topic elsewhere.  If the question does get moved, as it should, then a downvote on a correct answer becomes especially inappropriate.
Downvoting correct answers causes confusion. I came here because the OP (denesp) caused some significant confusion by downvoting an answer that is both correct and helpful to a whole class of problems.  Because downvoting is an inappropriate response to that, there was confusion about the reason for the downvote--I figured that because the poster was continuing to have problems, he had either voted the answer down or someone who thought my answer was not explicit enough had done so.  Downvotes mean something.  When they are used for something else, confusion ensues.

When you downvote an answer, StackExchange suggests that you leave a comment in case the answer can be improved.  This is clear evidence that a downvote is meant to indicate that the answer is bad, not that the question is off-topic.  That's how it should be used.
I've seen people who do all sorts of negative things, like downvoting good answers so their answer looks better, appealing to their (non-proveable) credentials, and posting off-topic comments.  The fact that these behaviors happen does not mean they are right nor helpful.  Before doing anything on StackExchange (upvoting, downvoting, or answering), ask yourself if what you are doing will help someone learn more about economics.  If the answer is no, don't do it.
============== Additional Context ==================
I posted this meta answer because of a problem this notion just caused.  Someone posted a mid-level undergraduate econ question, and demonstrated that effort had been put in but they were stumped.  In my opinion this is not off-topic but I respect those who think it is.  I provided an outline on how to solve this type of question and some hints that, if followed, would have solved the problem and others of that form.  The poster commented that they were glad for my help and learned a lot but my answer was wrong (apparently they made an algebra mistake while following my directions).  My answer also got a downvote.  To me this means either the poster downvoted because they thought I was the one who made a mistake or someone who didn't know how to solve the problem downvoted because they thought it was wrong based on the comment.  I left a more explicit solution and told the poster not to say things are incorrect unless they know that they are incorrect.
In fact, denesp had felt that the question was too introductory and therefore downvoted my answer, causing the confusion.  This type of behavior is not unknown among new stack exchange members, but for a high repuation expert to do it is strange.  To have a meta discussion coming to an apparent consensus that this is desirable behavior is bizarre.  I see that this meta question was initiated by denesp, who has also taken it to be a consensus view and is practicing it.  I hold no personal grudge--I'd be happy to go get a beer with you IRL--but I do want to make it clear that this idea was introduced, promoted, and practiced here by you and does not represent normal expert behavior from what I have seen elsewhere on StackExchange.  If StackExchange wanted a "penalize an expert for answering a question you think is bad" button, we would have one.
Comment: On this being a one man crusade I would like to point to [Ubiquitous's link](https://meta.stackexchange.com/questions/194963/should-one-downvote-answers-to-off-topic-questions), which points to the main meta, and where the same answer has the highest number of votes, 63.
Comment: You may also want to read [this econ meta question](https://economics.meta.stackexchange.com/questions/1465/economics-se-policy-on-homework-questions?noredirect=1&lq=1).
Comment: Ubiquitous wrote both the accepted answer here and the policy you are pointing to.  Certainly one person agrees with you.  I agree that the question we are discussing was not the best; however it was good enough that my answer was helpful not only to the OP but to others solving the same type of problem.  It was not clearly off topic, even by the standards you just linked to.
Comment: The main meta answer you reference is not, to me, compelling either in its arguments nor its statistical significance in representing what is actually done.  For that matter, neither is this question (not many people come to the meta). We can instead (or in addition) look to experience: You and I have just observed the downside of this practice and I would be surprised if either of us have observed others doing it or an upside.  I should think that would be compelling at least to you and me.
Comment: I am sorry if my downvote has caused confusion to you. It seems to me this was mostly due to unfamiliarity with the FAQ and other meta posts, but I am still sorry.
Comment: A flood of bad questions is a potential annoyance, but in my opinion the econ area of SE has something of the opposite issue: very few questions and very few answers.  Just because a question is more advanced doesn't mean it's more interesting nor helpful.  Ultimately you and I (and others here) decide what type of place econ.SE will be.  Will it be hostile to undergraduates in an attempt to have advanced questions only?  That is a valid choice but not one I prefer.  Anyway, in my opinion penalizing people who answer is not a good solution to the problem of too many bad questions.
Answer: I downvote questions and answers that are blatantly off-topic.
Here is what I do (now) with trivial homework questions without shown effort:

I downvote the question.
I downvote the answer if $>+1$ and they really just did the whole thing, including all calculations.
I upvote comments saying something along the lines of
"this is a homework question, don't post it without showing effort."
I never downvote anyone who provides encouraging hints without providing a full solution.
I have also upvoted an answer to an elementary question. The question came up in my lecture once and I couldn't figure out what is not to understand about this concept. Through the answer I could figure out what went wrong in a confused mind and how to answer it next time.

In general, I do not think that learning economics should be discouraged. I do think that shirking on homework questions should be discouraged. However, if minimal effort is shown, I am happy to be a teacher.
Comment: On the teaching angle: In my experience if the student has no concept of how he could arrive at a solution his time would be better spent studying theory than on deciphering the solution to one particular exercise. This sentiment (dare I say wisdom) is not shared by most students. But unless the exam has the exact same type of question with different numbers or the goal is not merely to pass the exam but to learn to think, deciphering solutions is pretty useless.
Comment: I am pretty new to this site. I came up with the procedure along the way. A problem of this site is that in the beginning I did not have enough reputation to comment and an answer not providing an answer gets downvoted. Also where is the bar for "low level" questions? As I have heard there have been multiple tries to open an econSE and all have failed, because there are too few experts. If I had to decide between no econSE at all and the current one, I'd pick the latter.
Comment: Unfortunately the line between minimal effort and zero effort is frequently blurred. You yourself have [answered](http://economics.stackexchange.com/a/14922/1601)
or provided [very strong hints](http://economics.stackexchange.com/a/15022/1601) to basic questions where the OP has clearly shown no effort at all.
Comment: And in case you would like some tips, the site does have some [guidance on homework questions](http://meta.economics.stackexchange.com/questions/1465/economics-se-policy-on-homework-questions).
Comment: I know (that is why I linked to the FAQ) and we are happy to have you. I also answered a lot of homework questions when I was new. Now I honestly don't believe I am helping the student by doing that. There are also several meta questions on whether having an econhomeworkSE is better than not having an econSE. I seem to recall there is no clear majority for either side.
Comment: As for the 'bar of low level questions': I have no clue where it is. But in my opinion basic no effort questions are underneath it. Btw. some would say that effort is no redeeming quality at all: The question is either interesting or it is not.


size issue related to universal quantifications over nets

Question: In this wikipedia article, it is written that

A function $f : X \rightarrow Y$ between topological spaces is continuous at the point $x$ if and only if for every net $(x_\alpha)$ with $\lim x_\alpha = x$ we have $\lim f(x_\alpha) = f(x)$ .

I'm wondering if there is a size issue related to the phrase "for every net".
A net is a function from a directed set to a set, so I think that we need the set of all sets to construct the set of all directed sets and do universal quantifications over it.
Comment: No, there is no issue.
Comment: In first-order  theories, such as ZF, quantification over the whole universe of discourse is allowed.
Comment: @Ponta You don't need something to be a set in order to quantify over it. For example, the axiom of extensionality (say) involves quantifying over the class of all sets, but the class of all sets is of course not a set.
Comment: @AndrésE.Caicedo Why? How to construct the set of all nets without using the set of all sets?
Answer: No, the statement is just "for every set $A$ that is directed and for every net $A\to X$..." This is a statement in first order logic that quantifies over all sets and is precisely the kind of thing we are allowed to do in ZF. Where size issues come in is when we try to quantify over all collections of sets (i.e. classes).$^*$
Not sure if this will make you feel better or worse at this point, but consider the power set of a set $X.$ It is the collection of all sets that are subsets of $X$ (which is a set provided we have the power set axiom). Notice we quantified over all sets in this definition too.

$^*$ There are usually a lot of questions at this point, like (1) "Aren't sets collections of sets?" and (2) "What does 'all sets' mean?" I'm pretty sure there's plenty of material on these kinds of questions on this site and overflow, so I'll only answer very briefly.

Sets have extensions, which are collections of sets related to them by the membership relation. Some collections are the extension of a set and others, e.g. the collection of all sets, are not. Colloquially, "the class is a set". Paradoxes are avoided by only allowing strong enough axioms to prove certain classes are sets. ZFC is strong enough to be very expressive while still weak enough to avoid all known possible contradictions.
We just assume there is some universe of sets that obeys the ZFC axioms, and that is where set-theoretically founded mathematics takes place (when and if we care about foundations and decide to use set theory). We can't really construct one in a satisfying way, since ZFC is powerful enough to do pretty much any construction that would be commonly accepted, and construction of a model of ZFC can't be done in ZFC due to the incompleteness theorem.
Answer: When we quantify as "for all $x$ in $T$ ...", $T$ is a type and need not be a set.
So we can quantify on the type of all sets like $\forall x \in \text{Set}(\varphi(x))$, without constructing the set of all sets.
Comment: As a minor technicality, "class," rather than "type," is appropriate here.
Comment: To explain what @Noah means, first order logic is untyped, and set theory specifically is untyped and single sorted. There is no Dana, there is only "set", to paraphrase Ghostbusters.


finding the correct architecture using jaxb, jax-rs and ejb's

Question: My application comprises three layers being:

Interaction layer (RestServices JAX-RS)
Business layer (Stateless EJBs)
Persistence layer (DAO's with queries etc.)

In addition I have this domain objects layer which runs through the layers. The application was first setup to use a nosql database, but we had to abandon that. Now we are using JPA with a RDBMS but running into trouble when migrating, mainly due to the fact that the jaxb objects that the interaction layer is using, is trying to lazily load domain objects without a transaction when the are serialized. This transaction has been closed once it returned from the stateless ejb.
After reading a lot on the web, I tried to annotate my restservice with @Stateless too in order to start a transaction a bit sooner and to avoid the transaction being closed once the business layer has been left. Unfortunately this doesn't work either as I still getting lazilyinitializationexceptions.
So my question is how should I combine JAXB, JAX-RS and EJB's in order to avoid the LIException?
regards
Michael
Comment: Sorry for the short answer. See if any of this helps

[How to solve lazy initialization exception using JPA and Hibernate as provider](http://stackoverflow.com/questions/578433/how-to-solve-lazy-initialization-exception-using-jpa-and-hibernate-as-provider)
Comment: Hi Nicholas, this is not really what I'm looking for. It's seems a kind of a hack.
Comment: You can inject your ejb to rest service this way: `@EJB private YourService service;`. Don't sure I understood your question correctly.
Answer: In order to avoid lazily initialization exceptions the simplest way is to create DTOs of the entities which will contain the desired values and pass them to the interaction layer.
In this way no initialization exceptions will be thrown and also the data model will contain all the info you want.


how can I change the location of Log files for SQL Server Reporting Services in sql2008?

Question: I tried to change the location of Log files for SQL Server by using these steps but it's not working because I can not find the RTrace in two web config files.
There are three files you need to modify to change the location of the Reporting Services Logfiles. These files are:

c:\Program Files\Microsoft SQL Server\Reporting Services\ReportManager\web.config

c:\Program Files\Microsoft SQL Server\Reporting Services\ReportServer\web.config

c:\Program Files\Microsoft SQL Server\Reporting Services\ReportServer\Bin\ReportingServicesService.exe.config

Add the following tag under RSTrace in all the above files:
<add name="Directory" value="c:\directorypath" />
Your help will be appreciate.
Answer: I'm not sure you can modify the location. This file is located at \Microsoft SQL Server\\Reporting Services\LogFile
Tracing levels are specified through DefaultTraceSwitch and RSTrace settings. All trace level settings are stored in the ReportingServicesrService.exe.config file.
The configuration file is found in the folder path \Program Files\Microsoft SQL Server\MSRS10.\Reporting Services\ReportServer\bin
The File name attribute only affects the file prefix
More info here:
http://msdn.microsoft.com/en-us/library/ms156500(v=SQL.100).aspx


Vetores - Separar negativos e positivos

Question: tenho que fazer um programa que receba um vetor de 8 números e retorne 2 vetores, o primeiro com os números positivos do vetor de 8 posições, e o segundo com os números negativos.
O PROBLEMA É QUE EU NÃO SEI COMO UTILIZAR VECTOR, já que os dois últimos vetores não devem possuim capacidade definida..
Isso está fazendo com que meu segundo vetor "perca" de alguma maneira as posições dos números positivos que são digitados primeiro. Não sei se ficou claro.
Se puderem ajudar, ficaria grato.
MEU CÓDIGO:
using namespace std;
int main(){
vector<int> vet(8);

for(int i=0;i<8;i++){
    cin>>vet.at(i);
}

vector<int> vet1(8);
vector<int> vet2(8);

int cont1=0,cont2=0;

for(int i=0;i<8;i++){
    if(vet.at(i)>=0){
        vet1.at(i)=vet.at(i);
        cont1++;
    }else{
        vet2.at(i)=vet.at(i);
        cont2++;
    }
}

for(int i=0;i<cont1;i++){
    cout<<vet1.at(i)<<" ";
}
cout<<endl;
for(int i=0;i<cont2;i++){
    cout<<vet2.at(i)<<" ";
}

return 0;

Comment: Bem vindo ao Stack Overflow, Thiago! Por favor [edite](https://pt.stackoverflow.com/posts/213206/edit) sua pergunta, e explique melhor o problema que você está tendo (qual é o resultado esperado? qual o resultado atual?) - normalmente perguntas com enunciado de problema não são muito bem vistas, pois a comunidade termina achando que você quer que ela faça o trabalho por você - sugiro que você remova esse trecho e escreva detalhadamente apenas o problema que você quer resolver.
Comment: Não vejo problema no enunciado, ele ajuda entender o que está fazendo, tem um código que tentou, mas falta dizer qual é o problema, qual a dúvida.
Comment: O problema é que minha resolução está errada. O vetor de números positivos que está sendo impresso na tela tem sucesso, porém o segundo está com problemas. Além disso, eu não poderia declarar o tamanho do "vet1" e "vet2", já que não sei a quantidade de números positivos e negativos.
Comment: Faz bem em fazer os vetores com o mesmo tamanho que o de entrada. Olhe a resposta que dei a baixo, espero ter ajudado, qualquer duvide me comunique.
Answer: O problema é que esta fazendo a inserção nos vetores de forma errônea, pois esta utilizando o mesmo int para iterar o loop e para adicionar em cada vetor.
Por exemplo se vem o vetor 1,-1,67,...
o vetor vet1 vai ficar 1,"lixo",67,...
e o vetor vet2 vai ficar "lixo",-1,"lixo"
você deve utilizar os contadores como índices do vetores de armazenamento como segue o código:
for(int i=0;i<8;i++){
    if(vet.at(i)>=0){
        vet1.at(cont1)=vet.at(i);
        cont1++;
    }else{
        vet2.at(cont2)=vet.at(i);
        cont2++;
    }
}

me diz depois se funcionou. =D
Comment: Mateus, muito obrigado pela resposta!!! Deu certo. Estou com mais uma dúvida sobre a declaração do tamanho do "vet1" e "vet2", pois eu não sei a quantidade de números positivos e negativos que o usuário irá digitar, sendo assim, eu não deveria então criar um vetor sem antes declarar seu tamanho inicial? **EDIT** Digo isso porque meu professor fala muito em não desperdiçar memória atoa, fazendo com que o programa fique o mais leve possível.
Comment: Bom é sempre bom poupar memória, deixar o programa mais leve, seu professor está certo. Você pode ver mais sobre isso se pesquisar sobre alocação dinâmica de vetores. Voce pode fazer de diversas maneiras. Acho que o que seu professor está querendo que faça é um vetor de ponteiros . Pode aprender um pouco mais aqui:
http://www.cplusplus.com/doc/tutorial/pointers/
Comment: Obrigado novamente!!

Vetores - Separar negativos e positivos


A few basics in topology

Question: I am studying some topology for my thesis (I come from a different area of mathematics) and I have some basic questions which I have difficulty to clear out.
I would really appreciate some help (also a good reference book if possible).
Suppose $X \subseteq Y$ equipped with the topologies $A$ and $B$ respectively, where the topology $A$ is stronger. (Also $X$ is not metrizable, but $Y$ is.
 I don't know if this helps but I am writing it in any case)
I would like to know which of the following statements are true and which are false  :
1) $A$ topology being stronger means that convergence wrt $A$ $\implies$ convergence wrt $B$.
2) $A\supseteq B$.
3) An open set in $X$ is not necessarily open in $Y$ (since if the previous question is correct then it can be in A but not in B).
4) the Borel $\sigma$-field defined by $A$ contains the Borel $\sigma$-field defined by $B$.
Comment: When is this due?
Comment: Can you clarify the questions? Are you asking whether the four statements are true, what they mean, or why they're true? (NB I'm not a topoligist eitger, but I think people will want to know what to answer.)
Comment: 2) only makes sense if $X = Y$.
Answer: I'll call the topologies $\mathcal{T}_1$ and $\mathcal{T}_2$ respectively, both defined on $Y$, and suppose $\mathcal{T}_2$ is stronger than $\mathcal{T}_1$.
This is by definition that the inclusion $\mathcal{T}_1\subseteq \mathcal{T}_2$ holds. I.e. there can be open sets in $(Y,\mathcal{T}_2)$ that are not open in $(Y, \mathcal{T}_1)$; I fail to see the relevance of your $X$, except that $X \subseteq Y$ can be $\mathcal{T}_2$-open and not $\mathcal{T}_1$-open. These are just reformulations of course.
If $y_n \to y$ in $\mathcal{T}_2$ (the stronger one) then certainly $y_n \to y$ in $\mathcal{T}_1$ as well. The inclusion-definition immediately
The Borel $\sigma$-algebra genererated by $\mathcal{T}_1$ will be contained in that generated by $\mathcal{T}_2$, which is obvious from the inclusion-definition too.

A few basics in topology


$f:\mathbb{N} \to M$ is surjective $\leftrightarrow$ $\exists$ $g:M \to \mathbb{N}$ injective with $(f \circ g)(x)=x$ $\forall x \in M$

Question: Prove:
$f:\mathbb{N} \to M$ is surjective $\leftrightarrow$ $\exists$ $g:M \to \mathbb{N}$ injective with $(f \circ g)(x)=x$ $\forall x \in M$
I think that I already proved one direction ($\leftarrow$) of the equivalence. But how to prove ($\rightarrow$)
Answer: Let us suppose that $f:\mathbb{N}\longrightarrow M$ is surjective. Then, for every $m\in M$ there exist $\{n_1,...,n_i\}\in\mathbb{N}$, $i\geq 1$, such that $f(n_i)=m$ for every $i$. Thus, let us define $g:M\longrightarrow\mathbb{N}$ as
$$ g(m):=n_i$$
for some $i$. We have that
$$(f\circ g)(m)=f(g(m))=f(n_i)=m$$
for every $m\in M$. Moreover, if we suppose that $g(m_1)=g(m_2)$, we obtain
$$m_1=f(g(m_1))=f(g(m_2))=m_2,$$
i.e. $g$ is injective.
Comment: Yeah all right, thats pretty clear thank you! Is the first half of the proof you can see in the picture I added correct?
Comment: @Analysis_Mark It looks correct, although, by definition of $(f\circ g)$, the element you called $a$ is in fact $x$. For every $x\in M$, $(f\circ g)(x)=x$. Therefore, $f(g(x))=x$, which means that, for every $x\in M$, there exists $n:=g(x)\in\mathbb{N}$ such that $f(n)=x$.
Comment: I just did the task again and read your answer again, but I can't understand why we are allowed to say that $(f\circ g)(m)=f(g(m))=f(n_i)=m$ $\forall m\in M$. I mean we said that $g(m)=n_i$ for some i. So if we have $f(n_i)$ we don't have every n anymore. Why are we allowed to say that $f(n_i)= m$ $\forall m\in M$?
Comment: @Analysis_Mark I will try to be clearer: by hypothesis, $f$ is surjective, which means, by definition, that, for every $m\in M$, the set $f^{-1}(m)$ is not the empty set. In other words, for every $m\in M$, there exists at least one element $n_m\in\mathbb{N}$ such that $f(n_m)=m$. Therefore, for every $m\in M$, we can define $g(m)=n_m$, which is well defined, injective, and is such that $(f\circ g)(m)=f(n_m)=m$, by construction.
Comment: Allright. So we construct an injective function g, that is mapping all $m\in M$ to exactly one of their inverse images. We may lose some $n_i$, if f is only surjective, but the $n_i$ that are left are already enough to get all elements of M as a value of f. Right?
Comment: @Analysis_Mark Yes. More precisely, since $g$ is injective, it is a bijection between $M$ and $g(M)\subset\mathbb{N}$, and $(f\circ g)(M)=M$.


Pageable must not be null Exception thrown when using group functionality in Spring Data-Solr

Question: When creating a group by query using the documentation example for springboot data-solr and SolrTemplate, I receive results but there is no grouping information. When looking at the sample code:
Field field = new SimpleField("popularity");
Function func = ExistsFunction.exists("description");
Query query = new SimpleQuery("inStock:true");

SimpleQuery groupQuery = new SimpleQuery(new SimpleStringCriteria("*:*"));
GroupOptions groupOptions = new GroupOptions()
    .addGroupByField(field)
    .addGroupByFunction(func)
    .addGroupByQuery(query);
groupQuery.setGroupOptions(groupOptions);

GroupPage<Product> page = solrTemplate.queryForGroupPage("collection-1", query, Product.class);

GroupResult<Product> fieldGroup = page.getGroupResult(field);
GroupResult<Product> funcGroup = page.getGroupResult(func);
GroupResult<Product> queryGroup = page.getGroupResult(query);

It appears that a group query is created however the call to queryForGroupPage does not use it which would explain why I do not receive any grouping information. If I instead pass in the groupQuery object to the call then i receive a "Page Must Not Be Null" error.
I have tested other query types and have not had this error so it seems it is just affecting this one function for me. I have tried using an older springboot version and an older Solr version, matching the two, and the same issue happens.
I have not had any other Solr issues with the setup so do not think i am missing anything in my config.
The following is a snippet of the stacktrace for the error.
11:15:14,323 ERROR [stderr] (default task-1) java.lang.IllegalArgumentException: Pageable must not be null!
11:15:14,325 ERROR [stderr] (default task-1)    at org.springframework.util.Assert.notNull(Assert.java:198)
11:15:14,326 ERROR [stderr] (default task-1)    at org.springframework.data.domain.Chunk.(Chunk.java:54)
11:15:14,327 ERROR [stderr] (default task-1)    at org.springframework.data.domain.PageImpl.(PageImpl.java:46)
11:15:14,328 ERROR [stderr] (default task-1)    at org.springframework.data.solr.core.ResultHelper.convertGroupQueryResponseToGroupResultMap(ResultHelper.java:306)
11:15:14,329 ERROR [stderr] (default task-1)    at org.springframework.data.solr.core.SolrTemplate.createSolrResultPage(SolrTemplate.java:448)
11:15:14,330 ERROR [stderr] (default task-1)    at org.springframework.data.solr.core.SolrTemplate.doQueryForPage(SolrTemplate.java:305)
11:15:14,330 ERROR [stderr] (default task-1)    at org.springframework.data.solr.core.SolrTemplate.queryForGroupPage(SolrTemplate.java:357)
11:15:14,331 ERROR [stderr] (default task-1)    at org.springframework.data.solr.core.SolrTemplate.queryForGroupPage(SolrTemplate.java:346)
...
Has anyone seen a working example of the group by functionality? I have also searched for anything and can't find a reference outside of the sample code from the official documentation.
Thanks,enter code here
Comment: hey, did you find a solution to this problem? Also, I have the same problem.
Comment: @DarrenP Same problem. Were you able to figure out the issue?
Answer: I think I resolved this problem. You should set the GroupOptions limit. The sample code is below.
GroupOptions groupOptions = new GroupOptions()
.addGroupByField(field)
.addGroupByFunction(func)
.addGroupByQuery(query)
.setLimit(1000);
groupQuery.setGroupOptions(groupOptions);

I also had the same problem and resolved by doing this.


Searching on a table using mysql table?

Question: I have a question asked in an interview
A form with following field "price","tool" , "range_max" , "range_min" , "age_of_tool" also any field can be NULL.
How will u implement the searching on table a query ?
My answer was
I will use "AND" while searching...

What do u think should be right query I should give them ?
Comment: This question is not legal in my opinion. A specifying question is needed. Should I search by price or by range? Maybe I need to search by tool name or by age? Maybe I need to search by both age and price or by tool name and range? Depending on this your search query would be organized differently, you would need different indexes and different search operators.
Answer: Personally, I think they're looking for intelligent search ideas based on the available criteria, not the logical join condition you're looking to use.
Contrary to what Ajay says, an AND search is more appropriate.  Think of it from your own perspective when searching for stuff on the Internet.  If you look for 'red' things and 'small' things, you'd expect the search results to only contain small red things.
Otherwise, take a look at those fields.  They pretty much tell you what you need to search.  For example, anything that uses "range_min" to discriminate is almost always going to be :-
WHERE [SomeValue] > range_min

Think logically about how each field might be employed in a search, and you'll probably arrive at better a understanding than any of the ready-rolled answers you receive on this question.
Answer: No, you should use OR in place of AND if you want to search in every column.
Because when we use AND then value must be present in all columns but in case of OR if it is present in one column, it will show you some records according to the search criteria you specified.

Searching on a table using mysql table?


Find the greatest common divisors

Question: I am given the following exercise:

If $p$ is a prime and $(a,b)=p$,calculate $(a^2,b^2), (a^2,b)$

That's what I have tried:

Both $a$ and $b$ contain $p$ and at least one of them contains $p$ with exponent $1$.
The two canonical forms of $a$ and $b$ have not an other common prime.
So,it can be

$a=p \cdot p_1^{a_1} \cdot p_2^{a_2} \cdots p_k^{a_k} \text{ and } b=p^{d} \cdot q_1^{d_1} \cdot q_2^{d_2} \cdots q_m^{a_m}$
$a=p^{a_0} \cdot p_1^{a_1} \cdots p_k^{a_k} \text{ and } b=p \cdot q_1^{b_1} \cdots q_m^{b_m}$

where $p_i \neq q_j \forall i,j$
So:

$(a^2,b^2)=p^{\min\{2,2d \}}=p^2$
$(a^2,b^2)=p^{\min \{ 2,2a_0\}}=p^2$

$(a^2,b)=\left\{\begin{matrix}
p,d=1\\
p^2,d \geq 2
\end{matrix}\right. $
$(a^2,b)=p$

Could you tell me if it is right?
Comment: Typo at the very end, you want $(a^2,b)$ not $(a^2,p)$.
Comment: Seems right to me, if a bit long of a proof.
Comment: Looks about right.
Comment: Nice,thank you all very much!!!!
Answer: Yes, $(a^2,b^2)=p^2$ which is obtained by counting powers of $p$ in $a^2$ and $b^2$.
For $(a^2,b)$ there are two answers:
$$
(a^2,b)=p^2,\, \mathrm{ for\, example,\, } a=p,\ b=p^2,
$$
$$
(a^2,b)=p,\, \mathrm{ for\, example,\, } a=p,\ b=p.
$$
There is no more cases, because $(a^2,b)|(a^2,b^2)$ and $(a,b)|(a^2,b)$. Hence $(a^2,b)$ is $p$ or $p^2$.
Answer: Your answer is correct. You may find it instructive to compare it to this more general method.
Note $\ \ (A,B) = p\iff A,B = pa,pb,\  (a,b) = 1.$
Thus $\,(A^2,B) = (p^2 a^2,pb) = p(p\color{#0a0}{a^2,b}) = p\color{#c00}{(p,b)},\ $ by $\,(a,b)=1\,\Rightarrow\,\color{#0a0}{(a^2,b)=1}\,$ by Euclid's Lemma.
So $\,\ (A^2,B^2) = (p^2a^2,p^2b^2) = p^2(a^2,b^2) = p^2,\ $ by $\,\color{#0a0}{(a^2,b)=1}\,\Rightarrow\,(a^2,b^2)=1\,$ by Euclid's Lemma.
Remark $\ $ Notice that the above method eliminates the case analysis, reducing it to $\, \color{#c00}{(p,b)} = p\,$ or $\,1\,$ if $\,p\,$ is prime. But the above proof works for any $\,p.$ In fact the above proof works more generally in any gcd domain, i.e. any domain where gcds exist. This is more general than using the existence and uniqueness of prime factorizations, since some gcd domains have no primes at all, for example the ring of all algebraic integers, where $\,\alpha \,=\, \sqrt \alpha\sqrt \alpha,\,$ so there are no irreducibles, so no primes.

Find the greatest common divisors


Given an Array of strings, return an array of strings that contains only the palindromes

Question: Helping a friend out with a question he had. For the life of me I can figure out why my code doesn't work correctly, I am sure it is something very simple I just need another pair of eyes to take a look at it,
public String[] bahB(String[] arr) {
    int count=0;
    for (int j = 0; j < arr.length; j++) {
        String[] f = new String[arr[j].length()];
        for (int i = 0; i < arr[j].length(); i++) {
            f[i] = arr[j].substring(i, i + 1);
        }
        if(isPalindrome(f)){
            count++;
        }
    }
    String[] d = new String[count];
    int y=0;
    for (int j = 0; j < arr.length; j++) {
        String[] f = new String[arr[j].length()];
        for (int i = 0; i < arr[j].length(); i++) {
            f[i] = arr[j].substring(i, i + 1);
        }
        if(isPalindrome(f)){
          d[y]=arr[j];
          y++;
        }
    }
    return d;
}

public boolean isPalindrome(String[] x) {
    int s1 = 0;
    int s2 = x.length - 1;
    while (s2 > s1) {
        if (x[s1] != x[s2]) {
            return false;
        }
        ++s1;
        --s2;
    }
    return true;
}

My code starts off by creating a counter that is supposes to get the amount of palindromes in the given String array, it is not an issue in the is Palindrome method so it must be something in the these lines
  int count=0;
    for (int j = 0; j < arr.length; j++) {
        String[] f = new String[arr[j].length()];
        for (int i = 0; i < arr[j].length(); i++) {
            f[i] = arr[j].substring(i, i + 1);
        }
        if(isPalindrome(f)){
            count++;
        }

Thanks to anyone that took the time to read this
Comment: What data have you tested it with, and in what way is the result incorrect?
Comment: The issue is that the count variable is not iterating
Comment: Why does `isPalindrome` have a `String[]` as a parameter, instead of a `String`?  I would have expected it to test a single `String`, not a whole array of them.
Comment: @David Well the way I wrote this program it creates a string array out of the string. As a reach around to compensate for the oddly written isPalindrome method. In hindsight it would be better to just rewrite the isPalindrome method so it uses a String instead of a String[]. But the code is already fixxed and working.
Comment: Considering that your title is plain flat wrong: you do not have an array of Strings, you have an array of arrays of truly stupid one character substings, you ar wasting our time and earn my downvote.
Answer: I'm not sure how you decided that "it is not an issue in the is Palindrome method", since in point of fact, your isPalindrome is quite broken. This:
        if (x[s1] != x[s2]) {

means "if x[s1] and x[s2] are references to the same instance of String"; whereas what you meant is "if x[s1] and x[s2] are references to String instances with the same content", i.e.:
        if (!x[s1].equals(x[s2])) {

(though really, you shouldn't be using a String[] here anyway; you should use be using a char[], or a String with charAt).
Comment: By the way, you should read about [how to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Your bug is not a huge deal, but your total inability to debug -- your dependence on "another pair of eyes" -- is a serious impediment. You will not be a programmer until you have overcome it.
Comment: huh well I repeatedly tested the isPalindrome method in eclipse and never had any issue with it that why I said "it is not an issue in the is Palindrome method", but I will I double check. Thanks for the responses
Comment: char array is faster than charAt method!!
Comment: @Prashant: I like that you're confident enough to include two exclamation points!!, but not confident enough to include actual benchmarking numbers to demonstrate that this makes a difference. (Hint: it doesn't.)
Comment: Your testing of `isPalindrome` probably used `String` literals as input.  Because of a quirk of the way Java handles Strings, `==` actually returns true if you use it to compare two equal `String` literals.
Comment: @ruakh : i have used both for large number of data (in loop). And there was huge different between these two in execution time.
Comment: @Prashant: Firstly -- what is your evidence that the OP has "large number of data (in loop)"? Secondly -- you do realize that this method iterates over each string only *once*? There is overhead in creating each string's `char[]` to begin with.
Comment: @ruakh : i don't think so that he is having large number of data. but as per me char array is faster than charAt and also string is internally having char array.


Pandas sorting by day

Question: I have a pandas dataframe (dfm), I want to get the min by each day and have the resulted sorted by day. There are more one - Oct 4 or Jun 7....etc.
dfmn
  count      Month  Day  Data_Value
    1        Nov   26          11
    3        Oct    4         178
    4        Nov   28          94
    5        Aug    6         144
    8        Jun    7          89
    9        Jan   25          33
    10       Mar   30          72
    11       Oct   14         106
    13       May   21          89
    17       Mar   27          44
    20       Sep   17         100
    21       Aug    4         194
    22       Jan   26          61
    24       Jun    7         100
    31       Sep   28         117
    32       Oct    1         139
    37       Apr   22          78
    39       Aug    4         200
    40       Jan   24          33
    45       Jun    4         150
    47       Oct   22         100
    49       Sep   14          94
    51       Mar   15          22
    52       Nov   25          50
    53       Oct   15         144
    55       Mar   30         106
    59       Jan   19          94
    60       Feb   28          78
    61       Aug    4         133
    62       Jun   14         117
    64       Mar   14          44
    66       Sep   18         106

I did the following, now my result-set has min for each month/day combination but it is not sorted by month-day, pandas is probably using English alphabet collation sequence for sorting.
dfmn.groupby (["Month","Day"]).min()

          Data_Value
Month Day
Apr   1          23.9
      2          24.4
      3          29.4
      4          32.2
      .          .
      .          .
 Aug  1          25.2
      2          33.1

I need
Jan   1          21.9
      2          20.4
      3          20.4
      4          14.2
      .          .
      .          .
 Feb  1          15.2
      2          13.1

How can I make this happen?
Comment: check category dtype , pd.Categorical
Answer: You can set Month to be an ordered categorical of all the months of the year:
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

df['Month'] = pd.Categorical(df['Month'], categories = months, ordered=True)

Then, when you do your groupby, they will be ordered:
>>> df.groupby(["Month","Day"]).min()
           count  Data_Value
Month Day
Jan   1      NaN         NaN
      4      NaN         NaN
      6      NaN         NaN
      7      NaN         NaN
      14     NaN         NaN
      15     NaN         NaN
      17     NaN         NaN
      18     NaN         NaN
      19    59.0        94.0
      21     NaN         NaN
      22     NaN         NaN
      24    40.0        33.0
      25     9.0        33.0
      26    22.0        61.0
      27     NaN         NaN
      28     NaN         NaN
      30     NaN         NaN
Feb   1      NaN         NaN
      4      NaN         NaN
      6      NaN         NaN
      7      NaN         NaN
      14     NaN         NaN
.....

It might be easier just to get your month abbreviations from the calendar module, though:
import calendar

months = [calendar.month_abbr[i] for i in range(1,13)]

>>> months
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

Pandas sorting by day


Order infinite or finite

Question: If $b$ has infinite order and $a$ has finite order what is the order of $bab^{-1}$?
Sorry for the formatting. I'm using the app.
Thanks in advance.
Comment: $a\mapsto bab^{-1}$ is an automorphism.
Comment: Can you show that $a^k=1$ if and only if $(bab^{-1})^k=1$? This leads to the result in Nicky Hekster's answer.
Answer: Hint: two elements that are conjugate have the same order, so $a$ and $bab^{-1}$ have the same order. The order of $b$ is irrelevant.
Comment: Why is the order of b irrelevant?
Comment: Nvmd just figured it out
Comment: Ok great! Then you actually learned something, which is better than me providing the answer right away!
Answer: Hint:
Since $a$ has a finite order, let $\textrm{ord}(a) = n$. What happens if you raise your conjugated element to the $n^{th}$ power?
$$(bab^{-1})^n =\ ?$$
Comment: (b^n)a^n(b^-1)^n = (b^n)e(b^-1)^n =e
Comment: @user277658 your calculation is incorrect.
Comment: @MattSamuel Can you please explain why?
Comment: Your calculation is correct - see how it means that $(bab^{-1})$ has a finite order? (proving that the order is exactly $n$ requires a tiny bit more work, but it's not necessary)
Comment: @user277658 it's the beginning that's wrong. You got the right end result. See my answer.
Answer: A misunderstanding you seem to have (sorry if I'm wrong) is that you seem to think exponents distribute over products. This is not true unless the group is abelian. So for example
$$(bab^{-1})^n\neq b^na^nb^{-n}$$
However, in this case the exponent does distribute, but it's an accident. It's because you get the identity either way.
An equation is worth a thousand words:
$$(bab^{-1})^2=bab^{-1}bab^{-1}=baab^{-1}=ba^{2}b^{-1}$$
I'm sure you see that if you keep doing this the exponent of $a$ is the only thing that changes. This explains why an element has the same order as its conjugates.
Comment: Oh ok. So algebraically it would be: (bab^-1)^n = (bab^-1)(bab^-1)....(bab^-1) = (a)(a)...(a)=a^n=e
Comment: No, it's $ba^{n}b^{-1}=beb^{-1}=bb^{-1}=e$.
Comment: Oh yeah, damn tiny keys on phone.

Order infinite or finite


Does a VPN requirement kill the concept of having a Web Application in the Cloud?

Question: Recently I posted a question in SO, but so far I got no answers. I wonder if I'm asking the wrong question.
This is the problem:

We need to design an application which
  offers a public http web service, but
  at the same time it must consume some
  services through a VPN connection from
  other existing company. There is no
  other alternative but to use a VPN
  connection to access those services.
  We want to host our application in
  some cloud infrastructure like Heroku
  or Amazon EC2. But there is no direct
  way to access the VPN services of the
  other company from there.

The solution I'm thinking, but I don't like is to have a different server to expose the services from that VPN. But this will require the setup of another server which I prefer to avoid. In the case this is the solution, can I use an Amazon EC2 instance to connect to a VPN?
This is what I was thinking, is it correct?
I don't have experience using VPNs, tunnels or those kind of networking stuff. I will really appreciate if you can propose me an alternative solution, or just give me a comment.
Answer: Are the services you're accessing Web Services, or something else?
If they are web services, then what you've described in your non-ideal setup would work quite well. You would set up a 3rd server that would act as a proxy for your web services, accepting requests from your "cloud" server, and tunneling them over the VPN to the corporate network (This is called a "reverse proxy").
Slapping on SSL (even self-signed would do as you only have to trust yourself) and only permitting the IP address of your "cloud" server through the firewall would even keep it pretty secure, but you're right in that its a lot of additional management overhead (although I've done similar things myself in the past, and once they're running you can usually just leave them alone for years at a time).
What I would suggest is finding a "cloud" provider (I use the term loosly, as a "cloud" server is really just a VPS bundled with a few other external technologies) where you have full administrator/root access to the machine and then create a VPN the way you would normally.
This will probably cost a small amount than other options, but is probably worth it in the long run.
Comment: Yes, those are plain Web Services. Really helpful answer, I was not so wrong then. It didn't occur to me about the self-signed certificate, cool! Just other thing, just to confirm, then with that setup I can use any Amazon EC2 instance, for example, running Ubuntu or CentOS and have a VPN client, right? Are OpenVPN and Openswan the right tools to use?
Comment: @Christian - If you can get access to the console of your OS then you will need to match whatever technology is set up on the other side of the VPN. So if they are using OpenVPN then you will too. If they are using PPTP then you will need to use PPTP, etc. The best way to get help with that is to find out what technology the other end of the VPN is using and if you can't get it working on your server, then search here or ask another question. This is why administrative console access is absolutally critical in getting this to work most of the time.
Comment: I see, it's very clear now. Thankx a lot!
Answer: Yes, I think anything that requires a VPN could not be considered a cloud service per se.  Ideally you would want to be able to hit a URL and log in with your credentials and the service be presented to you, that would be a true cloud service.
Comment: Being "in the cloud" doesn't preclude a VPN - in fact Mark already made an excellent case [in his answer](http://serverfault.com/a/219680/32986) for a situation where a VPN backhaul from "The Cloud" is an entirely sensible configuration, which doesn't preclude the "Hit a URL with your credentials" scenario you're describing (it just changes where some of the data might be coming from)....
Comment: needless to say, amazon VPC can help here.