How to Wrap Flux in a ResponseEntity

Question: I need my endpoint to return data in follow json format:
{
  "code": "SUCCESS",
  "message": "SUCCESS",
  "errors": null,
  "data": []
}

Here is my controller code:
@GetMapping(value = "/productSubcategories", produces = MediaType.APPLICATION_JSON_VALUE)
    public Flux<MyDTO> getMyObjects() {

        return myObjectService.getAll()
                .map(myObject -> modelMapper.map(productSubcategory, MyObject.class));
    }

What is the best way to put wrap all the MyDTO objects in the "data" section of json response?
Comment: Please provide actual behaviour and MyDto, MyObject code
Answer: I am not sure what you want to achieve but I think you need collectList()
@GetMapping(value = "/productSubcategories", produces = MediaType.APPLICATION_JSON_VALUE)
    public Mono<ResponseEntity> getMyObjects() {

        return myObjectService.getAll()
                .map(myObject -> modelMapper.map(productSubcategory, MyObject.class)) // here your have Flux<MyObject>
                .map(obj -> modelMapper.map(obj, MyDTO.class)) // lets assume that here is conversion from MyObject to MyDTO - Flux<MyDTO>
                .collectList() // now you got Mono<List<MyDTO>>
                .map(dtos -> ResponseEntity.status(HttpStatus.OK).body(dtos));
    }

Comment: This is a mix of reactive and non reactive. The real signature of the method here is Mono>>, List should be a Flux for this to be reactive. This code also forces the method to wait for all elements, as collectList does not emit till all elements are collected. Also the MediaType should be MediaType.APPLICATION_STREAM_JSON_VALUE, this would "foce" the List to be  Flux. Just a side note for future readers.

How to Wrap Flux in a ResponseEntity


Duvida sobre Listener para JComboBox

Question: Alguém saberia me dizer algum Listener para quando eu selecionar um item no JComboBox ele me da um aviso por exemplo. Lembrando que quando eu abro meu componente(JFrame) eu seto itens lá dentro pelo banco então não pode cair no Listener.
Vamos lá explicando melhor o meu projeto
O botão "..." abre a janela de cadastro de modalidade, toda vez que eu cadastro uma modalidade eu atualizado o combo box "modalidade" que no momento está com o registro "dança" toda vez que eu escolho uma modalidade no meu combobox ele vai abrir uma nova janela para cadastrar a mensalidade. Então como eu faço para carregar meu combobox na hora que eu abrir minha aplicação sem ativar o listener e como eu atualizo o combobox sem ativar o listener? Eu quero que o listener só seja ativado quando o usuario seleciona um item da lista, mas pelo que parece o comando "combobox.addItem("Teste");" ativa o listener na hora de atualizar. Alguma sugestão?

Método utilizado para atualizar o Combobox quando eu cadastro uma modalidade ou quando eu apenas abro meu sistema.
public void setModalidade() {
    try {
        this.cboModalidade.removeAllItems();

        this.listaModalidade = new ArrayList<Modalidade>(new ModalidadeDAO().listaTodos());

        int i = 0;
        for(Modalidade modalidade : listaModalidade) {
            this.cboModalidade.addItem(modalidade.getTituloModalidade());
            if(this.modalidade.getTituloModalidade().equalsIgnoreCase(modalidade.getTituloModalidade())) {
                this.cboModalidade.setSelectedIndex(i);
            }
            i++;
        }

    } catch(SQLException e) {
        e.printStackTrace();
    }
}

Esse é os listener que utilizo ou que já utilizei para tentar.
    JCombobox combobox = new JCombobox<>();
combobox.addActionListener(this); //<-- já tentei esse

combobox.addItemListener(this); //<-- Estou usando esse mas a função "combobox.addItem("Teste"); que utilizou para atualizar meu combobox ativa o ActionListener e o ItemListener

Comment: Acredito que sua pergunta está um pouco confusa... Tente ser mais claro...
Comment: Não ficou claro para mim, tem algum item em especial que deve ativar o aviso? O que o banco de dados tem a ver com o Listener?
Comment: Pelo que entendi, você quer colocar um listener em um evento que seja disparado quando o usuário seleciona um item da combo. O que você está usando agora para fazer isso está sendo disparado quando o método `addItem` é chamado. É isso? Talvez fique mais claro se você colocar o código referente ao listener que está usando, ou pelo menos indicar qual o nome do evento em que você associou o listener.
Comment: " O que você está usando agora para fazer isso está sendo disparado quando o método addItem é chamado". É exatamente isso que está acontencendo, vou postar o código para talvez melhorar o entendimento, mas programa já esta um tanto quando complexo, mas vamos lá
Answer: É pessoal a unica solução que eu encontrei foi.
public void setModalidade() {
        this.cboModalidade.removeActionListener(this); //<-- Quando eu vou setar o combobox com dados eu desativo o ActionListener
        try {
            this.cboModalidade.removeAllItems();

            this.listaModalidade = new ArrayList<Modalidade>(new ModalidadeDAO().listaTodos());

            int i = 0;
            for(Modalidade modalidade : listaModalidade) {
                this.cboModalidade.addItem(modalidade.getTituloModalidade());
                if(this.modalidade.getTituloModalidade().equalsIgnoreCase(modalidade.getTituloModalidade())) {
                    this.cboModalidade.addActionListener(this); //<-- quando eu realizo o cadastro de uma nova modalidade e dou um refresh no meu combobox eu ativo o Actionlister para ele seleciona o id da modalidade que acabei de cadastrar e automaticamente abrir a janela para inserir e mensalidade.
                    this.cboModalidade.setSelectedIndex(i);
                }
                i++;
            }

        } catch(SQLException e) {
            e.printStackTrace();
        }

        this.cboModalidade.addActionListener(this); //<-- Quando termina de setar o combobox eu ativo o Actionlistener novamente
    }

Answer: Eu utilizo o ItemListenner e funciona.
Faço da seguinte forma.
combobox.addItemListener(new java.awt.event.ItemListener() {
   public void itemStateChanged(java.awt.event.ItemEvent evt) {
        if (evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
             //o tratamento a esse evento aqui.
            //ele dispara duas vezes a cada item selecionado,
            //um para o que foi DESELECTED e outro para o SELECTED por isso a comparação.

        }

   }

}

espero ser isso que procura e ter ajudado.

Duvida sobre Listener para JComboBox


Python - How to properly fill a multiline text field in PDF form using pdfrw?

Question: I'm filling a PDF form using python with pdfrw. I have no problem with any single line text field in the form. But when I try to fill a multi-line textfield it doesn`t render properly, it ignores break lines.
This is part of my code:
pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true')))

for x in range(0, len(pdf.Root.AcroForm.Fields)):
    try:
        if pdf.Root.AcroForm.Fields[x].T in ['(Observaciones)']:
            pdf.Root.AcroForm.Fields[x].update(PdfDict(V='This\nis\nmultiline', Ff=1))
            continue

This is the output.

This is the settings in the form field using Adobe Acrobat.

I have selected the options: Multiline, Scroll Long Text, Allow Rich Text Formatting.
I have tried using \r and the
 tag too.
How should I set the value to render properly?
Comment: Uncheck "Permitir formato de texto enriquecido" (Allow Rich Text Formatting), and use \r (or \n) as line break. Note that Richt Text Formatting uses the richValue property, which has a rather complex structure.
Comment: I unchecked this option, tried \r (and \n) but it didn't changed the result. Text still in single line.
Comment: Do you by chance have any Format settings active?
Comment: No, it doesn't, it is set to None. Should I select any of the others?
Comment: No; my suspicion was that there was a format preventing the proper multiline display.
Answer: After struggling with flattening my fields (setting to read-only) while keeping the multiline intact I finally found the solution.
I came across this rushed solution to just turn the '/Ff' value to 1 but in doing so you run the chance of removing some of the formatting for the form, and here is a better explanation on how to manipulate this field.
In the 'PDF Reference: third edition' page:552 it states

"The value of the field dictionary's Ff entry is an unsigned 32-bit
integer containing flags specifying various characteristics of the
field. Bit positions within the flag word are numbered from 1
(low-order) to 32 (high-order)."

So, when I looked into the Ff field I got 4096 (in binary = 0001-0000-0000-0000) for allot of the forms I was struggling with. Turns out that the 13th bit controls the multiline setting and just setting the Ff to 1 therefor erases the rest of the settings and only dictates that the specific form should be read-only.
You could just do it the lazy way and give Ff the value 4097 (or whatever your Ff value is +1) or flip the bit you want in the byte string that you want to manipulate.
Here is a simple way to do it, that is modifiable to your needs.
bitPosition = 0 #First position being value 0
bitValue = 1
mask = 1 << bitPosition
oldFfValue = pdf.Root.AcroForm.Fields[x].Ff
newFfValue = (int(oldFfValue) & ~mask) | ((1 << 0) & mask)
pdf.Root.AcroForm.Fields[x].Ff.update(PdfDict(Ff=newFfValue))

ps. Not 100% sure if accessing the Ff value works this way for you since my approach was based on this persons example code since it fit my needs better.
All in all I recommend giving the PDF reference document a look if you want to mess with the rest of the bits to see the interesting characteristics they control.
Other usefull bits are for example:

14th bit is for password star typing.
23rd bit is for disabling spell-check.
24th bit is for disabling scrolling of the field.
Answer: I've had this issue too. I haven't delved into the implementation of the multi-line feature by pdfrw, but I do know that when I flatten the form field (Ff=1, which you also have in your code), it no longer supports multi-line. Try taking that off and see if multi-line is supported again.
Answer: I cannot read Spanish setting, but if you make sure these 2 fields are checked, then you probably will be OK.
Setting
Comment: As I wrote at the bottom of the image, I already checked those two options.
Answer: I set the the ff to 4097 and it seems to be working but need to check if it has impact on other things.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Parsing nested JSON and writing it to CSV

Question: I'm struggling with this problem. I have a JSON file and needs ti put it out to CSV, its fine if the structure is kind of flat with no deep nested items.
But in this case the nested RACES is messing me up.
How would I go about getting the data in a format like this:
VENUE, COUNTRY, ITW, RACES__NO, RACES__TIME

for each object and each race in the object?
{
    "1": {
        "VENUE": "JOEBURG",
        "COUNTRY": "HAE",
        "ITW": "XAD",
        "RACES": {
            "1": {
                "NO": 1,
                "TIME": "12:35"
            },
            "2": {
                "NO": 2,
                "TIME": "13:10"
            },
            "3": {
                "NO": 3,
                "TIME": "13:40"
            },
            "4": {
                "NO": 4,
                "TIME": "14:10"
            },
            "5": {
                "NO": 5,
                "TIME": "14:55"
            },
            "6": {
                "NO": 6,
                "TIME": "15:30"
            },
            "7": {
                "NO": 7,
                "TIME": "16:05"
            },
            "8": {
                "NO": 8,
                "TIME": "16:40"
            }
        }
    },
    "2": {
        "VENUE": "FOOBURG",
        "COUNTRY": "ABA",
        "ITW": "XAD",
        "RACES": {
            "1": {
                "NO": 1,
                "TIME": "12:35"
            },
            "2": {
                "NO": 2,
                "TIME": "13:10"
            },
            "3": {
                "NO": 3,
                "TIME": "13:40"
            },
            "4": {
                "NO": 4,
                "TIME": "14:10"
            },
            "5": {
                "NO": 5,
                "TIME": "14:55"
            },
            "6": {
                "NO": 6,
                "TIME": "15:30"
            },
            "7": {
                "NO": 7,
                "TIME": "16:05"
            },
            "8": {
                "NO": 8,
                "TIME": "16:40"
            }
        }
    }, ...
}

I would like to output this to CSV like this:
VENUE, COUNTRY, ITW, RACES__NO, RACES__TIME
JOEBERG, HAE, XAD, 1, 12:35
JOEBERG, HAE, XAD, 2, 13:10
JOEBERG, HAE, XAD, 3, 13:40
...
...
FOOBURG, ABA, XAD, 1, 12:35
FOOBURG, ABA, XAD, 2, 13:10

So first I get the correct keys:
self.keys = self.data.keys()
keys = ["DATA_KEY"]
for key in self.keys:
    if type(self.data[key]) == dict:
        for k in self.data[key].keys():
            if k not in keys:
                if type(self.data[key][k]) == unicode:
                    keys.append(k)
                elif type(self.data[key][k]) == dict:
                    self.subkey = k
                    for sk in self.data[key][k].values():
                        for subkey in sk.keys():
                            subkey = "%s__%s" % (self.subkey, subkey)
                            if subkey not in keys:
                                keys.append(subkey)

Then add the data:
But how?
This should be a fun one for you skilled forloopers. ;-)
Comment: What about [json2csv](https://github.com/evidens/json2csv)?
Comment: I guess I could try that, thanks for the link
Comment: Does this have to be generic? I'd write a format-specific conversion for this.
Comment: Yes its generic, I want to be able to parse any json file like this that has a deep nest like the example
Comment: @Harry: what, any level of nesting?
Comment: No, like the example. So just when a key:value is a dict of the first key:value, not deeper than that
Comment: @Harry: Right, and is the format consistent? E.g., all top-level and nested objects have the same keys, always, for their type?
Comment: Yes, we can asume that. So It will always be parentkey__childkey if that is what you meant
Comment: What happens if there are *multiple* nested objects in each 'venue'? Should you assume they are the same length, or do you write out the *product* the same way your sample rows are the product of 'venue' times 'race' (so venue info is repeated for each race).
Comment: It will follow the same scheme as in my example for races
Comment: Sorry, that isn't clear enough. If there is both a `RACES` and a `ACCIDENTS` entry, and they are not the same length, what should happen? Would you list `venue 1, race 1, accident 1`, then `venue 1, race 1, accident 2`, etc. then `venue 1, race 2, accident 1`, etc.? That is a product expansion. Or would a second nested item have to be the same length so that you can do `venue 1, race 1, accident 1`, then `venue 1, race 2, accident 2`? Or is only *one* nested item supported, so *only* `RACES` or another nested key?
Answer: I'd collect keys only for the first object, then assume that the rest of the format is consistent.
The following code also limits the nested object to just one; you did not specify what should happen when there is more than one. Having two or more nested structures of equal length could work (you'd 'zip' those together), but if you have structures of differing length you need to make an explicit choice how to handle those; zip with empty columns to pad, or to write out the product of those entries (A x B rows, repeating information from A each time you find a B entry).
import csv
from operator import itemgetter

with open(outputfile, 'wb') as outf:
    writer = None  # will be set to a csv.DictWriter later

    for key, item in sorted(data.items(), key=itemgetter(0)):
        row = {}
        nested_name, nested_items = '', {}
        for k, v in item.items():
            if not isinstance(v, dict):
                row[k] = v
            else:
                assert not nested_items, 'Only one nested structure is supported'
                nested_name, nested_items = k, v

        if writer is None:
            # build fields for each first key of each nested item first
            fields = sorted(row)

            # sorted keys of first item in key sorted order
            nested_keys = sorted(sorted(nested_items.items(), key=itemgetter(0))[0][1])
            fields.extend('__'.join((nested_name, k)) for k in nested_keys)

            writer = csv.DictWriter(outf, fields)
            writer.writeheader()

        for nkey, nitem in sorted(nested_items.items(), key=itemgetter(0)):
            row.update(('__'.join((nested_name, k)), v) for k, v in nitem.items())
            writer.writerow(row)

For your sample input, this produces:
COUNTRY,ITW,VENUE,RACES__NO,RACES__TIME
HAE,XAD,JOEBURG,1,12:35
HAE,XAD,JOEBURG,2,13:10
HAE,XAD,JOEBURG,3,13:40
HAE,XAD,JOEBURG,4,14:10
HAE,XAD,JOEBURG,5,14:55
HAE,XAD,JOEBURG,6,15:30
HAE,XAD,JOEBURG,7,16:05
HAE,XAD,JOEBURG,8,16:40
ABA,XAD,FOOBURG,1,12:35
ABA,XAD,FOOBURG,2,13:10
ABA,XAD,FOOBURG,3,13:40
ABA,XAD,FOOBURG,4,14:10
ABA,XAD,FOOBURG,5,14:55
ABA,XAD,FOOBURG,6,15:30
ABA,XAD,FOOBURG,7,16:05
ABA,XAD,FOOBURG,8,16:40


Where can I find good documentation on how to write XML DTDs?

Question: The description of DTDs in the XML 1.1 specification is very terse, and it is difficult to gain an appreciation of what features are available. For example, from looking at the unflattened XHTML+MathML+SVG DTD, I know it is possible to import and partially redefine external DTDs, but I would never have guessed that was possible from reading the spec.
Does anyone know of a good resource for learning the finer points of DTD writing?
Answer: May be too basic for your needs, but W3 schools often has good primers?
Comment: That is surprisingly useful. I didn't even think to try W3Schools since usually their content is rubbish :). Thanks.
Comment: I find their content reaching into some quite reasonably good technical stuff these days. I used to think it was rubbish too but find it to be a reasonably good jumping in point on some stuff I've never used before.
Comment: However, it doesn't cover ,  and probably some other things, so I'm still interested in hearing about something better.
Answer: I would recommend Elliotte-Rusty Harold's book "XML Bible".
This is not "documentation", document type definitions (DTDs) are one of the most complex parts of XML and deserve to be learnt from the best sources.
One can also learn from examining good existing DTDs. Look for example at the following DTD, required to be used for the Balisage Conference slideshow presentations.
Answer: I just kind of winged it using auto completion from Liquid Technologies XML Studio ; they even had a tool that let me give a sample of the XML I was writing a XSD for and it would try to infer the definition. Of course I now realize this was an XSD not a DTD.


selection on condition

Question: I'm trying and trying and can't make it working. I have a ul class="first" . From all the ul's "first" in the template I need to select only those containing ul class="second" and for the selected change h2 href to "#". Problem is that when I find this specific "first" with "second" I can change "second" parameters with no problems but in no way I can figure how to influence "first".
Here's the link with both js and html at once :
http://jsbin.com/acoqi/edit
HTML :

          Bags

                  Bags

                      Shoulder Bags

        ...

                  Bags

JS:
    var second = $(".second");
    if(second.length && second.closest(".first")) {
       $(".first h2 a").attr("href", "#");
    };

Answer: I think you're looking for the :has selector
$('ul.first:has(ul.second) h2 a').attr("href", "#");

Or, closer to what you're doing:
var second = $(".second");
if(second.length && second.closest(".first")) {
   second.closest(".first").find("h2 a").attr("href", "#");
};

Comment: great great great, that's what I was looking for !

selection on condition


Limit of a function without LH

Question: Evaluate the limit : ${((1+x)^{1/x} -e})/x$  when x tends to zero.
This  can be solved using L-Hopital rule , however  I was wondering if there is any other method to do it, like any series formula or any other thing?
Comment: This is a derivative, so it will be hard to have a well-defined dividing line between L'Hopital and any other method.
Comment: For small $x,y>0$, one has $(1+x)^{1/x}=e^{1-x/2+x^2/3...}$ and $e^{1+y}-e=ey+O(y^2)$ so using this with $y=-x/2+x^2/3-..$ works but not sure that is any diferent than L-Hopital
Comment: What does LH mean?
Comment: @fwd lhopital  rule in limits
Answer: Considering
$$y=\frac{(1+x)^{\frac 1x} -e}x$$ compose Taylor series
$$a=(1+x)^{\frac 1x}\implies \log(a)=\frac 1x\log(1+x)$$
$$\log(a)=\frac 1x\left(x-\frac{x^2}{2}+\frac{x^3}{3}+O\left(x^4\right) \right)=1-\frac{x}{2}+\frac{x^2}{3}+O\left(x^3\right)$$
$$a=e^{\log(a)}=e-\frac{e x}{2}+\frac{11 e x^2}{24}+O\left(x^3\right)$$ Just finish : you will get not only the limit but also how it is approached.

Limit of a function without LH


Rabbitmq-server not starting on debian jessie

Question: I have a VPS from digital ocean running jessie. I am trying to install rabbitmq-server on the machine but i am not able to start the server.
/etc/init.d/rabbitmq-server start
Starting rabbitmq-server (via systemctl): rabbitmq-server.serviceJob for rabbitmq-server.service failed. See 'systemctl status rabbitmq-server.service' and 'journalctl -xn' for details. failed!`

systemctl status rabbitmq-server.service
● rabbitmq-server.service - LSB: Enable AMQP service provided by RabbitMQ broker
   Loaded: loaded (/etc/init.d/rabbitmq-server)
   Active: failed (Result: exit-code) since Mon 2015-10-19 04:36:33 EDT; 2min 33s ago
  Process: 16172 ExecStart=/etc/init.d/rabbitmq-server start (code=exited, status=1/FAILURE)

Oct 19 04:35:22 saltcode.in su[16183]: + ??? root:rabbitmq
Oct 19 04:35:22 saltcode.in su[16183]: pam_unix(su:session): session opened for user rabbitmq by (uid=0)
Oct 19 04:36:00 saltcode.in su[16236]: Successful su for rabbitmq by root
Oct 19 04:36:00 saltcode.in su[16236]: + ??? root:rabbitmq
Oct 19 04:36:00 saltcode.in su[16236]: pam_unix(su:session): session opened for user rabbitmq by (uid=0)
Oct 19 04:36:33 saltcode.in rabbitmq-server[16172]: Starting message broker: rabbitmq-serverFAILED - check /var/log/rabbitmq/startup_\{log, _err\} ... (warning).
Oct 19 04:36:33 saltcode.in rabbitmq-server[16172]: failed!
Oct 19 04:36:33 saltcode.in systemd[1]: rabbitmq-server.service: control process exited, code=exited status=1
Oct 19 04:36:33 saltcode.in systemd[1]: Failed to start LSB: Enable AMQP service provided by RabbitMQ broker.
Oct 19 04:36:33 saltcode.in systemd[1]: Unit rabbitmq-server.service entered failed state.

These are lines from log
/var/log/rabbitmq$ tail *
==> startup_err <==

==> startup_log <==
ERROR: epmd error for host saltcode: timeout (timed out)

Comment: You should check and probably add the content of `/var/log/rabbitmq/startup_log` and `/var/log/rabbitmq/startup_err `.
Comment: @knowhy I have edited my question
Comment: try editing your `/etc/hosts` and add `saltcode` to the localhost line. You can also try to `ping saltcode`. I guess `saltcode` does not resolv and that is why the init script fails.
Answer: If you get ERROR: epmd error for host saltcode: timeout (timed out) in your rabbitmq startup log it means that your rabbitmq instance can't find the Erland Port Mapper Daemon (epmd). The default port for epmd is 4369.
If you get an timeout error in the log you should check if the hostname in the log resolves by running ping hostname. If the hostname does not resolve you need to edit the /etc/hosts file and add an entry for the host.


Pesquisa banco utilizando JSF

Question: Estou programando uma aplicação em JSF, a minha aplicação consegue fazer a função de Gravar e Alterar sem nenhum problema, porém como estou usando a tecnologia Java web agora estou encontrando uma certa dificuldade em realizar uma pesquisa e trazer os dados para um DataTable, alguém teria algo para que eu possa me basear para realizar tal operação?
Answer: um data table intera sobre uma lista.
O value do data table tem que ser uma lista do retorno na consulta ao banco. e o atributo var é cada objeto dessa lista podendo acessar assim suas propriedades.
Exemplo:
Java
class CarrinhoCompraBean {
  public List<Item> getItems {
    List<Item> items = consultaBanco(idCarrinho);
    return items;
  }
  public static class Item {
    // ...
  }
}

E em seu template, Html
<h:dataTable id="table1" value="#{carrinhoCompraBean.items}" var="item" >
    <h:column>
        <f:facet name="header">
            <h:outputText value="Item" />
        </f:facet>
        <h:outputText value="#{item.nome}" />
    </h:column>
    <h:column>
        <f:facet name="header">
            <h:outputText value="Preço" />
        </f:facet>
        <h:outputText value="#{item.preco}" />
    </h:column>
</h:dataTable>

javadoc dataTable
datatable primefaces
Comment: Não é mais fácil retornar o `ResultSet` para o `dataTable`?
Comment: Não Patrick, o resultset não é uma lista e os objetos que ele retornam não são pojos. Voce não tem exemplo o getNome no retorno de um resultSet. tempos que transformar resultSet e objetos.
Comment: Se não me engano, o componente `dataGrid` do PrimeFaces permite essa associação, com `ResultSet`.

Pesquisa banco utilizando JSF


how to uninstall visual-studio-code insider

Question: I have installed visual studio code from .deb package that I downloaded from its official site. but I can't uninstall it now. I tried all methods in how to uninstall visual studio code  . but none of them worked. some were not able to find code. Any suggestions on how to uninstall it.
Answer: Generally visual studio code and visual studio code-insiders is installed through snap install that resides into your /snap/ folder. to check whether a package is installed or not through snap install.( when you install it by running sudo snap install code or sudo snap install code-insiders or install from ubuntu software.)
1.  GO TO /SNAP FOLDER AND look for folder with package name.( in our case: look for code-insiders)
or
open terminal and type
$ snap list

find out the exact name of the application there.
now run
$ snap remove code-insiders

now it is uninstalled. you can verify by typing in terminal
$ dpkg -l

this command shows all kinds of packages installed through any means on the system. or type
which code-insiders

it should not print anything (just an \n character and the line changes.)
2. if any chance this method fails then go to ubuntu software. and search for code-insiders in search tab. from there you can uninstall it.
Note: this might not appear in the list of installed applications when you click installed tabs beside all tab


Euler characteristics of Tensor power of line bundle

Question: Let $X$ be a smooth projective variety,
and $L$ a line bundle on $X$ which satisfies $L^{\otimes n}=O_X$ for some $n$. I am wondering whether there is a relation between $\chi(L)$ and $\chi(O_X)$. Something like $\chi(L)=\chi(O_X)^n$ seems too optimistic.
Comment: I don't know the answer to this off the top of my head, but I would imagine that you should adjust the formula. Since $L^{\otimes kn}=\mathcal{O}_X$ as well, the formula should be correct in this case too, and it's clear that what you have wouldn't work unless $\chi(\mathcal{O}_X)=1$.
Answer: If $L^{\otimes n} \cong O_X$ then $L$ is numerically trivial, i.e., $c_1(L) = 0$ in $CH^1(X)_{num}$. Therefore, by Riemann--Roch
$$
\chi(L) = \chi(O_X).
$$
Comment: great, many thanks!


How to get custom entity data in custom page

Question: i have created Event entity, and I have custom page.
I want to load ALL Entity rows and then use it in my template.
This is the way everyone is prsenting, but i don't know how can i get NID value
<code>$events = \Drupal::entityTypeManager()->getStorage('event')->load($nid);</code>
Using Symfony i could do this like:
<code>$events = $this->getDoctrine()->getRepository(Event::class)->findAll();
</code>
Answer: This is the solution
<code>$storage = Drupal::entityTypeManager()->getStorage('event');

$nids = Drupal::entityQuery('event')->execute();
//Load all nids
$events = $storage->loadMultiple($nids);
//You can also use
$events = $storage->loadMultiple();
</code>
Comment: An empty loadMultiple() loads all entities by default: `$events = $storage->loadMultiple();`


SQL: Remove duplicates

Question: How do I remove duplicates from a table that is set up in the following way?
unique_ID | worker_ID | date | type_ID

A worker can have multiple type_ID's associated with them and I want to remove any duplicate types. If there is a duplicate, I want to remove the type with the most recent entry.
Answer: A textbook candidate for the window function row_number():
;WITH x AS (
    SELECT unique_ID
          ,row_number() OVER (PARTITION BY worker_ID,type_ID ORDER BY date) AS rn
    FROM   tbl
    )
DELETE FROM tbl
FROM   x
WHERE  tbl.unique_ID = x.unique_ID
AND    x.rn > 1

This also takes care of the situation where a set of dupes on (worker_ID,type_ID) shares the same date.
See the simplified demo on data.SE.
Update with simpler version
Turns out, this can be simplified: In SQL Server you can delete from the CTE directly:
;WITH x AS (
    SELECT unique_ID
          ,row_number() OVER (PARTITION BY worker_ID,type_ID ORDER BY date) AS rn
    FROM   tbl
    )
DELETE x
WHERE  rn > 1

Comment: I must be doing something wrong because I get the same "The multi-part identifier (unique ID) could not be bound" error.
Comment: @Ryan: `unique_ID` != `unique ID` -  I see a missing underscore.
Comment: I just put 'unique ID' in the comment to represent my table's specific unique ID.
Comment: @Ryan: have you had a look at the link I provided: http://data.stackexchange.com/stackoverflow/q/118656/demo-fro-ryan
You can test and see that is works there. This is `SQL Server 2008 R2`. Are you running an older installation maybe?
Comment: Yes, and thank you. I came back and tried it again today and it worked. I'm not sure what I was doing yesterday.
Answer: delete from table t
 where exists ( select 1 from table t2
                 where t2.worker_id = t.worker_id
                   and t2.type_id = t.type_id
                   and t2.date < t.date )

HTH
Comment: I get the error "The multi-part identifier ... could not be bound". Every change I try and make either results in nothing being returned or more errors. When I turned this into a SELECT statement for testing I didn't get the error, only when attempting to delete.
Comment: @Ryan: this is probably due to a typo. should be `from table t t2` instead of `from table t2`.
Comment: If I do that I get "Incorrect Syntax" errors on 'where' and 't2'.
Comment: This ended up working well, with the exception of not being able to detect duplicates that share the same date.
Answer: DELETE FROM @t WHERE unique_Id IN
(
    SELECT unique_Id FROM
    (
        SELECT  unique_Id
                ,Type_Id
                ,ROW_NUMBER() OVER (PARTITION BY worker_Id, type_Id ORDER BY date) AS rn
        FROM @t
    ) Q
    WHERE rn > 1
)

And to test...
DECLARE @t TABLE
(
    unique_ID  INT IDENTITY,
    worker_ID  INT,
    date  DATETIME,
    type_ID INT
)

INSERT INTO @t VALUES (1, DATEADD(DAY, 1, GETDATE()), 1)
INSERT INTO @t VALUES (1, GETDATE(), 1)
INSERT INTO @t VALUES (2, GETDATE(), 1)
INSERT INTO @t VALUES (1, DATEADD(DAY, 2, GETDATE()), 1)
INSERT INTO @t VALUES (1, DATEADD(DAY, 3, GETDATE()), 2)

SELECT * FROM @t

DELETE FROM @t WHERE unique_Id IN
(
    SELECT unique_Id FROM
    (
        SELECT  unique_Id
                ,Type_Id
                ,ROW_NUMBER() OVER (PARTITION BY worker_Id, type_Id ORDER BY date) AS rn
        FROM @t
    ) Q
    WHERE rn > 1
)

SELECT * FROM @t

Answer: you may use this query
delete from worker where unique_id in (
select max(unique_id)  from worker group by  worker_ID , type_ID having count(type_id)>1)

here i am assuming worker as your table name
Comment: And the date check requested by the OP?

SQL: Remove duplicates


A typical inequality: $\frac{8}{27}\leq\frac{(x^2+yz)(y^2+zx)(z^2+xy)}{(xy+yz+zx)^3}$

Question:
For $x, y, z\in (0, \infty)$ prove that: $$\frac{8}{27}\leq\frac{(x^2+yz)(y^2+zx)(z^2+xy)}{(xy+yz+zx)^3}.$$

My attempts to apply media inequality or other inequalities have been unsuccessful. In desperation I did the calculations and I have a rather complicated question question that I could not write as the sum of squares:
$$ 0\leq 6x^2y^2z^2 +19(x^3y^3+y^3z^3+z^3x^3)+27(x^4yz+xy^4z+xyz^4)-24(x^3y^2z+x^3yz^2+x^2y^3z+xy^3z^2+x^2yz^3+xy^2z^3).$$
Thanks for any ideas that might help me clarify the issue.
Answer: Add the following inequalities:
(1) Schur's inequality times $2xyz$:
$$xyz(x(x-y)(x-z)+y(y-z)(y-x)+z(z-x)(z-y))\ge 0$$
That is
$$2(x^4yz+y^4zx+z^4xy)+6x^2y^2z^2\ge 2(x^3y^2z+x^3yz^2+x^2y^3z+xy^3z^2+x^2yz^3+xy^2z^3)$$
(2) $12.5$ times $x^3+y^3-x^2y-xy^2\ge 0$: that is $12.5\sum_{cyc}xyz(x^3+y^3-x^2y-xy^2)\ge 0$. That is,
$$25(x^4yz+y^4zx+z^4xy)\ge 12.5(x^3y^2z+x^3yz^2+x^2y^3z+xy^3z^2+x^2yz^3+xy^2z^3)$$
(3) $9.5$ times $x^3+y^3-x^2y-xy^2\ge 0$: that is $9.5\sum_{cyc}(xy)^3+(yz)^3-(xy)(yz)^2-(xy)^2(yz)\ge 0$. That is,
$$19(x^3y^3+y^3z^3+z^3x^3)\ge 9.5(x^3y^2z+x^3yz^2+x^2y^3z+xy^3z^2+x^2yz^3+xy^2z^3)$$
Comment: Two questions: 1) when you add the three inequalities, how is the result connected to the question ? 2) What is your method for finding out your path ? Do you use a general/specialized software ?
Comment: (1) When you add those three, this is exactly the degree-6 polynomial form of OP's inequality. (2) I have not used software or something. Notice that the only trouble of that inequality is to deal with $x^2y^2z^2$ term (which is the smallest), and since I spotted $x^4yz$ term with a large coefficient, it is efficient to use that to clean up the $x^2y^2z^2$ mess. This is a really straightforward and common approach to deal with the expanded inequality. There are more advanced techniques for this type of inequality (such as pqr method and HCC) but this problem does not require those.
Comment: Thank you very much for your answers.
Answer: Alternative proof:
(pqr method)
Let $p = x + y + z, q = xy + yz + zx, r = xyz$.
The desired inequality is written as
$$\frac{8}{27} \le \frac{p^3 r - 6pqr + q^3 + 8r^2}{q^3} = \frac{p^3 r - 6pqr + 8r^2}{q^3} + 1. \tag{1}$$
We split into two cases:
Case 1 : $p^3 r - 6pqr + 8r^2 \ge 0$
Clearly, (1) is true.
Case 2: $p^3 r - 6pqr + 8r^2 < 0$
Using $q^2 \ge 3pr$, it suffices to prove that
$$\frac{8}{27} \le \frac{p^3 r - 6pqr + 8r^2}{q \cdot 3pr} + 1$$
or
$$\frac{9p^3 - 35pq + 72 r}{27pq} \ge 0.$$
Using $r \ge \frac{4pq - p^3}{9}$ (3 degree Schur),
we have
$$9p^3 - 35pq + 72 r
\ge 9p^3 - 35pq + 72\cdot \frac{4pq - p^3}{9}
= p(p^2 - 3q) \ge 0.$$
We are done.
Answer: Another solution based on what you have already obtained and AM-GM:
It is easy to check that;
$$x^2y^2z^2+x^4yz+x^3y^3 \geq3x^3y^2z.$$
So we need to show that;
$$17(x^3y^3+x^3z^3+z^3y^3)+25(x^4yz+xy^4z+xyz^4)\geq21(x^3y^2z+x^3yz^2+x^2y^3z+x^2yz^3+xy^3z^2+xy^2z^3).$$
Now realize that we simply get;
$$x^3y^3+x^3y^3+x^3y^3+x^4yz+x^4yz+xyz^4\geq6x^3y^2z,$$
by adding all the similar inequalities together, we will have;
$$(x^3y^3+x^3z^3+z^3y^3)+(x^4yz+xy^4z+xyz^4)\geq(x^3y^2z+x^3yz^2+x^2y^3z+x^2yz^3+xy^3z^2+xy^2z^3).$$
Hence, it is just needed to prove that;
$$8(x^4yz+xy^4z+xyz^4)\geq4(x^3y^2z+x^3yz^2+x^2y^3z+x^2yz^3+xy^3z^2+xy^2z^3).$$
Equivalently, we should show that;
$$2xyz(x^3+y^3+z^3)\geq xyz(xy(x+y)+xz(x+z)+yz(y+z)).$$
And this is almost obvious since $x^3+y^3\geq xy(x+y).$
Comment: Note that your "so we need to show that" is just Muirhead - $M(4,1,1) \geq M(3, 2, 1)$ and $M(3, 3, 0) ) \geq M(3, 2, 1)$ -  so this solution is essentially a two-liner. ( I was going to post that since it was much simplier/immediate the these solution, then realized it was yours.)
Comment: @CalvinLin Hello. Yes. you are right. Majorization didn't strike me when writing the solution at all.
Answer: First solution: We have
$$8(xy+yz+zx)^3 = [ \sum (xy+yz) ]^3 \leq 9( (xy+yz)^3 +  (yz+zx)^3 + (zx+xy)^3  ), $$
so it remains to show that
$$ (xy+yz)^3 +  (yz+zx)^3 + (zx+xy)^3   \leq 3 (x^2+yz)(y^2+zx)(z^2 + xy). $$
Let $ M (a, b, c) = \sum_{sym} x^a y^b z^c$. Then, by expanding everything, we get that
$$3(x^2+yz)(y^2+zx)(z^2 + xy)  - (xy+yz)^3 -  (yz+zx)^3 - (zx+xy)^3  \\ = M(4, 1, 1) + M(3, 3, 0) + M(2, 2, 2) - M (3, 2, 1). $$
By taking the symmetric summations of $ x^4 yz + x^3y^3 + x^2y^2z^2 \geq 3 x^3 y^2 z$, we get that $ M(4, 1, 1) + M(3, 3, 0) + M(2, 2, 2) \geq 3 M(3, 2, 1)$.
Hence we are done.

Alternative solution: Continuing from OP's work, WTS
$$27/2 M(4,1,1) + 19/2 M(3, 3, 0) + 1 M(2, 2, 2) \geq 24 M(3, 2, 1).$$
Muirhead tells us that $M(4,1,1) \geq M(3, 2, 1)$ and $M(3, 3, 0) ) \geq M(3, 2, 1)$.
We just need to AM-GM the $M(2, 2, 2)$ term, which has a very small coefficient, so it likely will work out.
As before, by taking the symmetric summations of $ x^4 yz + x^3y^3 + x^2y^2z^2 \geq 3 x^3 y^2 z$, we get that $ M(4, 1, 1) + M(3, 3, 0) + M(2, 2, 2) \geq 3 M(3, 2, 1)$.
Hence (by summing the relevant inequalities), the result follows.
Comment: [+1} Very interesting. Besides, what is the meaning of abbreviation "WTS" ?
Comment: @JeanMarie "Want to Show". This means that I'm still working with the original expression, and am uncertain if it's true. One then has to backtrack in the proof (or ensure that the implications are double-sided).


How to find the Base of an isoceles triangle in terms of its side?

Question: I have little math problem that I wish to solve but somehow I am having a hard time working it out... Say we have an isoceles triangle with sides equal to r and a base equal to b. Solve for b in terms of r.
Is there a way to do it? Without needing info about the angles. I tried using a combination of The pythagorean theorem and Herons formula but it did not work out, even though it seems like it should. Hehe. XD
Comment: It also depends on the angle opposite to the base, since by the cosine law $b^2=r^2+r^2-2r\cdot r\cdot \cos(\theta)=2r^2(1-\cos(\theta))$.
Answer: As already noted, we need one more piece of information. But it doesn't have to be an angle. We could choose this to be the triangle's height. By Pythagoras, $b=2\sqrt{r^2-h^2}$. Or in terms of the area $\Delta=bh/2$,$$b^2=4(r^2-4\Delta^2/b^2)\implies b^4-4r^2b^2+16\Delta^2=0\implies b^2=2r^2\pm\sqrt{4r^4-16\Delta^2}.$$This actually gives two solutions, since replacing an apex angle $\theta$ with $\pi-\theta$ preserves the area.
Answer: Consider a circle of radius $r$. If you draw any two radii of this circle, you can draw an isosceles triangle with two sides equal to $r$. But you'll notice that you can make $b$ of any length from $0$ to $2r$! Since $b$ is not fixed, there is no expression of $b$ in terms of $r$.
If you add the angle $\theta$ between the two radii, then $b=2r\sin(\frac\theta2)$.


Why does the expected value of given PDF not exist?

Question: For exam preparation I try to solve the following question:
Does the expected value exist for the density function $\frac{1}{\pi} \int_{-\infty}^{\infty} \frac{1}{x^2+1} \; \mathrm{d}x$
As I understand it I need to show that $\int_{-\infty}^{\infty}xf(x)\;dx$ converges
$$
\text{finding antiderivative}\\
\\
\frac{1}{\pi} \int_{-\infty}^{\infty} \frac{x}{x^2+1} \; \mathrm{d}x\\
\\
\text{substitute}\;u = x^2+1, du = 2x\\
\\
\frac{1}{2\pi} \int_{-\infty}^{\infty} \frac{1}{u} \; \mathrm{d}u = \frac{ln(\lvert u \rvert)}{2\pi} \Big|_{-\infty}^{\infty}\\
\\
\text{back substitution I get}\\
\\
\frac{ln(x^2+1)}{2\pi} \Big|_{-\infty}^{\infty} = 0
$$
So the integral exist and converges. What I am doing wrong here?
Any comment is appreciated. Thank you.
Comment: The integral for the expected value exists as a Cauchy principal value. The integrand being an odd function about $x=0$ gives you the zero you're getting.
Comment: For more detail, you can also check out [https://math.stackexchange.com/questions/2610315/how-to-prove-int-infty-inftyx-dx-is-divergent]
Comment: Regarding the first comment. Though, it's correct that one can give meaning to the integral by means of P.V., I don't think that it's too helpful here, or instructive. If you want to see, why this integral is not converging, read the wiki article on 'improper integrals'.
Answer: Your assertion
$$
\frac{1}{2\pi} \int_{-\infty}^{\infty} \frac{1}{u} \; \mathrm{d}u = \frac{ln(\lvert u \rvert)}{2\pi} \Big|_{-\infty}^{\infty}\\
$$
is not correct.  In fact, these four integrals all diverge:
$$
\frac{1}{2\pi} \int_0^1 \frac{1}{u}\;du = +\infty
\\
\frac{1}{2\pi} \int_1^{+\infty} \frac{1}{u}\;du = +\infty
\\
\frac{1}{2\pi} \int_{-\infty}^{-1} \frac{1}{u}\;du = -\infty
\\
\frac{1}{2\pi} \int_{-1}^0 \frac{1}{u}\;du = -\infty
$$
When we say
$$
\frac{1}{2\pi} \int_{-\infty}^{\infty} \frac{1}{u} \; \mathrm{d}u
$$
converges, we mean those four integrals all converge.


Mixed effects model error message: Model is nearly unidentifiable: large eigenvalue ratio

Question: I am fitting a mixed effects model with a binary outcome. I have one fixed effect (Offset, a 3 level factor) and one random effect (chamber, with multiple data points coming from each chamber). I have included random intercepts that vary across chambers to account for the non-independence of data points that come from the same chamber. There are 27 chambers with 3-20 data points coming from each chamber. My code is as follows:
ball1=glmer(Buried~Offset+(1|Chamber), family=binomial,
      data=ballData)

I then added random slopes to my model (that is allowed the slopes to vary across chambers) to see if I could imrpove the fit of the model. My code for this second model was
ball2=glmer(Buried~Offset+(Offset|Chamber), family=binomial,
      data=ballData)

ball2 did run and produce parameter estimates, however it gave me the following error message:

In checkConv(attr(opt, "derivs"), opt\$par, ctrl = control$checkConv,  :
          Model is nearly unidentifiable: large eigenvalue ratio
          - Rescale variables?

Nonetheless a comparison of the deviances between the two models showed that adding the random slopes did not improve the fit of the model. I have two questions (I have spent hours browsing the internet/other CV questions and am still unsure, so any help is much appreciated)
1) What does the error message mean and what can I do to fix the problem? I don't think I can rescale my variables because they are all factors.
2) I am including the random factor simply to control for any variation in the outcome variable across chambers so that I can test for the main effect of Offset. Is it correct to include both random slopes and intercepts to control for variation due to Chamber (i.e. (Offset|Chamber)), or is including only random intercepts sufficient to control for variation across Chambers (i.e. (1|Chamber))?
Here are the outputs for the models with and without the random slope. The first model (that includes random intercepts only, runs smoothly. When I add the random slopes (the second model), the warning appears.
    Generalized linear mixed model fit by maximum likelihood (Laplace
      Approximation) [glmerMod]
     Family: binomial  ( logit )
    Formula: Buried ~ Offset + (1 | Chamber)
       Data: ballData

         AIC      BIC   logLik deviance df.resid
       340.8    355.2   -166.4    332.8      267

    Scaled residuals:
        Min      1Q  Median      3Q     Max
    -1.5886 -0.6587 -0.5681  0.7003  1.9255

    Random effects:
     Groups  Name        Variance Std.Dev.
     Chamber (Intercept) 0.1574   0.3967
    Number of obs: 271, groups:  Chamber, 27

    Fixed effects:
                Estimate Std. Error z value Pr(>|z|)
    (Intercept)   0.7705     0.3010   2.559  0.01049 *
    Offset2      -1.2389     0.4021  -3.081  0.00206 **
    Offset3      -1.8705     0.4059  -4.608 4.07e-06 ***
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

    Correlation of Fixed Effects:
            (Intr) Offst2
    Offset2 -0.723
    Offset3 -0.765  0.545
    >

Now for the model with the random slopes added:
    Generalized linear mixed model fit by maximum likelihood (Laplace
      Approximation) [glmerMod]
     Family: binomial  ( logit )
    Formula: Buried ~ Offset + (Offset | Chamber)
       Data: ballData

         AIC      BIC   logLik deviance df.resid
       347.5    379.9   -164.8    329.5      262

    Scaled residuals:
        Min      1Q  Median      3Q     Max
    -1.7529 -0.5876 -0.5876  0.7008  1.9055

    Random effects:
     Groups  Name        Variance Std.Dev. Corr
     Chamber (Intercept) 0.3795   0.6160
             Offset2     0.8254   0.9085   -0.50
             Offset3     0.3795   0.6160   -1.00  0.50
    Number of obs: 271, groups:  Chamber, 27

    Fixed effects:
                Estimate Std. Error z value Pr(>|z|)
    (Intercept)   0.8497     0.3771   2.253   0.0242 *
    Offset2      -1.2570     0.5349  -2.350   0.0188 *
    Offset3      -1.9132     0.4343  -4.406 1.05e-05 ***
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

    Correlation of Fixed Effects:
            (Intr) Offst2
    Offset2 -0.705
    Offset3 -0.868  0.612
    convergence code: 0
    Model is nearly unidentifiable: large eigenvalue ratio
     - Rescale variables?

I have tried the following optimizers: however, they result in various new warnings:
ball2=glmer(Buried~Offset+(Offset|Chamber), family=binomial,
   data=ballData,
   control=glmerControl(optimizer="bobyqa"))
##
ball2=glmer(Buried~Offset+(Offset|Chamber), family=binomial,
   data=ballData,
   control=glmerControl(optimizer="Nelder_Mead"))
##
ball2=glmer(Buried~Offset+(Offset|Chamber), family=binomial,
   data=ballData,
   control=glmerControl(optimizer="optimx",
      optCtrl=list(method="nlminb")))
##
ball2=glmer(Buried~Offset+(Offset|Chamber), family=binomial,
  data=ballData,
  control=glmerControl(optimizer="optimx",
     optCtrl=list(method="L-BFGS-B")))

Answer:
1) What does the error message mean and what can I do to fix the problem? I dont think I can rescale my variables because they are all factors.

It means that the curvature of the likelihood surface is very flat in some direction. You might have complete separation (do you have estimated parameter values larger than 5 or so??) Alternatively it might be a false positive. See ?convergence for ways of testing (e.g. if you fit with more than one optimizer and get the same answer, you're probably OK). It would be interesting to see a reproducible example.

2) I am including the random factor simply to control for any variation in the outcome variable across chambers so that I can test for the main effect of Offset. Is it correct to include both random slopes and intercepts to control for variation due to Chamber (i.e. (Offset|Chamber)), or is including only random intercepts sufficient to control for variation across Chambers (i.e. (1|Chamber)).

This is a bit of a can of worms: see e.g. my answer here. Generally the advice is "include in the model all random effects that can be estimated in the experimental design, if the data allow it/it doesn't make the model too complicated".
The updated information on your fit shows that you have a singular fit (as shown by the -1.00 correlation between (Intercept) and Offset3). That definitely makes a reasonable justification for simplifying the model to (1|Subject) ...
Random effects:
 Groups  Name        Variance Std.Dev. Corr
 Chamber (Intercept) 0.3795   0.6160
         Offset2     0.8254   0.9085   -0.50
         Offset3     0.3795   0.6160   -1.00  0.50

Comment: Thank you for your thoughts Ben. I have pasted in the outputs of the two models. I don't have parameter values over 5. I am very new to R and my statistical understanding is (embarrassingly) rather rudimentary; I did get a bit lost in the information provided in the ?convergence page. I did try some optimizers (code above), however Im not sure if I have even used the correct script. All of the optimisers that I tried provided various warning messages. Could you clarify what the optimisers do? And have I even used them correctly?
Comment: Furthermore, given you advice regarding my 2nd question, I am wondering if I can get away with only including a random intercept (that varies by chamber), given that the addition of random slopes (that also vary by chamber) for two other predictors in the model does not improve the fit (I also do not get any warning message when I fit a random slope to these other predictors, it is only the Offset predictor that is causing problems). Perhaps by fitting random slopes I am unnecessarily complicating the model?


Changes to the DataGrid from v. 3.5sp1 (ToolKit) to .Net 4.0

Question: I recently discovered that some functionality has been changed drastically in the DataGrid since it made it into the general 4.0 framework (Using BindingGroups for one).
Can anyone point me at a list of changes (breaking or non-breaking)?
Answer: Unfortunately at least an official list does not seem to be available (which is a pity indeed), as informally confirmed by Lester Lobos answer to the similar question Official WPF DataGrid compared to WpfToolkit datagrid in the MSDN WPF forum:

the features should be similar for most scenarios... however, there isnt any documented list

Lester seems to be a Lead Software Engineer (QA) at Microsoft Corporation involved with the WPF team at least, so he should be in the know.
Only slightly related but still good to know in this context is Bob Baos answer to the more general question WPF Toolkit in WPF 4.0:

I get a mesage from a consultation in the internal WPF discussion. Unfortunately, the WPF Toolkit will not be updated to 4.0 anytime soon.
Comment: A pity (or PITA), indeed :-). IMHO, introducing BindingGroups is not 'similar' functionality... Thanks for taking the time to investigate it.

I'll award the bounty when I can.
Comment: @Goblin - agreed, this is a significant change in fact, which should be properly documented at least to help with migration! And you are welcome of course: I do enjoy investigating once in a while for procrastination anyway, your bounty made it more worthwhile even, thanks :)


Let $p_n = n$th odd prime. When is $p_n$ a continuous function of $n$?

Question: Under what topologies is the function $p(n) = n$th odd prime continuous?  If we take the Euclidean topology on $\Bbb{R}$ and induced it onto the subspace $\Bbb{N}$ and called it $\tau$.  Then isn't $p(n)$ continuous from $(\Bbb{N}, \tau)$ to itself?
Comment: primes in the sense of rings ? or in the sense of generators of a multiplicative group (or monoid) ?
Answer: The induced topology on $\mathbb{N}$ is simply the discrete
topology (all subsets are open), so any function $f\colon(\mathbb{N},\tau)\rightarrow(\mathbb{N},\tau)$ is trivially continuous (but, this isn't particularly interesting).


Serializing a custom class in ActiveRecord with specific syntax

Question: I have a custom Interval class that I would like to use inside a few different ActiveRecord models. Currently I am storing the interval as a string with a specific syntax (w/ a custom validator to enforce formatting) and just creating a new object anytime I need to access Interval methods.
What do I need to add to the ActiveRecord models/ Interval class to be able to use the interval as an object instead of a string, while still storing it in the database using the specific syntax?
Hopefully that makes sense but if not hopefully the following example clears things up.
The ActiveRecord class currently looks something like:
class MyClass < ActiveRecord::Base
  validates :interval, allow_blank: true, interval: true   # custom validator
  ...

And to do anything useful I create a new interval:
def some_helper
  ...
  interval_object = Interval.new(@my_class.interval)   # @my_class.interval is just a string with specific syntax
  if interval_object.useful?                           # 'useful' method
  ...

But I would like to do:
def some_helper
  ...
  if @my_class.interval.useful?   # 'useful' method
  ...

Interval syntax that initialize expects:
3:day  # represents every 3 days
1:week # represents every week

This seems like it should have a simple solution but I can't seem to find the right phrasing.
Answer: You should be able to override the accessor and mutator methods to do what needs to be done:
def interval
  Interval.new(super)
end

def interval=(i)
  # Or whatever needs to be done to convert `i` back to a string,
  # keep in mind that `i` might be a string already.
  super(i.to_s)
end

Then you can say things like:
@my_class.interval.useful?
@my_class.interval = some_interval_object
@my_class.interval = some_string_that_looks_right
@my_class.update_attributes(:interval => some_interval_object)
@my_class.update_attributes(:interval => some_string_that_looks_right)

and The Right Things should happen.
Comment: Thanks, that got things working but now I have an additional question, I plan on using this class in multiple models. Would a connection adapter be the best way to abstract this out so I don't have to reimplement this in every model?
Comment: Do you mean "patch the connection adapter"? That might be pretty hairy. You might be able to get away with a fairly simple `has_interval_in :column_name` macro to generate the `column_name` and `column_name=` methods for you.


How to make true/false statements

Question: It's not because I want to know how to do this instead of which one is faster..
How would I make a statement true or false ?
I want this:
if $var = true {
    do this
} else{
    do this
}

I'm aleady using a foreach but I thought something like this:
if($myvar == 'True'){
    echo copy from array
} else  {
    echo none
}

Comment: You can click 'edit' and fix it.
Comment: I don't know why formating has messed up :L
Comment: Have a look at PHP operators: http://php.net/manual/en/language.operators.php
Comment: possible duplicate of [PHP IF statement for Boolean values: $var === true vs $var](http://stackoverflow.com/questions/1670138/php-if-statement-for-boolean-values-var-true-vs-var)
Comment: It's not because I want to know how to do this instead of which one is faster..
Answer: Normally, if your variable contains a boolean, all you have to do is:
if($myVar)
{
    //do stuff
}
else
{
    //do something else
}

You can also do this if it's clearer to you:
if($myVar == true)
{
    //do stuff
}
else
{
    //do something else
}

What's important is not to mistake the comparison operator (==) with the assignment (=) otherwise you'll end up with strange results. This happened in your initial statement in which you also forgot the parenthesis.
As for the "else" statement, it is automatically executed when the condition is false, which in this case would mean $myVar is actually false.
Comment: You will never get in the if statement if you compare it to the string 'True' neither. You will always get true on the other hand with this syntax '$var = true' because the affectation will occur.
Comment: Add details on his mistake so this post can help others (comparison of a boolean as a string)
Comment: How would it ever do the else statement?

How to make true/false statements


Updating Select2 selected elements when Angular model changes

Question: I'm working on a project for deploying software through an AngularJS UI. On the current view, you have to select what environment a deployment is for. The possible list of environments is stored in the scope and is what the options for the select are built from:
<select ui-select2="{ }" data-placeholder="All Environments" ng-model="transformParams.EnvironmentIds" multiple="multiple" class="input-xxlarge">
  <option ng-repeat="environment in environments" value="{{ environment.Id }}">{{ environment.Name }}</option>
</select>

Also on this page, there is a drop down that changes the current item that the environment is going to be set for. Choosing an existing item from the dropdown should take the Environments property from the existing item and select the correct elements in my Select2 box. This would then obviously update the transformParams.EnvironmentIds model. I've tried updating that model to change which environments are select but to no avail.
I've seen the bugfix to Angular 1.2 but I am stuck on 1.0.7 and don't have the option to upgrade Angular at this stage.
Answer: I solved the problem by using some options for the select2:
<select ui-select2="selectOptions" data-placeholder="All Environments" ng-model="transformParams.EnvironmentIds" multiple="multiple" class="input-xxlarge">
    <option ng-repeat="env in environments" value="{{ env.Id }}">{{ env.Name }}</option>
</select>

With the options being defined in the controller:
$scope.selectOptions = {
    'multiple': true,
    'simple_tags': true,
    'initSelection': function (element, callback) {
        callback($(element).data('$ngModelController').$modelValue);
    }
}


Linkit not working with CkEditor

Question: I have installed the Linkit module to a test site.
I have created a profile, set Matchers and created attributes. I have gone into the CKEditor configuration and chosen my Linkit profile, added the Linkit button, saved the configuration and then liberally cleared the cache on my test site (Vagrant running a lamp stack and Drupal 8.)
When I attempt to use the Linkit feature on either a new piece of content, or an existing one, the dialog box appears with all the desired options, however, other than the standard CKEditor link behaviour none of the other attributes work. I cannot set the title, I cannot set the target attribute.
No errors are appearing in the log and I can find no similar problems on line.
Can anyone suggest a reason this is occurring?
Comment: Is the filter not full HTML? If not you may need to allow an a tag to have such attributes.
Comment: I've written a few CKEditor plugin integrations and I _still_ do it from time to time.
Comment: yup that was it... i'm an idiot. Always check the allowed tags in the CkEditor configuration. It would be nice if they provided an error/auto enabled the tags when you enabled something like linkit.
Answer: If the filter not Full HTML, you will need to edit the filter format and enter the attributes on the anchor tag in the settings. If not, they will be stripped out (for security reasons).

Linkit not working with CkEditor


Is there a historical reason why we say "C sharp" but notate on the staff "sharp C"?

Question: Early music students are often confused with where to place accidentals:

When we speak, we say the note name first and then the accidental: C sharp.
When we're writing away from the staff, we do the same: C♯.
But when we notate in the staff, we suddenly change the ordering: the ♯ comes before the C notehead.

Is there a historical (or even etymological) reason for this? I'd love to point to some specific reasoning instead of just telling my students "this is just how we do it."
Comment: Is this true in all languages, or just in English?  I would not at all be surprised to find it varies with the defined sentence structure rules for each language.
Comment: It's just a language convention. Like how we say "fifty dollars" but write "$50".
Comment: @Tim Does it intuitively make sense, or does it only make sense because that's what we're used to? It seems to me we could easily learn to read accidentals *after* a note, just as we've learned to read dots that appear after a note.
Comment: @curiousdannii That's a great example of a similar scenario that I hadn't thought of. If you have any more insight to add on that front, I'd love to see it as an answer!
Comment: @CarlWitthoft I considered this very issue with languages where the modifier comes after the noun. But my reasoning always seems to fall short of an explanation. I also wondered if this confusion was limited to students whose native languages are written right to left, but that's not at all the case.
Comment: In a way, accidentals are attached to lines/spaces rather than individual notes.  So rather than thinking about "a sharped C note" you can think of it as "a note which is on the C sharp space".
Comment: Regarding staff notation, note that  a # is written only once and keeps its validity until undone. So a sequence C#, D, C#, C1# ends up less messy as # C D C C1. In other words, the # appearing mid-staff is more like changing the whole key than like changing the single note. Why this? Because sharping a single note instead of temporarily changing the key is much less common. At any rate, this makes it more appropriate to write it as a "from here on" instead of "for the preceding note and then from here on".
Comment: It makes sense that any accidental is shown *before* the note on a stave, but you're right, there's no obvious logic to what's said or written longhand. French, for one, is the same as in English. Even the titles reflect what you say - 'Sonata in Eb'. +1.
Comment: Good point. A similar query of mine is why do we need the key sig. on each line? I used to read so much that just had it on the first stave, and that's it. Real/fake books, in the main. But since we don't repeat the *time* sig., why the key sig? Also loved one writer, who'd put, say, 4# any old where. It had to mean E/C#m, so who cares..?
Comment: The key signature comes before the notes too...
Comment: Hmm, I have no idea if this is the actual reason, but you mentioned dots being after the note - maybe it was a way to make sure that dots and accidentals on the same note don't interfere with eachother.  Compare `●··#` or `●#··` to `#●··`  The standard notation puts all modifiers close to the note head, which might be easier to read.
Comment: Apparently 'No' is not an acceptable answer!
Answer: I don't know about a historic source, but a few thoughts:
The reason to put the accidental before the note does make sense from a reading standpoint. Get the "warning" of the accidental first, then the note. Although it really wouldn't be too hard to read it with the accidental after, surely it's "read" as one visual "chunk."
There is non-notated usage "flat five", "lowered seventh", etc that prefixes the accidental.
The rest is just the craziness of the English language.
Sharp and flat are adjectives in basic usage, but they can also be adverbs, nouns, and verbs where to position before/after changes.

...start at 7:30 sharp..., ...turn down flat...
the musical symbols, a sharp, a flat
...sharp the C..., ...flat the C...

The last example, the verbs, it strange. Normally you would use sharpen or flatten, but definitions for music usage give plain sharp and flat as verbs.
That is further complicated when using a past tense verb as an adjective:

...the sharped C..., ...the flatted B...

Sometime English places adjective after nouns, postposition, like in attorney general, private first class, eggs benedict, Generation X, etc. etc. There aren't clear rules for when the adjective comes before or after the noun. But, in regard to historic use, it's interesting that Wikipedia explains that the postposition is often an archaic usage.
The musical usage C sharp or B flat seems to me the postposition form, putting the adjective after the noun.
Comment: I've never accepted '*sharp the C'*, or '*the C is sharped*'. To me it's just bad English. But just as daft - 'the pencil was sharpened', as opposed to 'the C was sharpened'. Englsih might be a bastardised language, but I think I have a better word...
Comment: That usage is strange to my ears too, but I do see it from time to time. Personally, I say "raise" or "lower" for the verb.
Comment: I was doing some research, but I've not found reliable sources so far about possible historic reasons. I agree with the reading standpoint, also conceptually: alterations are normally at the beginning of the piece, as some adjustments may be necessary to the instrument (like with timpani) or even choosing another one (consider trumpets), and since alterations can be persistent (at least for the current bar) it wouldn't very coherent to put individual accidentals *after* the note. Also "be aware, you're going to play an altered note" is better than "hey, the previous note had to be altered" ;-)
Answer: In German c sharp becomes cis (as opposed to c) and in a single word this sequence reversal is much less visible, but yes, is trails the note name.
I observe, however, that this is a standard way for word formation, so strong becomes strongly as an adverb, stronger as comparative, and a weakened blue becomes bluish. So I assume that it is more brain-compatible to start with the fixed concept and add modifiers later.
Concerning notation the other sequence has its advantages: if you already played a c it is too late to start modifying. (This is also shared by notation like computer keyboard CTRL+C). In computer science there is a special term for this, when applied to variable length encodings (see Wikipedia):

A prefix code is a code with the "prefix property": there is no valid code word in the system that is a prefix (start) of any other valid code word in the set

So with the note head as easily recognizable end the prefix property is kept. (Explanation, why this is desired: It has the advantage, that when sequentially decoding the notation, you recognize, when all information for a note is available without need to look ahead).
Comment: I disagree with your theory about word formation - it's not like word prefixes are unheard of (there are four in this sentence alone, and none are particularly brain-incompatible). It's also the case that in English, adjectives almost always come *before* the word they modify, and only rarely after.


Show four equal integrals$\int_0^1e^{4/\ln x}dx=\int_0^12xe^{2/\ln x}dx=\int_0^1\frac{2x}{\ln^2x}e^{2/\ln x}dx=\int_0^1\frac4{\ln^2x}e^{4/\ln x}dx$

Question: While investigating Mellin transforms I noticed that the following four integrals are all equal.

How do you show that these four integrals are equal?$$ \int_0^1 e^{\frac{4}{\log(x)}}~dx =\int_0^1 2xe^{\frac{2}{\log(x)}}~dx=\int_0^1 \frac{2x}{\log^2(x)}e^{\frac{2}{\log(x)}}~dx= \int_0^1 \frac{4}{\log^2(x)}e^{\frac{4}{\log(x)}}~dx $$

Now I want to be able to prove that they are all equal. My attempt was to show that the difference between each pair of them is zero.
$$ \int_0^1 e^{\frac{4}{\log(x)}}-2xe^{\frac{2}{\log(x)}}~dx= \int_0^1 e^{\frac{2}{\log(x)}}\bigg(e^{\frac{2}{\log(x)}}-2x\bigg)~dx \overset{\log( x) \to x}= \int_{-\infty}^0 e^{\frac{2}{x}+2x}\bigg(e^{\frac{2}{x}+2x}-e^{2x} \bigg)~dx=\int_{-\infty}^0 e^{\frac{2}{x}+2x}\bigg( e^{2x}\bigg(e^{\frac{1}{x}}-1 \bigg)\bigg(e^{\frac{1}{x}}+1\bigg)\bigg)~dx $$
However I got stuck here.
Comment: The first inequality is merely the transformation $x\to x^2$ and the last the inverse $x\to\sqrt{x}$ so you only need to show the middle equality.
Answer: Note
\begin{align}
&\int_0^1 \frac{4}{\ln^2 x}e^{\frac{4}{\ln x}}~dx
= -\int_0^1 x \> d\left( e^{\frac{4}{\ln x}}\right)
\overset{IBP} =\int_0^1 e^{\frac{4}{\ln x}}~dx\\
&\int_0^1 \frac{4}{\ln^2x}e^{\frac{4}{\ln x}}~dx
\overset{x\to x^2 }= \int_0^1 \frac{2x}{\ln^2 x}e^{\frac{2}{\ln x}}~dx\\
&\int_0^1 e^{\frac{4}{\ln x}}~dx \overset{x\to x^2} =\int_0^1 2xe^{\frac{2}{\ln x}}~dx
\end{align}


Euler characteristic of projective plane (rank$(H_1(\mathbb{R}P^2))=$ rank$(Z_2)=0?$)

Question: Let $K$ denote the $2$ dimensional projective plane $\mathbb{R}P^2$ . Then we have
$$H_0(K) \cong Z$$
$$H_1(K) \cong Z_2$$
$$H_2(K)=0$$
Let $b_i$ denote the Betti number of $K$ , $b_i=rank(H_i(K))$, then we have
$$E=b_0-b_1+b_2$$
We know that the Euler number $E$ of $K$ is $1$ , $b_0=1$, $b_2=0$ . So we must have $b_1=0$ , which means that $rank(Z_2)=0\neq1$ . However , $rank(Z_2)$ should be $1$ since $<1>=Z_2$ .
There must be something wong in the argument above , but I can't see where it is . Any help would be very appreciate .
Answer: The rank of a module $M$ is the rank of its free part, or equivalently the maximal number of linearly independent elements in $M$. $\mathbb{Z}_2$ has no linearly independent elements, since $2 \cdot 1 = 0$ in $\mathbb{Z}_2$, and hence its rank is 0.
Comment: Alternatively the rank of an abelian group ($\mathbb Z -$module) $A$ is the largest number $n$ such that there is an injective map $\mathbb Z^n \rightarrow A$
Answer: You are working in homology with coefficients in $\mathbb Z$, where the chain groups and homology groups are modules over $\mathbb Z$. The rank of a $\mathbb Z$-module is equal to the maximum rank of a free submodule over $\mathbb Z$. So no, $\text{rank}(\mathbb Z_2)=0$, not $1$, because the only free submodule over $\mathbb Z$ of $\mathbb Z_2$ is trivial.
Perhaps your are also trying to think about homology with $\mathbb Z_2$ coefficients? If so, you get a different calculation with a consistent outcome:
$$H_0(K;\mathbb Z_2) \cong \mathbb Z_2$$
$$H_1(K;\mathbb Z_2) \cong \mathbb Z_2$$
$$H_2(K;\mathbb Z_2) \cong \mathbb Z_2$$
all of which have rank $1$ as modules over $\mathbb Z_2$, and so the Euler characteristic over $\mathbb Z_2$ is $1-1+1=1 \in \mathbb Z_2$, which of course is equal to the reduction modulo $2$ of $1 \in \mathbb Z$.


What kind of analysis to use in SPSS for finding out groups/grouping?

Question: My research question is about elderly people and I have to find out underlying groups. The  data comes from a questionnaire. I have thought about cluster analysis, but the thing is that I would like to search perceived health and which things affect on the perceived health, e.g. what kind of groups of elderly rank their health as bad.
I have some 30 questions I would like to check with the analysis, to see if for example widows have better or worse health than the average. I also have weights in my data so I need to use complex samples.
How can I use an already existing function, or what analysis should I use?
Answer: The key challenge you have to solve first is to specify a similarity measure. Once you can measure similarity, various clustering algorithms become available.
But questionnaire data doesn't make a very good vector space, so you can't just use Euclidean distance.
Answer: If you want to generate clusters using SPSS, standard options include: k-means, hierarhical cluster analysis, or 2-step. I have some general notes on cluster analysis in SPSS here. See from slide 34.
If you want to see if widows differ in their health, then you need to form a measure of health and compare means on that measure between widows and non-widows (presumably using a between groups t-test). If you have 30 questions related to health, then you may want to do a factor analysis to see how the items group together.
If you are trying to develop  a general model of whats predicts perceived health then there are a wide range of modelling options available. Multiple regression would be an obvious starting point. If you have many potential predictors then you have a lot of choices regarding whether you are going to be testing particular models or doing a more data driven model building approach.
More generally, it sounds like you need to clarify the aims of your analyses and the particular hypotheses that you want to test.


Yahoo Finance YQL query not working. Did something change?

Question: For the past year I have been able to use Yahoo YQL Rest query to obtain the currency exchange rates; however, today it has stopped working for some odd reason.
https://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select+*+from+yahoo.finance.xchange+where+pair+in+(%22USDCAD%22)
https://query.yahooapis.com/v1/public/yql?format=json&q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22CADUSD%22%2C%20%22USDCAD%22%2C%20%22EURUSD%22%2C%20%22EURCAD%22%2C%20%22GBPUSD%22%2C%20%22GBPCAD%22)&diagnostics=false&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
Has something changed? How can I find out what happened?
Is there an alternative solution I can use to obtain this data?
Answer: There seems to be an issue with http://datatables.org/ at the moment, which is the basis for the "Community Tables" (such as the Yahoo Finance table) on YQL. I haven't been able to find any more information on why it's down, but hopefully it comes back up soon.


Which pedals do they use?

Question: Is there anybody has any idea which pedals might be used for this song? I looked up on comments but there is no answer at all.
Comment: You can start by explaining which part. In that intro, it seemed like a cheap vintage guitar which gets a very sitar-like sound because of fret buzz, with maybe a little chorus but not much. You can link to a specific starting time with the YouTube video sharing mechanism.
Comment: There are several different effects used at different times. They may not even be pedals. Can you be more specific.
Comment: Actually I am interested in vintage sound
Comment: You might well be, but it doesn't help us answering the question!
Comment: Then it means I do not have proper knowledge to properly tell which sound exactly I am looking for.
Comment: Dear Dave Jacoby thank you for your suggestions. I was exactly looking for that part, for that vintage sound at the beginning.
Answer: From this video seems like the sound is coming from an Fender Hot Rod Deluxe, which is a tube amplifier. This is what is making this kind of "vintage" sound.
From here you can have a glance on the pedals, seems there is at least a Big Muff Pi and a Boss Overdrive plus maybe a Mooer Octave and an unidentified pedal… It is likely that not all of them (maybe none) are used in the song you linked ;).
Hope it helps!

Which pedals do they use?