问:
How to take google Maps v2 snapshot?
i have to solve this with the new "snapshot maker" which is implemented in the google maps release august but i dont' know how to do this.
Can somone give me a simple example?

here is my code:

```<code>public class MainActivity extends Activity {
static LatLng HAMBURG = new LatLng(47.524749, 21.632745);
GoogleMap map;
File dbFile;
private File imageFile;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    PolylineOptions line = new PolylineOptions();

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();
    /*
     * Adatbázis
     */
    try {
        dbFile = getDatabasePath("/mnt/sdcard/Download/TeleSensors.db");
    } catch (Exception e) {

    }

    SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(
            dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);

    Cursor curTAB = myDataBase.rawQuery("SELECT * FROM  GPS_Values;", null);

    Integer count = 0;
    while (curTAB.moveToNext()) {
        String s_latitude = curTAB.getString(1);
        String s_longitude = curTAB.getString(2);
        count++;
        double latitude = Double.parseDouble(s_latitude);
        double longitude = Double.parseDouble(s_longitude);
        line.add(new LatLng(latitude, longitude));

        Log.i("Coordinates",
                s_latitude.toString() + " --- " + s_longitude.toString());

    }
    curTAB.close();
    myDataBase.close();
    // adatbázis vége

    map.addPolyline(line);

    // map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    // map.setMapType(GoogleMap.MAP_TYPE_NONE);
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    // map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    // map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

    // Move the camera instantly to hamburg with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

    // Zoom in, animating the camera.
    map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);

}
</code>```

}

Thank you very mouch!

答:
Try for Kotlin Android like this when click on button to take google map snapshot:

```<code>val snapshotReadyCallback : GoogleMap.SnapshotReadyCallback = GoogleMap.SnapshotReadyCallback { selectedScreenShot ->
    ivMapPreview.setImageBitmap(selectedScreenShot);
}

val onMapLoadedCallback : GoogleMap.OnMapLoadedCallback = GoogleMap.OnMapLoadedCallback {
    mMap!!.snapshot(snapshotReadyCallback)
}

mMap!!.setOnMapLoadedCallback(onMapLoadedCallback)
</code>```

Be successful.

Title: How to take google Maps v2 snapshot?

Body:
i have to solve this with the new "snapshot maker" which is implemented in the google maps release august but i dont' know how to do this.
Can somone give me a simple example?

here is my code:

public class MainActivity extends Activity {
static LatLng HAMBURG = new LatLng(47.524749, 21.632745);
GoogleMap map;
File dbFile;
private File imageFile;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    PolylineOptions line = new PolylineOptions();

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();
    /*
     * Adatbázis
     */
    try {
        dbFile = getDatabasePath("/mnt/sdcard/Download/TeleSensors.db");
    } catch (Exception e) {

    }

    SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(
            dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);

    Cursor curTAB = myDataBase.rawQuery("SELECT * FROM  GPS_Values;", null);

    Integer count = 0;
    while (curTAB.moveToNext()) {
        String s_latitude = curTAB.getString(1);
        String s_longitude = curTAB.getString(2);
        count++;
        double latitude = Double.parseDouble(s_latitude);
        double longitude = Double.parseDouble(s_longitude);
        line.add(new LatLng(latitude, longitude));

        Log.i("Coordinates",
                s_latitude.toString() + " --- " + s_longitude.toString());

    }
    curTAB.close();
    myDataBase.close();
    // adatbázis vége

    map.addPolyline(line);

    // map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    // map.setMapType(GoogleMap.MAP_TYPE_NONE);
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    // map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    // map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

    // Move the camera instantly to hamburg with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

    // Zoom in, animating the camera.
    map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);

}

}

Thank you very mouch!

Body:
Try for Kotlin Android like this when click on button to take google map snapshot:

val snapshotReadyCallback : GoogleMap.SnapshotReadyCallback = GoogleMap.SnapshotReadyCallback { selectedScreenShot ->
    ivMapPreview.setImageBitmap(selectedScreenShot);
}

val onMapLoadedCallback : GoogleMap.OnMapLoadedCallback = GoogleMap.OnMapLoadedCallback {
    mMap!!.snapshot(snapshotReadyCallback)
}

mMap!!.setOnMapLoadedCallback(onMapLoadedCallback)

Be successful.


来源: stackexchange

问:
Why do the IF statements cause batch file to exit?
I have tried to make the code pick a random number 1-5 and it would then choose a random area in the game. The problem is that it keeps exiting whenever it executes. It ignores also the x between the %place% variable.

```<code>pause
set place=%random% %% 5
timeout 1
if x%place%x==1 goto cave
if x%place%x==2 goto plains
if x%place%x==3 goto swamp
if x%place%x==4 goto volcano
if x%place%x==5 goto fail
:cave
echo You went for a crusade and ended up in a cave.
pause
:plains
echo You went for a crusade and found a plains biome.
pause
:swamp
echo You went for a crusade and ventured into a swamp.
pause
:volcano
echo You went for a crusade and somehow ended up on a volcano.
pause
:fail
echo Your boat sank and you survived. You lost 5 coins.
pause
</code>```

答:
The first mistake is already on the line:

```<code>set place=%random% %% 5
</code>```

This line assigns a string to environment variable place which consists of

a random decimal number in range 0 to 32767,

a space character,

a percent sign,

a space character and

the number 5.

As a result the first if command line is after processing before execution for example:

```<code>if x20934 % 5x==1 goto cave
</code>```

The Windows command processor exits batch file processing with the error message:

% was unexpected at this time.

That is a pretty clear error message on debugging the batch file. The first argument of command IF is x20934 and so the Windows command processor expects next either the string comparison operator == or with command extensions enabled as by default one of the operators EQU, NEQ, LSS, LEQ, GTR, GEQ which are mainly for comparing two 32-bit signed integer values, but can be used also for string comparisons.

Please read the answer on Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files for full details how Windows command processor does a string or integer comparison.

So it is first necessary to correct the command line which should evaluate an arithmetic expression and assign the result as string to environment variable place.

```<code>set /A place=%RANDOM% %% 5 + 1
</code>```

Then it would be possible to use IF conditions with either operator == or EQU to evaluate the result.

The usage of string comparison operator == would be faster in this case on which it is 100% sure that place is a string with first character being 1, 2, 3, 4 or 5 (with decimal code value 49 to 53) and second character is the terminating null (with decimal code value 0). So the function strcmp used by cmd.exe returns the integer result already after first or second character (byte) compare.

```<code>set /A place=%RANDOM% %% 5 + 1
if %place% == 1 goto cave
if %place% == 2 goto plains
if %place% == 3 goto swamp
if %place% == 4 goto volcano
if %place% == 5 goto fail
</code>```

It would be also possible to use EQU as operator. But in this case both strings are first converted with function strtol to 32-bit signed integer values which are next compared using an integer comparison. That requires much more CPU cycles to accomplish the comparison.

```<code>set /A place=%RANDOM% %% 5 + 1
if %place% EQU 1 goto cave
if %place% EQU 2 goto plains
if %place% EQU 3 goto swamp
if %place% EQU 4 goto volcano
if %place% EQU 5 goto fail
</code>```

The user running the batch file will not see a difference. The processors in PCs are nowadays so fast that the much more CPU cycles needed for the execution of the two strtol in comparison to execution of single strcmp is just a few microseconds.

The batch file execution efficiency can be increased even more by avoiding the five IF conditions completely because of the Windows command processor has to do in worst case five times:

Open the batch file.

Set file read position to byte offset of end of last read.

Read the bytes from batch file up to next line-feed.

Preprocess the command line to find out if more lines need to be read.

Remember current byte position in batch file.

Close the batch file.

Process the command line completely and execute it.

The IF conditions can be avoided by using appropriate labels and use just command GOTO with a label depending on environment variable place:

```<code>@echo off
set /A place=%RANDOM% %% 5
goto Place%place%

:Place0 - cave
echo You went for a crusade and ended up in a cave.& echo/& pause
rem More commands for cave.
goto :EOF

:Place1 - plains
echo You went for a crusade and found a plains biome.& echo/& pause
rem More commands for plains.
goto :EOF

:Place2 - swamp
echo You went for a crusade and ventured into a swamp.& echo/& pause
rem More commands for swamp.
goto :EOF

:Place3 - volcano
echo You went for a crusade and somehow ended up on a volcano.& echo/& pause
rem More commands for volcano.
goto :EOF

:Place4 - fail
echo Your boat sank and you survived. You lost 5 coins.& echo/& pause
</code>```

The Windows command processor interprets just the string after : up to first delimiter character as label. So it is possible to use the labels as shown above to know which Placex label is for which place because of the string after the space is ignored by Windows command processor.

The arithmetic expression results in a value in range 0-4 assigned as string to environment variable place which is concatenated with the string Place on next command line to the label name to be processed by GOTO to continue batch file processing on the line below that label.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

goto /?

pause /?

rem /?

set /?

See also single line with multiple commands for an explanation of operator &.

ContentLicense: CC BY-SA 4.0

Body:
I have tried to make the code pick a random number 1-5 and it would then choose a random area in the game. The problem is that it keeps exiting whenever it executes. It ignores also the x between the %place% variable.

pause
set place=%random% %% 5
timeout 1
if x%place%x==1 goto cave
if x%place%x==2 goto plains
if x%place%x==3 goto swamp
if x%place%x==4 goto volcano
if x%place%x==5 goto fail
:cave
echo You went for a crusade and ended up in a cave.
pause
:plains
echo You went for a crusade and found a plains biome.
pause
:swamp
echo You went for a crusade and ventured into a swamp.
pause
:volcano
echo You went for a crusade and somehow ended up on a volcano.
pause
:fail
echo Your boat sank and you survived. You lost 5 coins.
pause

Body:
The first mistake is already on the line:

set place=%random% %% 5

This line assigns a string to environment variable place which consists of

a random decimal number in range 0 to 32767,

a space character,

a percent sign,

a space character and

the number 5.

As a result the first if command line is after processing before execution for example:

if x20934 % 5x==1 goto cave

The Windows command processor exits batch file processing with the error message:

% was unexpected at this time.

That is a pretty clear error message on debugging the batch file. The first argument of command IF is x20934 and so the Windows command processor expects next either the string comparison operator == or with command extensions enabled as by default one of the operators EQU, NEQ, LSS, LEQ, GTR, GEQ which are mainly for comparing two 32-bit signed integer values, but can be used also for string comparisons.

Please read the answer on Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files for full details how Windows command processor does a string or integer comparison.

So it is first necessary to correct the command line which should evaluate an arithmetic expression and assign the result as string to environment variable place.

set /A place=%RANDOM% %% 5 + 1

Then it would be possible to use IF conditions with either operator == or EQU to evaluate the result.

The usage of string comparison operator == would be faster in this case on which it is 100% sure that place is a string with first character being 1, 2, 3, 4 or 5 (with decimal code value 49 to 53) and second character is the terminating null (with decimal code value 0). So the function strcmp used by cmd.exe returns the integer result already after first or second character (byte) compare.

set /A place=%RANDOM% %% 5 + 1
if %place% == 1 goto cave
if %place% == 2 goto plains
if %place% == 3 goto swamp
if %place% == 4 goto volcano
if %place% == 5 goto fail

It would be also possible to use EQU as operator. But in this case both strings are first converted with function strtol to 32-bit signed integer values which are next compared using an integer comparison. That requires much more CPU cycles to accomplish the comparison.

set /A place=%RANDOM% %% 5 + 1
if %place% EQU 1 goto cave
if %place% EQU 2 goto plains
if %place% EQU 3 goto swamp
if %place% EQU 4 goto volcano
if %place% EQU 5 goto fail

The user running the batch file will not see a difference. The processors in PCs are nowadays so fast that the much more CPU cycles needed for the execution of the two strtol in comparison to execution of single strcmp is just a few microseconds.

The batch file execution efficiency can be increased even more by avoiding the five IF conditions completely because of the Windows command processor has to do in worst case five times:

Open the batch file.

Set file read position to byte offset of end of last read.

Read the bytes from batch file up to next line-feed.

Preprocess the command line to find out if more lines need to be read.

Remember current byte position in batch file.

Close the batch file.

Process the command line completely and execute it.

The IF conditions can be avoided by using appropriate labels and use just command GOTO with a label depending on environment variable place:

@echo off
set /A place=%RANDOM% %% 5
goto Place%place%

:Place0 - cave
echo You went for a crusade and ended up in a cave.& echo/& pause
rem More commands for cave.
goto :EOF

:Place1 - plains
echo You went for a crusade and found a plains biome.& echo/& pause
rem More commands for plains.
goto :EOF

:Place2 - swamp
echo You went for a crusade and ventured into a swamp.& echo/& pause
rem More commands for swamp.
goto :EOF

:Place3 - volcano
echo You went for a crusade and somehow ended up on a volcano.& echo/& pause
rem More commands for volcano.
goto :EOF

:Place4 - fail
echo Your boat sank and you survived. You lost 5 coins.& echo/& pause

The Windows command processor interprets just the string after : up to first delimiter character as label. So it is possible to use the labels as shown above to know which Placex label is for which place because of the string after the space is ignored by Windows command processor.

The arithmetic expression results in a value in range 0-4 assigned as string to environment variable place which is concatenated with the string Place on next command line to the label name to be processed by GOTO to continue batch file processing on the line below that label.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

goto /?

pause /?

rem /?

set /?

See also single line with multiple commands for an explanation of operator &.


问:
Unable to separate csv's into separate columns
I have used the following function to create a unique data_frame with csv's (already encoded in UTF-8 form):

```<code>library(readr)
comentarios_hoteles<-list.files(path="C:/Users/OneDrive/Documentos/DFBA/ Melia", pattern="*.csv", full.names=TRUE) %>%
  lapply(read_csv)%>%
  bind_rows
</code>```

For some reason I am getting all the observations in one column instead of in 6.

```<code>This is the full code:
Comentario,"Fecha","Mes","Estación","Hotel","Marca"
1   No todas las instalaciones del hotel se pudieron usar, estaban cerradas sin avisar previamente al cliente. Se intentó hacer un cambio en las fechas de la reserva debido al temporal de calima que hubo (no porque no quisiéramos irnos de hotel) y no dejaron (añadiendo que el tiempo estaba mucho mejor que el día anterior) y tampoco propusieron solución. Al llegar al hotel, vemos que la piscina está cerrada por dicho temporal, por lo que encima no se podía disfrutar de todas las instalaciones. Los desayunos muy bien, variados. No puedo decir lo mismo de las cenas: arroz pasado y con olor, poca variedad y para colmo los camareros sirviéndose la cena sin darte paso a ti, cliente, a servite no siendo que le quitaramos el trozo de pizza que quería... En fin... Yo siempre que voy a hotel, voy a los Melia, pero este en concreto no está a la altura de lo que acostumbra la marca, por lo que no lo recomendaría. …,2020-02-01,"feb.","Invierno","Sol Arona Tenerife","Sol"
2   Me he ido con un buen sabor de boca, y ganas de volver. Me ha sorprendido totalmente el hotel.  Nuestra habitación en la planta 14, era genial! Espaciosa, bien cuidada, vistas preciosas, limpieza bien.  Servicio de restaurante con horario amplio. El día de comida mexicana, un acierto total!! Me encantó.  Eché de menos la nata en el desayuno, para las tortitas, gofres y demás. Aunque había sirope de sobra! Camareros, y recepcionistas, muy atent@os. Especial agradecimiento a Bela, de recepción, siempre muy amable con nosotros.  Volveré, y pronto!!! ,2019-11-01,"nov.","Otoño","Sol Arona Tenerife","Sol"
3   Hotel normalito. Está un poco viejo. Las habitaciones no tienen aire acondicionado. Las animaciones por la noche son muy cortas, están principalmente enfocadas para el turismo extranjero y empiezan muy pronto. En mi opinión, las instalaciones no están a la altura de un hotel de 4 estrellas. Lo que más nos gusto, fue el trato del personal del buffet, destacando al camarero Roberto, que nos hizo una estancia mucho más agradable y amena, siempre con una atención maravillosa en el restaurante, y ayudándonos y recomendándonos en cuanto a las actividades que queríamos realizar en la isla,  demostrando  ser un gran profesional que disfruta de su trabajo y siempre con una sonrisa.,2019-09-01,"sep.","Verano","Sol Arona Tenerife","Sol"
4   Tenemos dos niños pequeños por lo que contratar el hotel con pensión todo incluído nos viene muy cómodo. Por otro lado el hotel está cerca de tiendas, farmacias y una clínica por si hay alguna incidencia. Además el hotel está a 5 minutos a pie de la playa de los Cristianos por lo que es muy conveniente.,2020-02-01,"feb.","Invierno","Sol Arona Tenerife","Sol"
5   habitacion de albergue , 20 metros cuadrados para 5 personas incluyendo un bebé ,cama litera de peligro ,  a 180€ por noche deja que desear , la Directira del hotel incapaz de solucionar nuestro reclamo.  Buen buffet y localización , nada más - no volveremos , rato en un Meliá,2020-01-01,"ene.","Invierno","Sol Arona Tenerife","Sol"
6   Bastante bien para unas vacaciones por el sur, Cerca del muelle y de la playa. Se puede ir a pie por los paseos cercanos, Las habitaciones un poco viejas. Pero si vas a dormir y a disfrutar de la isla. Buena relación calidad-precio,2019-12-01,"dic.","Invierno","Sol Arona Tenerife","Sol"
7   Tuvimos el lavabo atascado y tuvimos que reclamar varias veces su arreglo. Camas incomodas. Todo muy viejo. El bufet malísimo  y sin variedad. Las animaciones y los horarios pensados para extranjeros solamente. Hay un camarero en el bufet de cena que es un pesado. Solamente hablando mal del hotel y de su administración. Desde luego no volveremos. Fuimos cuando era Princesa Dácil y ha sido una decepción.,2019-12-01,"dic.","Invierno","Sol Arona Tenerife","Sol"
8   puede parecer en un principio q es de la cadena Melia y asi debio ser en sus comienzos, a dia de hoy es bastante normalito tirando a básico, lo elegi para pasar diez días por eso mismo pensando q tenia la calidad de todo el grupo Melia, incluso antes de reservarlo me dijeron q aplicaban el programa de puntos cosa q no hicieron, por q no se había reservado directamente con ellos, si no a través de un operador(FALLO-MALTRATO AL CLIENTE)pero por teléfono te cuentan lo q quieres oir......el bufett es bastante bueno todo hay q decirlo y en cuanto a las habitaciones normalitas sin lujos pero limpias y en buen estado ,2019-01-01,"ene.","Invierno","Sol Arona Tenerife","Sol"
9   Nos alojamos un fin de semana en régimen de todo incluido y la experiencia no fue mala exceptuando algunas cosas. La habitación era grande y espaciosa, además estaba todo muy limpio. Lo malo es que la cama era muy incómoda y con muchos muelles, pero nos lo solucionaron ese mismo día y pudimos dormir decentemente. A pesar de ello, creo que un hotel de estas características debería tener una cama mucho mejor.  Nos vamos descontentos con el tema del todo incluido. Las bebidas eran muy malas. La comida no estaba mala de sabor, pero faltaba variedad en el almuerzo ya que durante los días que estuvimos comimos casi lo mismo. En la cena si que ponían algo más diferente. Los desayunos estaban muy bien pero desde las 10 empiezan a quitar las comida, algo que creo que no debería suceder…,2019-12-01,"dic.","Invierno","Sol Arona Tenerife","Sol"
10  No es la primera vez que me hospedo por lo que me parece
</code>```

Would greatly appreciate some help with this error as I am not able to solve it. Thank you in advance1

答:
The commentario part of your .csv file have no quotes "" and use commas , which are usually used to separate the text into columns from functions to read .csv files. .csv is abbreviated for comma separated values. Now, the separation algorithm gets confused because it doesn't know, whether a comma is part of a comment or should be used to separate into a column.

You could use readLines to juest read the plain lines. Then you may use gsub with a regex that converts the "hot" commas (where to separate) into something different, e.g. ;, which you then use to separate into columns.

Try the following.

```<code>A <- readLines(con <- file("V:/commentarios.csv"))
close(con)

## enquote dates
csv <-  gsub('(.*)(\\d{4}-\\d{2}-\\d{2})(.*)"', '\\1\\"\\2\\"\\3', A)

## convert "hot" commas into ";"
csv <-  gsub('\\"\\,\\"', '\\"\\;\\"', csv)
## convert "hot" commas that appear before a date
csv <-  gsub('\\,\\"', '\\;\\"', csv)

## finally read the .csv
res <- read.csv(text=csv, header=TRUE, sep=";", quote="")
#            Comentario     X.Fecha. X.Mes. X.Estación.             X.Hotel. X.Marca.
# 1  1   No todas la... "2020-02-01" "feb."  "Invierno" "Sol Arona Tenerife"     "Sol
# 2  2   Me he ido c... "2019-11-01" "nov."     "Otoño" "Sol Arona Tenerife"     "Sol
# 3  3   Hotel norma... "2019-09-01" "sep."    "Verano" "Sol Arona Tenerife"     "Sol
# 4  4   Tenemos dos... "2020-02-01" "feb."  "Invierno" "Sol Arona Tenerife"     "Sol
# 5  5   habitacion ... "2020-01-01" "ene."  "Invierno" "Sol Arona Tenerife"     "Sol
# 6  6   Bastante bi... "2019-12-01" "dic."  "Invierno" "Sol Arona Tenerife"     "Sol
# 7  7   Tuvimos el ... "2019-12-01" "dic."  "Invierno" "Sol Arona Tenerife"     "Sol
# 8  8   puede parec... "2019-01-01" "ene."  "Invierno" "Sol Arona Tenerife"     "Sol
# 9  9   Nos alojamo... "2019-12-01" "dic."  "Invierno" "Sol Arona Tenerife"     "Sol
# 10 10  No es la pr...
</code>```

Body:
I have used the following function to create a unique data_frame with csv's (already encoded in UTF-8 form):

library(readr)
comentarios_hoteles<-list.files(path="C:/Users/OneDrive/Documentos/DFBA/ Melia", pattern="*.csv", full.names=TRUE) %>%
  lapply(read_csv)%>%
  bind_rows

For some reason I am getting all the observations in one column instead of in 6.

This is the full code:
Comentario,"Fecha","Mes","Estación","Hotel","Marca"
1   No todas las instalaciones del hotel se pudieron usar, estaban cerradas sin avisar previamente al cliente. Se intentó hacer un cambio en las fechas de la reserva debido al temporal de calima que hubo (no porque no quisiéramos irnos de hotel) y no dejaron (añadiendo que el tiempo estaba mucho mejor que el día anterior) y tampoco propusieron solución. Al llegar al hotel, vemos que la piscina está cerrada por dicho temporal, por lo que encima no se podía disfrutar de todas las instalaciones. Los desayunos muy bien, variados. No puedo decir lo mismo de las cenas: arroz pasado y con olor, poca variedad y para colmo los camareros sirviéndose la cena sin darte paso a ti, cliente, a servite no siendo que le quitaramos el trozo de pizza que quería... En fin... Yo siempre que voy a hotel, voy a los Melia, pero este en concreto no está a la altura de lo que acostumbra la marca, por lo que no lo recomendaría. …,2020-02-01,"feb.","Invierno","Sol Arona Tenerife","Sol"
2   Me he ido con un buen sabor de boca, y ganas de volver. Me ha sorprendido totalmente el hotel.  Nuestra habitación en la planta 14, era genial! Espaciosa, bien cuidada, vistas preciosas, limpieza bien.  Servicio de restaurante con horario amplio. El día de comida mexicana, un acierto total!! Me encantó.  Eché de menos la nata en el desayuno, para las tortitas, gofres y demás. Aunque había sirope de sobra! Camareros, y recepcionistas, muy atent@os. Especial agradecimiento a Bela, de recepción, siempre muy amable con nosotros.  Volveré, y pronto!!! ,2019-11-01,"nov.","Otoño","Sol Arona Tenerife","Sol"
3   Hotel normalito. Está un poco viejo. Las habitaciones no tienen aire acondicionado. Las animaciones por la noche son muy cortas, están principalmente enfocadas para el turismo extranjero y empiezan muy pronto. En mi opinión, las instalaciones no están a la altura de un hotel de 4 estrellas. Lo que más nos gusto, fue el trato del personal del buffet, destacando al camarero Roberto, que nos hizo una estancia mucho más agradable y amena, siempre con una atención maravillosa en el restaurante, y ayudándonos y recomendándonos en cuanto a las actividades que queríamos realizar en la isla,  demostrando  ser un gran profesional que disfruta de su trabajo y siempre con una sonrisa.,2019-09-01,"sep.","Verano","Sol Arona Tenerife","Sol"
4   Tenemos dos niños pequeños por lo que contratar el hotel con pensión todo incluído nos viene muy cómodo. Por otro lado el hotel está cerca de tiendas, farmacias y una clínica por si hay alguna incidencia. Además el hotel está a 5 minutos a pie de la playa de los Cristianos por lo que es muy conveniente.,2020-02-01,"feb.","Invierno","Sol Arona Tenerife","Sol"
5   habitacion de albergue , 20 metros cuadrados para 5 personas incluyendo un bebé ,cama litera de peligro ,  a 180€ por noche deja que desear , la Directira del hotel incapaz de solucionar nuestro reclamo.  Buen buffet y localización , nada más - no volveremos , rato en un Meliá,2020-01-01,"ene.","Invierno","Sol Arona Tenerife","Sol"
6   Bastante bien para unas vacaciones por el sur, Cerca del muelle y de la playa. Se puede ir a pie por los paseos cercanos, Las habitaciones un poco viejas. Pero si vas a dormir y a disfrutar de la isla. Buena relación calidad-precio,2019-12-01,"dic.","Invierno","Sol Arona Tenerife","Sol"
7   Tuvimos el lavabo atascado y tuvimos que reclamar varias veces su arreglo. Camas incomodas. Todo muy viejo. El bufet malísimo  y sin variedad. Las animaciones y los horarios pensados para extranjeros solamente. Hay un camarero en el bufet de cena que es un pesado. Solamente hablando mal del hotel y de su administración. Desde luego no volveremos. Fuimos cuando era Princesa Dácil y ha sido una decepción.,2019-12-01,"dic.","Invierno","Sol Arona Tenerife","Sol"
8   puede parecer en un principio q es de la cadena Melia y asi debio ser en sus comienzos, a dia de hoy es bastante normalito tirando a básico, lo elegi para pasar diez días por eso mismo pensando q tenia la calidad de todo el grupo Melia, incluso antes de reservarlo me dijeron q aplicaban el programa de puntos cosa q no hicieron, por q no se había reservado directamente con ellos, si no a través de un operador(FALLO-MALTRATO AL CLIENTE)pero por teléfono te cuentan lo q quieres oir......el bufett es bastante bueno todo hay q decirlo y en cuanto a las habitaciones normalitas sin lujos pero limpias y en buen estado ,2019-01-01,"ene.","Invierno","Sol Arona Tenerife","Sol"
9   Nos alojamos un fin de semana en régimen de todo incluido y la experiencia no fue mala exceptuando algunas cosas. La habitación era grande y espaciosa, además estaba todo muy limpio. Lo malo es que la cama era muy incómoda y con muchos muelles, pero nos lo solucionaron ese mismo día y pudimos dormir decentemente. A pesar de ello, creo que un hotel de estas características debería tener una cama mucho mejor.  Nos vamos descontentos con el tema del todo incluido. Las bebidas eran muy malas. La comida no estaba mala de sabor, pero faltaba variedad en el almuerzo ya que durante los días que estuvimos comimos casi lo mismo. En la cena si que ponían algo más diferente. Los desayunos estaban muy bien pero desde las 10 empiezan a quitar las comida, algo que creo que no debería suceder…,2019-12-01,"dic.","Invierno","Sol Arona Tenerife","Sol"
10  No es la primera vez que me hospedo por lo que me parece

Would greatly appreciate some help with this error as I am not able to solve it. Thank you in advance1

Body:
The commentario part of your .csv file have no quotes "" and use commas , which are usually used to separate the text into columns from functions to read .csv files. .csv is abbreviated for comma separated values. Now, the separation algorithm gets confused because it doesn't know, whether a comma is part of a comment or should be used to separate into a column.

You could use readLines to juest read the plain lines. Then you may use gsub with a regex that converts the "hot" commas (where to separate) into something different, e.g. ;, which you then use to separate into columns.

Try the following.

A <- readLines(con <- file("V:/commentarios.csv"))
close(con)

## enquote dates
csv <-  gsub('(.*)(\\d{4}-\\d{2}-\\d{2})(.*)"', '\\1\\"\\2\\"\\3', A)

## convert "hot" commas into ";"
csv <-  gsub('\\"\\,\\"', '\\"\\;\\"', csv)
## convert "hot" commas that appear before a date
csv <-  gsub('\\,\\"', '\\;\\"', csv)

## finally read the .csv
res <- read.csv(text=csv, header=TRUE, sep=";", quote="")
#            Comentario     X.Fecha. X.Mes. X.Estación.             X.Hotel. X.Marca.
# 1  1   No todas la... "2020-02-01" "feb."  "Invierno" "Sol Arona Tenerife"     "Sol
# 2  2   Me he ido c... "2019-11-01" "nov."     "Otoño" "Sol Arona Tenerife"     "Sol
# 3  3   Hotel norma... "2019-09-01" "sep."    "Verano" "Sol Arona Tenerife"     "Sol
# 4  4   Tenemos dos... "2020-02-01" "feb."  "Invierno" "Sol Arona Tenerife"     "Sol
# 5  5   habitacion ... "2020-01-01" "ene."  "Invierno" "Sol Arona Tenerife"     "Sol
# 6  6   Bastante bi... "2019-12-01" "dic."  "Invierno" "Sol Arona Tenerife"     "Sol
# 7  7   Tuvimos el ... "2019-12-01" "dic."  "Invierno" "Sol Arona Tenerife"     "Sol
# 8  8   puede parec... "2019-01-01" "ene."  "Invierno" "Sol Arona Tenerife"     "Sol
# 9  9   Nos alojamo... "2019-12-01" "dic."  "Invierno" "Sol Arona Tenerife"     "Sol
# 10 10  No es la pr...


问:
Javac is not same version as java
Linux Mint 19.3

In file etc/profile:

```<code>export PATH=$PATH:$JAVA_HOME/bin
</code>```

run set in terminal:

```<code>JAVA_HOME=/usr/java/jdk1.8.0_251
PATH=/usr/java/jdk1.8.0_251/bin
</code>```

In terminal run

```<code>java -version

java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
</code>```

It's correct.

But when I run

javac -version I get another version.

```<code>javac 11.0.7
</code>```

I need javac to be version 1.8 (same as java)

答:
Root cause of the problem is due to JAVA_HOME being added at the end of the PATH.

The problem can be fixed by adding JAVA_HOME to beginning of PATH, as follows:

```<code>export PATH=$JAVA_HOME/bin:$PATH
</code>```

Working example:

Suppose that JDK 11 is installed in /opt/jdk-11 directory.
Here are the steps to use java version 11 for both java and javac:

1. Update JAVA_HOME and PATH

```<code>export JAVA_HOME=/opt/jdk-11
export PATH=$JAVA_HOME/bin:$PATH
</code>```

2. Verify that both java and javac are picked from /opt/jdk-11/bin

```<code>$ which java
/opt/jdk-11/bin/java

$ which javac
/opt/jdk-11/bin/javac
</code>```

3. Verify the output of java and javac

```<code>$ java -version
java version "11.0.7" 2020-04-14 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.7+8-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.7+8-LTS, mixed mode)

$ javac -version
javac 11.0.7
</code>```

Title: Javac is not same version as java

Body:
Linux Mint 19.3

In file etc/profile:

export PATH=$PATH:$JAVA_HOME/bin

run set in terminal:

JAVA_HOME=/usr/java/jdk1.8.0_251
PATH=/usr/java/jdk1.8.0_251/bin

In terminal run

java -version

java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)

It's correct.

But when I run

javac -version I get another version.

javac 11.0.7

I need javac to be version 1.8 (same as java)

Body:
Root cause of the problem is due to JAVA_HOME being added at the end of the PATH.

The problem can be fixed by adding JAVA_HOME to beginning of PATH, as follows:

export PATH=$JAVA_HOME/bin:$PATH

Working example:

Suppose that JDK 11 is installed in /opt/jdk-11 directory.
Here are the steps to use java version 11 for both java and javac:

1. Update JAVA_HOME and PATH

export JAVA_HOME=/opt/jdk-11
export PATH=$JAVA_HOME/bin:$PATH

2. Verify that both java and javac are picked from /opt/jdk-11/bin

$ which java
/opt/jdk-11/bin/java

$ which javac
/opt/jdk-11/bin/javac

3. Verify the output of java and javac

$ java -version
java version "11.0.7" 2020-04-14 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.7+8-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.7+8-LTS, mixed mode)

$ javac -version
javac 11.0.7


问:
Details about the specification of the function "strcpy'' and possible solution
I want to copy string from the line into strs

```<code>#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;

#define N 100
void readAndWrite();

int main() {
    readAndWrite();
    return 0;
}

void readAndWrite() {
    fstream in;
    char* strs[100];
    for (int i = 0; i < N; i++) {
        strs[i] = (char*)calloc(128,sizeof(char));
    }

    in.open("A.in");
    if (!in) {
        cout << "fail" << endl;
        exit(-1);
    }

    char line[128];
    in.getline(line, 128);
    **strcpy(strs[0], line);**
    cout << "line:" << strs[0] << endl;

    int count = 1;
    while (!in.eof()) {
        in.getline(line, 128);
        **strcpy(strs[count++], line);**
        cout << "line:" << strs[count - 1] << endl;
    }
}
</code>```

I got a report that strcpy is unsafe,which shows that

"strs [0]" may be "0": This does not conform to the specification of
  the function "strcpy".

how can I make my code work

答: You forgot to check the return value of calloc, that's why the compiler is telling you it might be zero (null), in case there is insufficient memory available to allocate.

Body:
I want to copy string from the line into strs

#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;

#define N 100
void readAndWrite();

int main() {
    readAndWrite();
    return 0;
}

void readAndWrite() {
    fstream in;
    char* strs[100];
    for (int i = 0; i < N; i++) {
        strs[i] = (char*)calloc(128,sizeof(char));
    }

    in.open("A.in");
    if (!in) {
        cout << "fail" << endl;
        exit(-1);
    }

    char line[128];
    in.getline(line, 128);
    **strcpy(strs[0], line);**
    cout << "line:" << strs[0] << endl;

    int count = 1;
    while (!in.eof()) {
        in.getline(line, 128);
        **strcpy(strs[count++], line);**
        cout << "line:" << strs[count - 1] << endl;
    }
}

I got a report that strcpy is unsafe,which shows that

"strs [0]" may be "0": This does not conform to the specification of
  the function "strcpy".

how can I make my code work


问:
Calling server function using jquery and returning with result
I have created a treeview which has function to move the nodes up / down. The function to move up / down is called in jquery. The jQuery code is

```<code> $("#move_up").live("click", function(e) {
            var rqdInstnId = GetRequiredId();
            $.post("/Instruction/MoveInstruction", { docId: DocId, instnId: rqdInstnId, action: "MoveUp" });
        });
</code>```

I need to reflect the changes in the treeview after the function is performed. Now the treeview is loaded to a div. Can this be attained by using iframe? Please clarify me on this.

答:
Use something like:

```<code>$(this).insertBefore($(this).prev());
</code>```

http://api.jquery.com/insertBefore/

ContentLicense: CC BY-SA 3.0

Body:
I have created a treeview which has function to move the nodes up / down. The function to move up / down is called in jquery. The jQuery code is

 $("#move_up").live("click", function(e) {
            var rqdInstnId = GetRequiredId();
            $.post("/Instruction/MoveInstruction", { docId: DocId, instnId: rqdInstnId, action: "MoveUp" });
        });

I need to reflect the changes in the treeview after the function is performed. Now the treeview is loaded to a div. Can this be attained by using iframe? Please clarify me on this.

Body:
Use something like:

$(this).insertBefore($(this).prev());

http://api.jquery.com/insertBefore/


问:
python cmd.Cmd dynamically add a command
I am trying to build a cli framework where commands need to be added to dynamically. What I want to achieve is - I will have a minimum class which inherit from cmd.Cmd and later on I will write my commands in separate classes and load those commands along with main classes.

The following is what I tried but while trying to execute the command showmore, it throw TypeError

```<code>import cmd

class MyExtraCmds(cmd.Cmd):

  def do_showmore(self, *args):
    print (type(self))
    print ("Show more command")

class MyCmd(cmd.Cmd):

  def __init__(self, target=None, user=None, passwd=None):
    cmd.Cmd.__init__(self)

  def do_show(self, *args):
    print (type(self))
    print ("Show command")

  def do_EOF(self, line):
    return True

if __name__ == "__main__":
    setattr(  MyCmd, 'do_showmore', MyExtraCmds.do_showmore)
    print (dir(MyCmd))
    target = MyCmd()
    target.cmdloop()
</code>```

答:
For me it works when I just set it with the equal operator. It does work as a valid command.

```<code>p = MyCmd()
p.do_extra = extra_command
p.cmdloop()
</code>```

and I found a workaround to make it work for autocomplete and help.
Reimplement get_names() in your class (I don't know why they used self.class instead of self there)

```<code>class MyCmd(cmd.Cmd):
  def get_names(self):
    return dir(self)
</code>```

Body:
I am trying to build a cli framework where commands need to be added to dynamically. What I want to achieve is - I will have a minimum class which inherit from cmd.Cmd and later on I will write my commands in separate classes and load those commands along with main classes.

The following is what I tried but while trying to execute the command showmore, it throw TypeError

import cmd

class MyExtraCmds(cmd.Cmd):

  def do_showmore(self, *args):
    print (type(self))
    print ("Show more command")

class MyCmd(cmd.Cmd):

  def __init__(self, target=None, user=None, passwd=None):
    cmd.Cmd.__init__(self)

  def do_show(self, *args):
    print (type(self))
    print ("Show command")

  def do_EOF(self, line):
    return True

if __name__ == "__main__":
    setattr(  MyCmd, 'do_showmore', MyExtraCmds.do_showmore)
    print (dir(MyCmd))
    target = MyCmd()
    target.cmdloop()

Body:
For me it works when I just set it with the equal operator. It does work as a valid command.

p = MyCmd()
p.do_extra = extra_command
p.cmdloop()

and I found a workaround to make it work for autocomplete and help.
Reimplement get_names() in your class (I don't know why they used self.class instead of self there)

class MyCmd(cmd.Cmd):
  def get_names(self):
    return dir(self)


问:
ImportError: No module named eventlet
I have installed eventlet library in python using : pip install eventlet. But when I tried to import eventlet this error occured:

```<code>$python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import eventlet
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named eventlet
</code>```

I tried to install it again but I got this :

```<code>$pip install eventlet
Requirement already satisfied (use --upgrade to upgrade): eventlet in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/eventlet-0.18.1-py3.5.egg
Requirement already satisfied (use --upgrade to upgrade): greenlet>=0.3 in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/greenlet-0.4.9-py3.5-macosx-10.6-intel.egg (from eventlet)
</code>```

How to rectify this error?

P.S : I am using Python 2.7

答:
```<code>$pip install eventlet
</code>```

This worked for me in windows10

Title: ImportError: No module named eventlet

Body:
I have installed eventlet library in python using : pip install eventlet. But when I tried to import eventlet this error occured:

$python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import eventlet
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named eventlet

I tried to install it again but I got this :

$pip install eventlet
Requirement already satisfied (use --upgrade to upgrade): eventlet in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/eventlet-0.18.1-py3.5.egg
Requirement already satisfied (use --upgrade to upgrade): greenlet>=0.3 in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/greenlet-0.4.9-py3.5-macosx-10.6-intel.egg (from eventlet)

How to rectify this error?

P.S : I am using Python 2.7

Body:
$pip install eventlet

This worked for me in windows10


问:
Returning multiple value through beforeShowDay in JQuery datePicker
I have been trying to disable multiple dates through beforeShowDay, some of them are dates and some are days of week.

Unfortunately I am only able to disable either of them.

```<code>var unavailableDates = ["2/6/2020", "4/6/2020"];

beforeShowDay: function(date) {
    // Disabling Sundays
    var day = date.getDay();
    return [day != 0,''];
    // Disabling Dates Array
    findDate = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
    if ($.inArray(findDate, unavailableDates) == -1) {
        return [true, ""];
    } else {
        return [false, "", "Unavailable"];
    }
}
</code>```

PS, I need all the Sundays to be disabled by default but dates only if found in array.

答:
Please try below code where in I am disabling the dates which are in Array as well as adding highlight class to the date element.

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />

    <form>

    </form>

```

Body:
I have been trying to disable multiple dates through beforeShowDay, some of them are dates and some are days of week.

Unfortunately I am only able to disable either of them.

var unavailableDates = ["2/6/2020", "4/6/2020"];

beforeShowDay: function(date) {
    // Disabling Sundays
    var day = date.getDay();
    return [day != 0,''];
    // Disabling Dates Array
    findDate = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
    if ($.inArray(findDate, unavailableDates) == -1) {
        return [true, ""];
    } else {
        return [false, "", "Unavailable"];
    }
}

PS, I need all the Sundays to be disabled by default but dates only if found in array.

Body:
Please try below code where in I am disabling the dates which are in Array as well as adding highlight class to the date element.

<html>

<head>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <script>
        $(function () {
           var dateArray  = [ "2020-03-17", "2020-03-18","2020-03-20"];
            $("#datepicker").datepicker({
                dateFormat: 'yy-mm-dd',
                beforeShowDay: function (date) {
                    var day = date.getDay();
                    // First convert all values in dateArray to date Object and compare with current date
                    var dateFound =  dateArray.find(function(item) {
                        var formattedDate = new Date(item);
                        return date.toLocaleDateString() === formattedDate.toLocaleDateString();
                    })
                     // check if date is in your array of dates
                    if(dateFound) {
                        // if it is return the following.
                        return [false, 'css-class-to-highlight', 'tooltip text'];
                    } else {
                        // default
                        // Disable all sundays
                        return [(day != 0), '', ''];
                    }

                }
            });

        });
    </script>
    <style type="text/css">

        .css-class-to-highlight a{
           background-color: blue !important;
           color: #fff !important;
        }
    </style>
</head>

<body>
    <form>
        <div>
           <div id="datepicker"></div>
        </div>
    </form>
</body>

</html>


问:
Error getting the value and key of a Combo Box in C#
I honestly can't find and don't see a solution to this error. I go to you to help me solve it.

What it does is when one select select get the url extension and then call it. how is this possible?

My code:

```<code>Dictionary<string, string> ldict = new Dictionary<string, string>();
ldict.Add("USA", ".com");
ldict.Add("MEX", ".com.mx");
ldict.Add("ESP", ".es");
ldict.Add("CAN", ".ca");
ldict.Add("FRA", ".fr");
ldict.Add("UKA", ".co.uk");
ldict.Add("ITA", ".it");
CountryCombo.DataSource = ldict.ToList();
CountryCombo.ValueMember = "Value";
CountryCombo.DisplayMember = "Key";
CountryCombo.SelectedIndex = 0;
</code>```

How do I get the value and the key to make a call like this:

```<code>string key = ((KeyValuePair)CountryCombo.SelectedItem).Key;
string value = ((KeyValuePair)CountryCombo.SelectedItem).Value;
</code>```

答:
Use a list based on the key collection as your datasource

```<code>CountryCombo.DataSource = new List<string>(ldict.Keys);
</code>```

Then use selected item as the key for the dictionary to get your 'value':

```<code>var value = ldict[(string)CountryCombo.SelectedItem];
</code>```

Body:
I honestly can't find and don't see a solution to this error. I go to you to help me solve it.

What it does is when one select select get the url extension and then call it. how is this possible?

My code:

Dictionary<string, string> ldict = new Dictionary<string, string>();
ldict.Add("USA", ".com");
ldict.Add("MEX", ".com.mx");
ldict.Add("ESP", ".es");
ldict.Add("CAN", ".ca");
ldict.Add("FRA", ".fr");
ldict.Add("UKA", ".co.uk");
ldict.Add("ITA", ".it");
CountryCombo.DataSource = ldict.ToList();
CountryCombo.ValueMember = "Value";
CountryCombo.DisplayMember = "Key";
CountryCombo.SelectedIndex = 0;

How do I get the value and the key to make a call like this:

string key = ((KeyValuePair)CountryCombo.SelectedItem).Key;
string value = ((KeyValuePair)CountryCombo.SelectedItem).Value;

Body:
Use a list based on the key collection as your datasource

CountryCombo.DataSource = new List<string>(ldict.Keys);

Then use selected item as the key for the dictionary to get your 'value':

var value = ldict[(string)CountryCombo.SelectedItem];


问:
Separator to make binary literals look cleaner
I am trying to write binary literals in a cleaner format.

I understand that the following can be done for integer literals:

```<code>int x = 1234_5678_9999;
</code>```

I assumed this would work for binary literals, so I tried:

```<code>uint32_t branch_bitmask = 0b0000_1111_0000_0000_0000_0000_0000_0000;
</code>```

Which gives me an "invalid suffix" error for everything past the first underscore.

Is there an alternative to underscores that would allow me to write the binary literal in a cleaner way than just:

```<code>uint32_t branch_bitmask = 0b00001111000000000000000000000000;
</code>```

答:
If you always have the same number of bits (32 in your example) you could #define a macro a bit like this:

#define BITS32(b1,b2,b3,b4,b5,b6,b7,b8) ( \
  ((b1) << 28) + \
  ((b2) << 24) + \
  ((b3) << 20) + \
  ((b4) << 16) + \
  ((b5) << 12) + \
  ((b6) << 8) + \
  ((b7) << 4) + \
  (b8))
```
<p>and then call it like this:</p>
<pre class="lang-c prettyprint-override"><code>uint32_t branch_bitmask = BITS32(0b0000,0b1111,0b0000,0b0000,0b0000,0b0000,0b0000,0b0000);
</code>```

or you can go further and use ## in the macro to prepend the 0b.

But the simple answer for me has always been to use hexadecimal, as one hex digit is 4 bits.

uint32_t branch_bitmask = 0x0F000000;
```

Body:
I am trying to write binary literals in a cleaner format.

I understand that the following can be done for integer literals:

int x = 1234_5678_9999;

I assumed this would work for binary literals, so I tried:

uint32_t branch_bitmask = 0b0000_1111_0000_0000_0000_0000_0000_0000;

Which gives me an "invalid suffix" error for everything past the first underscore.

Is there an alternative to underscores that would allow me to write the binary literal in a cleaner way than just:

uint32_t branch_bitmask = 0b00001111000000000000000000000000;

Body:
If you always have the same number of bits (32 in your example) you could #define a macro a bit like this:

#define BITS32(b1,b2,b3,b4,b5,b6,b7,b8) ( \
  ((b1) << 28) + \
  ((b2) << 24) + \
  ((b3) << 20) + \
  ((b4) << 16) + \
  ((b5) << 12) + \
  ((b6) << 8) + \
  ((b7) << 4) + \
  (b8))

and then call it like this:

uint32_t branch_bitmask = BITS32(0b0000,0b1111,0b0000,0b0000,0b0000,0b0000,0b0000,0b0000);

or you can go further and use ## in the macro to prepend the 0b.

But the simple answer for me has always been to use hexadecimal, as one hex digit is 4 bits.

uint32_t branch_bitmask = 0x0F000000;


问:
scipy.optimize.minimize can't find least square solution
My intention was to solve the l1 error fitting problem using scipy.optimize as suggested in L1 norm instead of L2 norm for cost function in regression model, but I keep getting the wrong solution, so I debugged using least square which we know how to get a closed-form expression:

```<code>n=10
d=2
A = np.random.rand(n,d)
x = np.random.rand(d,1)
b = np.dot(A, x)
x_hat = np.linalg.lstsq(A, b)[0]
print(np.linalg.norm(np.dot(A, x_hat)-b))

def fit(X, params):
    return X.dot(params)

def cost_function(params, X, y):
    return np.linalg.norm(y - fit(X, params))

x0 = np.zeros((d,1))

output = minimize(cost_function, x0, args=(A, b))

y_hat = fit(A, output.x)
print(np.linalg.norm(y_hat-b))
print(output)
</code>```

The output is:

```<code>4.726604209672303e-16
2.2714597315189407
      fun: 2.2714597315189407
 hess_inv: array([[ 0.19434496, -0.1424377 ],
       [-0.1424377 ,  0.16718703]])
      jac: array([ 3.57627869e-07, -2.98023224e-08])
  message: 'Optimization terminated successfully.'
     nfev: 32
      nit: 4
     njev: 8
   status: 0
  success: True
        x: array([0.372247  , 0.32633966])
</code>```

which looks super weird because it can't even solve the l2 regression? Am I making stupid mistakes here?

答:
The error is due to mismatching shapes. Minimize's x0 and the iterates have shape (n,). So when params has shape (n,), fit(X,params) will be shape (n,) while your y has shape (n,1). Thus, the expression y-fit(X,params) has shape (n,n) due to numpy's implicit broadcasting. And in consequence np.linalg.norm returns the frobenius matrix norm instead of the euclidean vector norm.

Solution: change your cost function to:

```<code>def cost_function(params, X, y):
    return np.linalg.norm(y - fit(X, params.reshape(d,1)))
</code>```

Body:
My intention was to solve the l1 error fitting problem using scipy.optimize as suggested in L1 norm instead of L2 norm for cost function in regression model, but I keep getting the wrong solution, so I debugged using least square which we know how to get a closed-form expression:

n=10
d=2
A = np.random.rand(n,d)
x = np.random.rand(d,1)
b = np.dot(A, x)
x_hat = np.linalg.lstsq(A, b)[0]
print(np.linalg.norm(np.dot(A, x_hat)-b))

def fit(X, params):
    return X.dot(params)

def cost_function(params, X, y):
    return np.linalg.norm(y - fit(X, params))

x0 = np.zeros((d,1))

output = minimize(cost_function, x0, args=(A, b))

y_hat = fit(A, output.x)
print(np.linalg.norm(y_hat-b))
print(output)

The output is:

4.726604209672303e-16
2.2714597315189407
      fun: 2.2714597315189407
 hess_inv: array([[ 0.19434496, -0.1424377 ],
       [-0.1424377 ,  0.16718703]])
      jac: array([ 3.57627869e-07, -2.98023224e-08])
  message: 'Optimization terminated successfully.'
     nfev: 32
      nit: 4
     njev: 8
   status: 0
  success: True
        x: array([0.372247  , 0.32633966])

which looks super weird because it can't even solve the l2 regression? Am I making stupid mistakes here?

Body:
The error is due to mismatching shapes. Minimize's x0 and the iterates have shape (n,). So when params has shape (n,), fit(X,params) will be shape (n,) while your y has shape (n,1). Thus, the expression y-fit(X,params) has shape (n,n) due to numpy's implicit broadcasting. And in consequence np.linalg.norm returns the frobenius matrix norm instead of the euclidean vector norm.

Solution: change your cost function to:

def cost_function(params, X, y):
    return np.linalg.norm(y - fit(X, params.reshape(d,1)))


问:
How to pass variable name from a file and use that variable in script in unix
I have a config file in unix as

```<code>Variable_name:sequences:Status
ABC:1234:/path/txt

and I have a script in unix as

$ABC="select * from table"
</code>```

I want to pass the variable name from file and use the variable in script with the value in script.

so I need to run script like

```<code>for i in /path/file_config;
 $Variable=ABC
 echo $variable # need result "select* from table"
</code>```

Please help me in this

答:
In bash (But not other shells), ${!foo} is an indirect reference that expands to the value of the variable named in $foo.

So,

```<code>ABC="select * from table"
name=ABC
echo "${!name}"
</code>```

will display select * from table

Body:
I have a config file in unix as

Variable_name:sequences:Status
ABC:1234:/path/txt

and I have a script in unix as

$ABC="select * from table"

I want to pass the variable name from file and use the variable in script with the value in script.

so I need to run script like

for i in /path/file_config;
 $Variable=ABC
 echo $variable # need result "select* from table"

Please help me in this

Body:
In bash (But not other shells), ${!foo} is an indirect reference that expands to the value of the variable named in $foo.

So,

ABC="select * from table"
name=ABC
echo "${!name}"

will display select * from table


问:
How can i get value from URL in java script
http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz

How do i get value "XYZ" from the url using javascript

答:
let url = "http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz";

let parts = url.split("/");

let final = parts[parts.length - 1];

console.log(final);```


问:
How to populate data on UI after reading from CSV file in Angular?
I am implementing angular template and I am reading CSV file data to show it in an organized table. I am not strong at core scripting part based on retrieved csv data.

I am sharing my code:

```<code>export class AppComponent implements OnInit{
  title = 'temp-app';

  public headers = [];
  public data = {};
  public strData = ''

  public selectedHeader = null;
  constructor(private fileSvc: FileService) {

  }

  ngOnInit(): void {
    this.fileSvc.getHeaders().subscribe(
      data => {
        if (data != null && data.length > 0) {
          let headers = data.split('\n');
          headers = headers.filter(x => x.trim() !== '');
          for (const item of headers) {
            this.headers.push(item.trim());
          }
          this.headers=[...new Set(this.headers)];
        } else {
          this.headers = [];
        }
      }
    );
</code>```

Service.ts

```<code>@Injectable({
  providedIn: 'root'
})
export class FileService {

  constructor(private httpClient: HttpClient) {

  }

  public getHeaders() {
    return this.httpClient.get('assets/data.csv', { responseType: 'text' });
  }

}
</code>```

Above code is not correct:
I am sharing UI, What I am accepting.

data.csv

Expected

1. Code first should read the column 1 i.e "AppName" and after reading all the rows of column 1 it should only keep the unique values and create a button using those unique values.Means - if "LDAP" is multiple times in column 1, it should only consider "LDAP" only once and using that it should create a button.
2. Similarily, create button for all remaining values of column 1.

For reference purpose one related link here:

https://stackblitz.com/edit/angular-ivy-ubcknl

Thanks in advance
In future I want to show respective value only in column. If i click on OAM then OAM column will show, If I will click on LDAP the LDAP column value will show.

答:
lets say you are getting this data from assets folder. For eg :-

```<code>return this.httpClient.get('assets/tableContent.csv', { responseType: 'text' }).pipe((map(res)=> {
                       let columns= new Set(response.split('\n').map((item) => item.replace('\r', '').split(",")[0]));
                       let rows= response.split('\n');
                       let result obj = {
                                             uniqueColumns: Array.from(columns),
                                             data: {}
                                        }
                       columns.forEach((columnName) => {
                           obj.data['columnName'] = [];
                       });
                       rows.forEach((row) => {
                              var rowItems = row.replace('\r', '').split(",");
                              obj.data[rowItems[0]].push(rowItems.slice(1));
                       });
                       return obj;
}));
</code>```

When you will subscribe to it you will get a object like below :-

```<code>{
  uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
  data: {
      'OAM': [
         ['DEV', 'OHS', 'Success'],
         ['Stage', 'OHS', 'Success']
       ],
       'LDAP': [
         ['DEV','MDS','FAIL'],
         ['DEV','DDNET','FAIL']
         //and other data
       ]
       //same for other columns
  }
}
</code>```

with the above data structure you can easily create your template using ngfor directive.

Eg:- Template Code :-

```<code><table id="mainTable">
  <thead>
    <tr>
      <th *ngFor="let head of items.uniqueColumns">{{head}}</th>
    <tr>
  </thead>
  <tbody>
    <tr>
      <td *ngFor="let head of items.uniqueColumns">
        <table id="columns">
          <tr>
            <td></td>
            <td *ngFor="let col of items.data[head]">
              <ng-container *ngFor="let items of col">
                  <td >{{items}}</td>
              </ng-container>
            </td>
          <tr>
          <tr>
            <td>Dev</td>
          </tr>
          <tr>
            <td>Stage</td>
          </tr>
        </table>
      </td>
    </tr>
  </tbody>
</table>
</code>```

CSS :-

```<code>table#mainTable,table#columns, th {
  border: 1px solid black;
}
#columns td {
  padding: 1em;
}
#columns>tr>td:not(:first-child) {
  border: 1px solid black;
}
#columns>tr>td:nth-child(2) {
  border-left: none;
}

#columns>tr:nth-child(1) {
  border-bottom: 1px solid black;
}
tr {
  padding: 1em;
}

table, td, th {
  border-collapse: collapse;
}
</code>```

Typescript :-

```<code>import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public items = {
  uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
  data: {
      'OAM': [
         ['DEV', 'OHS', 'Success'],
         ['Stage', 'OHS', 'Success']
       ],
       'LDAP': [
         ['DEV','MDS','FAIL'],
         ['DEV','DDNET','FAIL']
         //and other data
       ]
       //same for other columns
  }
}
}
</code>```

Body:
I am implementing angular template and I am reading CSV file data to show it in an organized table. I am not strong at core scripting part based on retrieved csv data.

I am sharing my code:

export class AppComponent implements OnInit{
  title = 'temp-app';

  public headers = [];
  public data = {};
  public strData = ''

  public selectedHeader = null;
  constructor(private fileSvc: FileService) {

  }

  ngOnInit(): void {
    this.fileSvc.getHeaders().subscribe(
      data => {
        if (data != null && data.length > 0) {
          let headers = data.split('\n');
          headers = headers.filter(x => x.trim() !== '');
          for (const item of headers) {
            this.headers.push(item.trim());
          }
          this.headers=[...new Set(this.headers)];
        } else {
          this.headers = [];
        }
      }
    );

Service.ts

@Injectable({
  providedIn: 'root'
})
export class FileService {

  constructor(private httpClient: HttpClient) {

  }

  public getHeaders() {
    return this.httpClient.get('assets/data.csv', { responseType: 'text' });
  }

}

Above code is not correct:
I am sharing UI, What I am accepting.

data.csv

Expected

1. Code first should read the column 1 i.e "AppName" and after reading all the rows of column 1 it should only keep the unique values and create a button using those unique values.Means - if "LDAP" is multiple times in column 1, it should only consider "LDAP" only once and using that it should create a button.
2. Similarily, create button for all remaining values of column 1.

For reference purpose one related link here:

https://stackblitz.com/edit/angular-ivy-ubcknl

Thanks in advance
In future I want to show respective value only in column. If i click on OAM then OAM column will show, If I will click on LDAP the LDAP column value will show.

Body:
lets say you are getting this data from assets folder. For eg :-

return this.httpClient.get('assets/tableContent.csv', { responseType: 'text' }).pipe((map(res)=> {
                       let columns= new Set(response.split('\n').map((item) => item.replace('\r', '').split(",")[0]));
                       let rows= response.split('\n');
                       let result obj = {
                                             uniqueColumns: Array.from(columns),
                                             data: {}
                                        }
                       columns.forEach((columnName) => {
                           obj.data['columnName'] = [];
                       });
                       rows.forEach((row) => {
                              var rowItems = row.replace('\r', '').split(",");
                              obj.data[rowItems[0]].push(rowItems.slice(1));
                       });
                       return obj;
}));

When you will subscribe to it you will get a object like below :-

{
  uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
  data: {
      'OAM': [
         ['DEV', 'OHS', 'Success'],
         ['Stage', 'OHS', 'Success']
       ],
       'LDAP': [
         ['DEV','MDS','FAIL'],
         ['DEV','DDNET','FAIL']
         //and other data
       ]
       //same for other columns
  }
}

with the above data structure you can easily create your template using ngfor directive.

Eg:- Template Code :-

<table id="mainTable">
  <thead>
    <tr>
      <th *ngFor="let head of items.uniqueColumns">{{head}}</th>
    <tr>
  </thead>
  <tbody>
    <tr>
      <td *ngFor="let head of items.uniqueColumns">
        <table id="columns">
          <tr>
            <td></td>
            <td *ngFor="let col of items.data[head]">
              <ng-container *ngFor="let items of col">
                  <td >{{items}}</td>
              </ng-container>
            </td>
          <tr>
          <tr>
            <td>Dev</td>
          </tr>
          <tr>
            <td>Stage</td>
          </tr>
        </table>
      </td>
    </tr>
  </tbody>
</table>

CSS :-

table#mainTable,table#columns, th {
  border: 1px solid black;
}
#columns td {
  padding: 1em;
}
#columns>tr>td:not(:first-child) {
  border: 1px solid black;
}
#columns>tr>td:nth-child(2) {
  border-left: none;
}

#columns>tr:nth-child(1) {
  border-bottom: 1px solid black;
}
tr {
  padding: 1em;
}

table, td, th {
  border-collapse: collapse;
}

Typescript :-

import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public items = {
  uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
  data: {
      'OAM': [
         ['DEV', 'OHS', 'Success'],
         ['Stage', 'OHS', 'Success']
       ],
       'LDAP': [
         ['DEV','MDS','FAIL'],
         ['DEV','DDNET','FAIL']
         //and other data
       ]
       //same for other columns
  }
}
}