Copy sheets between two Workbooks that have Formulas in it

Question: I am trying to copy sheets between to two workbooks. This is the code that  i have. xlWorkbook contains the data and i want to add sheets from xlDesTemplatebook that contains all my formulas.The code works and copies all the sheets but cells with formulas are appearing as #REF & if i select the cell having formulas and then hit enter it works.But my problem is that i am using the xlworkbooklater in my program for which i need the calculated data not the #REF in those cells. How can i fix this ?
<code> xlWorkBook = xlApp.Workbooks.Open(TextBox1.Text)
 XlDesTemplateBook=xlApp.Workbooks.Open("C:\Users\user\Desktop\Formulas.xlsx")
 Dim oSheetsList() As Object = {"IB6", "IB7", "IOB6", "IOB7", "LI", "LO", "VB"}
 XlDesTemplateBook.Sheets(oSheetsList).Copy(After:=xlWorkBook.Worksheets("PLC EXPORT-VB"))
</code>
Screenshot Showing my issue
Answer: I have got round this by doing the following:
1) make a copy of the sheet you want to send
2) select all or just the cells with formulae
3) do edit/ replace and replace = with xyxyxy or something that never appears
4) move the sheet over to the other workbook
5) select all and replace xyxyxy with =
Always works fine for me...
Comment: I have lot of Formulas like this "=IF(ISBLANK('LOCAL IO '!C2),"SPARE",'LOCAL IO '!C2)" in each cell. I have 6 sheets and upto 400 cells in each sheet. So i cant find and replace for every single formula
Comment: I have to move some of my "special" sheets (which grade 40 groups with 240 students and 6 faculty with 40 categories per student so several thousand cells and it works for me... Once you replace the "=" then it is just text and then the links don break unlike the ref error you get - and it was to get round exactly that problem that I came up with that method... BTW you can select all the sheets and all cells together...
Comment: Have you considered having a sheet in the template file so you paste the data then save-as so moving the data instead of the formulae...
Comment: I tried your tip and it works But i didn't figured it out yet how to do that in VB.net. I will wait for some more time if any other way to do this vb.net. Or else i will mark yours an answer
Comment: Well, you could have the template file already prepared so your vba just copies over the sheets then do the edit/replace of xyxyxy to "=" which would save a bit of grief coding...


Phonegap vs Android Native SDK for supporting multiple languages

Question: I want to parse a planet feed which has multiple rss that supports multiple languages like Spanish, German, etc
My question is should I go with phonegap or native android sdk. I am not sure which one would be better that can support this requirement.
Comment: use google for a while boss..!!
Comment: hey I did Google it, And have already considered the answers given below, it was just that I wanted an answer specific to localization,
Answer: Depends on your skill set. If you have to learn javascript and java it doesn't matter. Pick one and learn how to do it. If you already know javascript or java, pick the one you know better/like the most and go for it.
The native sdk offers localization : see here. Using phonegap, you'll have to define your own javascript localisation methods. Which is not so complicated, I have done it before and I'm not expert in javascript.
You also have to consider other things like:

Is your app android only or you'll support other platforms?
How "heavy" is your app? Does it render heavy graphics or has fancy animations? In my epxerience phonegap gets a bit laggy on
those.

Search the differences, pros and cons of doing both. To help you get started.


Replicação de banco de dados

Question: já li alguns artigos referente a replicação de banco de dados e espelhamento, mas uma dúvida que ainda tenho, e não encontrei uma resposta "concreta" seria referente e atualização do banco.
Por exemplo: Tenho o MASTER e o SLAVE, vou implementar uma nova funcionalidade no meu sistema e precisa adicionar novas tabelas, ou atualizar tabelas já existentes, adicionando novos campos ou removendo, entre outras operações necessárias.
Se eu atualizar o master, essas alterações em tabelas serão replicadas também para o slave?
Ou se eu fizesse essa atualização no slave (supondo que a replicação seja bidirecional), também seria replicada para o master?
Hoje, supondo que esse seja mesmo o processo...É a maneira utilizada para realizar essas atualizações em campos das tabelas, sem que a aplicação fique indisponível?
Comment: Provavelmente vai ter que deixar algum software para sincronizar, talvez uma rotina com CRONTAB. De qualquer forma é um assunto muito amplo. Não posso afirmar que este seja o caminho ideal, nem a sua ideia que descreveu nem a ideia de sincronizar.
Comment: Sim, compreendo essa questão....Mas minha dúvida seria, esses softwares vão sincronizar tudo, além dos dados?
Comment: Não tem software pronto pra isto (quero dizer deve ter), mas no geral usando as ferramentas nativas do MYSQL-client **você mesmo** define o que deseja sincronizar, fazendo um full-backup (deve ter maneira mais fácil) e fazendo um drop do slave.
Comment: Entendi, é, até o momento, eram essas as possibilidades que eu já tinha visto pessoas comentando....Realmente é um assunto amplo e complexo. Agradeço a reposta, caso eu encontrar mais algo interessante, irei compartilhar.
Comment: Eu uso SymmetricDS, faz todo o trabalho duro sem problemas, e pode usar qualquer banco de dados e ainda pode usar bancos diferentes nos servidores.
Funciona muito bem.
Answer: Cada método de replicação possui seus prós e contras. Como dito nos comentários da pergunta, você precisa identificar as suas necessidades para encontrar então o esquema de replicação mais adequado para sua aplicação.
Segue abaixo, em linhas gerais, transcrição do "discurso" que sempre utilizo quando preciso entrar nesse assunto. Foco em PostgreSQL, que é a solução que mais utilizo diariamente e com a qual possuo mais afinidade.
Replicação unidirecional
O PostgreSQL oferece de forma nativa apenas o método de replicação unidirecional, em que há um servidor master e um ou mais servidores slave em standby. Os servidores em standby podem ser utilizados para queries de consulta, mas não de escrita, sendo chamados nesse caso de hot standby. Nesse modo de replicação, todas as alterações efetuadas no master serão feitas também, automaticamente, em todos os servidores slave.
O método de replicação mais básico, que não oferece suporte a queries de leitura nos servidores standby é chamado de log shipping, ou warm standby. Nesse método, segmentos de log de transação do Postgres (WAL- write-ahead log), de 16MB cada, são enviados pela rede para os servidores de réplica e executados em processo cíclico. Dado o tempo para "preenchimento" de um segmento desses, este método de replicação representa certa lentidão no processo de replicação, sendo recomendado para baixos volumes de dados ou para circunstâncias em que não é necessário que o sincronismo da réplica seja tão atualizado.
Além do log shipping, o PostgreSQL possui um modo chamadao streaming replication, em que um fluxo constante de alterações é enviado diretamente ao servidor slave através de conexão persistente. Isso permite constante checagem da integridade dos dados aplicados e, portanto, o referido hot standby.
A replicação em hot standby pode ser configurada tanto como assíncrona (o padrão), em que os dados podem levar algum tempo para ser escritos nos servidores slave, quanto síncrona, em que o COMMIT do usuário só é considerado completamente atendido quando for efetuado também no servidor slave. É possível configurar um ambiente misto de réplicas tanto síncronas quanto assíncronas, assíncronas em cascata etc.
Embora o uso de replicação síncrona para fins de alta disponibilidade seja tentador, deve-se ter em mente a relação entre capacidade de transferência de rede e o volume de dados replicados. Se sua rede for lenta, os comandos de alteração executados no master demorarão para ser COMMITados e o banco parecerá "travado". Arquiteturas para replicação síncrona de boa performance tendem a ser especificadas com o uso de cabos cross máquinas vizinhas, sem qualquer outro ativo intermediário de rede, para evitar gargalos. Mesmo assim, grandes volumes de dados trafegados tendem a inviabilizar tal nível de imediatez. O custo de infraestrutura, portanto, aumenta de acordo com o volume transacional da aplicação, até se tornar inviável em quadros de alto volume de dados.
Dito isso, configurações de replicação que utilizam o método de hot standby representam o mundo intermediário: a replicação continua assíncrona, mas o volume de dados trafegados permite que as atualizações aconteçam de forma quase síncrona (near-sync), o que aparenta ser suficiente para a maioria dos usos sem risco de incorrer nas interrupções do método síncrono.

Replicação bidirecional
Não há solução nativa de replicação bidirecional em PostgreSQL, sendo necessário instalar plugins que ofereçam tal funcionalidade. O mais estável e mais utilizado atualmente é chamado BDR, desenvolvido pela 2nd Quadrant. Entende-se que em algum estágio tais funcionalidades serão incorporadas pela base de código do PostgreSQL, mas por enquanto é necessária a instalação do plugin BDR à parte.
Como o nome indica, a replicação bidirecional permite que sejam efetuadas alterações em todos os servidores envolvido, sendo portando um método de replicação multimaster. Alterações simultâneas de um mesmo objeto em nós diferentes podem provocar conflitos a serem resolvidos pelo plugin, e tal processo de resolução pode ser custoso. Isso significa que a aplicação deve estar preparada e dimensionada para evitar ao máximo tais tipos de conflito.
A replicação BDR é inerentemente lógica, oferecendo a funcionalidade de configuração dos objetos a serem replicados. Dessa forma, tabelas temporárias e outros dados menos importantes podem ser deixados de fora da replicação, podendo reduzir o custo com resolução de conflitos e o tempo de processamento das alterações pelos nós que recebem os dados.
Outra característica do BDR é ser inerentemente assíncrono: o COMMIT é retornado para o usuário pelo nó em que este comandou a alteração, e os demais nós terão a transação aplicada algum tempo no futuro. A replicação por BDR utiliza o mesmo mecanismo de streaming replication supracitado, portanto tendendo a resultar, quando não há necessidade de resolver conflitos, em tempos de replicação considerados near-sync.
A criação e configuração de nós bidirecionais, a manutenção e a monitoração da qualidade da replicação tendem a demandar mais atenção e trabalho do que os métodos de replicação unidirecional. Isso é algo que se deve levar em conta na escolha do BDR.

Balanceamento, paralelismo e pool de conexões
Há outros métodos de trabalho que podem solucionar problemas sem que seja necessário recorrer à replicação. Ferramentas que ficam entre a aplicação e o PostgreSQL, como o PgBouncer, permitem a divisão de trabalho entre mais de um servidor de banco de dados até no nível do comando em si, possibilitando um particionamento lógico de dados entre nós. O Pgpool-II permite a formação de pools de conexão entre nós, balanceamento de carga e execução paralela de queries em mais de um servidor. Ele também pode ser utilizado como agente intermediário em esquemas de failover automático.
Tais tecnologias podem ser utilizadas sozinhas ou em conjunto com métodos de replicação. Às vezes o que sua aplicação precisa é apenas de um Pgpool-II mandando as mesmas queries para dois bancos diferentes: o momento da execução em ambos os lados pode diferir em questão de milissegundos, trata-se de transações diferentes, mas os dados existem dos dois lados.
Além dessas duas ferramentas há outras capazes desse tipo de malabarismo, cada uma com suas funcionalidades específicas.

Casos de uso
Como visto acima, cada método de replicação oferece uma relação "custo-benefício" diferente para o sistema. Antes de se adotar uma solução, deve-se ter em mente as necessidades específicas da aplicação. Segue alguns quadros típicos.

Você replica para garantir a disponibilidade em momentos de mudança?
Talvez efetuar um failover para um nó hot standby assíncrono em momentos de
menor fluxo transacional seja suficiente. Se houver momento em que o volume de transações zere por mais tempo, até mesmo um warm standby daria conta, só que sem a vantagem de ter um nó separado só para consultas.
O problema é garantir que nenhum dado seja perdido em caso de
desastre? Bom, se absolutamente nenhum dado pode ser perdido, talvez seu sistema seja candidato à replicação síncrona, mas isso pode ter impacto na velocidade de atendimento das transações pelo banco. Ironicamente, se o sincronismo total não impacta sua aplicação, talvez a replicação assíncrona também atenda sem problemas!
Seu objetivo maior é dividir a demanda dos clientes entre vários servidores de forma a atender com mais agilidade? Isso é um trabalho para a replicação bidirecional! Lembrando que em um ambiente centralizado tende a ser rara a necessidade de mais de um servidor de escrita, e não se deve esquecer que o overhead de manutenção tende a ser maior do que nos outros modos de replicação.

É também sempre bom ressaltar a importância de efetuar backups periódicos de seus dados, mantidos apartados de seus sistemas de produção, para recuperação em caso de desastres maiores. A replicação pode ser entendida como um backup online, mas ela não de protege de falhas humanas, como um DROP ou TRUNCATE feitos no momento errado!

Referências
Segue algumas referências sobre replicação com PostgreSQL:

PostgreSQL.org - Chapter 26. High Availability, Load Balancing, and Replication (documentação)
BDR - Documentação (destaque para a seção de monitoração)
PostgreSQL Wiki - Replication, Clustering, and Connection Pooling (compara ferramentas análogas, às mencionadas nesta resposta)
PostgreSQL Wiki - Replicação multimaster
PostgreSQL.org - Chapter 25. Backup and Restore
Comment: Show de bola @nunks.lol , consegui sanar minhas dúvidas com sua explicação, estarei dando uma olhada nas referências que você disponibilizou! Fico agradecido.
Comment: @Marcelolx fico contende de poder ajudar. Provavelmente vou editar essa resposta aos poucos, melhorando aqui e ali, para poder indicar para as pessoas quando me perguntarem sobre isso no trabalho também, haha. Só frisando que tudo o que eu falei é pra PostgreSQL, não conheço as soluções de replicação em MySQL pra poder falar com propriedade.
Comment: Sim, eu também estava a procura de uma solução relacionada ao PostgreSQL...só incluí o MySQL nas tags, para caso alguém conhecer uma solução interessante para o mesmo.

Replicação de banco de dados


SSH keys for utility services on remote production server

Question: For convienience I'd like to have a private SSH key on my remote server.
But doing that creates a vulnerability if the server were hacked.  Same as if I'd hard coded a password, anyone who broke in could take it and use it to access the service it was intended for.
Is there a mechanisim for temporarialy making a SSH key available to the target server in a terminal sesssion ?
I'm guessing there are solutions out there I just dont know about.  Thanks for any help.
Comment: I'm on mobile so just a short hint: the openssh authorized_keys format allow you apply restrictions on what actions are allowed when a specific key pair is used to log on - that mitigates some of the risks of compromised private ssh keys
Answer: This is the answer I was hoping to find.
SSH agent forwarding can be used to make deploying to a server simple. It allows you to use your local SSH keys instead of leaving keys (without passphrases!) sitting on your server.
https://developer.github.com/v3/guides/using-ssh-agent-forwarding/


Há alguma relação entre estes dois elementos do código HTML?

Question: Estou a retirar dados de um site com o Jsoup mas eu não sou muito bom em html. Gostaria de saber se neste site existe alguma relação entre ".lin-area-c2" e ".lin-curso-c3".
Se houver, gostaria de saber como usá-la para colocá-los numa arrayList, por exemplo, já que da maneira que eu estou a fazer primeiro faz extract dos ".lin-area-c2" e depois dos ".lin-curso-c3" (gostaria de fazer sequencialmente).
No geral, extrai um ".lin-area-c2" e depois se após tiver um ".lin-curso-c3", é extraído também.
Obrigado!
Aqui esta o link do site.
Document document = null;

document = Jsoup.connect("http://www.dges.gov.pt/guias/indcurso.asp?letra=E").get();

for(int contador=0;contador<document.select(".lin-area-c2").size();contador++) {
    Log.d("tag",""+ document.select(".lin-area-c2").get(contador).text());
}

for(int contador=0;contador<document.select(".lin-curso-c3").size();contador++){
    Log.d("tag",""+ document.select(".lin-curso-c3").get(contador).text());
}

Answer: O box10 é a categoria do curso, o lin-curso é a linha com os dados do curso e as classes lin-curso-c1, lin-curso-c2, lin-curso-c3, lin-curso-c4 são as colunas com as informações do curso. Ele monta uma tabela utilizando divisores ao invés de usar uma tabela.
Comment: Ha alguma maneira de selecionar selecionar apenas lin-curso-c3 e Lin-area-c2?


Is there a Grouped Product listing type in Drupal Commerce

Question: I have a Magento site I would really like to migrate to Drupal Commerce.  The one must-have feature is Grouped Product.  A grouped product will have a base product from which the product listing will use the photos, description, etc.  The related products will provide their titles, prices, etc. to the product listing.  See the photo for an example.
Can this be done with Drupal Commerce?
Thanks for your time and help!
Answer: Drupal Commerce does differentiate between products and product variations same as other systems, but the feature you're looking for hasn't been ported to Drupal 8 yet. It's easy enough to create a table with individual Add to Cart buttons for the variations in Drupal 8, but to have a single Add to Cart button for all variations on a product page, you'd need this module upgraded for Drupal 8:
https://www.drupal.org/project/commerce_add_to_cart_extras
Answer: It sounds like from the question, and looks like from the photo example that you would like to sell multiple products as a "Set" (see photo) with one sku (see photo). If that's not the case, maybe add more detail regarding your use case.

The "best" option out of the box:

There is not currently a stable bundle module for Drupal Commerce 2. Commerce_product_bundle for Drupal 8 accomplishes the function you want, but the module is not stable, nor under active development or maintenance. I would only install it for testing on a sandbox site, and would be hesitant using it in production in it's current state. commerce_product_set on github was developed because commerce_product_bundles was not production ready/ maintained.
So unfortunately, nothing is ready for this out of the box, so whatever choice you make will likely require some development.
Commerce_bundle for Drupal 7 is actually very dependable as a dev module, but I'm guessing you don't want to start with Drupal 7 at this point.

Another suggestion:

There is also product add on (pado) module for Drupal 8, but the use case is a little different than your example.
Sorry there is not better news.
Comment: You're right, it's a little ambiguous from just the information that was provided, since it doesn't show any behavior of the products in the cart itself.
Comment: This isn't really a product bundle scenario. This is more a question of a bulk add to cart for individual products.
Comment: From what was provided in the question and in the photo, I thought he wanted to sell what he called "groups" of products as a "Set" with a single SKU (see picture on both). Commerce product bundles (Though not stable) can of course handle the use case of adding multiple products at different quantities as a "Set" sold under one new sku "group". Not sure where the downvote came from :) The closest thing Drupal 8 has to offer on this out for the box that I am aware of is CPB.


How to hide the submit button on a node add/edit form page within which a entity reference select list has no valid option?

Question: Registration content type has a required entity reference field. The widget of this field is a select list, the options are populated with a views entity reference display output. I want to hide(unset) the submit button if the views entity reference display returns no value.
I've asked a question here for reference, I'm suggested to post a new question.
Answer: You can do this by using hook form FORM ID alter .
Once hooked in you find the $form item for the drop down list.  It'll be somewhere like
$form['field_my_entity_ref']['und']['#options']
So you should be able to make a check on the values in that array and if there are none then make the Submit button disabled .  My guess is
<code>if ( count($form['field_my_entity_ref']['und']['#options']) < 1 ) {

   $form['#submit']['#disabled'] == TRUE;
 }
</code>
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#disabled
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7.x


How does this lick work harmonically?

Question:

 Here is the lick (3:38 - 3:39).
He is playing it over a F minor chord. The key of the song is Ab. It looks like he just playing extentions of the F minor chord. What is a better way to explain this?
Comment: It would be a tad easier if you transcribed the part in question
Comment: sorry. the lick is Bb and Eb, C and F, Eb and Ab, F and Bb.
Comment: Are you asking about the part at 3:38 - 3:39?
Comment: yes thats the part im talking about
Answer: He's playing a pentatonic scale pattern, harmonized in fourths, which is a common device in jazz. Open fourths give an ambiguous sense of harmony even though, in this case, he never actually leaves the home key.
Ab Major = Ab Bb C Db Eb F G and an F minor chord, F Ab C, is the vi chord, consisting entirely of notes within the Ab Major scale.
The primary (upper) notes of the solo are Eb F Ab Bb C Eb F Ab, which is an F minor pentatonic (also Ab major pentatonic) scale, starting on Eb. By using the pentatonic scale, both E natural (the leading tone in F minor) and G natural (the leading tone in Ab major) are avoided, giving a sense of tonal ambiguity even though all of the pitches are within the key/scale. This is enhanced by starting on Eb rather than F or Ab.
Harmonizing the scale at the fourth below gives Bb C Eb F *Ab* Bb C Eb. Note that the pattern breaks at the Ab. This keeps the harmony within the pentatonic scale and avoids the G natural (Ab leading tone). This use of fourths also reinforces the tonal ambiguity while staying within the key.
This is a basic example of "quartal harmony".
The pianist McCoy Tyner, among others, is particularly well known for using quartal chord voicings. A clear example can be heard in the opening vamp on "My Favorite Things" from the album Coltrane: Live at the Half Note.
Answer: He plays the following notes (disregard the rhythm values):
X: 1
K: C
L: 1/4
[_B,_E] [CF] [_E_A] [F_B] [_Ac] | [_B_e] [cf] [_e_a] [f_b] |

It is an (almost) constant interval moving up over the notes of F minor pentatonic (F Ab Bb C Eb). However, in this context I wouldn't call it "extension", but rather a passage, transition.

How does this lick work harmonically?


Selenium not able to identify the newly opened window in the IE browser

Question: I am not able to identify a newly opened window in my application.
After using driver.get("my app url") when I try to click on any object, I am getting  org.openqa.selenium.NoSuchWindowException: Unable to find element on closed window.
I replicated the same issue on flipkart website using the below code :
System.setProperty("webdriver.ie.driver","path to IEDriverServer.exe);

WebDriver driver = new InternetExplorerDriver();

driver.get("https://www.flipkart.com");

Thread.sleep(10000); // just for sample

driver.findElement(By.linkText("24x7 Customer Care")).click();

But when I run it I am getting NoSuchWindowException.
It is working fine in chrome and Firefox browser.
Selenium Version =2.53.0 ,
OS= Windows7
I tried by adding ignoreProtectedMode and IntroduceFlakinessByIgnoringSecurityDomains capabilities as well but even that is working.
Kindly assist.
Comment: Does `IE` browser session actually opens?
Comment: yes do u see any IE window get opened by selenium
Comment: System.setProperty("webdriver.ie.driver", "path to IEdriverServer.exe" );
    WebDriver driver =new InternetExplorerDriver();
  driver.get("https://www.flipkart.com");
  do {
   System.out.println("window size" +driver.getWindowHandles().size());
  }while(driver.getWindowHandles().size()!=0);
  System.out.println("Window size after loop ends " +driver.getWindowHandles().size());                Output is :window size1
window size0
Window size after loop ends 0
Comment: Seems like window gets opened and then it is closed automatically...
Comment: can you do a fresh installation of your IE,may be that helps
Comment: I already re installed IE.. I checked in both IE 9 and IE 11 . It is not working.   This issue is happening for almost all the websites. I tried on google.com as well
Answer: Use this it works for you
System.setProperty("webdriver.ie.driver", "path to IEdriverServer.exe" );
WebDriver driver =new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("https://www.flipkart.com");

Comment: Download latest IEDriver


How is Charter Spectrum doing this in my browser?

Question: I know this is not a programming question and it could be open ended. However, I feel like I can get this most help here.
Is the image below cross-site scripting or a result of net-neutrality? If so, what can do to get them out of my browser?
So far I have noticed this on my computer, my wife's computer which has better security on it, and it is happening to other people I know.
It happens randomly in my google chrome browser. I have not seen it in FF or Edge but I don't use those much. It will also occur on different websites. The copyright is 2016 but it is happening now (2019). I would think this was an annoying ad but it has my name in it, and it occurs when I have to pay the bill. Also just another observation, it seems to happen on HTTP sites, not HTTPS but I could be wrong.
Any information to get Charter out would be helpful. Please don't say use TOR
Answer: It's probably DNS hijacking.
To mitigate, you could try:

Not using your ISP's DNS servers. Try OpenDNS or similar.
DNS over HTTPS
The HTTPS Everywhere browser extension, which might help reduce it
a VPN
Comment: Thank you, I will have to look into my home network and apply the changes. You gave me a good list to start from


How can I create a PXE boot image that runs a single executable on startup?

Question: I'm in the process of setting up a compute cluster with the intent of using it for some parallel computing experiments. I have a single executable which I'd like to run on this cluster.
Due to operational constraints on said cluster I can only deploy this executable as a PXE boot image. Unfortunately, the only "ready-made" images I've been able to find are installation ones intended to install a particular distro. They don't particularly appear easy to modify.
Can someone perhaps provide some pointers as to how I could go about creating a pxelinux image that loads the linux kernel and subsequently run an executable?
Comment: Is your executable its own operating system?!
Comment: @MichaelHampton No, it's not. It's a program I compiled and have all required shared libraries for, so it should run on any linux distro.
Comment: Well, then you can just PXE boot your favorite Linux distro.
Comment: @MichaelHampton I'm sorry if it's a dumb question, but how do I include my program in the files being distributed to the machines, and subsequently have the machines execute it once they have finished booting?
Comment: Instead of booting the kernel/initrd for the _installer_, you boot the kernel/initrd for an _installed system_. Your distro's documentation should explain how to install the OS for PXE booting and root filesystem on the network.
Comment: @MichaelHampton Do you have an example of such documentation for a particular distro? The only ones I've been able to find talk about the installer.
Comment: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/storage_administration_guide/ch-disklesssystems
Answer: Using ubuntu-18-x86_64-initrd.gz:
wget http://archive.ubuntu.com/ubuntu/dists/bionic/main/installer-amd64/current/images/netboot/ubuntu-installer/amd64/initrd.gz
gzip -d initrd.gz
mkdir image
cd image
cpio -idmv < ../initrd

Now copy your executable, required shared libraries, and other files needed by your executable into image/. Edit etc/inittab. You probably want to remove ::sysinit:. Change ::respawn: to be an invocation of your executable.
find . -print0 | cpio --null -ov --format=newc | gzip -9 > ../initrd-bionic-foo.gz

Copy initrd-bionic-foo.gz to your tftp server. Sample pxelinux.cfg entry:
default foo
label foo
kernel boot/Ubuntu-18.04-x86_64-linux
append initrd=boot/initrd-bionic-foo.gz


How can create validation for single control's value required from multiple control in angularjs(1.*.*)

Question: i.e, I have four text boxes if I enter a value in any text box out of all text box, it should be allowed to submit otherwise throw an error,"Value is Required",
It is possible using angularjs directive.
Comment: Welcome to SO. Please read this [how to ask](https://stackoverflow.com/help/how-to-ask). Your current question will likely attract downvotes becase it shows no research effort and is too broad for q&a format.
Comment: You can use the `ng-required` directive to conditionally make fields required. It can get pretty messy in markup if there are a lot of fields, but you can always write a controller function to keep the logic in one place and make it more readable. Just realize that it will get called on every digest cycle (I've never had an issue, but then I've never had my conditional required fields be dependent on more than one or two other fields).
Comment: Hello, I need to create one form which contains multiple(N) control which is static.I want to add validation for that controls.Validation should be like If we touch any of one control then every control should be mandatory.and if not then no validation should be fire
Answer: You can check out the angularjs documentation here:
https://docs.angularjs.org/api/ng/directive/input
For example, if you want to validate text boxes, you can have something like
<code><form name="validationform" ng-submit="submit()">
    <input type="text" name="value1" ng-model="textinputvalue" ng-required>
    <input type="submit" id="submit" value="Submit" />
</form>
</code>
(and similarly for the other input boxes)
If you are looking to set a custom validation, there is a really good answer here that you can look at: How to add custom validation to an AngularJS form?
Comment: Hello, I need to create one form which contains multiple(N) control which is static.I want to add validation for that controls.Validation should be like If we touch any of one control then every control should be mandatory.and if not then no validation should be fire


PHP detect and remove unnecessary cent of price

Question: For invoicing I want to determine if my total amount has an unnecessary cent. e.g. $5.01 or $5.51. If it detects the cent then I run an if statement to remove the cent: minus 0.01
eg.
Change 30.51 to 0.01 and give a warning message
and also
30.51 to 0.51
and also
30.51 to 1
Both come from a POST, so they are both PHP strings.
but no worries - i got it to work now thanks to dmayo
$pieces = explode(".", $TotalAmt);
echo "
p1:".$pieces[1]; // piece2
$p1 = $pieces[1];
$spl1 = str_split($p1);
$TAmttmp = 0;
//echo "
sp11:".$spl1; // error convert array to string
$TAmttmp = $spl1[0];
echo "
TAmttmp: with useless cent".$TAmttmp;
echo "
IT:".$IT;
if ($TAmttmp == 0.01) //so if there is 1 cent subtract the useless cent.
$TAmt = $TAmt - 0.01;
echo "
TAmt: with useless cent".$TAmt;
echo "
TAmt: without useless cent".$TAmt;

Comment: What are the logics behind these conversions?
Comment: Hello on SO. What are you trying?
Comment: For invoicing I want to determine if my total amount has an unnecessary cent. e.g. $5.01 or $5.51. If it detects the cent then I run an if statement to remove the cent: minus 0.01
Answer: @Gumbo is right, we need to know the logic behind your conversions to provide a precise answer.
You could do an explode:
$var = explode('.',$_POST['val']);
$digits = $var[1]; // this will give you the digits after the decimal point

Now you can do what you need based on your logic.
You could also you use a substr() where you find the decimal point (is it always three places from the right?) and then grab the substring.
Not sure which would be more efficient.
Comment: Ja thanks I liked the explode idea, i tried it and it gave me converting array to to string error when I conveted the last digit to a number, but then i finally figured it out:
Comment: $pieces = explode(".", $TotalAmt);
//echo "p0:".$pieces[0]; // piece1
echo "p1:".$pieces[1]; // piece2
$p1 = $pieces[1];
$spl1 = str_split($p1);
$TAmttmp = 0;
//echo "sp11:".$spl1; // error convert array to string
$TAmttmp = $spl1[0];

echo "TAmttmp: with useless cent".$TAmttmp;
echo "IT:".$IT;

if ($TAmttmp  == 0.01) //so if there is 1 cent subtract the useless cent.
$TAmt = $TAmt - 0.01;
echo "TAmt: with useless cent".$TAmt;
echo "TAmt: without useless cent".$TAmt;
Answer: I don't know exactly what you want, but perhaps that helps:
$nr = "30.51";

echo round($nr - floor($nr), 2); // 0.51
echo round(($nr * 10 - floor($nr * 10)) / 10, 2); // 0.01
echo round(($nr * 10 - floor($nr * 10)) * 10); // 1


real analysis -functional equation

Question: Be $f:\mathbb R^ +\mapsto\mathbb R$ a function that satisfies the following conditions:
a)$ f(f(f(x)))+2x=f(3x)$ for every $x\gt 0$;
b)  $\lim_{x \to \infty} (f(x)-x)=0$.
This was proposed by Gabriel Dospinescu  at a romanian competitions about a decade ago. No idea how to approach it. Thank you!
Comment: @DanLeonte Just as a matter of notation, the symbol $\mapsto$ is usually (as a standard) used for discussing where an element is sent.  For example, we might say the element $x$ is sent to $x^{2}$ by writing $x \mapsto x^{2}$.  But when writing a function's domain and codomain, we use a regular arrow (code: $\text{ \to }$).  So, it would look like $f: \Bbb R^{+} \to \Bbb R^{+}$, with code $\text{f: \Bbb R^{+} \to \Bbb R^{+}}$.
Comment: What is the question? To determine every possible $f$ ?
Comment: yes. i forgot to mention:D thanks.
Answer: The function must be defined as follow $f:\mathbb{R^+}\to\mathbb{R^+}$,otherwise the functional equation can not be true because it involves $f(f(x))$
we know that if replacing $x$ by $\frac{x}{3}$ we obtain :
$$f(x)=\frac{2}{3}x+f(f(f(\frac{x}{3})))\geq\frac{2}{3}x$$
now let $u_0=\frac{2}{3}$ assuming that $f(x)\geq u_nx$ one can prove that:
$$f(x)\geq u_{n+1}x$$
 with $u_{n+1}=\frac{u_n^3+2}{3}$ and because $u_n \rightarrow 1$  when $n$ tends to infinity we conclude that $$f(x)\geq x$$ for evry positive real $x$.
Now for any real $a$ let $f(a)=a+t$ then $(3a)\geq 3a+t$ and by induction $f(3^na)\geq 3^na+t$ and using the second condition we have $t=0$
Conclusion The only function verifying the two conditions is the identity.
Comment: in fact $f(x)$ must be positive for every $x$ otherwise the functional equation will not have any sense because there is $f(f(x))$
Comment: $f(x)≥2/3x$ is true only for high-enough  x!
Comment: for every positive $ x>0$We have $f(x)=\frac{2}{3}x+f(f(f(\frac{x}{3})))\geq \frac{2}{3}x$ so why for hight enought x?, hmmmm you changed the definition of $f$!!!!
Comment: yes Elaqqad sory for editing the question so late and thankyou so much for your effort:D
Comment: @DanLeonte my answer **is correct** and because you can not edit the question like you did in fact the function **must be defind as $f:\mathbb{R}^+\to\mathbb{R}^+$ ,** otherwise the term $f(f(f(x)))$ will have nosense!!!!!!!!, if you're interested in the answer you can read mine if you're interested in something else $\cdots$
Comment: Elaqqad there must be some missunderstanding=)) i thanked for your effort because i really appreciated that you had helpeld me understand this problem by providing me with the solution. I now realise that it may have sound a bit ironic or sarcastic, but i was really not any of these two:D. So, thankyou again!!!!
Comment: ok  I understand so if you have any problem in the answer just ask!
Comment: @DanLeonte: If you're satisfied with the answer that you got, please don't forget to accept it (and also upvote it if you liked it).

real analysis -functional equation


What does it mean $X^{-2}$ in matrix notation?

Question: I have the following equation:
$$GCV(\lambda)=\frac{ n\times\text{trace}\{Y'[I-S_{\phi,\lambda}]^{-2}Y\} }{\{\text{trace}[I-S_{\phi,\lambda}]\}^2}$$
I know $I-S_{\phi,\lambda}$ is a matrix what is the power to the -2 supposed to mean? is it the power of each element?
Comment: I would think it's inverse squared.
Answer: I think the natural interpretation of the notation $X^{-2}$ would be the inverse squared.


Sorting by two columns in pandas series

Question: Putting a slight variation on a question I previously asked. I managed to get a solution to sorting values by a particular column in my pandas series. However, the problem is that sorting purely by time doesn't allow me to factor in different dates in which the time occurred. I understand that I could potentially hard code the order and use .loc to apply the order but wanted to find out if there was a simpler solution to sort primarily by week (earliest week first) and by time (0-23hours for each week).
Here is a sample of the dataframe I have again:
weeknum   time_hour
16-22Jun  0.0           5
2-8Jun    0.0           3
23-29Jun  0.0          11
9-15Jun   0.0           3
16-22Jun  1.0           3
2-8Jun    1.0           6
23-29Jun  1.0           3
9-15Jun   1.0           8
16-22Jun  2.0           3
2-8Jun    2.0           6
23-29Jun  2.0           3
16-22Jun  3.0           4
2-8Jun    3.0           2
23-29Jun  3.0           3
9-15Jun   3.0           4
16-22Jun  4.0           2
2-8Jun    4.0           7
23-29Jun  4.0           1
9-15Jun   4.0           7
16-22Jun  5.0           2
2-8Jun    5.0           9
23-29Jun  5.0           9
9-15Jun   5.0          12
16-22Jun  6.0           5
2-8Jun    6.0          12
23-29Jun  6.0           6
9-15Jun   6.0          14
16-22Jun  7.0          12
2-8Jun    7.0          17
23-29Jun  7.0          19

This is my code:
merged_clean.groupby('weeknum')['time_hour'].value_counts().sort_index(level=['time_hour'])

Comment: There are values only for June or also for another months?
Comment: @jezrael only June
Comment: Is your `weeknum ` column of type string? Have you already thought about using `df[your_datecolumn].dt.week`? (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.week.html). Maybe this would ease things a little, at least, if the ordering of the weeks is an issue for you.
Answer: Use function sorted by multiple keys for sorting MultiIndex with convert first number before - and for change order use DataFrame.reindex:
s = merged_clean.groupby('weeknum')['time_hour'].value_counts()
idx = sorted(s.index, key = lambda x: (int(x[0].split('-')[0]), x[1]))
s = s.reindex(idx)

print (s)
weeknum   time_hour
2-8Jun    0.0           3
          1.0           6
          2.0           6
          3.0           2
          4.0           7
          5.0           9
          6.0          12
          7.0          17
9-15Jun   0.0           3
          1.0           8
          3.0           4
          4.0           7
          5.0          12
          6.0          14
16-22Jun  0.0           5
          1.0           3
          2.0           3
          3.0           4
          4.0           2
          5.0           2
          6.0           5
          7.0          12
23-29Jun  0.0          11
          1.0           3
          2.0           3
          3.0           3
          4.0           1
          5.0           9
          6.0           6
          7.0          19
Name: a, dtype: int64

Sorting by two columns in pandas series


What is the difference between a loss function and an error function?

Question: Is the term "loss" synonymous with "error"? Is there a difference in definition?
Also, what is the origin of the term "loss"?
NB: The error function mentioned here is not to be confused with normal error.
Comment: My question is related to this one, but I didn't find it satisfactory https://stats.stackexchange.com/questions/179026/objective-function-cost-function-loss-function-are-they-the-same-thing
Comment: It would be helpful for us if you could indicate what you find unsatisfactory about the related thread.
Comment: It does not address the error function in particular and focuses mainly on the types of loss
Answer: In the context of a predictive or inferential model, the term "error" generally refers to the deviation from an actual value by a prediction or expectation of that value.  It is determined entirely by the prediction mechanism and the actual behaviour of the quantities under observation.  The "loss" is a quantified measure of how bad it is to get an error of a particular size/direction, which is affected by the negative consequences that accrue for inaccurate prediction.
An error function measures the deviation of an observable value from a prediction, whereas a loss function operates on the error to quantify the negative consequence of an error.  For example, in some contexts it might be reasonable to posit that there is squared error loss, where the negative consequence of an error is quantified as being proportional to the square of the error.  In other contexts we might be more negatively affected by an error in a particular direction (e.g., false positive vs. false negative) and therefore we might adopt a non-symmetric loss function.
The error function is a purely statistical object, whereas the loss function is a decision-theoretic object that we are bringing in to quantify the negative consequences of error.  The latter is used in decision theory and economics (usually through its opposite - a cardinal utility function).

An example: You are a criminal racketeer running an illegal betting parlour for the Mob.  Each week you have to pay 50% of the profits to the Mob boss, but since you run the place, the boss relies on you to give a true accounting of the profits.  If you have a good week you might be able to stiff him out of some dough by underrepresenting your profit, but if you underpay the boss, relative to what he suspects is the real profit, you're a dead man.  So you want to predict how much he expects to get, and pay accordingly.  Ideally you will give him exactly what he is expecting, and keep the rest, but you could potentially make a prediction error, and pay him too much, or (yikes!) too little.
You have a good week and earn $\pi = \$40,000$ in profit, so the boss is owed $\tfrac{1}{2} \pi = \$20,000$.  He doesn't know what a good week you had, so his true expectation of his share is only $\theta = \$15,000$ (unknown to you).  You decide to pay him $\hat{\theta}$.  Then your error function is:
$$\text{Error}(\hat{\theta}, \theta) = \hat{\theta} - \theta ,$$
and (if we assume that loss is linear in money) your loss function is:
$$\text{Loss}(\hat{\theta}, \theta) = \begin{cases}
\infty & & \text{if } \hat{\theta} < \theta \quad \text{(sleep wit' da fishes)} \\[6pt]
\hat{\theta} - \pi & & \text{if } \hat{\theta} \geqslant \theta \quad \text{(live to spend another week)} \\
\end{cases} $$
This is an example of an asymmetric loss function (solution discussed in the comments below) which differs substantially from the error function.  The asymmetric nature of the loss function in this case stresses the catastrophic outcome in the case where there is underestimation of the unknown parameter.
Comment: This new example seems to come from personal experience...
Comment: The example is terrific.
Comment: Very clear, thank you for your response. I will accept an answer after others have a chance.
Comment: There seem to be differing views on the example, so for the moment I'll leave it as is, but I am open to an edit if it proves to be unpopular.  Having said that, the purpose in the present context is to show the OP an example of a highly asymmetric loss function, to stress the difference with the error function.  The fact that the optimal solution is to give the boss all the money does not make the example "meaningless" - it just means that the optimal solution is to give the boss all the money.
Comment: While the example is fun an infinite loss is pretty meaningless. The optimal solution in this case would always be to give your boss all of the money you earned. I suggest changing this for the answer to be truly excellent.
Comment: @AlexbGoode If your objective is "minimise E(loss)", then yes, that would be the optimal solution. But minimising expected loss isn't always the objective.


What is the standard closed hi hat hit notation?

Question: So far I've been able to find standard notation for the hi hat hit and hi hat pedal hit but it its not clear to me what is the closed hi hat notation. As i understand, normal hi hat hit is on the G2 spot, while the hi hat played with foot is a circled x sign on the D1 spot. Any help?
Answer: Well, normal hihat IS closed hihat, ain't it?
Google tells me that an X note sitting on top staff line (that'd be G5 for a piano player) is normal hihat (closed).  If you want to SPECIFICALLY state that it's closed (not open) put a + on top of it.  Open having an o on top of the X note.
according to page 3 of http://web.mit.edu/merolish/Public/drums.pdf
Answer: I don't think the notation standard is settled on that. Every genre has a different shortcut but Stephen's +, o detail is pretty common.
Also putting a legend is a widely used solution. The main reason for the ambiguity is that there are too many percussive details to be fitted on the staff. Especially if you have lots of toms to transcribe and all the different types of splashes, crashes and chinas (where we decided to put a chinese character for cymbal to communicate) makes it pretty hard to read after all details are included.
The drumset notation is usually an approximation of the actual sound. Unlike other instruments, it's very hard to reproduce the exact replica of the transcribed music without extrapolating what it might have sounded like.


How to use form API to edit sub form that is added to user_register_form

Question: I need to alter a Redhen Contact form when it is attached to the user registration form.  More generically, I need to alter a sub form.  The form is added to user_register_form() via hook_form_FORM_ID_alter() in rendhen_contact.module:1029.  (I don't think this is specific to Redhen's implementation; I'm just providing this as a reference point.)
The first issue I encountered was that the hook implementation in redhen_contact.module hadn't occurred when my hook was called.  In a custom module, I used hook_module_implements_alter() to resolve that (see screenshot at bottom for kpr()).  With that I'm still unable to alter, for example, the #title attribute of field_agency_interest.  Even if I do $form['redhen_contact]['form']['field_agency_interest']['und']['#title'] or ...['und'][0]['title'] it doesn't change.
I tried using $form['#after_build'][] = 'module_callback_name' but I can't edit the sub form elements.

How can I alter a sub form added to a form?
Answer: You probably forgot to reference the $form variable ("&$form").
The alternative to #after_build would be #pre_render, which misses $form_state but should generally be preferred for changes that only affect the rendering of a form.
Comment: Thanks @ciss.  The callbacks for `#after_build` and `#pre_render` return the element (or form) so referencing isn't used here.  `#pre_render` doesn't work either though.  I am able to change the title for `$form['redhen_contact']` (which is a fieldset) but I can't seem to do anything with the fields.
Comment: I was referring to hook_form_alter(). A common mistake is to forget the argument reference, which makes changes to the $form array ineffective, including any added callbacks.
Answer: I came across this: https://drupal.stackexchange.com/a/129617/7595, which identifies that you have to dig a bit deeper into the element; specifically the ['value'] element.
So, for editing a subform this will work:
function hook_form_alter(&$form, &$form_state, $form_id) {
  $form['redhen_contact']['form']['field_agency_interest']['#pre_render'][] = '_field_agency_interest_pre_render';
}
function _field_agency_interest_pre_render($element) {
  $element[$element['#language']][0]['value']['#description'] = 'Test';

  return $element;
}

I'll note again that I'm using #pre_render because the RedHen module hook was being called after this one and this ensures everything has been added to the form prior to making changes.


Dúvidas sobre pusher do vue js

Question: Estou seguindo um tutorial que tem que digitar o seguinte comando para criar um projeto vue:
Ele criar uma pasta chamada music-db, em seguida ele digita esse comando estando dentro da pasta;
vue init webpack frondend
Ao digitar esse comando é criado somente uma pasta com o nome de frondend, e ao entrar dentro da pasta frondend existe outras pastas.
ai depois em seguida é digitado esse comando abaixo;
yarn install
E em seguida digita esse comando abaixo;
yarn add vuex vuex-router-sync vue-router axios animate.css google-material-color material-design-icons laravel-echo pusher-js
Depois desses comandos ele digita novamente esse comando:
yarn install
E em seguida ele sai da pasta frondend e entra em uma pasta com o nome API que está dentro da pasta music-db, isso no tutorial, porém essa pasta não foi criada no meu projeto.
Anteriormente quando eu executei o comando
vue init webpack frondend
Ele tinha somente criado somente  a pasta frondend e nada mais, agora dentro da pasta music-db tem uma pasta API.
O que tem dentro da pasta api?
tem uma arquivos chamado .env
Lá ele pega uma senha  é uma num arquivo como esse abaixo;

Ele pega essa senha do pusher_app_key e coloca dentro do projeto vue.
Qual é minha dúvida?

Como faço para criar essa pasta API dentro da pasta music-db?
Será que errei em algum comando no tutorial acima?
E para que serve o Pusher num projeto vue?

As perguntas parecem muito idiotas, mas é porque eu ainda estou apredendo e não tem ninguém para pedir ajuda sobre isso.
Answer: Sou novo no StackOverflow, e não sei se entendi muito bem, mas tentarei ajudar.

Como faço para criar essa pasta API dentro da pasta music-db?

Resposta: Provavelmente o tutorial é referente a uma aplicação em Vuejs2 e Laravel, no caso há duas pastas separadas, a "frondend" que é a aplicação front-end em Vuejs2, e a pasta "api" que é a pasta do back-end em Laravel. Não consegui verificar a criação da pasta api em realmente em nenhum momento do seu código. Se o tutorial for de vuejs, provavelmente ele está ensinando com o foco no front-end, e não está de fato explicando a criação e funcionamento do back-end. Se desejar criar um back-end do início, supondo que você já possui algumas] ferramentas necessárias instaladas, como o php 7.1, um editor que possua extensões compatíveis com Vuejs2 e Laravel, etc, citarei as com o foco no Laravel. Primeiramente é necessário o composer se não estiver ele instalado, pode verificar em getcomposer (caso não conheça sobre o composer, ele é um gerenciador de dependências do php, procure saber mais). Em seguida, vá na documentação do laravel e selecione a melhor maneira de criação de um novo projeto, recomendo pelo composer com o comando composer create-project --prefer-dist laravel/laravel api (o último parâmetro é o nome da pasta). Feito isso, para executar a aplicação em um servidor local utilize o comando php artisan serve. Ele executará um servidor local na porta 8000. Após isto, deverá verificar sobre o que exatamente o front-end está consumindo da API, para você implementar todo o processo. O fluxo básico de um tutorial geralmente é criar um model utilizando o comando php artisan make:model NomeDaClasse -m (o "-m" é para criar a migration que irá se comunicar com banco de dados). Uma rota no arquivo api.php na pasta routes. Finalmente, crie um controller php artisan make:controller PhotoController --resource (o "--resource" o laravel já disponibiliza todo o sistema de rotas de get, post, put e delete com apenas uma linha). Agora é só implementar de acordo com o front-end. Tudo pode ser encontrado na documentação do laravel.

Será que errei em algum comando no tutorial acima?

Resposta: Não tenho como ter certeza absoluta mas creio que não. Um comando contendo vue init webpack frondend apenas inicializa um projeto Vuejs2, e não arquivos de um API em Laravel. No caso, o .env é o local onde é armazenado todas as variáveis de ambiente. Ele está pegando a senha para provavelmente sincronizar os eventos do pusher e possuir acesso em real-time da aplicação da API com o Vuejs2 (front-end).

E para que serve o Pusher num projeto vue?

Resposta: Sinceramente, nunca utilizei, mas tentarei responder com base no pouco conhecimento que possuo. O Pusher no tutorial pode ser utilizado junto ao laravel-echo, que é uma biblioteca para realizar eventos em uma conexão de WebSocket. No caso do Vuejs2, pode ser necessário a sincronização da chave, para sincronizar em real-time (live-update) as telas do Vuejs2, ou seja, quando algum dado está atualizado no servidor, uma mensagem é enviada para conexão do WebSocket a fim de ser tratada pelo front-end. Basicamente é "disparar" eventos, onde você consegue compartilhar o mesmo nome do evento disparado no Laravel, do servidor, com sua aplicação cliente (front-end) em Vuejs2 , ou qualquer outra aplicação em javascript.
Espero ter ajudado.

Dúvidas sobre pusher do vue js


how does a probability density function of a continuous random variable is obtained(Real life or theoretically)?

Question: For example, if I want to find out or the probability how much it will rain tomorrow based off a PDF, how is that PDF is obtained?
if I want to find out or the probability how much signal may fade in a wireless channel based on a PDF, how is that PDF is obtained?
if I want to find out or the probability how much size is the size of an asteroid that may enter earth based on a PDF, how is that PDF is obtained?
How Continous Random variable that can take any number from -infinity to infinity, how we can quantize this and from a PDF just like PDF of a discrete random variable like a fair or unfair die!
Answer: I'm not sure I've got the question right, but if you're asking what I think you're asking, the basic answer is that we assume a process model, and based on that model, we can derive a PDF.
Keep in mind that this is also true of the probability distribution of a discrete random variable such as the result of a die roll: If we say that a die is fair, this is an assumption we make in order to assert the distribution
$$
p_k = \frac{1}{6} \qquad 1 \leq k \leq 6
$$
and if we say that it's unfair, in such and such a way, that's an assumption we make in order to assert a different distribution.  If we're talking about a real physical die, then we can make experiments (roll the die as many times as we like), but even so, we cannot obtain the "true" ideal distribution of the die, since we cannot make an infinite number of experiments.
This is no less a problem than it is with estimating the interarrival distribution of buses at a bus stop.  What often happens is that we conduct experiments, sampling the random variable in question, until we have enough data to propose a model distribution.  We might say that the distribution is Weibull, with such and such parameters.  We can then conduct statistical tests to see how well further measured data matches that distribution, possibly resulting in a refinement of the model, and further tests.
At some point, however, we declare our satisfaction with the model, and use the distribution for whatever our purpose is, such as predicting the expected number of people waiting at the bus stop.  At no point do we have a proof that our model is correct (in the same sense that we can prove a geometrical theorem), but it is sufficient for our needs.


Can someone implement LVM on an existing single-hard disk system?

Question: I am using SuSE Linux (10) and I am considering expanding the available disk, without resizing an existing partition (which is not easy to do on a VM). Instead, I want to create another virtual disk, and add it in a new LVM volume, which would include the existing disk, and this new one, in a seamless single mount point.
We are using VMware vServer 4, under Lab Manager and Virtual Centre. Does SuSE support LVM in version 10 ?
Thanks :-)
Comment: Clarification — do you want to do this "live", while maintaining the contents of your existing disk?
Answer: If the current virtual disk is not on LVM than you cannot do this easily. In this case I would create the new desired situation (including LVM) next to the current disk and move the current data over during planned downtime. There is no easy way to do this live.
For scenarios just like this I always put LVM on my virtual disks, even if I don't expect future growth.
Answer: Yes.
SuSE 10 should have support for LVM. Install the appropriate packages.
You should always use LVM, even if you only have one disk. It makes scenarios like this one trivial.
Answer: Why is it not easy to resize a partition?
You can alway resize the last partiton of a disk:
Resize the disk, delete the last partiton and recreate it with the same starting cylinder. Then put the new end cylinder to the end of disk.
If you have a PV on that partition: pvresize
If you have a direct FS on that partion: resize the filesystem afterwards.
But what you want to do is even simpler to accomplish. It sounds as if you already got an LV located in a VG consisting of a PV which in turn is a partion.
So create your new disk, partition it with one lvm-partition, use that partiton as new PV (pvcreate) and add that PV to your existing VG (vgetend). After that you can resize your LV using the addidional PV.


How to handle BatchNorm in the last layers of a deep learning model?

Question: I am creating a neural network using batchnorm as a regularization method to enable deep models and prevent overfitting.
I understand that batchnorming supresses the internal covariance shift introduced by randomly chosen minibatches, so it generally makes sense to add it to every layer in the model. However, the batchnorm also introduces noise into the training data, which has a particularly heavy effect on model output in the last few layers of the model.
How exactly should I handle the batchnorm at the end of my model? It seems intuitive that the last layer should not be batchnormed, as this would reduce the degrees of freedom for the output of the model and shift the outputs uncontrollably. But what about the penultimate layer and those before? Would it make sense to "lighten" the effects of the minibatch for example by reducing its impact gradually? Or is it better to just completely leave it out after some layer?
Answer: Based on a bit of research, it seems like this is still not a settled science.
The resnet implementation in Pytorch includes a batch normalization layer for every layer until the very last pooling and FC layer. This appears to be standard at least among most resnets I am familiar with - if not simply because designing the blocks in this way is easier rather than a bespoke definition for each block (and has fewer degrees of freedom to tune).
Based on some other threads I was able to find, it appears that in some other applications (such as GANs), they found value in removing the BN from layers closest to the "raw image" which would correspond to the first layers as well as removing from the front and the end. This seems generally atypical in the implementations I have seen.
My recommendation would be to try to experiment with some removal of the batch normalization if you feel that you have the time, but if not, go with the standard approach of BN up to the end.


Show $F \otimes_{\mathbb{Q}} F$ is isomorphic to $F \times F(\zeta_3)$, where $F = \mathbb{Q}(\sqrt[3]{2})$

Question: I have tried a few maps but none of them worked. Further since we are tensoring over $\mathbb{Q}$, $F \otimes_{\mathbb{Q}} F$ and $F \times F(\zeta_3)$ do not appear to have the same dimensions.
Answer: They actually DO have same dimension over $\mathbb{Q}$ (since $3^2=3+6$).
Note that, as $F$-algebras, we have $$F\otimes_\mathbb{Q} F\simeq \mathbb{Q}[X]/(X^3-2)\otimes F\simeq F[X]/(X^3-2)\simeq F[X]/(X-\alpha)\times F[X]/(X^2 +\alpha X+ \alpha^2),$$ where $\alpha=\sqrt[3]{2}$, hence $F\otimes F\simeq_\mathbb{Q} F\times F[X]/(X^2 +\alpha X+ \alpha^2)$.
Now the map $X\mapsto \alpha^{-1}X$ yields an isomorphism of $F$-algebras $F[X]/(X^2 +\alpha X+ \alpha^2)\simeq F[X]/(X^2 +X+ 1)$, and we are done since this last quotient is $F$-isomorphic to $F(\zeta_3)$.
Details are left to you as an exercise.


Marker Detection with Area Learning

Question: I want to use Marker Detection after detecting an area with Area Learning, but I can't find a way to do this. I have tried to merge the Google Tango SDK examples provided for Marker Detection and Area Learning but after localizing the area, it doesn't find the Marker Images provided by them. Is there a way to solve this "Marker Detection - Area Learning" issue, or a better way to do this?
Answer: Are you using Unity SDK? I have merged them and it works without loading ADF [new area learning mode]. Make sure to enable video overlay [Texture and raw bytes] and register for the event.
VideoOverlayListener.RegisterOnTangoImageAvailable(this.OnTangoImageAvailableEventHandler);

Marker Detection with Area Learning


Tráfego de usuários implica no valor mensal?

Question: Publiquei uma aplicação no Azure, criei um grupo de recursos com um plano, que por exemplo deu 50 dólares/mês.
Esse valor é independente de quantidades de acesso e tráfego? Se 1000 ou 100000 usuário acessam por dia, vai vir o valor diferente na fatura?
Answer: Diretamente a quantidade de usuários não afetará nada, o que afeta é o tráfego gerado por eles. Então se 1 usuário trafegar 1GB é isso que afetará. Se 100.000 usuários trafegar 1KB cada, estes usuários consumirão bem menos tráfego que aquele único usuário. Aí vai depender do uso que cada usuário pode fazer na sua aplicação específica, das medidas de segurança para evitar abusos (por ataques ou uso excessivo), etc.
No geral há um média de tráfego que cada usuário costuma fazer em uma sessão (o que é outra coisa a se analisar, afinal se o mesmo usuário acessar várias vezes ele provavelmente gerará mais tráfego que um usuário que acessa apenas uma vez) pode ser determinada analisando os logs de acesso. É possível fazer estimativas entendendo bem o padrão de tráfego de cada operação, as operações esperadas em cada sessão e a quantidade de sessões/usuários que devem usar. Só o uso real dará uma noção real.
Quanto vai ficar mais caro depende do seu plano, mas provavelmente ficará mais caro sim. Inclusive um dos ataques que se costuma fazer é gerar tráfego fictício para, ou que pode, encarecer a fatura de programadores inexperientes.
Comment: Mas tanto na calculadora de preços quanto na hora de criar o grupo de recursos ou atribuir para a aplicação, em nenhum momento existe essas informações de valor x quantidade de trafego. (ou pelo menos não encontrei)
Comment: Não sei como usou, mas você paga pelo tráfego usado.
Comment: Vlw, o @William forneceu o link na resposta abaixo: https://azure.microsoft.com/en-us/pricing/details/data-transfers/
Answer: Como o @Maniero falou a conta é baseada na quantidade de dados trafegados, não na quantidade de usuários, com base nisso você pode verificar e estimar qual vai ser o custo a ser pago, o valor está nessa página aqui.
Comment: Isso, era essa página que eu precisava, obrigado, dei a resposta correta ao @bigown, por responder a dúvida, mas seu link me ajudou muito.


Does the number a: a=cos(a) (fixed point for cosine = 0.73908513321516...) have any other interesting properties

Question: Can it be expressed in terms that do not directly or indirectly require the cosine calculation?
Is there a way to compute it without iteration?
I presume it is irrational...
Comment: It is transcendental, that follows easily from the Lindemann–Weierstrass theorem.
Answer: The solution of the equation is the Dottie number.
As you will see, a quite good approximation is given by
$$a \approx \left(\frac \pi {160} \right)^{1/13}\approx0.7390853722$$ Otherwise, you could approximate it using $[1,n]$ Padé approximants built around $a=\frac 1 {\sqrt 2}$ and get (nasty) explicit expressions.
For example, using $n=1$, you would get
$$a=\frac 1 {\sqrt 2}+\frac{2 \left(\sqrt{2}+\sqrt{2} \sin \left(\frac{1}{\sqrt{2}}\right)-\sin
   \left(\sqrt{2}\right)-2 \cos \left(\frac{1}{\sqrt{2}}\right)\right)}{-7-8 \sin
   \left(\frac{1}{\sqrt{2}}\right)+\sqrt{2} \cos
   \left(\frac{1}{\sqrt{2}}\right)+\cos \left(\sqrt{2}\right)}$$
Just for the fun of it, I produced values of $a_{(n)}$
$$\left(
\begin{array}{cc}
 n & a_{(n)} \\
 1 & \color{red} {0.73908}127514673336 \\
 2 & \color{red} {0.7390851}5691043600 \\
 3 & \color{red} {0.739085133}03909324 \\
 4 & \color{red} {0.739085133215}51992 \\
 5 & \color{red} {0.73908513321516}649 \\
 6 & \color{red} {0.739085133215160}52 \\
 7 & \color{red} {0.73908513321516064}
\end{array}
\right)$$
You could also perform one single iteration of high order iterations methods, starting with $a_0=\frac{1}{\sqrt{2}}$, and stil get explicit expressions. The corresponding numerical values would be
$$\left(
\begin{array}{cc}
 n & a_{(n)} \\
 1 & \color{red} {0.739}31860587975274 \\
 2 & \color{red} {0.7390}7951355898452 \\
 3 & \color{red} {0.739085}25658441687 \\
 4 & \color{red} {0.7390851}2998208803 \\
 5 & \color{red} {0.739085133}30261553 \\
 6 & \color{red} {0.73908513321}267735 \\
 7 & \color{red} {0.739085133215}23303 \\
 8 & \color{red} {0.7390851332151}5848
\end{array}
\right)$$
Answer: Such equations do not have closed-form solutions and the only way to calculate the root of it is by Numerical Analysis methods, such as iteration as you mentioned.
Take into account that there are numerous methods that converge faster or slower and each of them are chosen depending on the problem given.
Comment: Is this still the case? I see a section "Closed Form" under the wikipedia article now, that seems to have been added only last year: https://en.wikipedia.org/wiki/Dottie_number#Closed_form
Comment: It is included in Excel and LibreOffice, so it is rather standard.
Comment: @AlbertRenshaw it involves the $I^{-1}$ , which is the inverse regularized Beta function, a non standard-function.


Execute XML Source after script component completes in ssis

Question: I want to execute the XML source after a script component is complete n SSIS data flow. i.e based on whether the script fails or passes the xml source flow should start (in the data flow). Is there any simpler way to do it.
I cannot create a connector because XML source doesn't have any inputs.
Comment: Got it, i can add a script task instead of script component in dataflow. And make a flow from script task to data flow.
If there is anyother better way to do it. pleaes post, happy to mark that as a answer :)
Answer: Got it, i can add a script task instead of script component in dataflow. And make a flow from script task to data flow.


Countable open cover up to a null set

Question: Given a metric space $(X,d)$,a probability measure $\mu$ (on the Borel sigma algebra) and an open cover $C:=\{A_i\}_{i\in I}$ of $X$, is it always possible to find a countable subset of $C$ that covers $X$ up to a null set i.e. does there exists countable $C'\subseteq C$ such that $\mu(X\backslash \cup_{A\in C'} A)=0$?
Naively one would suspect that this is true because if we consider a "minimum" $C'\subseteq C$ that covers $X$ up to a null set, then for any $A\in C'$ we have $\mu(A\backslash \cup_{A\neq A'\in C'} A')>0$. Hence if such $C'$ is uncountable it's routine to show that $\mu(X)=\infty$, a contradiction. Obviously this argument doesn't necessarily work because such $C'$ may not exists.
For the sake of completeness I should mention that this is a natural question that one might want to answer to solve Exercise 2.2.3 of Einsiedler and Ward's Ergodic Theory text: Let $(X,d)$ be a metric space, $T:X\to X$ Borel measurable, and $\mu$ be a $T-$invariant probability measure. Prove that for $\mu-$almost every $x\in X$ there is a sequence $n_k\to\infty$ with $T^{n_k}(x)\to x$ as $k\to \infty$
Comment: No I didn't assume that $X$ is separable nor that $\mu$ gives an open set positive measure. The original question that I'm working on is easy if $X$ is separable/second-countable/compact and in fact for this question you directly get countable/finite subcover (rendering the up to null set property useless). Is there any good reason that I should assume that $\mu$ gives open sets positive measure? I am aware that in that case we can't have uncountably many disjoint open sets but that doesn't seem too bad.
Comment: Do you assume that $X$ is separable? Do you assume that $\mu$ gives open sets positive measure?
Comment: I remember that I once read that every separable probability space is measure-equivalent to a compact metric space.
Comment: It turns out that in the introduction of the book it was mentioned that metric spaces are separable unless stated otherwise, which means that this problem is easy. This is why one should read introductions carefully.
Answer: I don't have a complete answer, but I will argue that a positive answer to your question would refute a statement "widely believed by set theorists", namely the existence of measurable cardinals.
Let $X$ be an uncountable set with metric
\begin{align}
   d(x,y) &=
      \begin{cases}
         1 & \text{if $x\neq y$,} \\
         0 & \text{if $x=y$,}
      \end{cases}
\end{align}
so that $X$ has the discrete topology.
Suppose we can find a probability measure $\mu$ such that $\mu(\{x\})=0$ for each $x\in X$.  Then, this would provide a negative answer to your question, namely, the open cover $\{B_{1/2}(x): x\in X\}$ would have no countable subfamily that covers $X$ up to a null set.
According to this answer and the Wikipedia page it cites, the existence of such a measure space cannot be proven from ZFC (assuming the consistency of ZFC).  If you can prove in ZFC that countable subcovers modulo null sets always exist, you would get a proof of the inconsistency of the existence of measurable cardinals with ZFC.  This is a possibility as far as I understand, but it seems that most set theorists do not consider it a likely possibility (see e.g. here or Volume 5II, Chapter 54 or Measure Theory by Fremlin).
Comment: I really appreciate the comment because this leads me to the right direction. I wanted to point out that this is much stronger than what we need. In particular apparently the given measure in this case is an outer measure, which is very strong. I believe it suffices to consider $\mathbb{R}$ with the same metric as in your answer. The measurable set will be the countable and cocountable and the measure is 0 if it's countable and 1 if it's cocountable. By some easy work we can see that this is a counter example to both my question and the original question. Thank you.

Countable open cover up to a null set


Disable row select in jqGrid on right click

Question: In jqGrid, I am currently disabling row select with the following:
beforeSelectRow: function() {
     return false;
}

This works fine for left clicking. However, I noticed it's not firing the beforeSelectRow event handler and still selecting the row when I right click. This is a problem for me since I'm implementing a custom context menu.
I am able to get around this with what asker himself admitted is a hack found here:
Is it possible to Stop jqGrid row(s) from being selected and/or highlighted?
Is there any other, less hacky way to do this?
Thanks!
Update
It appears this is only a problem with subgrids. Please refer to this example. You'll notice left clicking does not select the row but right clicking does.
(I took the lazy way out and stole this example from an answer to a different question provided by Oleg.)
Answer: If you want to disable the row select, you can config onSelectRow to return false, this will block both left click and right click.
onSelectRow: function() {
     return false;
}

To force unselect row on right click:
onRightClickRow: function () {
    grid.jqGrid('resetSelection');
    return false;
}

Comment: Thank you for your answer. I've tried this exact code as you can see in my question. It must be this doesn't work in subgrids. Please see my update.
Comment: @iacii Updated. hope it helps.
Comment: What is the need to return `false`?


Representation of indefinite Kac-Moody algebras

Question: The Kac-Moody algebras are divided in three very distinct classes: finite-dimensional, affine and indefinite type.

For the first class the finite-dimensional representation theory is very known.
For the second one, it is not hard to see that we only have trivial representation.

Question:  does exists finite-dimensional representations of any Kac-Moody algebra of indefinite type which is not trivial?
EDIT: After I posted the question, I realized that I know the answer, so I posted it.
Answer: The answer is NO. There is no finite-dimensional representation theory for indefinite type, since they are all simple.


Finding the best univariate model

Question: I have the response variable as Profit, and several predictor variables. I have made a multivariate linear model to represent this, and have also made univariate models for every individual predictor variable. How can I determine which univariate model best represents the actual model?
My idea was to subtract the p-value of a predictor in the multivariate model from the p-value in it's univariate model, but I am not sure that this is the correct way to do this.
How should I do it? I am using R.
Answer: If I've understood your question, you could look at a correlation matrix with each variable correlated with the predictor.
You could also look at the adjusted R-squared of the whole model Vs each individual predictor. The best univariate R-squared is the highest.
I'd personally steer clear of a stepwise regression but it could point you in the direction of your answer. As for regressions in R, the code is fairly simple, I learned from and regularly used the below site as it also provides information around the assumptions in this type of model.
http://r-statistics.co/Linear-Regression.html
Comment: To hopefully clear up: There are 6 predictor variables. There is one model with ALL variables as predictors, and there are 6 other models with each of the predictor variables as the only predictor. I have been asked which of these models represent the model with all 6 predictors in best. If this is what you understood from the question, how would i do a correlation matrix with that? Also for the second method, is it the model with R squared closest to the R squared of the whole model?
Comment: To create the correlation matrix you can use the cor function e.g. corMatr <- cor(data)
Where data is your table of predictors and target. To your second point, for the multivariate model, you are looking at the adjusted R-squared. If for example this is 0.6 then 60% of the variation in the dependent variable is accounted for by your model.
If you then create 2 univariate models with an R-squared of 0.1 - 10% and one with 0.02 - 2% you can see that one of the predictors is better than the other and closer to the multivariate model for explaining the variation in the dependent variable.
Comment: Instead of using a correlation matrix, could I calculate all of the correlations between response and each predictor separately and then obviously the higher the correlation, the better fit that univariate model is?
Comment: You could do but the correlation matrix shows this information. Also remember that your R value (your correlation coefficient) is a measure of the strength of the relationship between predictor and dependent variable. Your R-squared is a measure of effect size. Apologies for not being specific but you want the adjusted R-squared if you are working with a sample as R-squared is positively biased. It would be correct to say 'The higher the Adjusted R-squared the better the fit the model is'
Comment: So I should use R-squared in this case? I am using a whole data-frame as the data.
Comment: Use adjusted R-squared

Finding the best univariate model


How to connect an ESP8266 device securely to a web frontend?


Prove that $\int|f − g| = \int_{-\infty}^{\infty} μ(F_t △ G_t) dt.$

Question: Let $f$ and $g$ be integrable functions on a measure space $(X,Σ,μ).$ For each
$t ∈ \mathbb{R},$ consider the sets
$F_t =\{x∈X :f(x)>t\},
G_t =\{x∈X :g(x)>t\}.$
Prove that
$\int|f − g| = \int_{-\infty}^{\infty} μ(F_t △ G_t) dt.$
Here $A △ B = (A $\ B) ∪ (B \ A) denotes symmetric difference of sets.
I am having a lot of difficulty figuring out where to start on this problem.  Some direction would be awesome.  Its a past qual problem.  Thanks.
Comment: Fubini will probably be useful
Answer: Notation: For $Y\subset X$, let $1_Y:X\to \Bbb R$ defined by $1_Y(y) = \begin{cases}1 \,\,\,\,\text{ if }y\in Y
\\ 0 \,\,\,\,\text{ otherwise.}
\end{cases}$

$$F_t △ G_t = \{ x: f(x) > t \ge g(x)\} \cup \{ x: g(x) > t \ge f(x)\}
$$
and the intersection of these sets is empty, so
$$\mu(F_t △ G_t)
= \mu(\{ x: f(x) > t \ge g(x)\})
+  \mu(\{ x: g(x) > t \ge f(x)\});
\\
\int_\Bbb R dt \mu(\{ x: f(x) > t \ge g(x)\})
= \int_X d\mu \left(\int_\Bbb R dt \{ t: f(x) > t \ge g(x)\}\right)
\\= \int_X d\mu (f(x)-g(x))1_{f(x)>g(x)} $$
using the Fubini theorem in the middle. Do the same thing with the other part and you are done.


How to get next valid `product_id` value within Rules for drupal commerce product?

Question: I'm using Rules to create drupal commerce products. The problem is that the product_id is not assigned.
Since the Rules settings page for creating products only gives the following options, I assumed that the product_id would be generated automatically:
Entity type, SKU, Type, Title, Creator, Price, Provided variables.
If the product_id has to be added manually (within Rules) how would I obtain the correct value to use? (Or is there a setting I am missing within Rules?)
Cheers!
Answer: You cannot set the product ID manually, because it depends on the AUTO_INCREMENT value in your commerce_product database table. What you can do is use "Save an entity" on the product and check the "Force saving immediately" checkbox. The entity will have an ID after that, though I've had scenarios in Rules where for some reason the ID wasn't immediately added to the entity in memory. If this happens to you, you'll just have to use "Fetch an entity by property" after saving and load the product using the SKU or something and use the fetched_entity from then on.
Comment: Thanks Ryan, added a "save entity" action and it works! :)


PPTP VPN Setup on Debian based plug-computer

Question: I have a sheevaplug Plug Computer running Debian taht I am trying to get a pptp VPN running on.
I have installed the pptp daemon and have it running and I can connect to it, but the IP address is not getting set properly and I cannot use the VPN to connect to the internet.
I have set the localip and the remoteip in my pptpd.conf file as follows:
localip 172.16.1.117 (which is the IP address of the sheevaplug)
remoteip 172.16.1.126-130
I have also set the net.ipv4.ip_forward = 1 in sysctl.conf
However, whenever I connect to the VPN, the IP address of the connection is set to 192.168.0.1 (or something similar) and not to the, as I would expect, 172.16.1.xx address.  I think this is causing me not to be able to access the internet through this VPN, as well, since the IP address is not matching up.
Is there another configuration I need to setup to get this working properly?  Any info or nudge in the right direction would be greatly appreciated.
Thank you.
Answer: Solved the issue by rebooting the plug computer.  It seemed from the instructions all I had to do was restart pptpd, but after a reboot, the IP was assigned correctly.
Now I just have to resolve a router port issue to get to it from the outside world.


A multilevel model with data on a school level and individual level

Question: I am trying to perform a multilevel regression analysis with SAS and I found a lot of information on how to do this if your dependent variable is at the lowest level (in my case, this would be the individual level). The problem is that I am trying to find out how individual and school variables influence a school level dependent variable (e.g., a perception of school safety or school climate). Is it possible? What kind of analysis would be the most appropriate? Thank you very much in advance!
Comment: Is the dependent variable really measured at the school level, or is it an aggregate of data from the individual level?
Comment: Thank you for your answer! It is an aggregate of data. Students give their opinon on their school climate (e.g., In my school, students have good relationships with teachers). There are 3 questions which we summed up, calculated means in each classroom and then assigned this score to all the students in the classroom. This is our dependent variable. Independent variables are such as self-reported level of empathy, self-esteem, etc. at the individual level.
Comment: Check out Judith Singer's paper *Using SAS PROC MIXED to Fit Multilevel Models, Hierarchical Models, and Individual Growth Models* (ungated copy here ... https://www.ida.liu.se/~732G34/info/singer.pdf). It's almost 20 years old but her discussion remains quite topical and relevant, not to mention that she fits all of her models in SAS, your software of choice.
Answer: If you are really interested just in the relationship at level 2 (the schools), then you might just use the level-2 data and run a standard linear model. However, your results may be biased, for example because your measurement of that level-2 variable (school climate) is unreliable---you can think of it as something like a latent variable measured by x indicators, where x are the students. Lüdtke et al. (2008) developed models that take that into account (but I fear this relates only to independent variables). And Croon and van Veldhoven (2007) have a nicer paper where the dependent variable is an aggregated level-1 variable.
References

Croon, M. A., & van Veldhoven, M. J. (2007). Predicting group-level
outcome variables from variables measured at the individual level: a
latent variable multilevel model. Psychological methods, 12, 45-57.
Lüdtke, O., Marsh, H. W., Robitzsch, A., Trautwein, U., Asparouhov,
T., & Muthén, B. O. (2008). The multilevel latent covariate model: A
new, more reliable approach to group-level effects in contextual
studies. Psychological Methods, 13, 203–229. doi:10.1037/a0012869
Comment: Level 2 is individual, not schools.
Comment: Thank you so much for helping me. HPlieninger - I will definitely read through these papers and check what can be done. SmallChess - what are the implications of this? I´m sorry but I don´t understand...
Comment: @SmallChess: From my understanding, the OP has students nested within schools (or classes), so level 1 are individuals.
Comment: @Izabela you can also aggregate the student level variables to make them useful for the higher level regression. However a proper analysis will then take the variance in that estimate into account, for example using a Bayesian analysis and/or Monte Carlo methods
Comment: Great! Thank you so much for your help. This also sounds like a good option. The paper recommended by hplieninger also seems to answer my question. It seems that a regression analysis can be performed with these data and then the results can be easily corrected with a formula. The paper is:

Croon, M. A., & van Veldhoven, M. J. (2007). Predicting group-level outcome variables from variables measured at the individual level: a latent variable multilevel model. Psychological Methods, 12, 45-57.


Numero da linha na tabela

Question: Tenho uma tabela e quero que quando clicar no botão informações, apareça as informações da linha seguinte(que está oculta).
Para isso teria que pegar o valor da td que cliquei e habilitar com o display:block somente a linha com valor de td + 1.
parte da tabela(observem que tenho 2 tr, uma que é habilitada e pra cada uma dessas tenho 1 abaixo que é a que quero mostrar)
   {% for volume in volumes %}

             {{ volume.nome }}
             {{ volume.tipo }}	"
             {{ volume.snap }}
             {{ volume.porcentagem_snap }}
             {{ volume.volume_real }}
             {{ volume.volume_dados }}
             {{ volume.porcentagem_uso }}
            info

             Snapshot: {{ volume.snapshot_autodelete }}

 Snapshot Policy: {{ volume.snapshot_policy }}
            Junction_Path: {{ volume.juction_path }}
             Export_Path: {{ volume.export_path }}
            Deduplication: {{ volume.deduplication }}

 Deduplication Savings: {{ volume.deduplication_savings }}

    {% endfor %}

javascript/jquery
 // quando clicar em info abrir card com mais informações
                $(".info").click(function(e){
                 e.preventDefault();
                el = $(this).data('element');
                $(el).toggle();
                    });

No momento quando clico está abrindo todas as linhas desse tr
Answer: No seu data-element você está colocando a classe .informacoes como parâmetro. O seu toggle vai agir nesse selector e vai fazer aparecer todos os elementos da classe .informacoes.
Uma outra forma de você obter a tag
 logo à frente é você utilizar a função next() do JQuery, que obtém o elemento imediatamente à frente do elemento selecionado. Mas como você está no contexto de uma tag , você vai precisar utilizar o parents() primeiro (para viajar dois níveis acima, até o
), e depois o next(). No fim, o seu código vai ficar assim:
                $(".info").click(function(e){
                   e.preventDefault();
                   var tr = $($(e).parents()[1]);
                   tr.next().toggle();
                });

Comment: Oi Pedro, tentei com o seu código, obtenho o seguinte erro: TypeError: e.parents is not a function. (In 'e.parents()', 'e.parents' is undefined)
Comment: Para mim poderia ser por meio da tag  ou mesmo com um click na linha, o que for mais fácil.. Poderia ajudar?
Comment: Obrigado! Vou corrigir o meu código. Em tempo: se você utilizar o evento de clique direto na linha, o elemento do evento vai ser o ``, e aí nesse caso seria só você usar o `next()`.

Numero da linha na tabela


Center text vertically with whilst in the same line as float: right button

Question: I have a div with information, and a cancel button positioned to the right using float.
I want to center the information text vertically in the center, but whatever I try to use doesn't work.
How can I align the text so that it is vertically center, but keeping the same button height and cancel button position?

.scb-frmo-frbtn {
  width: 75%;
  border-top: 1px solid var(--c1) !important;
  padding-top: 8px;
  padding-left: 5px;
  padding-bottom: 8px;
  box-sizing: border-box;
  font-family: var(--dm);
  cursor: pointer;
  transition: .1s;
  overflow: hidden;
  border-radius: 0;
  border: none;
  height: 57px;
}

.scb-frmo-frbtn > .title {
  font-weight: 800;
  font-size: 18.5px;
  color: var(--c5);
  vertical-align: middle;
}

.scb-frmo-frbtn > .desc {
  font-weight: lighter;
  margin-left: 10px;
  vertical-align: middle;
  color: lightgray;
  font-size: 13px;
}

.scb-frmo-frbtn > button.cancel-fr {
  float: right;
  background-color: var(--c6);
  color: white;
  font-weight: normal;
  margin-right: 8px;
  cursor: pointer;
  border-radius: 100%;
  border: 1px solid var(--c6);
  height: 40px;
  width: 40px;
  transition: .1s;
}

  username
  Outgoing Friend Request
  <button class="cancel-fr">X</button>

What it looks like:
Comment: why dont you use flex property
Comment: Ravi Yadav, I already tried using that and align-self/align-content, but the button ended up not being positioned correctly.
Answer: It's possible to center the text vertically by setting line-height to the height of the cancel (X) button.
As the button has a height of 40px, I set the values to that.
.scb-frmo-frbtn > .title {
    /* vertical-align: middle; */
    line-height: 40px;
}

.scb-frmo-frbtn > .desc {
    /* vertical-align: middle; */
    line-height: 40px;
}

.scb-frmo-frbtn {
  width: 75%;
  border-top: 1px solid var(--c1) !important;
  padding-top: 8px;
  padding-left: 5px;
  padding-bottom: 8px;
  box-sizing: border-box;
  font-family: var(--dm);
  cursor: pointer;
  transition: .1s;
  overflow: hidden;
  border-radius: 0;
  border: none;
  height: 57px;
}

.scb-frmo-frbtn > .title {
  font-weight: 800;
  font-size: 18.5px;
  color: var(--c5);
  line-height: 40px;
}

.scb-frmo-frbtn > .desc {
  font-weight: lighter;
  margin-left: 10px;
  line-height: 40px;
  color: lightgray;
  font-size: 13px;
}

.scb-frmo-frbtn > button.cancel-fr {
  float: right;
  background-color: var(--c6);
  color: white;
  font-weight: normal;
  margin-right: 8px;
  cursor: pointer;
  border-radius: 100%;
  border: 1px solid var(--c6);
  height: 40px;
  width: 40px;
  transition: .1s;
}

  username
  Outgoing Friend Request
  <button class="cancel-fr">X</button>


Is the one-point compactification of the rationals sequential or Frechet-Urysohn?

Question: Let $X=\mathbb Q^*=\mathbb Q\cup\{\infty\}$ be the one-point compactification of the rationals.  The open sets in $X$ are the open sets in $\mathbb Q$, together with the complements in $X$ of the (closed) compact subsets of $\mathbb Q$.
I have not seen a reference for this, but it seems the following should hold:

The compactification $X=\mathbb Q^*=\mathbb Q\cup\{\infty\}$ is Frechet-Urysohn.

In other words, if $A\subseteq X$ is not closed in $X$ and $x\in\overline A\setminus A$, there is a sequence $(x_n)_{n\in\omega}$ in $A$ that converges to $x$.  (see start of a proof below)
This is interesting because first countable $\implies$ Frechet-Urysohn $\implies$ sequential $\implies$ compactly generated.  From the properties compiled here and the references there we already know $X$ is not first countable.  Showing it's Frechet-Urysohn would imply it's compactly generated in the sense of Definition 2 in wikipedia.  On the other hand, the product space $\mathbb Q^*\times\mathbb Q^*$ is not compactly generated.  So $\mathbb Q^*$ would provide an example of a compactly generated space whose square is not compactly generated.

(Incomplete) Proof of result:
Let's write $Y=\mathbb Q$ for convenience.  Take $A\subseteq X$ with $x\in\overline A\setminus A$.
Case 1: Suppose $x\in \mathbb Q$.  Then $\mathbb Q$ itself is an open nbhd of $x$ and $\mathbb Q$ is Frechet-Urysohn since it is first countable.  So there is a sequence $(x_n)_n$ in $A\cap\mathbb Q$ that converges to $x$.
Case 2: $x=\infty$, so $A\subseteq \mathbb Q$.  We have to show there is a sequence in $A$ that converges to $\infty$.  By definition of the one-point-compactification, saying $\infty\in\overline A$ is equivalent to saying that $A$ is not contained in any compact subset of $\mathbb Q$.  On the other hand, if we can find an infinite discrete subspace $Z\subseteq A$ that is closed in $\mathbb Q$, any enumeration of it would be a sequence converging to $\infty$.  So the proof would boil down to this:

Suppose $A\subset\mathbb Q$ is not contained in any compact subset of $\mathbb Q$.  Does $A$ necessarily contain an infinite discrete subspace $Z\subseteq A$ that is closed in $\mathbb Q$?

How to show this?
Comment: Somewhat related: https://math.stackexchange.com/questions/4703664
Answer: If $A\subseteq\mathbb{Q}$ is not contained in any compact subset of $\mathbb{Q}$ (i.e., its closure in $\mathbb{Q}$ is not compact), then there is a sequence $(a_n)$ in $A$ with no subsequence that converges in $\mathbb{Q}$.  Such a sequence converges to $\infty$ in $\mathbb{Q}^*$ (any compact subset $K\subset\mathbb{Q}$ cannot contain a subsequence of $(a_n)$ so the sequence must eventually be outside of $K$).
Comment: Or, if you like, the closure of $A$ in $\mathbb{R}\cup\{\infty,-\infty\}$ must contain either an irrational number or $\pm\infty$, so there is a sequence in $A$ that converges to an irrational number or $\pm \infty$.
Comment: In the first sentence, why is it that there is a sequence in $A$ with no convergent subsequence in $\mathbb Q$?
Comment: The closure of $A$ is not compact so it contains a sequence with no convergent subsequence.  You can then approximate the terms of this sequence with elements of $A$ (making the approximations closer and closer as the sequence goes on).  (More generally, in any metric space, a set has compact closure iff every sequence has a subsequence that converges in the whole space.)


How do I reduce the Socialite scope in Laravel 5?

Question: I'm successfully using Laravel 5's socialite feature, but I feel that it's asking for more permissions than makes sense for the end user when they sign up. For instance, Google tells my users that I need:

Know your basic profile info and list of people in your circles.
  Includes people in circles that are not public on your profile.

and

Allow Google to let the people in these circles know that you have
  signed in to this app with Google: Your circles

All I need is the user's name and email address. How can I reduce the scope so that users don't have to worry about me posting things on their behalf?
Laravel's docs list this:
http://laravel.com/docs/5.0/authentication#social-authentication
return Socialize::with('github')->scopes(['scope1', 'scope2'])->redirect();

But there's no documentation on what scopes I can use, or if I can remove default scopes. Any ideas?
Answer: just for future reference this is how you can change it:
public function redirectToProvider()
{

    $scopes = [
        'https://www.googleapis.com/auth/plus.me',
        'https://www.googleapis.com/auth/plus.profile.emails.read'
    ];

    return Socialite::driver('google')->scopes($scopes)->redirect();
}

You can also play with all of the google scopes here: https://developers.google.com/oauthplayground/
Answer: It turns out that these extra permission requests only showed up while the API was disabled in my Google Dev console. It doesn't make sense as to why the scope request would change, but the request wont work anyway without the API being enabled. Enabling the Google Plus API simply changed all of the permissions to just 'offline access'. Looks much cleaner and better for the end user.


How to use GreatSchools API module?

Question: I enabled the GreatSchools module and entered the API KEY from greatschools in the configuration but there is no documentation on how to see the schools as content.
Can you point me to the right direction?
Comment: Belongs in the drupal.org issue queue as a support request.
Answer: This is an Drupal API module making it easier to use The GreatSchools API / get data from GreatSchools. You have to write your own module (or enable the PHP module and write PHP directly in your nodes - not recommended) to use the functionality provided by the module. Currently it provides the following functions:

great_schools_nearby_schools
great_schools_browse_schools
great_schools_browse_districts
great_schools_city_overview
great_schools_nearby_cities
great_schools_school_census_data
great_schools_school_profile
great_schools_school_search
great_schools_school_test_scores
great_schools_school_reviews

Good luck!
PS! I have never used this module myself.

How to use GreatSchools API module?


I purchased my domain with namecheap, have hosting from nearlyfreespeech - how do I get my site up and running?

Question: I bought my domain from namecheap a week or so ago. Today, I bought hosting from nearly free speech and have built my site. I've uploaded my site to the nearly free speech servers.
I can access my site at mysite.nsfhost.com. On Nearly free speech, it says that the associated domain is mysite.com
But I didn't change anything on the namecheap side of things, and I have no idea how to point mysite.com to the nsfhost.com
Help!
Comment: Who is going to host your name service? Nearly free speech, namecheap, or someone else?
Answer: Namecheap has a DNS control panel. All you need to do is set up an A record for your domain that points to the IP address of your nsfhost server. There is a video on setting up an A record using the namecheap control panel here