Como fazer uma paginação com jquery e ajax?

Question: Tenho uma função que retorna todos os cadastros de clientes. Mas a minha dúvida é como que eu posso fazer uma paginação com este código? OS ELEMENTOS SÃO CRIADOS DINAMICAMENTE. COMO POSSO RESOLVER ISSO?
    function retorna_cliente ()
    {
      var id_cliente = "";
      var nome_cliente = "";
      var data_nascimento_cliente = "";
      var telefone_cliente = "";
      var celular_cliente = "";
      var cpf_cliente = "";
      var endereco_cliente = "";
      var email_cliente = "";
      var container_mostra_cliente = $('.mostra_clientes');
      var itemHTML = "";
      var mensagem_cliente = "Nenhum cliente encontrado";

    $.ajax({
      url: url_base + "clientes",
      type: 'GET',
      dataType: 'json',
      success: function (data)
      {
        if (data == 0)
        {
          $('.cliente-error-registro').css('display','block');
          $('.cliente-error-registro .mensagem-erro').html(mensagem_cliente);
        }
        else
        {
          itemHTML += "
";
          itemHTML += "
";
          itemHTML += "
";
          itemHTML += "";
          itemHTML += "<input type='checkbox' id='check-all' class='flat'>	";
          itemHTML += "	";
          itemHTML += "Nome	";
          itemHTML += "Data de Nascimento	";
          itemHTML += "Telefone	";
          itemHTML += "Celular	";
          itemHTML += "Cpf	";
          itemHTML += "Endereço	";
          itemHTML += "Email	";
          itemHTML += "
";
          itemHTML += "
";

          data.forEach(function (item)
          {
            id_cliente = item.id;
            nome_cliente = item.nome;
            data_nascimento_cliente = formataDataSQL(item.data_nascimento);
            telefone_cliente = item.telefone;
            celular_cliente = item.celular;
            cpf_cliente = item.cpf;
            endereco_cliente = item.endereco;
            email_cliente = item.email;

            itemHTML += "
";
            itemHTML += "
";
            itemHTML += "<input type='checkbox' value='" +  id_cliente + "' name='verifica_check_box[]' id='verifica_check_box' class='flat'/>		";
            itemHTML += "" + nome_cliente + "	";
            itemHTML += "" + data_nascimento_cliente + "	";
            itemHTML += "" + telefone_cliente + "	";
            itemHTML += "" + celular_cliente + "	";
            itemHTML += "" + cpf_cliente  + "	";
            itemHTML += "" + endereco_cliente + "	";
            itemHTML += "" + email_cliente  + "	";
            itemHTML += "
";
            itemHTML += "
";
          });

          itemHTML += "
";
          container_mostra_cliente.append(itemHTML);
        }

      },
      error: function (XMLHttpRequest, textStatus, errorThrown)
      {
        console.log(data);
      }
    });
  }

Comment: Possível duplicata de [Paginação com ajax](https://pt.stackoverflow.com/questions/235884/pagina%c3%a7%c3%a3o-com-ajax)
Comment: Possível duplicata de [Paginação com Jquery](https://pt.stackoverflow.com/questions/243367/pagina%c3%a7%c3%a3o-com-jquery)
Comment: Bem eu gostaria de saber a lógica como que eu poderia fazer esta paginação pois ela cria os elementos dinamicamente.
Comment: Você pode enviar junto com a requisição ajax uma variável de controle indicando o registro de inicio da lista Atual. Por exemplo iniciando com zero e limitando a consulta a 20 registros. Quando mandar avançar de página, você vai enviar a busca iniciando do 20...    ou se preferir usar https://datatables.net/  que deixa tudo mais fácil....
Answer: O fato dos elementos serem criados dinamicamente não tem problema. O que você precisa é de uma estrutura estática na página que servirá como container para estes elementos.
Na solução abaixo utilizei bootstrap e JQuery.
Sugiro, então, o seguinte:

    <title>Test site</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/custom.css" rel="stylesheet">

                page1

                page2

                page3

                page4

            Change page

No arquivo CUSTOM.js inseri o controle necessário à paginação:
$( document ).ready(function() {
    var current_page = 1;
    var total_pages = $('#pagination').children('div').length;
    $('#page_command').on('click', function(){
        for (i=1;i<total_pages+1; i++){
            $("#page" + i).hide();
        }
        current_page++;
        $("#page" + current_page).slideDown(1000);
        if (current_page == total_pages)
            current_page = 0;
    });
});

No arquivo CUSTOM.css:
html, body{
    height:100%;
    width: 100%;
    position: relative;
    display: block;
    z-index: 0;
}
a{
    cursor: pointer;
}
.custom-page{
    width: 300px;
    height: 500px;
    border: 1px solid black;
    position: absolute;
    top: 0;
    left: 0;
    color: rgb(0,0,0);
    background-color: rgb(60,70,80);
}
.command{
    position: absolute;
    top:600px;

}
.hidden{
    display:none;
}

O que você precisa fazer agora é apenas criar os elementos usando as páginas como containers.
;)


What is meant by "what value does a Fourier (co)sine series converge to over some interval"?

Question: Let us say there is a function $f(x)$. Let us say that that it has a Fourier (co)sine series representation $$g(x) = \sum_{n=1}^{\infty} a_n\sin(kx) = f(x)$$
I am having difficulty understanding a question that asks me to find the value to which $g(x)$ converges to over an interval $[a, b]$? $g(x)$ is a function, so it cannot converge to a single value over an interval?
Comment: We usually write
$$
     f(x)
\sim \sum_{n = 0}^{\infty} [a_{n} \sin(n x) + b_{n} \cos(n x)]
$$
to indicate that the **formal Fourier series** of $ f $ is equal to
$$
\sum_{n = 0}^{\infty} [a_{n} \sin(n x) + b_{n} \cos(n x)].
$$
This formal trigonometric series may or may not converge at a given point in the interval on which $ f $ is defined, and even if it converges at a point $ x $, it may not converge to $ f(x) $.
Answer: Recall that $\sum_{n=1}^\infty a_n \sin(kx) = \lim_{N\to \infty} \sum_{n=1}^Na_n \sin(kx)$ is indeed a limit, and we say the sum converges if the limit exists.
To me, it looks like the question is asking the following:
Suppose $f$'s fourier sine coefficients are $(a_n)_n$. For what values of $x$ does the series converge $\sum_{n=1}^\infty a_n \sin(kx)$ converge? Call this set $D$. Then for what $x \in D$ do we have $f(x) = \sum_{n=1}^\infty a_n \sin(kx)$?
The subtlety here is that in general, the fourier series of a function does not necessarily converge to that function. The question is asking you to figure out when the series actually converges to what you would hope it converges to.


Gradebook Simulation

Question: I am trying to simulate a student in a grade book where it needs to return the students name, grade level, and classes. I know how to declare the name, grade levels, and classes but I do not know how to get them to return and print to the console.
This code is through the newest version of Processing.
void draw ()
{
    print();
}

//creating class
class Student
{
    String name;
    int grade;
    String[] classes;

    Student(String nameInput, int gradeInput, String[] classesInput)
    {
        int grade=gradeInput;
        String name=nameInput;
        String[] classesInput;
    }

    String getName()
    {
        return this.name;
    }

    int getGrade()
    {
        return this.grade;
    }
}

void printClasses()
{
    println("Biology,Math,English,History,Spanish");
}

the code is expected to print the student's name, grade level, and classes to the console but with the code I have, nothing happens.
Comment: Your code doesn't attempt to create any instances of the `Student` class, so it isn't clear why you expect anything to happen.
Comment: I'm guessing maybe you have more code than what you've shown? You never instantiate any `Student` objects, and you have no such `print()` method defined. As written, it's unclear what your issue is (aside from incomplete code). Please edit your question accordingly.
Comment: @JohnColeman could you be more specific about how I can fix this issue?
Answer: It sound like you need to create an instance of your class using the new keyword.
For example, this would create an instance of the Student class:
String[] anisaClasses = {"Computer Science", "Math"};
Student anisa = new Student("Anisa", 11, anisaClasses);

Now that you have an instance of Student in the anisa variable, from here you could call the functions on that variable:
println("Anisa is in grade " + anisa.getGrade());

Shameless self-promotion: here is a tutorial on creating classes in Processing.
Comment: where should I put this new line of code because I tried to put it in String getName() and that didn't work
Comment: @AnisaCallis It really depends on what you want your program to do. But basically you'd need to do it after you create the new instance. Did you read the tutorial I linked?

Gradebook Simulation


Modifying Date-time Objects

Question: Given the code below to add a month to a time and echo it:
<?php

$current_date = new DateTime('now');
$current_date = $current_date->format('Y-m-d H:i:s');

$Expiration_Date = new DateTime('now');
$Expiration_Date = $Expiration_Date->modify('+1 month');

echo $current_date;
echo $Expiration_Date;

?>

Catchable fatal error: Object of class DateTime could not be converted to string
Why am I receiving this error?
Answer: You forgot to format your expiration date
echo $Expiration_Date->format("d-m-Y");

Answer: As @Stefan and also you do not need to re-asign the DateTime object only simply modify it.
$Expiration_Date = $Expiration_Date->modify('+1 month');

Simply should be
$Expiration_Date->modify('+1 month');

That is not your error though, @Stefan has the answer for that.

Modifying Date-time Objects


Jquery Replace content on click

Question: I want to replace the content of the #textoGrande div with an external file.
I intend to use each menu li to call the included div files, avoiding the page to be reloaded.
My javascript include is empty... I don't know how to get started...
Here's the html structure:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link href="css/style.css" media="screen" rel="stylesheet" type="text/css">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Opera</title>

                Linux Logo

Home

News

About

Contact

Support

Opera ahora
 mas acojedor...

En su nueva versión, Opera apuesta por un nuevo diseño y pestañas visuales, un motor más veloz que incrementa su velocidad en un 40% frente a su anterior versión y un mejor soporte de estándares.

Answer: $("li a").live("click", function(){
       $("#textoGrande").load($(this).attr('href')+' body');
       return false;
});

Comment: Thanks, but it's only loading itself # ... How do you make it work for an specific html?
Comment: If I do that, for example
`Home`
The entire page loads, the javascript doesn't seem to make any effect.
Comment: Still not working, what am I doing wrong? Please check the live sample: http://gabrielmeono.com/working/
Comment: @Gabriel: Try to use new jQuery, not sure if it will work but try to change 1.5.1 to 1.7
Comment: I thought it was, but not quite, It's removing the old div, but it does load the new content...
Comment: @Gabriel because you're replacing only the title "Opera ahora
mas acojedor...". That's your choice
Comment: Sorry I meant that it is NOT loading the new content.
Comment: I made a new question with the javascript you suggested, and still the page does not load.  http://stackoverflow.com/questions/8047012/jquery-click-function-not-loading-new-content
Comment: @Gabriel I didn't notice you're not receiving .main class within ajax called page. Try to change .main to `body`
Comment: Forget it was chrome all this time. Tested with firefox and IE and now it's working.
Answer: $(document).ready(function() {
  $("li a").click(function() {
    $("#textoGrande").load($(this).attr('href'));
  });
});

Comment: It contains a sintaxis error in line 3. And doesn't do anything, the page loads entirely.

Jquery Replace content on click


Switch theme based on screen size

Question: I need to switch my theme based on the users screen size instead of their user agent. Currently I'm using the Browscap & Mobile Switch modules and they work perfectly. My problem is that for tablets, I want users to use the desktop site. For mobile phones or anything under a 7 inch tablet, I want users to use my mobile site. What modules can help me with this OR how can I create the switch based off screen size?
UPDATE: I've just found ThemeKey. Anyone know if using this in conjunction with Browscap/Mobile Switch will cause issues?
Comment: I'm not aware if it causes any issue. But, you'd like [this podcast](http://mustardseedmedia.com/podcast/episode52) about themekey
Comment: Wow. ThemeKey is awesome.
Answer: The ThemeKey module is definitely the way to go for this. Here is a quote about it (from the module's project page):

... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server

Switch theme based on screen size


hosting a PDF in a c# application

Question: I am creating an ebook for a friend. He has the content in word (docx) so I have a few questions. I created a thread earlier on how to approach this and the best response was to create PDF's out of it. The main point of this was so we can have insertable textboxes, links, and table of contents.
Now I was wondering if I can host the pdfs in my application. I want to make an "adobe reader" basically. Is there a library out there that does this? Can I use installed COM/dlls to do this?
The reason for this is that I was to create like a "quiz" section on my application, or a "report card" or even a "bookmark" feature.
Thanks guys.
Answer: Making a custom PDF browser control could be an extremely challenging task. You could instead use the real Adobe Reader in your application as it is provided as a COM control which could be hosted in any Windows application. Here are the steps:

Start a new WinForms application
Make the Acrobat control available in the toolbox (Tools -> Add/Remove Toolbox Items: turn on "Adobe Acrobat 7.0 Browser Document" in COM Components tab). Don't forget to grab a cup of coffee before clicking on the COM tab.
Drag the control to the form
Manipulate it:
<code>axAcroPDF1.LoadFile("mypdf.pdf");
axAcroPDF1.Show();
</code>
Comment: I'll vote that up because it will work.. Although I think using the WebBrowser control is simpler.
Comment: @David, while `WebBrowser` approach is indeed easier to implement it gives you little control over the PDF compared to the Adobe component which allows you to navigate, print, ...
Comment: Awesome! but is it possible for me to distribute the correct library as well? The installer should do the work. What about a lightwieght pdf reader like foxit, can it be used similarly?
Comment: The installer should include the COM interop wrapper assemblies but the end users will need to have Adobe Reader installed for the application to run. As far as Foxit is concerned I've heard that they also provide an AtiveX control but never used it and cannot give you much info.
Comment: Is it possible my installer then install adobe reader as well?
Comment: I am not sure that this is legally right. You could though write a custom install step that verifies if Adobe Reader is installed and if not prompt the user to download it from the official site. Or if Adobe allows it include the installer binaries and simply run it from within your installer.
Answer: I know this has been asked before, but I can't remember where.  The accepted answer was something along these lines:
It would be a very bad idea to create your own PDF reader, because:

you are not in control of when Adobe
changes specs
Adobe provides a
reader free of charge, and most
users already have it installed.
Given the previous two statements, why would you want to spend that much time on reinventing the wheel?  It makes sense to reinvent the wheel when you can improve upon it, but not when you are just copying functionality that is freely available.

It would be far better to find a way to use the Acrobat reader that they have already designed, and distribute free of charge.
This is very easy to do.  All you need to do us use the WebBrowser control (assuming this is WinForms) and set the DocumentSource to the PDF file.  The WebBrowser control will just automatically use whatever pdf reader is already installed on the client PC, just as would Internet Explorer.
Answer: I've had very good experiences working the the Aspose libraries. They're affordable and will save you a lot of time.
Answer: You can embed Adobe Reader in your apps via the ActiveX component that is installed on your machine along with the reader. You can add it to your VS Toolbox from the COM Components tab. Anyone who has Abobe Reader installed will then be able to use your app to view PDF documents.
Note that if there is not Adobe Reader installed your program will not work, or you need somehow to provide the lib with the application.
If you want something that does not require Adobe Reader then you may like to check out the iText#.
Comment: Drawback is hat your app wont work on machines that don't have adobe reader installed. I guess the OP is only building something for a friend, but I would be quite unhappy if I had to install adobe reader just to use some other application...
Comment: Acutally, the friend is a contractor to a bigger company. The company will need to distribute this out to their clients and well, they can't ship something out if it dosnt work.
Comment: The company then even less can distribute adobe libraries without permission from adobe (normal redist license allows only to redistribute a full installer: http://www.adobe.com/products/reader/rdr_distribution1.html). I would expect foxit to have similar requirements
Comment: @masfenix If the application must be distributed to others may be it would be better ti have a look at iText#.
Answer: A potential problem with using a Adobe ActiveX/com component is that the user must have Adobe Reader installed for this to work (I don't think you're able and/or allowed to redistribute the activeX control only and wouldn't want to force my users to install Adobe Reader). So for more serious work I would try to use a Pdf library that you can distribute with your code such as writing a (presumably very small) P/Invoke wrapper for the open source library http://ccxvii.net/mupdf/ or if you can/want afford it use some commercial library.
An problem with using a webbrowser control is that you have to be careful to test what happens if a target user as embedding of pdf disabled in IE. It can happen that instead of embedding you get a external adobe reader (or whatever is registered as pdf handler) pop up! There might be a workaround, but I've been bitten by this before (resulting in one of those "works on my machine" problems)
Comment: The problem with this is that the library dosn't support the PDFs that have links embedded or textboxes, etc. or does it?
Comment: Well, that would depend on the library :) I'm not sure about mupdf to be honest, but IIRC sumatrapdf is based on mupdf and sumatra at least supports embedded links, ToC and bookmarks. Tyler Jensen mentioned Aspose, I guess that would support more advanced pdf features but I've never used it myself and it's a bit expensive... For mupdf I guess you could simply try and see if sumatrapdf supports the features you need, then investigate how much effort a P/Invoke layer for .net would be.
Comment: Oh and of course mupdf is GNU GPL3 ("For commercial licensing please contact email@example.com."). So you'd definitely have to make sure you comply with the terms of the license

hosting a PDF in a c# application


How is this anonymous function being called

Question: I came across this code:
export default async function (req, res) {
 ...
}

This appears to be an anonymous function and it does get called when the app is run, but but I don't know how it can get called.
NOTE: This is part of a Nodejs app.
The entire code that it is part of is located in a single file:
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

export default async function (req, res) {
  if (!configuration.apiKey) {
    res.status(500).json({
      error: {
        message: "OpenAI API key not configured, please follow instructions in README.md",
      }
    });
    return;
  }

  const animal = req.body.animal || '';
  if (animal.trim().length === 0) {
    res.status(400).json({
      error: {
        message: "Please enter a valid animal",
      }
    });
    return;
  }

  try {
    const completion = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: generatePrompt(animal),
      temperature: 0.6,
    });
    res.status(200).json({ result: completion.data.choices[0].text });
  } catch(error) {
    // Consider adjusting the error handling logic for your use case
    if (error.response) {
      console.error(error.response.status, error.response.data);
      res.status(error.response.status).json(error.response.data);
    } else {
      console.error(`Error with OpenAI API request: ${error.message}`);
      res.status(500).json({
        error: {
          message: 'An error occurred during your request.',
        }
      });
    }
  }
}

function generatePrompt(animal) {
  const capitalizedAnimal =
    animal[0].toUpperCase() + animal.slice(1).toLowerCase();
  return `Suggest three names for an animal that is a superhero.

Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
Animal: ${capitalizedAnimal}
Names:`;
}

Comment: Some other file imports it.
Comment: What framework are you using? Consult its documentation. This is likely handled by the framework.
Comment: It's sample code from OpenAI. Even if it's imported, how is the function actually called?
Comment: What do you mean by `how`? Its called like any other function. Seems to be a http request handler function, so its probably called with an HTTPRequest object and a HTTPResponse object.
Comment: Normal functions have names, and you call them by using their name. But this function is anonymous and has no name. So how does it get called?
Comment: It gets a name when it is [imported](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import).
Comment: I updated my post. The code is just part of a larger amount of code in the file which includes stuff outside of the function. So importing it cannot assign a name to just that function since other code is present.
Comment: `So importing it cannot assign a name to just that function since other code is present.` _Other code_ doesn't matter. Its `export default` so if you import the default you get __exactly__ that function, nothing else.
Answer: Function in question is an default export of the file, so when this file will be imported you will be able to give this default export any name, e.g. import defaultExportAlias from "module-name";
Comment: File that you uploaded does not call mentioned anonymous function at any time. There must be another file that imports this one. If its part of a project, search for name of the file where this function is located and see where it gets imported.
Comment: I updated my post and am showing the entire code. I don't understand how importing runs that line of code since the entire code in the module is assigned to a variable, which includes stuff outside of the function. So it isn't clear how the function can be called using an import.
Comment: But even if it gets imported, how could it possibly even be assigned to any variable since the entire module contains code outside of the function?
Comment: There are many ways of importing, if a file is using syntax as in my response, only default export will be assigned to the variable ("defaultExportAlias" in this case), since anon function is default export in this case, it will be assigned to the variable and can be called by adding parenthesis at the end defaultExportAlias(). Please let me know if I misunderstood your question.
Comment: Your answer looks correct, but I scanned the project and couldn't find any import. It's a Nodejs app, so maybe something else is going on in some other module.
Comment: No there isn't anything else going on in the code. Please read the entire documentation I've linked above, there are multiple ways to import code, answers here introduce only few of the ways.
Comment: Try adding console.trace() to the anon function, start project and look where its being called
Answer: It's the default export of a file. So when it is imported in another file, the whole default export can be placed into a variable.
// file1.js
export default async function (req, res) {
 ...
}

// file2.js
import myDefault from "file1.js";

// do something with myDefault

Or using the alternative syntax, useful when there are other exports from the file:
// file3.js
import { default as alias } from "file1.js";

// do something with alias

Comment: I scanned the project but couldn't find anything that has "import { default". This is running in Nodejs. Maybe there is some other mechanism that does this?
Answer: Like this:
import func from './file';

func();

However keep in mind that unnamed exports are a violation of this eslint rule.
Comment: I updated my post to show the entire code. So according to your suggestion, is that even allowed?
Comment: It's allowed. Linter rules are arbitrary limitations devs impose on themselves but not rules about the language itself.
Comment: I scanned the project, but couldn't find anything with func();
Comment: `I scanned the project, but couldn't find anything with func();` Of course you didn't, it'll very likely have another name...


Certainty that one has found all of the socks in a pile

Question: Suppose that I have a pile of $n$ socks, and, of these, $2k$ are "mine." Each of the socks that is mine has a mate (so that there are $k$ pairs of my socks) I know $n$, but not $k$. Assume that all possible values of $k$ are equally likely.
Now, I draw socks from the pile, uniformly and at random. After I draw a sock, I keep it if it is mine, and discard it otherwise.
If, after I have drawn $m$ of my socks from the pile, I have drawn only pairs of my socks (that is, it I have drawn one of my socks, I have also drawn it's mate), how confident am I that I have drawn all $2k$ of my socks from the pile?
Comment: If you draw a sock that is not yours, does it go back in the pile, perhaps to be drawn again, or is it put in a new pile?
Comment: It is discarded, out of the pile.
Comment: (a) Do your socks have different patterns so you know which two make up a pair, or can any two be put together? (b) Do you have any view of the prior distribution of $k$ [from $0$ to $\lfloor n/2 \rfloor $] before you start?
Comment: @Henry: each of your socks has exactly one partner sock. Every possible value of $k$ is equally likely.
Answer: Suppose after $m$ draws, you might have exactly $j$ pairs of your socks and no singletons. Then, given $K=k,m,n$ and provided that  $j \le k$, $2j \le m$, and $2k \le n$, the probability of this event is
$$\Pr(J=j \text{ pairs and no singletons}| K=k,m,n) = {k \choose j}{n-2k \choose m-2j}\big/ {n \choose m}$$
and so the probability that $J=j$ given $K=j,m,n$ is
$$\Pr(J=j \text{ pairs and no singletons}| K=j,m,n) = {n-2j \choose m-2j}\big/ {n \choose m}.$$
You have suggested a flat prior for $K$, so the posterior probability given you have only have pairs is
$$\Pr(K=j| J=j \text{ pairs and no singletons}, m,n) = \frac{\displaystyle{n-2j \choose m-2j}}{\displaystyle\sum_{k=j}^{\lfloor n/2 \rfloor} {k \choose j}{n-2k \choose m-2j}}.$$
If you do not know $j$ and you are just observing the that the number of your odd socks is $0$ after $m$ draws from the pile then the calculation becomes a little more complicated with extra sums
$$\Pr(K=J| \text{no singletons}, m,n) = \frac{\displaystyle \sum_{j=0}^{\lfloor m/2 \rfloor} {n-2j \choose m-2j}}{\displaystyle\sum_{j=0}^{\lfloor m/2 \rfloor}\displaystyle\sum_{k=j}^{\lfloor n/2 \rfloor} {k \choose j}{n-2k \choose m-2j}}.$$
If your prior for $K$ was not flat, it could easily be introduced into the results above to give
$${k \choose j}{n-2k \choose m-2j} \Pr(K=k) \big/ {n \choose m}\, , \, \, {n-2j \choose m-2j} \Pr(K=j) \big/ {n \choose m} \, ,$$
$$\frac{\displaystyle  {n-2j \choose m-2j}\Pr (K=j)}{\displaystyle\sum_{k=j}^{\lfloor n/2 \rfloor} {k \choose j}{n-2k \choose m-2j}\Pr (K=k)} \text{ and }  \frac{\displaystyle \sum_{j=0}^{\lfloor m/2 \rfloor} {n-2j \choose m-2j}\Pr (K=j)}{\displaystyle\sum_{j=0}^{\lfloor m/2 \rfloor}\displaystyle\sum_{k=j}^{\lfloor n/2 \rfloor} {k \choose j}{n-2k \choose m-2j}\Pr (K=k)}$$ respectively.


403 Forbidden when creating a page with RESTful API

Question: Referencing this tutorial, I am trying to create a page with RESTful API:
{
  "_links":{
    "type":{
      "href":"http://www.example.com/drupal/rest/type/node/page"
    }
  },
  "title":[
      {
        "value":"My first page"
      }
    ]
}

The POST request is: http://220.127.116.11/drupal/entity/node
The POST request headers are:

Content-Type: application/hal+json
PHP_AUTH_USER: (admin_username)
PHP_AUTH_PW: (admin_password)

But Drupal responded with: 403 Forbidden (Access Denied in response HTML)
Drupal 8 is installed at: http://www.example.com/drupal/
Enabled: HAL, HTTP Basic Authentication, RESTful Web Services, Serialization, REST UI
What did I miss?
Comment: @KimberlyW IIRC I think I managed to get past this by checking an export of REST permissions and found they were empty, once corrected I started making headway with REST. Sorry if that's a bit vague, it was a while ago.
Comment: Did you manage to get this working? I'm having similar issues with POST and REST.
Comment: Same question as @dibs . If you have a solution, please post an answer to help others that might come across this question.
Answer: The tutorial example using Dev Client is probably what is throwing you off because PHP_AUTH_USER and PHP_AUTH_PW are not valid request headers for Drupal 8 REST. The tutorial does give a curl command using the --user parameter which should do the correct behavior - add an Authorization header. I demonstrated this by manually adding that request header in User login REST format.
Content-Type: application/hal+json
Accept: application/hal+json
Authorization: Basic admin_username:admin_password

Comment: I wish it's okay. Still 403 forbidden & Access denied.
Comment: A bit confused. How do I set the Dev Client for authentication (if I don't use cURL)? Just type `Basic admin_username:admin_password` in `Authorization` header?
Comment: I think that should work.
Answer: Had the same problem and solved it in Drupal 8.6.1 (using Postman for testing):

Must use in the POST command the url like http://website.com/entity/node?_format=hal_json

make sure you enabled HAL and HTTP Basic Authentication, then in the Configuration REST, Enable Content rest for POS  hal_json and Basic Authentication

Don't know if help but made the suggested feature in Getting a 403 error in REST & 8.2.3 has no permission set for REST for GET of content

put Headers:

Authorization: Basic ....
Content-Type:application/hal+json

the Body raw looks like:

{
  "_links": {
    "type": {
      "href": "http://website.com/rest/type/node/article"
    }
  },
  "title":[{"value":"test article55"}],
   "body": [{"value":"test body"}]
}

Answer: out of the tutorial

You should create also a new authenticated user for testing purposes.
  If you test your API with User 0 administrator account credentials,
  you will likely miss permission settings that you need to be set.

have you set permissions ?? try to create a new role with one user and make sure to give the according permissions from your content type.
Comment: Tried another authenticated user. Still the same. Frustrated...
Comment: Yes, I have set the permissions ( Basic Page: Create , Basic Page: Edit Own Page, Basic: Delete Own Page) for authenticated user according to the tutorial.
Comment: and what user do you use for PHP_AUTH ?
Comment: Already mentioned in the question. Please see above.
Comment: don't use admin_username, but another_username ?!
Answer: I know this question is already old but I found it while diving into a quite similar situation. In your case it could be the lack of a X-CSRF Token header which is important.
As indicated in the tutorial, you must visit http://www.example.com/drupal/rest/session/token and use the returned string as value for your X-CSRF-Token header key along with your authentication credentials.
Answer: If you're getting an HTML response in spite of specifying Accept: application/hal+json, it may mean that your server is blocking the request and not even sending it to Drupal. Check your Drupal's recent log reports to see if there's any error. If there is no mention of any access denied or similar errors, then you'll probably find the error in the Apache (or any other webserver) logs.
In my case, support for PATCH and DELETE had to be explicitly enabled by putting the following in my Drupal root .htaccess file:
<IfModule mod_headers.c>
  Header always set Access-Control-Allow-Methods "POST, GET, PUT, PATCH, DELETE"
</IfModule>

<Limit GET POST PUT DELETE HEAD OPTIONS PATCH>
  Order allow,deny
  Allow from all
</Limit>

The error I got in my Apache log was this:
AH01797: client denied by server configuration:

It does seem slightly odd for POST to be disabled, but this should put you on the right track to figuring out what's going wrong.


How can a classical pianist learn jazz piano?

Question: I'm a classically trained pianist. Took lessons all through my childhood. I've continued to play and read classical literature all my life. But I never learned anything about jazz piano. I also know a lot about music theory, am a good sight reader and have a good ear.
At this point in my life (>40) what's the best approach to try to learn to play jazz piano music? This could include improvisation, but looking for some tips on how to get started. And some things I can do on my own.
Comment: One thing that I don't think the answers below emphasise enough is the importance of learning to *comp*, i.e. play a rhythmic and harmonic accompaniment for soloists, before worrying too much about your own soloing. A pianist who can't solo (well) can still jam with other musicians, but a pianist who can't comp can't play.
Answer: Do you listen to jazz?
I think a big part of getting into jazz as a trained musician means experimenting on your own. One of the biggest challenges for you will likely be learning the style of jazz piano, i.e. being able to play and not sound "square".
If you want a listening list, check this out: "100 Greatest Jazz Pianists". The top 5 would be plenty to get you started--you could probably set up a Pandora station and be set for a good while.
The best jazz musicians learned by doing. They learned the "rules" in an intuitive sense just by going to gigs and using their ears. Now we have jazz educators, of course, so that process can be made a little less painstaking. One such jazz educator has written the well-regarded Jazz Piano Book that may be enough to get you off the ground if you don't want to go out and find a teacher.
You can also find plenty of books to get you familiar with jazz voicings through notation. The extremely popular Jamey Aebersold Play-A-Long series contains a selection of transcribed piano voicings from the existing play along CDs.
Answer: If you're well-trained in music theory and good at sight reading, then you've already got some strong and important assets. I have a background similar to yours, so here are some things that I remember from when I got started:

get used to jazz rhythm: if you take for instance 4/4 songs, you'll notice that in many genres the first and third beats are emphasised, whereas in jazz it's the second and fourth;
about reading: jazz pieces swing, which means for instance that two subsequent eighth notes should approximately be read as "dotted eighth note followed by a sixteenth note". I'm sure this sounds obvious to jazz players, but it confused many excellent classical piano players I know when they had to sight-read some of the pieces I was practicing.
listen to it of course, to get the hang of the overall feeling, because there will always be a point where you'll learn and understand things much better if you've first heard them (but then that also applies to many other genres).
get your hands on "The Real Book" volumes, which are standard books in jazz and contain many interesting tunes. This will also help you get acquainted with the above points, and help you learn frequently occurring patterns of chords (like 2-5-1) so you'll have a better idea of the big picture. In my experience, this is another big difference with classical music, where my training was more about playing a given sequence of notes rather than about getting the general structure of a song.
keep your excellent technical skills provided by your classical training, but try to be more flexible. There are a few chords in jazz music that might sound dissonant when you first hear them, especially when coming from a classical background, but you'll get used to them. This is also relevant to improvisation, if you want to avoid merely using scales.
it's frequent in jazz that the left hand keeps playing a rhythmic part, while the right hand improvises. To help develop their "independence", one exercise that my professor advised me to work on was to let your left hand play the beat, and try to do something else with the other hand at the same time -- not playing however: moving it slowly up and down the keyboard, grab an object and move it elsewhere, and so on.

I'm sure more seasoned and more serious players will have many things to add, but I hope these tips will at least help you get started.
Comment: Mostly good but the dotted 8th & 16th note is technically and feel wise incorrect... Swing feel comes from an African 12/8 triplet inference... i.e. a quarter note triplet with first two eighth notes tied rather than a dotted eighth (unless you're going for a "Lawrence Welk" tribute feel... take the train "Eh?"). Divide your quarter notes by 3 *not* 4.
Comment: @Noldorin if syncopation is the first thing you have to learn so as not to sound square when playing jazz, the zeroth thing you have to learn is not to call it 'syncopation' ;-)
Comment: Not a bad summary, but this completely fails to mention syncopation! Syncopation is probably the *first* differentiating feature of jazz music that I'd mention.
Comment: @DavidAxtellMooreII: I fully agree with what you have said, but would like to point out also that this is not a "new" development. Actually it goes back over 1000 years. See [Notes inégales](http://en.wikipedia.org/wiki/Notes_in%C3%A9gales) for an interesting article on the subject.
Answer: A few more suggestions -

Play Blues - not Delta guitar-style blues, but jazz blues, with turn arounds. There are hundreds of sets of jazz blues changes available ( http://www.jajazz.com ). Instead of jumping into the complexity of the full blown jazz repertoire, blues is a great way to get your chord voicings and soloing going. You can take blues a looooong way and many many tunes are based on the blues in one way or another, even if it doesn't seem like it. You can start simple and add more chords to solo over as you get better.
Listen to lots of jazz. Not just current players, but go back to the beginning and start listening to how jazz piano evolved - Art Tatum, Bud Powell, Red Garland, Bill Evans, Duke Ellington (his actual piano playing), Monk, McCoy Tyner, Chick Corea...there are hundreds of names. Be able to identify them by hearing them and why they sound like they sound.
Transcribe the players you like. Nothing will teach you more than figuring out the great masters. I think it is in the Levine book, but there is a quote that says "all the answers are in your CD collection". Meaning, if you figure out the lines/chords of the guys that invented it all, you will learn things at a level that a book cannot provide. Remember, DVD's/videos and method books about jazz are only things that exist in the second half of the 20th century. Everyone before that had to listen and figure stuff out. It is still the most powerful way. Being able to transcribe is the most important and useful skill to acquire.
Record yourself. It doesn't have to be high-quality, just a boom box with a built in mic, or your iphone, or whatever. The point is not the audio quality it is to hear what you REALLY sound like. We have biases and other things that make it hard to hear that, especially when we are actually doing it. You might hear that you rush or drag when you listen back, but you might not when you are actually playing.
Learn how to identify the third and seventh of any chord you see. Instantly. Those are the juice notes, many early chord voicings are nothing more than those two notes of every chord. For both harmony and soloing those are the most important notes of any chord.
Play with players better than you. It's scary and humbling, but it will make you stretch and you will be surprised how fear can motivate you. :)
Answer: I am a jazz musician who has helped people make this very transition. I would like to add the good comments here by suggesting a few books for study material:

The Jazz Piano Book - a definitive work by Mark Levine
The Jazz Theory Book - another definitive work by Mark Levine
Modern Harmonic Progression - a wonderfully written book on Tertiary Harmony by Allen Michalek

There are so many good books and so much to say about learning jazz, but I will leave it at these few suggestions for reading material because just the journey through these books will spark many paths that will cover all my comments.
However, the best thing to do is take some University jazz courses and take some lessons from the best jazz musician(s) you can find in your area. Also, if there are jazz workshops in your town or city, get into one of the better ones.
Have fun with the transition. I play with a Juno award winning jazz bass player who divides his time between the jazz and classical world. He made the transition many years ago and says it was the best move he ever made. I certainly envy all those who can do both.
Have a great time with it all.
Answer: I am pretty much exactly in your situation.  Some already mentioned the Jazz Piano Book, which is great for classical-trained pianists, though it's also "intense".  As a professional Jazz player friend of mine put it, if you study 8 hours from that book daily, you will be a pro jazz player in 3 years.
If you don't have that amount of time, I recommend a class by Gary Burton on coursera that was life-changing for me. He covers pretty much all the basics from a very practical standpoint.
The class is free and lasts 5 weeks, and I believe you can always watch it without registering to the class. This class is simply outstanding; you will be at a different level 5 weeks later, and you will have many of the tools you need to keep getting better.
Answer: My 2 cents is that:
You need to do something about your mindset.
 1. You need to get rid of the habit of sight reading which is very prevalent of music students in my country:
 2. You also need to get out of the mold and mindset where you must everything written for you. Let's just say that Jazz Musicians can hardly play the same piece exactly the same way twice with the same feel, same style or same notes.
Jazz is about 'Freedom' whereas a mainstream, classically trained student is used to playing exactly what's written.
A good start to jazzing is start with Melody Faking: using the repeated notes style, use the attentive style, use lots of syncopation and anticipation while retaining the melody motive, play around with lots of ornaments. A favourite folk song I like to "Little Brown Jug" and "Mack the Knife". Google Youtube to hear these songs.
And while doing that, developed the swing feel (where 2 quaver notes develop the long-short feeling - reminding you a bouncing ball). This one is best taught interactively with a coach where offline or online.
Once you catch the swing feel and developed your ability to melody fake, they you can move on to do ad-lib where you have total freedom to do whatever you want with music. Take your time. A mainstream note-reading student is going to find this a huge change of mindset.
Of course, one more aspect is your ability to play "by ear" so that you can deal with the harmony.
If you need any elaboration, you need to PM me.
Answer: I'm classically trained, and that kind of age, and took up jazz piano three years ago.  I think all the suggestions here are great, but finding a good teacher is really high on the list.  For me, there were so many stylistic aspects of playing that are different from what I was used to that I was "blind" to, even though I thought I understood them.  Swing, for example -- I thought I got it, but it took months before I realized I didn't and really began the process of getting it.  Anyway it happens that my piano teacher is the author of a jazz piano book which personally I love, and I think it's written and organized in a way that works very well for someone coming from a classical background.  It's very thorough in terms of the theory, but also kind of bootstraps you through a different relationship to the keyboard, in terms of intervals and chords and scales and colors.
Answer: This guy comes from a classical background and started studying jazz rather "late" in his musical career. He has a website with tutorials. Check out his practice tips and links section.
Answer: I agree with all of the above but here's another. Just sit down and play in the dark.  Doodle, noodle, explore... Don't judge.  The most important thing is to not stop.  Set a timer for say, 15 minutes and keep playing until it rings.  Dig into your imagination.  Forget your training.  Good luck!


Is fingers pointing towards each other a problem when fretting a guitar

Question: I've been practicing the guitar for a few months now and am currently learning a song that requires me to slide from the 10th and 12th fret on the A and B string down to the third and fifth frets, respectively. Muting other strings in this case is not an issue, but my question still applies to when you'd want to avoid muting the adjacent strings.
When I slide down, I naturally end up in a position similar to this:

I find this position comfortable on my fingers and my wrist isn't bent much. However, in live recordings and video tutorials online, such chords are fingered more similar to this:

The difference I want to demponstrate with the picture is how here, all 4 fingers point in the same direction (towards the player, in this case). For me, this position does look more "right" - but it's also hard for me to fret the strings like that, without at the same time bending my wrist at an uncomfortable angle.
Is the way I'm fretting the strings now "bad", as in, is it more likely to cause injuries or to hold back progress? If it is, I would like to improve - could you explain as detailed as possible how to properly fret a chord like this (I have the same issue with power chords on an electric guitar)?
Comment: *(Slight wording changes)*
Comment: I do both all the time.
Comment: Does this answer your question? [Bent ring finger. Problem in playing guitar](https://music.stackexchange.com/questions/81636/bent-ring-finger-problem-in-playing-guitar)
Answer: The first one (i.e. your natural one) also looks more natural to me when it comes to the fingers.
Personally I would make this kind of hold with the thumb near the centre of the back of the neck, rather than wrapped round the neck, but that may just be because I have short fingers! If your way feels easy and comfortable to you too then it's unlikely to be causing major damage (in my worthless, non-medical opinion), but you could try moving your thumb more to the centre of the back of the neck to see if that's even more comfortable. You might have to raise your guitar neck a bit to do so.
Answer: I am a little confused as, in my opinion, both pic show the fingers pointing towards the player.
The first pic looks correct from the classic approach to teaching guitar.  I would not trust a source that recommended the second.  If the first is uncomfortable there are a couple things to consider.  If you are a beginner, and a few months is a beginner, then it will take time for the correct posture to feel comfortable.  Second, you may not be sitting correctly and that is really what is placing stress on the hand and wrist.
Answer: I noticed the thumb position in both pictures and then tried holding my hand both ways, and it seems the thumb position might be the determining factor. In the first picture the thumb is situated a little more toward the center of the chord and when I tried it my hand went into the same shape as the picture. In the second picture, I made my fingers align themselves and found my thumb positioned off to the far end of the chord. I've always been told to position my thumb behind the chord, so I have to assume that the first picture is probably the more correct way to hold the hand. There's also the possibility my hand is different than yours.


Can we declare a object inside the if-else statement?

Question: This code is the main function for  the implementation of queues using arrays also using template class.
int main(){
    int choice, n;

    cout<<"Enter 1 for integer 2 for double\n";
    cin >> choice;
    cout<<"Enter the size of queue\n";
    cin>>n;

    if (choice == 1)
        queue<int> obj(n);
    else
      queue<double> obj(n);

    for(;;){
        cout<<"1:Insertrear 2:Deletefront 3:Display 4:Exit\n";
        cin >> choice;

        switch(choice){
            case 1:obj.insertRear();break;
            case 2:obj.deleteFront(); break;
            case 3:obj.display();break;
            default: return 0;
        }
    }

    return 0;
}

The thing that I could not understand is, why I got error 'obj' was not declared in this scope in the line below the switch statement.
Any help will be well appreciated.
Comment: The static type of an object can never depend on user input. So even in principal what you are trying to do can't be done. Is `obj` suppose to be `queue` or `queue`? You can only know at runtime so it's not possible. You can work around that, for example you could use a `std::variant, std::queue>` though that has it's own set of challenges. Otherwise, you would need to come up with a unified interface that both queues can respect and implement your own queues with that interface, using polymorphism.
Answer: The simple answer is: Yes, you can declare objects inside if and else blocks, but they will be destroyed while leaving this blocks. In fact, after the if block there is no obj anymore.
Your idea to have different data types represented by a single object, depending on other runtime variables will not work in c++. C++ has a strong type system which makes your code idea impossible. That can be done on languages like python, but not at all by c++.
If you have the same algorithm, which should be used for different data types, you can play with templates. But this will still generate the complete code multiple times, a single instance per used data type.
From C++17 you can use std::variant to have a container, which can contain different data types during runtime. But that comes with the cost, that there is an additional value ( tag ), which tells the rest of the code which data type is currently stored in the variant itself. On every access the compiler has to generate something like if ( data == int ) then ... In detail it will be handled a bit different ( jumptable for different methods to call ). variant can also be used from other libraries like boost before C++17.
Answer:
Can we declare a object inside the if-else statement?

Yes.

The thing that I could not understand is, why I got error 'obj' was not declared in this scope in the line below the switch statement.

The (potential) scope of a local variable declared within a if statement extends to the end of the statement where it was declared. Example:
if (choice == 1) {
    queue<int> obj(n);
    // obj is in scope here
}
// obj is no longer in scope
else {
    queue<double> obj(n);
    // obj that is in cope here is not the same variable
}
// neither obj is in scope here

You're attempting to refer to that variable from outside of its scope. The life-time of the object has ended, and the name is no longer in scope.

C++ is a statically typed language. The type of a variable must be known at compile time and cannot change at run time.
A typical solution is to use a function template:
template<class T>
int do_things() {
    queue<T> obj(n);
    for(;;){
        // ...
    }
}

// in main
if (choice == 1)
    return do_things<int>();
else
    return do_things<double>();

Answer: You are getting an error because of scoping. The scope of the obj ends in your if / else and is not visible outside.
For your use case an extra bit of indirection may help. If your template queue class has a base, you can define a pointer to the base class outside the if else scope and assign the strongly typed instances inside the if / else and use the base class pointer in your switch statement.


Condição IF / ELSE em expression no Jasperreports

Question: Preciso realizar uma verificação no campo expression em meu relatório criado no Jasperreports studio, minha situação é a seguinte, preciso realizar a seguinte conta:
$F{quantidade}/($F{quinze}/15.0)

Porém algumas vezes a conta ($F{quinze}/15.0) resulta em zero, e não é possível realizar uma divisão por zero, por esse motivo acaba sendo exibido em meu relatório o simbolo do infinito, minha necessidade é verificar se a conta ($F{quinze}/15.0) resultar em 0 quero alterar o retorno para que seja apenas $F{quantidade} e não o resultado da conta
Answer: Apenas olhando a documentação, fiz essa formula utilizando operação ternária, vê se atende ao seu problema:
(($F{quinze}/15.0 == 0) ? $F{quantidade} : ($F{quantidade}/($F{quinze}/15.0)))

Answer: $F{quinze} == 0 ? $F{quantidade} : $F{quantidade}/($F{quinze}/15.0)
ainda é possível adicionar outras condições no "if" com os operadores || (or) e && (and)
só não esqueça de circundar a condição com parênteses caso haja mais de uma, ou apresentará problemas. sendo apenas uma condição não há problemas em deixar fora do parêntese, inclusive acho que fica visualmente menos poluído


ExtJS 6 - Date Time Picker's numberfield not editable

Question: I have tried to extend existing ExtJS6 date picker for date time picker.
I used numberfield in the date picker as the selection for time.
However, the number field is not editable. Not only that, the spinner in numberfield once click the date picker is gone.
Can someone enlighten me where did I got it wrong ?
Why the numberfield is not editable ?
Code in Fiddle.
https://fiddle.sencha.com/#fiddle/tc3
Comment: Have you searched for prior art? I have seen a similar (but fully working) component somewhere on the net. Don't reinvent the wheel if you don't have to.
Comment: What I have found was for ExtJS-4, which is work perfectly.
Tried with ExtJS-4 also work flawlessly, but once ported to ExtJS-6 it does not work any more, of course with little change to cope with existing ExtJS-6.

Found another but it is a slider instead of input field.
Answer: You are missing the ownerCt and ownerLayout properties on your buttons in the beforeRender method.
me.minuteBtn = new _$Number({
    ownerCt: me,
    ownerLayout: me.getComponentLayout(),
    minValue: 0,
    maxValue: 59,
    step: 1,
    width: 68
});


Why can't I assign to 3d lists properly?

Question: Let's say that I make a 3D list
list = [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]

and I run
list[0][0][0] = 1 #set the first element of the first list of the first list to 1

print(list)

I'd expect to get
[[[1, 0], [0, 0]], [[0, 0], [0, 0]]]

but instead, I get
[[[1, 0], [1, 0]], [[1, 0], [1, 0]]]

Can someone figure out how to make it assign a variable to ONLY ONE element of a 3D list, instead of every first element? Thanks!
If it matters, I'm using Python 3.7 32-bit.
Comment: I get what you expected, not what you got. Is that your exact code?
Comment: In future, please test the code you post before posting.
Comment: How are you building your `list`?  Are you declaring it literally like that?  Or are you doing something like `list = [[a,a], [a,a]]`?  In that case, you are assigning the *same* list `a` to each element, so when you change it, you see that change everywhere `a` is referenced.
Comment: If you've built your list with some sort of replicator, then you've stumbled into a well-documented problem.  https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly
Comment: Turns out that Rocket Hazmat and juanpa.arrivillaga were right! I was using a different piece of code to make the list, which was ([([[0,0,0]])*size_x]*size_y) . Hoog's code fixed it.
Comment: P.S. Don't name your list `list`.  Use a different variable name.  Doing this will mask the built-in `list` causing interesting issues later in your program.  Like being unable to do `list(something)`...
Comment: If you plan to use a lot of 3D lists holding same type values (for example `int`s) I suggest you to consider usage of `numpy` (take look at `numpy.array`)
Comment: Because you did not create the list the way you are showing, rather, you made a list which references the same list internally. Note, *lists don't have dimensions*
Answer: I have reproduced your results by making an assumption about how you actually defined your list.  I assume that you defined some variable such as ab below and used that to create your list.  However, the new list is still a bunch of references to your ab variable, so changing one actually changes ab which will affect your whole list.
ab = [0,0]

mylist = [[ab,ab],[ab,ab]]
mylist[0][0][0] = 1

print(mylist,"    ",ab)

OUTPUT
[[[1, 0], [1, 0]], [[1, 0], [1, 0]]]      [1, 0]

To resolve this, simple initialize your lists with 0 instead of some variable:
mylist = [[[0,0],[0,0]],[[0,0],[0,0]]]

or
mylist = [[[0 for _ in range(2)] for _ in range(2)] for _ in range(2)]

Comment: Thank you! This worked for me. It turns out that, as Rocket Hazmat pointed out, I had somehow managed to declare the same list multiple times in the same list... Sounds like some wormhole type math to me. Declaring it using the last method you gave worked.


Laravel Http set custom user agent on request

Question: I've got a cron set up in my Laravel project that makes a GET request to an endpoint, I'd like to set my own customer user agent that this request uses so that it can easily be identified amongst other potential requests to the same server.
My current code within my function is:
$response = Http::timeout($timeout)->get($url);
$code = $response->getStatusCode();

I'd like to set a custom user agent for this request like so:

Mozilla/5.0+(compatible; EXAMPLE/2.0; http://www.EXAMPLE.com/)

Can't seem to find anything in the docs to suggest how to do this
Answer: Since Laravel v8.8 (this pull request) you can use the withUserAgent method to set your own user agent.
Http::withUserAgent($userAgent)->get($url);

Before that you could set your own header like this:
Http::withHeaders(['User-Agent' => $userAgent])->get($url);


how can i get a menu of a parent taxonomy term?

Question: I know menus can be made of taxonomies, with taxonomy menu.
But the real huge problem i have is I CANT get taxonomy menu to show only one term's children in the taxonomy list.For example consider this taxonomy vocabulary:
<code>creatures
-insects
--ants
--mosquitoes
-mammals
--rabit
--dog
</code>
I want the taxonomy menu to show only mammals links, how can i do that?
Answer: If your output should be a block or page, you could do it with Views.
If not, meaning you want to show only that part as a menu itself, you might want to consider writing your own query for it, and adding it as a hook in your template.php


Roots of $e^z - z - 1$ on inside the unit circle

Question: I want to use Rouche's theorem to determine the number of zeros of $e^z - z - 1$ in the unit disk, but I cannot seem to get the right functions to apply Rouche's.
Comment: @Peter : Rouché works for all holomorphic function, in its extended version also all meromorphic functions. This function is entire, so no proble to apply this.
Comment: *Hint*: Compared with the next term in the series for $e^z$.
Comment: Isn't Rouche's theorem for polynomials ? Perhaps , you can use truncated taylor expansions.
Answer: You can apply Rouché's theorem to $f(z) = e^z-1-z$ and $g(z) =z^2/2$: For $|z| = 1$ is
$$
 |f(z)-g(z)| = \left| \sum_{n=3}^\infty \frac{z^n}{n!}\right| \le \sum_{n=3}^\infty \frac{1}{n!} = e - \frac 52 < \frac 12 = |g(z)|
$$
so that $f$ and $g$ have the same number of zeros in the unit disk.

But Rouché's theorem is actually not needed here, only the triangle inequality:
$$
 f(z) = \sum_{n=2}^\infty \frac{z^n}{n!} = z^2 \left( \frac12 + \sum_{n=3}^\infty \frac{z^{n-2}}{n!}\right)
$$
has a double zero at the origin, and the second factor has no zero in the unit disk since
$$
\left|\sum_{n=3}^\infty \frac{z^{n-2}}{n!}\right| \le \sum_{n=3}^\infty \frac{1}{n!} = e - \frac 52 < \frac 12
$$
for $|z| \le 1$.


Is every finite 2-generated group a quotient of a Frattini-free 2-generated group?

Question: Let $G$ be a finite 2-generated group. Is $G$ the quotient of a finite 2-generated group $G'$ with $\Phi(G') = 1$?, where $\Phi(G')$ is its Frattini subgroup.
Answer: Yes. here is a sketch of a proof. I can fill in any details of necessary.
Let $p$ be a prime not dividing $|G|$, and let $M_1,\ldots,M_r$ be a set of non-isomorphic irreducible modules for $G$ over ${\mathbb F}_p$ such that no element of $G$ acts trivially on every $M_i$. (So, if $G$ has a faithful irreducible module, then we can take $r=1$.)
Let $M=M_1 \oplus \cdots \oplus M_r$ be the direct sum of the $M_i$ and let $G'$ be the semidirect product $M \rtimes G$.
It is is not hard to show that the semidirect products $M_i \rtimes G$ are all $2$-generated (since otherwise $M_i$ would have at least $|M_i|^2$ distinct complements in $M_i \rtimes G$, but all such conjugates are conjugate, so it has at most $|M_i|$), and then the fact that the $M_i$ are mututally non-isomorphic implies that $G'$ is $2$-generated.
Let $1 \ne g \in G'$. We need to show that $g \not\in \Phi(G')$. If $g \in M$, then $g \not\in M_i$ for some $i$, say $i=r$, and then $g$ is not in the maximal subgroup $(M_1 \oplus \cdots \oplus M_{r-1}) \rtimes G$ of $G'$.
Otherwise, some power $g^k$ of $g$ has order coprime to $p$. We know that $g^k$ acts non-trivially on some $M_i$, say $M_r$, and by Schur-Zassenhaus $g^k$ is contained in some conjugate $H$ of $G$, and hence in the maximal subgroup $(M_1 \oplus \cdots \oplus M_{r-1}) \rtimes H$ of $G'$. By conjugating this maximal subgroup by an element of $M_r$ that does not centralize $g^k$, we get a maximal subgroup of $G'$ not containing $g^k$ and hence not containing $g$.


CountdownTimer onTick() not getting called

Question: I'm using a simple CountDownTimer and calling the onTick() every millisecond:
    final int[] i = new int[1];

    CountDownTimer countDownTimer = new CountDownTimer(1000, 1) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.i("Time left", millisUntilFinished + "");
            i[0]++;
        }

        @Override
        public void onFinish() {
            Log.i("i = ", i[0] + "");
        }
    };

The problem is though the timer is finishing-up in the correct time, but the onTick() method is not getting called every millisecond. Few of the milliseconds get missing everytime.
I checked it using the logs and found that the value of i[0] was 597 at the end, whereas it should be 999, as it gets +1 every time onTick() is called. Is there a precision error?
Comment: this is because some ticks are skipped since your `countDownInterval` is extremely small (compared to `onTick` execution time), see: http://androidxref.com/6.0.1_r10/xref/frameworks/base/core/java/android/os/CountDownTimer.java#140, try removing  `Log.i` from `onTick` and compare results
Comment: `i[0]` increased from 597 to 613. @pskink, the problem is I want to call a method once only when a specific time in millisecond hits. I tried to do it this way, but `onTick()` keeps skipping milliseconds and my method doesn't get called. Currently I'm fixing it by keeping a global boolean flag to check if the method gets called and increasing the period of onTick.

If there's a limit-time-period of when does onTick starts getting screwed, what is it?
Comment: why dont you just use `Handler#postDelayed(runnable, your_delay_in_ms)`?
Answer: You can create handler like this:
Handler timer = new Handler();
timer.postDelayed(new TimerTask() {
    @Override
        public void run() {
            // Make something
        }
    }, 1000);

Answer: Well somtime due to load on main thread it skips some digits, otherwise it works perfectly.
 new CountDownTimer(10000, 1000) {

            public void onTick(long millisUntilFinished) {
                long durationSeconds=millisUntilFinished/1000;
               Log.e("Time","String.format("%02d:%02d", (durationSeconds % 3600) / 60, (durationSeconds % 60))");
                   }

            public void onFinish() {
                Log.e("Time Up!","");

            }

Comment: I don't think internet speed should have a role in it. My app anyway doesn't have the internet permission.
Comment: @user5038993 yeah.. actually it has no role. Due to load on main thread, somtimes it shows such behaviour otherwise works fine. :)
Answer: Try with following code:
Timer timer = new Timer();

TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                // To-do
            }
        });
    }
};

timer.schedule(timerTask, 1000, 1000);

Answer: Use Handler. Try this:
final Handler handler = new Handler();
    final Runnable countDownTimer = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1);
        }
    };

    handler.postDelayed(countDownTimer, 0);

Here first the handler will be called immediately. After that it gets called every millisecond.
Answer: You probably didn't call:
countdown.start();


Creating GPT partitions on EFI raw disk using diskpart

Question: I've got a raw, blank GPT disk for use in a UEFI system. I need to create the partitions on it using diskpart. The only tutorial I've found so far is for diskpart.efi, which I believe is slightly different from the command-line diskpart. MS guide to GPT partitions with diskpart.efi Also the guide says to create a MSR of 32MB, but for a disk>= 16GB I know it needs to be 128MB.
I'm happy doing it with diskpart, just want to be sure I understand the fundamentals. I'm planning on installing, in this order:

ESP partition, size 102 MB (create partition esp size=102)
MSR partition, size 128 MB (create partition msr size=128)
data partition, the remaining space (approx 460GB)

Is this the correct thing to do, or is there anything I'm missing?
Answer: I got around this, but strictly speaking haven't solved it. When I start up, in BIOS I can choose either 'legacy boot' or 'UEFI boot'. If I choose 'legacy boot' and install Windows on the blank disk it works fine. So for some reason when I was choosing 'UEFI boot' and setting it up this way, although Windows seemed to work OK, further down the line, after installing drivers etc, it would blue screen on restart.
In summary I've learned to simply: format the disk; delete all the partitions; choose 'legacy boot' at startup; allow Windows to create the partitions it requires on the disk. Basically I'm avoiding the UEFI side of things.
Comment: Why do you need to create the partitions manually?  If you're just trying to install Windows, when you boot in UEFI mode the install DVD's partitioning step will create the necessary GPT partitions.  When you get to that step in the installer, just delete the existing MBR partitions, then select the "unpartitioned space" and click Next.
Comment: This is what I attempted when I realised that Windows would do it for me, instead of attempting it manually. Although this seemed to work, further down the line, when installing drivers, I kept getting a blue screen, even when I allowed Windows to take care of it. Doing it 'legacy boot' sorted it.
Comment: That's probably not related to your partitions, but it may be related to the use of UEFI itself.  UEFI on PCs is relatively new and implementors haven't ironed out all the bugs yet.
Comment: Yeah I'm avoiding UEFI for the forseeable future then.
Comment: It's been working fine for me on several computers, at least in Windows.  But my laptop's UEFI didn't work for Linux prior to kernel 3.0, since that version introduced a workaround for a certain UEFI bug that'd cause it to hang when booting.
Comment: Also, check whether your motherboard has any firmware updates available.  (I'm talking about what people usually call "BIOS updates", but if it's UEFI, it's not BIOS.)
Comment: OK thanks for the advice, I'm going to leave the UEFI stuff for now though. I can't see any forseeable advantage for using it in my scenario. It's nice to have Win 7 up and running and the machine performing well, I won't be risking jeopardising that after the week I had installing Win 7 about 10 times!


closed and contractible regions in Euclidean cubes

Question: Let $[0,1]^{k}$ be the $k$-times Cartesian product of the closed interval $[0,1]$.  Let $\Omega$ be a contractible, nonempty, and closed region in $[0,1]^k$. Here a region in $[0,1]^k$ refers to a manifold of dimension $k$ that are contained in $[0,1]^k$ as a subset.  And a closed region means that the manifold is closed as a topological space.
Question. Whether could it be proved that $\Omega$ is homeomorphic to $[0,1]^k$? Or could we add more conditions on $\Omega$ to guarantee the conclusion that $\Omega$ is homeomorphic to $[0,1]^k$?
Answer: In Knotted contractible $4$-manifolds in $S^4$, Lickorish describes embeddings of contractible $4$-manifolds into $S^4$. His paper is concerned with producing these embeddings such that the fundamental group of the complement is an arbitrary balanced group $G$, but this does not matter for your question.
By Lickorish, we have a contractible $4$-manifold $\Omega$ that embeds into $S^4$. Also $\Omega$ is not homeomorphic to the $4$-ball $B^4$ (and thus not homeomorphic to $[0,1]^4$). So $\Omega$ embeds into $S^4\setminus\{\text{point}\}$, which is homeomorphic to $\mathbb{R}^4$, and $\mathbb{R}^4$ is homeomorphic to $(0,1)^4$. Therefore $\Omega$ also embeds into $[0,1]^4$.
The answer to your first question is no, we cannot conclude that $\Omega$ is homeomorphic to $[0,1]^k$. I am not sure about what additional conditions would have to be assumed to guarantee that $\Omega$ is homeomorphic to $[0,1]^k$.


Overriding Proxy in Device Settings for NSURLSessionConfiguration?

Question: Is it possible to ignore the proxy settings that are in the device network settings, and instead use no proxy when using an NSURLSession ?
Basically I want to fall back on using no proxy if the connection fails.
Thanks !
Answer: I'm pretty sure that providing an empty connectionProxyDictionary in a session configuration should do the trick.  Note that it must be an actual empty dictionary.  Setting it to nil uses the default system proxy settings.
Comment: Because there had to be a way to distinguish between "use the default settings" and "use no settings", and treating a NULL/nil value as "use defaults" is cheaper than providing a separate boolean property somewhere, I'd imagine.  :-)
Comment: I wonder why this worked


Erro de sintaxe Access SQL para encontrar e excluir duplicatas deixando apenas uma

Question: Boa tarde pessoal.
Estou tentando fazer um código SQL exemplo que encontrei na Internet para encontrar as duplicatas da minha tabela do Access e deletar mantendo apenas o primeiro record. Porém, ao trocar todos campos onde dizia (Field1, Field2, ...) pelos nomes das colunas em si, começou dar erro de sintaxe. Antes quando estava os valores "Field", ele rodava e abria um prompt solicitando o nome de cada coluna. Segue o código:
DELETE *
FROM [Export Excel]
WHERE [Export Excel].ID IN

(SELECT F.ID
FROM [Export Excel] AS F
WHERE Exists (SELECT [Export Excel].[Criado em], [Export Excel].Encerrado, [Export Excel].Número, [Export Excel].Elemento Primário, [Export Excel].Descrição resumida, [Export Excel].Grupo designado, [Export Excel].Atribuído a, [Export Excel].Categoria, [Export Excel].Estado, Count(ID)
FROM [Export Excel]
WHERE [Export Excel].Criado em = F.Criado em
   AND [Export Excel].Encerrado = F.Encerrado
   AND [Export Excel].Número = F.Número
   AND [Export Excel].Elemento Primário = F.Elemento Primário
   AND [Export Excel].Descrição resumida = F.Descrição resumida
   AND [Export Excel].Grupo designado = F.Grupo designado
   AND [Export Excel].Atribuído a = F.Atribuído a
   AND [Export Excel].Categoria = F.Categoria
   AND [Export Excel].Estado = F.Estado
GROUP BY [Export Excel].Criado em, [Export Excel].Encerrado, [Export Excel].Número, [Export Excel].Elemento Primário, [Export Excel].Descrição resumida, [Export Excel].Grupo designado, [Export Excel].Atribuído a, [Export Excel].Categoria, [Export Excel].Estado
HAVING Count([Export Excel].ID) > 1))
AND [Export Excel].ID NOT IN

(SELECT Min(ID)
FROM [Export Excel] AS F
WHERE Exists (SELECT Criado em, Encerrado, Count(ID)
FROM [Export Excel]
WHERE [Export Excel].Criado em = F.Criado em
   AND [Export Excel].Encerrado = F.Encerrado
   AND [Export Excel].Número = F.Número
   AND [Export Excel].Elemento Primário = F.Elemento Primário
   AND [Export Excel].Descrição resumida = F.Descrição resumida
   AND [Export Excel].Grupo designado = F.Grupo designado
   AND [Export Excel].Atribuído a = F.Atribuído a
   AND [Export Excel].Categoria = F.Categoria
   AND [Export Excel].Estado = F.Estado
GROUP BY [Export Excel].Criado em, [Export Excel].Encerrado, [Export Excel].Número, [Export Excel].Elemento Primário, [Export Excel].Descrição resumida, [Export Excel].Grupo designado, [Export Excel].Atribuído a, [Export Excel].Categoria, [Export Excel].Estado
HAVING Count([Export Excel].ID) > 1)
GROUP BY Criado em, Encerrado);

Answer: @Rodrigo BRF Os nomes dos campos que possuem espaços ou hífen devem ser colocados entre colchetes.
Exemplo: F.[Criado em]


Where in the US is the best geographic location to host servers for the UK/Europe market?

Question: We would like to keep our hosting in the US.
But for European traffic, where is the best location for ping/response times? (East Coast, West Coast, Central etc)
Comment: I am aware of the trans-Atlantic Frankfurt-Washington link, which often shows up in Europe-to-US traceroutes. But that is not really an answer, thus adding as a comment.
Answer: East coast is definitely best, latency to the rest of the US shouldn't exceed 40ms, and you can get to most of Europe for not much more.
Answer: The East Coast is good. There are plenty of well-connected facilities in New Jersey and Manhattan that serve the financial industry with links to the UK and Europe.


Eclipse - use OS environment variable in build path

Question: Say I have two Windows environment variables named JAVA8 and JAVA6
which point to the root folders of the respective JDKs.
Can I use the the JAVA8 Windows variable in Eclipse
(to e.g. add it the build path of a given project)?
I mean can Eclipse refer to %JAVA8% directly once it's set at the OS level?
Also, I want to make this project portable so that I can give
this project to another team member (who might be on Mac OS e.g.)
with the only requirement for him to create a JAVA8 environment
variable on his OS.
I did quite some searching on the web (incl. in SO), and this seems
impossible (but I doubt such a basic thing would be impossible).
Comment: Why do you cut your text in half? Let the browser do the text wrapping.
Comment: @SotiriosDelimanolis I don't know, just a habit, I find it more readable maybe.
Answer: Eclipse expects you to define the available JDK/JREs in 'Preferences > Java > Installed JREs'. In the project Java Build Path you reference this by name rather than path so that it is independent of the actual JDK/JRE location.
You can also use 'Preferences > Java > Installed JREs > Execution Environments' to choose a JRE for things like 'JavaSE-1.8'. Again you can use the Execution Environment name in the Java Build Path.
Comment: When another team member opens the same project how will this work on this machine and in his eclipse? I mean, how is this portable? He will have to define then the same thing in his `Preferences > Java > Installed JREs` right ? I don't think that's what I want.
Comment: He will have to define the Installed JREs in the preferences using the same names, but he will not have to change all the project build paths.
Comment: I see... Still, this approach sounds somewhat clumsy to me.
Comment: The other user won't *have* to do anything on the Execution Environments preference page, and actually, neither do you. It's mostly for resolving situations where you have more than one already set up that can represent an Execution Environment and want to change which one was chosen.


Download Excel in Backbone.js

Question:   //Download SKU logic
  downloadSku: function (e) {
    e.preventDefault();
    var checkedValues = this.$el.find('.chk:checked').map(function () {
      return this.value;
    }).get();
    var options = {
      success: function (model, response) {
        console.log(response);
        var blob = new Blob([response], { type: 'application/vnd.ms-excel' });

        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "downloadFile.xlsx";
        document.body.appendChild(a);
        a.click();
      }
    };
    var obj = {};
    obj["sku_ids"] = checkedValues;
    this.downloadSkuModel.set(obj, { validate: true });
    this.downloadSkuModel.save({}, options);

  }

services.js
    var services = {

    sync: function (method, model, options) {
        var self = this;
        var api_token = mainJs.get_api_token();
        var access_token;
        if (api_token == null) {
            access_token = api_token;

        } else {
            access_token = api_token.access_token;
        }

        options || (options = {});

        var beforeSend = options.beforeSend;
        options.beforeSend = function (xhr) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + access_token)
            if (beforeSend) return beforeSend.apply(this, arguments);
        };

        switch (method) {
            case "read":
                options.url = options.readUrl;
                break;
            case "delete":
                options.url = options.deleteUrl;
                break;
            case "update":
                options.url = options.updateUrl;
                options.contentType = 'application/json';
                break;
            case "create":
                options.url = options.createUrl;
                options.contentType = 'application/json';
                break;
        }

        options.error = function (xhr, statusTxt, thrown) {
            switch (xhr.status) {
                case 401:
                    console.log("Unauthorized error");
                    break;
                default:
                    var messageText = JSON.parse(xhr.responseText);;
                    console.log("Status code: " + xhr.status + " Error: " + messageText.message);
            }

        }

        if (options.url)
            return Backbone.sync.call(model, method, model, options);

    }

}

module.exports = services;

My response headers:
  HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: *
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Content-Disposition: attachment;filename=sku_list.xlsx
Content-Type: application/octet-stream;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 15 Sep 2015 14:56:58 GMT

I am getting a response from the server but it isn't coming on the View.
If i use Javascript in my view it works:
 var obj = {};
    obj["sku_ids"] = checkedValues;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', Urls.sku.download, true);
    xhr.responseType = 'blob';

    xhr.setRequestHeader("Authorization", "Bearer " + "somethign");
    xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    xhr.onload = function (e) {
      if (this.status == 200) {
        var blob = new Blob([this.response], { type: 'application/vnd.ms-excel' });
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "downloadSku.xlsx";
        a.setAttribute("data-bypass", "");
        document.body.appendChild(a);
        a.click();
      } else {
        alert('Unable to download excel.')
      }
    };
    xhr.send(JSON.stringify(obj));

The error i am getting with backbone is as below:
SyntaxError: Unexpected token P at Object.parse (native) at K.parseJSON

Comment: What about `sync` event? Does it fires?
Comment: yes it fires but it comes to the error part but with 200 OK
Comment: Can you post the raw JSON `xhr.responseText` that you are receiving in `services.js`?
Comment: @ThadBlankenship here is my response : http://jsfiddle.net/pvruLLdz/
Answer: I solved my issue:
This is what i did
I changed my options.dataType = 'text' as by default backbone was assuming it to be a json response and was doing a Object.parse

Download Excel in Backbone.js


zeroinfl doesn't seem to work (R)?

Question: I´vd tried to fit a zero-inflated negative binomial model with zeroinfl (package pscl):
model.zinb <- zeroinfl(formula = y ~ x1 + x2 + x3, data = data, dist = "negbin")

a = data.frame(count = data$y)
b = data.frame(count = fitted(model.zinb)
a$colour = "data"
b$colour = "fitted"
hist = rbind(a, b)

ggplot(hist, aes(count, fill = colour)) +
      geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity', bins = 31)

However, when plotting the count data y and the fitted data fitted(model.zinb), there are somehow almost no counts between 0 and 1 in the fitted model (see plot). It looks like the zeroinfl didn´t work. Since I'm a beginner in this field, I'm hoping to get some advice. Thanks!
Comment: Yeah, this description seems correct. I think you were expecting something like posterior draws from the model given these predictors, instead of point estimates per observation.
Comment: Or maybe I am misunderstanding something. I know that there are structural zeros (from the zero generating process) and sampling zeros (the count generating process). The fitted(model.zinb) command prints the mean response values of the fitted negative binomial distribution and therefore does not contain the structural zeros, right? So maybe this could be the reasons that no zeros are predicted?
Comment: What is your expected behavior? How does this deviate from the expected behavior?
Comment: I did expect the model to predict more values closer to zero, since my data is zero-inflated (and fitted(model.zinb) predicts almost no values close to zero as it can be seen in the plot). I'm confused.
Answer: The fitted() method for zeroinfl objects returns the fitted mean $\hat \mu$ for each observation which can be pretty far from some of the counts $y$ with substantial probability $f_\mathrm{zeroinfl}(y, \hat \mu)$. This is explained and illustrated in the answers to:
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) predict exact zeros?
Moreover, instead of overlaying the histogram of the observed counts and expected probabilities (rather than means) it's easier to judge deviations in a so-called hanging rootogram. See: Kleiber & Zeileis (2016). The American Statistician, 70(3), 296–303. doi:10.1080/00031305.2016.1173590. An R implementation is available in the countreg package on R-Forge (successor to the pscl implementation) and illustrated in:
Confused on how to interpret ZINB and Hurdle models
https://stackoverflow.com/questions/43075911/examining-residuals-and-visualizing-zero-inflated-poission-r/43584320
Comment: thanks, that makes sense!

zeroinfl doesn't seem to work (R)?


Short exact sequence of chain complex with non-trivial connecting homomorphism

Question: Title is pretty straightforward, it is almost a duplicate of Example of Short exact Sequence of chain complexes but I was unable to understand the answers. I have tried many complexes, and unable to find one where the connecting homomorphism. If possible, please provide a simple example which doesn't involve topology. Hopefully something with complexes containing $\mathbb{Z}$ only.
Comment: While the title is straightforward, your question should be understandable without its title. And it isn't.
Comment: What is too complicated with paul garrett's answer to the linked thread? There's no topology in there are the spaces involved are fairly small.
Comment: In any case pick any non split exact sequence 0\to A\to B\to C\to 0, resolve the two endpoints A and C projectively, use the horseshoe lemma to obtain a projective resolution of the middle term B. Now you have an exact sequence of complexes. Apply hom(-,A) to everything to obtain a short exact sequence of complexes. Its connecting morphism is not zero.
Answer: This one's pretty simple:
$$
\begin{array}{ccccccccc}
0 & \to & 0 & \to & 0 & \to & 0 & \to & 0 \\
  & & \downarrow & & \downarrow & & \downarrow \\
0 & \to & 0 & \to & \mathbb{Z} & \to & \mathbb{Z} & \to & 0 \\
  & & \downarrow & & \downarrow & & \downarrow \\
0 & \to & \mathbb{Z} & \to & \mathbb{Z} & \to & 0 & \to & 0 \\
  & & \downarrow & & \downarrow & & \downarrow \\
0 & \to & 0 & \to & 0 & \to & 0 & \to & 0 \\
\end{array}
$$
where all maps $\mathbb{Z} \to \mathbb{Z}$ are the identity.
Comment: Indeed, it cannot get simpler than drawing the smallest SES of complexes of free modules that supports the chase in the snake lemma. :)
Answer: $\DeclareMathOperator{\Ext}{Ext}
\newcommand{\Z}{\mathbb Z}$Let me explain why Mariano's approach works. Suppose indeed that $\xi : 0 \to A \to B \to C\to 0$ is a non-split short exact sequence of modules over some ring $R$, meaning it does not represent the zero class in $\Ext^1(C,A)$.
Consider resolutions $P'\to A$ and $P''\to C$, and then build a resolution $P$ of $B$ of the form $P'\oplus P''$ (but a priori a differential that adds a morphism at the top right, as in the Horshoe Lemma).
If you apply $\hom(-,A)$ to $P'\to P\to P''$ and take homology, what you get is the long exact sequence
$$\hom(C,A) \to \hom(B,A) \to \hom(A,A) \to \Ext^1(C,A) \to \cdots$$
One can show that the image of the identity $A\to A$ in $\hom(A,A)$ is sent to the class of $\xi$ in $\Ext^1(C,A)$, which is non-zero, so the connecting morphim $\hom(A,A) \longrightarrow \Ext^1(C,A)$, which is given by right multiplication by $[\xi]$, is not zero.
For a concrete example, let $A = C = \mathbb Z/2$ and $B = \mathbb Z/4$ over $R = \mathbb Z$. Then any short exact sequence with these modules is not split, and the connecting morphism is not zero.
Add. If you follow this construction in this case, you will get the following SES of complexes
$$
\begin{array}{ccccccccc}
0 & \to & \Z & \to & \Z^2 & \to & \Z & \to & 0 \\
  & & \downarrow & & \downarrow & & \downarrow \\
0 & \to & \Z & \to & \Z^2 & \to & \Z & \to & 0
\end{array}
$$
where the horizontal maps are $i_1$ and $\pi_2$, the two vertical maps $\Z\to \Z$ are multiplication by $2$, and the third vertical map
is given by the matrix
$$\begin{pmatrix} 2 & 1 \\ 0 & 2 \end{pmatrix}$$
If you do $\hom_\Z(-,\Z/2)$ and follow the definition of the chase in the snake lemma, you will see that the connecting morphism
$$\delta : \hom_{\Z}(\Z/2,\Z/2)\cong \mathbb Z/2 \to \mathbb Z/2 \cong \Ext_\Z^1(\Z/2,\Z/2)$$
is the identity. Indeed, the vertical maps $\Z/2\to \Z/2$ are zero, the map $(\Z/2)^2 \to (\Z/2)^2$ is the nilpotent map
$$\begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}$$
and this is all you need to conclude.


Creating Google Map Markers from Database Query

Question: I have a database of approx 4000 addresses that I would like to have listed as markers on a google map... My end goal is to have two separate queries to display two types of markers, but for now I would like to know how to combine the results from my php to the locations variable in my javascript for the map. Here is the PHP which successfully echos the latitude and logitude...
$address = pg_query($conn, "
SELECT
  incident.address,
  incident.city,
  incident.state_1
FROM
  fpscdb001_ws_001.incident
WHERE
  incident.initial_symptom = 'Chrome Upgrade' AND
  incident.is_installed != 'true';");

  if (!$address) {
          echo "Query failed\n";
          exit;
        }
while ($markers = pg_fetch_row($address)){
  $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$markers[0]."&sensor=true";
  $xml = simplexml_load_file($request_url) or die("url not loading");
  $status = $xml->status;
  if ($status=="OK") {
  $Lat = $xml->result->geometry->location->lat;
  $Lon = $xml->result->geometry->location->lng;
  $LatLng = "$Lat,$Lon";
  }
echo "$LatLng	";

  }

Here is the javascript... the sample code has lat and lng listed, I assume this is where I need to execute the php.
  function initMap() {

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 5,
      center: {lat: 39.350033, lng: -94.6500523}
    });

    // Do not actually need labels for our purposes, but the site_id is best if they are required.
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    // Add some markers to the map.
    // Note: The code uses the JavaScript Array.prototype.map() method to
    // create an array of markers based on a given "locations" array.
    // The map() method here has nothing to do with the Google Maps API.
    var markers = locations.map(function(location, i) {
      return new google.maps.Marker({
        position: location,
        label: labels[i % labels.length]
      });
    });

    // Find a way to set lat and lng locations from database.
    var markerCluster = new MarkerClusterer(map, markers,
        {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
  }

  var locations = //some code to populate from database

I have an api key and have included the clustering javascript.
Comment: You should probably change your PHP script to make it return a JSON formatted String instead of HTML elements. After that, look into how to use AJAX
Comment: You need to be careful of performance if you attempt to display 4000 markers simultaneously. You will need to find a way to filter them.
Answer: This should do it:
PHP:
$arr = array();
while ($markers = pg_fetch_row($address)){
  ....
  $Lat = $xml->result->geometry->location->lat;
  $Lon = $xml->result->geometry->location->lng;
  $arr[] = array("lat" => $Lat, "lng" => $Lng);
}
echo json_encode($arr);

As you can see, I'm creating an array and then converting in into a JSON formatted string. The JSON will have this format [{lat:Number, lng:Number},....] Exactly as the expected format for the JavaScript locations array.
JavaScript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        var arr = JSON.parse(xhr.responseText);
        if(Array.isArray(arr)){
            showMarkers(arr);
        }
    }
}
xhr.open('GET', 'link/to/php/script', true);
xhr.send();

function showMarkers(locations){
    var markers = locations.map(function(location, i) {
      return new google.maps.Marker({
        position: location,
        label: labels[i % labels.length]
      });
    });

    var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}

If you're using jQuery you can simplify the AJAX call.
The onreadystatechange as the initMap function is executed asynchronously, you'll have to make sure the map is ready before you make the AJAX call.
Comment: can I ask what the .... in the php is? I had it working, but tried to alter the code. It would seem I made an error and now I am getting a 500 response on the console.
Comment: @KevMoe I've just replaced the code in your question with `...`. The idea is to add new arrays with coordinates to the `$arr` array and outside the loop convert `$arr` to JSON and `echo` it.


Java.Error when calling python script with Runtime

Question: I have to calling python script in java project.I dont use jython because in script i using todoist-api. I tried use this:
try {
    String cmd = "/home/kiryushin/projects/python/stm/venv/lib/stmtest1.py";
    Process p = Runtime.getRuntime().exec(cmd);
}
catch (IOException e){e.printStackTrace();}

I get
" java.io.IOException: Cannot run program "/home/kiryushin/projects/python/stm/venv/lib/stmtest1.py": error=13, Permisson denied"

I try change permission with chmod -r 777, and other commands but i get this error again.
Ubuntu 18.04 lts. JDK 10. Intelij idea community edition.
Comment: execute your command with sudo
Comment: It is saying permission denied
Answer: Try with :
First manually check with sudo permission.
And modify:
String cmd = "sudo python /home/kiryushin/projects/python/stm/venv/lib/stmtest1.py"

Comment: in this case in Ubuntu it will ask for password if you only use `sudo`
Answer: use your command like this, echo your password then use sudo -S along with your command
String cmd = 'echo your_password|sudo -S python /home/kiryushin/projects/python/stm/venv/lib/stmtest1.py';

Answer: That's how I solve my problem

Recreate my project without virtual environments (venv)
Add shebang in python script
With pip3 add lib todoist-app
In calling python script i write:
String cmd = "python3.6 /home/kiryushin/projects/python/stm2/stm.py"; Process p = Runtime.getRuntime().exec(cmd);
Comment: if you want use venv in calling need to write: "pipenv run /home/your directory"


Evaluate : $\lim_{n\to \infty}\{(1+\frac{1}{2n})(1+\frac{3}{2n})(1+\frac{5}{2n})\cdots (1+\frac{2n-1}{2n})\}^{\frac{1}{2n}}$

Question: Evaluate : $\lim_{n\to \infty}\{(1+\frac{1}{2n})(1+\frac{3}{2n})(1+\frac{5}{2n})\cdots (1+\frac{2n-1}{2n})\}^{\frac{1}{2n}}$
My attempt : Since, [$\displaystyle \lim\limits_{n\to \infty} a_n^{1/n} = \lim\limits_{n\to \infty} \frac{a_{n+1}}{a_n}$]
$$Here \ \ a_n = \prod\limits_{k=1}^{n} \left(1+\frac{2k-1}{2n}\right) $$
I got $$\frac{ a_{n+1}}{a_n}=\frac{(4n+1)(4n+3)}{(2n+1)(2n+2)\times (1+\frac{1}{n})^n}$$
$$\ Hence, \ \lim\limits _{n\to \infty} {\frac {a_{n+1}}{a_n}}=\frac{4}{e} $$
My question is can I still use Cauchy's second theorem if the power of the function is $\frac{1}{2n}$? Caused I've solved it same as the power  $\frac{1}{n}$. Please help me for this. Thank you in advance.
Comment: So,the answer should be the square root of what you got.
Comment: As well as: [$\lim_{n\to \infty}\{(1+\frac{1}{2n})\cdot (1+\frac{3}{2n}) \cdot (1+\frac{5}{2n})\cdots(1+\frac{2n-1}{2n})\}^{{1}/{2n}}$](https://math.stackexchange.com/q/2756497/721644)
Answer: Hint
Let $$x_n=\prod_{k=0}^{n-1}\left(1+\frac{2k+1}{2n}\right)^{\frac{1}{2n}}\quad \text{and}\quad y_n=\prod_{k=0}^{n-1}\left(1+\frac{2k}{2n}\right)^{\frac{1}{2n}}.$$
let $$k_n=\prod_{k=0}^{2n-1}\left(1+\frac{k}{n}\right)^\frac{1}{2n}.$$
So, $$x_n=\frac{k_n}{y_n},$$
and you can compute $$\lim_{n\to \infty }\ln(y_n)\quad \text{and}\quad \lim_{n\to \infty }\ln(k_n),$$ using Riemann sum.
Answer: Another way
$$:L\lim_{n\to \infty}\{(1+\frac{1}{2n})(1+\frac{3}{2n})(1+\frac{5}{2n})\cdots (1+\frac{2n-1}{2n})\}^{\frac{1}{2n}}$$
$$\implies \ln L=lim_{n\to \infty}\frac{1}{2n} \sum_{k=1}^{n} \ln \left(1+\frac{2k-1}{2n}\right)=\frac{1}{2} \int_{0}^{1} \ln (1+x) dx$$
Here, we use $k/n=x, 1/n \to dx$ when $n$ is very large.
$$\implies \ln L=\frac{1}{2} [(1+x)\ln(1+x)-(1+x)]_{0}^{1}=\ln 2-1/2$$
$$L=2 e^{-1/2}.$$
Comment: In the step $$\ln L=\lim_{n\to \infty}\frac{1}{2n} \sum_{k=1}^{n} \ln \left(1+\frac{2k-1}{2n}\right)=\frac{1}{2} \int_{0}^{1} \ln (1+x) dx$$  Have you taken $$\frac{2k-1}{2n}=\frac{k}{n}$$ and neglected $\frac{1}{n}$?
Comment: Yes, as $n$ is very large.
Comment: In that case, we are adding 0's infinite times. The sum may or may not be tending to 0. Am I missing something?
Comment: Yes, you are right $\ln L$ actually takes the indeterminate form $0\times \infty$, so one requires a special method of converting the limit of sum to an integral when $n\to \infty$.
Comment: What is that method may I ask?
Comment: $\lim_{n \to \infty} \frac{1}{n}\sum_{k=1}^n f(k/n)= \int_{0}^{1} f(x) dx$ $k/n=x$ and $1/n \to dx$, sum is changed to integral..
Comment: Please don't get me wrong. I know that $$\int_0^1{f(x)dx}=\lim_{n \to \infty}\frac{1}{n}\sum_{k=1}^n{f(\frac{k}{n})}$$ In this case we have  $$\lim_{n\to \infty}\frac{1}{2n} \sum_{k=1}^{n} \ln \left(1+\frac{2k-1}{2n}\right)$$ But $\lim_{n\to \infty}\frac{1}{2}\frac{1}{n} \sum_{k=1}^{n} \ln \left(1+\frac{k}{n}\right=\frac{1}{2}\int_0^1{ln(1+x)dx}$ and  not $\lim_{n\to \infty}\frac{1}{2}\frac{1}{n} \sum_{k=1}^{n} \ln \left(1+\frac{k}{n}\-frac{1}{n}right=\frac{1}{2}\int_0^1{ln(1+x)dx}$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/111975/discussion-between-datboi-and-dr-zafar-ahmed-dsc).