Etiquetas

importado (41) programación (34) desahogo (30) linux (28) cine y TV (22) humor (21) software libre (19) internet (17) música (13) móviles (12) videojuegos (8) English (7) libros (6) vodafone (6) google (5) java (5) libreoffice (3) openoffice (3) consumismo (2) desarrollo con qt en nokia 5800 (2) economía (2) nokia (2) qt (2) c++ (1) ciencia (1)
Mostrando entradas con la etiqueta English. Mostrar todas las entradas
Mostrando entradas con la etiqueta English. Mostrar todas las entradas

12/09/2014

C++: consts and const references and const pointers and const methods, oh my!

C++ is powerful. But it has some concepts that seem easy to understand... until you actually use them for the first time. This is a compilation of some of my head-scratching moments while grasping C++ capabilities that are foreign to C programmers like me.

References

Declare a variable with "&" and it is a reference. Think of a C pointer ("*"), but it can not be NULL and you can not cast it to reference another type (the case of C's malloc() returned void pointer). Examples:
    // With a basic type
    int number = 3;
    int &reference = number;
    cout << reference << endl; // Prints 3
    reference = 1;
    cout << number << endl; // Now it prints 1

    // With a class instance
    string stringInstance = "Hi!";
    string &stringReference = stringInstance;
    cout << stringReference.size() << endl; // Note we are not using the "->"
                                            //  operator! It is not a pointer.
References in method declarations allow you to pass the instance itself instead of the value
/* Reverse a string in place, avoiding copies */
void reverse(string input){
    for (int i = 0, j = input.size() - 1; i < j; ++i, --j){
        char tmp = input[i];
        input[i] = input[j];
        input[j] = tmp;
    }
}
That didn't do anything to the real "input" string. This is C++, so "input" is an instance of the class "string" and not a pointer. The method reverse() has been working on a copy of the class instance that was destroyed as soon as the method finished! Solution? We could pass a pointer (string *input) and go crazy like in C, but then we would have to check for NULL pointers, use the "->" operator and who knows what else. The C++ way? Use a reference!
/* Reverse a string in place, avoiding copies */
void reverse(string &input){
    for (int i = 0, j = input.size() - 1; i < j; ++i, --j){
        char tmp = input[i];
        input[i] = input[j];
        input[j] = tmp;
    }
}
No changes required to the method body. It is also required for optimization, cause it avoids a deep copy of the instance's internal structure.

Const

The qualifier "const" (which also exists in C) can be mostly read as "readonly" (think Java's "final"). It effects whatever is on its left. If there is nothing on its left, then it effects the first thing on its right. So this is a mistake:
const int const *p = ...; // Compiler error, duplicate const!
Now the caveats:
    const int number = 2; // int value is readonly now
    int &reference = number; // Compiler error: "int &" requires
                             // an "int", not a "const int"
Fix:
    const int number = 2;
    const int &reference = number; // But now "reference = 1;" is an error, careful!
Note that "const int & reference" and "int const & reference" is the same thing (remember, left unless there's nothing, if so, right). What if we start moving the const modifier around?
   int & const reference = number; // Compiler error: const attempts
                                    // to modify the reference itself (&),
                                    // but references are always readonly!

Const and pointers

A C refresher. Remember: const affects that on its left, including the pointer (*) itself.
    // With a basic type
    int number = 2;
    const int *p = &number;
    *p = 3;   // Compiler error: the value is readonly!
    int * const pp = &number;
    *pp = 3;    // OK
    pp = &argc; // Compiler error, the pointer is readonly!

Const and method declarations

Const applies also to method arguments:
void clearString(const string & input){
    cout << "Deleting this many characters: " << input.size() << endl;
    input.clear();  // Compiler error: the instance is readonly!
}
Wait... how did the C++ compiler know the method clear() would change the string, and size() wouldn't? Hardcore static code analysis? AI? Magic? Not really. Const has another use: specifying which member methods in a class change no values and hence are safe to be called when the class is readonly. This is the declaration of the size() method in string, note the const after the parenthesis:
// Capacity:
///  Returns the number of characters in the string, not including any
///  null-termination.
size_type size() const
{
    return _M_rep()->_M_length;
}
That use of const is exclusive to objects. It will throw a compiler error if you try to use it in a function declaration that does not belong to a class.

Done for today. Hope it helped you!

2/03/2011

Scammer sells Blender

From Blender Nation:

With the success of blender.org projects, and publishing all the exciting Blender releases, we’re now being challenged by third parties who like to ride the waves and do business with Blender.

There’s nothing wrong with that. In its very nature, GNU GPL is about freedom, the freedom not only to use and modify the sources, but also to distribute and resell our releases under another brand name.

Recently we received several concerned emails and forum postings from people who were worried about Blender resellers using especially Ebay to sell Blender.

In this case, the products 3DMagix and IllusionMage are just rebranded Blender material, sold at a price with lots of wrong info. And even more, they use copyrighted images with no authorization, including pictures like a render of a Final Fantasy X character!

And helping here as it's asked in the Blender Nation article:

3DMagix, 3DMagixPro, IllusionMage, scam

1/11/2011

Compilando gSOAP en HP-UX / Compiling gSOAP on HP-UX

El siguiente error al compilar gSOAP en HP-UX significa que el m4 instalado en la máquina es el de serie. Hay que instalar la versión GNU.

The following error when compiling gSOAP on HP-UX means that the m4 tool in use is HP's. You need to install and use the GNU version.

bison -y  -d -v `test -f 'soapcpp2_yacc.y' || echo './'`soapcpp2_yacc.y
conflicts: 1 shift/reduce
gmake[4]: *** [soapcpp2_yacc.c] Error 141

11/16/2010

El virus de la locura

Interesantísimo artículo sobre la investigación de la esquizofrenia y esclerosis múltiple:

http://discovermagazine.com/2010/jun/03-the-insanity-virus/article_view?b_start:int=3&-C=


El investigador de esquizofrenia Fuller Torrey (cuya hermana Rhoda sufre esa enfermedad) realizó estudios sobre la presencia de retrovirus en pacientes esquizofrénicos. Sus razones para sospechar de ello:

- Hay mayor riesgo de sufrir esquizofrenia en personas nacidas en invierno y comienzos de la primavera (cuando aumentan los casos de enfermedades como la gripe)
- Los brotes se producen en algunos casos tras padecer síntomas parecidos a una infección de mononucleosis.
- Se producen pérdidas de tejido cerebral en esquizofrénicos a lo largo de su vida.

La presencia de retrovirus no identificados se confirmó.

Hervé Perron, por su parte, descubrió también que había retrovirus asociados a la esclerosis múltiple. En su caso, los identificó en 1997 y llegó a la conclusión de que todos tenemos retrovirus presentes en nuestro ADN. Fragmentos de virus presentes en nuestros genes desde que antepasados nuestros anteriores a los monos sufriesen la infección de un virus que llegó a las células que producen el esperma y los óvulos. Han llegado a contar 100.000 retrovirus distintos presentes en el ADN humano por esa herencia. Un 5% de nuestro ADN, que hasta ahora se consideraban fragmentos "muertos", o inútiles.

Esas cadenas víricas están normalmente inhibidas por secuencias de proteinas en el ADN que impiden que se extiendan a otras partes de nuestro organismo. Pero en el caso de la esquizofrenia y la esclerosis múltiple, ese aislamiento se rompería debido a enfermedades cuyos virus "liberan" al retrovirus que llevamos en el ADN. De ahí la coincidencia en el aumento de riesgo para los nacidos en épocas de mayor riesgo infeccioso.

Para apoyar esa teoría, en el artículo se citan casos como el de un esquizofrénico cuyo gemelo no desarrolló esa patología. ¿La razón? Después de nacer pasó más tiempo en el hospital debido a una infección que su gemelo sano no sufrió. Una infección cuyo virus causó la propagación del retrovirus causante de su esquizofrenia, que se manifestaría completamente 20 años más tarde tras sufrir un retraso en su desarrollo mental durante la infancia.

Tras estos descubrimientos se están realizando pruebas en animales que mejorarían notablemente la prevención y tratamiento de la esquizofrenia y la esclerosis múltiple en humanos. Mediante vacunas post-parto, antivíricos específicos en caso de infecciones en recien nacidos o anticuerpos que neutralizan proteínas del virus de la esclerosis múltiple.

Si estas teorías se confirman del todo serán un gran avance contra enfermedades cerebrales que se convierten en un infierno. Tanto para los que las sufren como para sus seres queridos.

Vía Jamie Zawinski.

10/18/2010

9/15/2009

Guessing TWAIN custom capabilities


  • 1.- Install Twirl TWAIN Probe

  • 2.- Start it and select your scanner from the combobox. Click "4 Souce Open", then "Monitor" so Twirl displays changes in every cap.

  • 3.- Make sure "Show device UI" is selected, then click "5 Source Enabled".

  • 4.- Change values you want to guess in the custom TWAIN UI, then either close it or do a full scan (depending on the maker/model, changes might be not triggered until you scan).

  • 5.- Watch changed caps in the text area, check the possible values for those caps in the caps list.

  • 6.- Document discovered information, test in custom program and enjoy!



Thanks to spike from Dosadi for the excelent tool that is Twirl.



1/18/2006

Shadow of the Colossus: cómo se hizo

Shadow of the Colossus es el último juego para PlayStation 2 del estudio que creó ICO. Su lanzamiento en España tendrá lugar (si no hay cambios) el 15 de febrero.

La manera en que Shadow of the Colossus explota la maquinaria de la PS2 resulta increíble, con gigantes que miden decenas de metros de alto cubiertos de pelo, paisajes sin fin y una iluminación impresionante. Aunque se producen algunas ralentizaciones cuando la cámara muestra panorámicas de paisajes o el interior del templo del principio, sigue pareciendo extraordinario que semejantes imágenes se puedan generar con una consola lanzada hace ya 6 años.

Para comprender mejor cómo se ha llegado al resultado final, los creadores del juego publicaron un artículo explicando la parte técnica. Originalmente en japonés, existe una traducción al inglés publicada en los foros de Beyond3D. Por desgracia no tiene las imágenes incluídas en el cuerpo de la traducción, pero aquí está arreglado.

Actualización: Traducción completa al inglés, con imágenes.