Best practice for storing and accessing common string literals

Question: What is the best approach for storing some string literals to be used throughout a large project? I don't want devs writing the literals in more than one place for obvious reasons. I also, don't want a bunch of redundant/useless code. I'm looking for the cleanest/simplest way to have a small list of string literals that are easily accessible (meaning they have a declarative name like status.passed = "passed" not status[0] = "passed") and are stored in a sensible way. An enum would be ideal but they can't take strings, and the dictionary + enum solutions I've seen here don't appeal to me.
Would a static class be the best choice?
Comment: If they need to be localized (or ever *will* need to be), use a `resx` file.  Otherwise, use const strings in a static class or struct.
Comment: @evanmcdonnal I will post an answer.
Comment: Please give an example of how an enum does not take a string.
Comment: @Blam: how do you provide an example of something that can't be done? :-) anyway: `Every enumeration type has an underlying type, which can be any integral type except char` http://msdn.microsoft.com/en-us/library/sbbt4032(v=vs.110).aspx
Comment: @Blam `enum status { Passed = "passed" }` will not compile. Neither will `enum status : string { Passed = "passed" }`. Maybe there's something I'm missing?
Comment: @JuliánUrbano Pretty easy you post the desired syntax that fails.
Comment: @Blam Alright, ty. Although resx is probably better practice I'm kind of apposed to it. I only have 4 strings, they're not going to change, I don't care if a change requires a rebuild (internal utils so rebuild is nbd).
Answer: You should use a resource (.resx) file.
Answer: Sure enum will not do what you need?
namespace EnumTest
{
    public enum enumRole : byte { projMgr = 2, docAdmin = 3, dataAdmin = 4, sysAdmin = 9, userAdmin = 5 };
    class Program
    {
        static void Main(string[] args)
        {
            enumRole myrole = enumRole.docAdmin;
            if (myrole == enumRole.docAdmin) Console.WriteLine("I am docAdmin");
            // i use the key to save to SQL and restore
            // in SQL have a fk table to match the enum
            Console.WriteLine((byte)myrole);
            myrole = (enumRole)9;
            Console.WriteLine(myrole.ToString() + " " + ((byte)myrole).ToString());
            Console.ReadLine();
        }
    }
}

Comment: If they are arbitrary strings then I agree.  But "I only have 4 strings, they're not going to change, I don't care if a change requires a rebuild (internal utils so rebuild is nbd)" is not what I would call arbitrary strings.
Comment: `enum.ToString` does not work for arbitrary strings, it just gives you the name of the enum variable. For example, it can't be `Project Admin`.
Comment: Yeah +1, this is actually a fine solution for what I'm doing.
Answer: Use Constants in this case
or
a resource file (*.resx).


prove relative error of X+Y<= max( relative error of X , relative error of Y) known X,Y have the same sign

Question: Let X,Y such that X * Y > 0 (which means that X,Y are both positive or negetive)
Let A be the relative error of X ,and B the relative error of Y
prove that the relative error of (X+Y) <= max (A,B)
I have tried to solve this question however I only get that relative error of (X+Y)<= A+B using that |X+Y| <= |X| and |X+Y|<=|Y| since X,Y have the same sign
any help would be appreciated
Answer: Assume $X^*$ is the true value, and $X$ is the approximation, so that $A=(X-X^*)/X^*$, and similarly for $Y^*$, $Y$ and $B$.
Then
$$\frac{X}{1+A}=X^*,\quad\frac{Y}{1+B}=Y^*$$
and so
$$X+Y=X^*(1+A)+Y^*(1+B)$$
and the relative error is
$$e_{rel}=\frac{(X+Y)-(X^*+Y^*)}{X^*+Y^*}=\frac{X^*(1+A)+Y^*(1+B)-X^*-Y^*}{X^*+Y^*}=\frac{AX^*+BY^*}{X^*+Y^*}$$
I'll leave the rest to you. (Note, I have been a bit careless by not using absolute value signs, but the method is the important bit.)


Bash script ctrl+c error

Question: I have log file system that renames the latest log file with current time and i must set a less command to check log file easily. I can quit less sommand with q but i must follow the latest incoming lines so after pressing shift+f q doesnt work and i need to quit with ctrl+c.
When i press ctrl+c main screen and process is being killed but terminal screen has the error that you can see below
terminal error
find /data/tomcat/logs/out.* -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" " |xargs less

i can clear the error with reset but its ridiculous to use it like this.
As i search on internet most of people explained it as ctrl+c kills the main command but the script doesnt respond the SIGINT. Tried a lot of them but cannot succeded on killing this simple script.
And also unable to make aliases because some of the arguments gave error but it works perfectly fine when i run this command on terminal.
I know it would be easier to use logger rotate to rename the old file and keep the latest file with the same name but its not gonna happen.
Answer: When you press shift-F while running less, it puts you into follow mode.  Press Ctrl-C to exit this mode, then you can press Q to exit.
It sounds like the terminal echo is disabled when you break out of your command.  It's the same thing that happens if you run stty -echo.  To reset your terminal you can type stty sane.  You'll have to type it blindly since you won't be able to see what you're typing, but it should work.
If you're not able to make an alias from the command line you provided, try putting it in a file and make it executable, then either make sure that script file is in your path, or make an alias to run it.  You might also want to add a second line to your script that runs stty sane to ensure the terminal echo is enabled when the less command exits.  Something like this should work:
#!/bin/bash
find /data/tomcat/logs/out.* -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" " |xargs less
stty sane

Comment: Hi virtex, thank you stty sane just do the job. As you said crtl+c doesn't behave like it should on follow mode but its just fine.

Bash script ctrl+c error


Imprimir valor de um dicionário

Question: Tenho essa questão pra resolver, preciso exibir a nota do primeiro nome na ordem de chama, mas só consigo imprimir a Key, a questão é essa:
Faça um programa em python que solicita que o usuário digite nomes e notas de 10 estudantes. A seguir, o programa deverá mostrar a nota do(a) estudante que aparece primeiro no caderno de chamada.
meu código até agora:
dicionario = {}
for x in range(0, 3):
    nome = input("\nInsira o nome do aluno: ")
    nota = float(input("Insira a nota do aluno: "))
    dicionario[nome] = nota

newdict = sorted(dicionario)

print(newdict[0])

como faço pra imprimir apenas o valor da primeira key do dicionario?
Answer: Na linha 7, onde você cria a variável newdict que recebe o dicionário ordenado, você está alocando ele como uma lista, por exemplo:
dicionario = {'Felipe': 4.0, 'Joao': 5.0, 'Ana': 7.8}
newdict = sorted(dicionario)
print(newdict)

Resultado:
['Ana', 'Felipe', 'Joao']

O correto seria você adicionar o método .items() na frente do dicionário, veja:
dicionario = {'Felipe': 4.0, 'Joao': 5.0, 'Ana': 7.8}
newdict = sorted(dicionario.items())
print(newdict)

Resultado:
[('Ana', 7.8), ('Felipe', 4.0), ('Joao', 5.0)]

Então mostrando o primeiro item do seu dicionário com newdict[0] ele retornará a nota do(a) estudante que aparece primeiro no caderno de chamada.
Por fim, o seu código fica assim:
dicionario = {}
for x in range(0, 3):
    nome = input("\nInsira o nome do aluno: ")
    nota = float(input("Insira a nota do aluno: "))
    dicionario[nome] = nota

newdict = sorted(dicionario.items())

print(newdict[0][1])

Veja mais sobre dicinários em python aqui!
Comment: Muito obrigado, porem na saída ele imprime chave e valor, eu queria só o valor
Comment: Basta referenciar o valor com `[1]`: `print(newdict[0][1])`

Imprimir valor de um dicionário


64bit C# .Net Wrapper for 32bit C# .Net DLL

Question: I have a 32bit Software written in C# who Communicates with many different devices.
Because of memory problems i upgraded to a 64bit System, no big Deal for the C# Software itself.
But for some of the implemented devices i had to change the way of implementation, it worked for all expect for one!
There i have a DLL which is written in C# 32bit, who is responsible for the communication to the device. Made by the supplier. I asked the supplier for a 64bit version but unfortunately its not possible for them to give me one.
My Idea was to create an Wrapper to make the DLL available to my 64bit Software.
I have seen that there are where many other people with a similar problem, but they always hat to Wrap an unmanaged DLL.
So my tried to write an wrapper who use COM to get the work done. But failed while implementing the C# COM Server into my C# Client. Here is the Idea what is tried:
https://blog.mattmags.com/2007/06/30/accessing-32-bit-dlls-from-64-bit-code/
Another Idea was to use a open source Project who can this topic with DLLImports:
https://github.com/CodefoundryDE/LegacyWrapper
There i could load it with DLLImport but i could not find the EntryPoint to my needed functions.
The question here is, if i'm completly on the wrong way and i can not load a managed DLL into C# with DLLImport or if i missed something and i just need to adjust the parameters.
Here is the Code i used so far (i changed the Names of the DLL)
    [LegacyDllImport(@"C:\Program Files (x86)\Company\Device\API.dll")]
    public interface IClassA : IDisposable
    {
        [LegacyDllMethod(CallingConvention = CallingConvention.Winapi)]
        bool MethodA();
    }

Comment: The idea about out-of-process 32-bit COM server is correct. But you don't need to work with C#-dll as with unmanaged dll. See this https://stackoverflow.com/questions/446417/create-out-of-process-com-in-c-net about how to create COM server with C#
Comment: Thank you a lot for the link! it finally worked, i will post my solution below
Answer: I used the example: https://learn.microsoft.com/de-de/samples/dotnet/samples/out-of-process-com-server/
Here is the Git Link: https://github.com/dotnet/samples/tree/main/core/extensions/OutOfProcCOM
to create an out of process com server to handle the bitness difference.
i "only" had to get familiar with the concept and had to change the the call of the Server a bit. I changed the value of "CLSCTX_LOCAL_SERVER" from 0x4 to x40004 to force the call of a x86 Server!
private class Ole32
{
    // https://docs.microsoft.com/windows/win32/api/wtypesbase/ne-wtypesbase-clsctx
    public const int CLSCTX_LOCAL_SERVER = 0x40004;//0x4;

    // https://docs.microsoft.com/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance
    [DllImport(nameof(Ole32))]
    public static extern int CoCreateInstance(
        [In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid,
        IntPtr pUnkOuter,
        uint dwClsContext,
        [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
        [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
}

Comment: `0x40040` is just a combination of `CLSCTX_LOCAL_SERVER | CLSCTX_ACTIVATE_X86_SERVER` (`0x4 | 0x40000`)
Answer: As addition to the @CyberMochi answer.
In particular case of x86-server and x64-client we don't need to call CoCreateInstance explicitly, as in case of bitness missmatch the standard .net COM interop mechanisms can do all the things automatically for us.
So, with the same sample (https://github.com/dotnet/samples/tree/main/core/extensions/OutOfProcCOM) I done the following:

(optional) Migrated to net6

Explicitly set bitnes for client (<PlatformTarget>x64</PlatformTarget>) and server (ExeServer.csproj: <PlatformTarget>x86</PlatformTarget>)

Built and registered server with "<path-to-samples>\ExeServer\bin\Debug\net6.0\ExeServer" /regserver (this need to be executed from elevated/admin command line)

Removed IServer declaration from the client project as the all information needed will be extracted from a tlb.

Reference the Server.Contract.tlb (from \ExeServer\bin\Debug\net6.0 folder) in the client project - "Add COM reference" into solution explorer. This added the following into csproj
   <ItemGroup>
     <COMReference Include="ServerLib">
       <VersionMinor>0</VersionMinor>
       <VersionMajor>0</VersionMajor>
       <Guid>46f3feb2-121d-4830-aa22-0cda9ea90dc3</Guid>
       <Lcid>0</Lcid>
       <WrapperTool>tlbimp</WrapperTool>
       <Isolated>false</Isolated>
       <EmbedInteropTypes>true</EmbedInteropTypes>
     </COMReference>
   </ItemGroup>

Use the server from the client with the code
     var server = new ServerLib.Server();
     var pi = server.ComputePi();
     Console.WriteLine(pi);

Some additional notes:

You can use per-user registration of the COM server. This will not require admin priveleges. But you will need to rewrite registration code - see here for details: Registering a COM without Admin rights
Instead of COM reference you can manually create COM interop DLL from the tlb with a tlbimp tool and reference this interop dll. This will speedup a build process.


Popular type["text"] pela select

Question: Estou tentando popular um type["text"] através de jquery e não esta dando certo!
Formulário:

        Plano:
        <select name="plano" id="plano" required>
             <?php echo $stringPlanos; ?>
        </select>

   Valor<input type="text" class="real" style="width:100px; height:40px" required maxlength="23" id="valorCombinado"  name="valorCombinado" />

Código jquery

planos.ajax.php
<?php
 $cod_plano = mysql_real_escape_string( $_REQUEST['cod_plano'] );
 $planosBase = $PlanosDao->pesquisaPlanoEdicao($cod_plano);
 $planosRetorno = $planosBase->getValor();
 echo( json_encode($planosRetorno) );
?>

Mas, o console do navegador não mostra$ erros e o campo não é populado!
Onde estou errando?
Comment: Se o que queres popular é um `input` tens de usal `.val(resultado)` e não `.html(resultado)`. Será esse o problema?
Comment: $('#valorCombinado').val(resultado).show();??? Não funcionou. Mas acho que não. Pois nem o alert funciona!
Comment: Testa este código: http://jsfiddle.net/e3jdemdb/
Comment: Não vás mudando a pergunta por favor... deixa estar como estáva, mesmo que estivesse errado. Pode ser útil para outros.
Comment: Sérgio.  Não funcionou. Nem o alert funcionou!
Mas vale lembrar que estou usando o plugin autocomplete do jquery.Quer que eu adicione a chamada dele na pergunta?
Comment: Usa `echo json_encode($planosRetorno);` sem parentesis aqui: `echo()`.
Comment: Quando usas esse código que coloquei no jsFiddle o que te dá nos headers do ajax?
Comment: nem assim Sérgio. headers do Ajax? Como faço para ver isso?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/29559/discussion-between-sergio-and-carlos-rocha).
Comment: O que ocorre é que esses valores da select são alterados não na select, mas em uma UL com lis criadas dinamicamente. Nesse caso, terei que descobrir como pegar o valor da li selecionado! Será que tem geito?
Answer: Opa amigo, você esta capturando a variável errado neste trecho de código:
          ...
          $.getJSON('planos.ajax.php?search=',{cod_plano: $(this).val(), ajax: 'true'}, function(resultado){
              var resultado = planosRetorno;
              alert(resultado);
              $('#valorCombinado').val(resultado).show();
          });
          ...

A variável resultado esta capturando um valor errado: planosRetorno não existe, o retorno na verdade já é resultado
Caso esteja com problemas para verificar o erro da sua requisição faça um teste utilizando o método ajax do jquery:
$.ajax( "example.php")
    .done(function() {
        alert( "success" );
    })
    .fail(function() {
        alert( "error" );
    })
    .always(function() {
        alert( "complete" );
    });

(http://api.jquery.com/jquery.ajax/)
Comment: Ok. Mas echo( json_encode($planosRetorno) ); não cria uma variável js de igual nome? Ou não é assim que interpreta?
Comment: na verdade a ideia é a seguinte:
`$.getJSON([url][parametro via get para a url][options], function([retorno da url]){ [função]});`

Popular type["text"] pela select


want to make a program that selects out prime numbers. don't get why my program doesn't work

Question: whenever I try to run this program, it first shows "The prime's upper bound?" After inserting an integer and pressing enter, I don't see anything then. I want it to display some "false" values, but I can't find where the problem is. And the Java doesn't show where the problem is.
import java.util.Scanner;

public class Lab11 {

    static int n;
    boolean [] primedetermine = new boolean [n];
    int [] list;

    public static void main (String[]args) {
        Scanner in = new Scanner (System.in);
        System.out.print ("The prime's upper bound? ");
        int max = in.nextInt();
        boolean prime [] = new boolean [max];
        computePrimes (prime);
    }

    public static void computePrimes(boolean[] primedetermine) {
        for (int x = 0; x<n; x++) {
            primedetermine [x] = false;
        }
        for (int prm = 2; prm <= n; prm++) {
            for (int prm2 = 2; prm * prm2 <= 21; prm++) {
                primedetermine [prm * prm2 -1] = true;
            }
        }
        for (int x = 1; x<=n; x++){
            if (primedetermine[x-1] == false);
                System.out.println(primedetermine[x-1]);
            }
        }
    }
}

Comment: Have you debugged your code? n will always be 0, so your loops won't iterate
Comment: Your n value is never initialized, such mistake is inappropriate for someone who calls himself geniushacker ))
Comment: Take a look [here](http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/)
Comment: This is not a code debugging service
Answer: You are using the variable n which is never initialized (so it's 0 by default, and your loops are never entered) :
for (int x = 0; x<n; x++)

instead of n use primedetermine.length.
That's just one problem. primedetermine [prm * prm2 -1] will throw an exception, since prm * prm2 -1 will exceed the range of the array.


Python pandas to extract only desired column and desired values from the columns

Question: I'm trying to use pandas to parse my CSV file, where my CSV file has multiple columns but I need to pick only certain ones. From my CSV file I'm looking to grab 'Platform ID' ,  that may startswith CS-Unix* next one is 'Target system address' where it contains Sever names which could be anything so I need whole value to be printed out another and the last column is 'Failure reason' which again a symptom and could be anything so need that printed.
I mentioned CS-Unix-* , because it could be anything after CS-Unix-
However, in another field, I opted * to print the value as Server name could again be different.
My Data Format will be ..
Platform ID               Target system address       Failure reason
CS-Unix-RootAccounts-SSH  Serer1                       xyz

Below what I'm trying but not working.
import csv
import pandas as pd

pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)

data = pd.read_csv('/home/karn/plura/Test/Python_Pnada/Cyber_July.csv', usecols=['Platform ID', 'Target system address', 'Failure reason'])
#data.drop(data.index[0], inplace=True)
hostnames = data[(data['Platform ID']=='CDS-Unix-*') | (data['Target system address'] == '*' )]['Failure reason']
print(hostnames)

Please guide to move forward.
Answer: This should provide failure reasons for all the rows with Platform IDs of the form CS-Unix-*.
hostnames = data[data['Platform ID'].str.startswith("CS-Unix-")][['Target system address','Failure reason']]
startswith() returns a boolean indicating whether the elements start with the string passes as a parameter to it.
Comment: gaganso, let me try this.
Comment: gaganso,  I need `Failure reason` and `Target system address` for all the rows with Platform IDs of the form CS-Unix-*, in that case what would be the `hostnames`.
Comment: @pygo, please see the updated answer. That is the syntax to select a subset of columns from the dataframe.


NullPointerException - Algoritmo Genético

Question: package chapter2;

public class AllOnesGA {

    public static void main(String[] args) {
        //Cria instância da classe "GeneticAlgorithm"
        GeneticAlgorithm ga = new GeneticAlgorithm(100, 0.01, 0.95, 0);

        //Inicializa a população
        Population population = new Population(50);

        ga.evalPopulation(population);
        int generation = 1;

        while (ga.isTerminationConditionMet(population) == false) {
            //Mostra o fittest indivíduo da população
            System.out.println("Best solution: " + population.getFittest(0).toString());

            //Aplicar crossover
            population = ga.crossoverPopulation(population);

            //Aplicar mutação
            population = ga.mutatePopualtion(population);

            //Avaliar a população
            ga.evalPopulation(population);

            //Incrementa mais uma geração
            generation++;
        }

        System.out.println("Found solution in " + generation + " generations");
        System.out.println("Best solution: " + population.getFittest(0).toString());
    }
}

//Nova Classe

public class GeneticAlgorithm {
    private int populationSize;
    private double crossoverRate;
    private double mutationRate;
    private int elitismCount;

    public GeneticAlgorithm (int populationSize, double crossoverRate,
    double mutationRate, int elitismCount) {
        this.populationSize = populationSize;
        this.crossoverRate = crossoverRate;
        this.mutationRate = mutationRate;
        this.elitismCount = elitismCount;
    }

    public Population initPopulation(int chromosomeLenght) {
        Population population = new Population(this.populationSize, chromosomeLenght);
        return population;
    }

    public double calcFitness (Individual individual) {
        //Rastreia o número de genes corretos
        int correctGenes = 0;

        //Loop sobre cada gene
        for (int geneIndex = 0; geneIndex < individual.getChromosomeLenght(); geneIndex++) {
            //Adiciona um ponto de fitness para cada "1" encontrado
            if (individual.getGene(geneIndex) == 1) {
                correctGenes += 1;
            }
        }
        //Calculo de fitness
        double fitness = (double) correctGenes / individual.getChromosomeLenght();

        //Armazena fitness
        individual.setFitness(fitness);

        return fitness;
    }

    public void evalPopulation(Population population) {
        double populationFitness = 0;

        for (Individual individual : population.getIndividuals()) {
            populationFitness += calcFitness(individual);
        }

        population.setPopulationFitness(populationFitness);
    }

    public boolean isTerminationConditionMet(Population population) {
        for (Individual individual : population.getIndividuals()) {
            if (individual.getFitness() == 1) {
                return true;
            }
        }
        return false;
    }

    public Individual selectParent(Population population) {
        //Crossover aplicado com o método "Roleta de Cassino"
        //Seleciona os indivíduos
        Individual individuals[] = population.getIndividuals();

        //Gira a roleta
        double populationFitness = population.getPopulationFitness();
        double rouletteWheelPosition = Math.random() * populationFitness;

        //Encontra o indivíduo para o crossover
        double spinWheel = 0;
        for (Individual individual : individuals) {
            spinWheel += individual.getFitness();
            if (spinWheel >= rouletteWheelPosition) {
                return individual;
            }
        }

        return individuals[population.size() - 1];
    }

    public Population crossoverPopulation(Population population) {
        //Cria nova população
        Population newPopulation = new Population(population.size());

        //Loop sobre população atual por fitness
        for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) {
            Individual parent1 = population.getFittest(populationIndex);

            //Aplicar crossover a este indivíduo??
            if (this.crossoverRate > Math.random() && populationIndex > this.elitismCount) {
                //Inicializa offspring
                Individual offspring = new Individual(parent1.getChromosomeLenght());

                //Encontra o 2 segundo par
                Individual parent2 = selectParent(population);

                //Loop sobre o genoma
                for (int geneIndex = 0; geneIndex < parent1.getChromosomeLenght(); geneIndex ++) {
                    //Usa metade dos genes do par 1 e metade dos genes do par 2
                    if (0.5 > Math.random()) {
                        offspring.setGene(geneIndex, parent1.getGene(geneIndex));
                    } else {
                        offspring.setGene(geneIndex, parent2.getGene(geneIndex));
                    }
                }
                //Adiciona offspring a nova população
                newPopulation.setIndividual(populationIndex, offspring);
            } else {
                //Adiciona individuo a nova opulação sem aplicar crossover
                newPopulation.setIndividual(populationIndex, parent1);
            }
        }
        return newPopulation;
    }

    public Population mutatePopualtion(Population population) {
        //Inicializa nova População
        Population newPopulation = new Population(this.populationSize);

        //Loop sobre população atual por fitness
        for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) {
            Individual individual = population.getFittest(populationIndex);

            //Loop sobre cada gene
            for (int geneIndex = 0; geneIndex < individual.getChromosomeLenght(); geneIndex++) {
                //Pula mutação se o indivíduo for elite
                if (populationIndex >= this.elitismCount) {
                    //Esse gene precisa de mutação??
                    if (this.mutationRate > Math.random()) {
                        //Pega novo gene
                        int newGene = 1;
                        if (individual.getGene(geneIndex) == 1) {
                            newGene = 0;
                        }
                        //Mutar o gene
                        individual.setGene(geneIndex, newGene);
                    }
                }
            }
            //Adiciona individuo a nova população
            newPopulation.setIndividual(populationIndex, individual);
        }
        return newPopulation;
    }

//Nova Classe

public class Individual {
    private int[] chromosome;
    private double fitness = -1;

    public Individual(int[] chromosome) {
        this.chromosome = chromosome;
    }

    public Individual (int chromosomeLenght) {
        this.chromosome = new int [chromosomeLenght];
        for (int gene = 0; gene < chromosomeLenght; gene ++) {
            if (0.5 < Math.random()) {
                this.setGene(gene, 1);
            } else {
                this.setGene(gene, 0);
            }
        }
    }

    public int[] getChromosome() {
        return this.chromosome;
    }

    public int getChromosomeLenght() {
        return this.chromosome.length;
    }

    public void setGene(int offset, int gene) {
        this.chromosome[offset] = gene;
    }

    public int getGene(int offset) {
        return this.chromosome[offset];
    }

    public void setFitness(double fitness) {
        this.fitness = fitness;
    }

    public double getFitness() {
        return this.fitness;
    }

    public String toString() {
        String output = "";
        for (int gene = 0; gene < this.chromosome.length; gene++) {
            output += this.chromosome[gene];
        }
        return output;
    }

//Nova Classe

public class Population {
    private Individual population[];
    private double populationFitness = -1;

    public Population(int populationSize) {
        this.population = new Individual[populationSize];
    }

    public Population (int populationSize, int chromosomeLenght) {
        this.population = new Individual[populationSize];

        for (int individualCount = 0; individualCount < populationSize; individualCount++) {
            Individual individual = new Individual(chromosomeLenght);
            this.population[individualCount] = individual;
        }
    }

    public Individual[] getIndividuals() {
        return this.population;
    }

    public Individual getFittest(int offset) {
        Arrays.sort(this.population, new Comparator<Individual>(){
            @Override
            public int compare(Individual o1, Individual o2) {
                if (o1.getFitness() > o2.getFitness()) {
                    return -1;
                } else if (o1.getFitness() < o2.getFitness()) {
                    return 1;
                }
                return 0;
            }
        });
        return this.population[offset];
    }

    public void setPopulationFitness(double fitness) {
        this.populationFitness = fitness;
    }

    public double getPopulationFitness() {
        return this.populationFitness;
    }

    public int size() {
        return this.population.length;
    }

    public Individual setIndividual(int offset, Individual individual) {
        return population[offset] = individual;
    }

    public Individual getIndividual(int offset) {
        return population[offset];
    }

    public void shuffle() {
        Random rnd = new Random();
        for (int i = population.length - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            Individual a = population[index];
            population[index] = population[i];
            population[i] = a;
        }
    }

Exceção:
Exception in thread "main" java.lang.NullPointerException
        at chapter2.GeneticAlgorithm.calcFitness(GeneticAlgorithm.java:27)
        at chapter2.GeneticAlgorithm.evalPopulation(GeneticAlgorithm.java:46)
        at chapter2.AllOnesGA.main(AllOnesGA.java:12)
C:\Users\edega\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 0 segundos)

Gostaria de saber o que posso fazer para corrigir este problema.
Comment: Esta pergunta está sendo debatida no meta: https://pt.meta.stackoverflow.com/q/6237/132
Comment: Acho que em todas as classes, exceto a primeira, você esqueceu de colocar o `package chapter2;` e o `}` no final da classe.
Comment: Lendo a linha de erro, está a ser utilizado um objeto que tem `null` na linha `27`, agora é só tentar descobrir o porquê desse objeto ter `null`
Comment: Estou mexendo neste código. O seu projeto é bem legal, só tinha uns errinhos bobos e uns detalhes para melhorar.
Comment: Já tenho uma resposta pronta. Votei para reabrir a pergunta.
Comment: Se conseguir me passar o código corrigido, seria grato!
Answer: O seu erro é porque no main, você cria um objeto do tipo Population usando o construtor que só recebe um int. Esse construtor cria o array de Individual, mas não o preenche com nada, e portanto todas as posições serão nulas.
Quando o evalPopulation é chamado nessa população vazia, o population.getIndividuals() do laço for trará esse array para ser iterado. Desta forma, no laço for do método evalPopulation, a variável individual será null, e isso será passado para calcFitness.
No método calcFitness, uma vez que o individual é null, o individual.getChromosomeLength() na condição de parada do for vai dar um NullPointerException.
Há formas bem simples e rápidas de se resolver isso, mas decidi buscar uma abordagem mais profunda. Seu código até que é razoavelmente bem escrito, mas há uns probleminhas que podem ser arrumados.
A primeira coisa que se nota é que o seu método calcFitness olha para a quantidade de 1's encontrada nos genes do indivíduo. Entretanto, algoritmos genéticos para problemas diferentes usam diferentes formas de avaliar o fitness. Assim sendo, é importante que a forma de calcular o fitness possa ser plugada e/ou definida por quem for utilizar a classe GeneticAlgorithm, assim como são os demais valores dessa classe (populationSize, crossoverRate, mutationRate e elitismCount). Logo, podemos especificar uma interface que diz o que é um cálculo de fitness:
package chapter2;

@FunctionalInterface
public interface FitnessFunction {
    public double getFitness(boolean[] chromosome);
}

Você notou o boolean[] no parâmetro do método? Pois bem, a sua classe Individual trabalha com int[]. Entretanto os ints usados são sempre 0 e 1, logo convém usar boolean[] ao invés de int[].
Parte do problema que levou você a cometer um erro que causou um NullPointerException era o de estar trabalhando com um objeto Population incompleto e não devidamente inicializado. Trabalhar com objetos em estados incompletos ou não-inicializados é uma má prática de programação, mas não se fala o suficiente sobre isso.
Uma arma contra essa classe de problemas é o princípio de que o construtor não deve apenas instanciar o objeto, mas sim devolver uma instância já devidamente inicializada e completamente preenchida.
Uma outra arma contra problemas de trabalhar com objetos inconsistentes é a imutabilidade, pois garante que o objeto assim que criado estará em um estado válido e dele não poderá sair. Caso um objeto em um estado diferente seja desejado, um novo objeto deverá ser criado. A imutabilidade é muito útil em Strings por exemplo, ao garantir que uma referência para "xyz" não possa misteriosamente e repentinamente se tornar em uma referência para "abc".
Juntando esses conceitos, vamos definir a classe Individual como uma classe imutável:
package chapter2;

import java.util.Random;

public final class Individual {

    private static final Random RND = new Random();

    private final boolean[] chromosome;
    private final double fitness;
    private final FitnessFunction fitnessCalc;

    private Individual(FitnessFunction fitnessCalc, boolean[] chromosome) {
        this.chromosome = chromosome;
        this.fitnessCalc = fitnessCalc;
        this.fitness = fitnessCalc.getFitness(chromosome);
    }

    public static Individual randomIndividual(FitnessFunction fitnessCalc, int chromosomeLenght) {
        boolean[] chromosome = new boolean[chromosomeLenght];
        for (int gene = 0; gene < chromosomeLenght; gene++) {
            chromosome[gene] = RND.nextInt(2) == 0;
        }
        return new Individual(fitnessCalc, chromosome);
    }

    public static Individual cross(Individual parent1, Individual parent2) {
        boolean[] chromosome = new boolean[parent1.getChromosomeLenght()];
        for (int geneIndex = 0; geneIndex < chromosome.length; geneIndex++) {
            //Usa metade dos genes do parent1 e metade dos genes do parent2.
            Individual parent = RND.nextInt(2) == 0 ? parent1 : parent2;
            chromosome[geneIndex] = parent.getGene(geneIndex);
        }
        return new Individual(parent1.fitnessCalc, chromosome);
    }

    public Individual newMutant(double mutationRate) {
        // Cria os cromossomos do novo indivíduo inicialmente como uma cópia do cromossomo deste indivíduo.
        boolean[] newChromosome = chromosome.clone();

        // Percorre os cromossomos do novo indivíduo e troca alguns genes aleatoriamente, respeitando a taxa de mutação.
        for (int geneIndex = 0; geneIndex < chromosome.length; geneIndex++) {
            if (mutationRate > RND.nextDouble()) {
                newChromosome[geneIndex] ^= true;
            }
        }

        // Cria o novo indivíduo com o novo cromossomo mutado.
        return new Individual(fitnessCalc, newChromosome);
    }

    private int getChromosomeLenght() {
        return this.chromosome.length;
    }

    private boolean getGene(int offset) {
        return this.chromosome[offset];
    }

    public double getFitness() {
        return this.fitness;
    }

    @Override
    public String toString() {
        char[] c = new char[chromosome.length];
        for (int geneIndex = 0; geneIndex < chromosome.length; geneIndex++) {
            c[geneIndex] = chromosome[geneIndex] ? '1' : '0';
        }
        return new String(c);
    }
}

Essa classe acima merece algumas explicações, vez que algumas coisas do seu código original que nela não estavam foram parar lá dentro e além disso, a estrutura é significativamente diferente da sua classe original. O principal motivo para isso são os métodos invejosos.
Um método invejoso é um método que "queria" estar dentro de uma classe, mas está em outra. Ou seja, é um método que foi colocado na classe errada. Idealmente, um método representa uma operação realizada sobre a classe que o contém. Porém um método invejoso que "tem inveja" de uma outra classe, ao invés de representar uma operação sobre a classe que o contém, representa uma operação sobre uma outra classe.
No seu código original, praticamente tudo o que está na classe GeneticAlgorithm são métodos que queriam estar na classe Population. Já o método calcFitness queria estar na classe Individual. Os métodos crossoverPopulation e mutatePopualtion têm inveja da classe Population, mas dentro dos laços for de ambos, é possível extrair-se um trecho em cada que têm inveja de Individual. Após a extração desses trechos e a mudança deles para a classe Individual, temos os métodos cross e newMutant na classe Individual.
Outra coisa a se notar é a imutabilidade de Individual. Observe que o construtor é privado, todos os campos são final e a classe é final. Isso é para garantir que quando o objeto é instanciado, ele já terá sido completamente inicializado e não poderá ser alterado. Observe que o cálculo do fitness é feito dentro do próprio construtor, o que elimina a necessidade de você ter que chamar um método setFitness ou calcFitness no objeto posteriormente. A necessidade de que um setFitness ou calcFitness tenha que ser chamado após a conclusão da execução do construtor demonstra que o objeto não havia sido construído por inteiro e que esse método servia para terminar de construí-lo. Assim sendo, o melhor lugar para calcular o fitness é no construtor (cálculo esse delegado ao FitnessFunction).
Uma mutação (método mutate) em um Individual consiste na criação de um outro Individual com um cromossomo um pouco diferente. Um cruzamento entre dois Individuals (método cross) também cria um novo Individual sem alterar nenhum dos dois pais. Do seu construtor original que recebia um int, fiz o método randomIndividual. O fato do construtor ser privado garante que é impossível criar-se instâncias de Individual por alguma forma que não seja por meio de um desses três métodos, o que garante que as regras de criação do Individual são respeitadas.
Além disso, como efeito colateral da eliminação da inveja de métodos, a classe Individual tem menos necessidade de expôr getters ou outros métodos para serem utilizados por outras classes, e como efeito o encapsulamento é melhorado, acoplamento entre classes é reduzido e a coesão da classe é aumentada. Isso possibilitou a remoção do método getChromosome() e a redução da visibilidade do getGene de public para private.
Utilize a classe StringBuilder para criar Strings complexas. Ficar concatenando Strings dentro de um loop é uma má-prática de programação, pois cria um monte de objetos intermediários String desncessários que consomem memória e têm que ter os seus conteúdos copiados cada vez que alguma coisa for concatenada, prejudicando o desempenho. Neste ponto, o fato de StringBuilder não ser imutável é uma vantagem.
Um caso análogo a esse, onde a mutabilidade é utilizada é nos métodos randomIndividual, mutate e cross, que se aproveitam da mutabilidade dos arrays para garantir um bom desempenho e só instanciar o Individual uma única vez no final. Se não fosse assim, ou teríamos que sacrificar a imutabilidade de Individual ou teríamos que instanciar vários Individuals intermediários cada qual com um gene diferente do anterior, e tendo que copiar várias e várias vezes os cromossomos.
Por fim, o último detalhe a se notar na classe Individual, é que só precisamos de uma instância de Random. Logo, ela é mantida em uma variável private static final.
Retirando tanta coisa referente à classe GeneticAlgorithm por causa de métodos invejosos levaria a classe Population a precisar de vários dos valores que estão em GeneticAlgorithm. Para evitar criar um acoplamento forte entre essas classes, criei a classe GeneticAlgorithmParameters:
package chapter2;

public final class GeneticAlgorithmParameters {
    private final double crossoverRate;
    private final double mutationRate;
    private final int elitismCount;
    private final int populationSize;
    private final int chromosomeLength;
    private final FitnessFunction fitnessCalc;

    public GeneticAlgorithmParameters(
            double crossoverRate,
            double mutationRate,
            int elitismCount,
            int populationSize,
            int chromosomeLength,
            FitnessFunction fitnessCalc)
    {
        this.crossoverRate = crossoverRate;
        this.mutationRate = mutationRate;
        this.elitismCount = elitismCount;
        this.populationSize = populationSize;
        this.chromosomeLength = chromosomeLength;
        this.fitnessCalc = fitnessCalc;
    }

    public double getCrossoverRate() {
        return crossoverRate;
    }

    public double getMutationRate() {
        return mutationRate;
    }

    public int getElitismCount() {
        return elitismCount;
    }

    public int getPopulationSize() {
        return populationSize;
    }

    public int getChromosomeLength() {
        return chromosomeLength;
    }

    public FitnessFunction getFitnessCalc() {
        return fitnessCalc;
    }
}

Esta classe não tem muito de especial sobre ela, mas é de se notar que ela é imutável. Ela representa os parâmetros com o qual o seu algoritmo genético opera: qual é a população, qual é o tamanho dos cromossomos, qual é a função de fitness, a taxa de mutação, etc.
Agora, vamos à classe Population:
package chapter2;

import java.util.ArrayList;
import java.util.List;

public final class Population {

    private final int generationNumber;
    private final GeneticAlgorithmParameters parameters;
    private final List<Individual> individuals;
    private final double populationFitness;

    private Population(
            int generationNumber,
            GeneticAlgorithmParameters parameters,
            List<Individual> individuals)
    {
        // Seta vários dos atributos desta população.
        this.generationNumber = generationNumber;
        this.parameters = parameters;
        this.individuals = individuals;

        // Ordena os indivíduos por fitness.
        individuals.sort((o1, o2) -> (int) Math.signum(o2.getFitness() - o1.getFitness()));

        // Calcula o fitness da população.
        this.populationFitness = individuals.stream().mapToDouble(Individual::getFitness).sum();
    }

    public static Population randomPopulation(GeneticAlgorithmParameters parameters) {
        // Cria uma lista inicialmente vazia dos indivíduos que serão gerados.
        List<Individual> individuals = new ArrayList<>(parameters.getPopulationSize());

        // Coloca na lista vários indivíduos gerados aleatoriamente.
        for (int individualCount = 0; individualCount < parameters.getPopulationSize(); individualCount++) {
            Individual individual = Individual.randomIndividual(
                    parameters.getFitnessCalc(),
                    parameters.getChromosomeLength());
            individuals.add(individual);
        }

        // Cria uma população na geração 1 com os indivíduos gerados.
        return new Population(1, parameters, individuals);
    }

    public Individual getFittest() {
        // Retorna o primeiro indivíduo (o que tem o melhor fitness).
        return individuals.get(0);
    }

    public int getGenerationNumber() {
        return generationNumber;
    }

    public boolean isTerminationConditionMet() {
        return individuals.stream().anyMatch(individual -> individual.getFitness() == 1);
    }

    private Individual selectParent() {
        // Crossover aplicado com o método "Roleta de Cassino".
        // Gira a roleta.
        double rouletteWheelPosition = Math.random() * populationFitness;

        // Encontra o indivíduo para o crossover.
        double spinWheel = 0;
        for (Individual individual : individuals) {
            spinWheel += individual.getFitness();
            if (spinWheel >= rouletteWheelPosition) {
                return individual;
            }
        }

        // Se a roleta não parou em nenhum indivíduo, escolhe o último.
        return individuals.get(individuals.size() - 1);
    }

    public Population crossover() {
        // Cria uma lista inicialmente vazia dos indivíduos que serão gerados.
        List<Individual> newIndividuals = new ArrayList<>(parameters.getPopulationSize());

        // Loop sobre população atual por fitness.
        int populationIndex = 0;
        for (Individual parent1 : individuals) {

            // Aplicar crossover a este indivíduo?
            if (parameters.getCrossoverRate() > Math.random() && populationIndex > parameters.getElitismCount()) {

                // Encontra o par para realizar o crossover.
                Individual parent2 = selectParent();

                // Realiza o crossover e cria um novo indivíduo.
                Individual offspring = Individual.cross(parent1, parent2);

                // Adiciona o novo indivíduo gerado à lista da nova população.
                newIndividuals.add(offspring);
            } else {
                // Adiciona o indivíduo à lista da nova população sem aplicar crossover.
                newIndividuals.add(parent1);
            }
        }

        // Cria uma nova população da geração seguinte com os indivíduos gerados.
        return new Population(generationNumber + 1, parameters, newIndividuals);
    }

    public Population mutate() {
        // Cria uma lista inicialmente vazia dos indivíduos que serão gerados.
        List<Individual> newIndividuals = new ArrayList<>(parameters.getPopulationSize());

        // Loop sobre população atual por fitness.
        int populationIndex = 0;
        for (Individual individual : individuals) {

            // Faz mutação se o indivíduo não for elite.
            Individual newIndividual = populationIndex >= parameters.getElitismCount()
                    ? individual.newMutant(parameters.getMutationRate())
                    : individual;

            // Adiciona o indivíduo a nova população.
            newIndividuals.add(newIndividual);

            // Conta um indivíduo a fim de podermos contar quantos
            // estão na elite e quantos sofrerão mutação.
            populationIndex++;
        }

        // Cria uma nova população da geração seguinte com os indivíduos gerados.
        return new Population(generationNumber + 1, parameters, newIndividuals);
    }

    @Override
    public String toString() {
        return "Generation " + generationNumber
                + ", best fitness " + getFittest().getFitness()
                + ", individuals " + individuals.toString();
    }
}

A primeira coisa a se notar aqui é que uso List<Individual> ao invés de Individual[]. Isso daí por si só já diminui a possibilidade de você ter um NullPointerException porque a lista nunca terá elementos nulos mesmo quando recém-instanciada, diferente do que ocorre com o array. Ao usar listas ao invés de array, você também passa a ter que se preocupar bem menos em rastrear o tamanho. Com listas, também há bem menos necessidade de ficar se contando e calculando posições de elementos.
A classe Population é imutável, devendo ser instanciada já com a lista definitiva de indivíduos. O método setIndividual da sua classe original foi eliminado, pois ele era usado apenas para preencher o Population recém-criado. Ou seja, o método setIndividual servia para terminar de construir o objeto que o construtor deixou incompleto, exatamente o que buscamos eliminar. O construtor também é privado e instâncias só podem ser criadas pelos métodos mutate, cross e randomPopulation, sendo que os dois primeiros se preocupam em aumentar o número da geração (o último cria a geração 1). As listas utilizadas por esses três métodos também são mutáveis enquanto estão sendo preenchidas, sendo tratadas como imutáveis quando essa lista é passada ao construtor de Population.
Além disso, o construtor de Population já ordena os indivíduos de acordo com o fitness, para que essa operação não seja mais uma etapa de construção do objeto que o construtor não fez. Com o cálculo do populationFitness, também temos novamente a mesma situação (o que fez sumir o método evalPopulation). E ainda por cima, perceba que o código para essas duas atividades (ordenar e medir o fitness da população) fica bem mais simples usando a sintaxe de lambda do Java 8. O lambda também é usado para simplificar o isTerminationConditionMet.
Quanto ao número de geração, tive a impressão de que isso era algo que tinha inveja da classe Population, e por isso coloquei aí dentro. Outro efeito da melhora do encapsulamento foi que o método getFittest agora não precisa mais do parâmetro int, apenas o indivíduo de maior fitness precisa ser acessado externamente.
Parte da sua classe AllOnesGA consistia no algoritmo genético propriamente dito, que é o algoritmo que produz tantas gerações quantas forem necessárias de populações, as avalia, faz crossover e mutações. Isso daí foi movido para a classe GeneticAlgorithm, que ficou assim:
package chapter2;

public class GeneticAlgorithm {
    private final GeneticAlgorithmParameters params;

    public GeneticAlgorithm(GeneticAlgorithmParameters params) {
        this.params = params;
    }

    public Population run(int maxGenerations) {

        // Inicializa a população.
        Population population = Population.randomPopulation(params);
        System.out.println("Start population: " + population);

        // Produz tantas gerações quanto forem necessárias até que o número
        // máximo de gerações tenha sido atingido ou uma solução ideal tenha
        // sido encontrada.
        while (population.getGenerationNumber() < maxGenerations
                && !population.isTerminationConditionMet())
        {
            // Aplica o crossover (conta uma nova geração).
            population = population.crossover();
            System.out.println("New population: " + population);

            // Aplica mutação (conta uma segunda nova geração).
            population = population.mutate();
            System.out.println("New population: " + population);
        }

        return population;
    }
}

Note que dessa classe não há nada da sua classe original. O que havia na classe original eram métodos invejosos que agora estão no lugar certo, e o que ficou aqui foi um comportamento que era invejoso por não estar aqui.
O único porém é que ele acaba contando uma geração para o crossover e uma outra para o mutate, vez que a cada iteração do while, cada um desses cria um novo Population o que implica em duas gerações por iteração do while.
Por fim, nota-se que há um parâmetro maxGenerations para evitar que o método fique preso em um loop infinito ou que uma solução demore dias, meses ou anos para sair. Ao atingir o número máximo de iterações, é retornada a última população gerada (que deve ser encabeçada pelo indivíduo com o maior fitness já encontrado).
E finalmente a sua classe AllOnesGA:
package chapter2;

public class AllOnesGA {

    // Função de avaliação de fitness de teste.
    // O valor máximo dela é quando todos os valores do cromossomo são verdadeiros.
    // Esta função é apenas para exemplificar, pois numa aplicação real, o valor
    // ótimo do cromossomo é difícil de ser determinado e a implementação desta
    // função seria bem complicada e difícil de otimizar manualmente ou por uso
    // de técnicas mais ortodoxas.
    private static double simpleFitness(boolean[] chromosome) {
        // Rastreia o número de genes corretos.
        int correctGenes = 0;

        // Loop sobre cada gene.
        for (boolean b : chromosome) {
            // Adiciona um ponto de fitness para cada true encontrado.
            if (b) correctGenes++;
        }

        // Cálculo de fitness.
        return (double) correctGenes / chromosome.length;
    }

    public static void main(String[] args) {
        double crossoverRate = 0.05;
        double mutationRate = 0.01;
        int elitismCount = 3;
        int populationSize = 80;
        int chromosomeCount = 15;
        int maxGenerations = 10000;

        // Cria os parâmetros do algoritmo genético (inclusive a função de fitness).
        GeneticAlgorithmParameters params = new GeneticAlgorithmParameters(
                crossoverRate,
                mutationRate,
                elitismCount,
                populationSize,
                chromosomeCount,
                AllOnesGA::simpleFitness);

        // Cria instância do algoritmo genético com os parâmetros dados (inclusive a função de fitness).
        GeneticAlgorithm ga = new GeneticAlgorithm(params);

        // Executa o algoritmo genético até obter a população final.
        Population finalPopulation = ga.run(maxGenerations);

        // Mostra a população final.
        System.out.println("Final population: " + finalPopulation);
        Individual fittest = finalPopulation.getFittest();
        System.out.println("Best solution: " + fittest + " - Fitness: " + fittest.getFitness());
    }
}

O método simpleFitness é o seu método de fitness original, que verifica se todos os genes são verdadeiros. Outros métodos de cálculo de fitness podem ser usados dependendo do problema específico no qual você vai buscar uma solução com algoritmos genéticos.
O método main também não possui muitos segredos. Ele cria os parâmetros do algoritmo genético (pode alterá-los para brincar a vontade), instancia o algoritmo genético, executa ele e mostra o resultado.
Para finalizar, lembre-se que:

O operador ternário é seu amigo se você souber utilizá-lo, e ele pode te eliminar aqueles ifs chatos onde o que está no bloco do if é quase igual ao que está no bloco do else, evitando duplicações de código.
Se você for utilizar uma expressão na forma blablabla == false, sendo blablabla uma expressão do tipo bololean, use apenas !blablabla ao invés disso. O mesmo vale para blablabla == true, basta usar simplesmente blablabla.
Usar blablabla ^= true; é um truque para inverter um valor do tipo boolean. Muito útil quando escrever blablabla = !blablabla fica ruim quando a expressão blablabla se transforma em uma expressão bem complexa tal como o newChromosome[geneIndex] da classe Individual. Por exemplo, newChromosome[geneIndex] ^= true; fica mais simples do que newChromosome[geneIndex] = !newChromosome[geneIndex].


Prometheus expose any metrics on itself? (e.g. disk space it uses)

Question: Does Prometheus expose any metrics on itself? i.e. how much disk space it's using etc.
I want to start fine tuning our prometheus server, so need to monitor what's currently there. I want to be able to see how much disk space it using.
Prometheus v2.31 installed via apt on Ubuntu Linux 22.04 LTS.
Answer: The /metrics endpoint should be enabled by default (couldn't find any documentation on enabling/disabling this feature, seems to be always on)
Prometheus needs to be configured to scrape the metrics endpoint from itself:
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # Override the global default and scrape targets from this job every 5 seconds.
    scrape_interval: 5s

    static_configs:
      - targets: ['localhost:9090']

Taken from the getting started guide.
I guess the most relevant metric from the Prometheus endpoint regarding disk space usage would be: prometheus_tsdb_storage_blocks_bytes
But for fine tuning and profiling you might want to install prometheus node exporter as well.


Probability of product x*y with ln(0) in integral

Question: I have two random variables with the following distributions:

P(x) = 2(1-x), 0 < x < 1
P(y) = 1, 0 < y < 1

I want to find the pdf $P(x\cdot y = z)$. Here is how I'm doing it:
$$
\int_0^1 P_y(y)P_x(z/y)\frac{1}{|y|}dx \\
2\int_0^1 1/y - z/y^2dy = 2[ln(y)+z/y]_0^1
$$
but ln(0) is indetermined. What am I doing wrong?
Comment: It is easier with CDFs:  To get $XY\le z$ then either $0 \le X\le z$ with any $Y$ or, when $z \le X \le 1$, then $0 \le Y \le \frac{z}{X}$.  That suggests to me that at least your limits may need adjustment
Comment: Thanks, Aaron, I just updated the question. I want to find the pdf $P(x\cdot y = z)$.
Comment: Notice $P_x (\frac{z}{y})=0$ if  $\frac{z}{y} \geq 1$. In other words: $y$ must be greater than $z$ for $z>0$.
Comment: Thanks, Henry. I'll take a crack at that.
Answer: Let $Z=XY$, then indeed the density of $Z$ is given by
$$
f_Z(z) = \int_{\mathbb R}f_X(x)f_Y(z/x)\frac1{|x|}\ \mathsf dx.
$$
Here $f_X(x)=2(1-x)\cdot \mathsf 1_{(0,1)}(x)$ and $f_Y(y)= \mathsf 1_{(0,1)}(y)$. The relation $\frac zx\in(0,1)$ occurs precisely when $0<z<x$, and hence
$$
f_Z(z) = \int_z^1 \frac{2(1-x)}x\ \mathsf dx = 2(z-(1+\log z)),\quad z\in(0,1).
$$


EntitySQL 'IN subquery

Question: I have the following T-SQL:
SELECT Cust.[CompanyName]
FROM Customers AS Cust
WHERE
(
  Cust.[CompanyName] IN (SELECT CustSQ1.[CompanyName] AS [Customer Company name]
FROM Customers AS CustSQ1
WHERE
(
  CustSQ1.Country = 'Argentina' )
) )
How do I do the same in EntitySQL?
Answer: I found the solution. Corresponding EntitySQL is:
"SELECT Cust.[CompanyName] FROM (SELECT CustSQ1.[CompanyName] FROM Customers AS CustSQ1 WHERE ( CustSQ1.Country = 'Argentina' )) AS Cust"

EntitySQL 'IN subquery


How to represent a Spearman correlation with a line?

Question: Working in health science research. We have generated correlations between two variables. This is the amount of two proteins in the system.
I wanted to make a straight line with slope, but the values of the straight lines are not consistent with the R values of the Spearman correlation test.
Indeed, the R is negative while the slope of the line is positive. Or vice versa.
Or two lines are similar, but the R is totally different.
It cannot be published in a newspaper.
I then wonder how to represent the correlation between the two variables on the graphs and see the evolution of the point cloud?
(1 and 2 are two different populations)
Thanks for your advices !

Whuber: yes sorry, I expressed myself badly.
We performed Spearman correlations, and we wanted to visually represent the trend of the data with a straight line. (not necessarily a non-linear line of regression).
It does not matter whether the correlation is good, significant or not.
Just show at a glance if there is a correlation or not.
I had in mind the correlation could be represented by a straight line. And the values of the correlation test made it possible to show scientifically that this is valid.
But with Alexis, I understand that I can't do that. And these graphs prove it, where I have negative R's with positive slopes.
I will try in log.
Is there a visual method to represent a correlation on this type of graph?
Because in life sciences, a representation of the genre is often more convincing for scientific journals.
Afterwards, I am not a mathematician or a statistician, so there are a lot of gaps. And I work on the GraphPad prism software, which may have some limitations.
chrishmorris: Indeed, we have an R and not an R².
Here is the type of data we have with a spearman correlation test in the GraphPad Prism software.
Comment: Three quite different comments: 0. You seem to have 3 variables here 1. The graph to make sense of Spearman correlations is a plot of the ranks of two variables. 2. Regardless of P-values straight lines aren't very convincing Perhaps it would help a bit to work with log Y, depending partly on what makes sense scientifically.
Comment: I want to link whuber and @NickCox's comments: While you can graph straight lines on the **ranks** of your data, you **cannot** validly represent **monotonic association** (i.e. what Spearman's $r_{\text{S}}$ measures) with (only) a straight line on your data (not ranks), since the are many nonlinear curves which are [monotonic functions](https://en.wikipedia.org/wiki/Monotonic_function) of two variables.
Comment: Please explain the sense in which a "straight line" might be considered "nonlinear regression."  That reads like a direct contradiction.  Why are you mentioning Spearman correlation, which otherwise appears unrelated to the rest of the question?
Comment: Hello,
Thank you for your answers. Indeed, I had misunderstood and I realize that the two tests are different!

Nevertheless, I am looking for the best test to apply to my data.
I want to know:
1) If X and Y are related. So show if X increases Y also increases (or vice versa) or show that this is not true.
2) know if the two groups (red and blue) are different from each other.

For the 1 I thought to use the correlation test
For the 2 I thought to use the simple line of regression and test the difference between two lines.
But maybe other tests are more suitable?
Comment: It might depend on what you mean by "different".
Comment: Usually when addressing this kind of question, you would use what might be called *analysis of covariance*, where the data for the two groups are put in a single model, and then you can test for differences for the slopes and for the intercepts. ...  There may be a nonparametric model that achieves this.
Comment: My two groups (red and blue) are healthy or sick patients. So know if there is a significant difference in relation between X and Y. For example the red graph 1 seems to indicate that when X is large, Y is small. Which is not the case with Blue. Is this significantly true? What is the appropriate test?
Comment: I use the GraphPad Prism software, I used the "Test whether slopes and intercepts are significantly different" function. And here is the result for the first graph: [Are the slopes equal? F = 3.493. DFn = 1, DFd = 199 P=0.0631 - If the overall slopes were identical, there is a 6.309% chance of randomly choosing data points with slopes this different. You can conclude that the differences between the slopes are not quite significant. Since the slopes are not significantly different, it is possible to calculate one slope for all the data. The pooled slope equals -0.1368.] Is this the right test?
Comment: On the internet, they seem to say that this test is equivalent to an analysis of covariance
Comment: Possibly related: https://stats.stackexchange.com/questions/64938/if-linear-regression-is-related-to-pearsons-correlation-are-there-any-regressi
Comment: Is the *r* presented Spearman's *rho* ?
Comment: The answers are pretty much in these comments:  Spearman correlation and linear regression aren't the same thing, so it's not surprising that the results are different.  You could rank transform both variables, plot them that way, and then Pearson correlation, Spearman correlation, and linear regression will all be consistent.   ...  But given the bivarate distributions of your observations, you might consider a different approach.  Perhaps nonparametric regression or transforming the observations. ... Ultimately, it really depends on what you want to know.
Answer: It is only with the blue points on the second graph that you have a model - an R value of 0.49 shows that there is a real correlation here, albeit not a very strong one.
A negative value for R-squared shows no correlation - it means that your model is a worse predictor than always predicting the mean value of Y.
Looking at your first graph, this is not surprising - neither the blue points nor the red points seem to show any correlation between X and Y. However, it is conspicuous that for both variables low values are more common than high values. It is worthwhile to try a data transformation to mitigate this and try again to find a correlation (e.g. square root).
On the second graph, with the red points, X is at best a weak predictor of Y. If there is any causal mechanism at all there would seem to be two subpopulations, one with low Y values positively correlated with X and a smaller one with large Y values negatively correlated with X.


OpenCV: how to create .vec file to use with opencv_traincascade

Question: As I explained in my previous post here, I am trying to generate some cascade.xml files to recognize euro coins to be used in my iOS app. Anyway, I am founding many difficulties in understanding how to generate a .vec file to give as input to opencv_traincascade. This because I heard many dissenting views: someone told me that vector file must include only positive images containing only the object to recognize; someone else instead (and also as read in my tutorials) said that vector file must include "samples" images, in other words random backgrounds to which the object to recognize has been added by opencv_createsamples. In oter words with:
opencv_createsamples -img positives/1.png -bg negatives.txt -info 1.txt -num 210 -maxxangle 0.0 -maxyangle 0.0 -maxzangle 0.9 -bgcolor 255 -bgthresh 8 -w 48 -h 48
which generated 12000 images.
Finally, I have created the .vec file with:
cat *.txt > positives.txt
opencv_createsamples -info positives.txt -bg negatives.txt -vec 2.vec -num 12600 -w 48 -h 48
So, I would like to ask you which the correct images to be contained in vector files from the following two:

Moreover, which is the final command to give to launch the training? This is the ones I have used up to now:
opencv_traincascade -data final -vec 2.vec -bg negatives.txt -numPos 12000 -numNeg 3000 -numStages 20 -featureType HAAR -precalcValBufSize 2048 -precalcIdxBufSize 2048  -minHitRate 0.999 -maxFalseAlarmRate 0.5 -w 48 -h 48 -mode ALL
where the .vec files contains 12000 samples images (background + coin to recognize).
Should the .vec file contain only positive images (only coins), how shall I tell opencv_traincascade to train using the samples images?
I really need to know how to do things correctly because I have launched many training which then lead to no correct result and since they take many hours or days to execute, I can't waste time anymore.
Thank to all for your attention.
UPDATE
I managed to create a cascade.xml file with LBP. See what happens if I give one of the image used as training samples to a simple OpenCV program:

while with an image like the following:

it does not work at all. I really don't know where I am making the mistake.
UPDATE
Maybe firstly converting positive images to gray scale could help?
Answer: I've used the negative samples database of the INRIA training http://pascal.inrialpes.fr/data/human/
and this input (png with alpha transparency around the coin):

using this with this command:
opencv_createsamples -img pos_color.png -num 10 -bg neg.txt -info test.dat -maxxangle 0.6 -maxyangle 0 -maxzangle 0.3 -maxidev 100
 -bgcolor 0 -bgthresh 0
produces output like this:

so background color obviously didn't work. Converting to grayscale in the beginning however gives me this input:

and same command produces output like this:

I know this is no answer to all of your questions, but maybe it still helps.
Comment: Thank you very very much Micka's!! I will try at once to create samples with coins images in grayscale. I'll let you know. Thank you from heart
Comment: Thank you for you answer but it really does not work. First I converted all my images to grayscale with `convert ../0.png -colorspace Gray 0.png` and then I launched the command you posted but the output was the same...nothing to do. Thank you anyway
Comment: is the background black in your grayscale image? It must really be value 0. If you checked that and still doesnt work, please upload such a grayscale input image.
Comment: it's not black. I have tried to convert both by gimp and by `convert` (from image magic) but the background is not black...hod did you do that? You can see ax example in my question I have just updated
Comment: in gimp just delete the background (mark a circle and invert the selection) and color it black (or any other constant color that you set the parameter to)
Comment: Ok, I guess I have made it with this command `convert 0.png -fill black -opaque none 0.jpg`
Comment: there is a thing which is unclear to me...should I want consider all the possible rotations (360°) of the coin around the z-axis (in other words the coin could be more or less "upside down"), which value for `-maxzangle ` shall I set?
Comment: sorry, I have no experience in actual training of haar classifier :-(
Comment: Don't worry. Your help has been very useful and kind. Thank you :)
Answer: OpenCV cascades (HAAR, LBP) can excellently detect objects which have permanent features.  As example all faces have nose, eyes and mouth at the same places. OpenCV cascades are trained to search common features in required class of object and ignore features which changes from object to object. The problem is conclude that the cascade uses rectangular shape of search window, but a coin has round shape. Therefore an image of the coin always will be have part of background.
So training images of the coin must includes all possible backgrounds in order to classifiers can ignore them (otherwise it will be detect coin only on the specific background).
So all training samples must have the same image ratio, size and position of the coin (square images with coin in center, diameter of coin = 0.8-0.9 image width), and different background!
Comment: I would add a bit of background on the edges in order to the classifier can use the edge of the coin.
Comment: My training samples are all similar to the onw I posted in question. As you can see I have many images like that, with the coin and many possibile backgrounds... Aren't they correct?
Comment: I know but that's a problem of `opencv_createsamples`. I mean, if I use a 2€ coin downloaded from google images, then those 4 corners are not put in the sample image. If I use a png image created by gimp (with circular crop) and obtained from the frames of a short video, then there are those 4 corners. Do you know how to fix it or where I am making a mistake?
Comment: if you create the images with GIMP you can easily use the alpha channel to remove the corners during insertion of the coin.
Comment: @Micka I use gimp only to crop the photos with the coin. Then the composition with a random background is done by `opencv_createsamples`, not with gimp
Comment: @LoryLory http://docs.opencv.org/master/dc/d88/tutorial_traincascade.html says you can use parameter `-bgcolor ` to define a background color which is interpreted as being transparent. You might be able to set it to the color of the image border, where the coint isn't 'active'.
Comment: I had read that and I had set bgcolor = 255 or = 0 but this is ignored...there are always those 4 corners
Comment: for me it is working... however i converted my input to grayscale first


QoS Traffic Shaping based on packet loss and latency for VPN

Question: I am currently having the following situation:
I am using a VPN (OpenVPN) over a rather unstable internet connection. This means the maximum bandwidth varies between 100kbs and 1mbit. Whenever the connection is rather unstable and there is high traffic I get a lot of packet loss and everything gets very slow. To prevent this I need some mechanism to control the maxium bandwidth based on packet loss / latency, to get below the threshold where packets are dropped massively.
I was thinking of having an icmp (ping) control channel to the vpn server, which is continously analyzed using some kind of script and if the ping gets bad or packets are dropped, the maximum bandwidth will be adjusted by setting a new max bandwidth using tc (for QoS).
My Questions would be:
1. Can this already be done just using tc?
2. Is there maybe a tool, which already does, what I want?
Thanks in advance and best regards!
Answer: I think you want to find a way to shape your traffic before the encapsulation occurs, inside a VM with bridged ethernet for example. Your computer shapes and route to your VM, your VM does the encapsulation.
Moreover, as you can't fix a rate, you should use prio scheduler with tc.
Since TCP has congestion avoidance mechanism and UDP hasn't (QUIC excepted), place UDP and TCP in different qdiscs.
Your problem may be in TCP flows lowering rate while UDP ones doesn't.
Furthermore, you should in this case where you don't know your line rate, priorize TCP qdiscs over UDP qdiscs, with one exception : low rate high priority UDP flows (DNS, NTP) should have the highest priority.
Comment: Hey, thanks for you response. The priorization would be done before VPN ecapsulation anyway.
I am not sure if the qdisc Prio would bring me anything, since my traffic is mostly tcp. The problem is that whenever traffic is too much and the connection is rather unstable, packets get dropped massiveley and it takes a while (up to 40 seconds), till everything calmed down.
Comment: Usually, when you're writing QoS rules, you need to know the bandwidth you can use. Prio is the lonely one, as far as I know, which doesn't.
Comment: I'm sorry, I forgot i can't use enter in comments. Prio will always priorize one flow over another, even if the second has to be completely dropped. This way, you could use something like : UDP Services (DNS, NTP) and ping > SSH > HTTP connections under 10 Mo (to avoid download connections to be here) > Other connections. Obviously, you have to change this to your needs. With such a QoS, if you have a low bandwidth for a while, your main connections should be availaible. The udp / tcp point isn't related to the qdisc.


Find a basis and dimension for the vector space $V=\bigl\{f(x)\in\mathbb{R}[x];\ \deg f<5,\ f''(0)=f(1)=f(-1)=0\bigr\}.$

Question: $$V=\bigl\{f(x)\in\mathbb{R}[x];\ \deg f<5,\ f''(0)=f(1)=f(-1)=0\bigr\}.$$
NOTE:
The degree is strictly less than 5 not equal.
Also my prof and T.A. said I should do $f(1)=f(-1)$ then solve it then do $f''(0)=0$ somewhere along the lines but I don't understand how to go about doing it that way.
PLEASE!! Can someone solve it doing it that way and not using matrices because for these questions you don't need to use matrices to solve it.
Answer: Hint:
Write $$
f(x)=a_0+a_1x+\cdots+a_4x^4.
$$
Find the relations among the $a_i$'s using $$f''(0)=f(1)=f(-1)=0.$$ For instance, what can you tell by $f(1)=0$?
Once you have the relations (precisely, linear equations) for these $a_i$'s, you would get a subspace of $\mathbb{R}^5$, the dimension of which is what you are looking for.
Comment: f(1)=0 -> a0=-a1-a2-a3-a4.......... @Jack
Comment: I finally get it!!! So we do f(1)=0, f(-1)=0, then f''(0)=0, and put what we got from that into each equation...... now I finally get it thank you. @Jack
Answer: Because $f(1)=0,$ you know $x-1$ is a factor of $f(x).$ Because $f(-1)=0,$ you know $x+1$ is a factor of $f(x).$ Therefore $(x-1)(x+1)=x^2-1$ is a factor of $f(x).$
Knowing that $f(x)$ is a polynomial of degree at most $4,$ and has a factor of $x^2-1,$ we must have $f(x)=(x^2-1)(ax^2+bx+c)$ for some constants $a,$ $b,$ and $c.$
Now consider the second derivative of $f(x)$; it is a polynomial of degree two or less, something of the form $g(x)=px^2+qx+r,$ and the value of $r$ is a multiple of the coefficient of $x^2$ in $f(x).$ But we know $g(0)=0,$ so $r=0.$ Therefore the coefficient of $x^2$ in $f(x)$ is zero.
Work out the coefficient of $x^2$ in $f(x)$ in terms of $a,$ $b,$ and $c.$ (Hint: $b$ isn't involved.) Express the fact that this coefficient is zero. The result will be an equation that lets you eliminate either $a$ or $c.$
To recapitulate: $f(1)=f(-1)=0$ lets you factor $f(x),$ leaving only three unknown parameters, and $f''(0)=0$ gives you a relationship among those unknowns, allowing you to reduce them to two.
I think writing $f(x)$ in its factored form makes it especially simple to rewrite it as a linear combination of two polynomials.


Multi-Effects Pedal or Multiple Effects Pedals?

Question: A long time ago I owned the BOSS PW-10 V-Wah and I loved it until I connected up to an incorrect power supply destroying the circuitry. I often see artists such as Matt Bellamy using a bunch of individual "single use" effects pedals wired into his loop fixed to a small board.
On the other hand we have the multi-effects pedal boards such as the BOSS GT-10 Guitar Effects Processor which do it all in one. This kind of package seems like a great deal when you think of the totalled individual prices of each effect (as I am sure BOSS's marketing department would let us know), but I have never really witnessed much widespread use by large bands.
The question then, is what really (when it comes down to it) is most beneficial for performance and experimental playing, a lot of individualistic pedals or a single big old "effects processor" like the GT-10? Is it worth the larger one-time payment? and where are all the cool people which use them?
Comment: SOME pros use stacked effect processors. Others use all sorts of separate boxes, wired using custom switchers and signal conditioners.
Comment: ... and some pros don't use effects at all (except the colour added by their amp)
Comment: pros use stacked effect processors...
Comment: Rafael Bittencourt, from Brazilian heavy metal band Angra, uses a BOSS GT-10 live. Maybe Angra isn't a major act absolutely speaking, but they can be regarded as a "large" band within many contexts.
Comment: And, Peter Torn, who's definitely a pro, is known to use TC-Electronic's G-System in his main board, and their Nova in his travel board. He supplements them with some individual external effects. Many pros have drawers in their rack for separate effects, controlled by effect switchers. So, it's obvious they do what it takes to get the sounds they want and don't necessarily rely on racks and/or multi-effects.
Answer: When you ask this question you are going to get 99% opinion because it is completely subjective. Plenty of people out there (like myself) absolutely hate multi-FX rigs, while others swear by them. There's no real scientific reason to pick one over the other, but here's a quick match up between their basic features:
All-in-One
Pros: Takes up less space; less expensive than a comparable pattern of boutique pedals, potentially easily configured depending on how intuitive the user interface is, most are software driven, easily powered with a single cable, no capacitance loss across longer cable runs, sometimes easier to use during a gig, most can midi sync with a click track, a single master volume (very big pro here). Good for guitarists that like options and swap between them a LOT.
Cons: Digital, can be annoying to tweak, hard to get some more unique sounds out of them, lack dynamics of some more high quality boutique pedals--specifically overdrives, tend to be very opaque.
Most all-in-one's sound obviously digital. Even the best modeling software out there is hard pressed to emulate analog circuits properly; it's tough to accurately represent hardware in software in many applications, and lots of these systems don't have the computational horsepower to compute the real deal algorithms quickly enough (Fourier transforms are hard, even the fast kind :D). Some people consider this to be a con, but others like the crystalline sound that you get from a purely digital source.
Pedals
Pros: Endless configuration possibilities (this one before that one, etc), more tangible--think of playing with legos vs. configuring sounds in software, arguably more versatile than some all-in-ones because there are a very large number of pedals on the market each with it's own sound, analog sound, digital sound, whatever sound you want, more modular. Good for guitarists who have a settled on a single sound and want to run with it, although a multi-FX unit could provide this same functionality as well if you don't monkey with it much.
Cons: Suffer from capacitance loss across long patch cable runs, way way way way more expensive, but scalable to the users budget, have to deal with inconsistant levels across the board if you have multiple pedals with volume controls, you have to compensate for amp goosing (boosts), potentially less compact than an all-in-one if you have a lot of pedals.
I prefer pedals due to their modularity, and my board is arguably more configurable than any multi-FX rig out there, I just gotta have the scratch to purchase that new cool pedal I want. Note that this only barely scratches the surface of this topic. Many a guitar forum has spent hundreds of pages discussing this exact issue.
I submit that there is no right answer for this conundrum :D.
Comment: "obviously digital" is subjecting and factually incorrect. There are *plenty* of great sound digital pedals and digital multi-effects units. Should be removed as a con. Also, on the pedal cons list "way, way, way more expensive" isn't necessarily true either. Sky is the limit in both categories. Last sentence is key. :)
Comment: Two additional points, with a multi-fx, you can easily dial in different types of the same effect, a little chorus on one patch vs a lot on a different one. This is hard to do with pedals without having multiple versions of the same effect. Second, there are higher end multi-fx that do not sound overly digital. In particular the Nova and G from TC are very good (the Nova even includes analog drive), but these are more expensive than Boss, Pod, Zoom, etc.
Comment: @Kaji: again, depends. I have instant access to any effect, in any patch, in my multi-effect rig thanks to a superior MIDI controller with lots of IA switches. So do the pros...
Comment: Hah okay okay, so some of my bias comes out. I tried pretty hard to keep it objective XD. Sounding digital definitely has it's place--I even own and use a pair of T-Rex Replicas on my main board because I can't live without tap tempo. So let me clarify that "I" consider sounding digital to be a con, but your mileage may vary. Thanks for pointing that out. It's not technically incorrect though. A discerning ear should be able to spot a digital delay against an MXR Carbon Copy or similar analog delay in a heartbeat.
Comment: As for the money comment, you're usually going to spend way more on a board than you will on say a Line6 MX10 or something similar. Granted, I know AxeFx rigs run in the 2k range, but my personal gigging board has approached that easily--and if you count all the pedals I have unloaded in the search for "my sound" eclipsed it.
Comment: It's also much easier to turn a single effect on or off with individual pedals than with milti-rigs.
Comment: Moved the "obviously digital" section out of the "cons" and explained it a little more in detail. Hopefully that looks better!
Comment: Agreed on this - personal choice. For me and for the gigs I play, I use a modest Vox Tonelab. It is not perfect, but the simplicity of popping it out, plugging in one patch cord and playing makes it just to good to pass up. Tone is excellent (although the discerning ear will be critical of it around the edges). As easy as it is, I admit to staring longingly at my old "box of toys" - these may find their back to my rig!
Comment: +1 for stating that its opinion based, and the detailed response.
I agree that digital effects don't quite have the same dynamics, but that sound also has value!
Answer: The big problem with an all-in-one box is you have to like all the sounds. For instance, I use a Pod X3 for recording into my computer, and it has a so-so chorus. Comparing it to my TC-Electronic chorus makes the Pod's chorus sound pretty bad. My Boss and MXR compressors are easier to control and I prefer their "sound" also, over the Pod's.
Prior to my X3 I had the Digitech modeler and got some good sounds from it too. Not all the sounds were to my liking, which is why I switched. Well, that and because I use Macs and their support of Macintosh is abysmal.
More expensive units, like the AxeFX might sound better for more of the effects, but I'd be surprised if every sound was killer or what you want. Being able to tweak to get there is important. That's where having individual effects is nice - if you don't like the sound of one you can replace it with something else retaining all your other sounds.
It's a trade-off and a pain trying to find a combo you like but we all go through it.
Comment: "It's a trade-off and a pain trying to find a combo you like but we all go through it." -- the journey we all take. Amen to that.
Comment: I have the TC Nova system, and I would say that all the effects are excellent quality. So, it is possible to get high quality out of a multi unit. The issue is that they're all high quality TC, so that's the only flavor you're getting.
Comment: I've looked at their G system, which is awesome, and the Nova, and would love either of them. TC has "their sound", but it is very nice sounding. Peter Torn's demo video of the Nova on [TC's site](http://www.tcelectronic.com/user_stories.asp?AjrDcmntId=9153) has some great tones.
Comment: Yeah. The unit rocks. But it is a very specific set of sounds you can get from it (I assume the G would give you more latitude).
Comment: I think we're only a few years away from some seriously powerful CPUs in the pedals that will make very realistic modeling available for reasonable prices. Line6 did a decent job on the X3; I'm eager to get my hands on the new generation to see how it does.
Answer:
and where are all the cool people which use them?

Here's list of artists that use the AxeFx -- an all-in-one effects unit and preamp that's of the seriously highest degree. Notables: Steve Vai (who's using it live as an effects processor along with his Legacy amps), Dweezil Zappa (who uses two of them to cover the sonic ground demanded by his Zappa Plays Zappa tour), Ty Tabor, John Petrucci...it's a good list of varied players. Those are four I know use them live, confirmed in the flesh.
Answer: I prefer the pedals because of the simplicity factor. All too often those multi-effects pedals just have too much going on [too many lights, settings, features]. Sure you can assign the pedals on the multi-units, but I know for sure that my 'white box' is my Red Witch chorus, and my little 'orange box' is my MXR phaser, etc.
Answer: In my opinion the main advantage of guitar processors is the convenience (easier to carry around, takes less space, you can use them without an amp), while the main advantage of a full effect chain is that it usually sounds better and is easier to tweak with in order to find the sound you are looking for.
I initially started with an amp and several pedals, but as I had to live between places switched to a Boss GT-3 and still use it. It is also easier to carry to rehearsal rooms.
But I know that as soon as I settle down I will definitely get a real set-up again.
Answer: It's a matter of taste, but here are some factors:
Price:
A $100 multi-fx pedal can gives you a set of effects you'd pay much more for in individual pedals.
Convenience:
Some multi-fx pedals take the same space as a single individual effect. All multi-fx pedals let you save patches, so it's easy to recall a combination of settings, and switch between stored settings quickly.
Flexibility:
Multi-fx pedals tend to have some fixed attributes. For example, the order that effects are applied is fixed. Sometimes certain effects are mutually exclusive (e.g. you can't have chorus and flanger at the same time). With separate pedals, you have complete flexibility to connect them in any order you like.
Control:
Individual pedals tend to have a switch or a knob for every setting. That makes the settings very available, visible and tactile. On a multi-fx unit, you'll find yourself using a selector knob to choose a setting, another knob to adjust it, and a digital display showing one (or sometimes a couple more) setting at a time. Changing settings on a multi-fx feels like adjusting a digital watch.
Tone: ... is completely subjective, so I will ignore it.
Noise: If you have five pedals, you have four analogue patch cords between them; that's four opportunities for noise to creep in. If some of those pedals are digital, it's also five opportunities for lag to creep in.
Don't forget that you can mix and match. There's nothing to stop you including a multi-fx unit in your chain of other pedals.
Also don't forget that effects are optional. I saw the great Wilco Johnson a couple of weeks ago. His guitar went straight into his amp, and he sounded incredible.
Comment: Wilco Johnson on the radio this week "Pedals? I'm a guitar player, not a cyclist!"
Answer: For ease of use, quick setup and immunity to a venue's foibles I use my Line 6 POD X3 Live almost everywhere, however for specific effects, especially in the studio, I add a whole range of other effects - some digital, some very old school.
When gigging around at festivals last summer I took a good look at kit - it does seem to vary wildly. Some folks use a couple of pedals on stage, and a rack processor backstage. Muse use everything and the kitchen sink.
YMMV
Updated = replaced that board with their new HD500 and it sounds much closer to 'real analogue' - so a couple of the extra pedals I used to carry about are now redundant!
Comment: You're like a POD X3 commercial mate :D. Nevertheless they are a really good unit.
Comment: I love them - you have no idea how much easier it makes touring when I just need one rucksack and a couple of guitars!
Comment: I hear you man :D. My board is so gigantic it's flight case has wheels on it (o.O).
Answer: There is a middle ground between the two - made available by the use of a loop switcher.  This effectively allows you to program combinations of individual effects pedals to turn on when you need them.  Take a look at the GigRig:
http://www.thegigrig.com/
This gives you more of an individual sound that buying a multi effects pedal off the shelf.  The upside of the multi effects pedal is that it's convenient and compact - but I don't believe that many pros use multi-effects pedals - maybe as a backup.
The other pro option is to purchased individual rackmount effects (like the Pod PRO, AxeFX etc...) and have a foot controller MIDI switcher to switch the patches or turn effects on/off.
Comment: "I don't believe that many pros use multi-effects pedals - maybe as a backup.". You might want to check out Peter Torn's comments on [TC-Electronic's site](http://www.tcelectronic.com/user_stories.asp?AjrDcmntId=9153)
Answer: Surprised no one mentioned Native Instruments Guitar Rig.  It would require a laptop as well, so I'm not sure if you want to deal with all that, but it makes editing & creating patches pretty easy (this is the main reason I switched from all-in-one pedalboards & rack effects - editing was a pain without the visual element).
You can switch presets with the Rig Kontrol, or control individual effects (you can map pretty much any control to any button on the Rig Kontrol).
I run it into my amp & only use the effects.  If you want to use the amp models as well through an amp, the docs say they sound best through a keyboard amp, but I haven't tried this.  Been using it since version 3 and love it.
Answer: I have both a Boss GT-6B and a Line 6 Floor Pod XT Live. The gt6 was a volume sucker(?). No matter what I did it cut the volume by a quarter to half sometimes. The amp modelling was average, and it was impossible to get a fully clean tone at playable levels (without DI-ing into a decent PA). By fully clean I mean without the model adding some dirt, not in bypass mode.
I got a old OC-2 (the Taiwanese one, I know right?) and the gt6 had an oc2 model on it. The stand alone pedal sounds better by a million miles, which I found strange and they're both made by boss... Plus it has the 2nd octave effect. Which is unusable on bass but by the by.
The line 6 is better by a long chalk, but has no dynamics to it. Every time I plug it into the amp it drains all the warmth of the valve in the pre and sounds thin an lifeless.
Also, you can't chain "stomp effects" on it, for example, you can't run an octave effect into a distortion effect, unless you use the octafuzz, which is piss poor. The choruses and phasers are good, the delays and reverbs are better.
The boss has been in a case and for sale now for 6+ months.
The line 6 rears it's ugly head now and again, but only for silent practice at home as not to wake the neighbours.
For me standalone pedals win hands down every time. With a good, transparent buffer you can use as much cable as you want without capacitance problems.
I will soon be using a buffer (depending on the next pedal) into a parallel/blender effects loop, with a programmable 8 loop true bypass series looper in the loop, with all my pedals into the series looper. If that makes sense. The point of the true bypass looper is to ensure there is only one (perfectly transparent) buffer in the chain while all effects are off.
Yes, very, very biased, but my honest opinion.
Comment: Line6's new board, the HD500 gets around your main gripes here - go test one. It still isn't a full set of analogue devices and a valve amp, but it is much closer :-)
Answer: I have both. I play at church with my Roland GT6 plugged into a DI box. At home, I have a bunch of pedals that go to a small amp. Because my effect pedal collection is limited, my palate is limited, but I have what I like. Except a delay. I need a delay.
If you plug in a series of effects and get no sound, you have several pedals and the patch cables between that might be the cause of your issues, plus however you power them all. With an all-in-one, there's the instrument cable, the cable to amplification, and the box itself. Much less involved.
But, if you have a pre-programmed box like the GT6, you can dream up a whole lot of sounds and get pretty close, but if you're in the middle of a song and say to yourself "Hey, I want the chorus right now", too bad. Some are more configurable than others for this, but the idea still arises. You can dream up a sound and store it, you can use it later, but changing it mid-song is harder.
So, both have their strengths.
Answer: I have a Zoom 707 pedal I've been using for about 13 years. It's a really good pedal and it also has a drum machine. The beats are nothing like the beats I have on my Boss Rhythm DR770 but they're ok to give a beat in the background for keeping rhythm and some extra sound.
I completely understand why some metal or classic rock style players don't like digital sound. I like prefer to play techno beats with acoustic and harmonica sometimes. I have certain digital effects I've tweaked that don't sound digital.
I have also have an Axe 1G and the Zoom blows it away. I do use the Axe sometimes just to play around with but my recording application (audio evolution) has onboard effects anyway.
I record instrumentals and sing and play harmonica over them like a one man band. I walk miles to play sometimes so having a drum machine effects unit and very limited looper in one works for me.
Answer: If you like the tone of your amp and guitar use single pedals. I found out that multi effect pedal boards degrade the tone. Also, creating your own tone and keeping it is much easier when you can customize individual pedal effects rather than going through a effects unit. You can lose all your settings in an effects unit if something goes wrong and it resets to factory settings.
The most important thing to me is the tone of guitar and amp...if you spent thousands for that why degrade it with the tonal characteristics of an effects unit? Some people may have the skill to adjust the units for their style but I like it simple especially in live settings.
Answer: I've had some big multi-fx pedals (like the Line6 m13), and every time I end up back toward using my gigantic pedal board made up of individual pedals.
The biggest reason is sonic flexibility. Ordering and re-ordering my pedals to get my "sound" is very important, along with being able to tweak settings on the fly without having to go through menus, etc.
And someone above mentioned dynamics. I've yet to play a multi-fx pedal that simply wasn't lifeless. The Line6 is a good example. The Line6 Echo Park pedal is awesome. The Line6 Echo Park effect in the m13 is "meh".
I'm not a snob when it comes to digital/analog, but I have through experience come to believe that individual pedals is more important to me than convenience.
Answer: Multi effect processor is great for fast cycling settings of the same pedals. For example slapback delay for rhythm and long delay for solo. For live it is not comfortable to crouch and change settings between songs (alternatively you can buy copies of same pedal). It is easy to plan effects and their settings that will be used on gig for every song
For experimental playing individual effects are better because adjusting presets stored in multi effect is quite uncomfortable. Sometimes digital copies have less options than original version or just don't sound as promised
My advice is to have both. Choose few effects you love to use them and have the rest in multi-effects box. Too many guitar-effects in signal chain will cause power,accessibility and sound quality problems that might be solved with other hardware. This is the expensive way
About cool people question. Many popular bands gave up real equipment to modelers because it is easier to gig with. Weather independent, easy to transport, less maintenance. Anyway they still use individual effects and amps in the studio
Answer: Interesting discussion. I'm likely going to go with a GT6B, at least for now. Second hand, they are really reasonable. I'm primarily playing bass now, so a touch of compression is usually all I might use, but with the availability of the additional effects, who knows?
I've played guitar for 35 years. Initially, I tried multi-effects in the late 1990s and found that they weren't quite there in my price range, so went back to individual boxes. The advantages and disadvantages that you all have listed for each type (multi-effects units vs. multiple effects).
However, I want to add that Victor Wooten is often seen playing using a GT6B, which surprised me.