Contar elementos de uma coluna

Question: Como contar o número de ocorrências em colunas?
Arquivo:
luz NC  luz
mas ADV más
blanquita   ADJ blanco
que CQUE    que
las ART el
que CQUE    que
traía   VLfin   traer
de  PREP    de
serie   NC  serie
mi  PPO mi|mío
coche   NC  coche

Script:
from collections import Counter

with open ("corpus_TreeTagger.txt", "r") as f:
    texte = f.read()
    colunas = texte.split("\n")

    def frequencia(colunas):
        for linhas in colunas:
            lexema = linhas.split('\t')[0]
            pos = linhas.split('\t')[1]
            lema = linhas.split('\t')[2]

        return Counter(lexema)
        return Counter(pos)
        return Counter(lema)

print(frequencia(colunas))

Erro:
Traceback (most recent call last):
  File "FINALV2.py", line 72, in <module>
    print(frequencia(colunas))
  File "FINALV2.py", line 23, in frequencia
    pos = linhas.split('\t')[1]
IndexError: list index out of range

Alguém poderia me ajudar?
Comment: Que tipo de arquivo é esse? o que divide as colunas? não há um caracter para separa-las? Vc cria o arquivo ou recbe de outra fonte? a terminação original é `.txt` mesmo?
Comment: Ok! Foi vcs que desenvolveram? se não, não há como configura-lo para que ele crie um caracter pra separar as colunas? do jeito que está, pelo menos visualmente, é impossível identificar as colunas, se pelo menos as mesmas tivessem largura fixa já ajudaria. [Veja esse texto](https://support.office.com/pt-br/article/Importar-ou-vincular-dados-em-um-arquivo-de-texto-d6973101-9547-4315-a8f8-02911b549306) (que, embora não nesse contexto, é sobre o assunto) para entender o que estou falando.
Comment: Veja se a minha resposta atende o objetivo
Comment: É um software que faz etiquetagem morfo-sintáxica. Nós damos um texto e ele faz a análise dividindo o arquivo de saída em três colunas: a palavra, a etiqueta morfológica e o seu lema.
Comment: Na verdade é uma coluna, uma tabulaçao, outra coluna, tabulaçao e coluna. Eu consigo imprimir toda a segunda coluna, por exmplo, deste jeito: linhas.split('\t')[2]
Comment: Obrigada @Sidon! Chama TreeTagger, muito utilizado na linguística e é um etiquetador em várias línguas, desenvolvido na Alemanha. O meu objetivo é fazer uma estatística de um texto, contando os lexemas, as etiquetas e os lemas. Estou tentando fazer um parser simples também. Imagino que existem outras maneiras de fazer, mas sou iniciante. Muito obrigada, vou dar uma olhada no Pandas :)
Answer: [TL;DR]
Pandas
Agora entendi o formato do arquivo, não sei se entendi completamente o objetivo, então fiz uma versão baseado no pandas, que conta as ocorrencias de cada palavra em cada coluna.
Primeiro vamos simular o arquivo, para facilitar inclui uma linha para identificar as colunas, isto pode ser feito facilmente em um sistema em produção.
import io
import pandas as pd

# Simulando um txt separado por tabs
s = '''
Palavra\tEtiqueta\tLema
luz\tNC\tluz
mas\tADV\tmás
blanquita\tADJ\tblanco
que\tCQUE\tque
las\tART\tel
que\tCQUE\tque
traía\tVLfin\ttraer
de\tPREP\tde
serie\tNC\tserie
mi\tPPO\tmi|mío
coche\tNC\tcoche
'''

Agora vamos ler o arquivo para um dataframe do pandas
# lendo o arquivo para um dataframe
df = pd.read_csv(io.StringIO(s), sep='\t')

Apresentando o dataframe
df
Out[15]:
      Palavra Etiqueta    Lema
0         luz       NC     luz
1         mas      ADV     más
2   blanquita      ADJ  blanco
3         que     CQUE     que
4         las      ART      el
5         que     CQUE     que
6       traía    VLfin   traer
7          de     PREP      de
8       serie       NC   serie
9          mi      PPO  mi|mío
10      coche       NC   coche

Agora vamos agrupar pela coluna Palavra e apresentar o número de ocorrencias de cada palavra dessa coluna em toda a tabela:
df.groupby('Palavra').count()

           Etiqueta  Lema
Palavra
blanquita         1     1
coche             1     1
de                1     1
las               1     1
luz               1     1
mas               1     1
mi                1     1
que               2     2
serie             1     1
traía             1     1

Agrupando pela coluna Etiqueta e apresentando o número de ocorrencias de cada palavra dessa coluna, na tabela:
df.groupby('Etiqueta').count()

          Palavra  Lema
Etiqueta
ADJ             1     1
ADV             1     1
ART             1     1
CQUE            2     2
NC              3     3
PPO             1     1
PREP            1     1
VLfin           1     1

Finalmente, os resulado do agrupamento pela coluna Lema e o número de ocorrencias de cada palavra dessa coluna em toda a tabela:
df.groupby('Lema').count()

        Palavra  Etiqueta
Lema
blanco        1         1
coche         1         1
de            1         1
el            1         1
luz           1         1
mi|mío        1         1
más           1         1
que           2         2
serie         1         1
traer         1         1

Baixe ou veja renderizado em jupyter notebook.

Contar elementos de uma coluna


Getting different results for admin versus non-admin user on view when there is a relationship

Question: I have a view that shows the two newest articles with specific taxonomy rules. We got a new requirement to now exclude articles that are linked via entity reference.
So I added the relationship for referencing entities. With just the relationship in place and no filters added, non-admin users only see articles that are related (the relationship is not set to required).
When I add the filter that node ID of the related (referencing) articles should be NULL, non-admin users see nothing, but admin users see the results as they should be.
What can explain the discrepancy and what can fix it?
Drupal 7
Comment: sounds like a permissions issue - do you have any content access modules or similar installed? Views usually honours permission control on nodes, so if the user does not have permission to see the content, it won't show in views
Comment: That would make sense for this case if it wasn't showing the data without the relationship. But it does show the data then. The content that references it is shown in a separate view right above.
Comment: that is definitely odd - if it were me (given the somewhat appearance of a permissions problem) I would create a new role, give it all permissions and see if a user with that role can view it properly.  If the user can, start taking away permissions until it fails - it would narrow down the problem (if it was or related to a permissions issue)
Comment: I got devel to output the query and I'm seeing this which isn't in the query when run by admin: SELECT na.nid AS nid FROM node_access. I'm not sure where this is set. I don't have any modules called node access, so I image it's set somewhere else.
Comment: Devel has a block that will show node access settings on each node, you could find out more about the issue that way. You may need to set your permissions correctly and rebuild the node access settings.
Comment: that's because admin by default has the permission to bypass all content access control, so Views doesn't even include it in the query - even including it though doesn't mean that's the problem - I will keep thinking about it, but nothing else comes to mind as a culprit
Answer: Seems like this problem is related to this drupal bug https://www.drupal.org/node/1349080 .
Solution: Edit your view > Right column "Advanced" > Query settings: check "Disable Query Rewriting"
Simple explanation for the bug and the solution https://www.drupal.org/node/1276450#comment-10451305, quote the comment below

Actually, this is a bug, in Drupal core, and there is a fix, in
  #1349080: node_access breaks any query that has node table appearing twice with a left join. It just has not been committed to Drupal core
  yet, because the fix is a bit brittle and may not work in all corner
  cases. It has to do with the node_access system, and any view that
  connects the node table or an entity table multiple times (e.g. via a
  relationship), when there is any access module enabled on the site,
  will trigger it.
Disabling SQL rewriting will bypass the issue, and should be entirely
  safe to do, unless you have some access rules you want to enforce
  (such as products in an OG group that only members of that group
  should be able to see) -- in which case you can usually address that
  by adding your own explicit filter to the view instead of relying on
  the core node access to filter it out for you.
If all your products are public, there's no need for this node_access
  check.

Cheers


Save variable in .awk file after completion for next time it runs

Question: So, I have a .awk file that will split one order file into many order files. The file name goes from orders.xml (main file containing say, 100 orders) into files that increment like order-1.xml, order-2.xml, order-3.xml etc.
When the .awk file is finished splitting the files, assume the last file is order-100.xml, how can I save that number for next time, so when the .awk file runs again, it begins from 101? so it will go order-101.xml, order-102.xml etc.
This is the current code I have but I can't figure out how to do it.
The variable being incremented is the 'count' variable, which applies the file name
script.awk
/<Order/ {
        rfile="order-" count ".xml"
        print $0 > rfile
        getline
        while ($0 !~ "<\/Order>" ) {
                print > rfile
                getline
        }
        print $0 > rfile
        close(rfile)
        count++
}

So, to sum it up, say the script finishes on order-65.xml, the next time it runs, it should start from 66.
Comment: What you're doing doesn't appear to be an appropriate use of `getline`, and you're using it incorrectly, see http://awk.freeshell.org/AllAboutGetline. If you [edit] your question to include a [mcve] with concise, testable sample input and expected output then we can help you do what you're trying to do the right way.
Answer: Something like this (untested since you haven't provided sample input/output to test against) is what you need:
#!/usr/bin/env bash
outdir='/some/dir'    # set this to whatever directory path you want to create the files in.
lastNr=$(printf '%s\n' "$outdir"/order-*.xml | sed 's/.*-\([^.]*\).*/\1/' | sort -n | tail -1)

awk -v count="$lastNr" -v outdir="$outdir" '
    /<Order/ {
        close(rfile)
        rfile = outdir "/order-" (++count) ".xml"
    }
    { print > rfile }
' "${@:--}"

You asked how to save the value of count between calls to the awk script but you're already saving that as part of the names of the files you're creating so the above shell script just reads that value back into lastNr before calling awk. I gave it a different name from count partially to make it clear what's a shell variable (lastNr) vs an awk variable (count).
Save that in a file called something like splitOrders, make it executable, and then execute it as ./splitOrders orders.xml
Note that splitOrders is a shell script, not an awk script. Internally it calls awk to interpret an awk script but it calls other commands (printf, sed, sort, and tail) too. Not also that a shell script is just one implementation of a command in Unix and you just name commands based on what they DO, not the language they're written in, so you don't give it a .sh or any other kind of language/tool-dependent suffix.
Answer: With your shown attempts, please have following code, in order to start xml file names from taking count from next to where it ended last time, create a file to keep its last time count and read it in starting of awk program each time it runs.
cat script.bash
#!/bin/bash
if [[ ! -f lastTimeCount.txt ]]
then
     varCount="1"
else
     varCount=$(cat lastTimeCount.txt)
fi

awk -v lastCount=$(varCount) '
BEGIN{ count=lastCount }
/<Order/ {
        rfile="order-" ++count ".xml"
        print > (rfile)
        getline
        while ($0 !~ "<\/Order>" ) {
                print > (rfile)
                getline
        }
        print > (rfile)
        close(rfile)
}
END{ print count > (lastTimeCount.txt) }
' Input_file

Comment: @DonnieBerry, yes code in `.awk` file is little different on running wise when we run it a direct awk code, in .awk script we need to run it by `awk -f script.awk file` format. Coming to your remembering the file name, let me fix it and get back here.
Comment: `testvar=$(cat test.txt) echo $testvar` is a shell script, not an awk script. awk is not shell. Ravinder didn't just post an awk script, he posted a shell script which, among other things, calls awk to execute an awk script. You are mixing up awk and shell and THAT is what's causing your problems, not MacOS vs Linux.
Comment: So, to be clear - you're getting those syntax errors because you're executing `awk -f scriptfile` but `scriptfile` doesn't contain an awk script, it contains a shell script. That's like running a C compiler on a file containing Fortran code - yes it will give you syntax errors.
Comment: Syntax error in the awk script `(lastTimeCount.txt)` --> `("lastTimeCount.txt")`
Comment: Two questions (sorry), I am new to this whole .awk programming. Can one line terminal awk scripts be run in a .awk file or is it completely different? and question 2, I don't want to hard code the '100', I want to make sure that whatever the count lands on the LAST time the script was ran, it begins on next time. So, if count ended on 56 last time, next time, it will begin on 57. Hopefully that makes sense!
Comment: @DonnieBerry, I have edited code now, this will create a output file named `lastTimeCount.txt` from where it will pick it up and start next to that count. Kindly do check it once and let me know how it goes.
Comment: Getting a syntax error. The context is: awk -v >>>  lastCount= <<< $(cat lastTimeCount.txt) '
Comment: @DonnieBerry, I just tested this is working fine for me. Create first time dummy file `touch lastTimeCount.txt` and then try running command once?
Comment: Tried that, so weird! Same error. Error in full is: awk: syntax error at source line 7 source file split-xml.awk
 context is
 awk -v >>>  lastCount= <<< $(cat lastTimeCount.txt)'
awk: bailing out at source line 7 source file split-xml.awk
Comment: @DonnieBerry, oh ok, you are on Sun OS, then try changing `awk` TO `nawk` and run same code, that should fly IMHO, let me know how it goes.
Comment: Sorry, should have said, I am on a Mac but they use UNIX so I thought the awk command would work as smoothly? Anyway, changing the terminal command to nawk didnt work, it says command isn't found
Comment: @DonnieBerry, sorry seeing your error I saw bailing out error so thought its mac O.S, let me do a tweak to code in a min.
Comment: @DonnieBerry, I have edited the code now. What it does is: if output file name `lastTimeCount.txt` is NOT present(which has count where it ended last time) then it will set count to `1` once 1st run is done then it should pick it from last time where it ended in next run of this script. NOTE: I have created script named `script.bash` which has all this code in it, make sure to give proper permissions to it and then try running it, let me know how it goes.
Comment: Still having some errors.. Can I ask though, I thought the terminals on mac and linux were more or less the same? Even running this simple .awk script: testvar=$(cat test.txt)
echo $testvar, gives me errors, it says there is a syntax error on the fullstop on the word 'test.txt', I don't see a syntax error but people on linux say it works, is there a reason for that?
Comment: @DonnieBerry, this code should work on Linux, I don't have Mac OS with me, but most of the awk codes work there, please give me error in comments here what you are seeing in code tags `like this`.
Comment: @DonnieBerry, Please try suggestion made by @ rowboat in previous comment and let us know if that helps you, thank you.


Prove that: (a * b)$^{x}$ mod n = ((a$^{x}$ mod n) * (b$^{x}$ mod n)) mod n

Question: (a * b)$^{x}$ mod n = ((a$^{x}$ mod n) * (b$^{x}$ mod n)) mod n
Can anyone give me some tips to prove the above equation?  Thanks.
Answer: This follows from basic modular arithmetic: if $k\equiv r\pmod{n}$ and $\ell\equiv s\pmod{n}$, then $k\ell\equiv rs\pmod{n}$. Since $(ab)^x = a^xb^x$, then what you have is just this instance with $k=a^x$, $\ell=b^x$, $r=a^x\bmod n$ and $s=b^x\bmod n$. The final "$\bmod n$" just assures that you fall inside the main residue class representatives.


ambiguous call to overloaded function with "bind" when i add header file"boost/function"

Question: I write a test of boost::function.
These codes are working.
#include <iostream>
#include <boost/lambda/lambda.hpp>
#include <boost/bind.hpp>
//#include <boost/function.hpp>
#include <boost/ref.hpp>
using namespace std;
using namespace boost;
template<typename FUN,typename T>
T fun( FUN function, T lhs, T rhs ){
    cout << typeid(function).name() << endl;
    return function(lhs,rhs);
}
int add4(int a, int b, int c){
    return a + b + c;
}
int main(){
    cout << fun(bind(add4,2,_1,_2),1,4) << endl;
    system("pause");
}

But when i add header file "boost/funcation"
VS2012 prompts me it.
error C2668: 'std::bind' : ambiguous call to overloaded function.
Answer: Don't import both std and boost namespaces into the global namespace, to avoid such an ambiguity.
Instead, either specify fully qualified names, like boost::function, boost::bind, or import particular symbols: using boost::function;.
Comment: That is exactly the problem! Thanks.


Why is the highest frequency on a piano 4186 Hertz?

Question: The human hearing range is between 20 Hz and 20,000 Hz. The lowest frequency on a piano is 27.5 Hz, which is almost at the start of the human hearing range. However, the highest frequency on a piano is only 4186.01 Hz. Why is this the highest frequency on a piano? In theory there could be a couple more octaves at higher frequencies. Why aren't there?
My own theory is this: The human ear's ability to distinguish between these higher frequencies is less effective than at lower frequencies. So higher frequencies all kind of sound the same, and having these frequencies doesn't add much to a pianist's toolset. Is that right?
Comment: I'd say thats true. Think about how much less tone you get in the last octave on a piano. It's almost more of a woody "plunk" than a note. You can distinguish pitch, but not easily.
Comment: Lots of great answers already... and an old question. But I just wanted to comment that it may have some relation to singing range since organs/harpsichords etc were often used to accompany voice
Comment: Try playing the highest D and C on a piano after a bunch of more regular C octaves; if you don't know it's a septime (is that the correct term? Gosh, musical theory in Eglish is hard) you'll probably say it's another octave.
Answer: Wheat stated in his comment that

"Theoretical physics or mathematics are largely irrelevant to musical
  instruments, or music performance and practice"

Let's see if we can answer this question using science adding psycho physics and engineering to the mix. I'm not trying to dispute what was already said, I'm just offering a different view point and approach to answer the same question.

Physics says that any periodic motions (such as the movement of a string) can be expressed as the sum of harmonic motions (motions of a single frequency). The frequencies are all integer multiples of the lowest or "fundamental" frequency
Physics says that the spectral difference between different instruments is primarily a function of the relative balance of the different frequency components.
Physics says that a piano note consists of a percussive onset (hammer hitting the string) and then a periodic motion of the string. The onset has a fairly wide (non-tonal) spectrum and the ringing string has a harmonic spectrum.
Psycho-physics says that human can perceive frequencies up to about 20 kHz. This is not a "black & white" cut off point but the sensitivity of the ear drops fairly quickly as the frequency gets higher. This effect is impacted by age and exposure.
Psycho physics says that perception of tonality and timbre is simply a function of the short term frequency spectrum of the sound at the ear drum
Physics says that the frequency at which a string vibrates is a function of mass, length & tension. In order to produce very high frequencies the string must be light, short and have a lot of tension.
Physics says that there are multiple ways that a piano radiates sound energy. The volume velocity of the string itself (how much air does it move), and mechanical energy transferred into the resonance structure of the pianos body and radiated through the surfaces of the piano
Physics says that mechanical loss in a piano surfaces gets higher with frequency

Taking all this we can draw some conclusions:

The maximum number of keys you could add would be 2 octaves. Above that nearly no one would be able to hear the fundamental any more
Even below that you would only get the fundamental and the first harmonic at max. At these high frequencies all instruments would sound the same as any difference in the harmonic spectrum are outside the human hearing range
As the frequency increases the harmonic motion of the string has less energy as compared the percussive onset. So you hear more and more "boink" and less and less "note". It turns into an a-tonal percussion instrument.
Getting any harmonic energy radiated is difficult. Since the string is very short the mechanical energy in the string is small. Loss in the piano's frame and wood is high so not a lot gets out. At the same time the radiated volume velocity is small as well (again, short string), so that doesn't radiate well either. In order to get enough sound radiated, you would have to add A LOT of strings.

So the scientists answer would be: "don't bother adding more keys: it would sound more like a percussion instrument that a piano, the tonal quality would be poor, and it's really difficult to get it loud enough"
Answer: Nobody can hear fundamental musical pitches up to anywhere near 20,000 Hz, not even new-born babies with perfect ears. The upper range of human hearing is only useful for hearing overtones and harmonics that are basically "felt" rather than "heard".
There are a few notes above the range of the piano that can be heard, but they are not musically useful. A very skilled violinist can produce these using harmonics. You could produce these pitches with some analog electronic synthesizers, but not with an acoustic instrument. If you try this yourself, it will occur to you that you've never heard these pitches used in any actual music because they are not musically useful and because few people can hear them, and those that can find them unpleasant to listen to.
Neil, piano design aside, there's a fundamental misunderstanding in your line of questioning. You read in a book somewhere that the range of human hearing goes up to 20,000 Hz. Well, so what? That is only a theoretical construct. Different individuals have different ranges of hearing. Most people can hear the pitches in the middle of the theoretical range of human hearing more or less the same, but there is a tremendous variation among people in how they hear pitches at the extreme low or high end. For virtually all people, the range of hearing decreases with age. Men as a group lose high-end hearing sooner in age than women. I am a man who has always been regarded as having excellent hearing, but at the age of 34 I discovered in a recording studio that I could no longer perceive a loud sine wave at 11,000 Hz, while younger women in the studio could hear that pitch (and clapped their hands over their ears in pain).
Furthermore, the frequency response of the human ear is not at all linear. It doesn't even follow a mathematically describable curve, because, again, human hearing is not based on mathematical laws; it's based on the physiology of the human ear and the brain. The loudness with which people perceive extremely high pitches is sharply attenuated.
A statement like "the human hearing range goes up to 20,000 Hz" is like saying "the range of human height goes up to 7-foot 2-inches (218cm)." Does the clothing industry only mass-produce clothes that fit people who are 7-foot 2? No, they make clothes that average people can wear. That way they sell more clothes.
Comment: It doesn't actually show that.  Noise-induced hearing loss (NIHL) tends to fit Fletcher-Munson, so without your care and judicious use of earplugs, you'd start losing somewhere around 4k first.  Most people lose their very high end due to age, rather than NIHL.  (Perhaps more relevantly, even if you can hear several semitones above 17kHz, you can't distinguish them as individual notes.)
Comment: There isn't a special kind of hearing for fundamentals, another for harmonics.
Comment: Although it is all variable - I recently had my hearing checked out (as I was worried what damage I was doing on stage) and found I still have good response over 20kHz in both ears. My left actually over 21kHz. Admittedly as a child my frequency range was quite a bit higher, but it shows that a bit of care and judicious use of earplugs can help.
Answer: The highest fundamental pitch on the piano is such that it is, and no higher, because it is not feasible to build any more higher-pitched strings into the harp of the piano. It's down to the limits of mechanical engineering and the properties of steel strings: string length, tensile strength, tension. What makes you think that it's possible to build an acoustic string percussion instrument that can play pitches up to the limits of human hearing? That would defy the laws of metallurgy and physics.
Please reference this question: Why piano keys are not integer factors of octave notes?
Musical instruments are built based on what is practical and possible to construct in the real world, not based on theoretical mathematics.
Comment: Being a scientist and a musician, I completely disagree with this statement. Most things that happen in musical instruments are very well grounded (albeit mostly empirically) in scientific laws and principles and theoretical physics and math are very relevant. I'm not trying to be controversial, but this would be a fun discussion to have!!
Comment: Well, I took a swing at a scientific answer below. I completely agree that instruments evolved by trial and error and not with physics. However, the laws of physics were their first and are the foundation of the "trial & error" even if the builders weren't aware of them. Now that we know these laws, we can understand this a lot better cut a out a few hundred years out of the process :-)
Comment: I do not wish to discourage this, but we get a lot of questions here from beginning musicians who have a background in science or engineering and say "The laws of physics say *this*, but the way musical instruments are made is *that*. Why are they different?" The obvious answer is that musical instruments are the way they are due to centuries of practical experience by millions of musicians. Theoretical physics or mathematics are largely irrelevant to musical instruments, or music performance and practice.
Comment: Yes, most things that happen in musical instruments are indeed grounded in scientific laws, but my point is that these instruments evolved over centuries by musicians and builders who had little or no knowledge of or regard for any scientific laws. The instruments evolved first by centuries of trial and error and craftsmanship, and much later, scientists studied the instruments and derived scientific laws from them. NOT the other way around. You see, "theory follows practice." Stradivari never heard of physics. Helmholz derived some scientific principles after he studied some old violins.
Answer: I think Josh's comment has the right idea. Since musical tones comprise many partial tones, as you approach the highest few octaves below 20,000Hz the upper partials of the notes fall off the top; and the tones lose their character. The notes lack richness and coherence.
Observe that 5,000Hz is only 2 octaves below 20,000Hz. So the 3rd partial and above have passed over the threshold and are inaudible.
I suspect Wheat's answer about the limits of frame and strings is probably the reason pianos stop where they do (the physical materials dictated a stopping point). My answer goes to explain why nobody found this to be a problem (no extra octave of tinkerbells were desired enough to become popular). You ("Joe Western Culture") really don't need notes any higher.
Inspired by Wheat, here's some anecdotal evidence:
Now, I'm probably considered hyperacute to pitches. Even in this seemingly quite room, I can hear the television monitor squeal, the laptop's teensy little squeek, and a 60cycle hum from the bathroom and the refrigerator (and cars and birds outside). But I've got a cousin who's much worse off. He can't go in to certain stores because of their shrieking broken-beam doorbell systems. When he pointed it out and stepped back outside, I became aware of sound he described, but I'm able largely to filter it out of my attention.
I suspect my cousin may have artificially increased his sensitivity by his work with restoring old radios, as I have with trying to read-along with the Rite of Spring.
Comment: That first sentence is funny if you know that my name is also Josh. :)
Answer: One factor not covered in the other answers is the physical width of the piano keyboard.
The size of a key is optimised for the typical human hand; let's assume it's not amenable to change.
Pianos have to fit in people's homes, classrooms, theatres, places of worship. Extra width has to prove its value.
The deepest note and the highest note should be reachable by a player seated in the middle.
I suspect market forces would have shaped the range of keyboard instruments. Perhaps once an instrument maker produced an extended-range piano. He probably didn't sell all that many, and hence it didn't catch on.
There is a market for keyboards with a reduced range - for reasons of cost and size. But enough people are willing to pay for, and make room for, 88 keys, that they continue to be the norm.
Bösendorfer make two grand pianos with extended ranges (92 and 97 keys), but clearly they do not sell well enough that their competitors are flocking to imitate them.
Answer: The oft-quoted 20Hz-20Khz range does not mean that people can perceive pitches in the range 20Hz-20KHz range but not 19Hz nor 20.1KHz.  Rather, there is a range of frequencies people can perceive as pitches, with people's ability to perceive things as pitches falling off near the ends of that range.  Beyond that, there is a range of frequencies which people cannot hear as pitches in and of themselves, but which will alter people's perception of how other frequencies sound.  It is the latter range which extends from 20Hz-20Khz; as with the former, perception falls off near the end of the range (adding a 10Khz signal to a 2Khz signal will make it sound different; adding a 15KHz signal may do likewise with a 3kHz signal, but the 15Khz signal might have to be louder to achieve the same effect).
Pipe organs often have some pipes which play pitches higher than the highest keys on a piano, but such pipes in isolation produce an annoying sound without a really discernible pitch.  Playing such pipes in combination with pipes that some octaves down, however, will yield a "brighter" sound than if those upper pipes were omitted.  The organist doesn't have to do any extra work to play those pipes beyond "turning them on".  Once they are enabled, anything the organist plays will be echoed some octaves up on the smaller pipes.
If a piano were to include an extra octave at the top, playing the notes in that octave in combination with notes an octave or two down could probably add a pleasant brilliance to the sound produced.  Unfortunately, playing everything in doubled octaves would limit what else the pianist could do.  Reed organs, in addition to having two sets of reeds an octave apart which could be individually enabled or disabled, and often had an octave coupler which, when enabled, would automatically operate the keys an octave above the ones the player was pressing.  I am unaware of any pianos ever having included such mechanisms, however.
Answer: Another obvious factor for not having that many scales in a piano, of course, would be the practical aspects of cost and space.
In particular, as to space, meaning the effort required to reach such high keys vs. the sound contribution to most music would not justify the cost nor space occupied by the instrument.
Not all instruments are suitable for sounding high frequencies. For high frequencies, in relation to hearing range, for instance, violins would have a preference.
High frequencies do come out of a piano, likely close to hearing limits, but they do that as harmonics, would say.
Answer: From my experience as an audio engineer, I can tell you that higher frequencies are distorted by the space you are in. It is impossible to maintain the ordinary ratios used in music (Just tuning's 1:2:3:4:5:6) because high frequency sound causes too much interference with its own reflections.  As a result, high frequency noise isn't used for music, but it does tell you what sort of a room you are in. This is also why bats use higher pitches to navigate, instead of lower ones.
Some friends of mine on the sound crew and I found this out when trying to hear the difference between cd quality sample rates (44100 Hz) and the same files at lower sample rates (usually 11025 Hz). With most of the recordings, we could reliably pick which was which, and the way we did it was by trying to hear what sort of space the recording was made in. At lower sample rates that information wasn't there.
Answer: Because it would sound shrill and generally awful, the frequencies would also start to bunch up more causing the actual note being played to disappear, that's just from a frequency based outlook, like science is why is basically what I'm saying. From a musical standpoint they'd rarely be used though. If you wanted more keys you could tune the notes to half or quarter tones and have a massive keyboard though.


Ant junit target to run tests having certain pattern?

Question: I want to my ant junit target to accept a String value from user. This String value will basically be the package name .The junit target should run the test present under this package and not any other test. How do i do the same. Currently , my junit target looks like this:
<target name="junit" if="run.junit">
        <junit dir="${project.root}" fork="true">
            <classpath>
                <path refid="junit.classpath"/>
            </classpath>
            <batchtest >
                <fileset dir="test">
                </fileset>
            </batchtest>
        </junit>
    </target>

How do i modify this to run the tests only as per the given input?
Answer: In the fileset resources, add an include pattern with the package criteria, e.g.:
<junit dir="${project.root}" fork="true">
     <classpath>
         <path refid="junit.classpath"/>
     </classpath>
     <batchtest >
         <fileset dir="test">
            <include name="my/package/**"/>
         </fileset>
     </batchtest>
</junit>

See the documentation for more examples.


How can I fix rattling tremolo?

Question: Why can a tremolo make a rattling sound? I changed the strings to thicker ones. I thought that the problem was a raised tremolo (but it didn't visually look like it), tried to tighten the screws on it and it didn't help. What else can I check myself or is it better go to a specialist?
Comment: You might think it's the tremolo, but it could be something else. Even a bad volume pot can make a rattling sound (heard only electronically), due to microphonic effects.
Answer: Take the bar off - does it stop?
Most common cause is the actual whammy bar rattling in its thread.
Fix is a few turns of PTFE tape on the thread before you screw it in, available from any hardware/plumbing store. Don't use sticky tape of any kind. PTFE is "teflon" & won't stick or jam.
If that's not it, you're going to have to give us better information.
Comment: Never worked out why the wangy bar is such an awful fit. Mainly in the Fender style guitar. One of the not-so-good points on Strats. Mostly he did a great job, which still holds good after 60 yrs, so can't complain. Except about that fit.
Comment: Agree - but I'm the son of a plumber, so I learned the PTFE tape trick waaay back in the 70s ;-)
Comment: I see it's been mentioned before & not just by me - https://music.stackexchange.com/search?q=ptfe
Comment: @tim on ebay you can buy a small spring that keeps the bar on a strat from rattling.
Comment: @bigbadmouse - I use them. 5mm or 6mm. But some Stratalikes have a through hole rather than a blind one. Won't work on those.
Comment: Spring £1 - might work on some guitars. PTFE tape, 20p - fits anything, so much left on the roll you can give it to your dad to fix the pipes or keep it for a lifetime's supply for you & all your friends ;)

How can I fix rattling tremolo?


Get form names in windev

Question: I use Itextsharp in WinDev and I try to get the names of a form.
My code is hereafter :
Machaine est une chaine
PdfSource= FicSource
PdfDestination = RepCible+"\"+fExtraitChemin(PdfSource,fFichier)+" "+CodId+".pdf"
MonStream = allouer un FileStream(PdfDestination,FileMode::Create)

MonPdfReader est un PdfReader(PdfSource)
POUR TOUT MaChaine  DANS MonPdfReader.AcroFields.Fields.Keys

FIN
The problem is that
"MonPdfReader.AcroFields.Fields.Keys"
is not accepted.
Thanks for your ideas ...
Comment: Please try to explain a more detailed what you want to do. The french sentences are belonging to the code or not? Please adjust it. :)
Comment: Ok.My aim is to get the fields names so that i can more easyly fill them
Comment: The french sentences are part of the code.
I do not succeed in defining the collection which is iterated.
Comment: In my code, "MaChaine" is a string and WinDev/Itext doesn't accept a string to refer to field.keys.
Comment: I eventually found out what was wrong.
If anybody interested :
PdfSource= Sai_FicSource //file pdf source
MonPdfReader est un PdfReader(PdfSource)
Monfield est un AcroFields.Item

POUR TOUT Monfield DE MonPdfReader.AcroFields.Fields.Keys
 MaChaine=Monfield
FIN
Comment: If this is your solution, please answer your own question. :)
Answer: As you didn't answer your question, here it is :
PdfSource = Sai_FicSource
//file pdf source
MonPdfReader est un PdfReader(PdfSource)
Monfield est un AcroFields.Item
POUR TOUT Monfield DE MonPdfReader.AcroFields.Fields.Keys
    MaChaine = Monfield
FIN

Get form names in windev


Como evitar redirecionamento de reescrita?

Question: Estou com a seguinte regra na raiz:
RewriteEngine On

RewriteRule ^webapp/(.*)$  ./sistema/public/v1/webapp/$1 [L,R=301]

O problema é que quando digito no navegador: http://projetoxyx.com.br/webapp
Ele está redirecionando e não reescrevendo para: http://projetoxyx.com.br/sistema/public/v1/webapp
VHost:
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    DocumentRoot "/Users/myuser/projects/projetoxyx"
    ServerName projetoxyx.local
    ServerAlias www.projetoxyx.local
    ErrorLog "logs/dummy-projetoxyz-error.log"
    CustomLog "logs/dummy-projetoxyz-access.log" common

    setEnv APPLICATION_ENV "development"
    <Directory "/Users/myuser/projects/">
        Options Indexes FollowSymLinks Includes execCGI
        AllowOverride All
        Require all granted
   </Directory>
</VirtualHost>

Este é do sistema: ./sistema/public/.htaccess:
RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]

    RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::^B$
    RewriteRule ^(.*)$ - [E=BASE:%1]
    RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

    Options -Indexes

O que precisa fazer para ele não redirecionar?
Answer: Remove o R=301, essa flag afirma que é para fazer o redirecionamento 301 conforme a documentação https://httpd.apache.org/docs/current/rewrite/flags.html#flag_r, mas se você só quer reescrever a url, remova-a assim:
RewriteEngine On

RewriteRule ^webapp/(.*)$ ./sistema/public/v1/webapp/$1 [L]

Eu não tenho certeza, mas creio que o ./ não esteja correto, se sistema/ está na raiz o correto seria isso apenas:
RewriteEngine On

RewriteRule ^webapp/(.*)$ /sistema/public/v1/webapp/$1 [L]

Alguns detalhes nesta pergunta: O que significa o L, R, NC no HTACCESS?


Angles between vectors: is my textbook wrong here, or am I mistaken?

Question: Below is a screenshot of my Calculus textbook, Stewart's Calculus: Early Transcendentals 8th edition. It's taken from the chapter on Vectors.

In Example 6, they ask to find the magnitude of the torque, which is the magnitude of the cross product of the force F and the position vector r:
$\tau = |\vec{F} x \vec{r}| = |\vec{F}||\vec{r}|sin(\theta)$
Where $\theta$ is the angle between the two vectors.
As I understand it, the angle between two vectors is measured if you start both vectors at the same tail, right? So in the diagram above, wouldn't the angle between the two vectors actually be 180-75 = 105 degrees? If so, why does my textbook use 75 degrees in its calculations? Is it because the sine of either of these angles will be the same, since both angles are above the x-axis in the 1st and 2nd quadrants?
Edit: or is the position vector in this case extending from the bolt to the end of the wrench? If that's the case, then I can see why it would be 75 degrees, since you would put tail to tail.
Comment: Sin(75 deg) = Sin(105 deg) so it doesn't matter which you use.
Also see http://math.stackexchange.com/questions/569105/why-is-sinx-sin180-circ-x if you aren't sure why
Answer: The position vector $\vec{r}$ is the vector with its tail at the bolt and its head at the point of application of force.
Answer: a) the position vector is usually taken to start from the origin, i.e. the bolt, so shift its tail to the end of the wrench and the angle will be $\pm 75^ \circ$.
b) depending on how you do the cross product ($r \times F$ or $F \times r$) and which value  you take for the angle, the torque will change sign.
c) The standard way is to take $\tau = r \times F= |r|\, |F| sin \theta$ with $\theta$ being the trigonometric angle spanned by $F$ in moving away from $r$.
In this way the torque is positive when it is exerted CCW, same as standard direction in trigonometry, and it will be a vector directed as the axis $z$, in a standard (right-hand rule) reference system.
In your case $\theta$ would be $-75^\circ$ (it is CW), and the torque would be negative (i.e, exerted CW, vector directed as $-z$).


Given $A^{-1}$ , find a matrix $C$ such that $ACA$ is a certain matrix

Question: $$A^{-1}= \begin{pmatrix}
1 &2 &1\\ 0& 3& 1\\ 4& 1& 2
\end{pmatrix}$$
Find a matric $C$ such that
$$ACA=
\begin{pmatrix} 2& 1& 3\\ -1& 2 &2\\2 & 1& 4
\end{pmatrix}.$$
My attempt at this problem is finding $A$, since the inverse of $A^{-1}$ is $A$.But I am getting fractions and I am not sure how to find $C$. Please no answers with cofactors as we are not in that chapter yet. Thank You.
Answer: $ACA= \begin {bmatrix} 2 & 1 &3 \\ -1& 2 &2\\ 2& 1& 4\\\end{bmatrix}$
$CA= A^{-1}\begin {bmatrix} 2 & 1 &3 \\ -1& 2 &2\\ 2& 1& 4\\\end{bmatrix}$
$C= A^{-1}\begin {bmatrix} 2 & 1 &3 \\ -1& 2 &2\\ 2& 1& 4\\\end{bmatrix}A^{-1}$
Answer: Hint:
If $ACA=B$  and $A$ is invertible ( i.e. there exists $A^{-1}$ such that $AA^{-1}=A^{-1}A=I$), than
$C=ICI=A^{-1}ACAA^{-1}=A^{-1}BA^{-1}$


How can I check if user logged in via mobile or using an application?

Question: On the login page, can we check if users logged in via mobile or using an application?
Basing on that, I need to check things.
Answer: There is a module for that, the Browscap module.

Browscap provides an improved version of PHP's get_browser() function.
  The get_browser() function can be used to tell what a visitor's browser is capable of. Unfortunately, the version provided by PHP has a number of limitations, namely:
  It can be difficult or impossible to configure for shared hosting environments.
  The data used to identify browsers and determine their capabilities requires consistent maintenance to keep up-to-date.
  Browscap automates maintenance by storing browser data in a database and automatically retrieving the latest data on a configurable schedule.

Configurating it is very easy, and you can use it with the Panels module to display or not a block if the user logged-in via mobile or not.
The current Drupal 8 version is 8.x-3.0-alpha2.


Implementing Oracle's RAWTOHEX function in C#

Question: I am looking to write the Oracle function rawtohex in C#.
I am looking at existing code that has been written and would like to be confirm if it is accurate.
public static string AsHexString1(this char[] chars)
{
    StringBuilder sb = new StringBuilder();

    foreach (var ch in chars)
    {
        int lowNibble = (int)ch % 16;
        int highNibble = (int)ch / 16;

        sb.Append(highNibble <= 9 ? highNibble.ToString() : ((char)('A' + (highNibble - 10))).ToString());
        sb.Append(lowNibble <= 9 ? lowNibble.ToString() : ((char)('A' + (lowNibble - 10))).ToString());
    }

    return sb.ToString();
}

Thanks.
Answer: As far as I know, RawToHex should be something similar to this:
public static string RawToHex(byte[] data)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.Length; i++)
        sb.AppendFormat("{0:X2}", data[i]);
    return sb.ToString();
}

I'm not sure why you're using a char array as input, since it's RAW data...
Comment: @pwee167 `rawtohex` is always performed on raw data. The database applies the function to the byte representation (cast) of the column in its character set. You may have character set conversion difference if your database doesn't use unicode (or the same flavour of encoding)
Comment: I'm not sure either to be honest as it is not my code. The data this is being performed on is stored in the db as char(80).
Comment: Thanks a lot @Jigsore for this code. I was really struggling to convert a RAW value from a Oracle Object ID column to string format. I was having issues in Datagridview that was being populated with the datatable coming from Oracle. This function helped me to convert those OIDs to string value and also the output string value matches the value as seen in Oracle DB table.


Clarification on the definition of separable Metric Space.

Question: In the 3rd edition of the Principles of Mathematical Analysis by Rudin, he defined a countable set as one which has a bijection between the set of Natural numbers and itself ie. it is infinite. He also defined a separable metric space as a set which possessed a countably dense set. Does this mean that all separable metric spaces have infinite dense subsets?
The reason for this question is the following:
A metric space in which every infinite set has a limit point is separable
In the solution provided in the link above and other solutions I've seen, a countably dense set was constructed but their definition of countable includes finite sets as well. No effort was shown to determine if the set needed to be infinite.
So for this particular question shown i Take countable as referring to finite sets as well?
Answer: Certainly every infinite separable metric space has a countably infinite dense subset. Let $ X $ be your space, $ D $ a countable dense subset (which exists by separability) and $ A $ a countably infinite subset (which exists as $ X $ is infinite). Then $ D \cup A $ is a countably infinite dense subset of $ X $.
As a general rule, when a question refers to a countable set, it should never require finiteness, as countable always at least includes the possibility of countably infinite. Thus, the distinction is often irrelevant, especially in the case of separable metric spaces as you can always perform the above maneuver to restrict to the countably infinite case.
Comment: Is D supposed to be dense in X?
Comment: Sorry, yes it is. I'll edit my post.
Comment: Just for clarification: all finite metric spaces are then separable?
Comment: Correct. In fact, all countable metric spaces are as well, as a space is dense in itself.
Comment: Btw. I think u don't need Set A as set D has to be infinite since every point in X is an element of D or is a limit point of D. i.e. If D is finite there exists q in X not in D. Hence, every neighbourhood of q has infinite elements of D.
Comment: It's not true that every element of $ X $ must be a limit point of $ D $. For example, take any finite space.
Comment: As in if X is an infinite space
Comment: You're right, if you have a dense finite subset in your metric space then the space will be finite. However, it's still not the case that every element of $ X $ will be a limit point of $ D $. Take, for example, $ X = D = \mathbb{Z} $ with the metric inherited from $ \mathbb{R} $. Then every point is isolated.


Open Source Foip Solution

Question: We already have an IPBX (AAStra ASX) for VOIP.
This IPBX gathers a T2 line.
We want to use the IPBX for Analogic Line and a FOIP solution (virtual machine) to send/receive fax by email (we are using MS Exchange 2010).
Is there  any Open Source Solution for Foip ?
Is it possible to "trunk SIP" my IPBX with this solution ?
Comment: I'm fairly sure that SIP trunks can't be used for FoIP, but I haven't looked into it for a long time.
Answer: You can try this open source FoIP solution http://ictfax.org
Answer: The only chance for this to work is to use a lossless codec (i.e.: g.711a or g.711u), which will try to ensure sync as much as possible. It's not 100% fail proof, but if your provider allows it, take a chance with it.
I've used such a solution, but with Asterisk (both over SIP trunk and E1 PRI) and it worked, so give it a try.

Open Source Foip Solution


Calculating endpoint for a function so arc length equals l.

Question: I'm trying to simulate a line hanging from a given point using a quadratic function.
The line is located at point $(x_0, y(x_0))$ where $y$ is my quadratic function.
Now, the line has length $l$, and I simulate it hanging and swinging from side to side by changing the quadratic and linear coefficient. This isn't really important in the problem, but I mention it just to give You a full picture.
Now, the problem is, that when I change the coefficients of the formula, the length of the line changes as well, and I have to pick a point $x_1$ in which the line will end so the length can stay the same.
Of course, the simplest way is just to pick a point $x_1$ such that distance from $(x_0, y(x_0))$ to $(x_1, y(x_1))$ is equal to $l$, but this actually calculates the straight-line distance, not the arc length, so for certain coefficeints this becomes really inacurate.
So, the proper way to find $x_2$ would be solving this equation:
$$\int_{x_0}^{x_1} \sqrt{1+f'(t)^2} dt = l$$
For a proper $x_1$. However, after integrating it's really complicated to "extract" $x_1$ from the equation.
Thinking about this, I have found a stupid idea that doesn't work, but I dont know why, and this is the main point of my question.
So, for this integral exists a antiderivative $F(x)$, so this whole equation can be represented as:
$$F(x_1) - F(x_0) = l$$
So:
$$F(x_1) = l + F(x_0)$$
Now, $l$ is a constant, and $x_0$ is set (I'm just solving for $x_1$), so $F(x_0)$ is a constant as well. This means, that I just can differentiate the whole equation over $x_1$ and get:
 $$F'(x_1) = 0 => \sqrt{1+f'(x)^2} = 0 $$
Which is obviously wrong, because it doesn't depend at all on values of $l$ and $x_1$.
So now, I have two questions:
1. Why is my differentiaton step wrong?
2. Is there any way to simplify solving for this integral?
Thank You so much for help with this problem!
Comment: When you differentiate a function w.r.t to a variable, you first differentiate in terms of the variable and then evaluate. What you are doing is differentiating $F(x_1)$ w.r.t $x$, which would be $0$, as $x_1$ is some fixed point
Answer: Note: This is an incomplete answer as I only answer part 1.

For question 1:
This is the same as attempting to "solve" a quadratic equation as follows:
\begin{align}
x^2 + 3x + 2 &= 0\\
\implies\dfrac{d}{dx}(x^2 + 3x + 2) &= \dfrac{d}{dx}0\\
\implies 2x + 3 &= 0\\
\implies x &= -\dfrac{3}{2}
\end{align}
One can easily verify that $3/2$ is not a solution of the first equation.
The problem is the following:
When we write $x^2 + 3x + 2 = 0$, we do not mean that the written equation is an identity. That is, it is not true that $x^2 + 3x + 2 = 0$ for all $x \in \Bbb R$.
What we are writing is that there's some $x$ such that $x^2 + 3x + 2 = 0$. So it does not make sense to differentiate both sides with respect to $x$ since it does not hold for "variable" $x$. (If you recall, the derivative of a function is a limiting operation, whereas the above equation holds only for two "discrete" points.)
Answer: For simplifying things, what I suggest is consider your hanging point the origin of your coordinate system, Hence $(x_0, y_0) = (0,0)$
Now, let the general quadratic passing through the point be of the form
$$y = ax^2 + bx$$
$$\implies y' = 2ax + b$$
Now, for curve length, we have
$$\int_0^{x^*}\sqrt{1+(2ax + b)^2}dx = L$$
Any further simplification is difficult, and you'd mostly end up using Lambert W functions to reverse solve for $x^*$.
Answer: This is an answer only to question (1).
Your differentiation step isn't wrong. What is wrong is the conclusion you draw. What that gives you is that $$\sqrt {1+f'(x_0)^2}=0.$$
By the way this shows that $f'(x_0)$ is imaginary.


Procedure to devise Questionnaire

Question: I understand that the reliability and validity are key while constructing a questionnaire. Kindly advise if the following procedures are appropriate to devise a questionnaire:

After creating all the items in the questionnaire, I plan to test the question with a sample of 25 participants. Next, I will re-test the same questionnaire with the same sample group, at some other time. To check internal consistencies, I will run a regression analysis to find the value of Cronbach alpha or Rho.

Please advise.
Comment: Chronbach's alpha is not part of regression analysis.
Answer: These procedures aren't bad, but they don't say anything about validity and don't fully address reliability.
Your first sentence "after creating all the items" covers a lot of ground. How will you write the items? How will you review them? How will you revise them?
"I plan to test the the question" what about pilot testing?
Testing and re-testing on a group is good, that gives you test-retest reliability. What will you do if it is low? How low is too low?
Chronbach alpha is a measure of internal consistency, that's also good. But, again, what is too low? What will you do if alpha is low? What about item analysis?
And what about validity? What constructs, tests, measures etc will you compare your results to? How will you be sure that your questions cover all the areas you want to cover? Will you do a factor analysis to see if there is evidence of multiple factors?
How extensive your questionnaire development should be depends partly on your budget and partly on what you intend to do with the questionnaire, but getting a fully validated questionnaire is a long and complex process.
Comment: good answer. but I believe there are textbooks written on this topic. there is no way to possibly address all the issues in a post.
Comment: You are correct. I meant a "pilot" testing with 25 participants for the testing and re-testing method. (i) I understand that if Cronbach alpha is closer to 1, does that indicate that the internal consistencies are strong among the items.
Comment: (ii) If alpha is low, I will delete/change the item that has low alpha. (iii) I am not sure how to perform item analysis. Kindly clarify.  (iv) So do I need to conduct a factor analysis as well in order to ensure that the constructs or measures are valid. The items of this questionnaire have been derived from existing validated questionnaire.
Comment: Item analysis involves looking at each item and seeing if it has good properties. E.g. if everyone gives the same answer, it isn't a useful item.
Comment: If you are deriving the items from an existing questionnaire, why not just use that one?
Comment: The context is different. For instance, the existing questionnaire has been used to evaluate perception of usability in the computer desktop domain, while my study is in the tablet area. That is why I needed to change the wording and at times, shorten the sentence etc.
Comment: Regarding Item Analysis, say if everyone says "disagree" on the 5 Likert Scale, does this become a red flag?
Comment: I do not understand what is meant by unidimensional scale? The link http://www.ats.ucla.edu/stat/spss/faq/alpha.html explains that the eigen value of item1 is much larger than item2, and item1 accounts for 67% of the variance. Can you please elaborate what does that imply? Thank you
Comment: Does the order of the items in a questionnaire matter?
Comment: The order certainly can matter

Procedure to devise Questionnaire


How to change ajax url when used in a callback

Question: How can url be changed from /devices/cars to /devices/trucks?  I chan change autocomplete's source, but as a matter of principle, would rather not duplicate the callback.
$(function(){
    $("#autofield" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                dataType: "json",
                url: "/devices/cars",
                data: {term:request.term, type:'all', fields:['id','name']},
                success: function(json) {
                    var data=[];
                    for (var i = 0; i < json.length; i++) {
                        data.push({id:json[i].id,label:json[i].name});
                    }
                    response(data);
                }
            });
        },
        minLength: 2,
        select: function( event, ui ) {
            $(this).parent().find("input[name='itemId']").val(ui.item.id);
        }
    });

    $("#changeUrl").click(function() {
        //Change url from /devices/cars to /devices/trucks
        $("#autofield" ).val('').autocomplete( "option", "source", function( request, response ) {
            $.ajax({
                dataType: "json",
                url: "/devices/trucks",
                data: {term:request.term, type:'all', fields:['id','name']},
                success: function(json) {
                    var data=[];
                    for (var i = 0; i < json.length; i++) {
                        data.push({id:json[i].id,label:json[i].name});
                    }
                    response(data);
                }
            });
        } );
    });
});

Comment: you would like to change it on runtime?
Comment: @ArupRakshit  Change it after page load.
Answer: Easiest way I see is to just create a variable that will be your url, unless I'm misunderstanding your question.
var dynamicUrl = "/devices/cars";

$("#changeUrl").click(function() {
    dynamicUrl.val(dynamicUrl.val() == '/devices/cars' ? '/devices/trucks' : '/devices/cars');
});

$.ajax({
...
    url: dynamicUrl,
...

Comment: I don't think `dynamicUrl` can be referenced this way.
Comment: @user1032531Why not? I just tested an ajax call and you can most definitely pass a variable to the url parameter instead of a string.
Comment: Yes, with the ajax part you could, but autocomplete's closure is causing problems.
Answer: Here is a way to change the URL based on an array index.
This will enable you to use as many URL as you wish.
Notice that you have to destroy the previous instance and re-instanciate it with the new URL.
$(function(){

    var ajaxURLs = ["/devices/cars","/devices/trucks", "/devices/planes", "/devices/boats" ];

    var usedURL = 0;  // The array index.

    function autoCompleteInit(){
      $("#autofield" ).autocomplete({
          source: function( request, response ) {
              $.ajax({
                  dataType: "json",
                  url: ajaxURLs[usedURL],
                  data: {term:request.term, type:'all', fields:['id','name']},
                  success: function(json) {
                      var data=[];
                      for (var i = 0; i < json.length; i++) {
                          data.push({id:json[i].id,label:json[i].name});
                      }
                      response(data);
                  }
              });
          },
          minLength: 2,
          select: function( event, ui ) {
              $(this).parent().find("input[name='itemId']").val(ui.item.id);
          }
      });
    }

    // On load init
    autoCompleteInit();

    // Change handler
    $("#changeUrl").click(function() {
        //Change URL to the next URL in array

        usedURL++;

        // Back to first URL if cycled throught all URL
        if(usedURL > ajaxURLs.length-1 ){
          usedURL = 0;
        }

        // Destroy previous autocomplete instance ans re-initialise it with the new URL.
        $("#autofield" ).autocomplete("destroy");
        autoCompleteInit();
    });
});

Comment: I guess I can just reapply each time, but seems like it should be possible to be more precise.
Comment: Instead of destroying previous autocomplete instance ans re-initialise it with the new URL, just changing the URL.  Maybe just not possible.
Comment: The best way is to try... I admit I didn't tested... But I'm quite sure it has to be re-instanciated.
Answer: Create a function containing the Ajax call and pass the url (or the prefix) as an argument.
Like
getDevices(url)


Induction Hypothesis Should there be a plus sign

Question:
$$\sum_{i=0}^n2^i=2^{n+1}-1.$$

After going through the steps I come up with
$$2^{k+1}+1,$$
And I expected
$$2^{k+1}-1.$$
Therefore it is false.
Can someone check and see if this is correct?
I can't find a way to validate my answer.
Comment: Why not check an example of two?  That will immediately tell you which formula is correct.
Answer: The second step of the induction requires that:
if we suppose $\sum_{i=0}^{n}2^i=2^{n+1}-1$ then it is true also for $n+1$? I mean it is true that $\sum_{i=0}^{n+1}2^i=2^{n+2}-1$? Yes, in fact by induction hypothesis:
$\sum_{i=0}^{n+1}2^i=\sum_{i=0}^{n}2^i+2^{n+1}=2^{n+1}-1+2^{n+1}=2(2^{n+1})-1=2^{n+2}-1$.
Comment: I was going in circles with this concept. There was a mixed bag way about how it was being taught on the net. Susanna S. Epp's book and your input here saved my day - actually days and night. Thank you very much!
Comment: @coder3 You're welcome!


Building Mongodb 3.0.0 with SSL

Question: I am trying to build Mongodb 3.0.0-rc8 (tried latest nightly too) with ssl support.
I found a gist which works for 2.6.7 but when I run it with 3.0.0-rc8 I get that eror
src/mongo/crypto/crypto_tom.cpp:30:2: error: #error This file should not be included if compiling with SSL support

I am building it in docker so the environment should be fairly standard.
Any idea?
Answer: Remove the file crypto_tom.cpp and try again.
Answer: So after some try and error (Thanks @wesley that put me on the right path), there is a known bug where if you try to  build all the different target despite what you specify if you put the source in the parent folder of where you want to install them.
I put my source in /usr/src/mongo and the target is /usr/
So I assume it try to build the non ssl as well as the ssl version.
Once I put my source in ~ in worked like a charm.
Hope it will help someone else with the same non descriptive error.

Building Mongodb 3.0.0 with SSL


std::array class member set during compile time?

Question: I have a class with private member std::array<int,10> m_arr; which contains zeros by default, but in one case it must be set to something else.
There is a setter for that class
void setArray(const std::array<int,10>& arr)
{
    m_arr=arr;
}

However I was wondering if the setting can be done compile time somehow for that specific case?
Thanks in advance.
Comment: That depends on what exactly distinguishes that use case?
Comment: It should be possible when `const std::array& arr` param is known at compile time. If it's users input etc. it's not possible
Comment: In that once case do all of the values need to be something other than 0 or will they have different values?
Comment: `const std::array& arr` is known at compile time, not user input and the values are different for zero.
Comment: you need `constexpr`, not just `const`
Answer: A possible solution can be the following one:
#include<utility>
#include<array>

struct S {
    constexpr S(): arr{} { }

    template<std::size_t... I>
    constexpr S(std::integer_sequence<std::size_t, I...>): arr{ I... } { }

    std::array<std::size_t, 10> arr;
};

int main() {
    constexpr S s1{};
    constexpr S s2{std::integer_sequence<std::size_t, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1>{}};
    // equivalent to: constexpr S s3{std::integer_sequence<std::size_t, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9>{}};
    constexpr S s3{std::make_index_sequence<10>{}};
}

Note that integer_sequence is part of the C++14 revision.
Anyway, you can find online an implementation of such a structure that is suitable for C++11 based projects.


Evento onBackPressed

Question: Tenho um projeto com NavigationDrawer, na pagina principal tenho um menu, e nas outros fragmentos eu inflo, só que quando pressiono o voltar do navigationbar 'botão voltar do celular', ele fecha o aplicativo e não retorna 'ou retorna uma pagina ou um fragmento', queria que ao pressionar ele retornasse e não fechasse o app.
Segue o onBackPressed
public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

Comment: Teria como dar mais detalhes do problema?
Comment: Tenho um projeto com NavigationDrawer, na pagina principal tenho um menu, e nas outros fragmentos eu inflo, só que quando pressiono o voltar do navigationbar 'botão voltar do celular', ele fecha o aplicativo e não retorna 'ou retorna uma pagina ou um fragmento', queria que ao pressionar ele retornasse e não fechasse o app.
Comment: Entendi. Edite sua pergunta e coloque seu comentário nela.
Comment: Dê uma olhada nessa resposta no SOen:  https://stackoverflow.com/a/14530879/2570426
Comment: certo, eu consegui voltar pra um fragmento escolhido, e depois quando chega nele o voltar não faz mais nada, queria que quando chegasse no fragmento escolhido ai sim ele fechasse o app.
Comment: Como vc está criando os fragments?
Comment: No meu `onNavigationItemSelected` está o seguinte.

`Fragment meuFragmento = null;
        boolean fragmentoSelec = false;`

`if (id == R.id.nav_quem_somos) {
            meuFragmento = new quemSomos();
            fragmentoSelec = true;`

`if (fragmentoSelec == true) {
            getSupportFragmentManager().beginTransaction().replace(R.id.content_principal, meuFragmento).commit();
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;`
Answer: Olá, pode tentar o seguinte:
   public void onBackPressed() {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    //retorna o drawer
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);

        // retorna todos os fragments que estão em backStack
    } else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        getSupportFragmentManager().popBackStack();
        if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
            //Volta o titulo pra Activity
            toolbar.setTitle("Activity");

        }

    }
    //fecha a aplicação, aqui você pode fazer voltar para alguma activity
    else {
        super.onBackPressed();
    }
}

Quando chamar os fragments acrescente em todos  addToBackStack(null) da seguinte forma:
getSupportFragmentManager().beginTransaction().replace(R.id.content_principal, meuFragmento).addToBackStack(null).commit();

Exemplo no github: onBackPressed
Comment: Ainda está fechando o app.
Comment: Olá amigo, editei, testei aqui e para mim funcionou perfeitamente, tenta fazer desse jeito que mandei agora.
Comment: Se quiser te mando o exemplo simples que fiz pra teste.
Comment: Manda se for possível,
Comment: manda pra email@example.com
Comment: Mas pra você desse jeito que coloquei, ainda não está voltando o fragment? e nem o drawer fecha quando clica no botão voltar? Coloquei o link do exemplo na edição da minha resposta
Comment: Murilo, se eu chamar o fragmento pelo menu e voltar ele funciona e volta para a tela anterior e depois fechar o app normal, mais eu coloquei uns botões na tela principal chamando os mesmos fragmentos, e quando volto ele fecha, não volta para o anterior.
Comment: Resolveu, coloquei essa linha `addToBackStack(null)` nos botões também.
Comment: @AriMelo esqueci de mencionar isso mesmo. Precisa colocar o addToBackStack() em todos os fragmentos para realizar a opção de voltar. Se tiver alguma dúvida a mais, eu te mandei um email no sábado só me responder por ele que eu ajudo. Abraço
Comment: Blz @MurilloComino, a única coisa que notei foi que, ao voltar pra tela inicial ele não está trocando o nome na barra toolbar, está ficando o nome do fragmento que se abre.
Comment: @AriMelo, editei a minha resposta, se você está chamando os titulos da toolbar dentro do fragment, alterando na sua MainActivity o  `onBackPressed()` na parte do `else if(...)` como editado na resposta dará certo, assim como testado e atualizado o projeto no github.

Evento onBackPressed


How to work with product meta field in Shopify?

Question: I have created a custom meta field for blog posts in Shopify. It's of the type product and I have chosen List of products.
I want to loop through the products and render them using the theme's product-grid-item template.
My problem is, that the type of my meta field output is a string - not an array.
If i try to output the field like this {{ article.metafields.blog_post.feature_products }}
I get the following:
["gid://shopify/Product/8078688583991","gid://shopify/Product/8078688715063","gid://shopify/Product/8078689141047"]
Which looks like an array, but liquid sees it as a string.
I have tried to loop through it like the following. But nothing happens
{% for product_id in article.metafields.blog_post.feature_products %}
  {{ product_id }}
{% endfor %}

It feels like I'm missing something obvious. It doesn't make sense, that the output is a string.
Does anybody know how to output it like an array? Or how to convert the string to an array - without the quote-marks, brackets and so on.
Answer: For metafields that allow multiple values, the list of values is stored in the value property of the metafield. Add .value at the end of your loop statement.
Note that your product_id variable will be a product object. I suggest you rename it to "product". You can then access the id (and other properties) using the dot notation.
{% for product in article.metafields.blog_post.feature_products.value %}
  {{ product.id }}
{% endfor %}


Updated Android SDK, now have problems installing apk to real devices

Question: I'm developing a taxi order application for Android. Two days ago I got stuck with a problem that I couldn't use Internet on emulator - it refused to work. The cause was in network settings in Windows, but I learned it later. That time I just tried to reinstall Android SDK hoping everyrhing will be repaired. Before that I was working with revision 16. Now I installed revision 20. My Eclipse ADT plugin automatically updated to support newer SDK version.
Now I work without real device and test everything on Android emulator. Today I sent the newest release of my app to my chief but I refused to be installed. The minimal SDK version is 8 (2.2), and the chief has an Android 2.3 device. He tried to install this app onto other two devices. Another 2.3 device also declined apk, but a 2.2 device accepted it. What's the problem? Note that I didn't set max SDK version. I also tried installing and running my application an a 2.3 emulator, everything was fine.
P.S. Problem solved, see Tim's suggestion below.
Comment: This is why I never develop on the emulator. I know that you can't always use a real device, but there are differences between real and emulators. Anyways, does your chiefs device accept unknown sources for app installations? Check the settings. It may be that.
Comment: No, there was never a problem for him to install apk received over email. Today he also tried to install some over verison of my program I emitted before reinstalling SDK - and everything was fine!
Comment: (read here "some older version")
Answer: If he had an old version installed have him try uninstalling that first. My guess is that you got a new debug key and it is failing install due to different keys.
Comment: That's an idea! We'll try it!


A question about normal subgroups.

Question: Let $G$ be a group and $\mathcal{A}=\{S_i\subseteq G \mid i\in I \}$ ($S_i$ is a no-empty subset of $G$.)
Conditions:

$G=\bigcup_{i\in I}S_i$;
For any  $i,j\in I$, we can find $S_k,\,\,s.t.\;S_iS_j\subseteq S_k$;
For any $i,j\in I$, $S_i\subsetneqq S_j$ is impossible.

Prove that $\mathcal{A}$ is a set of all cosets of some normal subgroup of $G$.
I have tried in this way:
Let $S_1$ contains $1_G$. Then I have proved $S_1$ is a subgroup of $G$. If we can prove that $S_i(i\neq 1)$ is exactly a right (resp. left)  coset of $S_1$, then $S_1$ will be a normal subgroup. But I failed , so how can we prove that  $S_i(i\neq 1)$ is exactly a right (resp. left) coset of $S_1$?
Answer: Consider $a\in G$; then $a\in S_i$ for some $i$. We know $S_iS_1\subseteq S_j$ for some $j$. Since $1\in S_1$, this means $S_i=S_i\cdot 1\subseteq S_iS_1\subseteq S_j$, so $S_i=S_j$ and we conclude $S_iS_1\subseteq S_i$. Since $a\in S_i$, this implies $aS_1\subseteq S_i$. From here $S_1\subseteq a^{-1}S_i$ as well.
Now, $a^{-1}\in S_k$ for some $k$, so $S_1\subseteq a^{-1}S_i\subseteq S_kS_i\subseteq S_l$ for some $l$, and again $S_1=S_l$. Therefore, $S_1\subseteq a^{-1}S_i\subseteq S_1$, so $aS_1\subseteq S_i\subseteq aS_1$, so $S_i=aS_1$. Similarly, $S_i=S_1a$. Thus $aS_1=S_1a$, so $S_1\lhd G$, and moreover every $S_i$ is a coset of $S_1$.

A question about normal subgroups.


Como formatar strings e armazena-las em um vetor dinâmico

Question: Em diversas partes do meu código acabo precisando usar comandos do bash para executar programas no Ubuntu. Para isso, formato o comando usando sprintf e depois executo com a função system.
Ex:
sprintf(sprintfoutput, "makeblastdb -in %s -dbtype prot -out SASBT_BLASTDB > /dev/null", one_rawreference);
system((char *)sprintfoutput);

Porém, notem que o tamanho de sprintfoutput varia de acordo com a "one_rawreference", cujo valor é definido pelo usuário. Como posso fazer para que o tamanho do sprintfoutput seja igual ao tamanho da minha string formatada?
Observação: Faço esse tipo de coisa mais de 40 vezes no meu código.
Answer: Tente a função asprintf(), que aloca e retorna o buffer necessário para acomodar o resultado. Além de retornar o tamanho certo, é muito mais seguro.
Por ser uma extensão da GNU libc, você precisa definir a macro
#define _GNU_SOURCE

antes de
#include <stdio.h>

Comment: Lembrando que `asprintf()` se trata de uma *extensão GNU* e não faz parte do padrão `C` (e nem do `POSIX`).
Answer: A função snprintf() da biblioteca padrão stdio.h é capaz de calcular o tamanho necessário para se acomodar a string formatada. O segredo é passar um buffer NULL, com tamanho 0, fazendo com que snprintf() retorne a quantidade de bytes necessários para acomodar a string formatada, veja só:
size_t tam = snprintf( NULL, 0, "makeblastdb -in %s -dbtype prot -out SASBT_BLASTDB > /dev/null", one_rawreference );

Segue um exemplo (testado) baseado na sua necessidade:
#include <stdio.h>
#include <stdlib.h>

char * formatar_comando( char const * one_rawreference )
{
    /* String de formatacao */
    const char * fmt = "makeblastdb -in %s -dbtype prot -out SASBT_BLASTDB > /dev/null";

    /* Calcula tamanho necessario para acomodar a string formatada */
    size_t tam = snprintf( NULL, 0, fmt, one_rawreference );

    /* Aloca a memoria necessaria para acomodar a string formatada */
    char * output = malloc( tam + 1 );

    /* Formata string efetivamente */
    sprintf( output, fmt, one_rawreference );

    /* Retorna */
    return output;
}

int main( void )
{
    /* Formatacao do comando em vetor dinamico */
    char * cmd = formatar_comando( "foobar" );

    /* Exibe o comando que sera executado */
    printf("Comando: %s\n", cmd );

    /* Execucao do comando */
    system(cmd);

    /* Libera memoria do vetor dinamico usada para formatacao */
    free(cmd);

    /* Sucesso */
    return 0;
}

A execução do seu comando pode ser encapsulada completamente dentro de uma unica função, que seria capaz de alocar somente a memoria necessária para a formatação da string, veja só:
#include <stdio.h>
#include <stdlib.h>

int executar_makeblastdb( char const * one_rawreference )
{
    /* String de formatacao */
    const char * fmt = "makeblastdb -in %s -dbtype prot -out SASBT_BLASTDB > /dev/null";

    /* Calcula tamanho necessario para acomodar a string formatada */
    size_t tam = snprintf( NULL, 0, fmt, one_rawreference );

    /* Aloca a memoria necessaria para acomodar a string formatada */
    char * cmd = malloc( tam + 1 );

    /* Formata string */
    sprintf( cmd, fmt, one_rawreference );

    /* Executa comando */
    int ret = system(cmd);

    /* Libera a memoria ocupada */
    free(cmd);

    /* Retorna status da execucao do comando */
    return ret;
}

int main( void )
{
    int ret = executar_makeblastdb( "foobar" );

    if( ret < 0 )
    {
        printf("Erro executando comando.\n");
        return 1;
    }

    printf("Comando executado com sucesso.\n");
    return 0;
}


How can use Github for my developer to work on my backend without having to share to much credentials and code?

Question: I have a Node.js backend running on an EC2 Instance with a Mongo DB.
I need to make some changes to my iOS App along with the Backend. I have already shared the Frontend Source Code with the developer, but I don't want to share the backend (if I don't have to directly..)
I have come across Github but I am totally new to it - also I am not a developer myself.
How can I use it for my purpose? Also, can 2 developers - say iOS developer and android developer then work on the code at the same time, without causing any mess?
What would you suggest me to do?
Appreciate any help! Thank you
Answer: Android and iOS developer can work together it will not cause any issue.
Now coming to your question first of all why a frontend developer needs to look at the backend code?..
If it's necessary ask them particularly what they wants to know may be backend code documentation can help or if the guy just need a look at some specific thing you can use some remote softwares like TeamViewer or else you don't have any options he have to look at code you can use last option to ask him sign the NDA (Non Disclosure Agreement)
Comment: Thanks for the response! He is a full stack developer, thats why.
Yes, he has signed an NDA but I just want to avoid my code being all over the place - in my scenario, is it useful for me to use Github?

Also, I would like to change my Mongo DB password - whats the easiest way to do so?

And one more general question, on my EC2 instance I have sent all incoming connection to my IP address - would it still be possible for an intruder to connect to my database, if he has my instance IP and my DB Username and Password?


K nearest neighbours model complexity

Question: My question is about the 1-nearest neighbor classifier and is about a statement made in the excellent book The Elements of Statistical Learning, by Hastie, Tibshirani and Friedman. The statement is
"For k nearest neighbours the model complexity is controlled by k."
"Also as model complexity is increased low bias and high variance"
Now in KNN , if we have a smaller k, we have low bias and high variance.So does that mean a smaller k is a more complex model ?
This seems kind of counter-intuitive as I just chose on basis of 1 point. How is this model more complex?
Comment: I think it is right, 1NN is the most complex model as it will have the most number of effective parameters = N/k = N and the most convoluted boundaries
Comment: Do those two statements appear near each other? They're both generally accurate, but sometimes they clash with each other.  Also, why does it matter?
Answer: I think it is right, 1NN is the most complex model as it will have the most number of effective parameters = N/k = N and the most convoluted boundaries

K nearest neighbours model complexity


Can't print or preview Crystal reports when an old server gets turned off

Question: We have a piece of ERP software installed on a server 2012 machine, we'll call this Server 1. It hosts the ERP software and a number of other things.
We have an old, semi-retired server that I will called Server 2. This machine runs server 2008, and used to host the company's old ERP software.
If we turn off Server 2, no one can print or preview the crystal reports in the ERP software on Server 1. Every other aspect of the program works. Every other program in the building works and prints correctly. But this one does not. If you click 'Print' or 'Preview' anywhere in the program, nothing will happen. If you try it again, the program will crash. This behavior is repeatable every time. If we turn Server 2 back on, all printing works as normal again.
-Server 2 has Crystal, SQL server, and the old ERP software on it. It also has the 'Application Server", "File Services" and "Web Server (IIS)" roles.
The Application Server only has .NET framwork 3.5.1 installed.
The File Services just has the File Server service installed.
The Web Server has the Web Server and Common HTTP services installed.
-Server 1 has Crystal, SQL Server, and the new ERP software. It has all of the mentioned services and roles from above, and then some.
We installed this new server and new ERP software nearly a year ago, and Server 2 has sat around as an archive of sorts. Now we want to actually turn it off and get rid of it, but can't because of this issue. We tried to get the tech team of the ERP software involved, but they are baffled. They are convinced it has something to do with the old SQL server, but can't figure out what is going on. It's almost like the new server is looking at the old SQL server or something, but I have looked everywhere, and there are no references that I can see.
The reports don't have any defined printers in them, either. The ERP company also scoured the software itself to make sure there were no defined printers in it. As a test, I made custom reports that had both defined and undefined printers and they were still affected by the problem.
Also of note: Our network does not have any defined print servers.
Answer: I don't have any specific advice, but I'd start by trying to narrow down the possible causes.
Stop one service at a time on server2 and see when the problem appears.
If SQL Server turns out to be the culprit, use its own monitoring tools to see what exactly is connecting to it, which database is using and the queries it's running.
If the problem is caused by IIS, look at its logs.
If the problem is in file or print sharing, examine the active connections to network shares.
And so on...


Como fazer cadastro de um CPT irem para uma página específica?

Question: Procurar mas não descobri como fazer com que os dados de um CPT de cadastro de jogador (que incluem nome, foto e telefone), vão para a página jogadores.
Ou seja quero que os dados do cadastro no (back-end, painel administrativo do WordPress) seja exibir na página jogadores (no front-end). Como fazer essa ponte?
Answer: Confira Tipos de Posts Personalizados « WordPress Codex (o original em inglês é mais completo) onde verá por exemplo:
$args = array( 'post_type' => 'product', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
  the_title();
  echo '
';
  the_content();
  echo '
';
endwhile;

Vai usar esse código dentro de páginas específicas do seu Theme trocando aquele product por jogador.
Recursos para entender a hierarquia de um Theme:

Template Hierarchy | Theme Developer Handbook | WordPress Developer Resources

The WordPress Template Hierarchy - a visualization resource

Boa parte do Codex tem tradução ao português.
A nova seção Official WordPress Developer Resources ainda não.
Comment: ps: o primeiro lugar para procurar é a documentação, seja trabalhando com WordPress, PHP, jQuery, Stack Overflow... se não encontrar aí, pode começar a pesquisar no resto e a escrever um pergunta para postar aqui. Ao final da pesquisa/testes, ou já resolveu ou tem uma excelente pergunta para postar ;)
Comment: Muito Obrigado amigo. Seguirei seus conselhos !


Testing if year-to-year change is significant?

Question: I have
Two related questions:
1) I have raw counts for voting vs. non-voting for the years 2018 and 2020.
2018 -> 11,000 voters and 3,000 non-voters
2020 -> 10,000 voters and 3,500 non-voters
How can I calculate that the decrease in voters from 2018 to 2020 is significant or not? What test would I use?

2) I also have the voter turnout rate which is 67% in 2018 and 66% in 2020. How can I check whether this 1% drop in voter turnout rate is significant?
what tests could I use in each case?
Thank you in advance!
Comment: I should add that--I have the total voting population number as well (if that is helpful)
Comment: [Significantly *what* kind of change](https://stats.stackexchange.com/a/125538/44269)?
Comment: If that is what actually happened in the election, then any change is significant in the sense that you can be sure that there was a change.  If this is based on random sampling of individuals from a much larger population and asking them whether they were voters or non-voters or something else (e.g. children or non-citizens) then you can apply usual techniques
Comment: It sounds like the total population for 2018 is 14,000 people.  Is this true?  If so, there's probably no need to conduct a hypothesis test (like a chi-squared test), since you have data on the whole population.  If this is not true, wouldn't you be able to get the data for the total potential voters in the election and the total number of actual voters?
Comment: @SalMangiafico Thanks for the question. No, the total population is a bit bigger because it includes those who are not allowed to vote (I do have the total population size as well). But my problem is that I wanted to know whether the year-to-year change is significant. The total population size and sample sizes across both years are slightly different in size.
Comment: My point is that if you are looking at the whole voting population, there's no point in conducting a hypothesis test.  You know how many people voted.  There's nothing to estimate.  It's like if I have 10 dollars in my wallet yesterday and 12 dollars in my wallet today, there's no place for a statistical test.  There's some discussion on the topic here: [stats.stackexchange.com/questions/70296/how-to-report-data-for-an-entire-population/](https://stats.stackexchange.com/questions/70296/how-to-report-data-for-an-entire-population/).
Answer: (1) In 2018, you have 11,000 voters out of 14,000 potentially available,
and in 2020, you have 10,000 voters out of 13,500.
In R, assuming randomness in willingness and ability to vote, you could compare the two proportions of voters
using prop.test as follows (declining continuity correction with parameter cor=F on account of large sample sizes):
prop.test(c(11000,10000), c(14000,13500), cor=F)

        2-sample test for equality
        of proportions without
        continuity correction

data:  c(11000, 10000) out of c(14000, 13500)
X-squared = 77.015, df = 1, p-value < 2.2e-16
alternative hypothesis: two.sided
 95 percent confidence interval:
  0.03493139 0.05501570
 sample estimates:
    prop 1    prop 2
 0.7857143 0.7407407

The proportions $.786$ and $.741$ are significantly
different on account of the P-value near $0.$
Alternatively, you could do a chi-squared test on
a $2\times 2$ table:
TBL = rbind(c(11000, 10000), c(3000, 3500)); TBL
      [,1]  [,2]
[1,] 11000 10000
[2,]  3000  3500

chisq.test(TBL, cor=F)

        Pearson's Chi-squared test

data:  TBL
X-squared = 77.015, df = 1, p-value < 2.2e-16

Except for the input syntax, the two tests are
essentially equivalent.
(2) You need to use counts (as above) instead of
percentages.
Comment: Thank you so much! I will use the chi-squared test approach


Preprocessor in C language

Question: I would like to define a variable (Mode) to choose between two functions, but the compiler doesn't seem to do what I want, here is the code:
<code>#include <stdio.h>
#define Mode dif

#if Mode == sum
    int function(int a, int b)
    {
        return a+b;
    }
#elif Mode == dif
    int function(int a, int b)
    {
        return a-b;
    }
#else
ERROR
#endif
int main()
{
    printf("%d",function(5,3));

    return 0;
}
</code>
The compiler chooses the function "sum" (or the first one I wrote) for any string value (or an integer 0) I put in "Mode", and it chooses the "ERROR" state for any integer I put besides 0, that's what I observed so far.
I can make it work by changing "sum" and "dif" with numbers but I'm working on another electronic project in which I have to use words instead of numbers otherwise it will be difficult to implement and diagnose, for examlpe:
<code>#define Falling_Edge 0x00
#define Rising_Edge  0x01
#define Both         0x02
#define IT_Mode X // X could be Falling_Edge, Rising_Edge or Both

#if IT_Mode == Falling_Edge
// do something
#elif IT_Mode == Rising_Edge
// do something
#elif IT_Mode == Both
// do something
#elif
ERROR
#endif
</code>
Is there a way to achieve something like this in C please?
Thank you.
Comment: The preprocessor does not do this, and that is not what it is designed for. In spite of your comment about "another electronic project in which I have to use words instead of numbers", you do not show any reason that using numbers would be a problem.
Comment: In C you cannot directly compare strings. With the code you have characters or integers will work just fine. Possible duplicate of [this](https://stackoverflow.com/q/2335888/4549234).
Comment: `Is there a way to achieve something like this in C please?` Yes you `can make it work by changing "sum" and "dif" with numbers`. (?)
Comment: What is an electronic project and how does it affect this task?
Comment: Thank you for your comments, so imagine you have to make a project that works with multiple microcontrollers, or the same project can be used to do different things, for example if you change the trigger mode of a simple counter then the numbers could increment or decrement with the same code.
Answer: You cannot use sum and dif like symbols in this way, you need to define them as numbers:
<code>#include <stdio.h>

#define sum 0
#define dif 1
#define Mode dif

#if Mode == sum
    int function(int a, int b)
    {
        return a+b;
    }
#elif Mode == dif
    int function(int a, int b)
    {
        return a-b;
    }
#else
    ERROR
#endif

int main(void)
{
    printf("%d\n",function(5,3));

    return 0;
}
</code>
Comment: The question asks for a way to do it without using numbers. So supplying a solution with numbers is not a correct answer.
Comment: That's just an example, imagine you have multiple functions, and every function could have many possible cases, so can you imagine how difficult it will be using numbers?
Comment: @Vertinhol normally that is not difficult at all. At some place you must decide what values are allowed to compare with. Then just add a `#define` for each of those values. To avoid duplicate numbers, you may put all this defined into one place. The way it is done at the top of this snippet and also at the top of your second snippet in your question is clean and I have no idea how this would become "difficult". That also provides a list of all allowed values you can chose from when defining your `mode` macro.

Preprocessor in C language


Can haproxy be used to balance unix sockets?

Question: In nginx it is fairly simple to configure it to proxy unix .sock files
Eg:
upstream bla {
      server unix:///home/sam/Source/bla/tmp/sockets/thin1.sock;
      server unix:///home/sam/Source/bla/tmp/sockets/thin2.sock;
 }

Is there a similar syntax in haProxy to enable balancing local .sock filew
Answer: Short answer: Yes, since version 1.5.
Let's have a look at server keyword arguments documentation:
<address> is the IPv4 or IPv6 address of the server. Alternatively, a
          resolvable hostname is supported, but this name will be resolved
          during start-up. Address "0.0.0.0" or "*" has a special meaning.
          It indicates that the connection will be forwarded to the same IP
          address as the one from the client connection. This is useful in
          transparent proxy architectures where the client's connection is
          intercepted and haproxy must forward to the original destination
          address. This is more or less what the "transparent" keyword does
          except that with a server it's possible to limit concurrency and
          to report statistics. Optionally, an address family prefix may be
          used before the address to force the family regardless of the
          address format, which can be useful to specify a path to a unix
          socket with no slash ('/'). Currently supported prefixes are :
                - 'ipv4@'  -> address is always IPv4
                - 'ipv6@'  -> address is always IPv6
                - 'unix@'  -> address is a path to a local unix socket
                - 'abns@'  -> address is in abstract namespace (Linux only)
          Any part of the address string may reference any number of
          environment variables by preceding their name with a dollar
          sign ('$') and optionally enclosing them with braces ('{}'),
          similarly to what is done in Bourne shell.

So you may specify path to unix socket with leading slash, or explicitly prepend address family prefix:
server nginx1 /run/nginx/default.sock
server nginx2 email@example.com

Answer: As quanta said it need IPv4 address, but with using socat to relay unix scoket to TCP maybe you can use HAProxy to that.
socat TCP-LISTEN:1234,reuseaddr,fork UNIX-CLIENT:/tmp/foo

Comment: I would change the backend (`thin` server?) to listen on a TCP socket (localhost:port) instead of Unix socket.
Comment: Yes I agree that it would be the best, but if it can't listen to TCP then you have to trick it to do so.
Comment: haproxy is high-performance server, socat isn't.
Answer: AFAIK, HAProxy doesn't support it. According to the document, you must specify an IPv4 or IPv6 (or hostname) of the server.
Comment: This is wrong. It does.
Comment: I couldn't get haproxy 1.9 to work with "server www-backend "unix@/var/run/docker.sock" (also tried with unix@ prefix) despite docs saying it should (http://cbonte.github.io/haproxy-dconv/1.9/configuration.html#4.2-server). I tried this. Using socat and that port as the backend worked but seems flaky.