Q:

Redundant indirect object pronoun: is "le" redundant in "preguntémosle al estúpido / a él"?

This is a canonical question / Esta es una pregunta canónica

In a movie scene from "Revenge" ("La Venganza", 1990, with Kevin Costner) the character Tiburón Méndez was discussing a political campaign with 2 guests at the 30 minute point (for context, see Italian version, they mention it by 00:53). I heard the following (translated/dubbed from English to Spanish):

Preguntémosle al estúpido.

In subtitles it was the following:

Vamos a preguntarle al estúpido.

I know that both are correct grammatically, of course.
QUESTION - Am I correct to say that the use of "le" in the above sentences is optional? While if one used "a él" instead of "al estúpido", you would definitely have to use the redundant "le"?
On what am I basing this? I have seen the following sentences as examples on Lawless Spanish's Redundant Object Pronouns, in which the use of "le" was stated to be optional:

[Le] estoy hablando a mi hermano. (I'm talking to my brother.)
[Le] traigo unos libros a la escuela. (I'm taking some books to the school.)
Mi idea [le] pareció al profesor la más interesante. (My idea seemed the most interesting to the teacher.)

While from What's the difference between “ti” and “te”? I read the following:

As above, you will sometimes find both ti and te in the same sentence, referring to the same person, when they are the object of a verb. You cannot say Yo elijo a ti (without te); it's ungrammatical. You will find ti on its own when it is not the verb object:

Traje esto para ti.
"I brought this for you."

After reading What is the role of the "le" in the sentence "Miguel le dio a su novia un anillo."?, I now understand that I am correct that in the sentences I wrote, the use of "le" is completely optional. But I still have doubts whether it is obligatory to use redundant indirect object pronouns ('me', 'te', 'le') with the corresponding emphatic form of pronouns ('a mí', 'a ti', 'a él') OR whether you can do it both ways (example - "Te pregunto a ti" = "pregunto a ti").

A:

TL;DR
The redundant le is only optional if a noun acts as indirect object and that noun is placed after the verb: otherwise, it is mandatory. However, in spoken speech, the redundant le is almost always used.

First a disclaimer: this is actually a complicated topic, which is treated in detail in Section 16.14 of RAE's Nueva gramática de la lengua española, which spans 7 pages. In this answer, I give an overview of the general rules, but I cannot cover all the exceptions mentioned in the NGLE. In most of the answer, I use a different source (also from RAE), which is easier to read.
There seem to be different opinions about whether redundant le is required there (partly due to different usage in different areas), but Javi's comment to this answer provides this link to an "official" source (RAE/DPD), which answers your question as follows:
First question: is redundant le optional when there is also a noun acting as indirect object?
See Section 5.2 of the source. The redundant use of le is mandatory in the following cases:

when the noun that acts as indirect object appears before the verb:

Al estúpido le hemos preguntado cinco veces

when the indirect object indicates who experiments or feels the action, instead of who the action is addressed to, such as when the verb is gustar, encantar, molestar:

Le molestó a ese estúpido que le preguntáramos tantas veces

The use of le  in sentences where a noun acts as the indirect object is optional in all other cases, i.e., when the noun appears after the verb and indicates an addressee of the action:

Preguntémos(le) al estúpido
(Le) he regalado un libro a mi hermano

However, though optional, in spoken speech the redundant le is almost always included.
Second question: is redundant le optional when there is also a stressed pronoun (a mí, a ti, a él, a ella...) acting as indirect object?
See Section 5.1 of the source. The unstressed pronouns (pronombres átonos) me, te, le can go alone in a sentence:

Le he preguntado qué piensa

or  together with the stressed pronouns (pronombres tónicos) a mí, a ti, a él/ella:

Le he preguntado a él qué piensa

But the stressed pronouns a mí, a ti, a él/ella cannot go alone in a sentence:

He preguntado a él qué piensa

There are a few exceptions to this rule. One of them are the verbs that express direction:

Se (*le) acercó a él

where stressed pronouns must go alone. There is some discussion whether this actually is an indirect object, as it can be replaced by le if it names a person (se le acercó), but it cannot be replaced by le if it names an object (se acercó al coche). RAE's Nueva gramática de la lengua española, in its Section 16.14i, says:

No se duplican necesariamente los complementos indirectos tónicos que expresan dirección (§35.4j), por lo que se asimilan en cierta medida a los complementos de régimen. Los verbos que los seleccionan alternan las formas tónicas del complemento indirecto pronominal, sin duplicación obligatoria (Se acercó a mí, [...]) con las variantes átonas (Se me acercó, [...]). [...] Como se ha señalado, entienden algunos autores que las primeras variantes pueden interpretarse como complementos de régimen [...].

The verb parecer does not have duplication of pronouns either:

Se (*le) parece a ella

Another class of sentences where stressed pronouns go alone (without duplication) is treated in this answer. These are sentences in which the verb is ditransitive (not reflexive) and the direct object is in the first or second person. In this case, the indirect object cannot be an unstressed pronoun: it must be a stressed pronoun and cannot be duplicated:

Te (*le) venderán a él
(*Te) me recomendaron a ti
Me (*le) presentaron a él

A:

Your sentences from the movie are examples of what is called "redundancia pronominal" or "reduplicación/doblado de clíticos" ("clitic doubling"): there is an object in the canonical position ("a su novia" in your case) and also a clitic pronoun ("le" in your case) with the same syntactic function. As explained in the Enciclopedia de lingüística hispánica, by several authors, it's a phenomenon that singles out Spanish with respect to other Romance languages (but this is not exclusive of Spanish: this also happens in Catalan with a lower extent).
In your case, what is duplicated is the indirect object ("le" and "al estúpido"). This book explains that there are situations in which such indirect object duplication is mandatory and others in which it is not, although the option with duplication is by far the preferred one.
The duplication is mandatory when the object (direct or indirect) in the canonical position is constructed with a pronoun (with some exceptions). For instance:

María me llamó a mi.
Yo le di el regalo a ella.

You cannot say "María llamó a mi" or "Yo di el regalo a ella". In the same way, you can say "preguntémosle a él” or "vamos a preguntarle a él", but not "preguntemos a él” or "vamos a preguntar a él".
The exceptions to this rule are the pronouns "usted" and neutral "ello" which do not require duplication, as in these examples:

Para servir a usted.
Es cuanto tenemos que decir a usted, señor presidente. (CREA, España, 1996)
La EMT agradece a usted la utilización de sus autobuses.
Dedicaré a ello el siguiente capítulo.

In other cases, duplication of indirect object is mandatory or not depending on its semantic role: it's (relatively) optional when this object express the target or the recipient, as in this example,

María le entregó el paquete a su dueño / María entregó el paquete a su dueño

or these other examples from the book Gramática descriptiva de la lengua española, by several authors:

Le dijeron a Juan que viniera / Dijeron a Juan que viniera,
Le dieron el premio al escritor / Dieron el premio al escritor.

But duplication is mandatory when indirect object has other semantical roles: what are called experiential ("experimentantes", which means that the role of the indirect object is to convey who is experiencing or feeling what is being expressed by the verb)

Nunca le gustó realmente el cine a María (you cannot say "Nunca gustó realmente el cine a María"),

beneficiary ("beneficiarios")

María le hizo los deberes al niño (you cannot say "María hizo los deberes al niño"),
Le preparó un brebaje al enfermo (you cannot say "Preparó un brebaje al enfermo")

and (inalienable) possessor datives

Aquí le rompieron la pierna a Juan (you cannot say "Aquí rompieron la pierna a Juan"),
Le cortaron las uñas al niño (you cannot say "Cortaron las uñas al niño"),
Le duele la pierna a Pedro (you cannot say "Duele la pierna a Pedro").

Note that, in your sentences from the movie, "el estúpido" has the role of recipient or target of the verb "preguntar", so it corresponds to the case in which duplication is (relatively) optional:  as in the examples "Dieron el premio al escritor" and "Dijeron a Juan que viniera", one can also say "Preguntemos al estúpido".
But, in this other sentence from your question

Mi idea le pareció al profesor la más interesante,

"el profesor" of the indirect object is the person who is feeling what is expressed by "parecer la más interesante", so it corresponds to one of the cases in which duplication is required. That is, in this instance, you can not say "Mi idea pareció al profesor la más interesante" without the clitic "le".
And, as stated in the comment by  OnlyThenDidIReckonMyCurse, you can say both

Le traigo unos libros a mi hermana / Traigo unos libros a mi hermana,

but not "Le traigo unos libros a la escuela" because "a la escuela" is not an indirect object, but a place complement, so one cannot use a dative pronoun in this sentence.
Note also that what's being said in some answers to this other question, namely something like "I'm a native speaker and the version with the clitic pronoun le sounds better to me", completely agrees to what is explained in the above cited books in reference to the case in which the presence of the clitic pronoun is (relatively) optional:

la opción del doblado es, con mucho, la preferida

and Gramática descriptiva de la lengua española adds to this statement

Véanse Silva-Corvalán 1981 para el español chileno; Bentivoglio 1978 para el Caribe y Barrenechea y Orecchia 1977 para el bonaerense.

The book Complementos argumentales del verbo: directo, indirecto, suplemento y agente by José-Álvaro Porto Dapena, gives also an example which is similar to your sentences in the sense that an indirect object is present but there is no need of clitic pronoun. In this case, it's written without the clitic pronoun:

Nicolás regaló una moto a su hijo

(you may also perfectly say "Nicolás le regaló una moto a su hijo").
In addition, this book provides some instances of constructions that also require the presence of a clitic pronoun (this happens also in other Romance languages) without a duplication of the indirect object, namely, what are called "etic dative" ("dativo ético"), in which the presence of the clitic pronoun adds to the sentence an intensive value, expressing a greater participation of the subject in the action expressed by the verb,

Se bebieron toda la cerveza

and "possessive dative" ("dativo posesivo"), in which the clitic pronoun adds the semantical role of possession to other noun phrase present in the sentence:

Le llevaron el equipaje a la estación,
Nos ocuparon los asientos.

These are examples of a complete different phenomenon because, as you can see, there is no duplication of the indirect object in the above sentences; but it is a peculiar use of dative clitics which can give also rise to wondering about the role of such pronouns.
Notice that I've not included in the above explanation what are called "left dislocation" ("dislocación a la izquierda", for instance, "A Juan le han dado un premio") and "right dislocation" ("dislocación a la derecha", for example, "No le dieron el premio, a Juan"), which are different phenomena also requiring the presence of clitic pronouns that duplicate an indirect object and that are not characteristic of Spanish language, but are also present in other Romance languages. So, let's explain them.
Dislocations are constructions typical of oral speech, although one can also find them in written texts which do not have a high degree of formality.
A left dislocation of an object consists of a direct or indirect object (more generally, a noun phrase which acts as complement of the verb) which is written at the beginning of a sentence and then repeated in the sentence in the form of a clitic pronoun. For instance, in this example from Enciclopedia de lingüística hispánica

Ese libro ya lo he leído

what is dislocated to the left is the direct object "Ese libro": notice how such direct object is again present in the sentence by means of the pronoun "lo". An example in which the indirect object is dislocated to the left may be

A Juan le dieron un premio.

As explained in detail in Enciclopedia de lingüística hispánica, in Spanish, as in other Romance languages, we tend to transmit information in such a way that the news comes after the known things. For this reason, one frequently needs to alter the order subject-verb-complements of the sentence components, which is the one that is felt as neutral, specially in oral speech. Left dislocations is one of the resources the language has to achieve this. So, for instance, one can say to some friends

A Juan le dieron un premio

if all of them know who is Juan and the news one wants to transmit is the fact that they have been awarded a prize. But if everyone knows that a prize has been awarded and the news is who is the winner, I would said instead

Dieron el premio a Juan Goytisolo,

which in oral speech is more likely to be expressed as

Le dieron el premio a Juan Goytisolo.

Notice that left dislocations of an object (direct or indirect) require object duplication by means of a clitic pronoun. In a certain sense, you can think about this as if you have decided to put the object "out of the sentence". But, once you make such decision, you must add to the sentence a clitic that has the same syntactic role of such object, otherwise it would lack of something.
An exception to this rule explained in Enciclopedia de lingüística hispánica is when the dislocated object is an undefined noun phrase. Since Spanish lacks of undefined clitic pronouns, in this case there is not object duplication by means of a clitic, as it happens in this sentence:

Carpetas rojas, yo no he visto.

As explained in Enciclopedia de lingüística hispánica, in Spanish right dislocations are much less frequent than left dislocations, but are quite used in Italian and Catalan. In "Hablado/Parlato: aspectos
lingüísticos y discursivos de la
comunicación oral", an interesting paper by Félix San Vicente (University of Bologna) which compares these and other oral constructions in Spanish and Italian, it is even stated that  right dislocations in Spanish may sometimes seem somewhat unnatural. When you make a right dislocation of an object (direct or indirect), first of all you produce a complete sentence that contains a direct or indirect object pronoun and then you decide not to finish the sentence there, but to add the direct or the indirect objrct of the sentence for further clarification. An example of right dislocation of the direct object from Enciclopedia de lingüística hispánica is this one:

La dará la doctora Pujol, la conferencia plenaria.

And here is an example of right dislocation of the indirect object from the above cited paper by San Vicente:

No, no le han dado el alta, a Juan.

Note that in these constructions there is a direct or indirect object in the form of a clitic pronoun and then it's duplicated by expliciting such object. As explained by San Vicente in their paper, a typical situation in which right dislocation is used is a conversation in which

el hablante, debido a un gesto o movimiento por parte de su interlocutor, interpreta que la comunicación no se ha percibido del modo adecuado (por haber supuesto un conocimiento compartido, o
  bien por descuido u olvido) y recupera la información que se suponía elidida

That is, the speaker, due to a gesture or movement of their interlocutor, interprets that the communication has not been perceived in the appropriate way (because they have supposed a shared knowledge or
 either by inattention or oversight) and retrieves the information that was supposed to be elided.


Q:

Auto fill and submit forms on external site

I was wondering how does one auto fill multiple forms (using bot/local server) on multiple pages of external site (PHP) using ajax or curl.
For example a site www.abc.com/index.php has a form <form> <input name='text'></form> which takes you to the www.abc.com/fst.php when the form is submitted and there is another form on www.abc.com/fst.php that needs to be filled and submitted too. I want to automatically fill both form from my local server. How do i accomplish that?

A:

The easiest way is to using something like greasemonkey ( https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/ ), but the better solution is to use the firebug 'net' tab to capture the post sent when you fill out the form and repeat that post with CURL ( http://php.net/manual/en/book.curl.php )
function post($url,$data) {
    $process = curl_init($url);
    curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
    curl_setopt($process, CURLOPT_HEADER, 1);
    curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
    if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
    if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
    curl_setopt($process, CURLOPT_ENCODING , $this->compression);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
    curl_setopt($process, CURLOPT_POSTFIELDS, $data);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($process, CURLOPT_POST, 1);
    $return = curl_exec($process);
    curl_close($process);
    return $return;
}


Q:

PC ram size using python or windows command line

Possible Duplicate:
How to get current CPU and RAM usage in Python?

How to read pc ram size using python or wmi generator/Windows command line

A:

Check out psutil, Just a note to those using linux if you install this via a package manager just be aware of the version you are using as they are generally out of date.

https://github.com/giampaolo/psutil
psutil is a module providing an interface for retrieving information
  on all running processes and system utilization (CPU, memory, disks,
  network, users) in a portable way by using Python, implementing many
  functionalities offered by command line tools such as:

For memory specifics check out http://code.google.com/p/psutil/wiki/Documentation#Memory


Q:

3D library recommendations for interactive spatial data visualisation?

Our software produces a lot of data that is georeferenced and recorded over time.  We are considering ways to improve the visualisation, and showing the (processed) data in a 3D view, given it's georeferenced, seems a good idea.
I am looking for SO's recommendations for what 3D libraries are best to use as a base when building these kind of visualisations in a Delphi- / C++Builder-based Windows application.  I'll add a bounty when I can.
The data

Is recorded over time (hours to days) and is GPS-tagged.  So, we have a lot of data following a path over time.
Is spatial: it represents real 3D elements of the earth, such as the land, or 3D elements of objects around the earth.
Is high volume: we could have a point cloud, say, of hundreds of thousands to millions of points.  Processed data may display as surfaces created from these point clouds.

From that, you can see that an interactive, spatially-based 3D visualisation seems a good approach.  I'm envisaging something where you can easily and quickly navigate around in space, and data will load or be generated on the fly depending on what you're looking at.  I would prefer we don't try to write our own 3D library from scratch - for something like this, there have to be good existing libraries we can work from.
So, I'm hoping for a library which supports:

good navigation (is the library based on Euler rotations only, for example?  Can you 'pick' objects to rotate around or move with easily?);
modern GPUs (shader-only rendering is ok; being able to hook into the pipeline to write shaders that map values to colours and change dynamically would be great - think data values given a colour through a colour lookup table);
dynamic data / objects (data can be added as it's recorded; and if the data volume is too high, we should be able to page things in and out or recreate them, and only show a sensible subset so that whatever the user's viewport is looking at is there onscreen, but other data can be loaded/regenerated, preferably asynchronously, or at least quickly as the user navigates.  Obviously data creation is dependent on us, but a library that has hooks for this kind of thing would be great.)
and technologically, works with Delphi / C++Builder and the VCL.

Libraries
There are two main libraries I've considered so far - I'm looking for knowledgeable opinions about these, or for other libraries I haven't considered.
1. FireMonkey
This is Embarcadero's new UI library, which is only available in XE2 and above.  Our app is based on the VCL and we'd want to host this in a VCL window; that seems to be officially unsupported but unofficially works fine, or is available through third-parties.
The mix of UI framework and 3D framework with shaders etc sounds great.  But I don't know how complex the library is, what support it has for data that's not a simple object like a cube or sphere, and how well-designed it is.  That last link has major criticisms of the 3D side of the library - severe enough I am not sure it's worthwhile in its current state at the time of writing for a non-trivial 3D app.
Is it worth trying to write a new visualisation window in our VCL app using FireMonkey?
2. GLScene
GLScene is a well-known 3D OpenGL framework for Delphi.  I have never used it myself so have no experience about how it works or is designed.  However, I believe it integrates well into VCL windows and supports shaders and modern GPUs.  I do not know how its scene graph or navigation work or how well dynamic data can be implemented.
Its feature list specifically mentions some things I'm interested in, such as easy rotation/movement, procedural objects (implying dynamic data is easy to implement), and helper functions for picking.  It seems shaders are Cg only (not GLSL or another non-vendor-specific language.)  It also supports "polymorphic image support for texturing (allows many formats as well as procedural textures), easily extendable" - that may just mean many image formats, or it may indicate something where the texture can be dynamically changed, such as for dynamic colour mapping.
Where to from here?
These are the only two major 3D libraries I know of for Delphi or C++Builder.  Have I missed any?  Are there pros and cons I'm not aware of?  Do you have any experience using either of these for this kind of purpose, and what pitfalls should we be wary of or features should we know about and use?
We currently use Embarcadero RAD Studio 2010 and most of our software is written in C++.  We have small amounts of Delphi and may consider upgrading IDEs, but we are most likely to wait until the 64-bit C++ compiler is released.  For that reason, a library that works in RS2010 might be best.
Thanks for your input :)  I'm after high-quality answers, so I'll add a bounty when I can!

A:

I have used GLScene in my 3D geomapping software and although it's not used to an extent you're looking for I can vouch that it seems the most appropriate for what you're trying to do.
GLScene supports terrain rendering and adding customizable objects to the scene. Objects can be interacted with and you can create complex 3D models of objects using the various building blocks of GLScene.
Unfortunately I cannot state how it will work with millions of points, but I do know that it is quite optimized and performs great on minimal hardware - that being said - the target PC I found required a dedicated graphics card capable of using OpenGL 2.1 extensions or higher (I found small issues with integrated graphics cards).
The other library I looked at was DXscene - which appears quite similar to GLScene albeit using DirectX instead of OpenGL. From memory this was a commercial product where GLScene was licensed under GPL. (EDIT - the page seems to be down at the moment : http://www.ksdev.com/index.html)
GLScene is still in active development and provides a fairly comprehensive library of functions, base objects and texturing etc. Things like rotation, translation, pitch, roll, turn, ray casting - to name a few - are all provided for you. Visibility culling is provided for each base object as well as viewing cameras, lighting and meshes. Base objects include cubes, spheres, pipes, tetrahedrons, cones, terrain, grids, 3d text, arrows to name a few.
Objects can be picked with the mouse and moved along 1,2 or 3 axes. Helper functions are included to automatically calculate the top-most object the mouse is under. Complex 3D shapes can be built by attaching base objects to other base objects in a hierarchical manner. So, for example, a car could be built using a rectangle as the base object and attaching four cylinders to it for the wheels - then you can manipulate the 'car' as a whole - since the four cylinders are attached to the base rectangle.
The only downside I could bring to your attention is the sometimes limited help/support available to you. Yes, there is a reference manual and a number of demo applications to show you how to do things such as select objects and move them around, however the reference manual is not complete and there is potential to get 'stuck' on how to accomplish a certain task. Forum support is somewhat limited/sparse. If you have a sound knowledge of 3D basics and concepts I'm sure you could nut it out.
As for Firemonkey - I have had no experience with this so I can't comment. I believe this is more targeted at mobile applications with lower hardware requirements so you may have issues with larger data sets.
Here are some other links that you may consider - I have no experience with them:

http://www.truevision3d.com/
http://www.3impact.com/
Game Development in Delphi

The last one is targeted at game development - but may provide useful information.

A:

Have you tried glData? http://gldata.sourceforge.net/
It is old (~2004, Delphi 7), and I have not personally used the library, but some of the output is amazing.


Q:

How to prepare yourself for work abroad

I want to work abroad, specifically in Canada or United States.
I am a software developer and have graduated the computer engineering faculty. My coworkers, and bosses over the years, have always considered me a professional and a good programmer.
I am able to read/write in English reasonably, but my speaking and listening English skills are far from fluent. I do not have a TOEFL or TOEIC certificate. So my question is:
What are the knowledge, skills and abilities that would be expected from a foreigner candidate in the field in these countries?
What are the documents and other process I should be looking up to?
I am planning to start working abroad in about 2 years, so I have plenty of time to prepare myself.

A:

Perspective from someone who did this (H1B, another H1B, green card, US passport):
First some legal stuff. I can't talk to Canada but here are the rules in the US that I went through (over the last 15 years or so). DISCLAIMER: I'm not a legal expert. There is an army of US immigration lawyers willing to help but they tend to be expensive ($300/hour is not unusual).

In order to work legally in the US, you need a qualifying Visa. In your case this will probably be an H1B (and an H4 for any family members that want to tag along). This needs a sponsor. You need to have a job first and your US employer needs to apply or the Visa. Only then can you enter and work in the US. Take care about potential travel restrictions while your Visa application is on progress.
Once you have the Visa you can start working but ONLY for your sponsor. If you resign or get fired, you will need to leave the country. An H1B is good for 3 years and can be extended for another three for a total of 6 years. The extension can be a major problem as you may have to leave the country to get the new Visa put in your passport (long and complicated story).
Your best shot is to get a Green Card (Permanent Resident Card) as early as possible. Again, this needs to be sponsored by your employer. It's a lengthy and expensive process: there are 5 different categories of Green Cards and depending on which category you go for there are different hoops to jump through and different quotas per native country. Your employer needs to file, then UCSIS does their evaluation, somewhere biometrics need to to be taken (which in a bizarre twist can actually expire) and the a decision is rendered. If that is positive, your status is changed to "Advanced Parole" (really!!) while the actual Green Card is being issued. The whole process can easily take three years, so the earlier you start, the better. Again during this period you can ONLY work legally for your sponsor. If anything goes wrong, you are out.
Once you have a Green Card, you are basically home free and can change employers and participate in the job market like any other US citizen or permanent resident. After 5 years of having a Green Card, you can apply for US citizenship (if desired), which is relatively simple and straight forward if you haven't run into any problems with the authorities. It's not cheap either.

I think it's clear from the legal stuff that your first priority will be to find a good sponsor. You will need an employer that's willing to spend money and effort bringing you into the US and that offers a good long term relationship. You will have to work for this employer for 5 years at least (best guess).
In order to prepare yourself you need to learn about the culture of the country. The culture will be different from what you have at home and some things about it will be great and others will be strange or weird. Learn about them and see what you like and what you don't like. Talk to people who live there whenever you have a chance. I have seen a lot of immigrants that have the attitude "I'm only here for the money and I go back home as soon as I have enough". I've never seen it work, and it's bound to create a lot of unhappiness (for a large number of reasons).
In terms of language, there are a few things you can do

Read local publications online. For the US, you can read CNN, New York Times, Wall Street Journal, etc. If you are interested in a certain area, read the local newspapers.
Find a class, teacher, tutor that is a NATIVE speaker. It's really important that teacher is native. Interact with native speakers whenever you can.
Watch movies or read books that are originals in English (with subtitles, if it helps). It's important that the original art work is English, translations are often very bad. It's not so important that you understand every single word or sentence but that you expose yourself to as much original & native English in picture, sound & word as possible.

So yes, it's a lot of work and risk, but it can also be very exciting and rewarding. Good luck.


Q:

Run SpecFlow test infinity times

I have a SpecFlow test that fails if you run it enough times. How can I take the existing SpecFlow test and make it run infinity times until it fails? (Ideally I'd like to count how many times it takes.)
My initial guess was to just call the binding methods that the test script ultimately calls - but I keep getting null pointer exceptions. Apparently SpecFlow is initialising something that I'm not.
My next guess was to try to launch the auto-generated code for the test feature, but it seems to want all sorts of data from the SpecFlow framework that I don't know how to generate.
All I want to do is run the test multiple times. Surely there must be some way to accomplish this utterly trivial task?

A:

It seems I was trying too hard. Here's what I came up with:
using System;
using NUnit.Framework;

[TestFixture]
public sealed class StressTest
{
    [Test]
    public void Test()
    {
        var thing = new FoobarFeature();
        thing.FeatureSetup();
        thing.TestInitialize();

        var n = 0;
        while (true)
        {
            Console.WriteLine("------------ Attempt {0} ----------------", n);
            thing.Scenario1();
            thing.Scenario2();
            thing.Scenario3();
            n++;
        }
    }
}

I've got a Foobar.feature file, which autogenerates a Foobar.feature.cs file containing the FoobarFeature class. The names of the scenario methods obviously change depending what's in your feature file.
I'm not 100% sure this works for tests having complex setup / teardown, but it works for my specific case...


Q:

Is it on topic to ask "help me remember this game?"

I have a computer game I played in the 90s that I can't remember the name of and am having trouble Googling.
Is it on topic to post the details I do remember and ask if anyone knows the name of it?

A:

Questions asking for help identifying a game, whether based on a description, or feature list, or any other set of criteria (i.e. "What was the first game to…") are off-topic; this blog post might help. We allow an exception for identifying games based on an actual piece of the game, such as screenshots or audio clips.


Q:

Is there a way to create a searchable picklist in a visualforce page?

I have a picklist field and I was wondering if there is a way to add a searchbox at the top of the picklist where we enter a picklist value and it searches through the picklist to find the values. Something like this:

A:

There is no standard component/way available to do this. You need to write your custom code to achieve it.
First you can use the dataList tag to achieve it.
<datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>

Or you can use third part JS like Select2.


Q:

Is it possible to do a partial string match on a Dictionary string key?

I have a Dictionary<string, List<int>> in my code which I am using in the following manner:
Key           Values
2011-07-15    1, 2, 3
2011-07-20    4, 5, 6
2010-02-11    7, 8, 9

My code needs to be able to query for all values matching a particular substring in the key.  For example, if I had the substring 2011-07 it should return values {1, 2, 3, 4, 5, 6}.  A substring of 11 should return all IDs from 1-9.
Can anyone recommend a concise way to achieve this?  Or provide a better data structure for retrieving this information?

A:

I would do an extension method :
public static class DictionaryExt
{
    public static IEnumerable<T> PartialMatch<T>(this Dictionary<string, T> dictionary, string partialKey)
    {
        // This, or use a RegEx or whatever.
        IEnumerable<string> fullMatchingKeys =
            dictionary.Keys.Where(currentKey => currentKey.Contains(partialKey));

        List<T> returnedValues = new List<T>();

        foreach (string currentKey in fullMatchingKeys)
        {
            returnedValues.Add(dictionary[currentKey]);
        }

        return returnedValues;
    }
}

The "cost" of adding values to the dictionary wouldn't change, but the cost of retrieval would be higher, but only when you know you're going with a partial match.
Btw, I'm sure you could transform this in a single Lambda expression, but the concept remains the same.
Edit: In your example, this method would return 2 lists of values, but you can change it to merge the lists. Here is the extension method you could do :
public static IEnumerable<T> PartialMatch<T>(
    this Dictionary<string, IEnumerable<T>> dictionary,
    string partialKey)
{
    // This, or use a RegEx or whatever.
    IEnumerable<string> fullMatchingKeys =
        dictionary.Keys.Where(currentKey => currentKey.Contains(partialKey));

    List<T> returnedValues = new List<T>();

    foreach (string currentKey in fullMatchingKeys)
    {
        returnedValues.AddRange(dictionary[currentKey]);
    }

    return returnedValues;
}

Edit 2: Come to think of it, you could also make it more generic. With the next extension method, it would work on any dictionary, as long as you provide a comparer that check what you mean by "partial match" :
public static IEnumerable<TValue> PartialMatch<TKey, TValue>(
    this Dictionary<TKey, IEnumerable<TValue>> dictionary,
    TKey partialKey,
    Func<TKey, TKey, bool> comparer)
{
    // This, or use a RegEx or whatever.
    IEnumerable<TKey> fullMatchingKeys =
        dictionary.Keys.Where(currentKey => comparer(partialKey, currentKey));

    List<TValue> returnedValues = new List<TValue>();

    foreach (TKey currentKey in fullMatchingKeys)
    {
        returnedValues.AddRange(dictionary[currentKey]);
    }

    return returnedValues;
}

A:

You are looking for concise answers. Without fancy indexing at a low-level for text (of which I don't know of any specialized .Net classes), I think dictionary is still your best bet. Query with something like:
myDictionary.Where(kvp => kvp.Key.Contains("11")).SelectMany(kvp => kvp.Value);
You have to search through all keys for a generalized substring anyway without some pretty cool magic (not provided by .Net), so LINQ shouldn't hurt you much here.


Q:

Android xml graphical layout/design not loaded properly of existing project

I am trying to import an existing android project, project xml graphical/design layout is not loaded . I made a new test project and the  xml graphical layout working fine, I dont know what is the problem.I just installed new android sdk r14, I dont knw what is the problem, Can anyone help me in this regard?
You can see it in the snapshot attached.
Thank you !!

A:

Easy fix:
Right click on the layout file -> Open With -> Android Layout Editor
Updated answer
In Eclipse, go to Window -> Preferences -> General -> Editors -> File Associations and select *.xml and then press Default on the Android Layout Editor entry in the list of associated editors.


Q:

close waiting dialog in c# when event occured

In socket programming that we wait for data receive, i show a dialog that with show method(i do not show it with show dialog method because event is not occured.)
Psudo code:
buttonClick()
{
    socket.Send(array byte)
    waitingForm.Show();
}

recieveCompletedEventHandler()
{
    WaitingForm.Close();
}

It is ok, but user can access the form controls and because the waiting form is not modal.i just want a sample code that when i send bytes and all data received and event occur and the waiting form close. And of course the waiting form be modal when data does not receive completely.

A:

Thanks @Ofir Winegarten for answer
i create a sample and put the code here for others
 public partial class Form1 : Form
{
    delegate void funDel();

    private waiting waitForm;

    private event funDel funEvent;
    public Form1()
    {
        InitializeComponent();
        funEvent += Form1_funEvent;
    }

    private void Form1_funEvent()
    {

       waitForm.Close();
    }

    private void buttonStart_Click(object sender, EventArgs e)
    {
        Task.Run(() =>
        {
            if (InvokeRequired) // Line #1
            {
                this.Invoke(new MethodInvoker(() => button1.Text = "Proccessing"));

            }

            else
            {
                button1.Text = "Proccessing";
            }

        });

        waitForm = new waiting();
        timer1.Start();
        waitForm.ShowDialog();

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        timer1.Stop();
        funEvent();
    }
}


Q:

Why is fixltx2e incompatible with tikzexternalize

I had some weird problems with tikzexternalize sometimes working sometimes not.
I narrowed it down to the culprit  fixltx2e. Here is a MWNE (Minimal not working exmple)
@ ALtermundus: Yes this is your picture (It is just too nice not to use it ;-)
\documentclass{article}

\usepackage{fixltx2e}

\usepackage{pgf}
\usepackage{tikz}
\usepackage{pgfplots}

\usetikzlibrary{calc}
\usetikzlibrary{external}
\tikzexternalize

\newcommand{\fancypicture}{
   % from http://altermundus.com/pages/tikz/tikz-examples/index.html
   \path  (0,0)       coordinate (A)
          (-60:12cm) coordinate (B)
          (240:12cm) coordinate (C);
    \foreach \density in {10,20,...,160}
        \draw[fill=blue!\density]
          (A) coordinate  (X) -- (B) coordinate[pos=.15] (A) --
          (C) coordinate[pos=.15] (B) --
          (X) coordinate[pos=.15] (C);
}

\begin{document}

\begin{figure}[ht] %[!b!h!t]
  \centering
  \begin{tikzpicture}
    \fancypicture
  \end{tikzpicture}
\end{figure}

\begin{figure}[ht] %[!b!h!t]
  \centering
  \begin{tikzpicture}
    \fancypicture
  \end{tikzpicture}
\end{figure}

\begin{figure}[ht] %[!b!h!t]
  \centering
  \begin{tikzpicture}
    \fancypicture
  \end{tikzpicture}
\end{figure}

\begin{figure}[ht] %[!b!h!t]
  \centering
  \begin{tikzpicture}
    \fancypicture
  \end{tikzpicture}
\end{figure}

\end{document}

The weird thing with the code above: If only two pictures are inserted everything works. Only if more pictures are drawn, I suspect this triggers some fix in fixltx2e and externalization fails. Since this was quite hard to track down I just wanted to know if there are more such subtleties to expect with tikzexternalize or fixltx2e.

A:

The problem seems to be in the fact that fixltx2e redefines \@doclearpage in a way that the doesn't please the externalize library: the output routine runs without producing any page and the compilation stops. This doesn't happen when only two figures are present because they fit on one page, I guess.
I don't think there is much else to do than not loading fixltx2e.

A:

Update: This is now fixed in PGF CVS, see Christian Feuersänger's comment below.

When TikZ/PGF goes into externalising mode then it still processes the entire document.  It needs to do this to ensure that it is in the right "state" when it gets to the picture that it is currently processing (ie any macros or styles or whatevers are as they would be in the normal document).  This means that it still goes through the process of building pages and sorting floats, it just throws it all away at the last minute.
It does do a little bit of optimising.  Anything in an \includegraphics can safely be thrown away.  So also is any tikz picture that isn't the one being processed.
However, this has an unexpected side effect.  It throws away the \includegraphics command or tikzpicture environment, but it doesn't throw away the containing float (which is sensible as that float can contain stuff other than the picture).  If, though, the float did only contain the picture then it is now a box of zero height.  This causes a problem when LaTeX tries to build a float page which consists entirely of these thrown away graphics (which, remember, could be other tikz pictures).  And as TikZ does this for every graphic other than the one that is being externalised, this could happen quite easily.
The problem that this causes is that it is quite possible that the resulting float page is also of zero height.  And this is a problem because LaTeX tests to see if the float page has non-zero height to check that it has been made correctly.  If the float page was of zero height the assumption is that it failed somehow and all the floats have to be pushed onto the next float page.  But if the floats themselves are of zero height we can never get out of this loop.
The reason that fixltx2e makes this evident is that it adds a loop to ensure that all the floats are correctly processed (before, if this failed it would simply lose those floats - I assume, I'm no expert on this).
This suggests a number of options:

Disable the loop in \@doclearpage.  This is the line \ifx\@deferlist\@empty \else\clearpage \fi.
Disable the optimisation step in tikz's externalisation library.  This means putting the option \tikzset{external/optimize=false} in your preamble.  This is probably the safest but might make the externalisation step slower.
Allow zero-height float pages.  This involves redefining the test as follows:
\def\@ytryfc #1{%
  \begingroup
    \gdef\@flsucceed{\@elt #1}%
    \global\let\@flfail\@empty
    \@tempdima\ht #1%
    \let\@elt\@ztryfc
    \@trylist
    \ifdim \@tempdima <\@fpmin
      \@cons\@failedlist #1%
    \else
      \global\@fcolmadetrue
    \fi
  \endgroup
  \if@fcolmade
    \let\@elt\@gobble
  \fi}

Fix the TikZ/PGF optimisation of tikzpicture so that it creates a box of non-zero height.  (I tried this but couldn't come up with something that was guaranteed to work.)
Add \newpage after every externalised float.  This means that it doesn't end up making a float page.  This is a bit extreme, except that you can put it in \tikzifexternalizing to ensure that it only happens in the externalisation run.

Now, I'd only recommend making changes to the Deep Core in the externalising run.  Fortunately, TikZ provides the \tikzifexternalizing command, so put the redefinitions in there (surrounding the whole lot with \makeatletter ... \makeatother) if you don't want to lose the optimisations.


Q:

typedef syntax clarification

I have a bit of confusion between the below declarations - could you please help clear it up?
typedef struct {
  int a;
  int b;
} example;

And this
struct something {
  int a;
  int b;
} ob;

And I am not sure what the below would even mean?
typedef struct foo {
  int a;
  int b;
} bar;

A:

typedef struct {
  int a;
  int b;
} example;

This one defines an unnamed structure type and introduces example as a type alias for that structure type. You can therefore refer to that structure type only as `example.
struct something {
  int a;
  int b;
} ob;

This one defines a structure type something and also declares an object ob of that type. You can refer to the structure type only as struct something.
typedef struct foo {
  int a;
  int b;
} bar;

This one defines a structure type named foo and introduces bar as a type alias for that structure type. You can refer to that structure type as struct foo or as bar.

A:

With
typedef struct {
  int a;
  int b;
} example;

you define an unnamed structure, but define a type-alias example for the structure. That means you can only create instance of the structures using the example "type", like e.g.
example my_example_structure;

With
struct something {
  int a;
  int b;
} ob;

you define a structure named something, and an instance (a variable) of that structure named ob. You can use struct something to create new variables of the structure:
struct something my_second_ob;

The variable ob can be used like any other instance of the structure:
printf("b = %d\n", ob.b);

Lastly, with
typedef struct foo {
  int a;
  int b;
} bar;

you define a structure named foo, so you can use e.g. struct foo to define variables. You also define a type-alias bar which can also be used. Like for example
struct foo my_first_foo;
bar my_second_foo;

The general syntax for typedef is
typedef <actual type> <alias name>;

In the last case of your examples, the <actual type> is
struct foo {
  int a;
  int b;
}

and the <alias name is bar.


Q:

What does "sex out of marriage" mean?

What does it mean when we say "sex outside marriage" or sex out of marriage? Is it same as sex before marriage (ie. premarital sex), or does it include having sex with someone while being married to someone else (ie. extramarital sex).
The source of this doubt is a video, which states that it is a woman's choice whether she wishes to have sex before marriage or have sex out of marriage.
Here's the transcript: My Choice by Deepika Padukon.

A:

Yes it means the same thing. When you are married, you are in a legal union, and in many cultures and religions you are permitted to have physical relations, within those parameters. If you are not married, you are outside of or out of those parameters.
The added meaning of out of compared to before is that it could take place after a divorce, or with somebody else you are not married to, even while married. Basically, it is with anyone you are not married to.


Q:

Root of a special rational function with positive coefficients

During my research I came across the following problem:
I need to find a root of the following function:
$$\Gamma_{N}(x) = \sum\limits_{i=0}^{M}\left(\frac{\sum\limits_{n=0}^{n_F}n\ \alpha_{i,n} x^n}{\sum\limits_{n=0}^{n_F}\alpha_{i,n} x^n}\right)- N,$$
where $\alpha_{i,n}$ are positive coefficients such that in general, $\alpha_{i,n} \in [0,1]$. Parameter $M$ and $n_F$ are integer numbers and $N$ is real. I want to consider only positive $x$, so I am searching for root in the domain $x \in [0, +\infty]$. I will do all calculations numerically, but I was wondering if this function possesses some properties?
Question: Is this function monotonic, such that there exists only a single root?

A:

More elementary argument than in the answer by Alexandre Eremenko:
it suffices to prove that if $a_k\geqslant 0$ for all $k$ and $x>y>0$, then $$\frac{\sum na_nx^n}{\sum a_n x^n}\geqslant \frac{\sum na_ny^n}{\sum a_n y^n}.$$
Multiplying by common denominator this reduces to $$\sum_{n,k}a_na_k(n-k)(x^ny^k-x^ky^n)\geqslant 0,$$
each summand is non-negative.


Q:

Finding the fraction $\frac{a^5+b^5+c^5+d^5}{a^6+b^6+c^6+d^6}$ when knowing the sums $a+b+c+d$ to $a^4+b^4+c^4+d^4$

How can I solve this question with out find a,b,c,d
$$a+b+c+d=2$$
$$a^2+b^2+c^2+d^2=30$$
$$a^3+b^3+c^3+d^3=44$$
$$a^4+b^4+c^4+d^4=354$$
so :$$\frac{a^5+b^5+c^5+d^5}{a^6+b^6+c^6+d^6}=?$$
If the qusetion impossible to solve withot find a,b,c,d then is there any simple way to find a,b,c,d
Is there any help?

A:

One way to approach such questions is to view $a, b, c, d$ as roots of a single quartic equation $x^4-s_1x^3+s_2x^2-s_3x+s_4=0$, when we have Vieta's relations
$$s_1=a+b+c+d$$$$s_2=ab+ac+ad+bc+bd+cd=(a+b)(c+d)+ab+cd$$$$s_3=abc+abd+acd+bcd$$$$s_4=abcd$$
We then let $p_k=a^k+b^k+c^k+d^k$ with: $$p_0=4$$$$p_1-s_1=0$$$$p_2-p_1s_1+2s_2=0$$$$p_3-p_2s_1+p_1s_2-3s_3=0$$
With the given values of $p_1, p_2, p_3$ these determine $s_1, s_2, s_3$.
For higher powers $(k\ge4)$ we have $$a^k-s_1a^{k-1}+s_2a^{k-2}-s_3a^{k-3}+s_4a^{k-4}=0$$ using the quartic equation. Adding together the corresponding equations for $a , b, c, d$ we obtain the recurrence for $p_k$$$p_k-s_1p_{k-1}+s_2p_{k-2}-s_3p_{k-3}+s_4p_{k-4}=0$$
Since we know $p_4$ we can use the recurrence to find $s_4$, and this is then sufficient to compute $p_5, p_6$ from the recurrence.
If this looks complicated, this is misleading. The relations between the elementary symmetric functions $s_r$ and the sums of powers $p_r$ are useful to know, and render this kind of problem essentially mechanical. You can see that you can solve the problem without solving explicitly for $a, b, c, d$.

Following this scheme we find successively $s_1=2, s_2=-13, s_3=-14, s_4=24$. Then the recurrence gives:$$p_5-2p_4-13p_3+14p_2+24p_1=0$$ and$$p_6-2p_5-13p_4+14p_3+24p_2=0$$
And this gives $p_5=812, p_6=4890$

A:

Here's an approach which involves AM-GM inequality(To bound the numbers).
I have considered the positive values of $(a,b,c,d)$. I can consider $a^2,b^2,c^2$ and $d^2$, since they are all strictly positive.
$\dfrac{a^2+b^2+c^2+d^2}{4} \ge \sqrt{abcd}$
$\dfrac{30}{4} \ge \sqrt{abcd} \implies 56.25 \ge abcd$
Since $a^2+b^2+c^2+d^2=30$ and $56 >|abcd|$, One of the $|a|,|b|,|c|,|d|$ is at most $5$.
Considering $a^4+b^4+c^4+d^4$, one of the $|a|,|b|,|c|,|d|$ is atmost $4$, since $5^4=625$ .
Now we have $a^2+b^2+c^2+d^2=30$, the value of $(|a|,|b|,|c|,|d|)$ is from set  $(1,2,3,4)$.
And also:
Considering $4th$ degree polynomial such that $a,b,c,d$ are the roots of the equation.
$x^4+px^3+qx^2+rx+s=0$
$a+b+c+d=2=-p$
$(a+b+c+d)^2-a^2+b^2+c^2+d^2=2(ab+bc+cd+ad+ac+bd)=q=-13$
Finding $\sum abc$ and $abcd$ with the help of other inequalities and finding the roots of equation is another way to go. (Not quite sure whether constructing polynomial is a great way to go. )

Edit: I have considered the absolute values of $(a,b,c,d)$ . I didn't assume them to be $+ve$.


Q:

How do I keep a button depressed in C++?

I want to create a navigation panel in my C++.net application, and I want to keep a button (or similar component) depressed to show that is the page the user is currently on.
Here is a image of what I mean:

How do I create a button that looks like that. (After further inspection, I think it's not a button, however, I cannot figure out the exact control unless it is a image drawn on the screen.)
Thanks.

A:

That is commonly called an "Outlook Bar". There are several examples at codeproject.com


Q:

Better Selection / Title for Top Questions List

With more Stack Exchange sites being created I typically skim over the Top Questions list for each to quickly see if there is anything interesting to get into.
I've noticed frequently on Programmers that the Top Questions list has a large number of poor questions.  Today I specifically counted, 43 questions, 10 were closed, 2 marked as duplicates. 7 had a negative score (some were closed, some were not).
Is there a shortage of questions? Or could there possibly be a better way to create the Top Questions list (maybe excluding closed or down voted questions)?
Thanks to Rachel's comments I'm realizing that the list may not be what I expect it to be. But then should it maybe not be titled "Top Questions"?

A:

By default, that list is everything that's been recently active (you can change this via the tabs on the right). "Top" in this case is a synonym for "recent" - it's the top of the stack, so to speak.
If you want to see the top-as-in-best questions for the site, check out the Greatest Hits


Q:

URL in Alert body

Can we put a tappable link in the alert body? Tapping the link should open the Mail client.
My pressing question is that has anyone tried it and is it accepted by apple.
The alert says 'Please contact Helpdesk for more information' with an OK button - tap on 'helpdesk' and it should open the mail client.

A:

From the Apple Documentation in regards to UIAlertView Class Reference

Subclassing Notes
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

So to get the sort of customization you are talking about you would have to subclass UIAlertView which is not allowed, your app will be rejected.
However there are some alternatives to UIAlertView implementations that can be found cocoa controls.
You could just have a button that does the same as the link and than you could just use this method
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

To determine which button was pressed then run your mail client.


Q:

problem representing a register with unions and bit fields

I'm writing a NES emulator in C++, and I bumped into an issue using bit fields to represent a register, which caused a very nasty bug. I'm representing an internal address register as:
union
    {
        struct
        {
            uint16_t coarseX : 5;            // bit field type is uint16_t, same as reg type
            uint16_t coarseY : 5;
            uint16_t baseNametableAddressX : 1;
            uint16_t baseNametableAddressY : 1;
            uint16_t fineY : 3;
            uint16_t unused : 1;
        } bits;
        uint16_t reg;
    } addressT, addressV;   // temporary VRAM adddress register and VRAM address register

so I can access the single bit-fields, and the register as a whole.
Initially I wrote the register as:
union
    {
        struct
        {
            uint8_t coarseX : 5;             // bit field type is uint8_t, reg type is uint16_t
            uint8_t coarseY : 5;
            uint8_t baseNametableAddressX : 1;
            uint8_t baseNametableAddressY : 1;
            uint8_t fineY : 3;
            uint8_t unused : 1;
        } bits;
        uint16_t reg;
    } addressT, addressV;   // temporary VRAM adddress register and VRAM address register

The bug was caused by the bit field behaviour when the type of the bit field (for example coarseX) is different from that of the register (reg).
In this case, when I increment a field (i.e. coarseX++), the reg member was updated "incorrectly", meaning that the bit pattern inside reg didn't reflect the pattern represented by the bit fields (or by the bit fields as I layed out them inside the struct).
I know that the compiler can pack bit fields inside "allocation units", and may even insert padding, but why the behaviour changes when I change the type of the bit field?
Can someone please explain why?

A:

You said it yourself:

I know that the compiler can pack bit fields inside "allocation units", and may even insert padding, ...

That is exactly what is happening.
uint8_t has 8 bits in it.  The 1st two fields in your struct, coarseX and coarseY, having 5 bits each, can't fit consecutively within a single byte in memory.  The compiler stores coarseX in the 1st byte, and then has to push coarseY to a 2nd byte in memory, leaving 3 unused bits in memory between coarseX and coarseY that offset your values in the register.
The next 3 fields, coarseY, baseNametableAddressX and baseNametableAddressY, total 7 bits, so they fit within that 2nd byte.
But that byte can't hold the fineY and unused fields, so they get pushed to a 3rd byte in memory, leaving 1 unused bit in memory between baseNametableAddressY and fineY that offset your values in the register. And the register can't access that 3rd byte!
So, effectively, your struct ends up acting as if you had declared it like this instead:
    union
    {
        struct
        {
            // byte 1
            uint8_t coarseX : 5;
            uint8_t padding1 : 3;

            // byte 2
            uint8_t coarseY : 5;
            uint8_t baseNametableAddressX : 1;
            uint8_t baseNametableAddressY : 1;
            uint8_t padding2 : 1;

            // byte 3!
            uint8_t fineY : 3;
            uint8_t unused : 1;
            uint8_t padding3 : 4;
        } bits;
        struct {
            uint16_t reg; // <-- 2 bytes!
            uint8_t padding4; // <-- !
        }
    } addressT, addressV;   // temporary

Using uint16_t instead of uint8_t, you don't run into that problem with extra paying being added, since there are enough bits allocated for the register to hold all of the bits you are defining.


Q:

Display div while page loads (all JS and HTML/CSS)

I have a load of images being pulled from Wordpress attachments and then dumped on the page using a masonry grid of sorts - all good. However, it takes a little long.
Is there any way to display a div, with some text, as the page is loading, and then display: none, after?
I have this so far:

and my CSS,
#loading-grid-page {
color: #ffffff;
font: 700 11px/25px 'proxima-nova-1', 'proxima-nova-2', sans-serif;
letter-spacing: 1px;
text-transform: uppercase;
background: #111111 url('images/ajax-loader-black.gif') no-repeat 15px center;
border-radius: 2px;
border: 1px solid #111111;
padding: 5px 30px;
text-align: center;
width: 200px;
position: fixed;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -100px;
z-index: 1000000;
}

However it throws back mixed results, sometimes it waits and all the masonry works, and sometimes it doesn't and the masonry fails and the page loads strangely.
Just wondered if there was anything else out there ;)
Thanks,
R

A:

I would do it this way:

Load an empty page and display a loader.

first time when you load the method just load (y) images, per example 12 will be enough. Don't load all of them.
Use (JQuery) Ajax to load the content.
 Use ajax/json to connect to the server and count the number of images left( total - displayed). if (total > 0) then return links to those images as a json array.
link to jquery's json call.
link to parsing json using PHP.
Hide the loader.
Hide the div that contain the loader and add the links to the content div.
Display the content.
Here you have two options append a div, or use an existing one but this depends on the way you implemented the code, again I recommend JQuery.


Q:

Remove ControlWrapper from Dashboard

I have a Dashboard that has a few different ControlWrapper's which each control a different column in a DataView. I have some checkboxes that allow a user to toggle the columns that are shown in the DataView. The issue is when the DataView columns are updated, using view.setColumns(), dashboard.draw() errors because there is now a ControlWrapper that is referencing a column that no longer exists in the DataView. My thought was that I could call dashboard.bind() and rebind the Dashboard with only the ControlWrappers that map to valid columns, but it does not seem to work.
I am wondering if you cannot call dashboard.bind() after a dashboard has already been drawn, or if there is another way to do this and redraw.

A:

Since there is no way to unbind what you previously bound, you'll have to build a new Dashboard from scratch.


Q:

Customise exported CSV content of Sonata Admin bundle

I'm new to sonata admin bundle. Now, I am try to export a csv file with something like: 'customer.phone', 'order.total'... but when I opened the csv file, in the field 'order.total' is only '99.99', I would like it to export as 'AUD $99.99', anyone know how I can achieve it? Thank a lot! The code is here:
public function getExportFields() {
    return array('id','customer.First_name','customer.Last_name',
        'customer.contact','total_amount'
        );
}

A:

You need to define method getTotalAmountFormated in your Order class, and make it return string that you need. Then add totalAmountFormated (or total_amount_formated, I think both should work) in array returned from getExportFields
public function getExportFields() {
    return array('id','customer.First_name','customer.Last_name',
        'customer.contact','totalAmountFormated'
        );
}

A:

Just to add, you can customize the header of each column like such:
public function getExportFields() {
    return array(
      'Id' => 'id',
      'Customer First Name' => 'customer.First_name',
      'Customer Last Name' => 'customer.Last_name',
      'Customer Contact' => 'customer.contact',
      'Total Amount' => 'totalAmountFormated'
    );
}


Q:

What good, standard digital signature / timestamp verification clients are widely or easily deployed?

I'm looking for a good way to publish data along with a digital signature (and ideally a timestamp) which is as easy as possible to verify via software run locally on public data.
For example, imagine an election administrator who wants to publish election data which is to be audited (totals by candidate by precinct).  We ideally don't want to require the public to have to acquire much if any special or proprietary software.  Signatures which adhere to an open standard, can be validated on PC, Mac, Linux, and can be generated by open source software are preferred.
The data has to remain machine-readable, so a pdf isn't suitable, so if pdf is used, the data would be in attachments to the pdf.
E.g. if we generate XML Signatures (e.g. for IEEE 1622-2011 Election Markup Language (EML) files for elections), is there standard functionality in any common browsers or operating systems to validate the signatures?  Is the user interface clear enough to make it clear to the user when the data looks good, when it is suspicious, and how to deal with common issues?
Alternatives (and concerns):

RFC 3161 - Internet X.509 Public Key Infrastructure Time-Stamp Protocol (TSP) - what cross-platform clients are friendly?
OriginStamp, backed by Bitcoin blockchain (charge for rapid turnaround)
Signed PDF overview with attached data files: can the timestamps be verified and trusted? Can users be tricked via bogus certificates into
Publish link to data and hash of it via various timestamped social networks: Keybase (backed by good crypto specs), Twitter (popular), ...
XML Signatures
Publish SHA-256 hash in the newspaper (How to describe verification steps to the user?)
Use a jar (signed zip) and jarsigner (is there a nice GUI for verifying jar signatures? X.509 PATH validation?)
Use OpenOffice (A hassle to install)
CMS or S-MIME (How can we publish an S-MIME message with attachments - public IMAP?)
Use gpg (but admins need to get in the PGP web of trust, and users need to learn to understand it)
Use s-http (a pity http://tools.ietf.org/html/rfc2660 never took off....)
Use Excel (are there free clients that can check the signature?  Open source software to generate it via a script?)
"Just serve from a secure web site" (doesn't deal with a variety of attacks)

Update, 2019:

Updated list of options with some newer ones, and clarified my goal (in the age of the cloud) of an approach that can be verified via locally-run software. We're learning more and more that web servers are vulnerable to attack, and there are advantages to distributing signed data.
Note that EML and even XML are losing favor these days

A:

Clients? That rather misses the point. It's really about file formats and protocols.
x509 is a cornerstone of encryption implementations. Although its just a starting point for implementing software on, it should probably be your starting point for looking for software.
About 10 years ago, I needed to implement a PKI for my then employers. The route I took was to set up a root Certification Authority using openSSL. At that time x509 verification was available for email required plugins for MSOutlook Express and Eudora (but not for the Bat!). IIRC, these are now built-in as standard. Wincrypt (file encryption) was available as a free download and Stunnel had just been ported to MSWindows.
Certainly 10 years is a long time in encryption circles - but the nice thing about x509 is it accomodates different algorithms / key sizes. It also builds on the same basis as LDAP.
More recently there are have been many more tools implemented using SSL type encryption - e.g. Gnu Anubis (OK, it doesn't actually add the sigs - but provides hooks for calling openssl), smart cards

A:

One option would be to digitally sign a message with the XML attachment with S/MIME. Use an online page on which users can enter their email address to which a copy will be sent.
Another option would be to use a signed PDF. The PDF standard allows PDF documents to be digitally signed and supports attached documents. The XML can be attached to the PDF as an attachment. The complete PDF including the attachments will be signed.
If you want to make it easier for end-users to check the signature, you should make sure that you use a universally trusted x.509 certificate or, use your own certificate and publish the thumbprint of the certificate somewhere.
Martijn Brinkers

A:

Signatures which adhere to an open
  standard, can be validated on [...] Mac [...]

On the Mac, there's a Certificate, Key and Trust service which is built in all over the place. That means that you could send them S/MIME data and they'd be able to inspect the certificate and its trust path in the mail client. On the other hand, the UI just looks like a little tick or cross in a bar above the message. That's also the problem with using TLS - it works, but it works silently, and in some situations it fails silently too. Everything in between needs special knowledge to comprehend.
There is a third-party plugin for GPG in Apple Mail, but as you observed in your question registration and subsequent correct use of OpenPGP is hard.


Q:

Displaying headers and footers in a PDF generated by Rotativa

I'm trying to specify headers and footers in a PDF generated by Rotativa library. As the author answered here it should be possible using CSS (described here). However, I'm not able to do this.
I have a stylesheet loaded in the meta tag:
<link href="print.css" rel="stylesheet" type="text/css" media="print" />

And in the stylesheet at the bottom:
@page {
    @top-left {
        content: "TOP SECRET";
        color: red
    }
    @bottom-right {
        content: counter(page);
        font-style: italic
    }
}

And then generating PDF by:
public ActionResult ShowPdf()
{
     var model = new Model();
     return new ViewAsPdf("view.cshtml", model)
                {
                    FileName = "Report.pdf",
                    CustomSwitches = "--print-media-type"
                };
}

And then nothing appears in the header and footer of the PDF. Any ideas?

A:

I've found a documentation of wkhtmltopdf and it is described there how to manage headers and footers.
Basically you can just add --header-center "text" (or similar switches) to the argument list and that's all.
So using it with Rotativa it would be:
public ActionResult ShowPdf()
{
     var model = new Model();
     return new ViewAsPdf("view.cshtml", model)
                {
                    FileName = "Report.pdf",
                    CustomSwitches = "--print-media-type --header-center \"text\""
                };
}

(I don't know if --print-media-type is necessary.)

A:

If you wanted to display a View instead of text in the header/footer then you can do so like this:
public ActionResult ViewPDF()
{
      string customSwitches = string.Format("--print-media-type --allow {0} --footer-html {0} --footer-spacing -10",
                Url.Action("Footer", "Document", new { area = ""}, "https"));

     return new ViewAsPdf("MyPDF.cshtml", model)
                {
                    FileName = "MyPDF.pdf",
                    CustomSwitches = customSwitches
                };
}

[AllowAnonymous]
public ActionResult Footer()
{
    return View();
}

Don't forget to add the  [AllowAnonymous] attribute on the Footer action otherwise Rotatina can't get access to the path.

A:

Here is how I did it (in full):
public ActionResult PrintPDF(int? selectedSiteRotaId, int selectedSiteId)
{
    string footer = "--footer-center \"Printed on: " + DateTime.Now.Date.ToString("MM/dd/yyyy") + "  Page: [page]/[toPage]\"" + " --footer-line --footer-font-size \"9\" --footer-spacing 6 --footer-font-name \"calibri light\"";

    return new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
    {
        FileName = "PDF_Output.pdf",
        PageOrientation = Orientation.Landscape,
        MinimumFontSize = 10,
        //PageMargins  = new Margins(5,5,5,5),
        PageSize = Size.A3,
        CustomSwitches = footer
    };

    //var pdfResult = new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
    //{
    //    FileName = "PDF_Output.pdf",
    //    PageOrientation = Orientation.Landscape,
    //    MinimumFontSize = 10
    //};

    //var binary = pdfResult.BuildPdf(this.ControllerContext);

    //return File(binary, "application/pdf");
}

public ActionResult RenderPDF(int? selectedSiteRotaId, int selectedSiteId)
{
    return RedirectToAction("Index", "PrintPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 });
}


Q:

How to display the xml tags as a list using css?

<team>
  <teamleader info="Team Leader">
    <name>Suresh KC</name>
    <email>kc.suresh@yahoo.com</email>
  </teamleader>
  <member id="ME1A">
    <name>Harry Jones</name>
    <email>Jones25harry@gmail.com</email>
    <salary>2500</salary>
  </member>
  <member id="ME3A">
    <name>John Deo</name>
    <phone>9866123456</phone>
    <salary>2500</salary>
  </member>
</team>

i want to display teamleader and member as

Suresh KC kc.suresh@yahoo.com
Harry Jones Jones25harry@gmail.com 2500
John Deo98661234562500

I tried using list-style-type:decimal; property of css but it doesnot work.

A:

You could do this using only CSS, see my example below.
It is more common to parse the XML using javascript and than displaying it as a list element. You'll be way more flexible that way.

teamleader,
member{
  display: list-item;
  margin-left: 1.3em;
  list-style-type: decimal;
}
<team>
  <teamleader info="Team Leader">
    <name>Suresh KC</name>
    <email>kc.suresh@yahoo.com</email>
  </teamleader>
  <member id="ME1A">
    <name>Harry Jones</name>
    <email>Jones25harry@gmail.com</email>
    <salary>2500</salary>
  </member>
  <member id="ME3A">
    <name>John Deo</name>
    <phone>9866123456</phone>
    <salary>2500</salary>
  </member>
</team>


Q:

c++ Operator overloading,

Whats wrong with my code shown below? please somebody throw some light. Thanks for your time !
    #include<iostream.h>
      using namespace std;

     struct mydata{
        int mx;
        mydata(int x = 0){}
        mydata operator+(const mydata& rhs){

                mydata temp(rhs);
                return temp;
        }
        operator int() const{ return mx; }
        operator double() const{ return mx; }
};

int main(){
        mydata d;
        mydata r = d + 5; // L1
        5 + d; // L2
        d + d; // L3
}

A:

First, you haven't stated what the problem is, but presumably you want an operator+ that sums the mx values of two mydata objects:
mydata operator+(const mydata& rhs){
        return mydata (mx + rhs.mx);
}

Next, I would suggest making this a non-member function, so that the LHS and RHS get treated in the same way, fixing the problem in L2:
mydata operator+(const mydata& lhs, const mydata& rhs){
        return mydata (lhs.mx + rhs.mx);
}

Finally, you will have an ambiguous overload remaining, because the compiler cannot decide whether to use the built-in operator+(int,int) or your own operator+(const mydata&, const mydata&). You can fix this by removing the cast operators int() and double().
See demo here.

A:

The problem (stated the comment) is that compiler doesn't know which + you want to execute:
(double)d + 5

or
(int)d + 5

In order to resolve this ambiguoity, you should point the type conversion, or replace one of these operators by a named function:
    operator int() const{ return mx; }
    operator double() const{ return mx; }

If you want instead use d + mydata(5) you should write so, because the above variants are more likely to be applied


Q:

Redirect Loop in PHP behind a Load Balancer with SSL

I have a situation where I'm getting stuck in an infinite redirect loop when I try to switch from SSL encrypted pages back to non-encrypted (https -> http).  Our current configuration is set behind a load balancer that creates a header: HTTP_X_FORWARDED_PROTO
When it is set to SSL it returns "https", othwerise it always returns "http"
The following code I used to use on the site before the SSL cert was moved to the load balancer instead of the web node the site runs on.  (HTTP_X_FORWARDED_PROTO) have been added to update the script accordingly.
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])){
    $redirect = '';
    if (!isset($sslPage)){
        $sslPage = false;
    }
    switch($_SERVER['HTTP_X_FORWARDED_PROTO']){
        case 'http' :
            if ($sslPage)
                $redirect = 'location: https://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
            break;

        case 'https' :
            if (!$sslPage)
                //$redirect = 'location: http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
            break;
    }
    if (!empty($redirect)){
        header ($redirect);
    }
}

Each page that needs ssl turned on has a preloaded variable of $sslPage = true;
So the redirect from http to https works great.. no issues.  But if I try to go backwards it doesn't work.  I get stuck in an endless loop.  I'm starting to think that it's because of apache.  Since the web node no longer terminates the SSL all traffic to it is run through port 80.  When php is doing the redirect through header(), I believe what happens is the server gathers the request since it's local and tries to parse it.  Since the HTTP_X_FORWARDED_PROTO is never updated because it didn't hit the load balancer again, the redirect can never be successul.
My question is if this makes sense or have I gone the wrong way with my thinking on this?  Would this call regardless always get forwarded back to the load balancer?  If it does stay internal to that web node, how do I force it to go back to the Load Balancer so it can write the new headers for the page it's trying to retrieve?
This has proven to be frustrating....
Thanks for your help in advance.

A:

You could just let Apache think SSL is on by setting the environment variable (in PHP logic $_SERVER['HTTPS'])
SetEnvIf X-Forwarded-Proto https HTTPS=On

This should allow your legacy code to work without the need to change.


Q:

Backticks versus real quote marks

So, I'm a Mac user, and a little bit of a type nut (probably not compared to many users on here, though! :P)
I've been happily typing emdashes and curly-quotes on my keyboard for years, and years: ⌥⇧-, ⌥[ / ⌥⇧[ … you get the idea. Now, LaTeX has been pretty wonderful so far, but I've been studiously avoiding junk like \wedge or --- or `` where just typing the damn Unicode character would work perfectly fine (Hon.m unicode-math!) … but I'm definitely getting the impression that that's going against the grain in this community, and I want to write what's perceived as clean, idiomatic code, so …

Is there any typesetting benefit or purpose to using `` instead of “, and similar LaTeX conventions, in the source-code to your LaTeX document?

A:

Assuming that you have unicode input correctly declared either via
\usepackage[utf8]{inputenc}

or using xelatex or lualatex then  `` will ligature to “ and produce identical output.
So the pros and cons are all about the human interface to editing, not about latex.
Most latex users use ascii input as they have been using it for a long time, but even now it has some advantages as many people learn (or copy what they did before) by viewing the source, for most people, with most keyboards it does not require any instruction to know how to type `` or \infty but it may not be so clear (and the instructions will be very system and locale specific) how to type “ or ∞.
For example I did not recognise your ⌥⇧- at all but the first character is U+2325 which is OPTION KEY which I vaguely remember being the name of one of the modifier keys on a Mac keyboard.


Q:

Is there a keyboard shortcut for inserting a new line above the one the caret is on?

I can do command-return to create a new line under the current one, even if the caret is in the middle of a word, but I often find myself wishing there was a similar command for inserting a line above and moving the caret to it. Does that exist?
I know I can type out my new line and then move it, but it'd be nice to skip that.

A:

Yep: ⌘ (Command) + shift + enter if you're on a Mac
Found here


Q:

Is there something during the work day that I can do to increase productivity after work?

I often find myself exhausted after work hours (8 hours of work plus commuting [and meal] times). When I get home, I am unable to be productive on my personal projects, even if I have the motivation to do so.
Is there something during the work day that I can do to increase off-work productivity?

A:

So I have experienced the same. The way I look at it, it's hard to do something for 8 hours, and then continue doing the same (developing software) when you get home. Once your hobby becomes your work, it hurts your hobby.
What you are asking is how can you increase your productivity once you get home from a long day at work, and the answer is actually quite dull, but it helped me and should definitely also help everyone else.
When you get home, then don't start on your personal project right away. You want to do something else for at least 20-30 minutes. I really recommend using this time for exercising, and maybe some daily tasks – don't turn on the TV. Furthermore, start eating healthy and stay away from sugar specifically. Good nutrition and exercise are really the key.
Another trap you shouldn't fall into is the whole idea of caffeine helping you. It won't, especially not in the long run. Drinking a lot of caffeine can actually have a negative effect on your energy level, and you start to depend on small sugar/caffeine rushes to be productive. One cup of coffee doesn't hurt, but be aware of your intake.
Doing these things will optimize your energy level during the day, and also give you better mental and physical health. If you are already doing this, then try to look into stuff like

your sleep schedule
your mental motivation towards the project
distractions at home

I can say from personal experience that this will have a greater effect than one might think.

A:

Apart from the sleep schedule regulations that has been already mentioned, here are a few things that I do at work and at home to have a bit more energy for my off-work related activities:

Meditate at least 15 minutes every day. This helps me to calm my mind and take away the work related stress.
Take a stroll to divert your mind (sometimes during office hours, I take a walk to get away from the problems and find better solutions, works with life as well).
Drink lots of water at work. Water keeps the most common headaches caused due to dehydration away.

Personally, these are the things that have worked for me (things which I've consciously put efforts into).

A:

Couple things to consider:

Have a stable sleeping schedule and stick to it  no matter what.
Getting enough rest as well as having your circadian rhythm be stable
will make you feel very energized and in sync when your body adapts
to it in case your current sleeping patterns are random.
Use some nootropics for the days you really dont feel like you can
pull through, I suggest this as you can regulate exactly the
amount of caffeine intake(unlike coffees) as well as ingredients that enhance your reaction to it.
Leave enough time for relaxation outside your work hours. I know its
very tempting to try to solely work as much as possible when you re
not sleeping but its a trap and you can easily get to a point you
feel burned out and keep pushing yourself for diminishing returns.


Q:

Прочитать два числа с клавиатуры

Как реализовать на Java такое чтение: scanf("%d%c%d", &x, &y);* ?
Плюс нужен контроль ввода: чтобы программа не вылетала, если ввести строку

A:

Эт вам не Ся... :)
Самый простой, незамороченный способ использовать Scanner - фактически это такой небольшой парсерочек, который входной поток разбивает на токены и далее уже можно с токенами делать что надо - типа:
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
    int myInt = sc.nextInt();
}


Q:

Make a phrase column out of columns with value of 1 in Pandas Dataframe

Let's say I have this dataset, I want to create a phrase column that adds a word for each column with value of 1...
    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET
0            1           0           0           0           0           1          0
1            0           1           0           0           0           1          0
2            0           0           1           0           0           1          0

This is the dataframe for the phrase values for each column if set to 1:
          col                  phr
0  SINNOUVEAU     sinistre nouveau
1  PERTETOTAL         perte totale
2  CHANGGARAN  changement garantie
3  SOCLOCATIO     societe location
4  SINISAMEDI               samedi
5  NOMASCONDU        nom different
6   SINIREPET   sinistre repetitif

So, for the dataframe above, this is the result I expect:
    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET  Phrase
0            1           0           0           0           0           1          0  sinistre nouveau, nom different
1            0           1           0           0           0           1          0  perte totale, nom different
2            0           0           1           0           0           1          0  changement garantie, nom different

A:

Assuming the first dataset is named df and the second one as df1:
We take help of df.dot() like below:
m=df.rename(columns=df1.set_index('col')['phr'].to_dict())
df['Phrase']=m.dot(m.columns+',').str.rstrip(',')
print(df)

   SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  \
0           1           0           0           0           0           1
1           0           1           0           0           0           1
2           0           0           1           0           0           1

   SINIREPET                             Phrase
0          0     sinistre nouveau,nom different
1          0         perte totale,nom different
2          0  changement garantie,nom different


Q:

Count the number of missing values in a dataframe Spark

I have a dataset with missing values , I would like to get the number of missing values for each columns. Following is what I did , I got the number of non missing values. How can I use it to get the number of missing values?
df.describe().filter($"summary" === "count").show

+-------+---+---+---+
|summary|  x|  y|  z|
+-------+---+---+---+
|  count|  1|  2|  3|
+-------+---+---+---+

Any help please to get a dataframe in which we'll find columns and number of missing values for each one.
Many thanks

A:

You could count the missing values by summing the boolean output of the isNull() method, after converting it to type integer:
In Scala:
import org.apache.spark.sql.functions.{sum, col}
df.select(df.columns.map(c => sum(col(c).isNull.cast("int")).alias(c)): _*).show

In Python:
from pyspark.sql.functions import col,sum
df.select(*(sum(col(c).isNull().cast("int")).alias(c) for c in df.columns)).show()

Alternatively, you could also use the output of df.describe().filter($"summary" === "count"), and subtract the number in each cell by the number of rows in the data:
In Scala:
import org.apache.spark.sql.functions.lit,

val rows = df.count()
val summary = df.describe().filter($"summary" === "count")
summary.select(df.columns.map(c =>(lit(rows) - col(c)).alias(c)): _*).show

In Python:
from pyspark.sql.functions import lit

rows = df.count()
summary = df.describe().filter(col("summary") == "count")
summary.select(*((lit(rows)-col(c)).alias(c) for c in df.columns)).show()


Q:

What directories to backup on ESXi apart from the VMs?

I know how to backup the VMs in the datastore, but what about the ESXi config?
In case of a disaster recovery (like fire and such) which directories should I backup off-site to be able to restore an ESXi configuration?
I know about these:
/bootbank
/altbootbank

Are there others?
Edit:
Note I'd like to move Microsoft Windows out of the equation (especially since VMware is doing the same with the vSphere Client, i.e. not being able to do certain operations on ESXi 5.5 with it any more).
My aim was to do it from a *nix machine (ESXi is very limited in what it can do, and I'd like to keep it that way, i.e. not install many things on it to keep it as stable as possible).

A:

You may want to look at purpose-built VMware backup tools. You will be very disappointed if you treat an ESXi host like a Linux/Unix server.
Use the VMware backup commands from a separate station, and you'll be left with a nice configuration tarball. I would find another approach for the actual VM backups.
Edit: Host-based example
vim-cmd hostsvc/firmware/sync_config
vim-cmd hostsvc/firmware/backup_config

This stores the config in /scratch/downloads:
# vim-cmd hostsvc/firmware/backup_config
Bundle can be downloaded at : http://ip.of.esxi.host/downloads/52fd67ba-2fdf-9876-6651-46c3da638f1a/configBundle-centaur.ewwhite.net.tgz

Also see: http://www.virtuallyghetto.com/2013/02/how-to-backup-restore-free-esxi-host.html


Q:

Mongo PHP Driver 1.2.10 with MAMP

I'm trying to get the latest Mongo Driver to work with MAMP 1.9.6 on OS X 10.5.8.
I built it successfully from source since it seems that there are no pre-compiled releases, included it into the right directory and restarted the apache.
But PHP doesn't recognize the extension. I used the 1.0.11 driver previously which worked fine, but I need the new version, because Doctrines ODM requires it.
When I replace the 1.2.10 mongo.so with the 1.0.11 and restart apache mongo is available. I don't get what could be wrong.
Anyone had this behaviour or any guesses to get this to work?
Update: The PHP error log shows the following:
[01-Jun-2012 22:02:37] PHP Warning:  PHP Startup: mongo: Unable to initialize module
Module compiled with module API=20060613
PHP    compiled with module API=20090626
These options need to match
 in Unknown on line 0

I'm not quite sure what it means?
2. Update:
I was finally able to sync the API version of phpize.
But now I'm not able to build the driver anymore.
I do the following:
phpize
./configure
make
sudo make install

But at the make command I'm getting tons of syntax errors. Seems that it can't find several header files.
The very first one is the zend_config.h and really I just have those other two files:
zend_config.nw.h
zend_config.w32.h

I downloaded the MAMP components to get this files. Why am I missing this one? And there are a lot of others.
I'm using PHP 5.3.5 Is there a way to get those header files from a different source?

A:

I followed the instructions at Develop MongoDB web apps with MAMP under Mac OS X to successfully build mongo.so for MAMP with php 5.3 on OS X 10.7.3.


Q:

How will changing taxonomy term affect tagged nodes

What happens when a taxonomy term is changed? Will the term just change for all nodes tagged with the original term or will the relationship be deleted?

A:

The taxonomy term relationship is stored in the database using the term ID. So if you change that term's name, but not the ID, it should be fine. If you delete that term, the relationship will no longer exist so avoid doing that.


Q:

Get an image from gallery Android Studio

I am trying to create an app in Android Studio that allows a user to choose a picture from their gallery. My code so far is:
public void openGallery ()
{
    Intent intent = new Intent();
    // Show only images, no videos or anything else
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    // Always show the chooser (if there are multiple options available)
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.chosenImage);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This does not work. When I run the app and click the button to choose an image it causes the app to crash. There is no error message. Is there something wrong with my code?
Logcat
07-25 18:48:29.590 4892-4892/com.example.findmyitem E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.findmyitem, PID: 4892
java.lang.IllegalStateException: Could not find method openGallery(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'galleryButton'
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:424)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:381)
    at android.view.View.performClick(View.java:6897)
    at android.view.View$PerformClick.run(View.java:26101)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

A:

Error is saying that it cannot find method openGallery(View ) and you have just openGallery() without View parameters inside it. Since you are referring that method in XML you should change that method signature to openGallery(View v)


Q:

Unwanted double quotes in json

I have the following code in .NET
public JsonResult<string> Get()
    {
        Message message1 = new Message("lala1");
        Message message2 = new Message("lala2");

        List<Message> listOfMessages = new List<Message>();

        listOfMessages.Add(message1);
        listOfMessages.Add(message2);

        var json = new JavaScriptSerializer().Serialize(listOfMessages);
        return Json(json);
    }

What I get as a result is:
"[{\"message\":\"lala1\"},{\"message\":\"lala2\"}]"
I do not want the double quotes ("") in the start and in the end. Why does it add them ?

A:

MSDN documentation for JavaScriptSerializer class actually recommends the following:

Json.NET should be used [for] serialization and deserialization.

JSON.NET library became de-facto standard for working with JSON in .NET, for example, it is a default serializer that is used with ASP.NET Web API (link).
Here is how you can re-write your code to use JSON.NET (be sure to add Newtonsoft.Json nuget package to your solution):
public static void Main()
{
    var result = SerializeMessages();
    Console.WriteLine(result);
}

public static string SerializeMessages()
{
    var listOfMessages = new List<Message>
    {
        new Message("lala1"),
        new Message("lala2")
    };

    return JsonConvert.SerializeObject(listOfMessages);
}


Q:

jQuery datatable custom sorting and filtering

I am using jquery datatables in my MVC4 application. The most simple configuration of jquery datatables.
Infact, I have placed this small jquery snippet in my layout.cshtml file which will take care of all tables in my application without doing anything custom.
$(".dataTable").dataTable({
   "bJQueryUI": true,
   "sPaginationType": "full_numbers"
}).columnFilter();

this works perfectly when I format the table with
,
 and
.
Here's the image :
Ofcourse, not everything will work work with this basic configuration.

The problem
The payment status column contains not just some text, it contains a span and a hidden dropdown list. on click of , The span gets hidden and dropdown becomes visible. on dropdown change it reverts back to a visible span and hidden dropdown.
The code :

                Completed

           <select name:"paymentstatus"="" style="display:none;" onchange="changepaymentStatus($(this).parent().attr('paymentId'),$(this).val(),10);">
               <option value="0" selected="'selected'">Completed</option>
               <option value="1">Pending</option>
               <option value="2">Cancelled</option>
           </select>

With all this mess present in the  element, it is not able to filter at all (for that column and sorting works incorrectly (for that column).

A:

Hi take a look at this http://datatables.net/examples/plug-ins/sorting_sType.html this will do the job for you.


Q:

How can I receive email notifications about reactions to my own content on Facebook?

Which email notification settings do I need to enable to receive email notifications about reactions (comments) to my published posts and status messages?

A:

Here it is:
Settings -> Notifications -> Email -> All notifications, except the ones you unsubscribe from
This will notify you by email about reactions. There is no special settings for reactions.


Q:

wpf begininvoke for updating ui

Hello i am working with c# wpf. now problem is threading. I cannot access other thread the UI elements and when i using Dispatcher.BeginInvoke I cannot control Window. The calculate take about 5min. I want update calculate state to UI progressbar and move windows my self. Who can help me. :)
public delegate void TrainDelegate();

private void btnTrain_Click(object sender, RoutedEventArgs e)
{
    Dispatcher.BeginInvoke(DispatcherPriority.Background, new TrainDelegate(StartTrain));
}

in StartTrain function I called textbox.
like follow
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(txtbTrainPath.Text);

It works but block main window. they said Begininvoke is non-block calling.
Could you please help me? What should be changed here?

A:

ok, then
private void btnTrain_Click(object sender, RoutedEventArgs e)
{
    string myText = txtbTrainPath.Text;
    Task.Factory.StartNew( () => { StartTrain(myText); } );
}


Q:

Get facebook user profile using cordova

I want to get first name, last name, email when user login with facebook. My app is in Cordova. I am using cordova plugin for facebook authentication this one "https://github.com/Wizcorp/phonegap-facebook-plugin". I can login with Facebook but how can I get name, email from it.
Thanks in advance.

A:

add facebook cordova plugin using below command See Details
cordova plugin add https://github.com/Wizcorp/phonegap-facebook-plugin --variable APP_ID="YOURAPPID" --variable APP_NAME="YOURAPPNAME"

html code

Javascript code


Q:

Why are static variables and methods in java called directly?

Why static variables are directly called without any use of object in java?Are they stored in some different memory location?And why only static methods can called with the name of the class directly without creating its object ?for example
class First
{
   public static void ss()
   {
     System.out.println("This genius will give answer");
   }
}

class Second
{
    public static void main(String ar[])
    {
       First.ss();

    }
}

A:

Yes static resources belong to the class and not the objects. And are stored in a separate location kind of global location. You can read more here.