CCK nodereference is returning empty nid when no node is selected

Question: For testing purposes I've installed CCK module on vanila drupal,
created new node type and attached CCK nodereference to it.
After creating new node, I've notice in node.tpl.php the following structure:
    [field_my_node_reference] => Array
    (
        [0] => Array
            (
                [nid] =>
                [safe] => Array
                    (
                    )

                [view] =>
            )

    )

As you can probably notice, there is a key $node['field_my_node_reference][0]['nid'] that is null.
In order for me to fully understand CCK - why CCK gives empty keys when nothing is selected?
Any answer is appreciated !
Comment: You found this in node.tpl.php? What theme are you using? Adding a cck field does not modify node.tpl.php. Is it possible that you are using the devel module to view the node object?
Comment: I've print_r($node) in node.tpl.php
Answer: You are looking at a node in CCK's post build_content() phase.  When you add a node reference field to a node, CCK adds the 'nid' portion to the database, and when you build or display the content, it creates the 'safe' and 'view' portions.  If you were doing this manually, you could do something like:
$foo=node_load(27);

and if $foo had a nodereference, $foo would contain
[field_my_node_reference] => Array
(
    [0] => Array
        (
           [nid] =>
        )
)

eg, you could print 'my nid is ' . $foo->field_my_node_reference[0]['nid'];'
and it would print out my nid is [blank] if unset, or my nid is 593 if set.  Now,
when CCK comes in and gets all fancy, it creates the safe and view pieces, and these are set up by those widgets you select in the display fields portion of CCK before getting to node.tpl.  (You can do this yourself by calling $foo=build_content($foo); in a module and looking at $foo again.)  Anyways, CCK works all of that up into the $content variable it aggregates things together into for your node.tpl as well as in the $node variable it has in there if you yourself want to get fancier, eg, print 'this is a link to my node: ' . $node->field_my_node_reference[0]['view'] would normally print out 'this is a link to my node:' followed by the title of the node linked to it.  All changeable via those display options/widgets.
But as to why it has empty keys, they are just part of the data structure created to ensure everything up and down the workflow works together as well as it does, eg, the safe and view portions are blanks where a link would probably go if the field was set, so that makes sense.  And a NULL is in nid since it hasn't been set.
But...just plop in some content and you will see everything fill up all nice :)


Mic use for masked performers

Question: I have been assigned to improve the audio quality in a School auditorium.  In specific, it is a common complaint that spoken text is difficult to understand.
The room is large, with a high ceiling, and while it is excellent for chamber music it is in fact a challenge to understand spoken text.
This year, of course, everyone is wearing a mask.  This exacerbates the issue.  When speakers use the mic it seems only to project their muffled sound, louder.
Assuming that speakers are properly trained in holding the microphone close to their mouths, how can I maximize the intelligibility of their speech?  Our PA system is older, low-tech, but it does have a rudimentary EQ.  Are there certain frequencies that I should adjust to help?
Comment: Is this a music question?
Comment: @Tim - it probably isn't, but it's not sound design either… & this stack is a lot busier than sound. If it were singers rather than speakers we'd all be fine about it.
Comment: @AndyBonner Sometimes stackexchange is just one big [XY problem](https://en.wikipedia.org/wiki/XY_problem).  Seriously, though: While knowing the room size and surfaces could lead toward acoustic recommendations, it can also help a little bit with performer/microphone placement on the stage and EQ settings.
Comment: I'd just like to remind everyone that the question is not "How do I improve the acoustics of the room." Unless nuggethead wants to ask that question separately, I think we should all assume we're not looking for acoustic treatments or the ideal speaker arrangement, but simply how to get the most out of the existing sound system.
Comment: You really need some curtains to hang on all the walls. The ceiling would be nice to damp out also, but much more difficult.
Comment: Are you using a lectern or is this just 'stand out front, wandering around with hand-held mic'? If a lectern, I'd get rid of the hand-held & get a couple of cheap shotgun mics - [example of cheap as chips shotgun](https://www.amazon.co.uk/citronic-Csm400-Shotgun-Conference-Microphone/dp/B00WRA8NNC) or a whole list of them - https://cpc.farnell.com/c/audio-visual/professional-sound-lighting/microphones/shotgun-microphones
Comment: @ToddWilcox - nice idea, but that would be counter-productive for when chamber music is performed in the same room. Curtains that could be drawn? I guess the room's high too, so expensive.
Comment: Is it a true auditorium, or is it just a large room that serves as one (and possibly also as a gymnasium and lunchroom)?  Could you give approximate dimensions of the room and a description of the surface materials?
Comment: Yes, all, the question is how to get the best out of what we have.  I think we'd invest any money we had into upgrading the 1980s sound system, not curtains.
Comment: Since the goal is to increase better text reception, test the installation with some hard hearing people and offer the actors to practice with this goal specifically.
Comment: `of course` why would this be an "of course" thing? The reasonable thing to do would be to _not_ wear masks.
Comment: @Jörg W Mittag point well-taken, but many of the so-called "speakers" are young children.
Comment: @user91988 as mentioned, not wearing masks is not an option.  That's not my opinion, nor a statement about the efficacy of masking, it's the policy.
Comment: Sure, but what I'm saying is that's not an "of course" thing. You should just say that's the policy. Plenty of places _don't_ require masks.
Answer: I'm going to offer a non-technological suggestion. As several answers have already observed, you're fighting some impossibilities (not the least of which is "I have been assigned to improve the audio quality in a school auditorium," presumably without any significant budget, just the expectation that you can create acoustics by tweaking a few pots). I'm also going to assume that having speakers remove their masks is not an option for policy reasons, and that we're not addressing here how one might upgrade the room or system if the money or will existed.
Yes, you should mess with the EQ; you should do so anyway to find what works best for the space. But the idea that you can take a signal that's muffled by the mask and "clean it up" through EQ is like the familiar trope from sci-fi and police shows: The team views a blurry picture of the crime scene, the commander yells "Enhance," and suddenly... we can identify the face of the killer! It's laughable because you can't just create data that was never there.*
Instead, I'm going to suggest that you do as much as you can to improve the human element. This can be a learning opportunity about elocution and skills that are always important to public speaking and singing, whether amplified or not. This training is the best way to radically improve the intelligibility of presenters at any time, but all the more so with masks on. I've been trying to remember, for the last 1.5 years, to walk up to a counter and place my order more or less in the character of Capt. Jean-Luc Picard. ("Hello. I would like a small house blend, please. Black. Engage!") Depending on the age of the students, there's only so much you'll be able to teach them, but you can try.
If leadership can give you a moment to do so, gather all the people who will be speaking. Train them to slow down their speaking (maybe 50%-75% of normal rate, especially if they're given to blurting a memorized line). Yes, train them to get appropriately close to the mic (a matter of inches for most dynamic mics) but also to project well, so you're not left maxing out the slider and getting feedback while someone whispers. Teach them to fill their lungs and use their diaphragm. Most of all, with face masks, encourage them to hyper-enunciate all consonants, since these are what is lost. Without face masks you might have to couple that with a "popper-stopper," but these days everyone is basically wearing one right on their face.
* (Or at least, that was true for decades; maybe now AI could make it possible. But if it's revealing "the face of the killer," maybe now we've got Minority Report-style concerns...)
Comment: I like this answer except eating the mic. Being too close to most microphones hurts intelligibility, although it can help gain before feedback (until you're really eating the mic and then it hurts gain before feedback again). Unfortunately, in a reverberant space, EQ can seriously hurt gain before feedback also.
Comment: Makes sense, and disclaimer, I'm a performer parroting what I've heard from "sound guys," not an actual sound guy. Also on second thought, as long as it's a quiet stage with one speaker, there's way less concern about gain than a singer in front of a drum kit. But I've also seen those folks who take a vocal mic, hold it at waist level, and mumble, and then wonder why no one can hear them :)
Comment: The speaking rate recommendation is *gold*.  People simply aren't accustomed to speaking in a reverberant space where the echo smears their syllables together.  (It probably also conceals the errors of student chamber musicians).
Comment: Actually, enhancing a _blurry_ image _is_ in many cases possible: if the blur is due to being out of focus, [deconvolution](https://en.wikipedia.org/wiki/Deconvolution) can be applied. The downside is that it increases noise, but this may be tolerable. For the mask-muffled sound it's similar; boosting the treble frequencies is similar to what deconvolution does. None of this requires machine learning techniques. The thing in film that's impossible is enhancing _pixelated_ images – in that case the required information is not merely muffled but actually missing completely.
Comment: Excellent answer, especially the bit about "enhance!".
Comment: Yeah, with the understanding that @nuggethead this also involves drafting you into teaching without a license: You basically become the Drama teacher for the day and just say "Slow down... enunciate... project..." on a loop.
Comment: @leftaroundabout boosting treble frequencies is more like edge detection than deconvolution. For deconvolution you need an image of the point spread function to divide by.
Comment: @Ruslan no, edge detection is low-cut. Deconvolution is _a particularly well-chosen_ treble boost, namely the one that exactly counteracts the a previous blurring (well, at least the linear effect of it). Normally with treble boost you won't _exactly counteract_ a previous muffling filter, of course. The image analogy to general treble boosting is [unsharp masking](https://en.wikipedia.org/wiki/Unsharp_masking).
Comment: I like this answer. Fix the source first... the best you can.
Answer: There are three things I'd recommend in terms of PA-settings that do usually make a significant improvement on intelligibility in excessively reverberant rooms:

Cut the bass. Like, properly. Many consoles have 80 Hz low-cut filters on each channel, definitely use those, but in addition don't hesitate to pull down a 100-150 Hz band as far as it goes, perhaps even remove as high as 300 Hz.It may be counterintuitive that removing parts of the sound improves understanding, but the thing is, these frequencies add almost nothing to text intelligibility, however they do push the speakers out of their comfort zone, overload the ears, warble around a lot in the room, and contribute to feedback problems. The bass frequencies are even more over-present through the masks.
Find resonance frequencies of the room and notch them out. This requires a parametric EQ or graphic with at least 31 bands. Even then it's unfortunately often not possible to get it completely right; such resonances tend to shift around strangely.
Apply some compression. Big part of the problem with understanding speech in echoey rooms is that the louder parts of the sounds (often P and T plosives as well as vowels that hit a room resonance) smear over everything else. A fast compressor can attenuate these sounds and thereby lets the rest of it have its needed share of the attention as well. Also, a compressor will just even out the overall volume level, which makes it easier for the ears to adjust.Unfortunately compression increases feedback sensitivity, so this cannot be done too strongly.
Comment: This! I strongly suspect that the "rudimentary" board won't let the OP notch room frequencies, but it's such an important thing to do especially in a room with acoustic issues.
Comment: In that order too, ideally. Compressing before the bass and mud-frequency cuts is ideal
Comment: We don't have a compressor, but I can try attenuating the bass somewhat.
Comment: @nuggethead - compressors aren't expensive, and can deal with all the vox channels on the p.a. simultaneously.
Comment: I think that plosives may already be largely muffled by a mask, perhaps so much that it produces the opposite problem (speech too muddy).
Comment: My main concern with a compressor is that it does need a little skill to set it up. I always use a light-touch progressive compressor on bussed vocals. But I chucked a kid on my desk once while my band was playing, who was a music tech student and should have known better, and afterwards I found he'd cranked the compressor controls to their limits so he'd completely killed any vocal dynamics. You can also get odd feedback problems with makeup gain. It's a very useful tool, but novices can shoot themselves in the foot with it, and it's a bit harder to train than EQ.
Comment: @Graham sure, any useful tool will also allow novices to shoot themselves in the foot. But IMO an EQ is much _more_ dangerous than a compressor. I've so often seen people set up "pleasant" hi-fi-ish EQ curves that only ended up making a complete mush out of the sound, or narrowly boosting a frequency that was apparently cancelling at the FOH but then horribly droned everywhere else, or boosting frequencies that the instrument in question didn't even produce and only added noise. A compressor generally won't do harm as long as the GR doesn't do more than -10 dB or so, which is easy to observe.
Comment: @leftaroundabout True enough - never underestimate the capabilities of a truly motivated idiot. ;)
Answer: Two solutions for you which are either no-cost or ultra-low-cost. They just need a little of your time and effort.
Clean or renew the foam mic windshield
Foam windshield are often left in place over a mic for a long time without being cleaned or replaced. They naturally will get saliva on them, which collects over time (and breeds bugs too). I've seen plenty of dirty foam windshields which cut off enough high end and high mids to interfere with speech intelligibility - as well as being a health hazard too, of course. They're easy to clean, and they cost peanuts to replace.
@AndyBonner has reminded me that many mics have an extra foam insert behind the mesh screen. Unscrew the mesh screen, and remove and clean that foam too. Spritz the mesh with antibac while you're at it too. Or if it's bad, replace the mesh ball entirely - it's pretty cheap, and you don't need genuine Shure mesh balls.
Where are the speakers, which way are they pointing, and what's driving them?
For clarity, you want one set of speakers at the front, facing down the hall. Since you have no room treatment, you want the speakers mounted fairly high and angled downward by about 20-30 degrees, so that the sound all goes towards the audience and doesn't bounce off the walls and ceiling.  Speakers typically give out sound to about 30 degrees up and 30 degrees down. If your speakers have a tilt socket or are adjustable, then do it. If not, speaker tilt adapters cost very little.
If you have more speakers, you want them halfway down the hall and facing along the hall towards the back wall. Again you need these pointing down at the audience. For best clarity, you want a loudspeaker management system which can put a delay on the signal for these speakers, delayed by 1ms per foot of distance between the two sets of speakers. This is how long it takes sound to travel that distance, so you don't get a strange echo. In a smaller hall you might get away with it, but if you've got a large room then this is basically essential. Look up the Haas Effect for how this works.
What you absolutely must not ever do is have a second set of speakers at the back of the hall facing forward. This guarantees an echo which destroys intelligibility. If this is the setup you have, then turn off the back speakers. Cut the wires if there is no other option! You'll find people will be able to hear way better, even if it's less loud for people at the back. And if you can move the back speakers, then put them halfway down the hall as above.
Comment: I need another upvote to give this answer for offering a dirt cheap, 5-second improvement in the form of the windscreens. Even a mic with an internal windscreen behind a grill like the Shure SM58 can replace that (or maybe it's easier to replace the grill as well? Looks like < $10).
Comment: @AndyBonner Thanks for the reminder about the foam inside the mesh ball. I've updated the answer to add that too.
Answer: This probably isn't something that can be solved at the microphone end. The space is too reverberant.  Probably there are just a couple of speakers trying to serve the whole room. It needs more, smaller speakers, closer to the audience. Or possibly a line array.   Not cheap, I'm afraid.
Masks don't actually muffle the voice very much.  They make it harder to communicate largely by removing the visual clues from mouth and face.
Answer: A radio (wireless) mic will help, along with not using a mask, but a visor instead. The kind which fits over the top of the head with a swan neck to position the mic in front of the mouth (I used to wear mine resting on my neck).
Without knowing the speaker configuration, it's difficult, but in a lecture room/auditorium holding say, 250 people, there needs to be 6 or 8 speakers minimum, spread from back to front. Even a couple of flown speakers covering the centre of the room would help. None would need to be expensive - covering vocal range will do - and my mic cost something like £50 - I used it for many gigs.
Comment: @gidds - yes it's worried me or some time - those arrogant aerosols who walk round with either no masks, or their noses poking out..!
Comment: As I understand it, a visor may help to deflect droplets — but it does very little to stop aerosols, which are now understood to be the main route of infection for COVID-19.
Comment: Face Shields are out re:our covid protocols, but I'll see if I can get wireless mics with the goose/swan neck
Answer: I can only recommend that each speaker, in order, approach the lectern and remove their mask.
Ensuring, of course, that everyone else on the podium or stage is six feet away or more.
Supply alcohol wipes to smear over the common microphone in between designated speakers.
Any other solution (such as boosting the treble for the Mic Line) is just folly, and more or less a socially-acceptable band-aid.
Comment: Definitely not a possibility with our covid guidelines
Comment: It really varies a **lot** around the world. In Montgomery County, MD we have a rule (effective August 5, 2021) exempting face masks: *when a person is giving a speech or performing for broadcast or an audience, if no one in a location accessible to the public is within six feet of the speaker*. However, it is not widely known within the county and every jurisdiction has a slightly (or dramatically) different set of rules. And the rules today could change tomorrow.

Mic use for masked performers


Usar JS para aliviar PHP

Question: Bom, tenho um arquivo PHP que me gera um documento(obtenho por AJAX).
Esse documento passa por algumas funções(que fiz em PHP), como por exemplo, converter uma string para código, somar campos..
Bom, para fins de organização, fiz tudo com PHP esses ajustes(então o documento é entregue pronto, o JS não precisa entrar em cena para finalizar o trabalho após a requisição).
Mas, qual seria a indicação? Aliviar para os servidor(memória, menos processamento, entrega mais rápida.. ??), ou se isso para o servidor seria de tão pouca importância(exige pouco processamento) que não valha apena se prender a detalhes e sim preservar um código mais limpo e mais simples de manutenção.
Comment: Essa é uma pergunta que venho me fazendo, principalmente com *infinite scroll* para fazer o javascript montar os elementos. Mas ter a composição fora da *view* me deixa um pouco incomodado. Aguardo ansioso por um bench sobre o tema.
Comment: Acredito que as respostas estão saindo um pouco do escopo da pergunta que não é quanto a quantidade de requisições, validação antes ou depois, etc... Dando a minha opinião, voltada a pergunta, acredito que o js pode ser, até certo ponto, utilizado como sua view (separada do servidor). Toda a parte lógica e as regras de negócio continuariam no servidor, mas quem processa a parte da interface, quem organiza as informações para exibir ao usuário, seria o js.
Answer: Olá.
Antes de mais vou começar por citar uma coisinha que as pessoas normalmente dizem ou pensam, quando se deparam perguntas desse tipo:
Javascript apesar de ser umas das principais linguagens web, não pode nunca substituir o PHP num aplicativo web que queira manter a integridade total dos dados que saem do cliente para o servidor e vice-versa ( lê isto se achares que estou errado ).
Outra coisa é, aliviar com o Javascript, não é nada mais que pré validar dados antes de serem enviados para o servidor segundo a tua questão.
O Javascript em si, serve apenas para lidar com animações e dinamização no lado cliente ou controlar eventos diretamente, sendo que se deixares o Javascript fazer a maior parte do serviço, para além daqueles que realmente lhe competem, e depois enviares para o servidor informações e não realizares outra verificação, sabe-se lá quais dados acabaste de enviar diretamente para o servidor, isso porque o Javascript fez o trabalho todo incluindo a parte do PHP ou outra linguagem BACKEND em uso, e o servidor limitou-se a recebe-los como se fosse ele quem os verificou.
Daí ter o princípio de validar com Javascript e depois voltar a validar com PHP ou outra linguagem que esteja a atuar no lado servidor. Até os frameworkfazem isso, mas de outra forma.
No final não sei se respondi a tua dúvida, mas espero que entendas ao menos que o Javascript não deve nunca substituir o PHP, tenta antes tornar o teu script no lado do servidor mais eficiente.
Comment: exato.. basicamente o mesmo o que respondi
Comment: Sim, é praticamente o mesmo, embora eu tenha estendido a explicação e aprofundando um pouco mais, ainda assim o autor: `As respostas atuais não contêm detalhes suficientes.`, se com isto ele não entender quais são os limites do `Javascript`, então nada posso fazer.
Comment: Pois é.. não entendi o quê mais ele quer.. talvez ele queira ver códigos com casos de estudo comuns e respostas quilométricas com tabelas, gráficos etc.. rsrs
Comment: Sério ? Pensei ter sido o único a achar isso :).
Comment: @Edilson, antes de eu colocar a recompensa de 100, não existia respostas mais completas( ou simplesmente respostas ) que a de DanielOmine, irei analisar estas agora e ver se atendeu a minha expectativa :). Obrigado pela resposta!
Answer: As validações devem ser feitas no PHP (server side) independente do que ocorre no lado cliente (js, html).
Para "aliviar" processos, é recomendável aplicar validações em JavaScript para evitar requisições ao servidor.
Exemplos:
Validar formato de email
Validar quantidade de caracteres
Validar dados somente numéricos ou somente letras
Vale salientar novamente que independente de existir validações no lado cliente, com JavaScript, as mesmas validações devem ser feitas no lado do servidor com PHP.
O "alívio" é útil também pela acessibilidade. Para o usuário no lado cliente, é visualmente melhor e performático.
Comment: Alexandre C. Caus, o motivo é que verificação no lado servidor sempre deve ser feita e a verificação no lado cliente é opcional. Mesmo que faça verificação/validação no lado cliente, as mesmas verificações devem ser feitas no lado servidor pois nem sempre as requisições proveem de um browser convencional.
Comment: Por qual motivo sua resposta se baseia unicamente em **validação**?
Comment: Sua ressalva a revalidação seria exclusivamente para caso o browser do cliente não estiver com JavaScript ativado? Mas neste caso não seria melhor verificar a presença deste, e caso não, solicitar na requisição(atraves de um parametro por exemplo) para que fosse feita a validação. Eu sou da ideia de poupar o servidor, são pequenos detalhes mas que somados talvez façam alguma diferença, mas se essa diferença for tão pouca então que valha mais apena garantir aplicação em termos de segurança de dados(como revalidar). Enfim, não sei o tamanho do esforço do servidor para tal feitos.. @Daniel Omine
Comment: Não sei se você entendeu, pois descreveu o mesmo que postei, porém com palavras diferentes. E sobre o caso de browser sem suporte a JS, é irrelevante para o caso. Por isso, nem precisa dizer que precisa ter validação no server e não confiar somente no lado cliente. E novamente salientando, verificação no lado cliente com JS é essencial para evitar processos desnecessários, principalmente requisições ao server. E browser sem suporte a JS, veja bem, sem suporte JS não navegará em praticamente nenhum website. Um request pode ser feito sem browser, por exemplo, mas isso é outro assunto.
Comment: Entendi que uma forma de "aliviar" seria verificar realmente se a requisição é válida para persistir com o trabalho por parte do servidor, assim não joga uma requisição fora e poupa esforços do servidor. Mas não entendi(talvez por falta de conhecimento) o porquê refazer a mesma(mesma) verificação em ambos(cliente, servidor), se passou em um, o que impede de passar em outro?
Comment: Papa Charlie, não entendi o motivo da sua pergunta. Se puder explicar agradeço.
Comment: @AlexandreC.Caus Se você não tiver validação no servidor, nada impede de que eu faça uma requisição a sua página diretamente, sem utilizar o seu site / formulário, enviando dados inválidos e que possivelmente quebrariam o seu site.
Comment: Porquê tem que repetir a validação do lado do PHP ? Simples, vocês acham mesmo que um método nunca poderia ficar exposto para integração em um webservice ?
Comment: Penso que dizer que é regra, revalidar do lado do servidor, seja errado. Se não comprometer a segurança de um banco de dados não há porquê jogar mais trabalho para o servidor. Não me venha com regras de aplicação, cada caso é um caso.
Comment: Alexandre.. ??? Como assim ?  REalmente não entendo como vc não consegue entender ?? rsrsr.. Tipo assim cara, vc está distorcendo o que foi colocado. Nenhuma das resposta diz que "todo o peso" deve ficar para o server.. de modo algum. Enfim.. aprenda a ler e interpretar..
Comment: @DanielOmine, querendo ou não, isso ficou debaixo dos panos, da para entender que virou regra. Não vou discutir sobre isso, apenas digo que nada é regra, depende de cada caso, sua resposta valeu mas não foi suficiente.. obrigado!
Comment: "debaixo dos panos"?? "virou regra" ?? vc está bem cara ?  rssrs
Answer: TL;DR: depende muito da sua aplicação e do custo beneficio de trocar a funcionalidade para o front-end.
Usar JavaScript para aliviar o back-end é bom. Mas se você deve usar ou não depende muito da sua aplicação, se você tem uma aplicação que está lenta no back-end, vale a pena deixar mais tarefas para o front-end. Se você tem uma aplicação pequena que está gerando os documentos no back-end sem problemas de performance talvez não seja necessário modifica-la e começar a usar o JS.
Deve-se levar em consideração o trabalho que dará alterar a aplicação e o quanto isso implicará na performance. Se for uma grande modificação, que levará muitas horas de trabalho e que irá remover pouca carga do back-end, então não vale a pena. Ao contrário se a modificação não for tão complexa, mas aliviar bastante o servidor então vale a pena fazer.
Como já foi citado em outras respostas aqui, tarefas como validação de dados devem sempre ser feitas no back-end, podem ser feitas no front-end para dar um feedback mais rápido ao usuário, mas devem ser refeitas no back-end para verificar a integridade dos dados, já que se os dados forem validados somente front-end criaria a possibilidade de um usuário malicioso desativar o JavaScript e fazer um ataque ao site como por exemplo um SQL Injection.
Outro ponto importante é que atualmente cada vez mais são usados serviços de computação na nuvem para hospedagem, esse serviços normalmente cobram por tempo de uso e/ou uso de CPU, então quanto menos processamento for usado, mais econômico fica. Logo, quanto mais funções forem dadas ao front-end e retiradas do back-end mais barato ficará o serviço.
Comment: é o mesmo ponto de vista que o meu
Answer: Ao meu ver, a questão é sobre usar o javascript para fazer o trabalho do PHP. Uma requisição feita com ajax pode retornar dados formatados em back-end ou pode receber um json e formatar para composição de uma view. Minha resposta se baseia nessa suposição.
Vou dar como exemplo uma requisição simples contendo um array de 2 índices, somente nome e sobrenome e formatos em JSON, XML e HTML para fins de comparação apenas.

DATA
 array( array( 'Papa' , 'Charlie' ) , array( 'Papa' , 'Charlie' ) )

JSON
LENGTH : 39
STING  : [["Papa","Charlie"],["Papa","Charlie"]]

XML
LENGTH : 191
STING  : <usuarios>
             <usuario><name>Papa</name><lastname>Charlie</lastname></usuario>
             <usuario><name>Papa</name><lastname>Charlie</lastname></usuario>
         </usuarios>

HTML
LENGTH : 66
STING  :
Papa

Charlie

Papa

Charlie

Um output em HTML vai usar o servidor para processar os dados, e você consegue exibir os dados usando funções simples. Pode ser a melhor opção quando se tem pouco fluxo de dados ou para quem não tem tanta familiaridade com javascript. Por outro lado, temos um fluxo maior de dados e pode tornar a aplicação mais presa.
Dados em JSON são fáceis de trabalhar com tipo object, alem de ter um comprimento bem menor que os outros formatos, e isso é um ponto interessante para economia de banda. JSON e XML são mais flexíveis e simples de implementar webservices, APPs, desktop, dispositivos móveis...
Não encontrei um benchmark de respeito que pudesse usar como efeito de comparação, mas não vejo uma desvantagem tão grande no tempo de processamento entre PHP e javascript que implique como fator decisivo para mudança. De fato o PHP consome mais recursos para montar o HTML, enquanto o javascript compõe com baixo custo. Mas para responder qual usar ou quando, depende da necessidade - reduzir trafego, flexibilizar a aplicação à outras plataformas... acho que são pontos de maior importância na escolha.

Algumas referencias interessantes
• Why is it a bad practice to return generated HTML instead of JSON? Or is it?
• AJAX - Using JSON vs echo HTML
• Why do Facebook, Twitter and GMail render all their data to the browser as JSON as opposed to HTML?
• PHP vs node.js: The REAL statistics
• The AJAX response: XML, HTML, or JSON?
• Creating HTML: PHP server-side vs. jQuery clie
Comment: Uau.. Boas referências, quando me sobrar tempo irei analisar estas, obrigado pela resposta, vou considera-la a mais completa e te recompensar. abraços
Comment: concordo, depende da necessidade e viabilidade na questão da segurança, não podemos simplesmente dizer que é uma OBRIGAÇÃO validar tudo no server, pois existem vários casos onde pode ser aplicado as "exceções" que resultam em ganho de performance.
Answer: Para jogar lenha na fogueira, posso sim fazer um código "LIMPO" do lado do cliente até chegar no lado do servidor, e continuar programando javascript no lado do servidor basta usar o nodeJs.

https://nodejs.org/

Então a questão de validar do lado do server ou do lado do cliente, vai depender do que esta validando, se for alguma coisa que não vá comprometer a segurança de um banco de dados, ou deixar um javascript do lado do cliente onde ele posso sobreescrever uma função para mudar alguma coisa nesses casos deixe tudo do lado do servidor.
Mas uma validação do tipo digite seu login que é o email, e uma função que verifica se o email tem um @ no meio da string, nesse caso eu posso tranquilamente jogar isso do lado do cliente.
Comment: @wryel acho que você não me entendeu, a validação de um "email" se ele esta dentro do formato nome@dominio eu valido somente com javascript do lado do cliente, se for usado como login, e ele passar errado simplemeste não vai logar, e o script da validação do lado cliente irá avisar que o formato do email esta errado, simples asism.
Comment: @wryel conforme citou ["deveriamos lançar um exceção ou e sair do fluxo principal"] nesse caso eu uso o javascript para lançar a exceção, assim nem chega um email sem ser formatado para o server verificar, e ref. a sair do FLUXO PRINCIPAL isso sim o php tratará(caso seja enviado um post para o server de forma maquiavélica) não logando pois o email não formatado não será localizado no SGBD.
Comment: NodeJs é um framework :)
Comment: Essa é uma resposta seria ? Sempre devemos validar os dados de origem duvidosa (que sua aplicação não tem controle). Até mesmo um e-mail / senha deveria ser validado, imagine que você tem uma política de senhas, você poderia validar esta politica antes de ir diretamente no banco de dados e ainda aproveitar a mesma regra no seu cadastro de usuários.
Comment: Concordo que se não comprometer a segurança de um banco de dados, jogar o trabalho para o lado do cliente(alguns casos) pouparia o servidor de fazer trabalhos extras(como repetir o mesmo processo). Não entendo porquê a galera insiste em dizer consistentemente(sem exceção) que deve-se se verificar de ambos os lados. Cada caso é um caso, como SneepS disse, e eu concordo,  "Então a questão de validar do lado do server ou do lado do cliente, vai depender do que esta validando, se for alguma coisa que não vá comprometer a segurança de um banco de dados"
Comment: @Edilson completando o NodeJs é um framework sim que fica do lado do servidor, e usa a linguagem javascript ;)
Comment: @SneepSNinjA não vai logar mesmo, concordo. O que eu estou querendo destacar aqui é um "requisito" do seu software que você só checou na criação do login, mas não está checando no momento do logon. Eu mesmo confesso que já fiz métodos de logons em que não valido formato de e-mail por exemplo como você mesmo justificou, mas não é certo, estamos burlando o requisito do formato do e-mail, neste caso, deveriamos lançar um exceção ou e sair do fluxo principal (neste caso, economizando uma ida ao recurso que valida os dados providos).
Comment: Acho que estou partindo para o offtopic, mas se concentrando na resposta do autor da pergunta, os dados SEMPRE devem ser validados no servidor, e o que for interessante para aumentar a experiencia do usuário, deve ser validado do lado do cliente.
Comment: Exato, há pontos para abordar do lado do servidor(como tratar os dados via POST(evitar sql injection)), e outros que no caso se julgue necessário, mas nada mais, código mais limpo e mais útil, enfim.. minha opinião pelo que vejo e consigo analisar dos usuários.. Obrigado pela Resposta SneepS NinjA, nodeJS realmente é interessante, vou ler mais sobre quando sobrar algum tempo!

Usar JS para aliviar PHP


How to compare contingency tables for a specific pattern?

Question: I have a a series of contingency tables, like:
<code>    A   B
  |----|----|
C | 0  | 10 |
D | 17 | 2  |
</code>
and I need a numerical value to select and order those tables where:

(C,A) tends to 0, is much smaller than (C,B)
(D,B) tends to 0, is much smaller than (D,A)
(C,B) and (D,A) are > 0, the bigger the better

It doesn't matter if the total of the first row is bigger than the total of the second row.
Example: this table
<code>    A   B
  |----|----|
C | 12 | 41 |
D | 72 | 0  |
</code>
is good, and this table
<code>    A   B
  |-----|-----|
C | 178 | 100 |
D | 266 |   1 |
</code>
is still OK-ish, but should be ranked lower than the other one. The first row is clearly bad, but the second row makes up for it.
EDIT:
After John's answer, I've plotted the data ordered by three "measures of fit", to compare my two measures against John's.

Inverse of Matthews Correlation Coefficient (MCC): a "perfect table" as defined above would produce an MCC of -1, while switching columns would provide "1". So doing -MCC and filtering out all values < 0 gives a good filtering/sorting index, and scales nicely between [0, 1].
Error Rate Difference: proportion of (C,B) on the first row minus proportion of (D,B) on the second row. A value of 1 means that (C,A) and (D,B) are equal to 0. Scales nicely between [0, 1].
John's fitting expression: doesn't fit into [0, 1], but models the constraints literally.

Here are the plots:
Comment: This looks like two questions so it's broader than is usually desired here (moreso than you realize). Edit this so that it's just about how to solve your fitting problem. If, after you get an answer you still want to ask about p-values as measures of fit then do that after. And also edit the problem because there's lots of superfluous information that's in some ways a little misleading. All you need is the contingency table and the statement A >> B is good but it must have z >> 0. That would satisfy the whole thing I think. Could x be small? Anyway, be clearer on what you need to fit.
Comment: I've tried to shorten it as much as I can. Thanks for the tip.
Comment: I thought before you also said that A should be larger than B.
Comment: In the original answer I spoke of both "good tables" and "bad tables", and differentiated the cases. This got a bit confusing. The ones respecting the property A >> B are "perfectly good" tables - but I'm not looking for those.

In the above, there is no ambiguity: those tables are the ones I need to identify and order by "extremeness", following the pattern I specified.

I hope it's clearer. Thanks.
Comment: Your original two measures don't take into account your third condition (two cells greater than 0). As far as I can see they only take into account the proportion on a row which would cover the first two conditions. My formula includes the third condition. You need to decide on the importance of that. And further, artificially constraining your measurements between 0 and 1 is almost never a good idea. Have you really thought about why you're doing that?
Comment: You're going to have to figure out the distribution of scores for whatever measurement and a constrained one will have tail issues and maybe not allow some math (e.g. correlations don't add). It would be nice to have probability density plots. If I was you I'd next compare ranks of the measures and see if what measure coincides with how you interpret good and bad patterns. (and given your figures probably do stats on the ranks in any event)
Comment: True, I'm being ambiguous about the third condition. It was in fact one of the sub-questions in the original question: how do I take _effect size_ into account in a statistically sound way?

Your formula does include that, but I cannot use current research for the cutoff threshold.

For example, with fisher test I could use a "reasonable" p < 0.05. With MCC, I can use Pearson's correlation "reasonable values", such as > 0.4 is a moderate correlation. ERD is highly (linearly) correlated to MCC (0.95 r) so I could use the same.

With an hand-crafted method, how do I choose a cut-off threshold?
Comment: Also, MCC for example is described as giving a much more equilibrated value (respect to other 2x2 table statistics) regarding to the two rows, and seems to especially work well with classes of different size. At least in the few references I've seen it used.
Answer: Your original suggestion to use p-values was problematic in a number of ways. The biggest one is probably that they're dependent upon N such that a table with a small number of values but very well fit what you desire would have a higher p-value than one that had more values but didn't fit nearly so well.
How about just using the requirements you set out as the measure? The function below just turns your list of requirements into a simple equation. The numerator can be larger than the denominator but only when the requirements are strongly met. I don't think this is going to be too dependent on N but you should try and see what it looks like. Check the distribution of values and see if it's reasonable.
You might also note that I flattened your matrices. The indexes I used will match the matrices and this will function with a matrix or a vector. So if you already have all of the tables as matrices this would work just fine.
<code>good <- c(12, 72, 41, 0)
ok <- c(178, 266, 100, 1)
bad <- c(178, 26, 100, 40)

myStat <- function(y){
    ( (y[3] - y[1]) +  (y[2] - y[4]) + y[2] + y[3] ) / sum(y)
    }

myStat(ok)
myStat(good)
myStat(bad)
</code>
When I generate some random binomial data I get a normal distribution centred on 0.5 which makes sense if you look at the equation carefully. If your criteria are correct high scores will be "good" matrices and low score "bad". Now that you've got normally distributed values you can pick one of many stats to analyze them. But even if they're not normal there are still a variety of options either non-parametric or one that models the observed distribution.
Comment: Thanks for the input. I am already using two other formulas but can't decide on one: Fisher's has the advantage of being an exact test and widely used in the literature (although recently I've seen many papers contesting its use).

I've updated the question with the other two measures I'm using, and I've plotted my data by ordering it by each of them in turn.

It seems to me that the ERD is very conservative, MCC is more loose, and the fitness function you provided is difficult to compare because it's not between [0, 1].


statistical tests for average data

Question: I'm working on visualising for some data set. I was going to run some statistical tests on the data set, but I'm not sure if I can run some tests or not. I'm sorry that I cannot put the data set here.
Basically, the data set is a csv file. And all the data in the file is an average value. I wonder if I can run a statistical test, such as ANOVA (or making a correlation matrix), for this data where all the inputs are average values.
Thank you!
Answer: If you have sample sizes and standard deviations as well as the means then you should be able to do Anova. But I get the feeling that you only have the mean
Comment: I only have the means and the population sizes. I don't have any other information. So can I not use any statistical tests? Also can I not use a correlation matrix either?
Comment: Without the standard deviation, you have no measure of spread which a lot of statistical tests rely on. For a correlation matrix, you would definitely need the raw data. Sorry.

statistical tests for average data


Habilitar evento do button ao pressionar tecla no teclado

Question: Estou desenvolvendo uma calculadora, e necessito de quando o usuário apertar a tecla enter repasse como se ele estivesse apertando a tecla igual.
A calculadora está dentro de um  form, então utilizo este código para desabilitar o Post do form.

E para clicar no button de igual, tentei fazer utilizando este código:
$(document).ready(function() {
        $('input').keypress(function(e) {
            if (code == 13) {
                $('#calculate').click();
            }
            return;
        });
    });

Segue abaixo o código completo:

//Desabilita a função Post do form
$(document).ready(function() {
            $('input').keypress(function(e) {
                var code = null;
                code = (e.keyCode ? e.keyCode : e.which);
                return (code == 13) ? false : true;
            });
        });

//Evento click no botao
 $(document).ready(function() {
        $('input').keypress(function(e) {
            if (code == 13) {
                $('#calculate').click();
            }
            return;
        });
    });

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

<form name="myform">

                                          <input type="text" name="display" size="20" class="form-control" />

                                <input type="button" name="clear" value="   C   " class="btn btn-danger"
                                       onclick="myform.display.value=''" onmouseover="window.status='Limpar'" onmouseout="window.status=''" />

                            <input type="button" name="seven" value="   7   " class="btn btn-default"
                                   onclick="myform.display.value+='7'" />

                            <input type="button" name="eight" value="   8   " class="btn btn-default"
                                   onclick="myform.display.value+='8'" />

                            <input type="button" name="nine" value="   9   " class="btn btn-default"
                                   onclick="myform.display.value+='9'" />

                                <input type="button" name="divide" value="÷" class="btn btn-default"
                                       onclick="myform.display.value+='/'" />

                            <input type="button" name="four" value="   4   " class="btn btn-default"
                                   onclick="myform.display.value+='4'" />

                            <input type="button" name="five" value="   5   " class="btn btn-default"
                                   onclick="myform.display.value+='5'" />

                            <input type="button" name="six" value="   6   " class="btn btn-default"
                                   onclick="myform.display.value+='6'" />

                                <input type="button" name="times" value="X" class="btn btn-default"
                                       onclick="myform.display.value+='*'" />

                            <input type="button" name="one" value="   1   " class="btn btn-default"
                                   onclick="myform.display.value +='1'" />

                            <input type="button" name="two" value="   2   " class="btn btn-default"
                                   onclick="myform.display.value +='2'" />

                            <input type="button" name="three" value="   3   " class="btn btn-default"
                                   onclick="myform.display.value +='3'" />

                                <input type="button" name="minus" value="–" class="btn btn-default"
                                       onclick="myform.display.value+='-'" />

                            <input type="button" name="zero" value="   0   " class="btn btn-default"
                                   onclick="myform.display.value+='0'" />

                            <input type="button" name="plus" value="   +   " class="btn btn-default"
                                   onclick="myform.display.value +='+'" />

                                <input type="button" name="calculate" value="   =   " class="btn btn-default"
                                       onclick="myform.display.value=eval(myform.display.value)" />

</form>

E segue um Exemplo no JsFiddle, para quem prefere.
Answer: Usa o e.which em vêz do e.code (e repara que no teu jsFiddle dá erro porque tens só code ==), a própria documentação do jQuery sugere isso. E depois podes chamar diretamente: myform.display.value=eval(myform.display.value);
Asim a mudança que tens de fazer é para
$('input').keypress(function (e) {
    if (e.which == 13) myform.display.value = eval(myform.display.value);

jsFiddle: http://jsfiddle.net/LLsx4pqL/
Answer: Você pode também usar a função .trigger() para disparar um evento de click no botão de calcular ao pressionar enter:
$('input').keypress(function(e) {
            if (e.keyCode == 13) {
                $('input[name="calculate"]').trigger('click');
            }
}

JSFiddle


How to compress a file (gzip) using boost libraries in C++

Question: Im trying to compress a file using boost library (gzip).
Its a simple task: lets suppose i have the file data.xml and I need to compress it to data.xml.gz. I can even use the default compression values, doesn't matter.
I tryed to look up in google and BOOST pages but with no success.
I have the following:
bool SyncFrequencyHistory::frequencyHistoryCompressFile(void)
{
    printf("\r\n===== ACTION: frequencyHistoryCompressFile =====\r\n");

    std::ifstream inStream(FREQUENCY_HISTORY_FILE, std::ios_base::in);
    std::ofstream outStream(FREQUENCY_HISTORY_FILE_GZIP, std::ios_base::out);
    boost::iostreams::filtering_streambuf<boost::iostreams::output> out;
    out.push(boost::iostreams::gzip_compressor());
    out.push(outStream);
    boost::iostreams::copy(in, out);

    return true;
}

FREQUENCY_HISTORY_FILE have the full location of the XML file
FREQUENCY_HISTORY_FILE_GZIP have the full location for the XML.GZ file
I know almost all code is wrong, but i have no idea who to write it the correct way.
Comment: Is running gzip as an external command not an option?
Comment: What happens when you run this?
Answer: Based on the following tutorial, I believe your code should be:
bool SyncFrequencyHistory::frequencyHistoryCompressFile(void)
{
    printf("\r\n===== ACTION: frequencyHistoryCompressFile =====\r\n");

    std::ifstream inStream(FREQUENCY_HISTORY_FILE, std::ios_base::in);
    std::ofstream outStream(FREQUENCY_HISTORY_FILE_GZIP, std::ios_base::out);
    boost::iostreams::filtering_streambuf< boost::iostreams::input> in;
    in.push( boost::iostreams::gzip_compressor());
    in.push( inStream );
    boost::iostreams::copy(in, outStream);

    return true;
}

Basically, you read the input, compress it and saves the dat
Comment: Thanks! Im going to try it :)
Comment: This code will create a zip file with data compressed, not as file compressed.
Answer: I already solved it! I changed to ZLIB library.
#include <zlib.h>

(...)

gzFile fi = gzopen(FILENAME,"wb");
gzprintf(fi,"This is a string"\r\n");
gzclose(fi);

Answer: This code works, you just need to specify binary type for the output stream: std::ios_base::binary.


Minimizing geodesic distance on cylindrical manifold

Question: I will try to explain my question via a trivial analogy.
Let $a$,$b$ be two points in 2D Euclidean space. I would like to make point $a$ closer and close to $b$. Let $L=||a-b||^2=(a_x-b_x)^2+(a_y-b_y)^2$, where $a_x$ is the x-coordinate of $a$ and so on. Then, minimizing w.r.t $a$ we have
$$L_x=\partial_x ||a-b||^2 = 2(a_x-b_x) $$
$$L_y=\partial_y ||a-b||^2 = 2(a_y-b_y) $$
and overall we can use gradient descent to obtain $$a_x := a_x - \alpha L_x $$
$$a_y := a_y - \alpha L_y $$
Eventually we will obtain $a=b$.
Now on to my question. Assume instead that $a,b$ lie on a manifold that's a a cylinder (without its interior, a cylinder with a fixed radius), i.e. $a=(a_\theta, a_h)$ where $a_\theta$ is the angle and $a_h$ is the height. How can I 'walk' or advance using a gradient-descend-type flow from point $a$ to point $b$? I think the curve should be the geodesic connecting the two points, but I'm not sure how to formulate the scheme correctly.
Thanks.
Answer: A curve $c(t)$, parametrised by arc length, on an oriented surface is a geodesic if and only if its acceleration vector $\ddot{c}(t)$ is normal to the surface. See differential geometry of surfaces - Wikipedia.
From there, you'll be able to prove that a curve joining the two points with minimal length is the smallest helix joining the two points.


React Jest Test Warning When More Than 1 Test

Question: I am getting a weird warning when I use more than 1 test.
When I use this test.
  it("should render default values", () => {
    render(
      <UserContext.Provider
        value={{
          userAuth: {
            profileId: 1,
            currentOrgId: 1,
            currentPrivileges: {}
          }
        }}
      >
        <SocialPostEdit
          id={elementId}
          socialPost={postContent}
          name={elementName}
        />
      </UserContext.Provider>
    );
  });

I get no warnings. When I duplicate it. Like this
 it("should render default values", () => {
    render(
      <UserContext.Provider
        value={{
          userAuth: {
            profileId: 1,
            currentOrgId: 1,
            currentPrivileges: {}
          }
        }}
      >
        <SocialPostEdit
          id={elementId}
          socialPost={postContent}
          name={elementName}
        />
      </UserContext.Provider>
    );
  });
 it("should render default values 1", () => {
    render(
      <UserContext.Provider
        value={{
          userAuth: {
            profileId: 1,
            currentOrgId: 1,
            currentPrivileges: {}
          }
        }}
      >
        <SocialPostEdit
          id={elementId}
          socialPost={postContent}
          name={elementName}
        />
      </UserContext.Provider>
    );
  });

I get this error
 Warning: An update to SocialPostForm inside a test was not wrapped in act(...).

      When testing, code that causes React state updates should be wrapped into act(...):

      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

The weird thing is why if I keep 1 test it works and if I add more than 1 it gives me warning?
Answer: The error message is correct, you need to wrap calls to render in act() as the documentation calls out:
 import { act } from 'react-dom/test-utils';

 it("should render default values 1", () => {
    act(() => {
      render(
        <UserContext.Provider
          value={{
            userAuth: {
              profileId: 1,
              currentOrgId: 1,
              currentPrivileges: {}
            }
          }}
        >
          <SocialPostEdit
            id={elementId}
            socialPost={postContent}
            name={elementName}
          />
        </UserContext.Provider>
      );
    });
  });

Comment: Same Error When I Add it. Also why with one tests I don't get any warnings.
Comment: Every call to `ReactDOM.render` needs to be wrapped in `act`. Did you do it for all of your tests?
Comment: Yeah. When I put the same test twice I get that warning. Both tests with act. I am not getting why on two tests it produces that warning. Should I cleanup then render tree?
Comment: Can you paste more of your code? What did you change, and what does it look like now?


Can this type of U-substitution work?

Question: Definite Integral of $(3x+1)^{\sqrt{2}}$ with lower and upper bounds being 1 to 4, respectively. I know that commencing a u-sub with $u = 3x+1$ is a nice way to approach this problem, but I believe that a u-sub with $u = (3x+1)^{\sqrt{2}} can still work. I have have not yet been able to reach the right answer, however.
Here is my work:
$\int_{1}^{4}(3x+1)^{\sqrt{2}} dx$
$u = (3x+1)^{\sqrt{2}}$
$du = \sqrt{2}(3x+1)^{\sqrt{2}- 1}  3 dx$
I ultimately end up with:
$\frac{1}{3*\sqrt{2}}$(integral sign with bounds 1 to 4) $u^{\sqrt{2}}$
and I notice, from the solutions I have seen, that having the $\frac{1}{\sqrt{2}}$ constant is where I messed up but I cannot see where I went wrong. Please help!
Comment: Oh dear. Please take a look at the MathJax tutorial so we can read your question. You have some of it right, but enclose the formatting in dollar signs!
Answer: $$\int_{1}^{4}(3x+1)^{\sqrt{2}}\ dx$$
Apply u-substitution $u=3x+1$ and we get$$\implies\dfrac13\int u^{\sqrt{2}}\ du=\dfrac13\cdot \dfrac{(3x+1)^{\sqrt{2}+1}}{\sqrt{2}+1}=\dfrac{\sqrt{2}-1}{3}(3x+1)^{\sqrt{2}+1}$$
So, we got $\int(3x+1)^{\sqrt{2}}\ dx=\dfrac{\sqrt{2}-1}{3}(3x+1)^{\sqrt{2}+1}$
Now apply the bounds and we get $$\int_{1}^{4}(3x+1)^{\sqrt{2}}\ dx=\left[\dfrac{\sqrt{2}-1}{3}(3x+1)^{\sqrt{2}+1}\right]_{1}^{4}=\dfrac{\sqrt{2}\cdot13^{\sqrt{2}+1}-13^{\sqrt{2}+1}-2^{2\sqrt{2}+\frac52}+4^{\sqrt{2}+1}}{3}$$

Can this type of U-substitution work?


Div com mesma altura de imagem no Bootstrap

Question: Tenho uma imagem a esquerda e outros 4 blocos a direita. Precisava que as quatro blocos seguissem a altura da imagem, mesmo ao mudar a resolução.

HTML:

Título

Lorem ipsum dolor sit amet.

Título

Lorem ipsum dolor sit amet.

Título

Lorem ipsum dolor sit amet.

Título

Lorem ipsum dolor sit amet.

CSS:
.img-container {
    padding: 0;
}

.container-painel {
   padding: 0;
}

.painel1 {
   padding: 0;
   border-bottom: 1px solid #333333;
   border-right: 1px solid #333333;
}

.painel2 {
   padding: 0;
   border-bottom: 1px solid #333333;
   border-right: 1px solid #333333;
}

.painel3 {
    padding: 0;
    border-right: 1px solid #333333;
}

.painel4 {
   padding: 0;
   border-right: 1px solid #333333;
}

Comment: Acho que se você não utilizar um pré-processador css como LESS ou SASS não vai funcionar. Estou tentando ver uma forma de fazer isso sem JavaScript, más esta meio difícil kkkk'
Se quiser aqui tem uma solução simples com Jquery (Se quiser responsivo só colocar dentro de um "onresize" que ele funciona normalmente)
https://codepen.io/anon/pen/dRrzKB
Answer: O que foi feito
Adicionei uma nova classe adapta em todos os 4 elementos (painel1,painel2,painel3,painel4).
Dessa forma é possível manipular todos ao mesmo tempo utilizando Jquery.
Criei a função adapta() para sempre que a página for carregada ou redimensionada ela entre em ação.
Lógica da função adapta()
Pegamos o height da imagem que está a esquerda, depois é só dividir por 2 e atribuir esse valor na height da classe adapta para que todas as div's a direita ocupem o height idêntico ao da imagem a esquerda.
$(document).ready(adapta);
$(document).on('resize', adapta);

function adapta()
{
  var altura = $('.img-responsive').css('height');

  var alturaF = altura.split('px');

 // alert(alturaF[0]/2);

  $('.adapta').css('height', alturaF[0]/2+'px');

};

Lembre-se de inserir a classe adapta aos paineis no html.
Comment: Acabei conseguindo fazer somente com css definindo uma altura para o container e inserindo a imagem através do css com background-image. Mas vou ficar com sua resposta para outras situações.


$\mathrm{Οut}(G) = [BG, BG]$?

Question: Let $G$ be a finite group and $BG$ its classifying space. Let $[BG, BG]$ denote the set of self-maps of $BG$ up to homotopy equivalence. Automorphisms of $G$ give such self-maps, and inner automorphisms are homotopy equivalent to the identity. I am looking for an answer, hopefully with a reference if positive, to the following question:

Is it true that $\mathrm{Aut}(G)/\mathrm{Inn}(G) \equiv [BG, BG]$?
Answer: Presumably you want all group endomorphisms of $G$, instead of just automorphisms.  Then it is true that if $G$ and $H$ are finite groups, then $$[BG, BH] \cong \operatorname{Hom}(G,H)/\operatorname{Inn}(H).$$
This is mentioned in Martino's Classifying spaces and their maps [MR1349123], where this result is attributed to Hurewicz.
Answer: The answer's no : take any nontrivial $G$ for which $Out(G) = 1$, e.g. $G=\mathbb{Z/2}$ or $\mathfrak{S}_n, n \neq 6$.
Then the isomorphism would imply $[BG,BG] = 1$, which would imply that the identity map is nullhomotopic, in other words $BG$ would be contractible, which is of course absurd.

$\mathrm{Οut}(G) = [BG, BG]$?


Unable to do code Code first Migration when deployed to azure web role

Question: When I deploy my application to Azure Web role, I expect code first migration to run, and unfortunately that doesn't happen.  When I run the application in the emulator, the code first migration happens fluently & I do not encounter any issues.
I have custom ClaimsAuthenticationManager, and that where EFF context is called first. I wonder if context is not available there.
I am using lastest MVC, with Azure SDK 2.4, & Eff 6.1.
Thanks
Answer: EF does not run migrations when deploying to SQL Azure, instead, if you check the appropriate option, a section should be added to the web.config that would register MigrateDatabaseToLastetVersion initializer, that should update your db first time you are using it. This is not the experience you are seeing?


How to escape accent letters in knit (R markdown)

Question: I'm trying to escape accent letters in knit like "ù". I use this letter inline, like in this exemple:
df$comune <- ifelse(df$comune == "carru'", "carrù", df$comune).
The result is

You can see the last letter is not rendered properly and it stops rendering.
Thanks in advance for the help!
I tried:

backslash (\)
use backticks + backslash (`\)
html encode char (ù)

edit:
I'm using the function for write r code and markdown on Rstudio.
You need to use ``` to open the section where you write code and again ``` to close it. When in this part i use "ù" (like in the photo) the function knit stops to render the html page
Comment: I cannot replicate your problem. Can you provide more information?
Comment: Doesnt it work when you remove the '? As in "carru" instead of "carru'"?
Comment: the ' is not a problem, with it or without the result don't change
Answer: Resolved!
The problem was the encoding setted on RSTudio. Must set UTF-8


Vmware ESXi change datastore to SSD

Question: I've been trying to reconfigure vmware to recognize a datastore as SSD strorage.  I've found several articles regarding this:
VmwareKB, Virtually Ghetto, Storage Monk.  However i'm running into issues:
When I run:
esxcli storage nmp satp rule add --satp SATP --device naa.6842b2b02599aa00181935940bbfce4c --option "enable_ssd"

I get the error:
Error: Invalid option enable_ssd

If I run
esxcli storage nmp satp rule add --satp SATP --device naa.6842b2b02599aa00181935940bbfce4c --option "enable_ssd"

I get the error:
Plugin 'SATP' is not a registered SATP. Please select a plugin from the list in
'esxcli storage core plugin registration list -N SATP' or use the --force option
 to force the use of this SATP.

I attempted to use the --force command and can see the rule if I run
~ # esxcli storage nmp satp rule list | grep enable_ssd
SATP                 naa.6842b2b02599aa00181935940bbfce4c                                                  enable_ssd                  user

However the datastore is still coming up as non-ssd.  Any ideas or easier ways to accomplish this ?  Thanks

Edit Output of esxcli storage nmp device list
naa.6842b2b02599aa00181935940bbfce4c
   Device Display Name: Local DELL Disk (naa.6842b2b02599aa00181935940bbfce4c)
   Storage Array Type: VMW_SATP_LOCAL
   Storage Array Type Device Config: SATP VMW_SATP_LOCAL does not support device configuration.
   Path Selection Policy: VMW_PSP_FIXED
   Path Selection Policy Device Config: {preferred=vmhba1:C2:T0:L0;current=vmhba1:C2:T0:L0}
   Path Selection Policy Device Custom Config:
   Working Paths: vmhba1:C2:T0:L0
   Is Local SAS Device: false
   Is Boot USB Device: false
~ # naa.6842b2b02599aa00181935940bbfce4c

Comment: In the examples 'SATP' is just a variable that is to be replaced by the real SATP value (e.g. VMW_SATP_CX), and this is displayed by "esxcli storage nmp device list". What is the output of this command on your host?
Comment: @VFrontDe See Edit
Answer: Since this is probably a small local installation, did you follow the last step in the VMware KB article?
You must reboot the ESXi host to tag the local datastore (if ESXi is installed locally) as the SSD drive.
Comment: See the [comment on your question](http://serverfault.com/questions/543658/vmware-esxi-change-datastore-to-ssd#comment626604_543658). The example you used possibly has different values than your system's values.
Comment: did try a reboot to no avail
Answer: You are meant to replace SATP with the SATP of the device as displayed in the Storage Array Type field - in this case VMW_SATP_LOCAL.  The directions aren't the clearest.
The following should work for you: esxcli storage nmp satp rule add --satp VMW_SATP_LOCAL --device naa.6842b2b02599aa00181935940bbfce4c --option=enable_ssd

Vmware ESXi change datastore to SSD


How to find the probabilities that maximize the standard deviation?

Question: Consider the problem: "one dice has three faces $1,2,3$ with probabilities $p_1,p_2,p_3$ and it is thrown many times with a mean value $a$. What are the values for $p_1,p_2,p_3$ which maximizes the uncertainty consistent with the mean value $a$?"
Here I believe uncertainty should be understood as standard deviation.
So, the experiment for a single such dice being thrown has outcomes described by the random variable $X$ taking values on $\{1,2,3\}$ with probabilites $p_1,p_2,p_3$ respectively.
I believe that it all boils down to maximizing
$$\sigma^2(p_1,p_2,p_3)=E[X^2](p_1,p_2,p_3)-E[X]^2(p_1,p_2,p_3)$$
subject to the constraints
$$g(p_1,p_2,p_3)=p_1+p_2+p_3=1\quad h(p_1,p_2,p_3)=E[X](p_1,p_2,p_3)=p_1+2p_2+3p_3=a.$$
Thus it seems we should use Lagrange multipliers and solve
$$\nabla \sigma^2=\lambda \nabla g+\mu\nabla h,\\ g(p_1,p_2,p_3)=1, \\ h(p_1,p_2,p_3)=a.$$
Furthermore, it is clear that we have
$$\dfrac{\partial}{\partial p_i}E[f(X)]=\dfrac{\partial}{\partial p_i}\sum_j f(x_j)p_j=f(x_i).$$
so that we have
$$\nabla \sigma^2(p_1,p_2,p_3)=(1-2E[X],4-4E[X],9-6E[X]).$$
Thus we have the system of equations
$$\begin{cases}1-2E[X]&=\lambda+\mu \\ 4-4E[X]&=\lambda+2\mu\\ 9-6E[X]&=\lambda+3\mu\\ p_1+2p_2+3p_3&= a \\ p_1+p_2+p_3&= 1.\end{cases}$$
The fourth equation imposes $E[X]=a$. Hence substituting it on the first and second we can find $\mu = 3-2a$ and $\lambda = -2$.
But now this ought to be wrong. If I substitute this on the third equation I get $$9-6E[X]=-2+9-6a\Longleftrightarrow 6E[X]=6a+2$$
which is incompatible with the fourth equation which tells that $E[X]=a$.
So this method doesn't work. What am I doing wrong here? What is the right way to solve this problem?
Comment: You need a specific definition of 'uncertainty'. Because you are talking about choices of $p_i$ to do that, you must mean 'uncertainty' in the population, not the sample. // If one of the $p_1 = 1$ and the rest are all $0,$ then $\sigma = 0.$ For most purposes, I guess best to have all $p_i$ equal. For example, binomial variance $p(1-p)$ is max if $p = 1/2.$ // Maybe you would get useful ideas from Wikipedia article on 'diversity indexes'.
Comment: The conditions you derived for $p_i$'s are actually for *unconditional* interior extrema, whereas here it should be a conditional one subject to $\sum p_i=1$, $\sum c_ip_i=\frac aN$, and $0\leqslant p_i\leqslant1$. The minimum is acheived at boundary points.
Comment: I don't understand what is the meaning of "maximizes the uncertainty".
Comment: @FelixMarin I found this problem in one Statistical Physics lecture notes. If I'm not mistaken (that's at least how I'm interpreting it), by uncertainty they mean the standard deviation. So that: one experiment whose outcomes are described by the random variable $X$ is repeated a large number of times, and the values summed. One wants to find the probability distribution for the values of $X$ which maximizes the standard deviation of the combined experiment, compatible with the mean value of said combined experiment being a given value $a$.
Comment: @user1620696 Thanks. Now, I got the whole idea.
Comment: @AlexFrancisco so the point is that I should use Lagrange multipliers? Thus I should set $f(p_i) = \sigma^2(p_i)$, $g(p_i) = \sum p_i$, $h(p_i) = \sum c_i p_i$ and then solve $\nabla f = \lambda \nabla g + \mu \nabla h$ with $g(p_i) = 1$ and $h(p_i) = a/N$?
Comment: @user1620696 Probably of littile use to use multipliers because $\sum c_k^2p_k$ can be seen as a quantity proportional to the distance of a $(n-1)$-dimensional hyperplane from the origin, thus its maximum is acheived at boundary points given those two constraints. However, multipliers only give interior extremum points.
Comment: @AlexFrancisco, actually the multipliers method didn't work (it could be some mistake on carrying it out, but I didn't find it). You said that the maximum is achieved at boundary points. You mean the boundary of the box $[0,p_1]\times [0,p_2]\times[0,p_3]\subset \mathbb{R}^3$? But that would mean that one of the $p_i$ is zero, right? I think I didn't understand, because this wouldn't make sense for me.
Answer: In this particular example of three variables $p_i$, $i=1,2,3$, we can solve this explicitly as a linear problem. More general cases where $i=1,2,\ldots,n$ most likely will not succumb to such a simple approach.
We assume the scenario as given above, in which a random variable $X$ takes values $1,\,2,\,3$ with associated probabilities $p_1,\,p_2,\,p_3$.

In your question you wish to consider the probabilities such that:

The sum of $N$ independent samples has average $\alpha$.
The sum has maximal variance.

We note that since variances of independent samples are linear, we have
$$ \text{Var}(X_1 + \cdots + X_N) = N\text{Var}(X_1),$$
from which it follows that it suffices to answer the question: find the probabilities such that

The mean of $X$ equals $\alpha / N$.
$X$ has maximal variance.

That is: we can solve the question by considering just a single $X$; henceforth we drop the dependence on $N$, since this is an arbitrary constant, so just ask to find the $X$ with mean $\alpha$ and maximal variance.

We want that the mean is equal to some given value $\alpha \in [1,3]$ (noting that it is not possible for $\alpha$ to be outside of this interval, given that $X \in \{1,2,3\}$). Then we have
$$\mathbf E[X] = p_1 + 2p_2 + 3p_3 = \alpha,$$
and moreover we have the following constraints
\begin{align*}
p_1+ p_2 +p_3 & = 1, \\
0 \leq p_1 & \leq 1 ,\\
0 \leq p_2 & \leq 1 ,\\
0 \leq p_3 & \leq 1. \\
\end{align*}
Using the first constraint, and the expression for the expectation above we see that both $p_2$ and $p_3$ can be expressed in terms of $p_1,\, \alpha$
\begin{align*}
p_2 & = (3-\alpha) - 2p_1, \\
p_3 & = (\alpha -2) + p_1.
\end{align*}
Not all combinations $(p_1,\,p_2,\,p_3)$ generated in this way form valid probability distributions: for this we will rely on the remaining constraints: $0 \leq p_i \leq 1$, $i=1,2,3$. Reformulating each of these in terms of $p_1$ leads to
\begin{align*}
0 & \leq p_1  \leq 1. \\
1 - \frac12\alpha & \leq p_1  \leq \frac32 - \frac12\alpha, \\
2 - \alpha & \leq p_1 \leq 3 - \alpha.
\end{align*}
Depending on the value of $\alpha$ many of these constraints will be redundant (eg. for the second inequality, if $\alpha = 3$ then clearly the left hand side is less than $0$, which is already ruled out by the first constraint).
But most importantly, we have found a description of the system using only a single variable (since $\alpha$ is constant), and with the single (non-linear) constraint
$$\max \left( 0, \,1-\frac12 \alpha, \, 2- \alpha \right) \leq p_1 \leq \min\left(1, \, \frac32 - \frac12 \alpha, 3 - \alpha \right).$$
In fact on checking cases, we note that this simplifies to
$$\max \left( 0, \, 2- \alpha \right) \leq p_1 \leq \frac32 - \frac12 \alpha.$$

Turning to the uncertainty, which you describe as being the standard deviation, we note that maximizing this is equivalent to maximizing variance; moreover the variance is given to be
\begin{align*}
\text{Var}(X) & = \mathbf E[X^2] - \mathbf E[X]^2 \\
& = \mathbf E[X^2] - \alpha^2 \\
& = \left(p_1 + 4 p_2 + 9p_3\right) - \alpha^2 \\
& = p_1 + 4 \big( (3-\alpha) -2p_1\big) + 9 \big( (\alpha -2 ) + p_1 \big) - \alpha^2\\
& = 2p_1 - 6 + 5\alpha - \alpha^2.
\end{align*}
We see immediately without taking derivatives that the variance is linear (and increasing) in $p_1$, and therefore has its maximum at the largest feasible value of $p_1$.
That is, the maximal variance random variable $X \in \{1,2,3\}$ with mean $\mathbf E[X] = \alpha$ is determined by:
$$p_1  = \frac32 - \frac12 \alpha, \qquad
p_2  = 0,\qquad
p_3  = \frac12 \alpha - \frac12.
$$
In particular we see that for any $\alpha \in [1,3]$ the solution is always has $p_2 = 0$.
In terms of standard distributions, we see that for fixed $\alpha \in[1,3]$ the maximal variance $X$ is given by
$$X = 1 + 2 Y, \qquad Y \sim \text{Ber}\left( \frac12(\alpha-1) \right).$$

As a final addition, though not strictly a part of the question, we note that from this we can also see that the distribution with maximal variance  on $\{1,2,3\}$, is given by the case $X = 1 + 2\text{Ber}(1/2)$.
To see this we note that if $Y \sim \text{Ber}(q)$ for some $0 \leq q \leq 1$, then  $X = 1 + 2 Y$ has the same variance as $Y$, and moreover this is
$$\text{Var}(X) = \text{Var}(Y) = q(1-q),$$
and in particular this is maximized at $q = 1/2$, which is equivalent to $\alpha =2$.


Cross class communication using protocols

Question: In my app I am using 3 classes MasterViewController, DeviceViewController, and BRButton. The BRButton class does all of the real work, and has the hardware delegate callbacks in it for bluetooth 4.0 devices. I am trying to get methods to fire in the other classes when something happens in BRButton. This is working in DeviceViewController, but not in MasterViewController, I'm still pretty green with IOS programing any help is appreciated. Here is some code snippets.
One more thing I should mention is it doesn't error, it just doesn't call the method.
BRButton.h
<code>@protocol RefreshScreen
-(void) tableTimer:(NSTimer *)timer;
@end

@protocol BRButtonDelegate
@optional
-(void) bounceBack;
-(void) tableTimer:(NSTimer *)timer;
@required
-(void) buttonReady;
@end

@interface BRButton : NSObject <CBCentralManagerDelegate, CBPeripheralDelegate> {
    NSTimer *myTimer;
}

@property (nonatomic,assign) id <BRButtonDelegate> delegate;
@property (nonatomic,assign) id <RefreshScreen> testCall;
</code>
BRButton.m (here is 2 different places I call something in a different class. First one doesn't work the second does.)
<code>- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    ...does some work then...
        [[self testCall] tableTimer:nil];  //tableTimer is nil here because no NStimer is used to trigger from this delegate method.
        printf("New UUID, adding\r\n");

    printf("didDiscoverPeripheral\r\n");
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    printf("Disconnecting \r\n");
    [[self delegate] bounceBack];
}
</code>
MasterViewController.h
<code>@interface MasterViewController : UIViewController < UITableViewDelegate, UITableViewDataSource, RefreshScreen> {
    BRButton *b;
}
</code>
MasterViewController.m  (I would expect this to be called after my break point on didDiscoverPeripheral, but it never is.)
<code>-(void) tableTimer:(NSTimer *)timer {
    if(b.peripherals.count > 0)
    {
        [self.deviceTableView reloadData];
    }
}
</code>
DeviceViewController.h
<code>@interface DeviceViewController : UIViewController <BRButtonDelegate> {
}
@property (strong, nonatomic) BRButton *bb;
</code>
DeviceViewController.m
<code>- (void) bounceBack {
    [self.navigationController popViewControllerAnimated:YES];
}
</code>
If you need anymore information let me know.
Comment: Could you show where you're setting the delegate and the "testCall"? Use a breakpoint and make sure it isn't nil when you call tableTimer on it.
Comment: Ill post as answer so you can accept if you want :P
Comment: That was it. I set delegate when it was needed, but never set testCall. Put in a simple b.testCall = self; now its all working. Thank you so much.
Answer: Use a breakpoint and make sure the "testCall" property isn't nil when you call tableTimer on it.
Also, you should make testCall and delegate weak instead of assign in case those objects get dealloc'd.
Answer: in MasterViewController.m you should be setting
<code>BRButtonInstance.testCall = self;
</code>
where BRButtonInstance is an instance of the class. Are you certain you're doing this somewhere?


session destroyed on mobile Google Chrome while changing view to desktop site

Question: I am using Google Chrome on a mobile device. When I change the mobile view to desktop view, the session is destroyed and it sends me to the login page of my website.
I am changing the view for my admin dashboard as some listing page is not showing properly in mobile view so I'd like to change to desktop view to be able to use the page properly.
Does anyone have any idea on this?
Comment: That's probably how it has to work, in case the site sets some sort of cookie that says "this is a mobile user, show them the mobile site".
Comment: Try disabling [`session.use_strict_mode`](http://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode) in your `php.ini`. If I recall correctly this setting takes into account the browser's user agent when validating the session. I experienced this issue with IE because it can randomly switch to compatibility mode which would invalidate sessions just by visiting a new page.
Answer: The browser is resetting session id on changing the view from mobile view to desktop or vice versa. To disable the resetting the session we have to disable the matching user agent. I have disabled in the CodeIgniter by <code>$config['sess_match_useragent'] = FALSE;</code>


Amazon EC2 - Creating new RSA/DSA Keypair

Question: I'm going to keep this quick.  A friend of mine's dev locked him out of his EC2.  Now I'm not familiar with Amazon EC2, but I've setup my fair share of keypairs.
Note: I will get the PEM/PPK (private key) from the dev, but I'm going to need to lock him out.
The question I'm posing is the proper process of creating a new pair.  I noticed in the control panel you can generate a new private key.  So..
1.) Where is the public key? I need to add it to .ssh/authorized_keys, but where is it?
2.) What account does the public key go to when generated from the panel?
3.) Can I disable keypairs for the moment to get proper access to make sure the key isn't refused with EC2?
I might have left something out here, an EC2 "gotcha".  Any insight on this matter would be greatly appreciated.
Cheers.
Answer: You can't add new key pairs to existing instances like that.
If you're well and truly locked out of an instance, your best option is shutting it down (not terminating!), unattaching its EBS root volume, attaching that root volume to another instance, and adding your public key in the right spot on that new instance. Reattach to the original instance and start it back up and you've got access.
Answer: I'll answer your specific questions below, but the Amazon getting started guide might be a handy general resource for you or your friend.  (Unlike most of the online documentation I'm used to, it's actually pretty good.)

1.) Where is the public key? I need to add it to .ssh/authorized_keys, but where is it?

On the instance itself.
Alternate answer with slightly more of a walkthrough.

2.) What account does the public key go to when generated from the panel?

EC2 key pairs are instance-specific, so it doesn't go to an Amazon account, it goes to an EC2 instance.  If you mean which machine account, root.

3.) Can I disable keypairs for the moment to get proper access to make sure the key isn't refused with EC2?

Nope.  EC2 uses certificate-based authentication only.
From Amazon's EC2 "getting started" guide:

Under Choose a Key Pair, you can choose from any existing key pairs
  you already created, or you can create a new one. For this example,
  we'll create a key pair:

Important

Do not select the None option. If you launch an instance without a key
      pair, you can't connect to your instance.
Comment: Alright so, I had created a secondary private key in the control panel, tried to connect with it and it refused it every time.
Comment: Isn't always root that gets the keypair. On Ubuntu instances it's the ubuntu user.
Comment: @wes Doesn't work that way. Keypairs are attached to an instance on creation. You can't add one after the fact.
Comment: So does it automatically add it to the authorized_keys?
Comment: Ah I see, so when I do make an additional int he panel, HopelessN00b said it goes to the instance, but where on the instance?
Comment: Adding a keypair in the EC2 console doesn't do anything to existing instances. It only makes it available if you want to launch a new instance. When you create an instance, you select a keypair. There's no way to have EC2 edit `authorized_keys` on your behalf post-creation.
Comment: Alright, so I need to change it.  I'll generate the public key from the private key when I get on the server.  From this article, I hear you can generate a new key/pair instance on restart, is this as easy as it sounds?
Comment: Oh no, don't get me wrong.  I plan on editing it myself.


Linear dependent functions

Question: V is a linear space of all functions $\ \mathbb R \to \mathbb R $ and $\ f,g,h \in V $
$\ f(x) = x\cos x $ , $\ g(x) = \cos x $, $\ h(x) = \sin x $
Need to see if those functions are dependent.
$\ 0 = \alpha_1 x\cos x + \alpha_2\cos x + \alpha_3 \sin x $
lets say $\ t= \cos x , s = \sin x $
$\ \alpha_1 x t + \alpha_2 t + \alpha_3 s $ = 0
$\ t(\alpha_1x + \alpha_2) + s \alpha_3 = 0 $
Not sure how do i go on from here? and I haven't been taught the Wronskian.
Answer: Hint.   If your first equation is true, it is true for all values of x.  Try specific values of x, that will give you multiple equations that are linear in your coefficients.   Show they are inconsistent.
Answer: Just working out Alan's hint:
$$\ 0 \equiv \alpha_1 x\cos x + \alpha_2\cos x + \alpha_3 \sin x$$
Set

$x= 0 \Rightarrow \alpha_2 = 0$
$x= \pi \stackrel{\alpha_2 = 0}{\Rightarrow} -\alpha_1 \pi = 0 \Rightarrow\alpha_1 = 0$
$x=\frac{\pi}{2}\stackrel{\alpha_1=0,\alpha_2 = 0}{\Rightarrow}\alpha_3 = 0$

It follows that the three functions are linearly independent, as the coefficients $\alpha_1, \alpha_2, \alpha_3$ have to be zero.
Comment: We want to show that the three vectors - here the three given functions - are linearly independent. This means we need to consider linear combinations of these three functions that produce the zero-FUNCTION:
$\ 0 \equiv \alpha_1 x\cos x + \alpha_2\cos x + \alpha_3 \sin x$. This in turn means these coefficients produce for any $x$ always the value zero. If we succeed in showing that this is only possible when all the coefficients $\alpha_1, \alpha_2, \alpha_3$ are equal to zero, then we are done. So, we pick some specific $x$ and check what consequences this has for the coefficients.
Comment: @Yarden: The word "inconsistent" is maybe a bit misleading. One may use it if you wanted to prove the independence of the three functions by contradiction. In this case you would assume a non-trivial linear combination $\ 0 \equiv \alpha_1 x\cos x + \alpha_2\cos x + \alpha_3 \sin x$ with at least one of the coefficients to be non-zero. Then, picking some specific values for $x$ would show that the equations obtained for the coefficients would be "inconsistent" with this assumption.
Comment: Yes. To show the independence of $n$ real functions $f_1(x),\ldots , f_n(x)$ directly using linear combinations, you set up the general equation to produce the zero-function: $0 \equiv \alpha_1 f_1(x) + \cdots +\alpha_n f_n(x)$. Then you choose $n$ different $x$-values in the common domain of these functions. That way you obtain an $n\times n$ linear system for the coefficients $\alpha_1 \cdots ,\alpha_n $. Here, choosing the $x$-values wisely can help simplify this system. If you can show that this system has only the trivial solution $\alpha_1 =\cdots  = \alpha_n = 0$, then you are done.
Comment: Thanks a lot but unfortunately i still can't seem to grasp the idea behind it.  Basically can I just pick any random value of x and then just see what happen to the coefficients ? Not sure what did Alan mean by "show they are inconsistent"
Comment: Okay.. I think I'm starting to get it. Another question, is I need to choose n different values for x where n = no' of functions , am I correct? I mean the end goal is to create new equations with the coefficients?
Comment: Thanks a lot trancelocation!!

Linear dependent functions


Troubleshooting Wake-on-Lan on Dell Microplex

Question: I am trying to get WOL working, but it simply does not help to power on my devices. Here's what I have tried:
I have a 2 PCs of different make/models connected to a Cisco Switch. Both them do not work, so it's not something to do with a specific NIC, BIOS setting etc. So, I will focus the troubleshooting from 1 PC - which is of Dell Microplex that is running Proxmox.

I am attempting local WOL. Not over the Internet. No port forwarding etc needed.

I have checked the BIOS settings for this. Here are the screenshots (sorry for the poor quality, I will mention details in the description for easy readability)

BIOS > Power options > Enable USB Power Share, Enable USB Wake Support

Active State Power Management AUTO

Block Sleep OFF

Deep Sleep Control Disabled

Wake on LAN/WLAN -> LAN Only

On Proxmox, here's the configured setting

Here's the IP link settings from the proxmox shell

I can confirm that the switch is not blocking any traffic because I captured traffic by generating a WOL packet from my Mac and I could see that it was received on the NIC. Here's a screenshot of that.

I also tried directly connecting my Mac to the Dell server to send the WOL packet, but that didn't work either.

What else have I missed troubleshooting here? I cannot get WOL working despite checking all the possibilities. As mentioned, it affects 2 machines of different makes/models.
Answer: USB power configuration isn't relevant. Internal NICs are connectec via PCIe, so you need to configure PCIe power management, something along Power On by PCIe, Power on by PME, or even Wake on LAN.
Some NIC drivers deactivate WoL on system shutdown, so you might want to unplug and replug mains power for testing. A very good indicator is when the NIC link/activity LED is lit or flickers with a soft-off system, especially when the switch indicates a reduced-speed link rate (10 or 100 Mbit/s).
Various sleep/standby modes deactivate WoL altogether, so it often only works from soft off.
Of course, you need a reliable tool for crafting magic packets for WoL. Always use the default hardware MAC address, no manually configured address (as far as I have seen).
Addresses that you configure on a hypervisor are not relevant for powering up the host. Some hypervisors support WoL though, so when the host is already running and accepting WoL magic packets to power up a specific VM.
Comment: Try unplugging mains. If the NIC LED lights up when restoring power (w/o powering on), the driver or its config is the problem. WoL often only works in soft off (S5 state). The switch isn't relevant, it just needs to link in any speed (Auto Negotiation on, the right thing in any case).
Comment: The switch just needs to support linking at 10 and 100 Mbit/s (depending on NIC). Check with the WoL speed with the other machine and temporarily configure it with the same speed, half duplex and see if the switch links. Perhaps it's a Gigabit-only port?
Comment: The NIC link/activity LED definitely is not lit when I power off my machine. I believe this is a problem. What sleep state should the machine be on for WOL to work and any suggestion where I'd modify this? I also believe this has something to do with the switch. It's a cisco switch, do you have any suggestions on what should I change on the switch cli.
Comment: Okay here's some progress. I do believe the switch is at play here. I connected the machine directly to my Mac. The NIC led was blinking and when I sent the magic packet, the machine did power on this time. So, it's definitely the switch. What do you suggest I check on the switch? thank you!
Comment: Thanks a lot for pointing me in the right direction. The problem was that I had forcefully set the speed to 1000. I configured auto for both speed and duplex and it worked. Thank you very much!


Minimum Spanning Tree - True or False

Question: Could somebody please help me with this problem?
I realise it's pretty simple, but for some reason can't really wrap my head around it.
Determine if these are true or false and prove it:
(i)  If $e$ is an edge with the least cost in a cycle of $G$, then $e$ belongs to a minimum spanning tree of $G$.
(ii) If $e$ is an edge of a minimum spanning tree of $G$, then $e$ is an edge with the least cost in some cutset in $G$.
Thank you!
Comment: @JMoravitz, $e$ is an edge with the least cost in *some* cycle of $G$. It doesn't have to be the least cost edge in *any* cycle that contains $e$. Noting this fact it is easy to build a counterexample to the claim (i).
Answer: (i) Let $G \cong K_4$, $V(G) = \{\, 1, 2, 3, 4\,\}$ and $w\colon V(G) \to \mathbb{R}$ be the following weight function: $w(\{\,1, 2\,\}) = w(\{\,1, 3\,\}) = w(\{\,1, 4\,\}) = 1$, $w(\{\,2, 3\,\}) = w(\{\,2, 4\,\}) = 3$, $w(\{\,3, 4\,\}) = 2$. Then $\{\,3, 4\,\}$ is an edge with the least weight in a cycle $2, 3, 4, 2$ of $G$. However it obviously doesn't belong to the only minimum spanning tree.
(ii) Let's remove edge $e$ of the minimum spanning tree and break the tree into two components with sets $U$ and $V$ of vertices. Now we can consider the cut set between these two sets of vertices. If there is an edge $e'$ such that $w(e') < w(e)$ then we can remove $e$ from spanning tree and add edge $e'$ to get a spanning tree of lower weight. So if $e$ belongs to minimum spanning tree then it has the minimum weight in some cutset.

Minimum Spanning Tree - True or False


Python h5py - Why do I get a broadcast error?

Question: I am trying to read a .h5 file data.h5, which has 2 datasets, 'Data' and 'metaData'. 'metaData' contains a dictionary which is 157x1, and looks like this:

Then, I am trying to write a new .h5 file, which contains 3 columns: the number, name (1st column of dictionary), and unit (last column of dictionary) of each variable in the dictionary. This is the code:
import numpy as np
import h5py as h5

hdf = h5.File('data.h5','r')
data1 = hdf.get('Data')
data2 = hdf.get('metaData')
dataset1 = np.array(data1)
dataset2 = np.array(data2)

#dictionary
hdfdic = dict(hdf['metaData'])
dic = hdfdic.get('dictionary')
dictionary = np.array(dic)

#write new h5 file
with h5.File('telemetry.h5', 'w') as var:

    dt = np.dtype( [('n°', int), ('Variable name', 'S10'), ('Unit', 'S10')] )
    dset = var.create_dataset( 'data', dtype=dt, shape = (len(dictionary),))

    dset['n°'] = np.arange(len(dictionary))
    dset['Variable name'] = [val[1] for val in dictionary[:][0][0]]
    dset['Unit'] = [val[2] for val in dictionary[:][0][-1]]

    data = dset[:]
    print(data)

I get the error:
Traceback (most recent call last):
  File "c:/Users/user/Desktop/new/code.py", line 28, in <module>
    dset['Variable name'] = [val[1] for val in dictionary[:][0][0]]
  File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "C:\Users\user\Anaconda3\envs\py38\lib\site-packages\h5py\_hl\dataset.py", line 707, in __setitem__
    for fspace in selection.broadcast(mshape):
  File "C:\Users\user\Anaconda3\envs\py38\lib\site-packages\h5py\_hl\selections.py", line 299, in broadcast
    raise TypeError("Can't broadcast %s -> %s" % (target_shape, self.mshape))
TypeError: Can't broadcast (4,) -> (157,)

What is the problem?
Comment: `dictionary` is a numpy array.  Indexing it with `[:]` does nothing.  You may want to use `dictionary[:,0,0]`.  But that's just a guess because I don't know much about it.
Answer: As @hpaulj noted, h5py returns HDF5 datasets as NumPy arrays. It can be confusing at first -- h5py uses Python's dictionary syntax to reference HDF5 objects (groups and datasets), but they are not dictionaries! Your attempt is on the right track. You need to modify it to work with data from hdf['metaData'] as a NumPy array instead of list.
Example below should work. Since I don't have the starting file (data.h5), I created a file to replicate the values in the image. Code to create that file is at the end.
Note 1: This example would be simpler if it didn't use use '°' for degree. That adds a extra step working with string data. That's why I used np.char.decode() to print dset['Variable name'] and dset['Unit']. More about that below.
Note 2: Be careful using hard-code string sizes. ('Variable name', 'S10') is from the answer to an earlier question (that had shorter strings). The code below gets the size from the hdf['metaData'] dataset dtype, then uses it when defining the dtype used for the new dataset in telemetry.h5.
with h5.File('data.h5','r') as hdf:
     #read dataset as a numpy array metaData, it is not a dictionary
     metaData = hdf['metaData'][:]
     print('dtype is:',metaData.dtype)

#write new h5 file
with h5.File('telemetry.h5', 'w') as var:

    dt = np.dtype( [('n°', int), ('Variable name', metaData.dtype), ('Unit', metaData.dtype)] )
    dset = var.create_dataset( 'data', dtype=dt, shape=(len(metaData),))

    dset['n°'] = np.arange(metaData.shape[0])
    dset['Variable name'] = metaData[:,0] # use first column of metaData
    dset['Unit'] =  metaData[:,-1]  # use last column of metaData

    for row in dset:
        print(row[0], np.char.decode(row[1]), np.char.decode(row[2]))

Here is the code I wrote to mimic data.h5. When you printed the raw data (as byte strings), you see b'\xc2\xb0' where you expect '°' for degree units.  There are some complications with that character with h5py. It is fine in Python and NumPy. However, h5py (and HDF5) don't support NumPy's Unicode dtype; you need to use Numpy byte arrays ('S' dtype). That's why I used np.char.encode() to encode array arr to arr2 before saving with h5py. That's why np.char.decode() is necessary when printing dset['Variable name'] and dset['Unit'] above -- you have to decode the encoded string byte data back to Unicode.
arr = np.array( \
    [['ADC_ALT_TC', 'ADC_ALT_TC',  'ADC.ALT:TC [ft]', 'ft'],
      ['ADC_AOA_TC', 'ADC_AOA_TC',  'ADC.AOA:TC [°]', '°'],
      ['ADC_AOS_TC', 'ADC_AOS_TC',  'ADC.AOS:TC [°]', '°'],
      ['ADC_CAS_TC', 'ADC_CAS_TC',  'ADC.CAS:TC [kts]', 'kts'],
      ['ADC_OAT_TC', 'ADC_OAT_TC',  'ADC.OAT:TC [°]'., '°'],
      ['ADC_SpeedWarning_TC', 'ADC_SpeedWarning_TC','ADC_SpeedWarning:TC', ''],
      ['ADC_Stall_TC', 'ADC_Stall_TC','ADC_Stall:TC', ''],
      ['ADC_TAS_TC', 'ADC_TAS_TC',  'ADC.TAS:TC [kts]', 'kts'],
      ['AHRS1_accX_TC', 'AHRS1_accX_TC',  'AHRS1.accX:TC [m/s^2]', 'm/s^2'],
      ['AHRS1_accY_TC', 'AHRS1_accY_TC',  'AHRS1.accX:TC [m/s^2]', 'm/s^2'],
      ['AHRS1_accZ_TC', 'AHRS1_accZ_TC',  'AHRS1.accX:TC [m/s^2]', 'm/s^2'] ]
print(arr)
arr2 = np.char.encode(arr)
print(arr2)

with h5.File('data.h5','w') as hdf:
     hdf.create_dataset('metaData',data=arr2)

Here are some references for those that need more details about the underlying HDF5/h5py requirement, or encoding/decoding between Unicode and string bytes:

Strings in HDF5 - Encodings
Conversion from U3 dtype to ascii
How to convert type from "str" to "numpy.string_" of each ndarray items?