问:
how would I compare the values to that of the user's, and then check if it is blacklisted
I am working on something to blacklist unwanted locations with the location service. Here is my current code:

How can I compare the values?

MAIN SCRIPT:

```<code>      if (navigator.geolocation) {
    // Locate position
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction

);
    } else {
        alert('Your device location is not approved.');
    }

    // Success callback function
    function displayPosition(pos) {
        var mylat = pos.coords.latitude;
        var mylong = pos.coords.longitude;
        var thediv = document.getElementById('locationinfo');
      alert('Your HWID is compliant of ProtoProt regulations.');
    }
      function errorFunction(pos) {
        alert('Error: (PROTOPROT_POS_DENIED). We only use your HWID for checking compliance. Enable location to enter.');
        }
</code>```

VALUES DICTIONARY:

```<code>blacklisted_areas = {
  'area 51' : [w, y], // Replace w y with the floats of long and lat
  'pink unicorn zoo' : [w, y], // same
  // etc.
};
</code>```

答:
You need to return an array containing both the latitude and longitude in your displayPosition function, and then compare this array against the keys in blacklisted_areas.

This can be done with the following (in ES6):

blacklisted_areas = {
  'area 51': [1, 2], // Replace w y with the floats of long and lat
  'pink unicorn zoo': [1, 2], // same
};

function displayPosition(pos) {
  var mylat = 1;
  var mylong = 2;
  return [mylat, mylong];
}

var blacklisted = false;

for (let x of Object.values(blacklisted_areas)) {
  if (displayPosition()[0] === x[0] && displayPosition()[1] === x[1]) {
    blacklisted = true;
  }
}

console.log(blacklisted);```

In the above code, the variable blacklisted will return true if the location is blacklisted, and false if the variable is not blacklisted. From here, you can adapt to suit.

Hope this helps! :)

Body:
I am working on something to blacklist unwanted locations with the location service. Here is my current code:

How can I compare the values?

MAIN SCRIPT:

      if (navigator.geolocation) {
    // Locate position
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction

);
    } else {
        alert('Your device location is not approved.');
    }

    // Success callback function
    function displayPosition(pos) {
        var mylat = pos.coords.latitude;
        var mylong = pos.coords.longitude;
        var thediv = document.getElementById('locationinfo');
      alert('Your HWID is compliant of ProtoProt regulations.');
    }
      function errorFunction(pos) {
        alert('Error: (PROTOPROT_POS_DENIED). We only use your HWID for checking compliance. Enable location to enter.');
        }

VALUES DICTIONARY:

blacklisted_areas = {
  'area 51' : [w, y], // Replace w y with the floats of long and lat
  'pink unicorn zoo' : [w, y], // same
  // etc.
};

Body:
You need to return an array containing both the latitude and longitude in your displayPosition function, and then compare this array against the keys in blacklisted_areas.

This can be done with the following (in ES6):

blacklisted_areas = {
  'area 51': [1, 2], // Replace w y with the floats of long and lat
  'pink unicorn zoo': [1, 2], // same
};

function displayPosition(pos) {
  var mylat = 1;
  var mylong = 2;
  return [mylat, mylong];
}

var blacklisted = false;

for (let x of Object.values(blacklisted_areas)) {
  if (displayPosition()[0] === x[0] && displayPosition()[1] === x[1]) {
    blacklisted = true;
  }
}

console.log(blacklisted);

In the above code, the variable blacklisted will return true if the location is blacklisted, and false if the variable is not blacklisted. From here, you can adapt to suit.

Hope this helps! :)


来源: stackexchange

问:
How to intercept server restart for GWT-based application?
I develop web-application which uses GWT for clients and JCR (Jackrabbit) for persistence.
Maven GWT plug-in (mvn gwt:run) launches some UI where communication between clients and server is tracked. This UI also provides an option to restart the server.

I'd like to intercept server restart event and perform some actions like repository.shutdown() before server actually goes to restart.

Is there a way to register handler and define an action for such server events?

答: You can implement ServletContextListener. The contextDestroyed() method will trigger when the context is about to be shut down.</p>

ContentLicense: CC BY-SA 2.5


问:
c++ Valgrind: Address 0x0 is not stack'd, malloc'd or (recently) free'd
I am learning a bit of programming and I am trying to code an Ant Colony algorithm for QAP, the problem is that sometimes I get segmentation fault and when I use valgrind it tells me "Address 0x0 is not stack'd, malloc'd or (recently) free'd". This is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>  //ifstream
#include <string>
#include <sstream>
#include <vector>
#include <utility> //pair
#include <iostream>
#include <algorithm> //shuffle
#include <random> //default_random_engine
#include <chrono> //chrono::system_clock
#include <cstdlib> // rand
#include <unistd.h>
#include <csignal>
using namespace std;

sig_atomic_t volatile done = 0;
void game_over(int) { done = 1; }

int funCosto(int dim,vector<int> sol,vector<int> dist, vector<int> flujo){
    int costo = 0;
    for (int i = 0; i<dim;i++){
        for (int j = i+1; j<dim;j++){
            // El costo es la * del valor de los flujos por la permutacion de las distancias
            costo += flujo[dim*i+j] * dist[dim*(sol[i]-1) + (sol[j]-1)];
        }
    }
    return costo*2; //La matriz es simétrica
}

int buscarLista(vector<int> lista, int elemento, int dim){
    int aux = 0;
    for (int i = 0; i < dim; i++){
        if (lista[i] == elemento){aux = 1;}
    }
    return aux;
}

vector<int> localSearch(int dim,vector<int> sol, vector<int> dist, vector<int> flujo){

    vector<int> solActual(dim), solAux(dim);
    solActual = sol;
    int mejorCosto = funCosto(dim,solActual,dist,flujo);
    int costoActual, mejorCostoAnterior;

    do{
        mejorCostoAnterior = mejorCosto; // para determinar que se llegó a un óptimo local
        for (int i = 0; i < dim; i++){
            for (int j = i+1; j < dim; j++){
                solAux = solActual;
                solAux[i] = solActual[j];
                solAux[j] = solActual[i]; //intercambiamos dos elementos
                /*Importante, hay que optimizar el cálculo del costo de los vecinos*/
                costoActual = funCosto(dim,solAux,dist,flujo);
                if (costoActual<mejorCosto){
                    break;
                }
            }
            if (costoActual < mejorCosto){
                mejorCosto = costoActual; //se actualiza el mejor costo
                solActual = solAux; //se efectua el movimiento
                break;
            }
        }
    } while (mejorCosto < mejorCostoAnterior); //se detiene cuando ya no hay mejoría

    return solActual;
}

pair<int,vector<int>> antColony(int numAnts, int dim, vector<int> dist, vector<int> flujo){

    done = 0;
    std::signal(SIGALRM, game_over);
    alarm(300);

    vector<vector<int>> hormigas(numAnts, vector<int>(dim));
    vector<vector<int>> hormigasNuevas(numAnts, vector<int>(dim));
    vector<vector<double>> feromonas(dim, vector<double>(dim));
    vector<int> mejorSol, mejorSolNueva;
    double mejorCosto, mejorCostoNuevo, totalFer, prob, auxProb, probAcum = 0 ;
    int numSwaps = dim/3;  // número de cambios que va a hacer cada hormiga en cada iteración
    random_device rd; // obtener un número aleatorio de hardware
    mt19937 eng(rd()); // semilla para el generador
    uniform_int_distribution<> disInt(0,dim-1);
    uniform_real_distribution<> disReal(0,1);
    int prim, seg, aux, contadorRep, sinMejoria = 0; //indices
    int inten = 1; //la intensificación está prendida al comienzo

    for (int i = 1; i <= dim; i++){
        hormigas[0][i-1] = i;
    }
    for (int j = 1; j < numAnts; j++){
        hormigas[j] = hormigas[0];
    }
    //obtener una semilla basada en el tiempo
    for (int k = 0; k < numAnts; k++){
        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
        shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
    }

    for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
        hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
    }

    mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
    mejorSol = hormigas[0];
    for (int i = 1; i < numAnts; i++){
        if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
            mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
            mejorSol = hormigas[i];
        }
    }
    for (int i = 0; i<dim; i++){
        for (int j = 0 ; j<dim; j++){
            feromonas[i][j] = 1.0/(100*mejorCosto);
        }
    }

    for (int z = 0; z < 1; z++){ //máximo número de iteraciones

        for (int i = 0; i < numAnts; i++ ){

            hormigasNuevas[i] = hormigas[i];

            for (int j = 0; j < numSwaps; j++){
                prim = disInt(eng);
                auxProb = disReal(eng);
                seg = -1;
                probAcum = 0;
                do{
                    seg++;
                    if (seg == prim){seg++;}
                    totalFer = 0; //limpiamos para esta iteración
                    for (int k = 0; k < dim; k++){
                        if (k != prim){
                            totalFer += feromonas[prim][hormigasNuevas[i][k]-1] + feromonas[k][hormigasNuevas[i][prim]-1];
                        }
                    }
                    //construimos la probabilidad con la que es aceptado el cambio segun las feromonas
                    prob = (feromonas[prim][hormigasNuevas[i][seg]-1]+feromonas[seg][hormigasNuevas[i][prim]-1]) / totalFer;
                    probAcum += prob;
                }while ((auxProb > probAcum) && (seg < dim));

                if (seg == dim){seg--;}

                aux = hormigasNuevas[i][prim];
                hormigasNuevas[i][prim] = hormigasNuevas[i][seg];
                hormigasNuevas[i][seg] = aux;

            }
            //mejoramos la solución modificada por la hormiga
            hormigasNuevas[i] = localSearch(dim,hormigasNuevas[i],dist,flujo);
        }

        //contadorRep = 0;
        //intensificación
        for (int a = 0; a < numAnts; a++){
            if (inten == 1){
                if (funCosto(dim,hormigasNuevas[a],dist,flujo) < funCosto(dim,hormigas[a],dist,flujo)){
                    hormigas[a] = hormigasNuevas[a];
                }
                else{ contadorRep++;} //para contar cuantas veces se queda con la respuesta anterior
            }
            else{
                hormigas[a] = hormigasNuevas[a];
            }
        }

        //if (contadorRep == numAnts){inten = 0;} //apaga la intensificación

        mejorCostoNuevo = funCosto(dim,hormigas[0],dist,flujo);
        for (int b = 1; b < numAnts; b++){
            if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){
                mejorCostoNuevo = funCosto(dim,hormigas[b],dist,flujo);
                mejorSolNueva = hormigas[b];
            }
        }

        if (mejorCostoNuevo < mejorCosto){
            //si se consigue una mejor solucíón
            mejorCosto = mejorCostoNuevo;
            mejorSol = mejorSolNueva;
            inten = 1;
            sinMejoria = 0;
        }

        //actualiación de la matriz de feromonas
        for (int c = 0; c < dim; c++){
            for (int d = 0; d < dim; d++){ //Evaporación
                feromonas[c][d] = 0.9*feromonas[c][d];
            }
        }

        for (int e = 0; e < dim; e++){//reforzamos la mejor solución
            feromonas[e][mejorSol[e]-1] = feromonas[e][mejorSol[e]-1] + 0.1/mejorCosto;
        }

        //diversificación
        if (sinMejoria > dim/2){

            hormigas[0] = mejorSol; //se queda la mejor solución hasta el momento
            //se vuelve a inicializar las hormigas
            for (int k = 1; k < numAnts; k++){
                unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
                shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
            }

            for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
                hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
            }

            mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
            mejorSol = hormigas[0];
            for (int i = 1; i < numAnts; i++){
                if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
                    mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
                    mejorSol = hormigas[i];
                }
            }

            //renovar la matriz de feromonas
            for (int i = 0; i<dim; i++){
                for (int j = 0 ; j<dim; j++){
                    feromonas[i][j] = 1.0/(100*mejorCosto);
                }
            }
        }
        sinMejoria++;
    }

    pair <int,vector<int>> pairSol = make_pair (mejorCosto,mejorSol);
    return pairSol;

}

int main (int argc, char* argv[]) {

    vector<int> resultados(10);
    for (int i = 0; i < 10; i++){

        clock_t startTime = clock();
        ifstream file(argv[1]);
        int dim;  //dimensiones de las matrices
        file >> dim;
        vector<int> suc(dim*dim); //matriz con los flujos entre las sucursales
        vector<int> loc(dim*dim); //matriz con las distancias de las localidades
        pair <int,vector<int>> pairSol; //tiene el costo de la busqueda y la permutación

        //guardar la matriz de distancia
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> suc[dim*i+j];
            }
        }

        //guardar la matriz de flujos
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> loc[dim*i+j];
            }
        }

        pairSol = antColony(10,dim,loc,suc);
        resultados[i] = pairSol.first;
        cout << pairSol.first << endl;

        for (int i = 0; i < dim; i++){
            cout << pairSol.second[i] << " ";
        }
        cout << endl;

        cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
    }

    int total = 0;
    for (int j = 0; j<10; j++){
        total += resultados[j];
    }

    cout << endl << "El promedio de de las soluciones es: " <<endl;
    cout << total/10 << endl;

    return 0;
}
</code>```

Valgrind gives me this:

Invalid read of size 4 at 0x804B331: main (antColony.cpp:269)
Address 0x0 is not stack'd, malloc'd or (recently) free'd

Process terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x0
at 0x804B331: main (antColony.cpp:269)

I am using this file:

```<code>20

 0 87 14  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
87  0  0 82 57  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
14  0  0  0  0 68  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0 82  0  0  0  0 19 18 38 47  0  0  0  0  0  0  0  0  0  0
 0 57  0  0  0  0  0  0  0  0 91  0  0  0  0  0  0  0  0  0
 0  0 68  0  0  0  0  0  0  0  0 77  0  0  0  0  0  0  0  0
 0  0  0 19  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0 18  0  0  0  0  0  0  0  0  6  0  0  0  0  0  0  0
 0  0  0 38  0  0  0  0  0  0  0  0  0 75  0  0  0  0  0  0
 0  0  0 47  0  0  0  0  0  0  0  0  0  0 73 52  0  0  0  0
 0  0  0  0 91  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0 77  0  0  0  0  0  0  0  0  0  0 51  0  0  0
 0  0  0  0  0  0  0  6  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0 75  0  0  0  0  0  0  0  0 93  0  0
 0  0  0  0  0  0  0  0  0 73  0  0  0  0  0  0  0  0 84  0
 0  0  0  0  0  0  0  0  0 52  0  0  0  0  0  0  0  0  0 40
 0  0  0  0  0  0  0  0  0  0  0 51  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0 93  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0 84  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 40  0  0  0  0

0 4 7 7 4 6 3 7 1 7 8 7 2 9 8 2 9 3 4 3
4 0 8 1 7 9 8 7 6 5 1 3 1 4 4 2 7 6 3 5
7 8 0 5 7 9 1 6 3 2 9 8 4 8 7 7 4 3 7 1
7 1 5 0 3 1 9 9 7 1 6 6 1 1 2 2 4 2 7 8
4 7 7 3 0 9 9 6 9 4 1 8 2 9 8 6 1 9 2 6
6 9 9 1 9 0 7 6 9 2 3 1 4 1 9 5 3 3 7 3
3 8 1 9 9 7 0 3 7 3 5 1 9 4 6 4 7 4 9 6
7 7 6 9 6 6 3 0 7 1 6 7 3 9 4 1 8 4 9 1
1 6 3 7 9 9 7 7 0 6 1 5 7 6 5 3 4 9 8 1
7 5 2 1 4 2 3 1 6 0 6 3 9 3 3 6 4 1 8 6
8 1 9 6 1 3 5 6 1 6 0 6 3 8 2 4 8 1 9 6
7 3 8 6 8 1 1 7 5 3 6 0 8 2 7 6 4 5 4 1
2 1 4 1 2 4 9 3 7 9 3 8 0 4 4 2 5 6 4 9
9 4 8 1 9 1 4 9 6 3 8 2 4 0 3 2 8 7 2 8
8 4 7 2 8 9 6 4 5 3 2 7 4 3 0 4 3 3 8 4
2 2 7 2 6 5 4 1 3 6 4 6 2 2 4 0 8 5 9 9
9 7 4 4 1 3 7 8 4 4 8 4 5 8 3 8 0 1 2 7
3 6 3 2 9 3 4 4 9 1 1 5 6 7 3 5 1 0 1 1
4 3 7 7 2 7 9 9 8 8 9 4 4 2 8 9 2 1 0 4
3 5 1 8 6 3 6 1 1 6 6 1 9 8 4 9 7 1 4 0
</code>```

The error comes from this lines near the end:

```<code>    for (int i = 0; i < dim; i++){
        cout << pairSol.second[i] << " ";
    }
</code>```

Where I am trying to print the solution vector.

I don't understand the problem with the memory this is generating. This is more confusing because sometimes it works perfectly. If someone could explain it to me I would be grateful.

Thanks in anticipation for your help!

答:
I have debugged your program a bit, and found that when the error happens, the pairSol.second is actually empty.

The only way I see this could happen is if mejorSolNueva is never assigned a value, but then assignment mejorSol = mejorSolNueva happens.

ContentLicense: CC BY-SA 3.0

Body:
I am learning a bit of programming and I am trying to code an Ant Colony algorithm for QAP, the problem is that sometimes I get segmentation fault and when I use valgrind it tells me "Address 0x0 is not stack'd, malloc'd or (recently) free'd". This is the code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>  //ifstream
#include <string>
#include <sstream>
#include <vector>
#include <utility> //pair
#include <iostream>
#include <algorithm> //shuffle
#include <random> //default_random_engine
#include <chrono> //chrono::system_clock
#include <cstdlib> // rand
#include <unistd.h>
#include <csignal>
using namespace std;

sig_atomic_t volatile done = 0;
void game_over(int) { done = 1; }

int funCosto(int dim,vector<int> sol,vector<int> dist, vector<int> flujo){
    int costo = 0;
    for (int i = 0; i<dim;i++){
        for (int j = i+1; j<dim;j++){
            // El costo es la * del valor de los flujos por la permutacion de las distancias
            costo += flujo[dim*i+j] * dist[dim*(sol[i]-1) + (sol[j]-1)];
        }
    }
    return costo*2; //La matriz es simétrica
}

int buscarLista(vector<int> lista, int elemento, int dim){
    int aux = 0;
    for (int i = 0; i < dim; i++){
        if (lista[i] == elemento){aux = 1;}
    }
    return aux;
}

vector<int> localSearch(int dim,vector<int> sol, vector<int> dist, vector<int> flujo){

    vector<int> solActual(dim), solAux(dim);
    solActual = sol;
    int mejorCosto = funCosto(dim,solActual,dist,flujo);
    int costoActual, mejorCostoAnterior;

    do{
        mejorCostoAnterior = mejorCosto; // para determinar que se llegó a un óptimo local
        for (int i = 0; i < dim; i++){
            for (int j = i+1; j < dim; j++){
                solAux = solActual;
                solAux[i] = solActual[j];
                solAux[j] = solActual[i]; //intercambiamos dos elementos
                /*Importante, hay que optimizar el cálculo del costo de los vecinos*/
                costoActual = funCosto(dim,solAux,dist,flujo);
                if (costoActual<mejorCosto){
                    break;
                }
            }
            if (costoActual < mejorCosto){
                mejorCosto = costoActual; //se actualiza el mejor costo
                solActual = solAux; //se efectua el movimiento
                break;
            }
        }
    } while (mejorCosto < mejorCostoAnterior); //se detiene cuando ya no hay mejoría

    return solActual;
}

pair<int,vector<int>> antColony(int numAnts, int dim, vector<int> dist, vector<int> flujo){

    done = 0;
    std::signal(SIGALRM, game_over);
    alarm(300);

    vector<vector<int>> hormigas(numAnts, vector<int>(dim));
    vector<vector<int>> hormigasNuevas(numAnts, vector<int>(dim));
    vector<vector<double>> feromonas(dim, vector<double>(dim));
    vector<int> mejorSol, mejorSolNueva;
    double mejorCosto, mejorCostoNuevo, totalFer, prob, auxProb, probAcum = 0 ;
    int numSwaps = dim/3;  // número de cambios que va a hacer cada hormiga en cada iteración
    random_device rd; // obtener un número aleatorio de hardware
    mt19937 eng(rd()); // semilla para el generador
    uniform_int_distribution<> disInt(0,dim-1);
    uniform_real_distribution<> disReal(0,1);
    int prim, seg, aux, contadorRep, sinMejoria = 0; //indices
    int inten = 1; //la intensificación está prendida al comienzo

    for (int i = 1; i <= dim; i++){
        hormigas[0][i-1] = i;
    }
    for (int j = 1; j < numAnts; j++){
        hormigas[j] = hormigas[0];
    }
    //obtener una semilla basada en el tiempo
    for (int k = 0; k < numAnts; k++){
        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
        shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
    }

    for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
        hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
    }

    mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
    mejorSol = hormigas[0];
    for (int i = 1; i < numAnts; i++){
        if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
            mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
            mejorSol = hormigas[i];
        }
    }
    for (int i = 0; i<dim; i++){
        for (int j = 0 ; j<dim; j++){
            feromonas[i][j] = 1.0/(100*mejorCosto);
        }
    }

    for (int z = 0; z < 1; z++){ //máximo número de iteraciones

        for (int i = 0; i < numAnts; i++ ){

            hormigasNuevas[i] = hormigas[i];

            for (int j = 0; j < numSwaps; j++){
                prim = disInt(eng);
                auxProb = disReal(eng);
                seg = -1;
                probAcum = 0;
                do{
                    seg++;
                    if (seg == prim){seg++;}
                    totalFer = 0; //limpiamos para esta iteración
                    for (int k = 0; k < dim; k++){
                        if (k != prim){
                            totalFer += feromonas[prim][hormigasNuevas[i][k]-1] + feromonas[k][hormigasNuevas[i][prim]-1];
                        }
                    }
                    //construimos la probabilidad con la que es aceptado el cambio segun las feromonas
                    prob = (feromonas[prim][hormigasNuevas[i][seg]-1]+feromonas[seg][hormigasNuevas[i][prim]-1]) / totalFer;
                    probAcum += prob;
                }while ((auxProb > probAcum) && (seg < dim));

                if (seg == dim){seg--;}

                aux = hormigasNuevas[i][prim];
                hormigasNuevas[i][prim] = hormigasNuevas[i][seg];
                hormigasNuevas[i][seg] = aux;

            }
            //mejoramos la solución modificada por la hormiga
            hormigasNuevas[i] = localSearch(dim,hormigasNuevas[i],dist,flujo);
        }

        //contadorRep = 0;
        //intensificación
        for (int a = 0; a < numAnts; a++){
            if (inten == 1){
                if (funCosto(dim,hormigasNuevas[a],dist,flujo) < funCosto(dim,hormigas[a],dist,flujo)){
                    hormigas[a] = hormigasNuevas[a];
                }
                else{ contadorRep++;} //para contar cuantas veces se queda con la respuesta anterior
            }
            else{
                hormigas[a] = hormigasNuevas[a];
            }
        }

        //if (contadorRep == numAnts){inten = 0;} //apaga la intensificación

        mejorCostoNuevo = funCosto(dim,hormigas[0],dist,flujo);
        for (int b = 1; b < numAnts; b++){
            if (funCosto(dim,hormigas[b],dist,flujo) < mejorCostoNuevo){
                mejorCostoNuevo = funCosto(dim,hormigas[b],dist,flujo);
                mejorSolNueva = hormigas[b];
            }
        }

        if (mejorCostoNuevo < mejorCosto){
            //si se consigue una mejor solucíón
            mejorCosto = mejorCostoNuevo;
            mejorSol = mejorSolNueva;
            inten = 1;
            sinMejoria = 0;
        }

        //actualiación de la matriz de feromonas
        for (int c = 0; c < dim; c++){
            for (int d = 0; d < dim; d++){ //Evaporación
                feromonas[c][d] = 0.9*feromonas[c][d];
            }
        }

        for (int e = 0; e < dim; e++){//reforzamos la mejor solución
            feromonas[e][mejorSol[e]-1] = feromonas[e][mejorSol[e]-1] + 0.1/mejorCosto;
        }

        //diversificación
        if (sinMejoria > dim/2){

            hormigas[0] = mejorSol; //se queda la mejor solución hasta el momento
            //se vuelve a inicializar las hormigas
            for (int k = 1; k < numAnts; k++){
                unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
                shuffle(hormigas[k].begin(),hormigas[k].end(), default_random_engine(seed));
            }

            for (int i = 0; i < numAnts; i++){ //aplica local Search para las soluciones aleatorias
                hormigas[i] = localSearch(dim,hormigas[i],dist,flujo);
            }

            mejorCosto = funCosto(dim,hormigas[0],dist,flujo);
            mejorSol = hormigas[0];
            for (int i = 1; i < numAnts; i++){
                if (funCosto(dim,hormigas[i],dist,flujo) < mejorCosto){
                    mejorCosto = funCosto(dim,hormigas[i],dist,flujo);
                    mejorSol = hormigas[i];
                }
            }

            //renovar la matriz de feromonas
            for (int i = 0; i<dim; i++){
                for (int j = 0 ; j<dim; j++){
                    feromonas[i][j] = 1.0/(100*mejorCosto);
                }
            }
        }
        sinMejoria++;
    }

    pair <int,vector<int>> pairSol = make_pair (mejorCosto,mejorSol);
    return pairSol;

}

int main (int argc, char* argv[]) {

    vector<int> resultados(10);
    for (int i = 0; i < 10; i++){

        clock_t startTime = clock();
        ifstream file(argv[1]);
        int dim;  //dimensiones de las matrices
        file >> dim;
        vector<int> suc(dim*dim); //matriz con los flujos entre las sucursales
        vector<int> loc(dim*dim); //matriz con las distancias de las localidades
        pair <int,vector<int>> pairSol; //tiene el costo de la busqueda y la permutación

        //guardar la matriz de distancia
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> suc[dim*i+j];
            }
        }

        //guardar la matriz de flujos
        for (int i = 0; i < dim; i++){
            for (int j = 0; j < dim; j++) {
                file >> loc[dim*i+j];
            }
        }

        pairSol = antColony(10,dim,loc,suc);
        resultados[i] = pairSol.first;
        cout << pairSol.first << endl;

        for (int i = 0; i < dim; i++){
            cout << pairSol.second[i] << " ";
        }
        cout << endl;

        cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
    }

    int total = 0;
    for (int j = 0; j<10; j++){
        total += resultados[j];
    }

    cout << endl << "El promedio de de las soluciones es: " <<endl;
    cout << total/10 << endl;

    return 0;
}

Valgrind gives me this:

Invalid read of size 4 at 0x804B331: main (antColony.cpp:269)
Address 0x0 is not stack'd, malloc'd or (recently) free'd

Process terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x0
at 0x804B331: main (antColony.cpp:269)

I am using this file:

20

 0 87 14  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
87  0  0 82 57  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
14  0  0  0  0 68  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0 82  0  0  0  0 19 18 38 47  0  0  0  0  0  0  0  0  0  0
 0 57  0  0  0  0  0  0  0  0 91  0  0  0  0  0  0  0  0  0
 0  0 68  0  0  0  0  0  0  0  0 77  0  0  0  0  0  0  0  0
 0  0  0 19  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0 18  0  0  0  0  0  0  0  0  6  0  0  0  0  0  0  0
 0  0  0 38  0  0  0  0  0  0  0  0  0 75  0  0  0  0  0  0
 0  0  0 47  0  0  0  0  0  0  0  0  0  0 73 52  0  0  0  0
 0  0  0  0 91  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0 77  0  0  0  0  0  0  0  0  0  0 51  0  0  0
 0  0  0  0  0  0  0  6  0  0  0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0 75  0  0  0  0  0  0  0  0 93  0  0
 0  0  0  0  0  0  0  0  0 73  0  0  0  0  0  0  0  0 84  0
 0  0  0  0  0  0  0  0  0 52  0  0  0  0  0  0  0  0  0 40
 0  0  0  0  0  0  0  0  0  0  0 51  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0 93  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0 84  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 40  0  0  0  0

0 4 7 7 4 6 3 7 1 7 8 7 2 9 8 2 9 3 4 3
4 0 8 1 7 9 8 7 6 5 1 3 1 4 4 2 7 6 3 5
7 8 0 5 7 9 1 6 3 2 9 8 4 8 7 7 4 3 7 1
7 1 5 0 3 1 9 9 7 1 6 6 1 1 2 2 4 2 7 8
4 7 7 3 0 9 9 6 9 4 1 8 2 9 8 6 1 9 2 6
6 9 9 1 9 0 7 6 9 2 3 1 4 1 9 5 3 3 7 3
3 8 1 9 9 7 0 3 7 3 5 1 9 4 6 4 7 4 9 6
7 7 6 9 6 6 3 0 7 1 6 7 3 9 4 1 8 4 9 1
1 6 3 7 9 9 7 7 0 6 1 5 7 6 5 3 4 9 8 1
7 5 2 1 4 2 3 1 6 0 6 3 9 3 3 6 4 1 8 6
8 1 9 6 1 3 5 6 1 6 0 6 3 8 2 4 8 1 9 6
7 3 8 6 8 1 1 7 5 3 6 0 8 2 7 6 4 5 4 1
2 1 4 1 2 4 9 3 7 9 3 8 0 4 4 2 5 6 4 9
9 4 8 1 9 1 4 9 6 3 8 2 4 0 3 2 8 7 2 8
8 4 7 2 8 9 6 4 5 3 2 7 4 3 0 4 3 3 8 4
2 2 7 2 6 5 4 1 3 6 4 6 2 2 4 0 8 5 9 9
9 7 4 4 1 3 7 8 4 4 8 4 5 8 3 8 0 1 2 7
3 6 3 2 9 3 4 4 9 1 1 5 6 7 3 5 1 0 1 1
4 3 7 7 2 7 9 9 8 8 9 4 4 2 8 9 2 1 0 4
3 5 1 8 6 3 6 1 1 6 6 1 9 8 4 9 7 1 4 0

The error comes from this lines near the end:

    for (int i = 0; i < dim; i++){
        cout << pairSol.second[i] << " ";
    }

Where I am trying to print the solution vector.

I don't understand the problem with the memory this is generating. This is more confusing because sometimes it works perfectly. If someone could explain it to me I would be grateful.

Thanks in anticipation for your help!


问:
Python: How can I extract common setup code into a single file?
I have a few Python scripts that use the same configs and variable initialization. How would I extract this common code out into a single file to be included everywhere? What is the best practice? </p>

答:
What I like to do is:

1 - Store all the config settings within a text file (such as a config.json)

2 - Create a class Config which loads the json file(s) and provides useful methods to load and read the configs, perform some concatenations, or simply returns it as a dict

4 - I ensure I do not load the config(s) multiple times (goal: single disk read and config caching) by using a module Globals (which is just an empty Global.py file) in which I store the dict and controls if it exists before deciding to load the config.

3 - import Config, do a config = Config() and I am good to go


问:
How can i force to fire an error with selenium webdriverIO
How can I force to fire an error using chromedriver with selenium webdriverIO? i don't know if there some script like browser.fire('error')?</p>

答:
```<code>throw new Error('Error occurred');
</code>```

This will throw an exception for the window and if not handled I believe you will get what you need.

Body:
throw new Error('Error occurred');

This will throw an exception for the window and if not handled I believe you will get what you need.


问:
pass JSON dictionary and a char with argparse
I'm trying to pass two arguments to python, one read-only JSON file and one char together. In fact I want the arguments both positional, but I couldn't do it either, so let the char one optional. At the end I will read the dictionary and the char will be my key.

When I try like below, the second argument is passed as None. I can't understand why it's empty. Do you have any idea?

Thanks a lot!

python3 myProg.py dict.json -a

```<code>import json
import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description = 'program')
    parser.add_argument('json', nargs = 1, type = argparse.FileType('r'))
    parser.add_argument('-args', nargs ="?")

    arguments = parser.parse_args()
    dictionary = json.load(arguments.json[0])
    arg_start = arguments.args
</code>```

Recieving this error:

Namespace(args=None, json=[<_io.TextIOWrapper name='dict.json' mode='r' encoding='UTF-8'>])

答:
It looks like you got the json file ok.  If you'd omitted the nargs=1 you could have used:

```<code>dictionary = json.load(arguments.json)
</code>```

-args is an nargs='?'.  That means it it is ok to omit an argument.  If not used at all its value will be the Actions default (currently None).

If provided as just -a, the value is the Action's const (also None).

If provided as -a foo, it will set that string.

If you'd define that argument as positional, plain 'args' (without the -) then it would have accepted the next string after the json file name.

Body:
I'm trying to pass two arguments to python, one read-only JSON file and one char together. In fact I want the arguments both positional, but I couldn't do it either, so let the char one optional. At the end I will read the dictionary and the char will be my key.

When I try like below, the second argument is passed as None. I can't understand why it's empty. Do you have any idea?

Thanks a lot!

python3 myProg.py dict.json -a

import json
import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description = 'program')
    parser.add_argument('json', nargs = 1, type = argparse.FileType('r'))
    parser.add_argument('-args', nargs ="?")

    arguments = parser.parse_args()
    dictionary = json.load(arguments.json[0])
    arg_start = arguments.args

Recieving this error:

Namespace(args=None, json=[<_io.TextIOWrapper name='dict.json' mode='r' encoding='UTF-8'>])

Body:
It looks like you got the json file ok.  If you'd omitted the nargs=1 you could have used:

dictionary = json.load(arguments.json)

-args is an nargs='?'.  That means it it is ok to omit an argument.  If not used at all its value will be the Actions default (currently None).

If provided as just -a, the value is the Action's const (also None).

If provided as -a foo, it will set that string.

If you'd define that argument as positional, plain 'args' (without the -) then it would have accepted the next string after the json file name.


问:
Why don't my Rails server render times add up?
I'm having some trouble with my Rails app being very slow on my staging server. What is most confusing is that the final line of the log output for each request.

It seems the View and Database times aren't even close to the entire render time. On one page it is as bad as ~1000ms for Completion, ~450ms for the View and ~20ms Database.

Where does the rest of the time required to render the page come from?

答:
What does your apache log say? It will definitely have different numbers to show the time required to serve the request.

Apache sends requests to rails and rails works on it and that is what you see in your production logs.

All the HTML still has to be rendered on your browser (heavy CSS, images, js etc). Try using firefox extension httpwatch to know rendering time of UI elements and it should add up.

As suggested earlier, NewRelic should give you decent breakup of time spent in various activities (M V C)

OwnerDisplayName: Ben


问:
How to use a list of variable in the operation in a loop (or lapply)?
I would like to run a series of analysis using different variables from a list. These variables are in the same dataset.

sample data frame is as below

```<code>df <- data.frame(x1=runif(10),
             x2=runif(10),
             x3=runif(10),
             x4=runif(10),
             y=runif(10))

# I would like to use variables from this list
xlist <- c("x1","x2","x3")

summary<-NA
</code>```

my thought is to use for loop or lapply, but it seems that both methods have the same problem when calling the variable from the list.
The problem is that I use "var" in the loop to represent x1,x2,or x3, but functions like "lm" require an argument of "data", and the function will recognize var as the variable to call, instead of x1,x2,or x3.

Any idea how can I avoid this?

```<code># using for loop
for (var in xlist) {
  model <- lm(y~var,data=df)
  temp <- data.frame(coef=model$coefficients[2])
  summary<- rbind(summary,temp)
}

# using lapply
func <- function(var){
  model <- lm(y~var,data=df)
  temp <- data.frame(coef=model$coefficients[2])
}

result <- lapply(xlist, func)
</code>```

答:
Perhaps you need the formula function...

```<code>for (var in xlist) {
  form <- formula(paste0("y~",var))
  model <- lm(form,data=df)
  temp <- data.frame(coef=model$coefficients[2])
  summary<- rbind(summary,temp)
}

summary
         coef
x1  0.3626764
x2 -0.3194918
x3  0.1216511
</code>```

It should work in exactly the same way with lapply (or you might prefer sapply).

Body:
I would like to run a series of analysis using different variables from a list. These variables are in the same dataset.

sample data frame is as below

df <- data.frame(x1=runif(10),
             x2=runif(10),
             x3=runif(10),
             x4=runif(10),
             y=runif(10))

# I would like to use variables from this list
xlist <- c("x1","x2","x3")

summary<-NA

my thought is to use for loop or lapply, but it seems that both methods have the same problem when calling the variable from the list.
The problem is that I use "var" in the loop to represent x1,x2,or x3, but functions like "lm" require an argument of "data", and the function will recognize var as the variable to call, instead of x1,x2,or x3.

Any idea how can I avoid this?

# using for loop
for (var in xlist) {
  model <- lm(y~var,data=df)
  temp <- data.frame(coef=model$coefficients[2])
  summary<- rbind(summary,temp)
}

# using lapply
func <- function(var){
  model <- lm(y~var,data=df)
  temp <- data.frame(coef=model$coefficients[2])
}

result <- lapply(xlist, func)

Body:
Perhaps you need the formula function...

for (var in xlist) {
  form <- formula(paste0("y~",var))
  model <- lm(form,data=df)
  temp <- data.frame(coef=model$coefficients[2])
  summary<- rbind(summary,temp)
}

summary
         coef
x1  0.3626764
x2 -0.3194918
x3  0.1216511

It should work in exactly the same way with lapply (or you might prefer sapply).


问:
Calling a Python script from C# - changing the script's filepath causes the program to not work
The following code works perfectly without flaw:

```<code>    public partial class MainForm : Form
    {
        string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + @"\config\pathToPythonInterpreter.txt");
        string pyWeather = @"C:\getWeather.py";
        public MainForm()
        {
            InitializeComponent();
            UpdateWeather();
        }

        public void UpdateWeather()
        {
            labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
        }
    }
</code>```

However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:

```<code>string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py";
</code>```

Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.

The Python script is the following:

```<code>from requests import get
from bs4 import BeautifulSoup as soup

r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))
</code>```

(It webscrapes my local weather)

PySharp.ExecutePy() can be viewed here

By far the strangest bug I've ever encountered. Any ideas?

EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.

EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:

```<code>C:\foo bar\testing\pyWeather.py
</code>```

does not work!

答:
Try surrounding the path that contains spaces with 2 double quotes.

For e.g.

string pyWeather = @"""C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py""";

Similarly, you can do string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py"; followed by pyWeather = "\"" + pyWeather + "\"";.

Body:
The following code works perfectly without flaw:

    public partial class MainForm : Form
    {
        string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + @"\config\pathToPythonInterpreter.txt");
        string pyWeather = @"C:\getWeather.py";
        public MainForm()
        {
            InitializeComponent();
            UpdateWeather();
        }

        public void UpdateWeather()
        {
            labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
        }
    }

However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:

string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py";

Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.

The Python script is the following:

from requests import get
from bs4 import BeautifulSoup as soup

r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))

(It webscrapes my local weather)

PySharp.ExecutePy() can be viewed here

By far the strangest bug I've ever encountered. Any ideas?

EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.

EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:

C:\foo bar\testing\pyWeather.py

does not work!


问:
JFileChooser in LibGDX
I'm trying to use Javas JFileChooser in my LibGDX scene2d project, but as soon as I launch JFileChooser my program freezes.

Here is the code I use to launch file chooser:

```<code>private String getPath(){
    String path = "";
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            try {
                path = file.getAbsolutePath();
            } catch (Exception ex) {
                System.out.println("problem accessing file" + file.getAbsolutePath() + "\n" + ex.getMessage());
            }
        } else {
            System.out.println("File access cancelled by user.");
        }
        return path;
    }
</code>```

is it swing and libgdx compability problem or is there something I am missing? Same code works perfectly with nativa java projects.
Except instead of: fc.showOpenDialog(null);
I use: fc.showOpenDialog(button); // button is the JButton that triggers the event.

any idea what am I doing wrong?

EDIT: I don't really mind if it wont work on other platforms than Windows.

BUT if I choose to go with cross platform solution, and use LibGDX's method, do I have to create file chooser class with UI from scratch all by myself?

答:
Coming late to the party but if the point of the question is to invoke a "native" ie. non-gdx file chooser from a libgdx project I made a library to do so here: https://github.com/spookygames/gdx-nativefilechooser.

Example from the readme:

```<code>// Configure
NativeFileChooserConfiguration conf = new NativeFileChooserConfiguration();

// Starting from user's dir
conf.directory = Gdx.files.absolute(System.getProperty("user.home"));

// Filter out all files which do not have the .ogg extension and are not of an audio MIME type - belt and braces
conf.mimeFilter = "audio/*";
conf.nameFilter = new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith("ogg");
    }
};

// Add a nice title
conf.title = "Choose audio file";

fileChooser.chooseFile(conf, new NativeFileChooserCallback() {
    @Override
    public void onFileChosen(FileHandle file) {
        // Do stuff with file, yay!
    }

    @Override
    public void onCancellation() {
        // Warn user how rude it can be to cancel developer's effort
    }

    @Override
    public void onError(Exception exception) {
        // Handle error (hint: use exception type)
    }
});
</code>```

On the desktop, this example will currently launch an AWT FileDialog (not exactly what is asked) yet a Swing version is currently on the master branch and should be incorporated to the next version of the lib.

Title: JFileChooser in LibGDX

Body:
I'm trying to use Javas JFileChooser in my LibGDX scene2d project, but as soon as I launch JFileChooser my program freezes.

Here is the code I use to launch file chooser:

private String getPath(){
    String path = "";
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            try {
                path = file.getAbsolutePath();
            } catch (Exception ex) {
                System.out.println("problem accessing file" + file.getAbsolutePath() + "\n" + ex.getMessage());
            }
        } else {
            System.out.println("File access cancelled by user.");
        }
        return path;
    }

is it swing and libgdx compability problem or is there something I am missing? Same code works perfectly with nativa java projects.
Except instead of: fc.showOpenDialog(null);
I use: fc.showOpenDialog(button); // button is the JButton that triggers the event.

any idea what am I doing wrong?

EDIT: I don't really mind if it wont work on other platforms than Windows.

BUT if I choose to go with cross platform solution, and use LibGDX's method, do I have to create file chooser class with UI from scratch all by myself?

Body:
Coming late to the party but if the point of the question is to invoke a "native" ie. non-gdx file chooser from a libgdx project I made a library to do so here: https://github.com/spookygames/gdx-nativefilechooser.

Example from the readme:

// Configure
NativeFileChooserConfiguration conf = new NativeFileChooserConfiguration();

// Starting from user's dir
conf.directory = Gdx.files.absolute(System.getProperty("user.home"));

// Filter out all files which do not have the .ogg extension and are not of an audio MIME type - belt and braces
conf.mimeFilter = "audio/*";
conf.nameFilter = new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith("ogg");
    }
};

// Add a nice title
conf.title = "Choose audio file";

fileChooser.chooseFile(conf, new NativeFileChooserCallback() {
    @Override
    public void onFileChosen(FileHandle file) {
        // Do stuff with file, yay!
    }

    @Override
    public void onCancellation() {
        // Warn user how rude it can be to cancel developer's effort
    }

    @Override
    public void onError(Exception exception) {
        // Handle error (hint: use exception type)
    }
});

On the desktop, this example will currently launch an AWT FileDialog (not exactly what is asked) yet a Swing version is currently on the master branch and should be incorporated to the next version of the lib.


问:
How much performance do you get out a Heroku dynos/workers?
How much traffic can a site with 1 or 2 Dynos handle on www.Heroku.com and would increasing workers improve this? Any help on dynos/workers would be appreciated. </p>

答:
This blog entry may be of use.  He does a great breakdown of the kind of bottlenecks heroku can run into, and how increasing dynos can help, and provides links and information to the official performance guide on heroku as well as some tools that will help you test your own app.

Worker performance really depends on how your site is built and what you are using them for.  Background processing (image formatting, account pruning, etc) called Delayed Jobs is how you put them to work

EDIT // 1 March 2012:
Here is another blog entry that explored heroku latency and throughput performance for a variable number Dynos.

EDIT // 28 Feb 2013:
There have been some concerns raised in this post regarding Heroku's random routing algorithm and how metrics may be misreported when scaling Dynos, specifically those provided by New Relic.  This is still an ongoing issue and is something to note in the context of my previous answer.  Heroku's responses are linked within the post.

EDIT // 8 May 2013:
A recent post on Shelly Cloud blog analyses impact of number of dynos and web server used on application perfomance. Baseline performance script used there should be useful in performing further tests.


问:
What are frames in an Image Stream?
I am reading over the documentation for SurfaceTexture. Specifically, it states:

SurfaceTexture captures frames from an image stream as an OpenGL ES texture. The
  image stream may come from either camera preview or video decode. A
  Surface created from a SurfaceTexture can be used as an output
  destination for the android.hardware.camera2 API

But there is no explanation as to what a frame is. My understanding of streams are the I/O streams where you have a sequences of bytes that you can read from (InputStream) or write to (OutputStream). Are frames a synonym for bytes or are they a distinct feature of I/O streams?

答: No. Frames are the still images that compose the video. One picture is one frame. A video (in the US) is usually 30 frames per second. Other countries use other standards (for example, PAL is 25 frames per second). At least in modern times, pre-HD it was "fields" (not "frames") and two "fields" made one "frame".</p>

Title: What are frames in an Image Stream?


问:
HIVE : External Table - how do you clean-up the files in loaded in the user/hive/warehouse/db/table directory
According to the documentation, when we create an EXTERNAL table in HIVE, and then DROP the table, the metadata is updated and the data that was loaded in the HDFS directory /user/hive/warehouse//> still exists?

I have two questions :
1. How do you do clean-up of the files in the /user/hive/warehouse//>?
2. When I tried to create the table again and the files are the same name but the data is different,  HIVE warehoouse files did not get updated
Should it be?? (I asked this since I am not sure if this is a set-up issue or an expected behavior)

答:
Hive doesn't store (manage) any data files for EXTERNAL tables in the warehouse directory. It only stores the metadata for these tables in the Metastore.

This is the main difference between Hive internal (managed) and external tables. Internal table owns the data, external table only knows about it.

More detailed explanation here.


答:
If you don't mind making a new list, you can try something with just a list comprehension like</p>

```<code>filtered_list = [i for i in list if i.isdigit() and 10000000 < int(i) < 99999999]
</code>```

Title: Extract 8-digit numbers from a list of strings

Body:
I have a list of strings which may contain letters, symbols, digits, etc, as below:

list = ['\n', '', '0', '38059', '', '', '?_', '71229366', '', '1', '38059', '', '', '?_', '87640804', '', '2', '38059', '', '', '?_', '71758011', '', '', ':?', ';__', '71229366287640804271758011287169822']

How do I filter out all other strings, except numbers less than 10000000 and greater than 99999999?

Expected Output:

list = ['71229366', '87640804', '71758011']

Body:
If you don't mind making a new list, you can try something with just a list comprehension like

filtered_list = [i for i in list if i.isdigit() and 10000000 < int(i) < 99999999]


问:
Is there a way to merge these two tables?
I have two tables :

```<code>question_likes:

question_id references question(id)
user_id references users(id)
primary key (user_id, question_id)

answer_likes:

answer_id references answers(id)
user_id references users(id)
primary key (user_id, answer_id)
</code>```

A colleague suggested that I can use inheritance in Postgres to merge these into one table.

Is there a way to design this requirement?

答:
Something like this should do:

```<code>CREATE TABLE likes (
    like_id            serial PRIMARY KEY,
    user_id int
);

CREATE TABLE question_likes (
    question_id int,
    primary key (user_id, question_id)
) INHERITS (likes);

CREATE TABLE answer_likes (
    answer_id int,
    primary key (user_id, answer_id)
) INHERITS (likes);
</code>```

Than merging can be done using UNION

```<code>SELECT like_id, user_id, question_id, null as answer_id FROM question_likes q
UNION
SELECT like_id, user_id, null as question_id, answer_id FROM answer_likes a;
</code>```

What exactly do you want to achieve?

Body:
I have two tables :

question_likes:

question_id references question(id)
user_id references users(id)
primary key (user_id, question_id)

answer_likes:

answer_id references answers(id)
user_id references users(id)
primary key (user_id, answer_id)

A colleague suggested that I can use inheritance in Postgres to merge these into one table.

Is there a way to design this requirement?

Body:
Something like this should do:

CREATE TABLE likes (
    like_id            serial PRIMARY KEY,
    user_id int
);

CREATE TABLE question_likes (
    question_id int,
    primary key (user_id, question_id)
) INHERITS (likes);

CREATE TABLE answer_likes (
    answer_id int,
    primary key (user_id, answer_id)
) INHERITS (likes);

Than merging can be done using UNION

SELECT like_id, user_id, question_id, null as answer_id FROM question_likes q
UNION
SELECT like_id, user_id, null as question_id, answer_id FROM answer_likes a;

What exactly do you want to achieve?


Body:
You can use a map and filter.

your_list = ['\n', '', '0', '38059', '', '', '?_', '71229366', '', '1', '38059',
             '', '', '?_', '87640804', '', '2', '38059', '', '', '?_', '71758011',
             '', '', ':?', ';__', '71229366287640804271758011287169822']

new_list = list(map(int, filter(lambda x: x.isdigit() and 10000000 < int(x) < 99999999, your_list)))
print(new_list)

list() optional on python2.

Output:

[71229366, 87640804, 71758011]

If you don't want the conversion to integer, drop the map:

>>> list(filter(lambda x: x.isdigit() and 10000000 < int(x) < 99999999, your_list))
['71229366', '87640804', '71758011']


问:
Iterable without element at index in Guava
If I have a FluentIterable, how do I get a new FluentIterable without the element at index i?

答:
There's nothing built in for this, and no particularly great implementation either.

I'd honestly recommend using a mutable list and calling remove(int index).  Fluent view chains really don't seem likely to be effective for this sort of use case.


答:
Here's a way to do it without mutable lists:

```<code>FluentIterable.concat(myIterable.limit(i), myIterable.skip(i + 1));
</code>```

And here's a slightly more performant way:

```<code>ImmutableList<String> list = ImmutableList.copyOf(myIterable);
FluentIterable.concat(
    list.subList(0, i - 1),
    list.subList(i + 1, list.size() - 1));
</code>```

Note that #subList is backed by the original ImmutableList, so we only iterate through myIterable once here.

Title: Iterable without element at index in Guava

Body: If I have a FluentIterable, how do I get a new FluentIterable without the element at index i?

Body:
Here's a way to do it without mutable lists:

FluentIterable.concat(myIterable.limit(i), myIterable.skip(i + 1));

And here's a slightly more performant way:

ImmutableList<String> list = ImmutableList.copyOf(myIterable);
FluentIterable.concat(
    list.subList(0, i - 1),
    list.subList(i + 1, list.size() - 1));

Note that #subList is backed by the original ImmutableList, so we only iterate through myIterable once here.


问:
Is it worth pooling byte[] and char[] arrays or is it better to just create
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

```<code>take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}
</code>```

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.

答:
Object pools add complexity to an application.  In general, you have to deal with:

implementing the acquire / release operations in a thread-safe fashion,

ensuring that objects are always released, and are never retained / used after release,

making sure that released objects are "cleaned" before the next acquire, and

growing and shrinking the pool size.

If you make a mistake in the pool implementation, you can introduce insidious bugs.

Is it worth it?  Well, the answer depends on the circumstances:

If memory is severely constrained, GC pauses are a major issue, and/or the cost of allocating and initializing an object is large, then probably yes.

If the cost of "cleaning" and object is roughly the same as the amortized cost of allocating a new one, then it is doubtful.

To understand the last point, you need to understand some basic copying GC ergonomics.  Specifically if you:

assume a constant sized working set of reachable objects,

ignore object finalization and soft/weak/phantom references, and

increase the total heap size towards infinity,

then the amortized GC cost of allocating and reclaiming memory for object in Java approaches the cost of zeroing memory.

Thus, if the cost of cleaning an object is roughly equivalent to the GC overhead (zeroing) + the object constructor cost, then the only thing you gain by pooling is reducing the number of times the GC marking / copying occurs.  But you can do the same thing by simply giving the application a larger heap.

Body:
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.


问:
What is the correct way of setting up Tensorflow on Linux, after all?
I'm having some misinformation problem regarding Tensorflow. Lot's of info on lot's of places, and never complete enough.

I got my system set up with CUDA 8.0, cuDNN and I have Keras + Theano working ok with python 2.7. I'm trying to move to Tensorflow.

As I had compatibility problems with numpy and other stuff when I tried to install it in the same environment, I installed miniconda2, created a virtual env for it conda create -n tensorflow pip and activated it, as instructed here: https://www.tensorflow.org/install/install_linux#InstallingAnaconda

The environment seems operational.

Afterwards, I installed tensorflow from https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.2.1-cp27-none-linux_x86_64.whl and also Keras, only to noticed I had some modules duplicated on conda list, some marked with a version string, others marked with <pip> only. Specially, I got one Tensorflow-gpu 1.2.1 and Tensorflow 1.1.0. Both of them. The old version just comes by with Keras.

Also, there's a myriad of warnings about Tensorflow not being compiled to use certain CPU instruction sets, and there's this answer How to compile Tensorflow with SSE4.2 and AVX instructions? about compiling it with using basel, but I don't really find any information about where to put the source code and what files to move to where after running that bazel command line.

To make matters worse, whenever I run a simple 20x20 matrix multiplication code with "/gpu:0" as device, the code list that horrendous warnings, correctly detects the presence of a GTX 1070, but never really confirms it was used to to the calculations. And it runs faster on "/cpu:0". How I miss Theano...

Could someone point me out where can I find:

what version to download of Tensorflow that is current (not necessarily latest)?

concise steps to get it done and how to test if those steps went right?

I'm using Linux Mint 18.

答:
I have used conda and have installed Tensorflow=1.1.0, but it never seemed to have worked correctly within python. I also came across in github issues that anconda are currently working on the Tensorflow GPU version and so no matter what I tried in Anaconda, it never used my Tesla NVIDIA P100-SXM2-16GB card and it used only the CPU.

I suggest you use the normal environment till they get Tensorflow-gpu to work right in Anaconda.

To check if the tensorflow-gpu works I used the Inception v3 model with TF0.12 / TF1.0.

This is the process that I go through to install tensorflow1.0:

Step 0.

```<code>sudo -i
apt-get install aptitude
aptitude install software-properties-common
apt-get install libcupti-dev pip
apt-get update
apt-get upgrade libc6
</code>```

Step 1. Install Nvidia Components. I think you already have that installed

Download the NVIDIA cuDNN 5.1 for CUDA 8.0 from
https://developer.nvidia.com/rdp/cudnn-download
(Registration in NVIDIA's Accelerated Computing Developer Program is required)

Cudnn 5.1 works well with most of the architectures and OS out there

Step 2. Install bazel and tensorflow

```<code>apt-get install bazel
</code>```

you can go to this link https://pypi.python.org/pypi/tensorflow-gpu/1.1.0rc0 and do a

```<code>pip install <python-wheel-version>
</code>```

If you have python2.7 and python 3.* installed, then use pip2 to install for python2.7

Step 3. Install openjdk

```<code>apt-get install openjdk-8-jdk
</code>```

Step 4. git clone the Inception model code

```<code>git clone https://github.com/tensorflow/models.git
cd models
git checkout master
cd inception
</code>```

This is where bazel comes in the picture. See Bazel's Getting Started docs for a more detailed explanation of what a target is. So, if you do a

```<code>ls -lstr
</code>```

you might see 5 bazel related symbolic links

```<code>bazel-bin  bazel-genfiles  bazel-inception  bazel-out  bazel-testlogs
</code>```

these are the target directory to which you build your specific model

Assuming you're in the models/inception directory

```<code>bazel build inception/imagenet_train
</code>```

This activates the symbolic link

NOTE: For this imagenet_train.py to work you need to prepare the imagenet dataset. You either skip this part or go through this:

STEP 5. Prepare the Imagenet dataset
Before you run the training script for the first time, you will need to download and convert the ImageNet data to native TFRecord format.
To begin, you will need to sign up for an account with ImageNet to gain access to the data. Look for the sign-up page, create an account and request an access key to download the data.

After you have USERNAME and PASSWORD, you are ready to run our script. Make sure that your hard disk has at least 500 GB of free space for downloading and storing the data. Here we select DATA_DIR=$HOME/imagenet-data as such a location but feel free to edit accordingly.

When you run the below script, please enter USERNAME and PASSWORD when prompted. This will occur at the very beginning. Once these values are entered, you will not need to interact with the script again.

```<code>#location of where to place the ImageNet data
DATA_DIR=$HOME/imagenet-data
</code>```

Here $HOME is /root

```<code># build the preprocessing script.
bazel build inception/download_and_preprocess_imagenet

# run it
bazel-bin/inception/download_and_preprocess_imagenet "${DATA_DIR}"
# Place the tensor records at /root/dataset
</code>```

Step 6. Source bazel and tensorflow
This step is very important. This will activate the python packages and I think you maybe getting errors because the python package for tensorflow is not activated.
If you have skipped step 5 then you might want to go to

```<code>apt-get install bazel
</code>```0

and run the gpu.py script

```<code>apt-get install bazel
</code>```1

This should verify that your tensorflow version works with your gpu

```<code>apt-get install bazel
</code>```2

You also check by importing tensorflow into python
eg:
    import tensorflow as tf

find a hello world eg on their site and if this gives errors then it has not been installed properly

Step 7. Run the imagenet training --You can skip this step if you have skipped step 5.

```<code>bazel-bin/inception/imagenet_train --num_gpus=1 --batch_size=256 --train_dir=/tmp --data_dir=/root/dataset/ --max_steps=100
</code>```

Body:
I have used conda and have installed Tensorflow=1.1.0, but it never seemed to have worked correctly within python. I also came across in github issues that anconda are currently working on the Tensorflow GPU version and so no matter what I tried in Anaconda, it never used my Tesla NVIDIA P100-SXM2-16GB card and it used only the CPU.

I suggest you use the normal environment till they get Tensorflow-gpu to work right in Anaconda.

To check if the tensorflow-gpu works I used the Inception v3 model with TF0.12 / TF1.0.

This is the process that I go through to install tensorflow1.0:

Step 0.

sudo -i
apt-get install aptitude
aptitude install software-properties-common
apt-get install libcupti-dev pip
apt-get update
apt-get upgrade libc6

Step 1. Install Nvidia Components. I think you already have that installed

Download the NVIDIA cuDNN 5.1 for CUDA 8.0 from
https://developer.nvidia.com/rdp/cudnn-download
(Registration in NVIDIA's Accelerated Computing Developer Program is required)

Cudnn 5.1 works well with most of the architectures and OS out there

Step 2. Install bazel and tensorflow

apt-get install bazel

you can go to this link https://pypi.python.org/pypi/tensorflow-gpu/1.1.0rc0 and do a

pip install <python-wheel-version>

If you have python2.7 and python 3.* installed, then use pip2 to install for python2.7

Step 3. Install openjdk

apt-get install openjdk-8-jdk

Step 4. git clone the Inception model code

git clone https://github.com/tensorflow/models.git
cd models
git checkout master
cd inception

This is where bazel comes in the picture. See Bazel's Getting Started docs for a more detailed explanation of what a target is. So, if you do a

ls -lstr

you might see 5 bazel related symbolic links

bazel-bin  bazel-genfiles  bazel-inception  bazel-out  bazel-testlogs

these are the target directory to which you build your specific model

Assuming you're in the models/inception directory

bazel build inception/imagenet_train

This activates the symbolic link

NOTE: For this imagenet_train.py to work you need to prepare the imagenet dataset. You either skip this part or go through this:

STEP 5. Prepare the Imagenet dataset
Before you run the training script for the first time, you will need to download and convert the ImageNet data to native TFRecord format.
To begin, you will need to sign up for an account with ImageNet to gain access to the data. Look for the sign-up page, create an account and request an access key to download the data.

After you have USERNAME and PASSWORD, you are ready to run our script. Make sure that your hard disk has at least 500 GB of free space for downloading and storing the data. Here we select DATA_DIR=$HOME/imagenet-data as such a location but feel free to edit accordingly.

When you run the below script, please enter USERNAME and PASSWORD when prompted. This will occur at the very beginning. Once these values are entered, you will not need to interact with the script again.

#location of where to place the ImageNet data
DATA_DIR=$HOME/imagenet-data

Here $HOME is /root

# build the preprocessing script.
bazel build inception/download_and_preprocess_imagenet

# run it
bazel-bin/inception/download_and_preprocess_imagenet "${DATA_DIR}"
# Place the tensor records at /root/dataset

Step 6. Source bazel and tensorflow
This step is very important. This will activate the python packages and I think you maybe getting errors because the python package for tensorflow is not activated.
If you have skipped step 5 then you might want to go to

/models/inception/sample

and run the gpu.py script

python gpu.py

This should verify that your tensorflow version works with your gpu

source /opt/DL/bazel/bin/bazel-activate
source /opt/DL/tensorflow/bin/tensorflow-activate

You also check by importing tensorflow into python
eg:
    import tensorflow as tf

find a hello world eg on their site and if this gives errors then it has not been installed properly

Step 7. Run the imagenet training --You can skip this step if you have skipped step 5.

bazel-bin/inception/imagenet_train --num_gpus=1 --batch_size=256 --train_dir=/tmp --data_dir=/root/dataset/ --max_steps=100


问:
Remove last lines in csv file with "Totals" info
I have a large csv file that I'm saving to Google Cloud Storage with the following sample format:

```<code>id,revenue
1,100
2,100
...
Totals
All,12000
</code>```

Or:

```<code>title,profit
titanic,200
avatar,400
fox total,600
paramount total,400
grand total,1000
</code>```

I want to be able to remove all lines after and including the Totals, because that isn't really valid information within the csv file (it's more summation information of the csv below the data).

Is there a way to delete this? Currently, we're saving the csv file to Google Cloud Storage and then importing it directly via csv-import in Big Query. Perhaps, there's a way to append row-number to a csv file when importing csv via BigQuery or something similar, so we could do a delete statement at the end?

答:
What if you delete the MAX() row after importing?

```<code>#standardSQL
DELETE
FROM `project.dataset.table`
WHERE revenue = (
  SELECT revenue
  FROM `project.dataset.table`
  ORDER BY taxi_trips DESC
  LIMIT 1
)
</code>```

Or go for the id "All":

```<code>#standardSQL
DELETE
FROM `project.dataset.table`
WHERE id = "All"
</code>```

Body:
I have a large csv file that I'm saving to Google Cloud Storage with the following sample format:

id,revenue
1,100
2,100
...
Totals
All,12000

Or:

title,profit
titanic,200
avatar,400
fox total,600
paramount total,400
grand total,1000

I want to be able to remove all lines after and including the Totals, because that isn't really valid information within the csv file (it's more summation information of the csv below the data).

Is there a way to delete this? Currently, we're saving the csv file to Google Cloud Storage and then importing it directly via csv-import in Big Query. Perhaps, there's a way to append row-number to a csv file when importing csv via BigQuery or something similar, so we could do a delete statement at the end?

Body:
What if you delete the MAX() row after importing?

#standardSQL
DELETE
FROM `project.dataset.table`
WHERE revenue = (
  SELECT revenue
  FROM `project.dataset.table`
  ORDER BY taxi_trips DESC
  LIMIT 1
)

Or go for the id "All":

#standardSQL
DELETE
FROM `project.dataset.table`
WHERE id = "All"


问:
Extract image from PDF using itextsharp
I am trying to extract all the images from a pdf using itextsharp but can't seem to overcome this one hurdle.

The error occures on the line System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS); giving an error of "Parameter is not valid".

I think it works when the image is a bitmap but not of any other format.

I have this following code - sorry for the length;

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        FileStream fs = File.OpenRead(@"reader.pdf");
        byte[] data = new byte[fs.Length];
        fs.Read(data, 0, (int)fs.Length);

        List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

        iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
        iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
        iTextSharp.text.pdf.PdfObject PDFObj = null;
        iTextSharp.text.pdf.PdfStream PDFStremObj = null;

        try
        {
            RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(data);
            PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

            for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
            {
                PDFObj = PDFReaderObj.GetPdfObject(i);

                if ((PDFObj != null) && PDFObj.IsStream())
                {
                    PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                    iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                    if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                    {
                        byte[] bytes = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStremObj);

                        if ((bytes != null))
                        {
                            try
                            {
                                System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes);

                                MS.Position = 0;
                                System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS);

                                ImgList.Add(ImgPDF);

                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
            PDFReaderObj.Close();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    } //Form1_Load
</code>```

答:
This works for me and I think it's a simple solution:

Write a custom RenderListener and implement its RenderImage method, something like this

```<code>    public void RenderImage(ImageRenderInfo info)
    {
        PdfImageObject image = info.GetImage();
        Parser.Matrix matrix = info.GetImageCTM();
        var fileType = image.GetFileType();
        ImageFormat format;
        switch (fileType)
        {//you may add more types here
            case "jpg":
            case "jpeg":
                format = ImageFormat.Jpeg;
                break;
            case "pnt":
                format = ImageFormat.Png;
                break;
            case "bmp":
                format = ImageFormat.Bmp;
                break;
            case "tiff":
                format = ImageFormat.Tiff;
                break;
            case "gif":
                format = ImageFormat.Gif;
                break;
            default:
                format = ImageFormat.Jpeg;
                break;
        }

        var pic = image.GetDrawingImage();
        var x = matrix[Parser.Matrix.I31];
        var y = matrix[Parser.Matrix.I32];
        var width = matrix[Parser.Matrix.I11];
        var height = matrix[Parser.Matrix.I22];
        if (x < <some value> && y < <some value>)
        {
            return;//ignore these images
        }

        pic.Save(<path and name>, format);
}
</code>```

Title: Extract image from PDF using itextsharp

Body:
I am trying to extract all the images from a pdf using itextsharp but can't seem to overcome this one hurdle.

The error occures on the line System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS); giving an error of "Parameter is not valid".

I think it works when the image is a bitmap but not of any other format.

I have this following code - sorry for the length;

    private void Form1_Load(object sender, EventArgs e)
    {
        FileStream fs = File.OpenRead(@"reader.pdf");
        byte[] data = new byte[fs.Length];
        fs.Read(data, 0, (int)fs.Length);

        List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

        iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
        iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
        iTextSharp.text.pdf.PdfObject PDFObj = null;
        iTextSharp.text.pdf.PdfStream PDFStremObj = null;

        try
        {
            RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(data);
            PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

            for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
            {
                PDFObj = PDFReaderObj.GetPdfObject(i);

                if ((PDFObj != null) && PDFObj.IsStream())
                {
                    PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                    iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                    if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                    {
                        byte[] bytes = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStremObj);

                        if ((bytes != null))
                        {
                            try
                            {
                                System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes);

                                MS.Position = 0;
                                System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS);

                                ImgList.Add(ImgPDF);

                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
            PDFReaderObj.Close();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    } //Form1_Load

Body:
This works for me and I think it's a simple solution:

Write a custom RenderListener and implement its RenderImage method, something like this

    public void RenderImage(ImageRenderInfo info)
    {
        PdfImageObject image = info.GetImage();
        Parser.Matrix matrix = info.GetImageCTM();
        var fileType = image.GetFileType();
        ImageFormat format;
        switch (fileType)
        {//you may add more types here
            case "jpg":
            case "jpeg":
                format = ImageFormat.Jpeg;
                break;
            case "pnt":
                format = ImageFormat.Png;
                break;
            case "bmp":
                format = ImageFormat.Bmp;
                break;
            case "tiff":
                format = ImageFormat.Tiff;
                break;
            case "gif":
                format = ImageFormat.Gif;
                break;
            default:
                format = ImageFormat.Jpeg;
                break;
        }

        var pic = image.GetDrawingImage();
        var x = matrix[Parser.Matrix.I31];
        var y = matrix[Parser.Matrix.I32];
        var width = matrix[Parser.Matrix.I11];
        var height = matrix[Parser.Matrix.I22];
        if (x < <some value> && y < <some value>)
        {
            return;//ignore these images
        }

        pic.Save(<path and name>, format);
}


问:
VBA Vlookup gives N/A, but regular Vlookup gives correct result
I have some VBA code that when run is returning N/A, but if I do the normal Vlookup in the cells it returns the correct information.

```<code>=VLOOKUP(A6,'[AR Aging Detail Report as of 06-26-2017.xlsx]Sheet1'!$H:$V,5,FALSE)
</code>```

That's the normal Vlookup that works in the cells. I have this code which only returns N/A for all cells. I can post the full code, but this is what is relevant. xlWS and xlWB2 are defined earlier as the relevant workbooks.

```<code>xlWS.Activate
With xlWS
    For i = 2 To rCount
        sFormula = Application.VLookup(Range("A" & i), xlWB2.Sheets(1).Range("H:V"), 5, False)
</code>```

What could be wrong here? The vlookup looks to be the same.

Adding full code for context. It first finds the most recent file with "AR Aging*" as the name and assigns it to xlWB2. That's the bulk of the code there. Then I try to run the Vlookup on each row and put the returned value in column 'O' of xlWB.

```<code> 'Specify the path to the folder
MyPath = "C:\Users\TheAgency\Documents\test"

'Make sure that the path ends in a backslash
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

'Get the first Excel file from the folder
MyFile = Dir(MyPath & "AR Aging*.xlsx", vbNormal)

'If no files were found, exit the sub
If Len(MyFile) = 0 Then
    MsgBox "No files were found...", vbExclamation
    Exit Sub
End If

'Loop through each Excel file in the folder
Do While Len(MyFile) > 0

    'Assign the date/time of the current file to a variable
    LMD = FileDateTime(MyPath & MyFile)

    'If the date/time of the current file is greater than the latest
    'recorded date, assign its filename and date/time to variables
    If LMD > LatestDate Then
        LatestFile = MyFile
        LatestDate = LMD
    End If

    'Get the next Excel file from the folder
    MyFile = Dir

Loop

'Open the latest file
Set xlWB2 = Workbooks.Open(MyPath & LatestFile, True, True)

On Error Resume Next
' test if excel is already running
Set xlApp = GetObject(, "Excel.Application")
On Error GoTo 0
If Err.Number <> 0 Then
    ' Excel is not running
    ' so create an object
    Set xlApp = CreateObject("Excel.Application")
Else
    ' flag. excel is already running before we execute this code
    bolIsExcelRunning = True
End If

xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open(WB_PATH & "hdremittance.csv")
Set xlWS = xlWB.Sheets("hdremittance")
Set xlWS2 = xlWB2.Sheets(1)
xlSheetName = xlWS2.Name

rCount = xlWS.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count - 1
Debug.Print "rCount : " & rCount

' rCount2: 6 Months Row Count
On Error Resume Next
rCount2 = xlWS2.Range("D:D").Cells.SpecialCells(xlCellTypeAllFormatConditions).Count - 1
Debug.Print "rCount2 : " & rCount2

Sheets.Add(after:=Sheets(Sheets.Count)).Name = "Sheet2"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = "returns"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = ".com"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = "Shortage"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = "No Store"

xlWS.Activate
With xlWS
    For i = 2 To rCount
        sFormula = Application.VLookup(.Range("A" & i), xlWB2.Sheets(1).Range("A:J"), 3, True)
        rFormula = Application.VLookup(.Range("A" & i), xlWB2.Sheets(1).Range("A:J"), 2, False)
        Inv = Application.VLookup(.Range("A" & i), xlWB2.Sheets(1).Range("A:V"), 6, False)
        Debug.Print sFormula
        .Range("O" & i).Value = sFormula
        .Range("R" & i).Value = rFormula
        .Range("S" & i).Value = "Wire Transfer"
        .Range("T" & i).Value = "1200"
        .Range("U" & i).Value = "4699"
        .Range("V" & i).Value = "1100"
        .Range("X" & i).Value = Inv
        DoEvents
    Next
End With
</code>```

答: Perhaps your reference to Sheets(1) is not correct.  I rebuilt your procedure and found the Error 2042 (#N/A) is returned if there is no match.  Your formula clearly shows you are referring to "Sheet1" but your code indicates Sheets(1), which may not necessarily be the same thing.  Replace "Sheets(1)" with "Sheets("Sheet1")" and try again.</p>

Body:
I have some VBA code that when run is returning N/A, but if I do the normal Vlookup in the cells it returns the correct information.

=VLOOKUP(A6,'[AR Aging Detail Report as of 06-26-2017.xlsx]Sheet1'!$H:$V,5,FALSE)

That's the normal Vlookup that works in the cells. I have this code which only returns N/A for all cells. I can post the full code, but this is what is relevant. xlWS and xlWB2 are defined earlier as the relevant workbooks.

xlWS.Activate
With xlWS
    For i = 2 To rCount
        sFormula = Application.VLookup(Range("A" & i), xlWB2.Sheets(1).Range("H:V"), 5, False)

What could be wrong here? The vlookup looks to be the same.

Adding full code for context. It first finds the most recent file with "AR Aging*" as the name and assigns it to xlWB2. That's the bulk of the code there. Then I try to run the Vlookup on each row and put the returned value in column 'O' of xlWB.

 'Specify the path to the folder
MyPath = "C:\Users\TheAgency\Documents\test"

'Make sure that the path ends in a backslash
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

'Get the first Excel file from the folder
MyFile = Dir(MyPath & "AR Aging*.xlsx", vbNormal)

'If no files were found, exit the sub
If Len(MyFile) = 0 Then
    MsgBox "No files were found...", vbExclamation
    Exit Sub
End If

'Loop through each Excel file in the folder
Do While Len(MyFile) > 0

    'Assign the date/time of the current file to a variable
    LMD = FileDateTime(MyPath & MyFile)

    'If the date/time of the current file is greater than the latest
    'recorded date, assign its filename and date/time to variables
    If LMD > LatestDate Then
        LatestFile = MyFile
        LatestDate = LMD
    End If

    'Get the next Excel file from the folder
    MyFile = Dir

Loop

'Open the latest file
Set xlWB2 = Workbooks.Open(MyPath & LatestFile, True, True)

On Error Resume Next
' test if excel is already running
Set xlApp = GetObject(, "Excel.Application")
On Error GoTo 0
If Err.Number <> 0 Then
    ' Excel is not running
    ' so create an object
    Set xlApp = CreateObject("Excel.Application")
Else
    ' flag. excel is already running before we execute this code
    bolIsExcelRunning = True
End If

xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open(WB_PATH & "hdremittance.csv")
Set xlWS = xlWB.Sheets("hdremittance")
Set xlWS2 = xlWB2.Sheets(1)
xlSheetName = xlWS2.Name

rCount = xlWS.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count - 1
Debug.Print "rCount : " & rCount

' rCount2: 6 Months Row Count
On Error Resume Next
rCount2 = xlWS2.Range("D:D").Cells.SpecialCells(xlCellTypeAllFormatConditions).Count - 1
Debug.Print "rCount2 : " & rCount2

Sheets.Add(after:=Sheets(Sheets.Count)).Name = "Sheet2"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = "returns"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = ".com"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = "Shortage"
Sheets.Add(after:=Sheets(Sheets.Count)).Name = "No Store"

xlWS.Activate
With xlWS
    For i = 2 To rCount
        sFormula = Application.VLookup(.Range("A" & i), xlWB2.Sheets(1).Range("A:J"), 3, True)
        rFormula = Application.VLookup(.Range("A" & i), xlWB2.Sheets(1).Range("A:J"), 2, False)
        Inv = Application.VLookup(.Range("A" & i), xlWB2.Sheets(1).Range("A:V"), 6, False)
        Debug.Print sFormula
        .Range("O" & i).Value = sFormula
        .Range("R" & i).Value = rFormula
        .Range("S" & i).Value = "Wire Transfer"
        .Range("T" & i).Value = "1200"
        .Range("U" & i).Value = "4699"
        .Range("V" & i).Value = "1100"
        .Range("X" & i).Value = Inv
        DoEvents
    Next
End With


问:
Turning simple c algorithm into matlab
It's simple, I want to pick the biggest value of a line, make all other elements in a line equal to zero and then the position with the biggest value shall be transformed into 1.

This is the code:

```<code>float A [3][3];
 A [0][0] = 1.1, A [0][1] = 3.2, A [0][2] = 1.3;
 A [1][0] = 2.1, A [1][1] = 2.2, A [1][2] = 2.3;
 A [2][0] = 3.1, A [2][1] = 3.2, A [2][2] = 3.3;
for (int i=0; i<3; i++) {
  float biggest=-1000000;
  int biggest_position=0;
  for (int y=0; y<3; y++)
     if (A [i][y]>biggest) {
        biggest_position = y;
        biggest = A[i][y];
        cout << "biggest position" << biggest_position << endl;
     }
  for (int y=0; y<3; y++)
     A [i][y] = 0;
  A [i][biggest_position] = 1;
}
for (int i=0; i<3; i++)
   for (int j=0; j<3; j++)
     cout << A [i][j] << endl;
</code>```

So what I need to do to rewrite properly this code in matlab language?

答:
Just do:

```<code>A = A==max(A); %array of zeros with only ones at the maximum  of the columns of the array.
</code>```

If  you want the maximum of a row you transpose first using a '

```<code>A = (A'==max(A'))';
</code>```

Title: Turning simple c algorithm into matlab

Body:
It's simple, I want to pick the biggest value of a line, make all other elements in a line equal to zero and then the position with the biggest value shall be transformed into 1.

This is the code:

float A [3][3];
 A [0][0] = 1.1, A [0][1] = 3.2, A [0][2] = 1.3;
 A [1][0] = 2.1, A [1][1] = 2.2, A [1][2] = 2.3;
 A [2][0] = 3.1, A [2][1] = 3.2, A [2][2] = 3.3;
for (int i=0; i<3; i++) {
  float biggest=-1000000;
  int biggest_position=0;
  for (int y=0; y<3; y++)
     if (A [i][y]>biggest) {
        biggest_position = y;
        biggest = A[i][y];
        cout << "biggest position" << biggest_position << endl;
     }
  for (int y=0; y<3; y++)
     A [i][y] = 0;
  A [i][biggest_position] = 1;
}
for (int i=0; i<3; i++)
   for (int j=0; j<3; j++)
     cout << A [i][j] << endl;

So what I need to do to rewrite properly this code in matlab language?

Body:
Just do:

A = A==max(A); %array of zeros with only ones at the maximum  of the columns of the array.

If  you want the maximum of a row you transpose first using a '

A = (A'==max(A'))';


问:
Jenkins with Cleracase - Creating Automatic Baselines in CC and triggering Jenkins Job
I am new to Jenkins and need some help.

We have ClearCase and Jenkins running on same machine (windows).

I am trying to configure Jenkins with clearcase through basic CC or CC UCM plugin. But i am not sure which one i need to choose.

My Current Process :
Step 1: Once developer deliver the code to Integration region in clearcase, Devops team manually do the baseline for Int stream and also do the rebase.
Step 2: And with some batch script they build the process and move the ear or jar to particular region.

Now i need to automate this process through Jenkins, where i got stuck with automating baseline and rebase in clearcase which they are doing it manually now. i think once the baseline creation is done by developer or through command process only Jenkins will be triggered to start the job.

So please suggest me the exact steps which i need to start automating the whole process.

答:
From a non-Jenkins standpoint, you may want to find out when the "Devops" folks create the baselines. It is possible (though not recommended) to create those baselines in a postop deliver_complete trigger. (Baseline and label accumulation can have long-term performance impacts and may not be easy to clean up...)

If they have set up a trigger to create the baseline, you might be able to skip the whole "polling" by adding whatever is needed to trip the rebase and build within the trigger.