chrome...addListener, how to wait for chrome.storage.sync.get?

Question: My extension is modifying some URLs. It worked fine, but now I want to check if modifying is enabled in the settings or not.
chrome.webRequest.onBeforeRequest.addListener
(
    modifyUrl,
    {urls: ['http://somewebsite/*'], types: ['main_frame']},
    ['blocking']
);

The problem is that I do not know how to wait for the value. I must get the setting before exiting modifyUrl. Is this possible? If this were C#, I would probably have used ManualResetEvent or something after calling the sync.get.
function modifyUrl(details)
{
    chrome.storage.sync.get("someSetting",
          function (data)
          {
            //I can get the setting here
          }
    );

    //how to know the setting here?
    if(enabled in the setting)
    {
        return {redirectUrl: some different url};
    }
}

Comment: Looks like you need a callback or promise to wait for the async operation, and *then* return from the function
Comment: Here's an idea -> https://jsfiddle.net/adeneo/69pskkad/
Comment: @adeneo What if the setting changes after you register the event listener?
Comment: @adeneo Chrome seems to load the background script only once, so if I read the setting first and then add the listener, if the user changes the setting after that, the script is not called again... or if there is any way to reload the background script when the setting is changed, I do not know.
Comment: @wOxxOm Thank you. I will use that 'caching' method. I tried that 'Swapping` approach before posting this question. As I wrote above, the script was called only once, so I could not swap the handler. Could you copy your comment to an answer, so that I can select it as the accepted answer? That may be helpful for future users who might encounter the same problem.
Answer: See Returning Chrome storage API value without function for detailed explanations.
In short, a blocking onBeforeRequest event is synchronous so it can't depend on asynchronous functions such as all chrome.* API callbacks to derive its return value.
Cache the data in a global variable, and use chrome.storage.onChanged to update it when changed elsewhere, which can easily happen if you use chrome.storage.sync (it's updated on profile sync).
var settingEnabled; // a global variable
chrome.storage.sync.get("someSetting", function (data) {
    var settingEnabled = data.someSetting;
});

chrome.webRequest.onBeforeRequest.addListener(
    modifyUrl,
    {urls: ['http://somewebsite/*'], types: ['main_frame']},
    ['blocking']
);

function modifyUrl(details) {
    if (settingEnabled) {
        return {redirectUrl: 'http://example.com'};
    }
}

chrome.storage.onChanged.addListener(function(changes, area) {
    if (area == "sync" && "someSetting" in changes) {
        settingEnabled = changes.someSetting.newValue;
    }
});

Of course, in case you want to disable processing completely, simply detach the listener:
function toggleListener(enable) {
    if (enable) {
        chrome.webRequest.onBeforeRequest.addListener(
            modifyUrl,
            {urls: ['http://somewebsite/*'], types: ['main_frame']},
            ['blocking']
        );
    } else {
        chrome.webRequest.onBeforeRequest.removeListener(modifyUrl);
    }
}

chrome.storage.onChanged.addListener(function(changes, area) {
    if (area == "sync" && "someSetting" in changes) {
        toggleListener(changes.someSetting.newValue);
    }
});

chrome.storage.sync.get("someSetting", function (data) {
    toggleListener(data.someSetting);
});

Another interesting approach is to re-attach onBeforeRequest inside storage.get callback on updates.


Proper network configuration on Windows Server 2008 R2 without internet access

Question: I have a new Winwdows Sever 2008 R2 machine with two network cards. The situation is as follows:

One network card is connected to CompanyLAN_1 (10.0.0.0/24)
Through this card the machine can reach 10.0.0.254
Through 10.0.0.254 the machine can reach 10.0.0.0/16
The other network card is connected to CompanyBackup_1 (192.168.0.0/24)
Through this card the machine can reach 192.168.0.254
Through 192.168.0.254 the machine can reach 192.168.0.0/16
The machine should NOT be able to access any networks beyond 10.0.0.0/16 and 192.168.0.0/16 (the machine should have no internet access at all)

What is the proper/recommended way of setting this up in Win2k8R2?
A) set up the network cards with the proper netmasks and put default gateways to each one
B) set up the network cards with the proper netmasks and put a default gateway to the normal one and add a static route to the backup one
C) set up the network cards with the proper netmasks and add two static routes, one for each?
Any link to official Microsoft references detailing recommendations would be welcome as well.
Answer: The simplest way to do this is not to specify any default gateway. When you do that, only the networks specified in the local routing table will be available.
You should, however, consider using a proper firewall for this machine: not only is it simpler to configure, it's also much more resilient to problems.
Comment: Ohh, the machine is behind multiple firewalls - what we are aiming for here is called multilevel security. E.g. we have the very same ruleset installed on both the local firewall and the proper firewall in front of the machine. Some industries have requirements like this... :/
Comment: Fair enough. I'm not sure it really adds to the overall security but I guess it's a minor enough change it doesn't really matters.


How to increment text on cart icon which is present in Bottom Navigation bar Android Studio

Question:
Help me out, how to do the following for bottom navigation icon
Comment: Just create a layout with the shopping cart icon with the circle and a `TextView` in it that you can update.
Answer: You can use the  below code to show badge count in bottom navigation menu item.
<code>        navViewBottom.getOrCreateBadge(R.id.shoppingCartFragment).number = value
</code>
Here, shoppingCartFragment is menu item id. You need to use material design theme to achieve this.


Save file after forgetting to open as root / sudo vi

Question:
Possible Duplicate:
vim re-edit as root

I could have sworn I saw this question asked. But after looking though every search result for "vi" I'm stumped/lazy.
I've opened a file, made an edit and now I realize it's read only and I've opened it as non-root me.
Comment: Duplicate of http://serverfault.com/questions/22558/vim-re-edit-as-root
Answer: I think you want something like this:
<code>:w !sudo tee "%"
</code>
I first saw it on commandlinefu. The quotes are only necessary if the file path contains spaces.
Answer: i do this occasionally, and if the changes i've made are trivial, i just exit and edit it again as root.
otherwise i save the file to /tmp, and mv/cp it as root to where it really belongs later.  and use chown/chgrp/chmod to fix the ownership/perms.
Comment: Rather than cp/mv and chown etc., you could 'sudo cat tmpfile > realfile && rm -f tmpfile', to keep the ownership and perms of the original but give it new contents.
Answer: consider adding this line to your vimrc:
<code>" Remaps :SW to sudo save the current file and tell vim to reload it
command SW execute 'w !sudo tee % >/dev/null' | e! %
</code>
Answer: Try this http://blog.sriunplugged.com/2009/12/how-to-save-file-in-vi-not-opened-with-sudo/ . This is what you want i guess


Could B♭ instruments be built in C? Why are they in B♭ in the first place?

Question: Why did the clarinet and trumpet get made to 'be' in B♭?  Could they have been made to produce concert pitch C?
This would make a composer's life so much easier when physically writing scores.  Surely a slightly longer instrument wouldn't make that much difference to sound, timbre, etc?
Comment: In the case of the brass instruments at least, the original instruments had no valves or slides, so the difference between an instrument in C or Bb was big. Trumpet players had to switch horns when the piece modulated, and had quite boring parts, limited to the tones they could play without valves. Why the trumpet settled on a Bb base later on, I don't know. Note also that the C trumpet is rather popular in classical music, at least for solists.
Comment: Almost duplicate: http://music.stackexchange.com/questions/7225/what-are-the-practical-reasons-for-still-having-transposing-instruments
Comment: Every musical notation software I know of makes it a snap to adjust voices to a transposing instrument. You are not talking about writing notes with pen on paper?
Comment: I'm not sure that I agree about instruments being "made" in B♭, A etc.  Transposition is not a physical thing its more conceptual.  Its a protocol for how the instrument is used and played.  A particular fingering on a B♭ clarinet produces the note G but it is the convention that the note it is written as an A.  On an A clarinet that fingering produces an F# but is still written as an A.
Comment: @JimM - I'm not averse to having to transpose, I do it on a daily basis. The point is that maybe it would have been just as easy and successful to produce a clarinet that read and played concert pitch than not. Someone chose Bb, I doubt it was an accident.
Answer: This goes back to the early days of "modern" instruments.  Initially, instrument-makers did not have the accuracy of instruments (mechanical) to create keys, accurate boring, etc.  If you look through the history of any wind instrument, you'll see such profound comments as "and then it received two keys!"  Because most instruments were created at a time before using keys, you had an instrument in a single scale degree.  If you had a C clarinet, you could not play F#s or Ebs.  You played diatonically, in the C scale.
As instrument-makers learned more precise tools and were able to create more complex systems, the number of clarinets needed to play the full range of scales diminished.  We were left with three soprano clarinets: A, Bb and C.  Bb sounds the best, and was determined to be the winner of the clarinet races.  It is most commonly played.  However, any professional clarinetist has all three "orchestra clarinets", because there are parts still written for them.
Part of the problems with the other instruments: the modern A clarinet has been designed to fit the Bb mouthpiece.  Unsurprisingly, this is a less than perfect match.  It means that the A clarinet has interesting intonation problems and what's commonly referred to as "the grunt" -- a sort-of grumbling sound from the instrument in the second half of the clarion register.  It just doesn't want to play them!
The modern C clarinet on the other hand tends to be a bit brighter (is smaller) and also has different intonation problems than the standard Bb.  I think the C instruments are not bad, but because they aren't standard, harder to find essentials like reeds, ligatures, replacement parts, etc.  Not hard, just harder.
These instruments are only commonly used today in orchestra.  In bands of any variety, the Bb is commonly used.  It's not a difficult transposition, and trying to "re-write" for concert pitch would probably induce screams as loud as asking a violist to play in treble clef. :-P
The long and short of it is: there are more than one clarinet, there are reasons for playing any, and those reasons probably have more to do with tradition than anything else.
Comment: I get what you are going for there, but any competent violist is used to reading treble clef regularly--it's a not uncommon part of viola music, particularly in higher registers. I just played an orchestra concert last night, and in my part (viola) for Barber's "Adagio for Strings", there's several lines in treble clef.
Answer: Originally there were 3 clarinets: A, B♭ and C
According to Wikipedia, the C clarinet — being the highest and therefore brightest of the three — fell out of favour as the other two clarinets could cover its range and their sound was considered better.
Building to make the composer's life easier wasn't one of the design requirements, and in fact isn't for most instruments!
Answer: The point is not that people specifically want instruments with a natural scale other than C. The point is to make different sizes of the same instrument and have them all playable with the same fingering without additional learning effort. And different sizes will result in instruments starting their scale on different notes (unless you make them so big that it's exactly an octave above or below).
But to take advantage of the reduced learning effort, at least one variant has to be notated in a transposing manner. And if composers, conductors and copyists have to deal with transposing instruments anyway, it's a better idea to build your instrument variants on those scales that work especially well for that particular shape and have both variants transposing, raher than have a "standard" C version and e.g. a non-standard A version.
(And what does it mean that a specific scale works "better" for an instrument? Well, the difference between an A clarinet and a B clarinet is subtle, but clarinet players will tell you at length that it's very characteristic, and the C clarinet is another thing altogther.)
Comment: Oh yes, they did. Clarinet players will tell you at length why the bright, squeaky sound of the C clarinet is a abomination compared to the mellow, round tone of the A clarinet. The piccolo clarinet in D or Eb exists, but it's *really* squeaky. Clarinets in Ab were once widely used in marching bands, etc. Ultimately, having *not too many* variants of an instrument is a value in itself, and people have settled on the Bb version because it was already the most common.
Comment: Briefly, making an instrument sound lower involves making it larger (a fifth requires a size increase of 50%, a third an increase of 20% - 26%). But simultaneously it has to stay at a size so that the same human hand can still hold and operate it. This means that not only the size but also the *shape* has to change subtly, and this affects sound more than the change in size.
Comment: I appreciate your answer, but I still quest for why , say, the clarinet has ended up essentially in Bb (for most of them). What I'm getting at now is - did anyone make , say, a D, or Ab clarinet, but found that its sound was inferior.
Comment: None of this explains the trend towards flatter keys for "band" instruments.
Answer: As for the trumpet, the choice of key Bb goes back into history. I have no sources available, but has been told that it goes like this.
The valved brass instruments started to come inte play a bit into the 19-th century. At that time the large buyers of instruments were military bands in continental Europe. The military had large marching orchestras and liked the sheer volume of brass instruments. The military ordered full sets of instruments, from large tubas up to small trumpets and anything between. From some reason they decided to select the Bb key and standardize on that. Exactly why, I have no idea of.
From this start, the market started to contain a lot of Bb brass instruments and players. The production turned inte a mechanized industry. The Bb instruments probably were both better and cheaper than the alternatives, so it spread outside of the military to other areas.
From a player perspective, you like to play the same key instrument as your teacher and that you started playing on. From a composer perspective, it does not really matter -- learning to write for transposing instrument is learned from the very beginning and is not really complicated. So the tradition of Bb keyed brass instruments has stayed with us.
(It should be noted that the Eb keyed instruments fit in the middle between two octaves of Bb and fits well into how to transpose).


error when using `dataframemapper` class from pickle

Question: I am trying to save a DataFramMapper object to use on new data for a model.
 mapper = DataFrameMapper([
        (['price', 'Argentina', 'Canada', 'Australia', 'barcat_numeric'], None),
        ('TTL',CountVectorizer( ngram_range=(1, 2))),
        ('BARCAT', CountVectorizer( ngram_range=(1, 2)))
    ])
    with open('company_dill.pkl', 'wb') as f:
        dill.dump(mapper, f)

when i read in the data:
with open('company_dill.pkl', 'rb') as f:
mapper_v = dill.load(f)
print(type(mapper_v))

output is:

but when i try using it i get:
---> 20     X = mapper.transform(data_frame)
 21     return X

C:\Users\eliav\Anaconda3\lib\site-
packages\sklearn_pandas\dataframe_mapper.py in transform(self, X)
    269         extracted = []
    270         self.transformed_names_ = []
--> 271         for columns, transformers, options in self.built_features:
    272             input_df = options.get('input_df', self.input_df)
    273             # columns could be a string or list of

TypeError: 'NoneType' object is not iterable

When i do not save to pickle it works fine, used both pickle and dill
Answer: OK i found my mistake:
I saved the DataFrameMapper object before i fitted the data, this is the right way:
 mapper = DataFrameMapper([
        (['price', 'Argentina', 'Canada', 'Australia', 'barcat_numeric'], None),
        ('TTL',CountVectorizer( ngram_range=(1, 2))),
        ('BARCAT', CountVectorizer( ngram_range=(1, 2)))
    ])
    X=mapper.fit_transform(data_frame)
    pickle.dump(mapper, open( "mapper.pkl", "wb") )


Substituir múltiplas substrings de um dicionário

Question: Estou tentando fazer um replace, mas não estou conseguindo.
Meu código:
dicionario = {
    "uva":"R$ 5,00",
    "abacaxi": "15%",
    "abacate": "preço: N/A"
    }

for key, value in dicionario.items():
  if 'R$ ' in value or '%' in value or 'N/A' in value:
    dicionario[key] = value.replace('R$ ', 'reais ')
    dicionario[key] = value.replace('%', 'porcento')
    dicionario[key] = value.replace('N/A', 'Nada')

print(dicionario)

Output atual: {'uva': 'R$ 5,00', 'abacaxi': '15%', 'abacate': 'preço: Nada'}
Output que desejo: {'uva': 'reais 5,00', 'abacaxi': '15porcento', 'abacate': 'preço: Nada'}
Por algum motivo que não consegui resolver, apenas o último valor do dicionário está sendo atualizado. Alguém tem alguma luz de onde estou errado?
Comment: Execute cada substituição sobre o resultado da anterior.
Answer: Primeiro vamos modificar um pouco o seu exemplo para entender melhor o que acontece:
dicionario = {
    "uva":"R$ 5,00"
}

for key, value in dicionario.items():
    print('substituindo', value)
    if 'R$ ' in value or '%' in value or 'N/A' in value:
        print('antes da primeira substituição: ', value)
        dicionario[key] = value.replace('R$ ', 'reais ')
        print('depois da primeira substituição: ', dicionario[key])
        print('antes da segunda substituição: ', value)
        dicionario[key] = value.replace('%', 'porcento')
        print('depois da segunda substituição: ', dicionario[key])
        print('antes da terceira substituição: ', value)
        dicionario[key] = value.replace('N/A', 'Nada')
        print('depois da terceira substituição: ', dicionario[key])

Deixei o dicionário apenas com uma entrada, para simplificar. Depois, eu imprimo o value antes de cada chamada de replace e o valor de dicionario[key] logo depois. O resultado é:
substituindo R$ 5,00
antes da primeira substituição:  R$ 5,00
depois da primeira substituição:  reais 5,00
antes da segunda substituição:  R$ 5,00
depois da segunda substituição:  R$ 5,00
antes da terceira substituição:  R$ 5,00
depois da terceira substituição:  R$ 5,00

Repare que o value nunca muda, pois a chamada de replace não modifica a string: o que ela faz é retornar outra string modificada.
Então você primeiro troca o "R$" por "reais", e modifica o valor do dicionário (dicionario[key] recebe o valor da string modificada, mas value continua tendo o "R$").
Depois você tenta trocar o "%" por "porcento", mas como value não tem "%", ela não é modificada. E esse valor não modificado (ainda com o "R$") é colocado em dicionario[key] - ou seja, o valor anterior ("reais 5,00") foi sobrescrito, e dicionario[key] passou a ser "R$ 5,00".

Se a ideia é fazer todas as substituições, as chamadas de replace devem ser encadeadas. Algo assim:
dicionario = {
    "uva":"R$ 5,00",
    "abacaxi": "15%",
    "abacate": "preço: N/A"
}

for key, value in dicionario.items():
    if 'R$ ' in value or '%' in value or 'N/A' in value:
        dicionario[key] = value.replace('R$ ', 'reais ').replace('%', ' porcento').replace('N/A', 'Nada')

print(dicionario)

Mas acho que  isso só faz sentido se uma string puder ter mais de um desses elementos.
Por exemplo, se tiver a string R$ 1,00 - 10%, ela se tornaria reais 1,00 - 10 porcento.
Mas se cada string só pode ter uma dessas opções (ou ela tem só "R$", ou só tem "%", etc), aí não precisaria trocar todas as possibilidades, bastaria trocar somente o que ela tem:
# no caso de uma string só poder ter uma das opções
for key, value in dicionario.items():
    if 'R$ ' in value:
        dicionario[key] = value.replace('R$ ', 'reais ')
    elif '%' in value:
        dicionario[key] = value.replace('%', ' porcento')
    elif 'N/A' in value:
        dicionario[key] = value.replace('N/A', 'Nada')

Comment: Muito obrigado, consegui entender bem onde estava o problema! abs =]


Suggestions for what to look for in a keyboard that would be a suitable stepping-stone towards learning piano

Question: Two of my kids have developed passion for classical music. They have been taking cello lessons, teaching themselves composition, and they listen to and discuss classical recordings together.
The younger, in particular, loves visiting friends who have pianos, and he picks out melodies by ear (ode to joy, William tell, etc) on these pianos.
We can't get a full-sized piano but I would like to get a keyboard of proper size and feel and tone so that they can start to play. Can anybody offer suggestions as to what features are most important, and what to avoid (or even "that's a terrible idea," if you think it's a terrible idea).
Thank you.
[addendum: The consensus among many people with whom my wife and I consulted was that many companies make excellent starter pianos around a $500 price point, so long as you get good pedals, etc. to go with them. Adorama had a big sale on the Korg B1 so we are getting that.]
Comment: Yes, it's a great idea. And a keyboard with piano feel keys (weighted) will be good, as it can be used with headphones and not disturb family/neighbours etc. You wouldn't really need a full 88 key piano, if room was a problem, but 61 should be an absolute minimum. Recommendations are out of bounds here, but the idea - great!
Comment: as far as this site goes, recommendations for specific models are off-topic here, but we can give recommendations for what to look for in a keyboard, if that's helpful? (There may even be a similar question somewhere already...)
Comment: Sure, general characteristics would help. He most useful page I have found so far is this one: https://www.reddit.com/r/piano/wiki/faq#wiki_choosing_a_keyboard
Comment: Make sure you get a sustain pedal - personally I'm happy playing 'piano' on even a cheap unweighted keyboard as long as I have something to stamp on!
Answer: The most important features in a keyboard to learn to play piano (in approximate order of importance):

Full sized keys
Complete keyboard of 88 keys
Fully weighted keys
Stand & bench adjustable to the proper heights for good ergonomics
A place to put sheet music
A sustain pedal
Good sound quality
Good touch response
Other pedals (una corda, sostenuto)

There could be lots of debate about the order of importance. Personally, I learned piano for a few years before I was ever taught to use the sustain pedal, and particularly young children are often not able to reach the pedals, which is ok because learning to play without pedals is important.
Learning to sit properly at the piano is pretty critical, so making sure the height of whatever keyboard stand can be set appropriately is important, and even more important is the height adjustment of the piano bench. Generally you want the bench and stand to be adjustable so the thighs/knees can be raised up to just under the bottom of the keybed. If the player's elbows can be slightly above the keys, that's great, but that may not be possible for smaller children.
Having semi-weighted keys might be helpful for younger players, but at the same time playing the most realistic fully weighted keyboard will start the training on proper technique that much earlier.
Sound quality may seem like a trivial objective for a beginner instrument, but even young children can appreciate tone quality and will quickly learn to prefer hearing themselves making more beautiful sounds. One advantage of the piano as a first instrument is that the sound quality is only very slightly about player skill.
One thing you might consider avoiding is keyboards that have a lot of "features". I would look for an instrument that is focused on being a digital piano. You don't need a lot of different sounds or controls or anything like that, those are just gimmicks added on to try to sell instruments that don't have the best sound or keyboard feel, etc.
I suggest looking for an affordable "digital piano" - the kind that comes with a wooden stand and built-in speakers and is meant to be an affordable alternative to acoustic pianos. Many major musical instrument manufacturers make them, such as Yamaha.
Comment: I might put weighted keys ahead of all 88 keys, but that being said I don't know that you will find weighted action keys on anything less than a full size keyboard.
Comment: And by weighted action I mean hammer action. There are velocity sensitive and partial weighted (spring) action keyboards available in 61 keys.


TypeORM: how to load relations with CreateQueryBuilder, without using JOINs?

Question: I'm developing an API using NestJS & TypeORM to fetch data from a MySQL DB. Currently I'm trying to get all the instances of an entity (HearingTonalTestPage) and all the related entities (e.g. Frequency). I can get it using createQueryBuilder:
const queryBuilder = await this.hearingTonalTestPageRepo
      .createQueryBuilder('hearing_tonal_test_page')
      .innerJoinAndSelect('hearing_tonal_test_page.hearingTest', 'hearingTest')
      .innerJoinAndSelect('hearingTest.page', 'page')
      .innerJoinAndSelect('hearing_tonal_test_page.frequencies', 'frequencies')
      .innerJoinAndSelect('frequencies.frequency', 'frequency')
      .where(whereConditions)
      .orderBy(`page.${orderBy}`, StringToSortType(pageFilterDto.ascending));

The problem here is that this will produce a SQL query (screenshot below) which will output a line per each related entity (Frequency), when I want to output a line per each HearingTonalTestPage (in the screenshot example, 3 rows instead of 12) without losing its relations data. Reading the docs, apparently this can be easily achieved using the relations option with .find(). With QueryBuilder I see some relation methods, but from I've read, under the hood it will produce JOINs, which of course I want to avoid.

So the 1 million $ question here is: is it possible with CreateQueryBuilder to load the relations after querying the main entities (something similar to .find({ relations: {  } }) )? If yes, how can I achieve it?
Answer: I am not an expert, but I had a similar case and using:
const qb = this.createQueryBuilder("product");

// apply relations
FindOptionsUtils.applyRelationsRecursively(qb, ["createdBy", "updatedBy"], qb.alias, this.metadata, "");

return qb
    .orderBy("product.id", "DESC")
    .limit(1)
    .getOne();

it worked for me, all relations are correctly loaded.
ref: https://github.com/typeorm/typeorm/blob/master/src/find-options/FindOptionsUtils.ts
Answer: You say that you want to avoid JOINs, and are seeking an analogue of find({relations: {}}), but, as the documentation says, find({relations: {}}) uses under the hood, expectedly, LEFT JOINs. So when we talk about query with relations, it can't be without JOIN's.
Now about the problem:

The problem here is that this will produce a SQL query (screenshot
below) which will output a line per each related entity (Frequency),
when I want to output a line per each HearingTonalTestPage

Your query looks fine. And the result of the query, also, is ok. I think that you expected to have as a result of the query something similar to json structure(when the relation field contains all the information inside itself instead of creating new rows and spread all its values on several rows). But that is how the SQL works. By the way, getMany() method should return 3 HearingTonalTestPage objects, not 12, so what the SQL query returns should not worry you.
The main question:

is it possible with CreateQueryBuilder to load the relations after
querying the main entities

I did't get what do you mean by saying "after querying the main entities". Can you provide more context?


Do keepalives to socket connections exist?

Question: Pre briefing:
Although my question is broad on purpose, I am dealing with nginx connecting to php-fpm (fcgi), which is served via a local socket (/tmp/somesocket.socket).
Nginx has a setting to keepalive connections to fcgi backends ( http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_keep_conn ).
This is what my question relates to.
Question:
In linux, when making connection to local sockets, does such a thing as keepalives exist?
Would having a connection kept alive remove (even a tiny bit) some overhead related to creation / teardown of the connection?
Thanks.
Answer: I am assuming you mean local unix sockets here.

In linux, when making connection to local sockets, does such a thing as keepalives exist?

No, keepalives prevent the remote side timing out. Since the host knows the status of both sides of the connection a keepalive is redundant.

Would having a connection kept alive remove (even a tiny bit) some overhead related to
  creation / teardown of the connection?

Yes, at the cost of maintaining more file descriptors which is probably a very cheap cost in practical terms. Setting up a connection and closing it incurs 5 system calls (open and connect on client, accept on server, close on client/server) which with maintaining the connection is avoided until necessary.


Preciso criar uma forma via css para que o usuário saiba que selecionou um botão

Question: Minha empresa tem um template em WP concedido por outra em que não temos acesso ao FTP, apenas a edições de CSS. Porém ao clicar em selecionar a página não faz nada. Tentei adicionar uma alteração de cor no botão, porém ele só altera enquanto está pressionado, então não serviu.
Alguém tem uma ideia do que posso fazer? Basicamente como a página é grande, preciso que ao clicar no botão o cliente saiba que está selecionado.
CSS do botão:
.list_options.hotels .hotel_block .rooms_options > .price a {
    color: #fff;
    font-family: Open Sans;
    font-size: 14px;
    font-weight: 400;
    text-transform: uppercase;
    background: #00b6d4;
    background-size: 15px;
    background-color: #00b6d4;
    border-width: 0px;
    border: transparent;
    padding: 10px 20px;
    margin: '';
    display: inline-block;
    cursor: pointer;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    -webkit-transition: all 0.3s ease-out 0;
    -moz-transition: all 0.3s ease-out 0;
    -o-transition: all 0.3s ease-out 0;
    transition: all 0.3s ease-out 0;
    -webkit-transition: all 0.2s ease;
    -o-transition: all 0.2s ease;
    -moz-transition: all 0.2s ease;
    -ms-transition: all 0.2s ease;
    -kthtml-transition: all 0.2s ease;
    transition: all 0.2s ease;
    margin: 10px 0px 0px 0px;
    padding: 5px 10px;
}

Comment: O problema é que não sei como adicionar Jquery em um wordpress engessado. Algum plugin pra me indicar?
Comment: Com CSS vc pode usar um `a:focus { seu css }`, mas quando ele clicar em outro lugar da tela seu `` vai perder o CSS... Se dessa forma já for suficiente pra vc posso te postar uma resposta
Comment: Infelizmente não serve também. Talvez uma forma de "back to top", porém nos botões de seleção ajudaria, porém eu teria que fazer isso via plugin, pois não tenho acesso ao FTP dessa pagina.
Comment: Se vc tem acesso ao CSS vc resolve parcialmente usando :focus. Estou falando do :focus do CSS e não do .focus do JS que vc precisaria de plugin etc...
Comment: As soluções apresentadas no tópico que enviou precisam de edição no html. Não tenho nem como criar uma class no html, só tenho acesso ao css e a plugins.
Comment: Tem algum link dentro dessa `` ? quando vc clica nesse btn, ele adiciona algo na barra da URL do site? Tipo: meusite.com.br/#nomedolink ?
Comment: Selecionar
Comment: Pior que não muda o link bro, na verdade aparentemente essa pagina nem é html. Você vai clicando em tudo e o link não muda, porém se você clicar em "reservar" ele vai no item selecionado.
Answer: Para fazer esse tipo de evento via CSS eu desconheço. Mas com jQuery você pode fazer assim:

#btn-click{
    background-color: blue;
    padding: 10px;
}

<button id="btn-click" type="button">Meu botão</button>

Comment: Juliano Nunes, mesmo que seja com JS, tem alguma forma de adicionar JS sem acesso as paginas? Algum plugin que faça isso?
Answer: Adicione o seletor active no seu button.
Exemplo:
button:active {
  background-color: yellow;
}


Reference for real analytic manifolds

Question: I'm trying to find a reference for some introduction to real analytic manifolds. I'm especially interested in the fact, that the set of regular points of an analytic function $F \colon M \to \mathbb{R}^n$ is open dense on a real analytic manifold $M$.
By a regular point, I mean that the differential $d_xF \colon T_xM \to \mathbb{R}^n$ has maximal rank in $M$.
Comment: Can you do the equidimensional case when M is a ball in some euclidean space?
Comment: @zhw. unfortunately, I don't know how do it. Passing to charts I should only have to show that $f \colon N:=(0,1)^m\times 0_k \to \mathbb{R}^n$ has full rank on an open and dense subset for $f$ real analytic. So if $x$ is a singular point with rank $l$, I could try to show that there is no open neighborhood $V$ in $N$ around $x$, such that all elements of $V$ are singular with rank $l$. But I don't see how to produce a contradiction by assuming the existence of $V$.
Comment: The hypothesis should assume that M is connected and f is non constant, right?
Comment: Well, you are right. Otherwise it is clear, that it isn't true...
Comment: Suppose $f: \mathbb R^n \to \mathbb R$ is real analytic and equal to $0$ on some open ball. Then $f\equiv 0.$ Do you know this?
Comment: I thought already , that I have to use this fact. But I'm not sure how to use this uniqueness of real analytic extension.
Comment: Wait a second. What if $f(x,y) = (x,0)$?
Comment: Again I forgot to assume that $f$ has full rank in at least one point. Instead of full rank we should assume the set of point, such that the rank is maximal in $M$
Answer: Let $\overline R$ be the closure of the set of points where $dF_x$ has full rank. If this is not everything, pick a point $x \in \partial \overline R$. Pick a real analytic chart around this point $x$; because the partial derivatives of real analytic functions are real analytic, $dF$ is real analytic. Supposing for notational convenience that $\dim M =n$ (though there is no reason to make this assumption), $\det(dF)$ is also an analytic function. Because it is nonzero somewhere, it must be nonzero on a dense open set (in this chart) - otherwise there will be a point for which $\det(dF)$ vanishes in a small open set around it, and hence $dF$ vanishes everywhere by the identity theorem, contradicting the choice $x \in \partial \overline R$.
Note that there was no point here where we needed the codomain to be $\Bbb R^n$ as opposed to some other analytic manifold.

Reference for real analytic manifolds


LibGDX XLib Extension: "GLX" Error

Question: Well I'm trying to setup libgdx. I used the setup-ui and installed everything on eclipse, but I get this error when I try to run my desktop project : http://pastie.org/8399448
I'm running ubuntu, and I think this might have something to do with why my android emulator won't work in eclipse, but I don't really need it because i'm not planning to make it into an android app. Thanks for taking time to read this/help me. I really appreciate it.
Answer: I think you're missing some basic OpenGL setup on your system.  Its not Libgdx-specific.  For example does glxgears run?
See OpenGL GLX extension not supported.
The answer is probably going to be very to Ubuntu and the video card your machine is using.  You might have more luck at askubuntu.com.
Comment: Well it didn't run, because I didn't have mesa-utils installed, so I installed them, and then ran glxgears and this is what I got: Xlib:  extension "GLX" missing on display ":0.0".
Error: couldn't get an RGB, Double-buffered visual
Comment: Yeah, its not a Libgdx or Java problem.  It is your X11 configuration that needs an extension loaded to support OpenGL on your video hardware.  Search the Ubuntu forums...

LibGDX XLib Extension: "GLX" Error


nginx rewrite rules for tweetnest

Question: Recently I migrated my last apache to nginx (+ php-fpm). Everything works fine except tweetnest by month links (tweetnest/yyyy/mm).
tweetnest provides apache rewrite rules (.htaccess) which works fine OOTB
.htaccess for apache
RewriteEngine On
 RewriteBase /tweetnest
 RewriteRule ^sort/?$ ./sort.php [L]
 RewriteRule ^favorites/?$ ./favorites.php [L]
 RewriteRule ^search/?$ ./search.php [L]
 RewriteRule ^([0-9]+)/([0-9]+)/?$ ./month.php?y=$1&m=$2
 RewriteRule ^([0-9]+)/([0-9]+)/([0-9]+)/?$ ./day.php?y=$1&m=$2&d=$3

However, no example for nginx.
I managed to find this https://github.com/graulund/tweetnest/issues/37
But it is for CNAME, not exactly the same as my tweetnest use case -> domain.com/tweetnest.
I tried various combinations but failed to get it work.
Currently I am using the following block in nginx vhost config file
 # tweetnest rewrite rules
 location ~ /tweetnest {
     root /var/www/path;
     rewrite ^/sort/?$ sort.php last;
     rewrite ^/favorites/?$ favorites.php last;
     rewrite ^/search/?$ search.php last;
     rewrite ^/([0-9]+)/([0-9]+)/?$ month.php?y=$1&m=$2;
     rewrite ^/([0-9]+)/([0-9]+)/([0-9]+)/?$ day.php?y=$1&m=$2&d=$3;
 }

Getting 404 error when clicking on tweetnest/yyyy/mm links.
The complete vhost configuration is like below
upstream php {
    server unix:/var/run/php5-fpm.sock;
}

server {
    listen   *:80;

    root /var/www/path/to/root;
    index index.php index.html index.htm;

    server_name domain.com www.domain.com;
    # rewrite ^(.*)$ $scheme://www.domain.com$1;

    access_log /var/log/nginx/domain.com-access.log;
    error_log /var/log/nginx/domain.com-error.log;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to index.html
        try_files $uri $uri/ /index.html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_index index.php;
        include fastcgi_params;
        # fastcgi_pass unix:/var/run/php5-fpm.sock;
        # Use upstream
        fastcgi_pass php;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ /\. {
        deny all;
    }

    location ~* (?:\.(?:bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$ {
        deny all;
    }

    # Browser cache
    location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|eot|mp4|ogg|ogv|webm)$ {
        expires 30d;
        log_not_found off;
    }

    # tweetnest rewrite rules
    location ~ /tweetnest {
        # root /var/www/domain.com;
        rewrite ^/sort/?$ sort.php last;
        rewrite ^/favorites/?$ favorites.php last;
        rewrite ^/search/?$ search.php last;
        rewrite ^/([0-9]+)/([0-9]+)/?$ month.php?y=$1&m=$2;
        rewrite ^/([0-9]+)/([0-9]+)/([0-9]+)/?$ day.php?y=$1&m=$2&d=$3;
    }
}

Any help is appreciated ;-)
Update on 27 June, 2014.
Issue fixed by changing the rewrite rules as below
# tweetnest rewrite rules
location ~ /tweetnest {
    rewrite ^/tweetnest/sort/?$ /tweetnest/sort.php last;
    rewrite ^/tweetnest/favorites/?$ /tweetnest/favorites.php last;
    rewrite ^/tweetnest/search/?$ /tweetnest/search.php last;
    rewrite ^/tweetnest/([0-9]+)/([0-9]+)/?$ /tweetnest/month.php?y=$1&m=$2;
    rewrite ^/tweetnest/([0-9]+)/([0-9]+)/([0-9]+)/?$ /tweetnest/day.php?y=$1&m=$2&d=$3;
}

Comment: `^` indicates the start of the line.  You need to put `tweetnest/` between the `^` and the first `/` on all of your rewrite lines.
Comment: Thanks, but it didn't make a diff.
Comment: I guess, you have to add tweetnest to rewrite result too.
`rewrite ^/tweetnest/sort/?$ /tweetnest/sort.php last;` and so on should work.
Comment: @alexeyten thanks but still doesn't work ;-(
Comment: Try to turn [`rewrite_log`](http://nginx.org/r/rewrite_log) and look into error.log for details
Answer: You set root directive inside the location. This is not a good idea. You should use the alias directive if you need to specify a separate location for tweetnest files.
So, if your tweetnest sort.php is located in /var/www/tweetnest/sort.php, your config should look like this:
EDIT: Modified after new information in comment below.
root /var/www/terry;
# tweetnest rewrite rules
location /tweetnest {
    rewrite ^/tweetnest/sort/?$ /tweetnest/sort.php last;
    rewrite ^/tweetnest/favorites/?$ /tweetnest/favorites.php last;
    rewrite ^/tweetnest/search/?$ /tweetnest/search.php last;
    rewrite ^/tweetnest/([0-9]+)/([0-9]+)/?$ /tweetnest/month.php?y=$1&m=$2 last;
    rewrite ^/tweetnest/([0-9]+)/([0-9]+)/([0-9]+)/?$ /tweetnest/day.php?y=$1&m=$2&d=$3 last;
}

Comment: Thanks for the answer. In my use case, the vhost root is `/var/www/terry` and tweetnest is a subdirectory `/var/www/terry/tweetnest`. I access tweetnest using `domain.com/tweetnest`I tried using alias, that will result in a 404.
Comment: I've modified my answer based on the new information.

nginx rewrite rules for tweetnest


How to use a LIKE database query in Symfony2

Question: please i need to know what's the problem, it should work but it didn't get back the results.
There is my controller:
<code>    public function searchAction()
{
    $form = $this->createForm(new SearchCoursesType());
    $request = $this->getRequest();
    if($request->getMethod() == 'POST')
    {
        $form->bind($request);
        if($form->isValid())
        {
            $em = $this->getDoctrine()->getManager();
            $data = $this->getRequest()->request->get('formation_appbundle_scourse');
            $courses = $em->getRepository('FormationAppBundle:Course')->findCoursesByParametres($data);
            return $this->render('FormationAppBundle:Courses:coursesList.html.twig', array('courses' => $courses));
        }
    }
    return $this->render('FormationAppBundle:Template:searchIndex.html.twig', array('form' => $form->createView()));
}
</code>
I defined the search function in the Repository like this
<code> public function findCoursesByParametres($data)

{

    $query = $this->createQueryBuilder('a');

    $query->where($query->expr()->like('a.title', ':title'))

        ->setParameters(array(

            'title' => $data['title']
        ));
    return $query->getQuery()->getResult();

}
</code>
using a simple form
<code>{{ form_start(form) }}
    {{ form_widget(form) }}
<input type="submit" value="Create" />
{{ form_end(form) }}
</code>
I think that it didn't collect the input but i can't find the problem
Comment: $data = $form->getData(); should get your title.  But it does not make much sense to use LIKE without some % characters.
Answer: Change your function Repository:
<code> public function findCoursesByParametres($data)
 {
     $query = $this->createQueryBuilder('a')
              ->where('a.title LIKE :title')
              ->setParameters(array(
                  'title' => '%' . $data['title'] . '%'
              ));
     return $query->getQuery()->getResult();
  }
</code>


Styling em menus

Question: Estou a criar um menu para um site de classificados, e queria colocar uma borda arredondada(border-radius) no item 'publicar anuncio', usando css.
Deixo aqui o meu código do menu:

Publicar anúncio

Login

Registar

Categorias

Blog da equipa

Home

Enfim, não consigo identificar o item 'publicar anuncio' no css.
Comment: E qual é a dificuldade?
Comment: já olhaste alguma documentação? https://developer.mozilla.org/pt-BR/docs/Web/CSS/border-radius
Answer: Para se referir ao item publicar anuncio no css, você deve fazer desta forma:
.pub {
    border: 1px solid black;
    border-radius: 100%;
}

Neste exemplo, você deixaria uma borda preta, de 1px, com 100% de radius, em todas as tags que possuírem a propriedade class="pub".

Mais sobre border:
Border CSS
Answer: Brother vc ja tem uma classe "pub" com ela vc consegue identifica-lo no CSS!

.pub {
  border-radius: 30px;
  border: 1px solid #FFF;
  color: #FFF;
  padding: 4px 12px;
  text-decoration: none;
  font-family: Arial;
  font-size: .9em;
  transition: all ease-in-out .4s;
}

.pub:hover {
  color: #333;
  background: #FFF
}

.menu {
  width: 100%;
  background: #333;
  padding: 10px;
}

  Publicar anúncio

Answer: CSS
.pub{
border: 1px black solid;
border-radius: 10px;
}

Styling em menus


slow http connection in LAN

Question: I have a weird problem I'm trying to solve, but can't find out how. I found that problem when trying to access a php page and only the basic html and css were loaded but the flash didn't. when I tried to download the swf file directly, I encountered an http timeout error.
In order to find the problem I ran some tests:
1) when I downloaded a file via FTP, the download speed was ok.
2) when I downloaded a BIG file (100M) via http - the download speed also was ok.
3) when I downloaded a small file (50K) via http - the download speed was very slow. I tried several file extensions but it gave the same result. This is the reason for the flash swf file to not load successfully - due to a timeout.
Edit: the file is downloaded, but corrupted since data is missing in the middle of the file
The most interesting part is that when I access the same page via localhost or outside of the network (s.a via ppp interface over cellular modem) the files are loaded perfectly. Therefore, the problem is only for LAN.
The server is apache2, over Ubuntu 10.04.
Any ideas?
Answer: It sounds more like some sort of LAN issue, either the network itself, the client machine, or the server. This is supported by you mentioning you are getting corrupted data in the middle of the file assumably over the LAN but not localhost/PPP.
I would try and narrow down the issue. A few things you can check:

Is it just HTTP or all other services being affected on the LAN?
Is it just this one server or all machines on the LAN?
Is it just outgoing data or incoming data?
Are there any relevant log messages (Apache, boot-up, system, etc...)?
Are there any firewalls (software/hardware) on the LAN that might be causing an issue?

Don't ignore the possibility of rare things like bad hardware (network card, router, switch, cable, etc...).
Answer: Only for LAN but not with "localhost" or over PPP? Sounds like a resolving issue to me.
Check your DNS-settings on the server: e.g. /etc/resolv.conf, local running BIND-server and look for wrong entries in /etc/hosts
Comment: i'm not connecting via DNS, but only by IP. does it still counts?
Comment: Yes, it still counts.
Comment: can you please specify what might be a wrong entry in those /etc/hosts?

slow http connection in LAN


Isolate Key/Value Pair from Laravel Model Relationship

Question: In my Laravel App, a poll has many poll options. I can create a collection of those options by simply running:
$result = Poll::find(1)->options()->get();
This query returns:
Collection {#387 ▼
    #items: array:6 [▼
        0 => PollOption {#388 ▼
          #table: "poll_options"
          #connection: null
          #primaryKey: "id"
          #keyType: "int"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:8 [▼
            "id" => 1
            "poll_id" => 1
            "option_text" => "Never"
            "responses" => 54
            "is_public" => 0
            "created_at" => null
            "updated_at" => null
            "deleted_at" => null
          ]
          #original: array:8 [▶]
          #relations: []
          #hidden: []
          #visible: []
          #appends: []
          #fillable: []
          #guarded: array:1 [▶]
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          #morphClass: null
          +exists: true
          +wasRecentlyCreated: false
        }
        1 => PollOption {#389 ▶}
        2 => PollOption {#390 ▶}
        3 => PollOption {#391 ▶}
    ]
}

Within my poll option, there is a column called responses, which returns an integer. I need to take the collection above and isolate the responses key/value pair.
Collection {#385 ▼
  #items: array:6 [▼
    "responses" => 54
    "responses" => 20
    "responses" => 10
    "responses" => 123
    "responses" => 33
    "responses" => 11
  ]
}

The only() collection method does exactly what I need, but I can't figure out how to structure the query when working with Eloquent models:
$options = Poll::find(1)->options()->get();
$responses = $options->only('responses');
dd($responses->all());

Returns an empty collection because the responses value is nested within the PollOption object.
I've also tried flatten(), but that seems to have no effect in this scenario.
Is there an easier way to return a single key/value pair within an Eloquent model collection?
Answer: It's not actually possible to assign the same key to multiple values within a collection. I knew this, but I wasn't thinking the problem through properly.
For future devs: the pluck() method takes two arguments: the value you want to pluck, and a second value that gets assigned to the key. Using the scenario above, I was able to write:
$result = $poll->options()->pluck('responses', 'option_text'); //Value and corresponding key

This results in something like:
Collection {#386 ▼
  #items: array:6 [▼
    "Never" => 54
    "Occasionally" => 21
    "2–3 times a week" => 80
    "4–5 times per week" => 33
    "Daily" => 11
  ]
}

Which ultimately did what I need it to do. Amit Gupta's mapWithKeys() answer is also correct, and will land you in the same place.


Ten minute piano practice techniques?

Question: It seems quite simple to allocate 10 - 15 minutes in the morning for a piano. At least much easier than to find later time for a longer session during the day.
There is a similar (and very good) "ten minute" question for guitar but most of answers there are instrument specific. Would it be possible to get recommendations on how to use short but daily time for a piano the most efficiently? Especially, does it make more sense to learn new thing or just play the known pieces?
Comment: The most "correct" answer is of course: scales.
Comment: If it was me and I only had 10-15 minutes, I would practice the last thing I learned before I forgot how to play it.  All my playing is from memory, however.
Answer: I'm a fairly early piano player, so I usually dedicate about 20 mins to practice.
I've found that the best thing to do is to timebox your playing time into sections, so for example 5 mins on finger exercises and technical studies, then 5 mins on a piece you're working on at the moment.
Schmitt's Preparatory Exercises for the piano is my choice for exercises. 5-10 mins of proper practice a day from Scmitt has been in my opinion the best use of my time, because it's all about correct basic technique, which is the most important skill for a beginner.
Answer: I´m a professional guitarist and teacher. My opinion is that you should keep the practice challenging enough so you can have small victories in that short period of time. You should link what you learnt today to what you learnt yesterday. You should advance everyday, and review the music you have learnt. So if you played an old piece  it perfect the first time why should you repeat it? But if you made a mistake try to go for the cause and solve it. Do you have a related mistake in other pieces? You can use your ten minutes to solve that problem, you could create exercises that address that same problem. As you see you can address the practice from many points of view. Get creative and keep your practice varied.
Answer: I've been playing for fifteen years, and I've come to appreciate the value of relaxing and setting an intention before sitting down.  It's so easy to sit down and play something you know, but if you're not mentally prepared you're much more likely to play sloppy and form bad habits.
For me, the first thing I do when I sit down is make sure each finger "understands" what it feels like to strike the key properly.  Once you have established finger action, focus on relaxing the arms and allowing them to move gracefully to make the finger action as graceful and effortless as possible.
Finally, you can either play a short piece you know slowly or work on a select few measures you've chosen ahead of time.
Bottom line - attention is the most important aspect.

Ten minute piano practice techniques?


I need help fixing a command (node.js

Question:
I can't get this code to work. I am trying to check if a user has this role and ban them.
Comment: Code in questions here should be pasted into your question as TEXT, not as an image and then formatted appropriately as code here.  This is so that people on mobile devices can see it, so that people can copy portions of your code into answers without retrying it all, so it can be indexed by search engines, etc...  Please edit your question to include the code as plain text and formatted appropriately as code.  Plus, I can't even read that image.
Comment: What's the intended function?
Comment: this is supposed to act as a ban command but the code up above in the image is supposed to be to check if the person has this role
Comment: Please add more information about the problem.
Comment: I edited the question to make the intended function clearer, is what I wrote right? If it is right, are you checking the user you mention or all users in the server?
Comment: Its actually supposed to check the user who sent the message roles to see if they have the role "ban"
Comment: Please update the post with a code example (not a photo) and more information about what the intended purpose is, what's not working, and what's expected to happen. "This is supposed to act as a ban command" and "check the user who sent the message roles" aren't the same thing.
Answer: You're going about it the wrong way, you don't need to look for the ban role, you just need to check if the GuildMember has a role named ban
if (message.member.roles.cache.some(role => role.name === 'ban')) return message.member.ban({ reason: 'Had the ban role' })

I need help fixing a command (node.js


How to interpret meaning of residual vs. predicted quantile plots in DHARMa?

Question: I understand that the lines in the residual vs. predicted quantile plots should be flat at each quantile, but I'm struggling to understand what each line is actually showing. Similarly, what does it mean if only one of the lines is off? I've included an example of this - thanks for any input.
Answer: I'm the developer of DHARMa. First of all, I would like to highlight the package help of plotResiduals(), which basically explains what is calculated:

The function plots residuals against a predictor (by default against
the fitted value, extracted from the DHARMa object, or any other
predictor).
Outliers are highlighted in red (for information on definition and
interpretation of outliers, see testOutliers).
To provide a visual aid in detecting deviations from uniformity in
y-direction, the plot function calculates an (optional) quantile
regression of the residuals, by default for the 0.25, 0.5 and 0.75
quantiles. As the residuals should be uniformly distributed for a
correctly specified model, the theoretical expectations for these
regressions are straight lines at 0.25, 0.5 and 0.75, which are
displayed as dashed black lines on the plot. Some deviations from
these expectations are to be expected by chance, however, even for a
perfect model, especially if the sample size is small. The function
therefore tests if deviation of the fitted quantile regression from
the expectation is significant, using testQuantiles. If so, the
significant quantile regression will be highlighted as red, and a
warning will be displayed in the plot.

Based on this, I would conclude that you have slight evidence for a humped-shape res~fitted pattern, which you should interpret as for normal lm residuals, i.e. there seems to be a nonlinearity in the data that is not captured by your model. You could, for example, try to add a quadratic effect for your main predictor(s).
That being said, given the low number of data points, this might as well be a statistical fluke.
Comment: I have to be curious. Why start the horizontal scale at 0.2 when (correct me if I am wrong) values start at 0 or just above? Are 0.2 and 0.6 special numbers in this context? If this your code speaking or some R default?
Comment: If rank = T, the x values are displayed as rank from 0 to 1. The current scale is what the R plot function chooses to display. I think I should force the axis labels to start / end at 0,1 if rank = T.
Comment: The fact that the qq plot chooses the same values is completely coincidental by the way, maybe you referred to the qqplot? This is again the default R plotting function for qq plots, it should be the same for plot.lm()
Comment: It's manifestly a side-issue, but thanks for coming back on that. Elsewhere I have code for similar plots and would always label 0 and 1 and usually some other points too.
Comment: I agree, would be an improvement.
Comment: Thanks for your response!


How do I correctly display OG content using Views?

Question: I have an Organic Group page, inside I have a view which lists out news items specific to this OG. However it is showing 'There is no content in this group' when I am not logged in. And shows up fine when I am logged in.
I have checked that the new article is published, the permission of the View is set to 'Permission' | 'View published content', and I also ensured that the 'View published content' permission is checked for anonymous user.
It's obviously a permissions issue, but I cannot see where else I can set permissions. I am using Workbench OG but there are no relevant settings on there.
How do I correctly display OG content using Views?
Answer: It could be that you use a relationship in the view that is restricted to only authenticated users.
Or it could be that you have set group content visibility to hidden.
But let's start from the beginning..check if it works with a simple view like this:
Create view of nodes, filter it by node type,
Add relationship: OG membership: OG membership from Node
Add contextual filter: OG membership: Group ID, and use the relationship you just created, and set default value: content ID from URL.
If the problem you describe still appears, you can check if it is a permission issue by selecting "Disable SQL Rewriting" in the views settings. But this will disable views permissions and is not wise apart from testing purposes.


Alternative to LinearLayouts' layout_weight attribute?

Question: I need a View to hold a number of TextViews, and the exact number I will not know unfortunately. I need the TextViews to sort of stack either under each other or right next to each other (imagine Tetris, but with just rectangles or squares). The way I have tried thinking about it is using LinearLayout to hold them either horizontally or vertically. I then use their weights to stretch them appropriately if they are next to each other. Otherwise, I use a vertical orientation. Problem is the performance with nested LinearLayouts with more complicated stacks. I thought about using RelativeLayout, but that wouldn't work because I need the TextViews to not overlap. So like if they are next to each other, they need to each take enough space evenly. With layout_weight it works great. I was hoping someone had any idea on how to make this work right/alternative.
Heres an example that is giving me a warning (only a simple example of what I am doing programmatically):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello World 1"
        android:background="#000000"
        android:layout_weight="1"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello World 3"
        android:background="#000000"
        android:layout_weight="1"/>
        <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello World 4"
        android:background="#000000"
        android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World 2"
        android:background="#000000" />
</LinearLayout>

I've tried it with RelativeLayout by the way, but one of the TextView's needs to be a set size, but I need them to take space evenly. I won't know specific sizes. Measuring the screen width and dividing it that way is also both clunky and not precise. I appreciate anybodies input.
Edit: So I've been thinking about it some more and thought of a solution using RelativeLayout. There is a nice example in the Android docs, but the only problem is one of the Views needs to be a set size so the other one could stretch. But if there is a way to allow all of them not to have a set size, that could work too, so then they can stretch. Anyone tried doing that at some point?
Comment: I don't understand your question. You say that you don't know how many `TextViews` there will be but then show an XML layout file. If you don't know how many there will be then you'll have to create your layout programatically.
Comment: @Squonk I added "Heres an example that is giving me a warning". I decided to test it out in a simple version compared to doing it with my more complicated version programmatically.Again, its an example.
Comment: What about a table layout? They are pretty easy to create in code, and seems like it could do what you want
Comment: @Jameo I have thought about that, but the issue is having the TableRow View as well. Like 2 Views to hold one View. Not very efficient. But I Have not used it very often. Any hints would be appreciated if you have a very efficient way in mind.
Answer: It's a bit unclear what your final use case looks like, so I don't know if this will completely solve your problem, but you might take a look at TableLayout (docs link).  It's based on LinearLayout so items can still be defined to evenly occupy a given space, but it allows you to define your positions and spans in terms of rows and columns.
So, for instance, your example code would look like:
<TableLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:stretchColumns="*" >

    <TableRow>
        <TextView
            android:text="Hello World 1"
            android:background="#000000"/>
        <TextView
            android:text="Hello World 3"
            android:background="#000000"/>
        <TextView
            android:text="Hello World 4"
            android:background="#000000"/>
    </TableRow>

    <TextView
        android:text="Hello World 2"
        android:background="#000000"/>
</TableLayout>

You can also use the android:layout_column and android:layout_span attributes to define exactly which column an item should be in, and how many columns it should occupy.  Also note that TableLayout and TableRow have basically ignore any layout params applied and use very specific (documented) parameters, so adding them to your code will only confuse what is actually going on.  Of course, this can all be built programmatically as well as in XML.
If this does not provide the flexibility you need, I would then recommend creating your own custom layout that either extends or is based on LinearLayout.  The mechanism is uses to measure children with weight is not that complex, and then you can override how each child is placed after measurement.  Here is a source link to LinearLayout if you want to see how the platform does these things.
Comment: Yea I was worried I would need to create my own custom View, but I have no idea how to do it it regards to extending LinearLayout. Anyways, I really appreciate your example code. I just tried it out and it works nicely for horizontal views within the TableRow :) In terms of efficiency, that extra TableRow shouldn't be an issue right? Oh and do you by any chance know a great tutorial on creating custom views? If not its fine, you've been a big help either way!
Comment: The performance should be slightly better than a nested layout with weights since it is an optimized case, though probably not as much as going fully custom since you can pull out all the code that doesn't do exactly what your application needs.  For doing a custom layout, you might look at Romain Guy's Devoxx session from a few years ago.  He live codes a FlowLayout implementation in the video: http://www.parleys.com/#st=5&id=2191&sl=0
Comment: WOW!! I would have never found that. I really appreciate your time and input. It really gave me enough to figure out my best options. Wish I could do more than just up-vote and accept. :)
Answer: Update: As we know the percent support library is deprecated from API level 26. ConstraintLayout is the new way to achieve the same flat xml structure.
Updated Github Project
Updated Samples:
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/fifty_thirty"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#ffff8800"
        android:gravity="center"
        android:text="@string/fifty_fifty_text"
        android:textColor="@android:color/white"
        app:layout_constraintHeight_default="percent"
        app:layout_constraintHeight_percent="0.5"
        android:textSize="25sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.5" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#ffff5566"
        android:gravity="center"
        android:text="@string/fifty_fifty_text"
        android:textColor="@android:color/white"
        android:textSize="25sp"
        app:layout_constraintHeight_default="percent"
        app:layout_constraintHeight_percent="0.5"
        app:layout_constraintLeft_toRightOf="@id/fifty_thirty"
        app:layout_constraintTop_toBottomOf="@id/fifty_thirty"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.5" />

</android.support.constraint.ConstraintLayout>

Deprecated
update: We can use android support library for the same.
compile 'com.android.support:percent:23.0.0'

Consider this demo for dividing the screen into 50-50 percent.
<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/fifty_huntv"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#ff7acfff"
        android:text="20% - 50%"
        android:textColor="@android:color/white"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="50%" />
    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_toRightOf="@id/fifty_huntv"
        android:background="#ffff5566"
        android:text="80%-50%"
        app:layout_heightPercent="80%"
        app:layout_widthPercent="50%"
        />

</android.support.percent.PercentRelativeLayout>

Output:

Demo HERE!!!
GitHub Project HERE!!!


How to create a User search view?

Question: I am trying to create User search view (using Views). But when I create the view, I am not able to see the search option in filter.
What I am missing?
Comment: The above question is too vague to be answerable. What do you want to do? Are you sure **Views** is the correct tool for doing it? How do you create a View? What do you expect to see in the search option in filter?
Comment: It is very simple question...I want to search User search result using views....
Comment: I do not want to use exposed filter for this...I want to use global search form...and drupal search url for showing the result...
Comment: I agree with @FreeRadical you have to provide much more info, including what you have done so far to try and resolve this...
Answer: Forgive me if this is more than you are looking for, or it is difficult to follow. Drupal's built-in search is bad for a number of reasons. One of them is how poorly it handles partial matches (i.e. 'appl' for 'apple'). Generally, search is done best when you use the search API module and integrate it with a search server. If you start down the path of looking into this you will find a lot of people saying you need to use SOLR, which is not the case. SOLR is great for more intensive applications, but you can make a very effective search system without it. This article details how:
https://www.webwash.net/drupal/tutorials/intro-search-api-part-1-how-create-search-pages
Following those instructions you will want to create an index of users. Then you will need to use the search views modules to create a view of the search results. The exposed filters (your search box is an exposed filter in this case) can even be placed in separate blocks.
This article describes that portion of the process:
https://www.webwash.net/drupal/tutorials/how-create-search-pages-using-views-drupal-7
This may be a little more work than you hoped for, but it will solve the problem.
Comment: Above articles not found useful to me...I am very clear..I am looking for search filter for User View. When choose user view...It does not show me Search option in filter...Do you know that
Comment: I'm not sure if the filter you are looking for exists the way you want it to. A more modest start is this: In your user view create a filter on the user name and expose the filter. You will now have an autocomplete filter that will search by user names. It will also show a list of users. If that is not desired you can work around the behaviour by also adding the user id filter and making it match uid of -1 BUT using the OR operator between the two. That will give you a simple autocomplete search field. But a real 'search' sytstem requires the method posted above.
Comment: I am trying to use the global search form and their result page for user search. sitename.com/search/user/rony - this will be my sample result page...but instead of normal result. I am trying to show user result using panel and views module.....

How to create a User search view?


Proportion comparaison between 4 modalities of one factor in R (chi2?)

Question: I would need help in order to perform a proportion comparison between 4 different modalities of one factor.
Here is an example.
I would like to compare the proportion of mother-to-child smoking between individuals from 4 different countries.
Contry   USA  INDIA  CHINA  ITALIA
Mother   100  2000   1600   200
Child    25   860    64     10
%        25%  43%    4%     5%

So what I would like to compare is then the percentage of smoking child between countries
I firts tought to chi2 test of fit to a uniform distribution law such as:
           USA  INDIA  CHINA  ITALIA
observed   25%  43%    4%     5%
expected   25%  25%    25%    25%

But I know chi2 does work only on numbers and not on proportions, right ?
Does someone have an idea of a test to support that USA and INDIA have a significantly higher level of smoking childs regarding their mothers compared to CHINA and ITALIA compared to what is expected if it were homogeneous ?
Thanks a lot for you help and time
Note: keep in mind that it is just a toy data, meaningless without any biological sens, I just want to put a sample example where I would like to compare proportions.
Comment: What do the numbers in your first table represent?
Comment: Number of people that smoke, in mother and  their childs respectively.
Comment: I cannot believe that, because I know far more than 100 mothers in the US smoke.  And because most mothers have multiple children, and numbers of children per mother vary among countries, what exactly does the "child" count mean?  How to conduct your test depends on what your data mean and how you collected them, making clear descriptions essential.
Comment: Hello whuber, it is a toy data, I simply invented the data and the biological question so that I could then report it on a real question. The idea here is to give a simple example so that community members can help. Here is basic idea is to compae the proportion of smoking child between countried, that's all...
Answer: A 4-sample proportion test. The null being prop.test can be used for testing the null that the proportions (probabilities of success) in several groups are the same, or that they equal certain given values.
> prop.test(c(25,860,64,10),c(100,2000,1600,200))

    4-sample test for equality of proportions without continuity correction

data:  c(25, 860, 64, 10) out of c(100, 2000, 1600, 200)
X-squared = 772.76, df = 3, p-value < 2.2e-16
alternative hypothesis: two.sided
sample estimates:
prop 1 prop 2 prop 3 prop 4
  0.25   0.43   0.04   0.05

resulting in a rejection of the null (unsurprisingly).
Comment: As pointed out in comments to [the previous version of this question](https://stats.stackexchange.com/questions/548003), this answer is not necessarily correct, because it depends (among other things) on whether a unique child is associated with each mother or multiple children might have been observed; and it also might depend on how many children the mothers tend to have.
Comment: thanks a lot for your help


- using charAt I am trying to write a code which should display which word as unique character

Question:
i am new to js.
using charAt I am trying to write a code which should display which word as unique character.
i achieved using array https://jsfiddle.net/at661zsu/
but how to achieve using charAt.
providing code below

//var wholeWord = "pak";
var wholeWord = "pakk";

for(i=0;  i<wholeWord.length; i++) {
    var firsLoopCharacter = wholeWord.charAt(i);
    var unique = true;

    for(j=0; j<wholeWord.length; j++) {
        var secondLoopCharacter = wholeWord.charAt(j);

        if( i === j)
        {
            continue;
        }

        if( firsLoopCharacter === secondLoopCharacter[j] )  {
            unique = false;
            break;
        }

    }
}

if (unique) {
    console.log("its an unique string");
}

else {
    console.log("not unique string");
}

Comment: Why do you need to use String::charAt ?
Comment: @GeorgeSimms requirement is I should not use array...can you update in my code...
Answer: If you want to test if a string doesn't contain duplicate characters, here's a function that uses String.prototype.charAt():
function isUniqueCharsString(str) {
  var chars = [];
  for (var i = 0; i < str.length; i++) {
    if(chars.indexOf(str.charAt(i))>=0){
        return false;
    }else{
        chars.push(str.charAt(i));
    }
  }
  return true;
}

It loops over the string characters and store unique charcters into a temporary array and test upon it.
Here's a Demo:

var wholeWord = "pak";

function isUniqueCharsString(str) {
  var chars = [];
  for (var i = 0; i < str.length; i++) {
    if (chars.indexOf(str.charAt(i)) >= 0) {
      return false;
    } else {
      chars.push(str.charAt(i));
    }
  }
  return true;
}

console.log(isUniqueCharsString(wholeWord));


How to determine whether to find an upper bound or lower bound

Question: I have a rather general question about sequences:

How do you determine whether it is appropriate to find an upper or lower bound of a sequence? In particular, suppose $a_n = \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{p_n}$ where $p_n$ denotes the $n^{th}$ prime. How do I know whether to bound the sequence from above or below?
Comment: Isn't your question a tautology then? To prove that it's bounded above, bound it from above; to prove that it's not bounded above, bound it from below (by some sequence you know to not be bounded above). Similarly if you want to prove/disprove that it's bounded below.
Comment: In order to do what?
Comment: @Qiaochu Yuan: Just for the sake of seeing whether it is bounded above or below.
Answer: Your question is vague, but for your particular example, the sequence a_n is bounded below by zero and doesn't have an upper bound. Look at here for more:
https://secure.wikimedia.org/wikipedia/en/wiki/Proof_that_the_sum_of_the_reciprocals_of_the_primes_diverges


Swift showing Firebase duplicating data (.observeChildAdded) not working

Question: Each time I add a new post to the database, the amount of times the posts show is increased by one. For instance, when I add one new post, the number of times the posts are duplicated is once. When I add another post (the view is reloaded) I see all the posts three times. I assume that the problem is with the function fetchPosts(), as each time the view loads it collects all the data from the firebase and appends it to the array. I have already tried emptying the array in the view did load, but that only makes all the posts show even more times. Also, I have tried using observe(.childAdded) and that results in no posts showing at all.
<code>    var ref: DatabaseReference!
    var postList = [Post]()
    var refHandle : UInt!

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
        super.viewDidLoad()
        checkForSignedIn ()
        ref = Database.database().reference().child("posts")
        fetchPosts()

    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return postList.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PostTableViewCell
        //set cell content
        let contentOfCellPost = postList[indexPath.row]
        cell.label?.text = contentOfCellPost.post_words
        cell.revealCount.text = contentOfCellPost.Reveals
        return cell
    }

public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let tableSize = tableView.bounds.height
    return tableSize
}

    func fetchPosts () {

        let query = ref.queryOrdered(byChild: "timestamp").queryLimited(toFirst: 10)

        query.observe(.value) { (snapshot) in

            for child in snapshot.children.allObjects as! [DataSnapshot] {
                if let value = child.value as? NSDictionary {
                        let post = Post()
                        let poster = value["poster"] as? String ?? "Name not found"
                        let post_content = value["post"] as? String ?? "Content not found"
                        let post_reveals = value["Reveals"] as? String ?? "Reveals not found"
                        post.post_words = post_content
                        post.poster = poster
                        post.Reveals = post_reveals
                        post.postID = child.key
                        self.postList.append(post)
                        print (post.post_words ?? "none")
                        DispatchQueue.main.async { self.tableView.reloadData() }
                        //make this for when child is added but so that it also shows psots already there something like query.observre event type of
            }
        }
    }
}
</code>
The console log at first, for instance, will show the correct number of posts :
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
When I add a new post, it shows this:
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
Answer: You need to clear your model (self.postList) at the beginning of the .observe block like so:
<code>query.observe(.value) { (snapshot) in
    self.postList.removeAll() //or however you can clear it
        for child in snapshot.children.allObjects as! [DataSnapshot] {
            if let value = child.value as? NSDictionary {
                    let post = Post()
                    let poster = value["poster"] as? String ?? "Name not found"
                    let post_content = value["post"] as? String ?? "Content not found"
                    let post_reveals = value["Reveals"] as? String ?? "Reveals not found"
                    post.post_words = post_content
                    post.poster = poster
                    post.Reveals = post_reveals
                    post.postID = child.key
                    self.postList.append(post)
                    print (post.post_words ?? "none")
                    DispatchQueue.main.async { self.tableView.reloadData() }
                    //make this for when child is added but so that it also shows psots already there something like query.observre event type of
        }
    }
</code>
Currently, each time the database is updated with a post, you add all posts to your model once again. Therefore you must clear your model each time you fetch all posts.
The reason why this doesn't work in viewDidLoad is because viewDidLoad is called only once, in the beginning, and not everytime the view appears -- thus the data will not be cleared upon adding a post.
Alternatively, you can use .childAdded -- but then you need to change the way you parse it because each snapshot with .childAdded returns a single post, not all the posts together.
Comment: This seems to fix the problem in the app - the correct number of posts show up. The only minor nuance left is that for debugging, I have added DispatchQueue.main.async { self.tableView.reloadData() }
                            print(self.postList), and this still shows duplicated posts in the console log, however the app shows the correct number of cells. Why is this?
Comment: override func viewWillDisappear(_ animated: Bool) { ref.removeAllObservers() } fixed it. Working as expected!


Interpreting interactions in 2 way ANOVA

Question: I ran a 2 way anova with 2 categorical IVs, i.e. age(young/old) and condition(control/low alcohol/high alcohol/marijuana) and 1 continuous IV. Most critically, here are my p-values on my interaction variables:
conditionLow_alcohol:ageYoung      0.32096
conditionHigh_alcohol:ageYoung     0.11353
conditionMarijuana:ageYoung        0.01446 < 0.05

as you can see only the marijuana:young interaction was significant.
My question is, how do I interpret this result? Do I say that there is an interaction between age and condition only when participants are in the marijuana group? or can I say more generally that there is an interaction between condition and age?
Answer: It looks like you used R's lm() function to perform this analysis. R has a very funky way of doing factorial ANOVA, and unless you made some critical adjustments, it will not give you the results you might expect from SAS or SPSS. First, R uses Type I SS, which means the effects depend on the order you enter your independent variables. Second, R uses a contrast coding scheme that is appropriate for regression but not for ANOVA. In particular, by default it uses treatment coding, which means that you aren't able to get a valid overall F-test for the effect of an interaction. So you can't simply say that the interaction is statistically significant. Your results imply that the effect of being young and taking marijuana increases relative to the expected combination of the main effects for each. That's not really a complete statement about the interaction as a whole, and the F-test for that interaction may not be significant (which is weird, I agree). This free book is an excellent guide to this issue.
Comment: That link doesn't work anymore


The distribution of $\bf{x}$ given an underdetermined system $A{\bf x}={\bf b}\sim N(0,\sigma^2 I)$

Question: Suppose I have an linear system $A{\bf x}={\bf b}$ such that $\bf b$ is a vector of IID normal random variables and $A$ has dimension $n\times p$ with $p > n$.
What can be said about the distribution of $\bf x$?  Must it come from a multivariate normal distribution?
Since the system is underdetermined one possible solution is certainly that $\bf x$ is multivariate normal, but since $A^TA$ is singular you can't explicitly solve for $\bf x$ as the sum of multivariate normal random variables.
We do have
$$A\mathbb{E}{\bf x}=0$$
$$A\text{Var}({\bf x})A^T=\sigma^2I$$
and thus the mean of $\bf x$ lies in the kernel of $A$.  Furthermore $\frac{1}{\sigma}A$ can be interpreted as the whitening matrix of $\bf x$, but that's about all I know.
Answer: Consider a simple case where $A = \left[\begin{array}{cc}1& 1\end{array} \right] $ and $\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \end{bmatrix}$.
Let $x_1$, $x_2$, and $b$ be random variables. We know from $A {\bf x} = {b}$ that $x_1 + x_2 =  b$. We also know that $b$ is a normally distributed random variable.

Must $x_1$ and $x_2$ be distributed multivariate normal? No.
Could $x_1$ and $x_2$ be multivariable normal? Yes.

In contrast, if $A \mathbf{x}$ is normal for any 1 by 2 matrix A, then $x_1$ and $x_2$ would be distributed multivariate normal (by definition of multivariate normality), but if $A$ is some specific matrix, all bets are off.

Example:
Let $b$ be a normally distributed random variable. Then define:
$${ x_1} = \left\{ \begin{array}{c} { b} &\text {if } {b} \leq 0 \\ 0 &\text{if } { b} > 0\end{array} \right\} $$
$${ x_2} = \left\{ \begin{array}{c} 0 &\text {if } { b} \leq 0 \\ { b} &\text{if } { b} > 0\end{array} \right\} $$
${x_1} + {x_2}$ is normally distributed but neither $x_1$ nor $x_2$ are normal.
Comment: Ah yes that's what I was afraid of, and even if you assumed $\bf x$ was multivariate normal you still couldn't determine its mean or covariance matrix exactly.
Comment: @Thoth Yeah, taking expectations, $A \mathrm{E}[{\bf x}] = \mathrm{E}[{\bf b}]$ and you have an underdetermined system for the mean of $\bf x$.


Loading fields of a node

Question: I have a simple content type, which contains the fields:

Title
Body

In my view the titles of the above content type are listed. When I click on a title, I want the body of the corresponding node to be loaded with AJAX and appended after the title.
Has anyone a hint for me, how to accomplish that?
Answer: Use built-in Drupal Ajax framework.. Steps:

implement hook_menu
build ajax callback
render links (titles) like /[menu callback menu item]/nojs/arguments and add class use-ajax

Here is a good tutorial: A little Ajax-driven article reader built with the Drupal Ajax framework
Answer: You can use Views Accordion module for the same. Module uses jquery accordion style plugin to show hide contents. It's not exactly what you are looking for since module uses hide and show concept instead of Ajax calls to load content. But User Experience wise good option.
Project Pages says

Views Accordion provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using
  the first field as the header for the accordion rows.
Comment: Thanks for your answer, but as there are multiple images in the body an Ajax call is needed due to loading times.

Loading fields of a node