Problemas com Numeração de Página com iText

Question: Boa tarde pessoal.
Estou precisando criar relatórios com o iText. Tudo estava indo muito bem até a hora em que precisei numerar estes relatórios. Encontrei uma resposta no post de outra pessoa no GUJ, mas não deu muito certo.
Baseado neste tutorial (adequado ao meu contexto) eu consegui numerar apenas a última página de cada PDF. Alguém poderia me dar uma luz de como numerar todos? Melhor ainda se for no modelo "Página 1 de X".
Segue a Classe completa para auxiliar:
public class Relatorio extends PdfPageEventHelper {

    private Font titulos = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD, new BaseColor(73, 146, 255));
    private Font subtitulo = new Font(Font.FontFamily.HELVETICA, 15, Font.BOLD, new BaseColor(73, 146, 255));
    private Font labels = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD);
    private Font content = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL);
    private List lista;
    private String filepath;

    public void onEndPage(PdfWriter w, Document d) {
        PdfContentByte cb = w.getDirectContent();
        cb.saveState();
        try {
            String txt = "Página "+w.getPageNumber();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

            float txtBase = d.top();
            float txtSize = bf.getWidthPoint(txt, 8);
            float adj = bf.getWidthPoint("0", 80);

            cb.beginText();
            cb.setFontAndSize(bf, 8);

            cb.setTextMatrix(d.right() - txtSize - adj, txtBase);
            cb.showText(txt);

            cb.endText();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
        cb.restoreState();
    }

    private void prepararPDF(String nome, int opcao) {
        Document doc = null;
        FileOutputStream fos = null;
        String username = new com.sun.security.auth.module.NTSystem().getName().toString(); // Nome do usuario logado
        String fileName = null;
        filepath = "C:\\Users\\" + username + "\\Desktop\\Relatórios Hydros\\" + nome + "\\";

        try {
            File diretorio = new File(filepath);
            if (!diretorio.exists()) {
                diretorio.mkdirs();
            }

            fileName = "TEMP_" + new SimpleDateFormat("yyyy_MM_dd").format(new Date()).toString() + ".pdf";
            doc = new Document(PageSize.A4, 20, 20, 40, 40);
            fos = new FileOutputStream(filepath + fileName);
            PdfWriter w = PdfWriter.getInstance(doc, fos);

            doc.open();

            switch (opcao) {
                case 1: relatorioReservatorios(doc); break;
                case 2: relatorioBombas(doc); break;
                case 3: relatorioPlacas(doc); break;
                case 4: relatorioPortas(doc); break;
                case 5: relatorioBombasXReservatorios(doc); break;
            }

            onEndPage(w, doc);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (doc != null)
                doc.close();

            if (fos != null) {
                try {
                    fos.close();
                    adicionarMarcaDagua(filepath, fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void adicionarMarcaDagua(String path, String name) {
        try {
            String filepath = path + name;
            String newfilepath = path + name.substring(5);

            PdfReader pdfr = new PdfReader(filepath);
            int paginas = pdfr.getNumberOfPages();

            PdfStamper stamp = new PdfStamper(pdfr, new FileOutputStream(newfilepath));

            int i = 0;
            Image watermark = Image.getInstance("C:\\Users\\Hugo\\Dropbox\\Programação\\Java\\Projetos\\Eduardo\\Hidros\\Workspace\\Hidros\\WebContent\\resources\\img\\watermark.png");

            watermark.setAbsolutePosition(50, 375);
            watermark.scaleAbsolute(500, 110);

            PdfContentByte pdfcb;
            while (i < paginas) {
                i++;
                pdfcb = stamp.getUnderContent(i);
                pdfcb.addImage(watermark);
            }
            stamp.close();
            pdfr.close();

            excluirArquivo(filepath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private void excluirArquivo(String path) {
        File f = new File(path);
        if (f.delete())
            System.out.println("Excluiu");
        else
            System.out.println("Não excluiu");
    }

    private void relatorioReservatorios(Document doc) throws DocumentException {
        Paragraph p = new Paragraph("RELATÓRIO DOS RESERVATÓRIOS - " + new SimpleDateFormat("dd/MM/yyyy").format(new Date()) + "\n", titulos);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        p = new Paragraph("Quantidade: " + lista.size() + " unidades.", subtitulo);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        doc.add(new Paragraph(" "));

        PdfPTable table = new PdfPTable(4);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("NOME", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("CAPACIDADE (Lts)", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("TIPO", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("OBSERVAÇÃO", labels));
        table.addCell(cell);

        Reservatorio r;
        for (int i = 0; i < lista.size(); i++) {
            r = (Reservatorio) lista.get(i);

            // Nome do reservatório
            cell = new PdfPCell(new Phrase(r.getNomeReservatorio(), content));
            table.addCell(cell);

            // Capacidade do reservatório
            cell = new PdfPCell(new Phrase(String.valueOf(r.getCapacidadeReservatorio()), content));
            table.addCell(cell);

            // Tipo do reservatório
            cell = new PdfPCell(new Phrase(r.getTipoReservatorio(), content));
            table.addCell(cell);

            // Observação do reservatório
            cell = new PdfPCell(new Phrase(r.getObsReservatorio(), content));
            table.addCell(cell);
        }

        table.setWidths(new int[] { 80, 80, 80, 80 }); // Largura das colunas
        doc.add(table);
    }

    private void relatorioBombas(Document doc) throws DocumentException {
        Paragraph p = new Paragraph("RELATÓRIO DAS BOMBAS - " + new SimpleDateFormat("dd/MM/yyyy").format(new Date()) + "\n", titulos);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        p = new Paragraph("Quantidade: " + lista.size() + " unidades.", subtitulo);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        doc.add(new Paragraph(" "));

        PdfPTable table = new PdfPTable(4);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("NOME", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("VOLTAGEM (V)", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("POTÊNCIA (W)", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("OBSERVAÇÃO", labels));
        table.addCell(cell);

        Bomba b;
        for (int i = 0; i < lista.size(); i++) {
            b = (Bomba) lista.get(i);

            // Nome da Bomba
            cell = new PdfPCell(new Phrase(b.getNomeBomba(), content));
            table.addCell(cell);

            // Voltagem da Bomba
            cell = new PdfPCell(new Phrase(String.valueOf(b.getVoltagemBomba()), content));
            table.addCell(cell);

            // Potência da Bomba
            cell = new PdfPCell(new Phrase(String.valueOf(b.getPotenciaBomba()), content));
            table.addCell(cell);

            // Observação da Bomba
            cell = new PdfPCell(new Phrase(b.getObsBomba(), content));
            table.addCell(cell);
        }

        table.setWidths(new int[] { 80, 80, 80, 80 }); // Largura das colunas
        doc.add(table);
    }

    private void relatorioPlacas(Document doc) throws DocumentException {
        Paragraph p = new Paragraph("RELATÓRIO DAS PLACAS - " + new SimpleDateFormat("dd/MM/yyyy").format(new Date()) + "\n", titulos);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        p = new Paragraph("Quantidade: " + lista.size() + " unidades.", subtitulo);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        doc.add(new Paragraph(" "));

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("NOME", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("IP", labels));
        table.addCell(cell);

        Placa pl;
        Anchor anchor;
        for (int i = 0; i < lista.size(); i++) {
            pl = (Placa) lista.get(i);

            // Nome da Placa
            cell = new PdfPCell(new Phrase(pl.getNomePlaca(), content));
            table.addCell(cell);

            anchor = new Anchor(String.valueOf(pl.getIpPlaca()));
            anchor.setReference("http://"+pl.getIpPlaca());

            // IP da Placa
            cell = new PdfPCell(anchor);
            table.addCell(cell);
        }

        table.setWidths(new int[] { 80, 80 }); // Largura das colunas
        doc.add(table);
    }

    private void relatorioPortas(Document doc) throws DocumentException {
        Paragraph p = new Paragraph("RELATÓRIO DAS PORTAS - " + new SimpleDateFormat("dd/MM/yyyy").format(new Date()) + "\n", titulos);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        p = new Paragraph("Quantidade: " + lista.size() + " unidades.", subtitulo);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        Porta po;
        Placa pl;
        Bomba b;
        Reservatorio r;

        for (int i = 0; i < lista.size(); i++) {
            PdfPTable table = new PdfPTable(2);
            PdfPCell cell;

            po = (Porta) lista.get(i);
            pl = po.getPlaca();
            b = po.getBomba();
            r = po.getReservatorio();

            // Pular linha
            doc.add(new Paragraph("\n"));

            // Nome da Placa
            cell = new PdfPCell(new Phrase("NOME DA PLACA", labels));
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(pl.getNomePlaca(), content));
            table.addCell(cell);

            // IP da Placa
            cell = new PdfPCell(new Phrase("IP DA PLACA", labels));
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(String.valueOf(pl.getIpPlaca()),
                    content));
            table.addCell(cell);

            // Número da Porta
            cell = new PdfPCell(new Phrase("NÚMERO DA PORTA", labels));
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(String.valueOf(po.getNumeroPorta()),
                    content));
            table.addCell(cell);

            // Número da Porta
            cell = new PdfPCell(new Phrase("TIPO DA PORTA", labels));
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(po.getTipoPorta().getNomeTipoPorta(), content));
            table.addCell(cell);

            // Nome da Bomba
            cell = new PdfPCell(new Phrase("NOME DA BOMBA A QUE ESTÁ VINCULADA", labels));
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(b.getNomeBomba(), content));
            table.addCell(cell);

            // Nome da Bomba
            cell = new PdfPCell(new Phrase("NOME DO RESERVATÓRIO A QUE ESTÁ VINCULADA", labels));
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(r.getNomeReservatorio(), content));
            table.addCell(cell);

            table.setWidths(new int[] { 250, 170 }); // Largura das colunas
            doc.add(table);
        }
    }

    private void relatorioBombasXReservatorios(Document doc) throws DocumentException {
        Paragraph p = new Paragraph("RELATÓRIO DE\nBOMBAS X RESERVATÓRIOS - " + new SimpleDateFormat("dd/MM/yyyy").format(new Date()) + "\n", titulos);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        p = new Paragraph("Quantidade: " + lista.size() + " unidades.", subtitulo);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);

        doc.add(new Paragraph(" "));

        Bomba_Reservatorio br;
        Bomba b;
        Reservatorio r;

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("NOME DA BOMBA", labels));
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("NOME DO RESERVATÓRIO", labels));
        table.addCell(cell);

        for (int i = 0; i < lista.size(); i++) {
            br = (Bomba_Reservatorio) lista.get(i);
            b = br.getBomba();
            r = br.getReservatorio();

            // Nome da Bomba
            cell = new PdfPCell(new Phrase(b.getNomeBomba(), content));
            table.addCell(cell);

            // Nome da Bomba
            cell = new PdfPCell(new Phrase(r.getNomeReservatorio(), content));
            table.addCell(cell);
        }

        table.setWidths(new int[] { 250, 170 }); // Largura das colunas
        doc.add(table);
    }

    public void gerarRelatorio(int op, List lista) throws IOException {
        this.lista = lista;

        switch (op) {
            case 1: prepararPDF("Reservatórios", op); break;
            case 2: prepararPDF("Bombas", op); break;
            case 3: prepararPDF("Placas", op); break;
            case 4: prepararPDF("Portas", op); break;
            case 5: prepararPDF("Bombas X Reservatórios", op); break;
        }

        Runtime.getRuntime().exec("explorer " + filepath);
    }
}

Desde já, obrigado!
Answer: Seu problema é que você está utilizando de forma errada a classe PdfPageEventHelper. No trecho
PdfWriter w = PdfWriter.getInstance(doc, fos);

doc.open();

switch (opcao) {
    case 1: relatorioReservatorios(doc); break;
    case 2: relatorioBombas(doc); break;
    case 3: relatorioPlacas(doc); break;
    case 4: relatorioPortas(doc); break;
    case 5: relatorioBombasXReservatorios(doc); break;
}

onEndPage(w, doc);

você está chamando o método onEndPage(w, doc) depois de gerar o relatório pelo switch.Ou seja, ele adicionará o conteúdo deste método somente na página atual do documento, neste caso, a última.
Este método, assim como o método onStartPage, não devem ser chamados de modo avulso, pois eles são métodos que são automaticamente chamados pelos eventos de endPage e startPage. O que você deve fazer é mudar este trecho para:
PdfWriter w = PdfWriter.getInstance(doc, fos);

w.setPageEvent( this );

doc.open();

switch (opcao) {
    case 1: relatorioReservatorios(doc); break;
    case 2: relatorioBombas(doc); break;
    case 3: relatorioPlacas(doc); break;
    case 4: relatorioPortas(doc); break;
    case 5: relatorioBombasXReservatorios(doc); break;
}

onde this é a classe que extende o PdfPageEventHelper. No seu caso, é a própria classe Relatorio.
Desse modo, você estará atribuindo um "listener" aos eventos de endPage e startPage deste documento e avisando ao iText que, ao chegar ao fim de uma página, o método onEndPage(w, doc) deve ser chamado.
É possível numerar no formato "Página 1 de X", mas o único modo que posso pensar é gerar duas vezes o documento. Na primeira vez, pode ser através de um arquivo temporário, então pode ser utilizado o iText mesmo para verificar quantas páginas este documento possui. Desse modo, ao gerar pela segunda vez, você terá o número de páginas que este documento possuirá.
Considere também separar a classe PdfPageEventHelper e o restante do relatório, o código fica mais organizado e fácil de entender.


How to link fields from a Content Type to an Entityform field

Question: Using Drupal 7. Our Recruiting department will be creating events & at these events want to be able to hand a tablet off to an individual so that they can enter info about themselves:

Name
Address
Email, etc...

After content is submitted the Recruiter then can go in & enter "Notes" about the individual.
I'm using Entityforms for that part.
I've also created a content type for Events.
Data would be Event Type (Career Night, College Fair, etc) Location (Rutgers University, etc) Date of Event, Recruiter (Last name) & after the event enter Number of Attendees.
I'm trying to figure out how to relate an applicant to the event that they attended. I'm not having any luck with Entity References.
I'm thinking the related items would be Event Date, Location, Recruiter. I can't figure this out. Any help would be appreciated.
Comment: `I'm not having any luck with Entity References` What does that mean? If you create an event-type node and a registree-type node, you can perfectly connect them using entity references. What are the problems you are running into?
Comment: I guess what I was trying to say was that I could not figure out how to use Entity Reference. The Event is a content type the Registree is created from an Entityform.
Answer: Thinking of this leads me to the following conclusion. You want to hand over the tablet, meaning it should not be logged in as an administrator or by any other means allow people to see and edit more then then allowed.
So you could do this with simple comments.
Create a content type of event in which you have fields for the date, the name of the event, the location and the recruiter (author?).
Then edit the content type and navigate to this tab:

Here you can add comment fields, including the name and any other information you want from the person. Give anonymous users permission to create comments, but not view them and you are done.
Later if you log in, an admin can edit the comment and add notes.
Another solution would be the webform module. More or less allowing you to create any type of form on any type of node. It comes with a wide variety of fields and a clear admin interface, also allowing exports etc.
Adding notes can be achieved by editing the submission as well.
UPDATE:
I always thought entity forms were for backend forms. You can attach one to a node folloing this tutorial: http://www.sixmiletech.com/content/embedding-entiyform-node
That should solve your entity reference stuggles.
Summary of the video would be to create an entity reference field on the event-node. Configure it to reference to Entity form type(s). On the manage display tab of the content type configure the entity reference to 'Render the entity`.
Now create a node, select the right entity form type and save. You now have a node with an attached form.
Comment: I guess what I was trying to say was that I could not figure out how to use Entity Reference. The Event is a content type the Registree is created from an Entityform.

Events would be entered ahead of time. At an event a person submits their data using the Entityform.

Afterwards reports would need to be generated such as a list of applicants that attended a particular event which I would be using Views to accomplish. I think that's where I'm having my difficulties with Entity References. Related fields would be Event Date, Recruiter Last Name to the Applicant.
Comment: See the video of the update, that covers how to attach an entity form to a node using entity references.
Comment: I actually did try that yesterday. Just couldn't accomplish what I was trying. It would only allow me to use one reference.
Comment: How is you `Resubmit action` configured if you edit the entity form type? You should allow new submissions from anonymous users.
Comment: Edit old submission. So he could go back in to add notes. He's logged in with his own user account not Admin
Comment: This means the form only takes one submission from the same account. It should allow more submissions otherwise this won't work.
Comment: I just checked that. I changed it to Allow New Submission
Answer: I was not able to resolve this with Entity Forms. I did find exactly what I was looking for: Drupal 7 Node Reference Tutorial
I had to create a content type for a "Registrant" & using Node Reference URL was able to tie a registrant to an event. This video explains it perfectly.


How to fix error of two bundle id in my mac project

Question: My mac application project has two compiled binaries and the Sqlite mac framework. Each of these three items has its own info. plist
this is the plist of the main binary

this is the plist of the second binary working for the autorun function(the function works successfully)

plist framework SQLite Mac

and here is the error that gives validate app:

All identifier, profiles, bundle id are registered in the developer profile, as everything is written in the settings General, Signing & Capabilities and other items, but clearly something is wrong I specify! I can't send apps to Mac AppStore for three days! Help!
Comment: "Each of these three items has its own info. plist"  For what!?
Comment: Otherwise, the project does not compile and displays errors that there are not enough settings items... in any case, I did not create them myself - the second binary must be signed to send and the sql framework also requires a signature from the cocoapods source code
Answer: I solved the problem myself! It was necessary to remove the Bundle identifier and bundlenames for the application framework in all windows, and it was also necessary to remove the line in build settings - the key of the Framework search path parameter


A proof using the integration of power series and fundamental theorem of calculus.

Question: Define $f(x) = \frac{x}{1!} + \frac{x^3}{3!} + \dots +\frac{x^{2n-1}}{(2n -1)!}+ \dots$ and $g(x) = 1 + \frac{x^2}{2!} + \dots +\frac{x^{2n}}{(2n)!}+ \dots$ on $\mathbb R.$ Prove that for all $x \in \mathbb R$:

$1 + \int_{0}^{x} f(t)dt = g(x)$.
$\int_{0}^{x} g(t) dt = f(x).$

My thoughts are:
Using the fundamental theorem of calculus together with integration of power series. But I have a problem in applying the fundamental theorem of calculus though. Could someone show me the details please?By the way, I have seen a solution that did not use the fundamental theorem of calculus at all, so maybe I am wrong in this thinking.
Answer: Those power series have an infinite radius of convergences and you can deal with them as if they were polynomials. To be more precise: their convergence is uniform on any bounded interval, and therefore exchanging infinite sums and integrals, as I do below, is allowable. You have\begin{align}1+\int_0^xf(t)\,\mathrm dt&=1+\int_0^x\sum_{n=1}^\infty\frac{t^{2n-1}}{(2n-1)!}\,\mathrm dt\\&=1+\sum_{n=1}^\infty\int_0^x\frac{t^{2n-1}}{(2n-1)!}\,\mathrm dt\\&=1+\sum_{n=1}^\infty\frac{x^{2n}}{(2n)!}\\&=\sum_{n=0}^\infty\frac{x^{2n}}{(2n)!}\\&=g(x).\end{align}The other equality is similar.
Comment: But you used the fundamental theorem of calculus on your third equality, am I correct?
Comment: Yes, I did.${}$


Android Studio: android.intent.category.LAUNCHER Client not ready yet

Question: Every time I try to run my app on my phone I get this message

and it crashes. I don't know how to fix it, I already unchecked Instant Run and installed ADB Idea but still no luck. Any help?
EDIT (build.gradle):
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.fretshot.ihc.sapp"
        minSdkVersion 22
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resValue "string", "google_maps_key", (project.findProperty("GOOGLE_MAPS_API_KEY") ?: "")
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.google.android.gms:play-services-maps:15.0.0'
    implementation 'com.google.android.gms:play-services-location:15.0.0'
    implementation 'com.ncorti:slidetoact:0.3.0'
}

Comment: are you running on Huawei device or on different device have u tested
Comment: Yes I'm using a Huawei device since it's the only one I have to test my apps. But I've never had trouble with it until now.
Comment: Can you paste your build.gradle dependencies?
Comment: So there may be 2 reason for it your `device is not connected properly` or your device already having the application installed in it for `other user` so you need to uninstall for all users from your mobile
Comment: @lidkxx Pasted.
Comment: @DanielMtz ok, thought you may be trying to use play-services dependency in a too broad scope, but your build.gradle seems fine.
Answer: Did you export your launcher activity in AndroidManifest.xml? Seeing you're launching it via adb you need to add:
<activity
    android:name=".yourpackagename.YourActivity"
    android:exported="true"/>

in order for your activity to be adb-launchable. Activities with intent-filter are exported by default.
Comment: I did it but I still get the same error as before.

https://i.stack.imgur.com/OTPhc.jpg
Comment: How would exporting the activity resolve this issue?


Understanding a proof that $|\mathbb{R}^{\mathbb{N}}| = |\mathbb{R}|$

Question: I'm reading a set of lecture notes that gives a proof that $|\mathbb{R}^{\mathbb{N}}| = |\mathbb{R}|$. I don't think I fully follow it, though it makes sense to me that this would give a bijection.
It first notes that $|\mathbb{R}| = |(0,1)|$, so it suffices to defines a bijection $(0,1) \to (0,1)^{\mathbb{N}}$. We do so as follows. Given $x \in (0,1)$ with decimal expansion $x = 0.r_1 r_2 r_3 \ldots$, define
\begin{align*}
x_1 & = 0. r_1 r_3 r_5 r_7 \\
x_2 & = 0.r_2 r_6 r_{10} r_{14} \\
x_3 & = 0.r_4 r_{12} r_{20} r_{28} \\
& \vdots \\
\end{align*}
so I believe the general formula (but I'm not fully sure) comes out to
$$
x_n = \sum\limits_{i=1}^\infty r_{2n - i} \cdot 10^{-i}.
$$
I don't fully understand why this is a bijection, though it seems I really only need it to be a surjection. I can certainly inject $(0,1)$ into $(0,1)^{\mathbb{N}}$ by taking $x \in (0,1)$ and sending it to a constant sequence, so if I can surject $(0,1)$ onto $(0,1)^{\mathbb{N}}$, I can inject $(0,1)^{\mathbb{N}}$ into $(0,1)$ and conclude there exists a bijection by the Schroeder-Bernstein theorem.
The proof, for the sake of well-definedness, surely requires that I make clear which decimal expansion of $x$ I'm using, so I think I need to say, "if $x$ has two decimal expansions, pick the one that doesn't terminate in $9$'s." If I fix a decimal expansion (or a "class" of decimal expansions), I can claim this map is well-defined.
This doesn't guarantee that the resulting expansion of each $x_n$ doesn't terminate in $9$'s, so that may be the reason this is only a surjection. If I pick a sequence in $(0,1)$, I can expand each $x_n$ in a decimal expansion. That gives me a construction of the above form, and then I should be able to reconstruct $x$ by the above pattern. I'm not completely certain about injectivity, but I think it likely will fail because of issues with infinite $9$'s in the decimal expansions.
I would appreciate any help with making sense of this.
Comment: Did you mean $r_{2^{n-1}+(i-1)2^n}$ instead of $r_{2n-i}$?
Comment: These types of considerations are irrelevant to set theory. The set of irrational numbers $I$ is bijective with $\omega^{\omega}$, (via continued fractions) and $|I^n| =|I|$ is easy to show by this identification, further $|I|=|\mathbb{R}|$ is also easy.
Comment: https://math.stackexchange.com/questions/243590/bijection-from-mathbb-r-to-mathbb-rn/243689#243689
Answer: So basically you are trying to turn a sequence to a sequence of sequences. Understanding the key point, the problem can be solved in a nice formal way:
First show that $|\mathbb R|=|\mathbb N^\mathbb N|$.
Secondly show that $|\mathbb N\times \mathbb N|=|\mathbb N|$.
Finally $|\mathbb R|=|\mathbb N^\mathbb N|=|\mathbb N^{\mathbb N\times\mathbb N}|=|(\mathbb N^\mathbb N )^\mathbb N|=|\mathbb R^\mathbb N|$.
The pain of handling different decimal expansions lies in the first step, if you have to use it. The second step is essentially the way you turn a sequence to a sequence of sequences.
Comment: This answer is very nice and it's the way I would have done the proof before reading these lecture notes, but I'm really trying to understand this specific proof, assuming there isn't an error in it.


How to calculate exact sum of the series? Determine if it converges or diverges.

Question: This is the problem:
$$\sum_{n=2}^\infty \frac{n(n-1)}{2^n}$$
How can we write the exact sum of the series and determine if it is converges or not?
Comment: Solution 1: Take two derivatives of $\sum_{n=0}^{\infty}x^n=\frac{1}{1-x}$ and evaluate at $x=\frac{1}{2}$. Solution 2: Multiply its partial sums by $\left(1-\frac{1}{2}\right)^2$.
Comment: [This question](https://math.stackexchange.com/questions/593996/how-to-prove-sum-n-0-infty-fracn22n-6) is pretty similat.
Comment: Welcome to Mathematics Stack Exchange! A quick [tour](https://math.stackexchange.com/tour) will enhance your experience. Here are helpful tips to [write a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960) and [write a good answer](https://stackoverflow.com/help/how-to-answer).
Answer: Convergence is trivial from either the ratio or root tests.
To evaluate the sum, write $f(x):=\sum (x/2)^n=1/(1-x/2)$. Now notice that your sum is $f''(1)$. In other words take two derivatives of the right side and plug in $x=1$. The answer should be 4.
Answer: Hint:
$$\sum_{n=2}^\infty n(n-1)x^n=x^2\Bigl(\sum_{n=2}^\infty n(n-1)x^{n-2}\Bigr)=x^2\Bigl(\sum_{n=0}^\infty x^{n}\Bigr)^{\!''}.$$
Comment: @cansomeonehelpmeout: Yes, of course. Sorry for the mistyping. It's fixed now.
Answer: $$\frac{1}{1-x}=\sum_{n=0}^\infty x^n$$
$$(\frac{1}{1-x})''=\sum_{n=2}^\infty n(n-1)x^{n-2}$$
$$x^2(\frac{1}{1-x})''=\sum_{n=2}^\infty n(n-1)x^{n}$$
$$\frac{2x^2}{(1-x)^3}=\sum_{n=2}^\infty n(n-1)x^{n}$$
now let $x=\frac{1}{2}$


I want to make python identify if `num1` and `num2` were numbers or not in this calculator so that python can notify you're not typing in valid things

Question: I want to make python identify if num1 and num2 were numbers or not in this calculator so that python can notify you're not typing in valid things. Maybe using if statements?
num1 = float(input("Enter a number: "))
num2 = float(input("Enter a number: "))
op = input("What operator would you use?")
if op == "+":
    print(num1 + num2)
elif op == "-":
    print(num1 - num2)
elif op == "*":
    print(num1 * num2)
elif op == "/":
    print(num1 / num2)
else:
    print("Invalid operator")

Answer: You can wrap it in a try-except block:
try:
    num1 = float(input("Enter a number: "))
    num2 = float(input("Enter a number: "))
except ValueError:
    print("Invalid number")

If you wanted to keep prompting the user:
while True:
    try:
        num1 = float(input("Enter a number: "))
        break
    except:
        print("Invalid number")

And do the same for num2.


Why isn't disk space reduced after deleting mails through IMAP with Dovecot?

Question: I'm running an email server with OpenSMTPD and Dovecot on Linux and accessing emails using IMAP with a Thunderbird client. When I delete an email in Thunderbird, why doesn't disk space usage go down?
As an example, one user's mbox files are stored in /var/vmail/${domain}/$[user}/:
$ ls
Archives  Drafts  inbox  Sent  Spam  TrainSpam  Trash

I'm not sure if mbox files are sparse files, so instead of du (which also shows the issue), I expect ls will have the most accurate "effective" file sizes, so I added up all sizes of all files in this directory:
$ ls -al | grep vmail | awk '{print $5}' | paste -sd+ | bc
1119217444

Next, I go to Thunderbird, and delete a large email with attachment which shows a size of 1MB. Thunderbird sends it to the Deleted folder, then I go to the Deleted folder, delete it there, confirm the permanent deletion dialog and re-count the file sizes:
$ ls -al | grep vmail | awk '{print $5}' | paste -sd+ | bc
1119217443

So it went down 1 byte. Perhaps it's just marking it deleted? How to I actually get back the disk space? I understand this may be non-trivial since an mbox file is just a huge, flat file.
Answer: In MBOX format messages are stored in a single huge file one below the other, with a very simple structure:
From firstname.lastname@example.com  Sat Nov 10 06:00:00 2018
From: Author <firstname.lastname@example.com>
To: Recipient <firstname.lastname@example.com>
Subject: Sample message 1

Message body.
>From is escaped. Otherwise it would break the MBOX file.

From firstname.lastname@example.com  Sat Nov 10 06:30:00 2018
From: Author <firstname.lastname@example.com>
To: Recipient <email@example.com>
Subject: Sample message 2

Another message body.

Therefore, deleting a message from the middle of the file will cause rewriting the rest of the file, which might be bad for both performance and data integrity, as the file might became corrupted if the write is interrupted.
One solution is to flag the message as deleted rather than actually deleting it, as it requires only modifying one line while keeping rest of the file intact. This allows combining multiple deletions into a single operation, later.
MozillaZine's article on Compacting folders explains this from the Thunderbird perspective:

When you delete messages in an email client such as Thunderbird they
  aren't physically deleted. Even emptying the Trash does not get rid of
  them. Instead they are marked for deletion and hidden from view. They
  are not physically removed until you "compact" the folder. This is a
  tradeoff done to improve performance in large folders.

Dovecot's article on Mbox Mailbox Format explains how Dovecot handles the problems with MBOX format. The deletion is stored in X-Status: D header added to the message headers.

Dovecot uses C-Client (ie. UW-IMAP, Pine) compatible headers in mbox
  messages to store metadata. These headers are:

X-IMAPbase: Contains UIDVALIDITY, last used UID and list of used keywords
X-IMAP: Same as X-IMAPbase but also specifies that the message is a "pseudo message"
X-UID: Message's allocated UID
Status: R (\Seen) and O (non-\Recent) flags
X-Status: A (\Answered), F (\Flagged), T (\Draft) and D (\Deleted) flags
X-Keywords: Message's keywords
Content-Length: Length of the message body in bytes

Whenever any of these headers exist, Dovecot treats them as its own
  private metadata. It does sanity checks for them, so the headers may
  also be modified or removed completely. None of these headers are sent
  to IMAP/POP3 clients when they read the mail.
Comment: I know you already solved this, but your question was stated *why*. :)
Comment: Thanks! This is a great explanation and explains how Dovecot marks the message as deleted; however, it doesn't directly solve my problem - I found the answer through the `doveadm expunge` command (see my answer to the question). But thank you for the details, I'll upvote.
Answer: Found the dovecot command:
$ doveadm expunge -u $user@$host mailbox Trash all


How to Calculate the following integration?

Question: I need to calculate the following integration.
$$\int_0^\infty \!\,xe^{-tx^2}\, j_\alpha ( u_1 x)j_{\alpha }(u_2 x)dx$$
where
$j_\alpha ( u_1 x)$ and $j_{\alpha }(u_2 x)$ are Bessel functions of the first kind of an integer order $\alpha$.
Comment: What are $u_1$ and $u_2$? Also, the lowercase "j" is usually reserved for [spherical Bessel functions](https://mathworld.wolfram.com/SphericalBesselFunctionoftheFirstKind.html). Usually we use a capital "J" for regular Bessel functions.
Answer: Identity 10.22.67 on DLMF says that
$$\int_0^\infty x\exp(-p^2x^2)J_{\nu}(ax)J_\nu(bx)\mathrm{d}x=\frac{1}{2p^2}\exp\left(-\frac{a^2+b^2}{4p^2}\right)I_\nu\left(\frac{ab}{2p^2}\right)$$
With $I_\nu$ being the modified Bessel function of the first kind of order $\nu$. Plug in $p=\sqrt{t}$ for your answer.


QR code generation from an image?

Question: I wish to know if a QR code can be generated from an image input, like how one can generate QR code from a text input. So that, when I scan the QR code, I should be able to get the image as the scan result.
Can someone please let me know if this is possible?
Comment: You'd have to make a really big QR code block, as the image contains *tons* of information.
Comment: Short answer - no, it's not possible.
Answer: It would have to be either an incredibly small bitmap, or a link to the image hosted somewhere else.  The map of a QR code expands depending on data size, and while I am unsure if there is a technical upper limit, there is almost assuredly a practical upper limit with camera resolution being unable to decipher the massive code.

QR code generation from an image?


Finding a joint log likelihood function given some data and a probability model

Question: I am reviewing some notes on binary data analysis and encountered the following problem Let $y=(1, 1, 1, 1, 0, 0, 0)$ and $x=(0.9, 1.2, 0.5, 1, -0.3, -1.5, -2)$. I make the assumption that $y_i$ ~ $Bin(1, \pi_i)$ and $logit(\pi_i)=x_i\beta$.
How do I draw the join log likelihood function of $y$ (as a function of $\beta$).
Comment: This sounds like a [tag:self-study] question. Try looking [here](https://en.wikipedia.org/wiki/Logistic_regression). Then if you are still stuck, you can [update the question](http://stats.stackexchange.com/tags/self-study/info) to show what you have done so far, and where the remaining issue is (specifically).
Answer: Let's first write down the likelihood function for a $Binomial(1, \pi_i)$ (which by the way is a $Bernoulli(\pi_i)$):
$$L(y_i|\pi_i) = \pi_i^{y_i}(1-\pi_i)^{1-y_i}$$
Notes:

How can you generalize this for $L(\bf{y}|\pi)$ where $\bf{y}$ is a vector representing all of your observations?
Then what happens when you take the log of that function?
You're using a logit link function, namely $logit(\pi_i) = x_i\beta$. What does that make $\pi_i$ in terms of $\beta$? It shouldn't require too much algebra to plug-in this value for $\pi_i$ in your log-likelihood.
To actually "draw" it, I assume you want to make a plot with $\beta$ on the x-axis and $L(y|\beta)$ on the y-axis. That's now a programming question that we can help you with when you get there.

Give that a shot and let us know if you have more questions.


What is the difference between 2/4 and 4/4 when it comes the accented beats?

Question: What is the difference between 2/4 and 4/4 when it comes the accented beats?
I have been taught that 2/4 is popular in faster music like polka. I also see some hymns written in both 4/4 and 2/4. 4/4 is strong-weak-less strong-weak.
2/4 would probably strong-weak or a bar divided into eight notes with strong-weak-less strong-weak.
What do you experts say about this?
Comment: IMO this is entirely down to stylistic convention and there's no absolute reason any time signature has to be accented differently than any other - if the composer wanted, a piece could be written in any meter but directed to be played identically.  There are conventions in different styles to accent different parts in different meters, but from a theoretical standpoint they can all be rendered mathematically equivalent.  You can see different online forums where people debate the meter of popular songs by ear, and this is purely an exercise in futility.
Comment: Close, if not duplicate: [this question](https://music.stackexchange.com/q/77400/2600).
Answer:
2/4 would probably strong-weak or a bar divided into eight notes with strong-weak-less strong-weak.

It's the first one, never the second. That's the difference. Four beats in 4/4 is strong-weak-medium-weak, and four beats in 2/4 is strong-weak-strong-weak.
One way to think of 2/4 is as a march. As in feet going left-right-left-right. So there's a simple two beat alternating feel.
Comment: Would a hymn played in 2/4 sound different from the tune played in 4/4?
Comment: @Hank - it will also depend on *how* it's written out. 4/4 using crotchets should sound about the same as 2/4 using quavers. It also depends *who* is doing the playing!


How to change Admin Url path

Question: I am using magento version 1.8.1. and I want to change admin url path.
Is there any possibility to change admin url path with two slashes after domain name?
I want to like http://test.com/test/admin ?
Many thanks in advance.
Comment: https://www.properhost.com/members/knowledgebase/15/How-to-change-the-Magento-Admin-URL-or-Path.html please check this `note` special character is not allowed in this. make sure you are not using it.
Comment: what you have tried so far...?
Comment: I have followed these 2 methods but its not working for me. its only support one name after domain name. url : http://blog.chapagain.com.np/magento-how-to-change-admin-url-path/
Comment: Is your install in a sub folder of the main domain?
Answer: You can change the route for admin to test from local.xml,
 but as magento request flow takes second param as controller name, it will go searching for app/code/core/Mage/Adminhtml/controllers/AdminContoller , which will throw 404
Instead you can try to make it test_admin..
Hope it helps!
Answer: app\etc\local.xml
<frontName><![CDATA[admin]]></frontName>

or alias in server or alias in htacess

How to change Admin Url path


Getting warnings with SHA512 OpenSSL with unsigned char

Question: I am playing with openssl in C and getting some warnings I like to get rid of and am unsure how to tackle it as the examples I had found seem to do what I am emulating.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>

int main(int argc, char** argv)
{
    int i;
    unsigned char resSHA512[SHA512_DIGEST_LENGTH];
    unsigned char unhashed[1024];

    printf("Input string to hash: ");
    fgets(unhashed, sizeof(unhashed), stdin);
    unhashed[strcspn(unhashed, "\n")] = 0;

    SHA512(unhashed, strlen(unhashed), resSHA512);
    printf("\nSHA512: ");
    for ( i = 0; i < SHA512_DIGEST_LENGTH; i++ )
    {
        printf("%02x", resSHA512[i]);
    }
    printf("\n");
    return 0;
}

I also got an alert that SHA512 has been deprecated by open when I compile on my Mac using openssl I got through it's git repository.  I get no warnings in Linux unless I used the -Wall flag with gcc.
Any help is greatly appreciated, as I am trying to learn new things!
Thank you
Answer: What you're reading in to unhashed is a string, so you should declare it as an array of char.  That will address the warning with the string-related functions.
That leaves you with a warning when calling SHA512 which expects an unsigned char for its first argument.  In this case you can safely cast the argument to unsigned char *.
The warning you see on Mac is because the entire OpenSSL library was marked deprecated on that OS in favor of its own crypto library.


How to emphasise a note in a group of notes in right hand?

Question: I am planning to work on the No.5 Prelude and Fugue in F minor, op.35 by Mendelssohn. When I saw the score and then heard a performance, I noticed that the right hand is playing a series of chords of where the topmost note is emphasised.
   Any suggestions for exercises as to how to achieve this will be welcome.
Answer: The piece itself is a pretty good exercise for this.
Start by practising the right hand with just two "lines" of music - the tune and one note from the accompaniment. Try rotating your hand when you play the notes in the tune, so you get more downwards motion on your little finger.
You can also make it easier by playing more of the accompaniment notes with the left hand - for example the middle Cs in bar 1, the F's in bar 3, etc.
Answer: One of the things that I conceptualize is "leaning" my hand towards the emphasized pitch. For instance, if the uppermost pitch in my right hand needs to be brought out, I conceptualize leaning into the pinky finger of my right hand. The same is true if I need to bring out a middle voice; here I might find myself "leaning into" the thumb. (Note: this is precisely what alephzero mentions, he just uses the word "rotating.")
What's important, though, is to ensure that all pitches still sound together. It's very common for a young student to practice this "leaning into pitches" technique and have the emphasized pitch sound before all of the others. This is almost never ideal; make sure they still sound together!
Another practice tip is to remove the non-emphasized pitches, often resulting in a LH accompaniment and a single RH melody. In doing so, one is able to solidify their interpretation of the melodic line, making it easier for this to come across when the non-emphasized pitches are added in.
Similarly, I've found singing the emphasized pitches while I play also helps.
As always, recording yourself is the best method of tracking your progress. Often we think we're emphasizing a particular line, but then when we record ourselves and play it back, we realize just how much the emphasis is only in our heads, and not actually coming out in the music!
Answer: Play the chord, then slightly lift the fingers on the keys you DON'T want emphasized. Hold it like that. Gymnopedie no. 1 is great for learning this with!


Convolution of $L^1$ and Schwartz function

Question: I had a question regarding convolution. Given $f$ $\in L^1(\mathbb{R})$, is it always possible to find a Schwartz function $g$ such that $f * g$ is Schwartz? I know that such a convolution will always be smooth, but can we make it Schwartz by picking a suitable function $g$? Thanks!
Comment: You want $g\not= 0$?
Comment: Yes. I want a non trivial example. I was wondering if this can be done for any choice of $f \in L^1$ and $g \neq 0$
Answer: No, that is not always possible. Up to rescaling, you may always assume that the absolute value of an $L^1$ function is a probability density function, and the same clearly holds for Schwartz functions. If the pdf of $X$ is $|f|$ and the pdf of $Y$ is $|g|$, then the pdf of $X+Y$ is $|f|*|g|$. If $g$ is a Schwartz function all the central moments of $Y$ are finite, but if the pdf of $X$ behaves like $\frac{c}{(1+x^2)^{5/2}}$ then only the first three central moments of $X$ are finite, so only the first three moments of $X+Y$ are finite and $|f|*|g|$ cannot be a Schwartz function.


What does 'Drupal-friendly' hosting mean?

Question: I'm new to Drupal and web-hosting generally. My question is what constitutes a totally Drupal-friendly host? I know that the installation is made easier by the host provider letting you have SSH access and the ability to extract compressed files on the server.
What else should I look for in a Drupal-friendly host?
Answer: There are some things you may want to look into:
Drupal Requirements:

PHP 5.2+ (Drupal 7)
MySQL Database
128mb Memory Limit (For Heavy Imagecache processing)

Not Requirements but perks:

SSH
Drush
Git (Latest)
Crontabs
Curl
Comment: From http://www.php.net/archive/2011.php#id2011-01-06-1: "All PHP users should note that the PHP 5.2 series is NOT supported anymore. All users are strongly encouraged to upgrade to PHP 5.3.6."
Comment: Thanks, Chris. I appreciate the list-format answer to this question.
Comment: PHP 5.2 is only required by Drupal 7; Drupal 6 is compatible with PHP 4. MySQL is the database engine for which the modules are tested with, but Drupal is compatible with PostgreSQL, even if Drupal code could not behave correctly with PostgreSQL; Drupal 7, then, can also be used together SQLite.
Comment: For Drupal 7, you need to make sure that the necessary PDO (pdo and pdo_mysql if you want to use MySQL) extensions enabled. Some hosters manage to not do that by default. And yes, Drupal 6 does not require PHP 5, but it is totally insane to even think about using PHP4. In fact, even PHP 5.2 is officially unsupported now.
Comment: @Berdir, can you clarify "PHP 5.2 is officially unsupported now"?  PHp 5.2 is the recommended version for D6 installs according to http://drupal.org/requirements.
Answer: Continuing F1234k's list:
4) Drupal fanatic:

APC cache for better PHP performance
Varnish proxy cache for faster content delivery
Memcache for faster storage of temporary data
Apache Solr for far better search functionality
Fully managed hosting infrastructure
Support staff with actual Drupal experience
Comment: We have to add that these specifications above are for only  VPS or dedicated, and not for shared hosting. I suppose if someone has root access, he can define his own specifications. I think the question was about shared hosting, where someone has no such control.
Comment: If someone has a good and fast shared hosting account and not a big site, then he may not miss APC/Varnish/Memcache, because these refer to performance. One may miss, though, Solr which adds extra functionality. There are companies out there that offer Solr hosting, and someone can use them in combination with their shared hosting account.
Comment: Thanks, geewiz. The last two points would be truly 'fanatical'.
Comment: don't forget mysql and files residing on the same server, there is a pretty large performance penalty without that.
Answer: "Drupal-friendly" hosting is a term that can be interpreted in many different ways depending on what kind of site you are planning to build and what kind of user you are. If I had to break it down to "levels of friendliness" I would say the following:
1) Drupal tolerant:

PHP 5.2.5,
MySQL,
Apache (preferrably)

2) Drupal friendly:

ability to change your PHP memory allocation to 96MB or more (Views is a common example that needs lots of memory)
ability to change your PHP max execution time (30+ seconds)
php safe mode: off
enabled pdo (more info here)
php register globals: off

(almost all of the above are met, if you can customize your php.ini file)
3) Drupal loving:

SSH
Drush installable (even better: through GUI)
crontab access (there is an alternative for drupal 6, poormanscron, but comes with performance penalties if my memory serves well)
Comment: Thorough and very helpful answer. Thank you! I've since purchased hosting, but your details on PHP are appreciated.
Answer: Personally I think that friendly Drupal hosting is not just a hosting providing you the basic set of Apache + PHP + MySQL. Because you still have to configure all dependencies to make it work reliable and fast.
And every Drupal expert knows that if you want your Drupal website work fast, you have to use fast cache storages like Redis/Memcahe and reverse cache proxy Varnish.
There are few hosting providers who provides out of the box this infrastructure configured specifically for Drupal:

Acquia Cloud - Mostly for enterprise. Built on top of Amazon Web Services
Pantheon.io - Built on top of Rackspace
Platform.sh - Built on top of Amazon Web Services

The last two is very similar and use container virtualization, but they aren't cheap.
As an alternative, you can try Wodby. It's not a hosting provider, but a cloud infrastructure service that will bring features similar to Pantheon.io/Platform.sh on any server, i.e. makes your own server Drupal friendly. It's built on top of Docker.
Comment: +1 for this contribution. When I first asked this question, cloud services were in a much different place. I don't use Drupal anymore, but if I did I would probably opt for a solution such as this.


Dangling reference for smart pointer in C++

Question: I understand that in C++ it is best/safer to use smart pointers in order to make sure we never miss freeing/deleting the allocated memory. Now I recently came across the following in a lecture about smart pointers in C++. This is the example:
void test_pointer(void)
{
    typedef std::shared_ptr<MyObject> MyObjectPtr;
    MyObjectPtr p1; // Empty

    {
        MyObjectPtr p2(new MyObject());
        p1 = p2;
    }
}

Now I understand that std:shared_ptr will be destroyed after the last reference of it is done, ie after we exit the function p1 will be destroyed. But the warning at the end was about a dangling reference, which is what confused me:
MyObjectPtr* pp = new MyObjectPtr(new MyObject());

The Note mentions that if this was declared within the function then it is a dangling reference, which prevents the std::shared_ptr from ever being deleted. Why is that? We are using smart pointers so we should never end up in this situation?
Comment: The sanity of a manually managed pointer to a smart pointer is something you should probably consider a *tremendous* code smell.
Answer: I just realized it (and please correct me if I'm wrong):
We are using a raw pointer to the std::shared_ptr which is never being freed which is what is causing the issue. It is never been freed. and since this is happening with in the function then it prevents p1 as well from being destroyed.
Comment: Yes, exactly that.
Answer:
How come? We are using smart pointers so we should never end up in this situation?

You are not. Here:
MyObjectPtr* pp = new MyObjectPtr(new MyObject());

You are using raw pointer to an object which type is a smart pointer. But it does not mater what kind of object you allocate manually and keep in raw pointer - you have to manage that object lifetime manually. Or use a smart pointer.


Statements about modules (generators and linearly independent sets)

Question: I am trying to prove or disprove with a counterexample the following statements:
(i) From every set of generators of a module $M$ one can extract a basis.
(ii) Every linearly independent subset of a module $M$ can be extended to a basis.
I am pretty sure none of them is true since if this was the case, then every module $M$ would be a free module however I can't think of any counterexamples, any suggestions would be appreciated.
Answer: As you say, take any non-free module, for example $\mathbb{Z}/2$ over $\mathbb{Z}$. But even for free modules the claims (i) and (ii) are wrong.
(i) $\{2,3\}$ is a generating set of the $\mathbb{Z}$-module $\mathbb{Z}$, but it does not contain a basis.
(ii) $\{2\}$ is a linearly independent subset of the $\mathbb{Z}$-module $\mathbb{Z}$, but it cannot be extended to a basis (since this would have to cardinality $1$, but $\{2\}$ is no basis.)


Create a new column after comparing two or more columns from two dataframe

Question: Requirement:
I have two csv files named S1 and S2. Both sheet have Contact_ID as common value. I want to fetch all the records which satisfy the given conditions.
Table/Sheet Structure:
S1[Contact_ID, T1, T2, T3]      primary_key = Contact_ID and foreign_key = Contact_ID2
S2[Contact_ID2, L1, L2, L3]
Compare T1, T2, T3 to L1, L2, L3 respectively then return Contact_ID and print YES/NO (in new column) if they matched.
Output:
S3(Contact_ID,Contact_ID2, T1, L1, T2, L2, T3, L3, Matched)
New sheet(S3) should have columns (Contact_ID,Contact_ID2, T1, L1, T2, L2, T3, L3, Matched)
"Matched" columns will stored the YES/NO/Not Applicable value.
TABLE S1
Contact_ID2 L1      L2              L3
590474  Voice   Can't Be Called Fast Busy
590000  Voice   Circuit         Circuit Down
590744  Voice   Circuit         Circuit Down
588642  Voice   Can't Call Out  Cannot Call Out

TABLE S2
Contact_ID  T1      T2              T3
588439  Voice   Circuit         Circuit Down
588984  Voice   Call Quality    Static/Noise
590000  Voice   No Dial Tone    No Dial Tone
588563  Voice   No Dial Tone    No Dial Tone
588642  Voice   Can't Call Out  Cannot Call Out

Expected Output: TABLE S3
Contact_ID2 L1      L2              L3              Contact_ID  T1      T2              T3              Matched
590474  Voice   Can't Be Called Fast Busy                                                           NO
590000  Voice   Circuit         Circuit Down    590000  Voice   No Dial Tone    No Dial Tone    NO
590744  Voice   Circuit         Circuit Down                                                        NO
588642  Voice   Can't Call Out  Cannot Call Out 588642  Voice   Can't Call Out  Cannot Call Out YES

My Approach:

I have merged both the sheets using Left Join w.r.t Contact_ID and saved in sheet S3.[need all S1 data, hence left join.]
In S3, Check if Contact_ID equals to Contact_ID2 ,if True, then
2.1. Check if (T1 == L1),( T2 == L2) & (T3 == L3)  if True, Print YES in new column
2.2. Else if any (T1 != L1) OR (T2 != L2) OR (T3 != L3) then print NO

In S3, if (Contact_ID != Contact_ID2) ,Print "Not Applicable".

My Code:
    import pandas as pd
    import numpy as np
    pd.options.mode.chained_assignment = None  # default='warn'

    S1_data = {'Contact_ID' : [590474,590000, 590744, 588642],
           'L1' :['Voice','Voice','Voice','Voice'],
           'L2' :['Can\'t Be Called', 'Circuit','Circuit','Can\'t Call Out'],
           'L3' :['Fast Busy','Circuit Down', 'Circuit Down','Cannot Call Out']
          }

    S2_data = {'Contact_ID2' : [588439,588984,590000, 588563, 588642],
           'T1' :['Voice','Voice','Voice','Voice','Voice'],
           'T2' :['Circuit', 'Call Quality','No Dial Tone','No Dial Tone','Can\'t Call Out'],
           'T3' :['Circuit Down','Static/Noise', 'No Dial Tone','No Dial Tone','Cannot Call Out']}

    S1 = pd.DataFrame(S1_data)
    S2 = pd.DataFrame(S2_data)

    S3 = pd.merge(S1, S2, how = 'left', left_on = ['Contact_ID'], right_on = ['Contact_ID2'])

    if S3['Contact_ID'] == S3['Contact_ID2']:
        if (S3['T1'] == S3['L1']) & (S3['T2'] == S3['L2']) & (S3['T3'] == S3['L3']):
            S3.iloc[:,'Matched'] = 'YES'
        else:
            S3.loc[:,'Matched'] = 'NO'

    else:
        S3.iloc[:,'Matched'] = 'NA'

Comment: Could you display `S1` and `S2`, please? `S1.head()` should be sufficient.
Comment: @Corralien I have added the sample dummy data for better understanding.
Comment: Use text rather than image. [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: @Corralien I have added the table now. Please see if it fits the requirement and now can you please help me solve this?
Comment: What is the output of `print(S1)` and `print(S2)`. I need to load `S1` and `S2` as a dataframe. https://stackoverflow.com/a/20159305/15239951
Comment: @Corralien Updated the code with S1 and S2 data.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/233915/discussion-between-chandan-kumar-yadav-and-corralien).
Answer: Merge using outer to get union of S1 and S2, evaluate your conditions (T1 == L1, T2 == L2, T3 == L3) and fix inconsistent Contact_ID != Contact_ID2:
S3 = pd.merge(S1, S2, how='outer', left_on=['Contact_ID'], right_on = ['Contact_ID2'])

S3['Matched'] = (S3['T1'] == S3['L1']) & (S3['T2'] == S3['L2']) & (S3['T3'] == S3['L3'])
S3.loc[S3['Contact_ID'] != S3['Contact_ID2'], 'Matched'] = pd.NA

S3['Matched'] = S3['Matched'].replace({True: 'YES', False: 'NO'})

>>> S3[['Contact_ID', 'Contact_ID2', 'Matched']]
   Contact_ID  Contact_ID2 Matched
0  59017474.0          NaN    <NA>
1  59011000.0   59011000.0      NO
2  59031744.0          NaN    <NA>
3  58838642.0   58838642.0     YES
4         NaN   58837439.0    <NA>
5         NaN   58837984.0    <NA>
6         NaN   58838563.0    <NA>

Comment: Is it what you expect?
Comment: Not exactly, but I was able to further modify my code with your above code and finally got my expected output.  I am giving the solution in the new answer. You can upvote that , if you think that is a good approach. :)
Answer: Posting my final accepted answer. It may be helpful to others.
Merge both table S1 and  S2 and then evaluate the condition and removed the S3['Contact_ID'] != S3['Contact_ID2'] with the Not Applicable
Lastly, update the the True and False with YES & NO.
# Join the crm_data and nlp_data
S3 = pd.merge(S1, S2, how='left', left_on=['Contact_ID2'], right_on = ['Contact_ID'], indicator = True)

# Check if ContactID, Tier1, Tier2, Tier3 are matching or not in S2 and S1
S3['Matched'] = (S3['L1'] == S3['T1']) & (S3['L2'] == S3['T2']) & (S3['L3'] == S3['T3']) & (S3['Contact_ID'] == S3['Contact_ID2'])
S3.loc[S3['Contact_ID'] != S3['Contact_ID2'], 'Matched'] = pd.NA
S3['Matched'] = S3['Matched'].replace({True: 'YES', False: 'NO'}) # Replace True -> YES and False -> NO

S3.drop(['_merge'], axis = 1, inplace = True)  #Drop the _merge column

>>> S3
Contact_ID2 L1      L2              L3              Contact_ID  T1      T2              T3              Matched
590474  Voice   Can't Be Called Fast Busy                                                           NO
590000  Voice   Circuit         Circuit Down    590000  Voice   No Dial Tone    No Dial Tone    NO
590744  Voice   Circuit         Circuit Down                                                        NO
588642  Voice   Can't Call Out  Cannot Call Out 588642  Voice   Can't Call Out  Cannot Call Out YES


Infinite series of converging sequence: $\sum_{n=1}^{\infty}\frac{1}{n2^n}=\ln 2$

Question: How can I prove the following equality;
$$\sum_{n=1}^{\infty}\frac{1}{n2^n}=\ln 2\,.$$
Comment: $$- \ln(1-x) = \sum_{n \ge 1} \frac{x^{n}}{n}$$ with a particular value of $x$.
Answer: Notice that
$$\frac1{1-r}=\sum_{n=0}^\infty r^n$$
Integrate both sides with respect to $r$ from $0$ to $x$ to get that
$$-\ln(1-x)=\sum_{n=0}^\infty\frac{x^{n+1}}{n+1}=\sum_{n=1}^\infty\frac{x^n}n$$
Now proceed to use $x=1/2$.
Comment: The right idea. In an exam I would insist that you justify, why it is ok to integrate this infinite series term-by-term.
Comment: Because $\sum_{n=0}^{k}r^k$ converge uniformly to $\frac{1}{1-r}$ in $[-a,a]$ for $|a|<1$ as $k\rightarrow\infty\,.$
Comment: @David I think you ought to check that?  I think we need DCT here.


guitar cabinet: why not just use a PA speaker cabinet?

Question: I've been thinking about building myself a rackmount rig to replace an old 12" combo amp, and was wondering if it really makes any difference to use a something that's marketed as a "guitar" speaker cabinet... Why not just select a nice PA speaker that's ostensibly already built to faithfully reproduce whatever is pushed through it?
This is especially of interest to me because I'd like to be able to use this rig for electric guitar, acoustic guitar, and mandolin. Ideally I'd have a rackmount preamp for the electric guitar and use a Baggs DI direct into the power amp for the acoustic instruments, and get appropriate tones on each instrument through one speaker cabinet.
Comment: There is one situation where using a full range, full frequency reproduction system like a PA makes a lot of sense: that is if you're using modelling technology like a Pod or an Axe-Fx that include speaker cabinet simulation. In that case, the use of an FRFR amplification system is one of the best ways to enjoy your rig, loud.
Comment: Yeah, that's a really good point, thanks. I have the option of using a SansAmp GT2 in the electric guitar section of the rig, which does have speaker cabinet emulation baked in.
Comment: Cabinet emulation is good. If you go dry, definitely do that. It's an extra set of algorithms that can make you sound slightly more natural--which is important when playing electric but not so much with acoustic.
Answer: There's absolutely nothing wrong with using a PA speaker cabinet, especially if you plan to play amplified acoustic instruments through the rig. It might even produce a better overall sound with these.
Guitar cabinets are designed for a very specific purpose - electric guitar amplification and thus have their construction optimised for this purpose. They will generally have a limited frequency response - in the range best suited to the electric guitar - and will genrally be more robust than the typical PA speaker in terms of handling level and square-shaped waveforms, such as distorted guitar. Like guitar amplifiers, guitar cabinets are generally designed with a specific sound in mind and will contribute to the overall tone. This actually makes them less-suited for general amplification jobs, since they tend to colour the sound too much.
The drawback of using a standard PA speaker for an electric guitar amplification system is that it does faithfully represent whatever is fed through it, thus losing the aforementioned speaker colouration that is an element of many guitar tones and producing a sound not unlike a DI-ed guitar, which is disliked by many guitarists. You should try out both options before choosing one or the other.
Comment: Limited frequency response is key, but note that it's got less to do with the design of the cabinet and much to do with the choice of speaker. You can find guitar-specific speakers in a range of frequency-limiting bands and they all sound markedly different.
Comment: Cabinet designs are important. Closed back sounds completely different than open back and partially closed back. This is pretty much right on though. Good answer.
Answer: It is good to note that the difference between an acoustic guitar and an electric guitar.
The acoustic guitar is the full instrument.
The electric guitar is only one half of an instrument, the electric guitar and the electric guitar amplifier is the full instrument.
The electric guitar signals are raw and needs to be processed by the electric guitar amplifier to get the best results. That is why there are many effect boxes that can be used to further process the raw electric guitar signals before they are being amplified.
An electric guitar signals is like a wild horse that needs to be tamed before it is safe to ride it. Although it may seems ironic, the electric guitar signals may also be made more "wild" but in a controlled manner (distortion, overdrive, etc). The waveform is being shaped but the wild swing in amplitudes and frequencies (desired and undesired) are being moderated before they are being sent to the listeners' ears.
If you need to use your electric guitar on a regular PA amplifier, it will be good to let the signal go through an equalizer or effect box so you can shape and control the signal levels.
Answer: For Guitar, I totally agree with using PA amplifiers and cabinets loaded with ProAudio speakers, provided you are using a high-end guitar processor such as Fractal Axe FX, Avid Eleven rack, Roland VG99, etc. Virtually all guitar amplifiers include coloration such as tone controls, distortion/overdrive, presence, reverb, that would need to be set flat, neutral, or OFF. These features become redundant and even unwanted.
Today's processors do it all, including dynamics, delay, pitch-shifting, you name it. The guitar amplifier becomes nothing more than a power amp, neutral in all respects. If every patch you command from your pedal has custom settings designed to fine-tune that sound, why add further color from your amp head and speakers?
Now, let's talk about speakers. The whole idea behind a "guitar speaker" is to reproduce the range of frequencies a guitar is capable of. In addition, a design that allows for a desirable "break-over" point, both resulting in a characteristic rock&roll tone, and tolerating being overdriven without damage. ProAudio reproduces almost exactly what you feed it at a broad range of volume levels. The average Celestion, Eminence or Fane speaker, etc. is rated at 75 to 200 watts RMS and is intended to be overdriven, while ProAudio (for a 12") would be best specified at around 500 watts, and should never be overdriven. Generally, they offer a usable frequency range of 40-4000hz. The Roland VG99 processor is capable of dropping you down a full octave. Although you might not use those patches very often it would be nice to have a system that can support frequencies low enough to enable you to hang with your bass player.
The bottom line is: If you must have a true "vintage" sound, go with analog stomp-boxes, tube amps and a good sealed cabinet designed to give you that "Marshall" sound.
Otherwise it's digital all the way!
Answer: Bad for electric guitar sound. The horn will cause horrible high-pitched feedback. Use a guitar or bass cab.
Fine for acoustic guitar, but then, why not just use monitors?
Fine for upright bass reinforcement.
Not good for electric rock bass, you won't get character sound. The clean sound of the horn is nice for jazz bass.
Answer: I have been playing through not only a p/a speaker, but using a full stereo p/a amplifier.
This is because I have been fully converted to Modelling technologies. Up until recently I was using a VOX Tonelab LE, and it finally took a crap so I picked up an HD500. I have better sound than anybody on an standard amp, and it's versatile as hell. I can go clean and have what sounds just like a fender twin cranked, and then immediately jump to a dual rectifier. Using an amp you are severely limited by the amp itself, and your sound will be shaped by it. If you haven't tried a multi-effects processor with amp-modelling through a full p/a you're missing out. (I no longer own an amp, and I never will again)
Also, I run a full 800 watt stereo p/a for my guitar, and it's life changing. I don't wash out with high level amp distortion as many wind up doing when they try to crank their amp in a small room. Basically the dynamics are unbelievable. I have had many a band come asking about how the hell I get my sound.
Go try it for yourself, and you'll kick yourself for buying a massive amp that isn't as good! I would love to pick up an AxeFX-2 but I'm just not that rich right now! ;) The POD is a little thinner than the VOX, but VOX is built like crap. If you're gonna use a VOX, get a midi controller, and stick it somewhere safe. Really that's good advice for any of them! Midi controllers are cheaper!
Answer: I used a Dayton XO2W-3.5K crossover. Cost $35.00. Installed it in a passive American audio cabinet with existing 15 in. speaker and horn/driver, $35.00 craigs list. Replaced the 15 in. with an Altec 421A that I already had. There all over on Ebay. Replaced the driver with an Altec 802-D that I also had. It's night and day differance in sound. I just use a Modeling amp, the Vox VT20+ with an simple added 1/4 in. out jack. Of course you can EQ it any way you wish. I like the sound because it retained the tone I was looking for. It's a cheap way to go. Honestly, it sounded pretty darn good with the original hardware.
Answer: With today's amp modeler you don't really need a Guitar amp. Using a guitar amplifier will just color the tone from your amp modeler. PA is way better.
If you are going to use an AMP modeler DON'T BUY a GUITAR AMP.
Comment: This really depends on what kind of amp modeling you are doing and how you have it set up. There are so many combinations and possibilities that it doesn't really work to say you would never connect a modeling amp to a guitar cabinet. The real question is whether you are using speaker simulation at any point in the signal chain. No speaker simulation - use a guitar cabinet. With speaker simulation - use a PA cabinet or go direct.
Answer: I agree with not using a guitar amplifier with fx modellers, but - there are guitar amplifiers with a POWER AMP input, and that's a good option, because you've got the chance to change from the modeller sound to stompboxes or just input the guitar directly into the amp. I've tried in a live performance a Peavey amplifier (I don't remember the model) with my POD XT (bean) and its power amp input, and it sounds fine, maybe some equalizer was needed between the modeller and the amp, but the final result was fine. Although I must say that I've tried a PA system and the sound was amazing, pure and powerful.
Answer: Without modelling and ground lift, it is a bad idea. Distorted guitar into PA without either of those may !) damage the PA speakers 2) Produce a lot of noise.
There is a good reason we guitarists mic up our tube amps.


Standardized python binary location?

Question: On a native Mac OS X install, I see Python binary at /usr/bin at version 2.6
Recently I installed Python 2.7.2 from the official binaries and it installed it at /usr/local/bin
What path of the Python interpreter should I give in my #! which will be standardized across all platforms?
I am assuming it could be /usr/bin so that I may have to symlink /usr/bin/python to /usr/local/bin/python but I just wanted to sure before I do this
Answer: Nope. You would use env to find the python executable in $PATH and run it as appropriate.
#!/usr/bin/env python

print 'Hi mom!'

Comment: But first you have to have the right directory on your PATH.  For OS X Python framework installs, that's not necessarily obvious.  `/usr/local/bin` isn't sufficient when you install third-party packages with scripts.  You need to include the framework `bin` directory; various distributors of OS X Pythons use different locations for their framework roots.
Comment: Evangelize the python3!! `print('Hi Mum!')`
Answer: On Mac OS X, do not modify anything in /usr (including /usr/bin) other than /usr/local, nor anything in /System/Library.  Those directory spaces are managed by Apple as part of OS X.  You risk breaking your system if you change or delete the wrong thing there.  The best way to manage different versions is to modify your shell PATH environment variable; then you can use /usr/bin/env if needed.  You can also use shell aliases or just use absolute paths.  The Python installers from python.org have an option to automatically modify your shell initialization files appropriately.

Standardized python binary location?


How to prevent slow printer performance when AD is not available

Question: When I take a domain based computer (Windows XP) and plug it into a network that doesn't have access to the AD, the first time I select a local printer (printing directly to printer) on the current network it takes a good 20-30 seconds before I can select the printer.  Doing a little investigating using wireshark I can see the computer is trying to hit AD for some reason and it just keeps timing out.  I also tried the same experiment with just a plain workgroup computer and it was able to bring the printer up immediately.  Does anyone know how to prevent the machine from trying to contact AD?
Comment: Are you logging in with cached credentials, or a local account?
Comment: The printer is not shared or published in AD.
Answer: Manually add the printer using a local TCP/IP port. This will make your client to point directly to the printer IP but of course you will lose the printer server queue management advantages as you are printing directly to printer.
Regards, D.


Jquery table cell to input not working

Question: I am trying to implement an editable table using jquery. It is working fine but after I click it again it shows <input type="text">
To simplify problem statement :-

While I click in a cell it becomes editable.
When I click in another cell all cell values becomes <input type="text">
I am losing the values I input in one cell as soon as I click to another cell.

My fiddle is here :-
https://jsfiddle.net/6g9nwhqo/
jquery is :-
$('#editTable').click(function () {
    $('td').each(function () {
        var html = $(this).html();
        var input = $('<input type="text" />');
        input.val(html);
        $(this).html(input);
    });
});

Comment: why not just add an `attribute contenteditable` on the td check this
Comment: http://mrbool.com/how-to-create-an-editable-html-table-with-jquery/27425
Comment: where did you get this... I never heard of this
Answer: $('#editTable').click will be called each time you click, so when you change first time, all td changed with input, when you click next time on input tag it gets propagated to  #editTable, you can use $('#editTable').one('click' as below
$('#editTable').one('click', function () {
    $('td').each(function () {
        var html = $(this).html();
        var input = $('<input type="text" />');
        input.val(html);
        $(this).html(input);
    });
});

Answer: Try checking td for input element before adding
$("#editParamValues").click(function() {
  $("td").each(function() {
      if (!$("input", this).length) {
        var html = $(this).html();
        var input = $("<input type=text />");
        input.val(html);
        $(this).html(input);
      }
  });
});

Comment: upvote, but for each click its going to iterate on all `td`
Comment: @JagsSparrow Could use `:not()` , `:has()` to prevent iteration of each `td` at each `click` event https://jsfiddle.net/6g9nwhqo/5/ ; not certain if `.each()` is utilized for other processes not included at OP

Jquery table cell to input not working


Access Domain over Wireless

Question: I have an active directory server and all hard wired clients connect perfectly fine. However any wireless clients do not recognize that they are connected to the domain, despite the dns server being appropriately set to the domain controller for both wired and wireless connections. Also - both wired and wireless clients are on the same subnet.
I am using a Verizon food actiontec router.
What am I missing?
For instance, this is the same computer connected first via an Ethernet cable and second via the wireless.
Comment: What do you mean with "do not recognize that they're connected to the domain"?
Comment: @Joren - see my update with pictures -
Comment: Can you ping the domain controller from the wireless client?
Comment: Is your wireless network the same IP range as your wired? As in; does your DHCP server give IP addresses to your wireless clients or does the AP also use DHCP?
Comment: @Joren - there is only a single DHCP server which handles both wired and wireless (i.e. there is a single IP range).
Comment: @Ron - Yes I am able to ping the domain controller from the wireless client without any issue - it works with either the direct address and via domain name resolution (i.e. "ping 192.168.1.2" and "ping ADSERVER" both work.
Comment: @William in that case, I suspect it's not actually a networking issue, but perhaps something in Windows that isn't set up right.  You might try asking on Serverfault or Superuser forums to see if they might have an idea.
Comment: Please add [more details](http://meta.networkengineering.stackexchange.com/questions/292/network-engineering-question-checklist) to the question.  Specifically,  a map of the wireless subnets, how they are connected,  what equipment connects them, and hopefully configs for the equipment
Comment: It may be the "home group" setting in win7 causing issues.  If wireless is not told its a business network it may be firewalling or other odd things to traffic needed to allow a full domain connection. wifi has always been problematic at best even when using cisco every thing in a enterprise.
Comment: @Kendrick how would you 'tell' wireless that it is a business network?
Answer: I figured it out.
I had an old DirectAccess configuration in the Group Policies of my Domain Server.  For some reason, this was not allowing any 'remote' connection to be part of the domain (so anything connecting via Wireless or VPN).
When I removed these policies, everything starting working as expected!
Answer: http://windows.microsoft.com/en-us/windows/choosing-network-location#1TC=windows-7
http://support.microsoft.com/kb/2578723
The top one explains about what the "home group is" the bottom should make it changeable if it isn't any more. Another possibility is whether or not your wireless is set with enterprise settings. It may need a authentication method like radius or something to change it to domain, I haven't looked closely at what work wireless connections say for type so not 100% sure. The enterprise networks I have used were admined by others so not sure how they work. My instincts are saying its windows firewall which is auto configured by that home group setting. you may want to temporarly turn off all firewalls on one of the pc's and see if it connects normally then.  that would verify if it is firewall related.
Comment: I really don't think that Homegroup comes into play here.  All of the clients in question are already members of the domain -

Access Domain over Wireless


What content do the charts from the Lydian Chromatic Concept of Tonal Organization contain?

Question: I recently purchased George Russell's seminal work, the Lydian Chromatic Concept of Tonal Organization, however my used copy is missing its fold-out charts. The text refers these charts extensively. What information is presented there? Or alternatively, where may I acquire a copy of them to complete my volume?
Answer: Try this: http://monoskop.org/File:Russell_George_Lydian_Chromatic_Concept_of_Tonal_Organization_4th_ed.pdf
I can't download it at work, but it probably has what you're looking for.  If it does, let me know and I'll tell you how I found it.
Comment: I googled "Lydian Chromatic concept of tonal" and it was the first thing I saw.  :)
Comment: When you're googling your way through the internet to find things like this, it's a good idea to look for "pdf" files. When I put in those words, one of the results in the little dropdown menu was "lydian chromatic concept of tonal organization pdf". I picked that one. You will often be able to find entire books and the like in links to pdf files. So, if you see a link to a pdf file, it's a good idea to have a look at it.
Comment: From what I can tell it has one chart, Chart A.
Comment: Thank you! Yes, it includes the chart. My copy is from a 1950's typewriter manuscript. The typesetting for this version is far superior. THANK YOU. (And yes, I would like to learn how you discovered it too.)
Comment: When I researched this some time ago, I only found the site selling this latest printing. I wound up buying an old, albeit incomplete, printing from an online auction. This will aid my study...


Find the determinants of the following matrices

Question:
Let
  $$\det\begin{bmatrix}
   a& b & c   \\
   d & e & f   \\
   g & h & i
\end{bmatrix} = 5.$$
  Find the determinants of the following:
  $$1)\quad
\begin{bmatrix}
   a& b & c   \\
   g & h & i   \\
   d & e & f
\end{bmatrix},
\quad
2)\quad
\begin{bmatrix}
   d& e & f   \\
   g & h & i   \\
   a & b & c
\end{bmatrix},\quad
3)\quad
\begin{bmatrix}
   a& b & b   \\
   d & e & e   \\
   g & h & h
\end{bmatrix}.$$
Comment: What have you tried? Do you know the basic properties of a determinant? how it's value changes after row/column exchanges?
Comment: Exactly the same question was asked 15 minutes ago by [this gentleman](http://math.stackexchange.com/questions/1658177/if-deta-5-find-the-determinant-of-the-following). They must be doing the same homework assignment.
Comment: @DietrichBurde The determinant of the first matrix is 5, he's asking the determinant of all others.
Comment: I think you can find the determinant of a $3\times3$ matrix by your own. It's elementary algebra. Thence, you can solve the associate equations.
Comment: @Nikunj  The first matrix is A where det(A) =5 using that information i have to find the determinant of other 3 matrices
Comment: @bubba seems he has deleted the question
Comment: @DhanuRaja I know that, I want to know what you yourself have tried
Comment: @Nikunj well i went through the properties of determinant. But i dint find such property to tackle this questions
Comment: @DhanuRaja Seriously? Your book doesn't have row column exchange properties?
Answer: Hint: you have probably learned that the value of a determinant changes in certain predictable ways when you swap two rows, permute the rows, etc.
For part #3, if you can't find any clever approach, just compute the determinant from the definition:
$$
\text{determinant} = a(eh-he) - b(dh - ge) + \ldots
$$
Comment: in Question 3, two columns are same so the determinant should be zero (i just learnt)
Comment: Correct. Very good. And you can confirm that it's zero by completing the computation that I started for you. Now look in the same section of your book for some other useful facts about determinants.


Two constraints in single column

Question: My table contains a column named 'Email'. Now I want if someone provide an Email,SQL check the validation or if someone forgot to provide Email,SQL hold the default value 'None'.
How can I do that?
Comment: I'm definitely no DB expert but you could look into computed columns
Comment: Which database are you targetting?
Comment: I am using MSSQL 2016.
Answer: Im not sure which database you are working on. This will work on Postgresql.
While creating the table, add constraint on the email column like this,
create table email_test
(email text  check (email like '%@%.%' or email like 'NONE') default 'NONE');

If the table as been already created,
alter table email_test add constraint check_email check (email like '%@%%' or email like 'NONE');

But this ALTER will fail if there are any rows that violate the specified constraint.

Two constraints in single column


Trocar corretamente texto utilizando TextSwitcher

Question: Preciso utilizar um componente TextSwitcher com a intenção com que quando o usuário movimente este TextSwitcher para a direita assim como para a esquerda seja alterado o texto da mesma.
Para isso criei uma variável do tipo String[] e armazenei 5 valores, e utilizei o evento OnTouch no componente do tipo TextSwitcher, porém com o seguinte código que irei postar abaixo o texto não é trocado, continua o mesmo, até dar um erro de ArrayOfBounds porque não tratei o tamanho do array de Strings.
Qual seria a melhor maneira de trocar os textos?
    tsIntroduction.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getActionMasked()) {

            case MotionEvent.ACTION_DOWN:
                // Variaveis declaradas no topo da aplicação
                initialX = event.getX();
                initialY = event.getY();

            case MotionEvent.ACTION_UP:
                float finalX = event.getX();
                float finalY = event.getY();

                if (initialX < finalX) {
                    pos =+ 1;
                }

                if (initialX > finalX) {
                    pos =- 1;
                }
            }

            // Varíavel pos declarada no inicio da aplicação para pegar a posição atual
            tsIntroduction.setText(descriptions[pos]);
            return true;
        }

Answer: Consegui resolver o problema, foi feito o seguinte:
Implementei a interface OnGestureListener do pacote android.view.GestureDetector e utilizei dois métodos principais para fazer a lógica:
 @Override
 public boolean onTouchEvent(MotionEvent event) {
  this.mDetector.onTouchEvent(event);
  return super.onTouchEvent(event);
 }

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY) {
     float sensitvity = 50;

      if((e1.getX() - e2.getX()) > sensitvity){
          pos += 1;
          tsIntroduction.setText(descriptions[pos]);
      }else if((e2.getX() - e1.getX()) > sensitvity){
          pos -= 1;
          tsIntroduction.setText(descriptions[pos]);
      }

      return true;
}

Sendo que a variável mDetector é do tipo GestureDetectorCompat e inicializa da seguinte maneira:
mDetector = new GestureDetectorCompat(this,this);

E tsIntroduction seria o ImageSwitcher e descriptions é o array de Strings que criei.
Não implementei a lógica para tratar o erro ArrayOutOfBounds, mas não é nada díficil de criar.


Upgrade image in a Deployment's pods

Question: I have a Deployment with 3 replicas of a pod running the image 172.20.20.20:5000/my_app, that is located in my private registry.
I want do a rolling-update in the deployment when I push a new latest version of that image to my registry.
I push the new image this way (tag v3.0 to latest):
$ docker tag 172.20.20.20:5000/my_app:3.0 172.20.20.20:5000/my_app
$ docker push 172.20.20.20:5000/my_app

But nothing happens. Pods' images are not upgraded. This is my deployment definition:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: myapp-deployment
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: app
        image: 172.20.20.20:5000/my_app:latest
        ports:
        - containerPort: 8080

Is there a way to do that automatically? Should I run a command like rolling-update like in ReplicaControllers?
Comment: using latest tag is bad practice in kubernetes
Answer: There is no reason to pull latest image from Kubernetes point of view - it's already available on the system and pods are in the declared state. Use proper image tagging and you will be OK.
There are some workarounds based on imagePullPolicy: Always, but IMO I don't like them:
https://stackoverflow.com/questions/33112789/how-do-i-force-kubernetes-to-re-pull-and-image

Upgrade image in a Deployment's pods


Map array of node IDs to bundle types without loading all the nodes

Question: For complicated reasons I need to map an array of node IDs to a list of node bundles. That is, for a given list of node IDs, I need to get all the different bundles (node types) of the nodes the IDs belong to. The simple approach would be to load all the nodes, map that to their bundles and using array_unique to get the final list. Unfortunately, this is not a good solution because there may be hundreds of IDs in the array and loading all those nodes will result in a bad performance hit and/or go over the memory limit.
What is the best way to map an array of node IDs to (unique) node bundle types? Is there something built-in or does this require a custom database query? If so, I would be grateful for a dynamic query I could use for this (we're using MySQL). Thanks!
Answer: Rather than trying to load all nodes, you can query the DB directly for the nid/type (Bundle) pairs you need. Query the node_field_data table and use the IN operator to retrieve all the relevant nids you need.
$nids = [1, 2, 3];
//@TODO: add select query on node_field_data
$query->condition('nid', $nids, 'IN');
//@TODO: execute query and array map results

See the drupal.org docs on using IN operator in dynamic queries.
Comment: Thanks, I did end up writing a database query for this. I have added the completed query as a separate answer below.
Answer: For reference, here's the query I used to get this result:
$nodeIds = [1, 2, 3]; // array of node ids
$query = \Drupal::database()->select('node_field_data', 'n');
$query->condition('nid', $nodeIds, 'IN')
    ->fields('n', ['type'])
    ->distinct()
    ->groupBy('type');
$nodeTypes = $query->execute()->fetchCol('type');


Chamar função em JavaScript após leitura de um JSON

Question: Estou fazendo um trabalho de faculdade, no qual se trata de um e-commerce.
E tenho uma dúvida referente a seguinte questão, eu preciso chamar uma função apenas após o carregamento de alguns arquivos JSON que tenho em meu projeto.
Preciso fazer isso, pelo fato de que estou fazendo um carrossel de produtos, e esse carrossel só poderá ser construído, quando eu carregar dinamicamente todos os meus produtos.
Abaixo está as funções que precisam ser feitas antes de executar o carrossel:

Função genérica, para evitar chamar muitas funções.
function loadProdutos() {
    findJogosPs4();
    findJogosXbox();
    findJogosNintendo();
}

Essa função abaixo é semelhantes as demais que estou chamando no 'load produtos':
function findJogosPs4() {
    let produtosPs4 = new Array();
    $.getJSON('repository/produtosPs4.json', function (data) {
    data.jogosPs4.forEach(function (jogo) {
        newProduto = new Produto(
            jogo.id,
            jogo.nome,
            jogo.preco,
            jogo.caminhoCapa,
            jogo.qtdeParcelas,
            jogo.descontoAvista);
        produtosPs4.push(newProduto);
    });
    montaJogos(produtosPs4, '#gamePs');
    });
 }

E esse é o carroussel que preciso chamar após buscar todos os produtos:
function carrossel() {
$('.jogos').slick({
    dots: true,
    speed: 600,
    autoplaySpeed: 2500,
    autoplay: false,
    slidesToShow: 4,
    slidesToScroll: 4,
    responsive: [
        {
            breakpoint: 1024,
            settings: {
                slidesToShow: 3,
                slidesToScroll: 3,
                dots: true
            }
        },
        {
            breakpoint: 760,
            settings: {
                slidesToShow: 2,
                slidesToScroll: 1,
                dots: false
            }
        },
        {
            breakpoint: 480,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
                dots: false
            }
        }
    ]
});
}

Answer: Você pode utilizar a método .done() do Jquery para fazer isso, ele irá fazer algo quando finalizar o processamento do Json, pelo que vi no seu código ele ficaria assim.
function findJogosPs4() {
 let produtosPs4 = new Array();
 $.getJSON('repository/produtosPs4.json', function (data) {
 data.jogosPs4.forEach(function (jogo) {
    newProduto = new Produto(
        jogo.id,
        jogo.nome,
        jogo.preco,
        jogo.caminhoCapa,
        jogo.qtdeParcelas,
        jogo.descontoAvista);
    produtosPs4.push(newProduto);
 })
  montaJogos(produtosPs4, '#gamePs');
 }).done(function(){
    carrossel();
 });
}

Aqui você pode ver como funciona melhor os outros métodos.
https://api.jquery.com/jquery.getjson/
Comment: Valeu cara, eu tinha visto esse método .done() em alguns sites, porém não sabia como aplicar da forma certa. O único problema que deu é que se eu chamar em todos as minhas funções, a biblioteca que estou utilizando para o carrousel, dispara um erro. Entretanto coloquei apenas na última função de busca que faço, e funcionou perfeitamente. Obrigado!


Como enviar parâmetros do formulário ao invés do JSON em angular?

Question: Estou  tentando enviar um POST via angular, da mesma maneira que eu fazia no JQuery, porém, ao tentar capturar os dados via variável $_POST, não está trazendo nenhum valor.
Eu estou executando um código parecido com esse no angular:
$http.post('/users/ajax-create', user).then(...);

O angular parece estar enviando os dados sem a formatação necessária para que o PHP processe os parâmetros para a variável $_POST.
Eu só consigo obter os valores se eu fizer assim:
 json_decode(file_get_contents('php://input'), true);

Mas o comportamento acima não é desejado. Eu gostaria de usar o angularjs na minha aplicação php, porém não gostaria de reescrevê-la ou começar a fazer coisas diferentes só por causa dessa particularidade do angular.
Existe alguma maneira de enviar os dados de um objeto javascript pelo angular, mas como parâmetros de um formulário form-url-encoded?
Observação: Se esse for um comportamento padrão do angular, não gostaria de ficar escrevendo nenhum código a cada projeto que eu implementasse o angular. Então se houver alguma biblioteca pronta que converta os dados para form-url-encoded, ficarei satisfeito se houver uma indicação.
Answer: Você precisa passar o cabeçalho Content-Type: application/x-www-form-urlencoded na requisição, além de reescrever o corpo da requisição de modo que não se transmita um JSON.
Assim sendo, no método $http faça assim:
$http({
    method: 'POST',
    url: url,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformRequest: function(obj) {
        var str = [];
        for (var p in obj) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    },
    data: xsrf
});

Comment: Sei que talvez não seja comum isso no Angular, mas em casos de formulários com  `arrays`, essa função não funcionará corretamente.
Comment: Será mesmo? Fiz um teste aqui na função `encodeURIComponent` com um valor do tipo `a[b]` e ele converte para `a%5Bb%5D`, que é a forma certa de se enviar arrays via form data.
Comment: Faz sentido sua colocação. Na verdade, a função só não faz a mesma coisa que `$.param` do jQuery faz. Se quiser adicionar ele como referência na resposta, também será legal
Answer: Você pode utilizar o serviço $httpParamSerializer para modificar um objeto e prepará-lo para envio, en conjunto com um cabeçalho específico indicando o tipo form-urlencoded.
$scope.submitForm = function(data) {
  $http({
  method  : 'POST',
  url     : 'process.php',
  data    : $httpParamSerializer(data),
  headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // Necessário para especificar o tipo de conteúdo
 })
  .then(function(data) {
  });
};

Fontes:
 - https://docs.angularjs.org/api/ng/service/$httpParamSerializer
 - https://stackoverflow.com/questions/33065986/angular-js-httpparamserializer-and-jquery-ajax
Comment: Boa solução, eu não conhecia o serviço `$httpParamSerializer`.
Comment: @RodrigoRigotti Angular tem vários serviços de suporte, geramente eu preciso checar se não estou reinventando a roda.
Comment: @OnoSendai reportei o [bug no meta](http://meta.pt.stackoverflow.com/questions/5163/bug-ao-linkar-url-que-contenha). Olha como ficou a url na resposta.
Comment: @WallaceMaxters *nice catch!*
Comment: Arrumei e estraguei o post do meta :P


Run SQL without transaction

Question: Is there a way how to execute SQL or stored procedure without creating additional transaction in entity framework ? There is solution for entity framework Stored Procedure without transaction in Entity Framework but it is not available for .net core.
Answer: The default behavior of ExecuteSqlCommand in EF Core is different than the EF6:

Note that this method does not start a transaction. To use this method with a transaction, first call BeginTransaction(DatabaseFacade, IsolationLevel) or UseTransaction(DatabaseFacade, DbTransaction).
Note that the current ExecutionStrategy is not used by this method since the SQL may not be idempotent and does not run in a transaction. An ExecutionStrategy can be used explicitly, making sure to also use a transaction if the SQL is not idempotent.

In other words, what are you asking is the default behavior in EF Core, so no action is needed.
Comment: Wow that is great, i always manage transaction myself in SQL Server. Thank you :-)

Run SQL without transaction