Retrieve Firestore data and populate Vuejs but v-html update is not working

Question: I am retrieving firestore data and populate to the interface with Vuejs. Unfortunately, the innerHTML is not updated and I am stuck for 3 hours but still do not know where have I done wrong.
HTML

Vuejs
Vue.component('dashboard', {
    template: '#dashboard',
    data() {
        return {
            boardDetails: ''
        }
    },
    mounted(){
        var studIdentity, studName, studEmail, photoUrl, uid, emailVerified;

        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                studIdentity = user;
                if (studIdentity != null) {
                    studName = studIdentity.displayName;
                    studEmail = studIdentity.email;
                    photoUrl = studIdentity.photoURL;
                    emailVerified = studIdentity.emailVerified;
                    uid = studIdentity.uid;
                }

                var boardId = [];
                ref_du.get().then(function (snapshot) {
                    snapshot.forEach(childSnapshot => {
                        let data = childSnapshot.data();
                        let st_id = childSnapshot.id;
                        let userId = data.studId;

                        if (userId == uid) {
                            boardId.push({ st_id: st_id, t_id: data.taskboardId });
                        }
                    });
                });

                var boardInfo = []
                du.get().then(function (snapshot) {
                    snapshot.forEach(childSnapshot => {
                        let data = childSnapshot.data();
                        let t_id = childSnapshot.id;

                        for (let i = 0; i < boardId.length; i++) {
                            if (boardId[i].t_id == t_id) {
                                boardInfo.push({ t_id: t_id, name: data.taskboardName, date: data.createdDate });
                            }
                        }
                    });

                    let html = '';
                    for (let i = 0; i < boardInfo.length; i++) {
                        html += `

${boardInfo[i].name}

            `;
                    }
                    this.boardDetails = html;
                    console.log(this.boardDetails);
                });

            } else {
                window.location.href = 'index.html';
            }
        });

    }
});

The console log shows that the boardDetails is updated but the interface does not show anything.
Answer: When you use the function keyword, it changes the this context.
To fix your problem, add var self = this; at the top of mounted and then replace anywhere you have this.boardDetails with self.boardDetails
Comment: Omg Thank you! I'm crying. It works! 3 hours wasted not knowing about this. Thank a lot =)


PHP - encryptar/ decryptar dados

Question: Eu estou usando encriptação AES-128 para mensagens de utilizadores, mas eu pretendia encryptar com mais Layers.
Exemplo :
<code>        Layer 1: encryptacao aes-128
        Layer 2: "outra encryptacao".
</code>
Acham que é boa ideia proteger desta forma? Se sim, que encryptacao posso usar para encryptar e desincriptar
Answer: Não há porque fazer isso, ninguém faz isso já que o AES é seguro.
Se você não quer usar AES-128 use o AES-256 ou AES-192. Se você não confia no AES, principalmente se você não tem um processador com suporte para AES-NI, use outra cifra, como o Serpent-256, Salsa20 ou ChaCha20.
O único ganho de segurança que teria é se o algoritmo, isoladamente, é vulnerável a buscas exaustivas, como é o caso do DES. Neste caso existe o 3DES que faz exatamente 2 encriptações e 1 decriptação, mas ainda existe o problema de meet-in-the-middle.
O 3DES foi criado porque o DES é vulnerável a busca exaustiva. Usar o mesmo processo para o AES é inútil, o AES não tem o mesmo problema. Inclusive, o AES é segura até contra computadores quânticos, se prefere cifras de fluxo o Salsa20 também é, segundo a PQCrypto.

Acredito que existe outros problemas que pode estar preocupado, como a integridade da informação ou o armazenamento das chaves, por exemplo.
Comment: Exato, eu quero que a encryptacao seja super segura. Pois o objetivo das mensagens è serem anonymas.

Já agora, que tipo de verificaçoes eu deva fazer para proteger um Form?

PHP - encryptar/ decryptar dados


Getting around the 8192 byte var limit in NSIS?

Question: I'm supplying a c++ .dll to a user who is writing an installer via an NSIS script. Using System.dll, the user can call my .dll as such:
System::Call 'my.dll::GetJson(v) t .r0'
DetailPrint $0

The return value of GetJson() gets stored in $0. This is all working correctly, though GetJson() may return a json blob whose length is > 8192, in which case the value stored in $0 gets truncated.
I looked at trying to increase NSIS_MAX_STRLEN by building NSIS myself using scons, as mentioned here: https://nsis.sourceforge.io/Special_Builds
 scons NSIS_MAX_STRLEN=16384 PREFIX=C:\somewhere install-compiler install-stubs

However, after doing this, the NSIS-compiled .exes crashed upon running. It seems like 8192 may be some kind of memory limitation.
Is there any way around this for me? For example, would it be possible to call
System::Call 'mydll::GetJson(v) t .r0'

But instead of the return value being stored in $0, have it be split into chunks? Perhaps it's possible to write the contents of GetJson() to a file first, and then NSIS can read that and split it?
Any help is appreciated. Thank you.
Comment: If splitting the string is acceptable, does that mean you don't need to parse/modify the string in NSIS?
Comment: @Anders Oof great point. The user will need to parse that JSON, so splitting probably won't help me.
Answer: If the user needs to edit a very long string you basically have two options:
Use the system plug-in to fill a text field on a nsDialogs custom page. You can't use the registers to store the string, you need to use ...func()p.r0 to get the raw address of the string from your plug-in and use Sendmesage to fill the text field. To save you need to allocate memory, get the text with SendMessage and write it to a file and finally free the memory.
The other option is to create the custom page with your custom plug-in.
Comment: Ah, that is an interesting technique. Thank you for the help.


Calippo, toothpaste and milk .. packing

Question: This post was posing the question "The Calippo™ popsicle has a specific shape ... Does this shape have an official name?", and the accepted answer was that it is a Right Conoid which in fact is much resembling.
However,  a conoid is not developable and so cannot be economically made out of a cardboard sheet.
Now, a cardboard cylinder, pinched and sealed at one end, will look like a toothpaste tube, and the
pinched end will  be larger than the mouth diameter (by $\pi /2 $).
That does not fit to the calippo's look,
whose tube is in fact fabricated from a cone (made from a plane circular sector) pinched at one end (and reinforced at the opposite circular rim).
And a related subject is that,  a cylinder with both ends  pinched at  90° relative to each other make up
a tetrahedral "milk carton" (berlingot in French).
In this Mathcurve page  after stating that
"le berlingot est la surface réglée non développable .. ",
referring to a picture of a real tetrahedral milk carton is noted:
"Attention, un berlingot comme ci-dessus fabriqué avec du papier
est une surface développable, fabriquée avec un patron de tétraèdre en arrondissant les arêtes... "
Also refer to the Coin Conic page.
Suppose that the material is inextensible, and that a grid of directrices and orthogonal circles is marked on the cone/cylinder,
then it is clear that upon pinching the directrices will not appear straight.
Since a developable surface implies that it be ruled, then either the ruling lines have moved, or the surface has undergone some deformation.
Therefore the question is:
Can the calippo (and bottom of toothpaste, and milk) package be a ruled developable surface , in case, admitting that the shape of the pinched edge be not exactly linear ?
or is some deformation of the material demanded ?
---- P.S:  -----
Thanks to the answer, with expressive sketch, received by Rahul, complemented with that provided by C.Blatter to the previous post, we can conclude that such a surface is a plausible model.
So, scaling all the dimensions to have the base circle of radius $1$, height $=h$ and length of the pitch $=2c$

we can parametrise the surface as
$$
\eqalign{
  & {\bf q} = \left( {sc,\;0,h} \right) - \left( {\cos \alpha ,\;\sin \alpha ,0} \right) = \left( {sc - \cos \alpha ,\; - \sin \alpha ,h} \right)  \cr
  & {\bf p} = \left( {\cos \alpha ,\;\sin \alpha ,0} \right) + t\,{\bf q} \cr}
$$
where
$$
\left\{ \matrix{
  \alpha  =  - \pi /2\quad  - 1 < s < 1\quad 0 \le t \le 1 \hfill \cr
   - \pi /2 < \alpha  < \pi /2\quad s = 1\quad 0 \le t \le 1 \hfill \cr
  \alpha  = \pi /2\quad  - 1 <  - s < 1\quad 0 \le t \le 1 \hfill \cr
  \pi /2 < \alpha  < 3\pi /2\quad s =  - 1\quad 0 \le t \le 1 \hfill \cr}  \right.
$$
Then we can develop half of the surface as indicated, by putting for the flattened conic part that
$$
q(\alpha )d\beta (\alpha ) = d\alpha \quad \left| \matrix{
  \,q = \left| {\bf q} \right| \hfill \cr
  \,s = 1 \hfill \cr}  \right.
$$
Comment: The other suggestion in that question, the convex hull of a line segment and a circle, *is* a developable surface. Does that answer your question?
Comment: On the other hand the tetrahedral milk carton will actually form exactly a tetrahedron with four flat triangular faces.
Comment: @Rahul what do you mean by *convex hull* ? made by straight lines ? if so, how do you relate (map)  the end points $P(s)$ on the segment with $Q(r \alpha)$ on the circle? under a linear map I am not sure it will be developpable. That's the core of the question.
Comment: @Rahul One matter is to make up a tetrahedron by taking a piece of paper, draw the four triangles connected on a hedge, fold it and solder on three edges. Another is to start from a cylinder, pinch and solder it at the ends, making them more or less straight, in case trimming straight the joints. Just think and cut open a milk carton ..
Comment: Careful: the curved sections do not unfold to sectors of a circle, because they are not portions of *right* circular cones. After all the three angles at the apex of each isosceles triangle should add up to $180^\circ$.
Comment: oohps, you are .."right" ! the half cones are not *right* : their median generatrix is (if the pinch equals the diameter). But I do not get your remark about the triangles.
Comment: I mean there should not be two "corners" where the arcs meet; they should form a single differentiable contour. After all if you look at the two sliver triangles on both sides of the large one in my discretized figure, all three are almost coplanar, and *their* angles at the shared vertex add up to almost $180^\circ$. In the limit this tells you something about the angle between the contour's tangents on either side.
Comment: A better approximation might be a single circular arc centered at roughly $(0,-2)$ in your figure.
Comment: @Rahul: so I re-elaborated the situation and edited the P.S., and in fact the sector is almost circular (for $h>>c$ )
Answer: The convex hull of a circle and a line segment is developable. I don't know if this is the unique developable surface with the given boundaries.

(Ignore the extra chords drawn in the circle.)
I'm fairly sure that if you start with a cylinder and pinch it flat at both ends, a perfectly flat tetrahedron is the only developable surface you can get. The curved nature of the real-world milk cartons is because the material is slightly extensible (it has a coating of plastic to make it liquid-proof). Better intuition can be gained by trying the experiment with a sheet of plain paper instead.
Comment: this solid, with the right proportions chosen, can cast a shadow of a circle, a square, or an equilateral triangle. From a book I read as a child.
Comment: @WillJagy: Usually people have [a slightly different shape](https://math.stackexchange.com/a/1947378/856) in mind for that problem, though this one works too. However I think it is impossible to have a circle, a square, and an *equilateral* triangle as shadows, because the altitude of the triangle is too short.
Comment: I guess you are right, if you tilt it just a little you get an elliptical arc as part of the shadow.

Calippo, toothpaste and milk .. packing


ASP.NET Core middleware vs filters

Question: After reading about ASP.NET Core middleware, I am confused about when I should use filters and when I should use middleware as they seem to achieve the same goal.
When should middleware be used instead of filters?
Comment: This documentation targets that specific question. https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters#using-middleware-in-the-filter-pipeline
Comment: Steve Gordon explained the middleware vs filters in his "Anatomy of ASP.NET Core Requests" talk at the NDC Conference 2020. https://youtu.be/0UZf_7c_EeE
Answer: There is a video about this on channel 9:  ASP.NET Monsters #91: Middleware vs. Filters. To summarize the video:
The execution of request starts and we have a middleware, and another middleware, think of it like the "Russian dolls inside of dolls"  and eventually the routing middleware kicks in and then request goes into the MVC pipline.

So if you don't require the context  of MVC (let's say you're concerned about flow and execution, like responding to headers some pre-routing mechanism, etc.) then use middlewares.
But if you require the context of MVC and you want to operate against actions then use filters.
Comment: Can't you have filters in an .NET Core Web API (which is not MVC)?
Comment: So, if I have logic I want to run on every request (Logging for instance) only some of which are MVC related, I would put that in the middleware, then have the filter handler do whatever specific logic may be required for it, then rethrow to the middleware?
Answer: Middleware operate on the level of ASP.NET Core and can act on every single request that comes in to the application.
MVC filters on the other hand only run for requests that come to MVC.
So for example, if I wanted to enforce that all requests must be done over HTTPS, I would have to use a middleware for that. If I made an MVC filter that did that, users could still request e.g. static files over HTTP.
But then on the other hand something that logs request durations in MVC controllers could absolutely be an action filter.
Answer: The execution of middleware occurs before the MVC context becomes available in the pipeline. That is, middleware does not have access to the ActionExecutingContext or the ActionExecutedContext in the case of an ActionFilter for example. What you do have access to is the HttpContext, which will allow you to perform actions on the request as well as the response. Since model binding hasn't occurred yet, using middleware would not be suited to running a validation function or modifying values. Middleware will also run on every request regardless of which controller or action is called.
On the other hand, filters will only run on specified actions and controllers unless you register the filter globally in the startup. Since you have full access to the context you can also access the controller and action itself.
Source and example: thetechplatform.com
Comment: Your answer really help me understand clearly something. Thank you.
Comment: The attached link seems to be broken and dead
Comment: just replaced the link
Answer: Filter pipeline is similar to middleware pipeline in many ways, but they also have some differences that should be considered when deciding which approach to be used.
What are the similarities:

Incoming requests pass through a middleware component and outgoing responses to those requests are passing again through the same middleware when going to the client. Some filters (resource, action, and result) are also two-way, others (authorization and exception) run only once for a request, and page filters (Razor pages specific) run three times.
Middlewares can short-circuit a request by directly returning a response, instead of executing the entire middleware pipeline and not passing the request down to later middlewares. Filters can also short-circuit the filter pipeline by directly returning a response.
Middlewares are used for cross-cutting concerns (eg: logging, performance profiling or exception handling). Filters are also used for dealing with cross-cutting concerns.

What are the differences:

A middleware can run for all requests while filters will only run for requests that reach the EndpointMiddleware and execute an action from an API Controller or a Razor Page.
Filters have access to MVC components (eg: ModelState or IActionResults). Middleware works at a lower level compared to filters and is independent of MVC and Razor Pages, so it can't use any of those related components.
Filters are designed to be applied to a subset of requests, not to all of them. For instance, we can apply a filter on a single controller or a single Razor Page. In contrast, middlewares don't have this kind of design.

So, when trying to figure out what should use: filters or middlewares, the answer should come from the above comparison.
As a TL;DR:

middleware is the more general concept, which operates on lower-level abstractions like HttpContext, so can be applied in a wider area. Also we should be aware of the fact that the functionality we need to implement has no MVC-specific requirements
filters can enable us the usage of MVC-constructs and can be used for implementing custom and specific behavior for some MVC actions. It is not so general as middleware.
Answer: According to my experience Middleware can be used for the entire request pipeline but Filters is only used within the Routing Middleware where we have an MVC pipeline so Middleware operates at the level of ASP.NET Core but Filters executes only when requests come to the MVC pipeline.

ASP.NET Core middleware vs filters


How to run the PJSIP in xcode?

Question: I'm new with XCode and still trying to understand objective-C. I'm using xcode 4.3.2, and I have to create an app that integrates with PJSIP.
I found this link. I am still confused about that link, because the article said that we must have installed the command line tool. But the command line tool is already installed in my XCode. How can i use it?
Do I need to create a view base application? how can I run the command line tool like the link says?
Comment: Not any more it doesn't. Xcode 4 now comes as a bundle and doesn't use the `/Developer/` folder any more. The path you are talking about is `/Applications/Xcode.app/Contents/Developer/usr/bin`
Comment: How did you install PJSIP?  Did you have to build it, or was a binary download available?
Comment: actually i just download the .zip file, after that i extract it. and finally don't know how to use it, then i search for the article and found that link. Do you ever use the PJSIP?
Comment: The Xcode installer installs command-line tools in /Developer/usr/bin. you can find it that path.
Comment: @Abizern i just found alot of command line at  /Applications/Xcode.app/Contents/Developer/usr/bin. how can i use it? there are instruction like this "$ cd /path/to/your/pjsip/dir
$ ./configure-iphone
$ make dep && make clean && make". How can i run it?
Answer: The command line tools allow you to compile "traditional UNIX programs" from source, generally using make.  If you are using Xcode to create your projects then you don't even need them installed.
EDIT OK you have edited your question, stating the real issue you are facing; You don't know how to use the PJSIP package you have installed.  The link you reference is about building PJSIP, not using it, so you can still forget about the command line and concentrate on how to configure your Xcode project to use PJSIP.  This will require setting the header search paths and library search paths to find the header files and library file, in order to compile and link against it.  Hopefully it's a static library as that will be easier to use; if it's a dynamic library or framework then you have your work cut-out as that's much harder to use.
Comment: Unless you want to use the version of git that comes with Xcode if you don't already have it installed
Comment: thanks for your answer.this is the link http://trac.pjsip.org/repos/wiki/Getting-Started/iPhone#OtheriPhoneProjects, but i still don't know how to use the command tool. should i create a new project->view base app first?
Comment: @Abizern But as mentioned, if you are using Xcode, then you won't be going near the command line anyway.
Comment: @AlfredAngkasa OK you didn't mention anything about PJSIP in your question, and so your question should have been about how to build it rather than about the command line.
Comment: I'm just pointing it out incase somebody wants to use git but doesn't want to install it themselves. You can use the basics of it through Xcode without going to the command line.
Comment: @trojanfoe thanks for your answer. i will make this usefull by click it once. thanks.
Answer: In newer XCode (4.3 or above) you might have to install command line tools since it has been made optional. Open XCode and go to XCode->Preferences
Open the Downloads panel and click on "Components". If Command Line Tools are not installed already, you will get an option to install them from here.
Do so and you are set.
Comment: but after that how to use it? what is the purpose of using command line tool?
Comment: I don't think you need to use it explicitly.
Answer: I done with it by myself. if you face the same problem, you can refer to this link, I already tried and run it. It works both on simulator and device. thanks.

How to run the PJSIP in xcode?


Why aren't there barlines in the piano solo parts in Beethoven's Piano Concerto No. 5?

Question: In the beginning of this piece you'll notice that the piano solo part has no barlines. Why? And why does he use 16th notes? How can a "16th" note have any meaning without barlines (not to mention triplets and septuplets)? Is this just a way to invite a virtuoso pianist to play it however she wants without the constraint of barlines?
Score at imslp
YouTube with score
Answer: This is a cadenza. The lack of barlines is, as you suppose, because Beethoven intends the performer to play in a rhythmically free, quasi-improvised manner. The pitch durations are intended to be suggestive -- relative to each other -- but not necessarily exact.

Another example is the opening of Chopin's Etude in C# minor, op. 25 no. 7. Notice that there is no time signature at the beginning. However, the editor of the score in the video has put in some suggested barlines as a guide to the performer. On the other hand, on IMSLP, Mikuli's edition (below) does not include those.

Another example comes from the final bar of Chopin's Etude in E minor, op. 25, no. 7 (Mikuli's edition again)

Also, regarding your question "How can '16th' note have any meaning without barlines", the answer is that the note values are not influenced by the presence of barlines. In strict tempo, a 16th is always the duration of two 32nds or half of an 8th. The note durations are only relative to each other. Barlines are, essentially, a convenience for reading -- so that you can easily see groupings of beats.
Comment: Barlines may be for the reader's convenience, but bars are not! Bars are super-important!


Let $G$ be connected graph, r-regular, show that if $G^c$ is connected then....

Question: can you help me, if what I wrote is ok?
Let $G$ be connected graph, $r-regular$, show that if $G^c$ (G's complement) is connected, the:
a) $G$ or $G^c$ is eulerian
b) $G$ or $G^c$ is hamiltonian
$G$ has order $n$, if $G^c$ is connected the $G^c$ is $(n-r-1)-regular$
a)

$G$ is eulerian if $r$ is even
if $r$ and $n$ are odd then $G$ is no eulerian, and $G^c$ woluld be n(odd) - r (even) - 1  regular and this operation is an odd number, so none of them is eulerian (I'm not sure about this, because it says that $G$ or $G^c$ is eulerian but in this case none of them is eulerian)
if $r$ is odd and $n$ is even then n(even) - r(odd) - 1 this operation is and even number, then $G^c$ is eulerian

b)
A graph is hamiltonian if all its vertex has degree $\geq n/2$ so we know that $r \leq n- 1$

As $G$ is r-regular then in orden to be hamiltonian $r\geq n/2$ this way all its vertex fits with the condition said above.
$G^c$ is $(n-r-1) - regular $ then: $n-r-1 \geq \frac {n}{2}$ which is: $\frac {n}{2} - 1 \geq r$ which indicates that $\frac{n}{2} -1 \leq r \leq \frac {n}{2}$ in order to $G^c$ hamiltonian

is this the way to show it? I'm not sure, just an idea.
Answer: a) Hint: can both $r$ and $n$ be odd?
b) I assume that $n\ge 3$. Assume that both $G$ and $G^c$ are not Hamiltonian. Then $r<n/2$ and $n-r-1<n/2$. If $n$ is even then we have $r\le n/2-1$ and $n-r-1\le n/2-1$. Adding these inequalities, we obtain that $n-1\le n-2$, a contradiction. So $n$ is odd. If $r<(n-1)/2$ or  $(n-r-1)<(n-1)/2$ then similarly to the previous we obtain a contradiction. Thus $r=n-r-1=(n-1)/2$ and both $G$ and $G^c$ are   Hamiltonian by Nash-Williams theorem.
Comment: @DanielaVelásquezGarzón Yes, both $r$ and $n$ cannot be odd, because in this case the sum of degrees of all vertices of $G$ equals $rn$, but this sum also equals twice the number of edges, a contradiction.
Comment: Thank you so much, for case a, I believe this can't happen because all graph has an even number of vertix with odd degre, right?


Rhino - Convert Parameter Map to Native JS object

Question: What's the "right" way to convert the parameters from request into a native JS object?
It seems that no matter what I do, I end up with a java object.
Answer: PrimitiveWrapFactory will do what I'm looking for, but the easiest way is to just call:
String(javaObj), since I always want them as strings.


Sequence to sequence autoencoder - decoder input?

Question: What's the input to the decoder part of a sequence to sequence autoencoder? I've seen certain examples of such an autoencoder (using LSTM's more often than not) but am still unclear.

For example, here in this often-cited paper by Dai & Le ('Semi
Supervised Sequence Learning'), we have the following diagram:

What's the input to the decoder portion of the autoencoder here? In this example it's 'W-X-Y-Z.' But in general, is
it the same as the input to the encoder? Or is it using the output
from the previous timestep/LSTM cell as input?
Similarly, in another popular paper by Srivastava et. al
('Unsupervised Learning of Video Representations using LSTMs'), they
have the following diagram:

It seems they're using the reversed input from the encoder as input
here. However, there's a section as follows:

The decoder can be of two kinds – conditional or unconditioned. A conditional decoder receives the last generated output frame as
  input, i.e., the dotted input in Fig. 2 is present. An unconditioned
  decoder does not receive that input.

In the unconditioned decoder, what input does the decoder receive?

Thank you! I'm new here, so please be kind :)
Answer: If I understand the Semi-supervised Sequence Learning paper correctly, the input to the decoder-portion of the autoencoder is the same as it would be for an ordinary language model. The authors state:

We also find that recurrent language models [2, 24] can be used as a pretraining method for LSTMs. This is equivalent to removing the encoder part of the sequence autoencoder in Figure 1

Thus, it should be the same input that is fed to the encoder. The difference, then, would be that the hidden state of the decoder is initialized with the last hidden state of the encoder.


How to handle valid missing values in a classification problem?

Question: I would like to predict a binary output based on borrower's informations in a bank credit demand/file.
My problem is that this file can be filled either by

a single borrower (celibate)
or 2 borrowers (couple)

My dataset looks like this:
nb_of_B | B1_Info1 | ... | B1_InfoN | B2_Info1 | ... | B2_InfoN
(B means Borrower, and I have about N = 15 informations for each borrower)
Then, I have automatically normal missing values in B2_InfoX variables in the case of there is just 1 borrower (nb_of_B = 1).
I've found many posts on how to interpolate/impute missing data but in this case, it would not make any sense!
So my question is: Which classification algorithm can handle theses normal missing values?
Do I have to find a workaround? like making 2 models, one for the case nb_of_B = 1, the other for the case nb_of_B = 2?
Any other solution?
How can we generalize this type of problem for a bigger situation, like files with potentially 10 borrowers? (10 is the limit and I don't expect it to increase)
For information, the number of files decrease drastically as the number of borrowers exceed 2 borrowers and I cannot make a unique model for the case of 10 borrowers because there is too few files to learn. Below is the distribution:
1 borrower -> 62,57%, 2 borrower -> 36.48%, ... 10 borrowers -> 0,0015% so 99% of my files fall into 1 or 2 borrowers
Thanks for your answers,
Mat
Comment: do you know the max no of borrowers possible ? i mean like is 10 the limit or do you expect it to increase ?
Comment: In this case, 10 is the limit and I don't expect it to increase. but to give you more insight, it's distributed like this.
1 borrower -> 62,57%, 2 borrower -> 36.48%, ... 10 borrowers -> 0,0015%
so 99% of my files fall into 1 or 2 borrowers
Comment: Would be good to edit your question to include the extra information from your comment.
Comment: That's right. It's done. ;-)
Answer: Well , it would make sense if you do some intelligent feature engineering-that way you have a single model for all.
For example if you have salary of the person as a feature you could use two features - total salary (sum of the salaries) and average salary (maybe drop one, like average ). All the while keeping the num borrowers as a feature in itself.
You should think of it this way does an increased total salary necessarily help you to predict or not ? you could also extract other statistics but keep in mind what makes sense for the problem. This could be a good starting point.
Why, Im suggesting this is because we have done something like this in the medical domain for example when using patient reading's for diagnosis. In our case the number of readings per patient varied drastically ... um well you can figure that each patient stays for a different duration. Hand engineered Statistical features (mean ,median,mode) and interpolation of missing values worked best for us... Interpolation doesn't make sense in your case ,Im hopeful that statistical features will work for you .
Comment: Thanks for your answer Vaibhav.
'Well , it would make sense if you do some intelligent feature engineering-that way you have a single model for all.' Yes that's the strategy I would primary like to follow. For quantitative variable, I've already done some feature-engineering like you say. What about categorical data like "socio-professional category" (40 modalities)? any Idea to "aggregate" this kind of data for every borrower in an intelligent way?
Comment: one idea that comes to mind is to consider modalities as a collection of words effectively forming a document for each sample.This way each sample becomes a document. use one-hot, tf-idf. eg your document :-[1,12,0,0,0,0,0,0,0,0] for two borrowers in case one is a banker(1) and second is  doctor(12). then onehot this.you will have to experiment with what works . Hope this Helps !!!
Comment: Yes, very good idea!
I'll try to implement it. Thx!


Connect four game logic

Question: Building a connect four game as my first js project. My game has a background photo of a Connect Four game board and an HTML table on top to hold the tokens. The tokens are images that I will drag onto the board.
So far I have the code(below) which allows me to drag the tokens onto the game board.

var dragYellow = document.getElementById('yellowToken1');
var dragRed = document.getElementById('redToken1');
var dropLoc = [];

function locOnDrop(e) {
 e.preventDefault();
 e.currentTarget.appendChild(
  document.createElement('img')
 ).src = document.getElementById(
  e.dataTransfer.getData('key')
 ).src;
}

gameGrid = [ [1, 2, 3, 4, 5, 6, 7],
          [8, 9, 10, 11, 12, 13, 14],
          [15, 16, 17, 18, 19, 20, 21],
          [22, 23, 24, 25, 26, 27, 28],
          [29, 30, 31, 32, 33, 34, 35],
          [36, 37, 38, 39, 40, 41, 42],
          ];

for(var i = 0; i < gameGrid.length; i++){
     for(var j = 0; j < gameGrid[i].length; j++){

     dropLoc[gameGrid[i][j]] = document.getElementById(gameGrid[i][j].toString());
     dropLoc[gameGrid[i][j]].ondrop = locOnDrop;

     dropLoc[gameGrid[i][j]].ondragover = function(e) {
         e.preventDefault();
     }
 }
}

There are numerous 'check for winner' examples, but they are all based on games utilizing arrays instead of tables. The closest I found was this question asked in 2012(see below). The best answer suggested was NOT to use DOM transversal, but rather a 2D array. I'm ok with that, but how would I get my table to "communicate with the array? If I'm drag & dropping the pieces into a table how will I connect these moves with the array?
algorithm connect four javascript
Not to complicate matters, but for the end result I want to just drop the tokens at the top of each column and let them drop down to the lowest available position just like in the real game. I'm only mentioning this in case affect the answer to my first question.
Thank you!
Comment: Could you give us a complete working example?
Comment: not sure how I would do that. The background , gameboard and token images are saved on my computer. I can post the HTML and CSS files as well if that helps?
Comment: here's the HTML
Comment: @JeffS to get best answer here try to add your code at http://jsfiddle.net or http://codepen.io/. Then link your code here. As your project is html + js + css you will have no problem. People can help you much more when they can see and run your code
Answer: The way you communicate is by making sure (like the answer mentioned) that your table is only JUST a visual representation of your data which in this instance would be stored in a 2D array.
So you should engineer your code so that is doesn't flow
-> from HTML to JS but
-> from JS to HTML
By that I mean instead of thinking how the car should look and then build your engine according to that, figure out how the engine will turn out first and then build your car around it.
In this instance the answer in the other Stack question gives a good pointer for that.
If I was to try to tackle this problem I would (in no particular order):

Create a function that allows users to "fill" a certain spot
Function that checks if a specific spot is taken
Function that check if this newly played move is winning combination
Function to place a certain token whether red or yellow in a given slot

There might be more that come up and all but this is just to give you an example. You see a lot of the things that are happening here are all calculation or algorithm based which happens inside the JS and there's very few interaction with the actual DOM.
The only one I've listed here is to add a token. You have all the information you need about your game stored in your 2D array for these functions to work.  It is ONLY when something needs to be physically modified that your application say to the DOM: "Hey, add a yellow token at this spot" and so on.
Then of course these variously created function These functions can be mapped to your DOM by attaching events handler, etc... but hopefully you get the point.
Answer: While you could do something to figure out the position of a given cell in the row, and the position of the row in the table (for example, when you click a TD or the like), the simplest way is probably to actually build the data into the table.
For example, if your HTML table looks like:

It becomes pretty trivial to use jquery or similar to find the right position that maps to the array info.  For that matter, if each cell has a unique number (as your sample suggests) you could even just have each TD have that info stored as data-position="12" or the like and make the query even easier.
In jquery you could just use $('td[data-position=12]') to grab the element directly.
Answer: per @Alireza Fattahi request
https://jsfiddle.net/lgehrig4/thg468ex/
what my code accomplishes so far
1. visuals (background, gameboard, tokens)
2. Grab player names(2 player only. Not against the computer)
3. Randomly picks a player to start
4. Can drag and drop tokens onto the board

//SETUP
var button = document.getElementById("setStart");
var gameActive = false;

//GRAB PLAYER NAMES / CHOOSE FIRST MOVE /RESET BOARD
function setStart() {

 if (gameActive == false) {
  playerOne = prompt("Player One(yellow) please enter your name");
  playerTwo = prompt("Player Two(red) please enter your name");
  document.getElementById("yellowPlayer").innerHTML = playerOne;
  document.getElementById("redPlayer").innerHTML = playerTwo;
  gameActive = true;
 }
 players = [playerOne, playerTwo];

 if (gameActive == true) {
        first = Math.floor(Math.random() * 2);
        alert(players[first] + " you go first");
 }
}

//MOVE TOKENS TO BOARD

var dragYellow = document.getElementById('yellowToken1');
var dragRed = document.getElementById('redToken1');
var dropLoc = [];

function locOnDrop(e) {
 e.preventDefault();
 e.currentTarget.appendChild(
  document.createElement('img')
 ).src = document.getElementById(
  e.dataTransfer.getData('key')
 ).src;
}

gameGrid = [ [1, 2, 3, 4, 5, 6, 7],
          [8, 9, 10, 11, 12, 13, 14],
          [15, 16, 17, 18, 19, 20, 21],
          [22, 23, 24, 25, 26, 27, 28],
          [29, 30, 31, 32, 33, 34, 35],
          [36, 37, 38, 39, 40, 41, 42],
          ];

for(var i = 0; i < gameGrid.length; i++){
     for(var j = 0; j < gameGrid[i].length; j++){

     dropLoc[gameGrid[i][j]] = document.getElementById(gameGrid[i][j].toString());
     dropLoc[gameGrid[i][j]].ondrop = locOnDrop;

     dropLoc[gameGrid[i][j]].ondragover = function(e) {
         e.preventDefault();
     }
 }
}

dragYellow.ondragstart = function(evt) {
    evt.dataTransfer.setData('key', 'yellowToken1');

dragRed.ondragstart = function(evt) {
    evt.dataTransfer.setData('key', 'redToken1');
}
* {
 margin: 0;
 padding: 0;
}

body {
 background: url("img/table.jpg") no-repeat;
 background-size: cover;
 background-position: bottom;
}

#game {
 background: url("img/background1.png");
 position: relative;
 width: 700px;
 height: 700px;
 margin-left: 260px;
 margin-top: 120px;
 /*z-index: -1;*/
}

table {
 position: absolute;
 right: 117px;
 top: 120px;
 border-spacing: 0px;
 z-index: 2;
}

td {
 width: 66px;
 height: 59px;
 text-align: center;
}

#yellow {
 position: absolute;
 width: 50px;
 height: 50px;
 left: 220px;
 top: 520px;
 z-index: 3;
}

#red {
 position: absolute;
 width: 130px;
 height: 50px;
 left: 341px;
 top: 520px;
 z-index: 3;
}

.image {
    position: relative;
    width: 50px;
    height: 50px;
}

button {
 position: relative;
 width: 200px;
 height: 50px;
 left: 1100px;
 top: 700px;
 border: 2px solid black;
 border-radius: 15px;
 background-color: green;
 color: white;
 font-family: monospace;
 font-weight: bold;
 font-size: 2em;
 text-transform: uppercase;
}

button:hover {
  background-color: lightgreen;
  color: black;
}

/*player one div*/
#playerOne {
 position: relative;
 width: 165px;
 height: 110px;
 left: 1120px;
 top: 475px;
}

/*player two div*/
#playerTwo {
 position: relative;
 width: 165px;
 height: 110px;
 left: 1120px;
 top: 510px;
}

/*player one name*/
#yellowPlayer {
 width: 160px;
 height: 25px;
 background-color: yellow;
 border: 2px solid black;
 border-radius: 15px;
 text-align: center;
 text-transform: uppercase;
 font-family: monospace;
 font-size: 15px;
}

/*player two name*/
#redPlayer {
 width: 160px;
 height: 25px;
 background-color: red;
 border: 2px solid black;
 border-radius: 15px;
 text-align: center;
 text-transform: uppercase;
 font-family: monospace;
 font-size: 15px;
}

h3 {
 text-align: center;
}

#playerOneWins {
 width: 50px;
 height: 50px;
 border: 2px solid black;
 border-radius: 50px;
 margin: auto;
}

#playerTwoWins {
 width: 50px;
 height: 50px;
 border: 2px solid black;
 border-radius: 50px;
 margin: auto;
}
<!DOCTYPE html>

 <meta charset="utf-8">
 <title>Connect Four</title>
 <link rel="stylesheet" type="text/css" href="connect.css">

WINS

WINS

 <button id="btn" onclick="setStart()">New Game</button>

Comment: Edit your question and add the html there instead of sending an answer

Connect four game logic


Manipular eventos do windows usando Python

Question: Preciso desenvolver uma aplicação em Python com Pop-up's no Windows (como o Avast, por exemplo). No caso, minha aplicação será um keylogger que pegará uma string de um leitor de código de barras. Quando o keylogger detectar o código, um pop-up surgirá com as informações do boleto.
Que ferramenta do Python eu posso utilizar para manipular este evento?
Comment: Procure por "python desktop notification". [Nessa pergunta do SOen](http://stackoverflow.com/q/2240674/520779), por exemplo, há algumas opções - dentre elas [uma multi-plataforma](http://code.google.com/p/readertray/source/browse/trunk/readergui.py) que parece bem simples (usa o `wx` que, se não me engano, vem incluída no Python). Nunca usei pessoalmente entretanto, por isso não saberia avaliar se é boa ou não.
Comment: A propósito, aqui no StackOverflow nós normalmente não utilizamos saudações e agradecimentos nas perguntas, daí a sugestão de edição. Veja [esse post no meta](http://meta.pt.stackoverflow.com/q/846/215) para mais detalhes. P.S. Uma coisa não está clara na sua pergunta: é só notificações ao usuário que você está interessado, ou tem mais coisa? (ex.: chamadas de API, manipulação de registro, COM, MFC...) "Eventos do windows" me parece um pouco genérico demais, poderia por favor editar sua pergunta colocando mais detalhes?
Comment: Ok, desculpe pelo transtorno. Adicionei mais detalhes a minha pergunta.
Answer: Por se tratar de uma script que rodará no Windows, pode ser utilizado a função Shell_NotifyIcon para mostrar o popup.
Exemplo:
from win32api import *
from win32gui import *
import win32con
import sys, os
import struct
import time

class WindowsBalloonTip:
    def __init__(self, title, msg):
        message_map = {
                win32con.WM_DESTROY: self.OnDestroy,
        }
        # Register the Window class.
        wc = WNDCLASS()
        hinst = wc.hInstance = GetModuleHandle(None)
        wc.lpszClassName = "PythonTaskbar"
        wc.lpfnWndProc = message_map # Também poderia especificar uma wndproc.
        classAtom = RegisterClass(wc)
        # Criar a Janela.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = CreateWindow( classAtom, "Taskbar", style, \
                0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
                0, 0, hinst, None)
        UpdateWindow(self.hwnd)
        iconPathName = os.path.abspath(os.path.join( sys.path[0], "balloontip.ico" ))
        icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
        try:
           hicon = LoadImage(hinst, iconPathName, \
                    win32con.IMAGE_ICON, 0, 0, icon_flags)
        except:
          hicon = LoadIcon(0, win32con.IDI_APPLICATION)
        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
        nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "tooltip")
        Shell_NotifyIcon(NIM_ADD, nid)
        Shell_NotifyIcon(NIM_MODIFY, \
                         (self.hwnd, 0, NIF_INFO, win32con.WM_USER+20,\
                          hicon, "Balloon  tooltip",msg,200,title))
        # self.show_balloon(title, msg)
        time.sleep(10)
        DestroyWindow(self.hwnd)
    def OnDestroy(self, hwnd, msg, wparam, lparam):
        nid = (self.hwnd, 0)
        Shell_NotifyIcon(NIM_DELETE, nid)
        PostQuitMessage(0)

def balloon_tip(title, msg):
    w=WindowsBalloonTip(title, msg)

if __name__ == '__main__':
    balloon_tip("Título para o pop-up", "Corpo da mensagem aqui!")

Fonte
Em relação a captura de teclas, você pode usar o PyHook, é um wrapper que permite que seja feito a técnica de Hooking através de um script em Python, além de poder manipular os eventos do teclado, pode-se alterar o comportamento dos eventos do mouse.
O exemplo abaixo captura as teclas digitadas e imprime na tela.
#!/usr/bin/python

import pyHook
import pythoncom

def OnKeyboardEvent(event):
        print event.Ascii

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()

while True:
        pythoncom.PumpMessages()

Para encerrar basta pressionar as teclas CTRL + C.
Answer: Eu já fiz uma aplicação em python que captura e envia eventos do windows, no meu caso do teclado e mouse e utilizei o pywin32
Apesar do nome tem versão para python 64 bit também.
A biblioteca é basicamente um binding, pode ter coisa que você vai ter que ver a documentação da api do windows para C e definir as constantes no seu codigo.
Para instalar recomendo que você baixe o instalador do site dele, escolha a ultima versão da biblioteca e a versão compatível com o seu python (eg: 2.7 64 bit)
Para instalar dentro de um virtualenv você pode usar o easy_install e passar o path local do instalador.exe ou a url.


Using multiple Ultrasonic sensors as counter

Question: I am working on a small project which is using multiple ultrasonic sensors to detect a movement object and count it(such as a car). I use switch case but the program is not going to the all cases, therefor it is not working properly and the counter is not increase either decrease. i tested each sensor and realized they are worked. but I don`t know why i cant get a result with this code , if you help me i appreciated in advance ... below is my code
     const int sensorNum = 2;

uint8_t reading_0;
uint8_t reading_1 ;

int sensing[sensorNum][2];

unsigned long duration = 0; //period between transmit time and receive time in microSeconds
float distance = 0.00;      //distance in centimeter
const float fixedDistance = 30.00;
const float vilocity = 0.034;   //Vilocity of ultrasonic waves = 340 m/Sec = 0.034 cm/uSec
//const float cmDivisor = 29.4118;

float reading = 0.00;
int carCounter =200;
int PCarCounter=0;
int capacity = 200;
//int activate = LOW;
uint8_t current_ENTERstate = 0;

const uint8_t RESET = 0,CAR_START2EN=1,CAR_ENTERING=2,CAR_EN1=3,CAR_ENTERED=4;

void setup()
{
  Serial.begin(9600);
  for(int i = 0; i<sensorNum; i++){

    sensing[i][1]=LOW;
    sensing[i][2]=LOW;
    pinMode(i+2,OUTPUT);
    digitalWrite(i+2,LOW);
    pinMode(i+8,INPUT);
    digitalWrite(i+8,LOW);
    current_ENTERstate = 0;

  }
}

//==============================================================

void loop()
{
    for(int l=0; l<2; l++){

          reading_0 = calcDistance(2,8);
          reading_1 = calcDistance(3,9);

              if(reading_0 > 30.0 && reading_0 < 200.0) {
                sensing[0][l] = HIGH;
              }else if(reading_0 < 30.0 || reading_0 > 200.0) {
                sensing[0][l] = LOW;

              }
              if(reading_1 > 30.0 && reading_1 < 200.0) {
                sensing[1][l] = HIGH;
              }else if(reading_1 < 30.0 || reading_1 > 200.0){
                sensing[1][l] = LOW;

              }

    }
switch(current_ENTERstate){

      case RESET:
        if(sensing[0][0]||sensing[0][1]){

          current_ENTERstate = CAR_START2EN;

          break;
        }else{
          current_ENTERstate = RESET;
          break;
        }
        break;
      case CAR_START2EN:
        if( sensing[0][0]||sensing[0][1] && sensing[1][0]||sensing[1][1] ){
          current_ENTERstate = CAR_ENTERING;
          break;
        }else{
           current_ENTERstate = RESET;
          break;
        }
        break ;
      case CAR_ENTERING:
        if(  sensing[1][0]||sensing[1][1] ){

           current_ENTERstate = CAR_EN1;

          break;
        }else{
           current_ENTERstate = CAR_START2EN;
          break;
        }
      case CAR_EN1:
        if( sensing[0][0]==LOW && sensing[0][1]==LOW && sensing[1][0]== LOW && sensing[1][1]==LOW ){
           current_ENTERstate = CAR_ENTERED;

          break;
          }else{
           current_ENTERstate = CAR_ENTERING;
          break;
          }
     case CAR_ENTERED:
          carCounter++;
          break;

     default: RESET;
  }       // switch end

}
//====================================================================================

float calcDistance(int trigger, int echoPin){

    digitalWrite(trigger,LOW);
    delayMicroseconds(2);
    digitalWrite(trigger, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigger,LOW);

    duration = pulseIn(echoPin,HIGH,40000);
    distance = vilocity * duration / 2.0;

 //Serial.print(distance);
  return distance;
}

Comment: It is much more: every time I see a `1` I have to look twice to see if it's an `l` and vice-versa.
Comment: Please don't use `l` as a variable name. It makes code like `sensing[1][l]` tricky to follow.
Comment: What @WeatherVane says.  Also from a practical point of view you would do well to add some hysteresis between HIGH and LOW switching, because sensors are generally "noisy"; for example while it must be >30.0 to go HIGH,  you might require it to fall below say 28.0 to go LOW.  In principle you do have some tiny hysteresis because when the value is *exactly* 30.0 you do not change the state, but being floating point that is an unlikely situation.
Comment: its just an (L) letter and nothing more .
Comment: `default: RESET; ` ?
Comment: ok bro , sorry next time i will not do like that
Comment: In `if( sensing[0][0]||sensing[0][1] && sensing[1][0]||sensing[1][1] )` do you realise that `&&` takes precedence over `||`?
Comment: The easiest way to test this is to build the build with a stub for `calcDistance()` that provides the expected sequence of measurements, and then set through the code in a debugger.  If you want debugging assistance you would do well to describe the algorithm and how you expect it to work and how it actually works.  Even without a debugger, some simple trace-debug prints to the console will help.
Comment: This is not C, but likely Arduino.
Comment: You have not elaborated on what it should do and what it *does* do, only stating that it does not enter *all* the states; you have provides less diagnostic information than that available to you and expect a diagnosis.
Comment: Having every `case` statement executed is entirely dependant on the logic within those `case` statements that change the state, which is where I previously pointed out a possible error in your logic. So I suggest you re-examine them, and put (brackets) round anything you are unsure of, to force the logic to behave the way you want it to, since I don't know if Arduino has different precedence rules.
Comment: @KarzanA.Raza : Whose comment are you referring to that you cannot understand?  It is difficult to provide detail in the comments.  I will post an answer in the hope that it is in fact a solution, but the reason for the comments is that it is not yet clear what your problem is.
Comment: @WeatherVane : Arduino "Sketches" are essentially C++ (so the order of precedence is the same as C), a framework is provided so that you define two functions `setup()` and `loop()`, and the Ardunio executive calls `setup()` once and `loop()` repeatedly. The environment takes care of details such a linking the necessary libraries etc. but the code is ultimately compiled as C++ using GCC for AVR.
Answer: The following is suspicious (credit to @WeatherVane for spotting it):
if( sensing[0][0]||sensing[0][1] && sensing[1][0]||sensing[1][1] )

Because && is evaluated before ||The conditional expression is evaluated as if it were written:
a = sensing[0][1] && sensing[1][0] ;
if( sensing[0][0] || a || sensing[1][1] )

which seems unlikely to be the intention.  It should probably be written thus:
if( (sensing[0][0] || sensing[0][1]) &&
    (sensing[1][0] || sensing[1][1]) )

(line break added for clarity).
With respect to the sensing, you should add some hysteresis when reading noisy sensors. To avoid repeating a great deal of high-maintenance code it would be better to define a function
void distanceHighLow( float reading, int& sensing ) ;
{
    static const float HYSTERESIS = 2.0f ;
    static const float MIN_DISTANCE = 30.0f ;
    static const float MAX_DISTANCE = 200.0f ;

    if( reading > MIN_DISTANCE &&
        reading < MAX_DISTANCE )
    {
        sensing = HIGH;
    }
    else if( reading < (MIN_DISTANCE - HYSTERESIS) ||
             reading > MAX_DISTANCE + HYSTERESIS)
    {
        sensing = LOW;
    }
}

Then you call this function thus:
distanceHighLow( reading_0, sensing[0][l] ) ;
distanceHighLow( reading_1, sensing[1][l] ) ;


Eigenvalues of positive semidefinite matrix

Question: Today I found a problem concerning positive semidefinite matrix:
Suppose $A$ is a positive semidefinite matrix, with eigenvalues: $\lambda_1\geq\dots\geq\lambda_n$, and diagonal elements: $a_{11}\geq\dots\geq a_{nn}$.  Now prove that, for any $k\leq n$, $\sum_{i=1}^k\lambda_i\geq\sum_{i=1}^ka_{ii}$.
Now for $k=1,n-1,n$, the problem is trivial. But what about the other $k$?
This proposition is very likely to be true as I've run some simulation on MATLAB, without finding any exception.
However this seems hard to prove. I think maybe some transformation needs to be done. Anyone has any clue? Thanks~
Besides there are some background in PCA. I shall provide some supplement if necessary later.
Comment: How do you get $k=1$?
Comment: Consider the fact that $\lambda_1I-A$ is positive semidefinite.
Comment: Is $A$ symmetric?
Comment: yeah of course, that's the requirement of "positive semidefinite".
Comment: The definition I know says that a matrix $A$ is positive semidefinite iff $x^T A x \ge 0$, without requiring $A$ to be symmetric
Answer: By Sylvester's criterion, a symmetric matrix is positive semi-definite if and only if all its principal minors are non-negative. This in particular means that all the principal submatrices are also positive semi-definite themselves. You checked the result for $k=1$, so it is true in general by induction.
Comment: You're right, that's actually a non-trivial step and the eigenvalues of the principal submatrices do not need to be the same as the eigenvalues of the original matrix, I was a bit hasty. It seems that we can bound the eigenvalues of the submatrix between the eigenvalues of the original matrix, according to [this answer](https://math.stackexchange.com/questions/1670000/eigenvalues-of-the-principal-submatrix-of-a-hermitian-matrix).
Comment: Ok I think Ivo Terek got the key. Using those bounds I can indeed solve the problem. Thanks A Lot  !!!!!!!!!!!!!!!  This problem bothers me for a whole day lol.
Comment: I was about to post a similar answer, but I struggled to clarify the relationship between the eigenvalues of the principle minors and the eigenvalues of the full matrix. Could you elaborate on this point?
Comment: yeah it's true, only considering the minors seems not strong enough


Conditional multiplication probability

Question:
In a city, 40% of the inhabitants have one eye, 20% have black skin and 15% have both black skin and one eye. A person is randomly selected from the city.
a.  If he has black skin, what is the probability he also have one eye?
b.  If he has one eye, what is the probability he does not have black skin?
c. If he does not have black skin,  what is the probability he has one eye?
Comment: Make a Venn diagram...
Comment: Who wrote this crappy word problem?
Comment: Sir David please can you explain better thanks
Comment: @Abdul:  Draw a Venn diagram, with a circle representing "have black skin," a circle representing "have one eye," and so on, and adjust their overlapping areas according to the problem statement...
Answer:
In a city, 40% of the inhabitants have one eye, 20% have black skin and 15% have both black skin and one eye. A person is randomly selected from the city.

What you know: $\mathsf P(E)=0.4\\\mathsf P(B)=0.20\\\hspace{-4.5ex}\mathsf P(E\cap B)=0.15$

a.  If he has black skin, what is the probability he also have one eye?

You seek: $\mathsf P(E\mid B)$.   Simply apply the definition of conditional probability.

b.  If he has one eye, what is the probability he does not have black skin?
c. If he does not have black skin,  what is the probability he has one eye?

And similar.  Also use the rule of a complement's probability.

Conditional multiplication probability


Improving UX with views exposed filters: automatically selecting certain options based on a profile value

Question: Background
On my site, users input their birthday, from which I use a computed field to calculate their age.  Then, based on that age, I use rules to add a taxonomy term to their profile to classify  them into one of the following age groups:

20s
30s
40s
50s
60s
70+

I have a view that allows members to search other members' profiles, and on this view I have an exposed filter for the taxonomy vocabulary age group.  The exposed filter widget is converted from a dropdown box to a list of checkboxes using the Better Exposed Filters module.
What I want to do
This works well, but I want to further improve the UX by automatically checking boxes based on the user's age when he or she visits the page.  Ideally, I want to automatically check the box for the user's own age group (e.g., a user in his/her 20s will automatically have the 20s box checked, while a user in his/her 40s will have the 40s box checked).
What I tried
I have no way how to implement this smartly.  One possibility that entered my mind is creating a panel with variants for each age group and then cloning a view once per age group and then using views rewriting functionality to rewrite the query strings for all of the views to check the appropriate boxes...  but this would lead to a huge amount of duplication and be very difficult to maintain.
Answer: As a huge fan of direct approach and writing own helper modules, I would make it happen mostly with jQuery.

Outputting user's age or age category in a hidden
 is easy. You can append it to view's form with hook_form_alter, or simply output it as a block that will never really be seen.
Attach your JS library to views form (or again - simply load it and make it see if form is on page)
In behavior, read user's age from
 created in 1. and based on that check checkboxes. Invoke click() on them for full emulation of user interaction (i.e. to reload what would get reloaded if it was user who selected it).
Comment: I believe there should be some smart way to connect current user's taxonomy with views taxonomy, but I cannot find it.


Spectral resolution of multiplication operator

Question: Kosaku YOSIDA claims in his book "Functional Analysis" that it is easy to see that the multiplication operator
$Hx(t) = tx(t)$ in $L^2(-\infty,+\infty)$
admits the spectral resolution $H = \int_{-\infty}^{+\infty} \lambda \, \mathrm{d}E(\lambda)$, where the resolution of the identity is defined via
$E(\lambda)x(t) = x(t)$ for $t \leq \lambda$,
$=0$ for $t > \lambda$.
At this point in the book (Chapter XI.6 Normed Rings and Spectral Representation: The Spectral Resolution of a Self-adjoint Operator) the Spectral theorem is NOT yet proven.

I have problemes with the "easy to see"-part. I think he tries to argue that
$\int_{-\infty}^{+\infty} \lambda^2 \, \mathrm{d} \| E(\lambda) x \|^2 = \|Hx\|^2$
and
$\int_{-\infty}^{+\infty} \, \mathrm{d} \langle E(\lambda) x , y \rangle = \langle Hx, y \rangle$.
But how does this show the claim?
Comment: What you have to show (by the usual definition) is $\int \lambda d\langle E(\lambda) x, y\rangle = \langle H x, y\rangle$ for all $x,y$ (as well as $\int d\langle E(\lambda)x, y\rangle = \langle x, y\rangle$).
Comment: As far as I know only the first identity is needed according to the definition. Where is the second one needed?
Comment: This expresses the fact that $E$ is indeed a resolution of the identity. I don't know whether this follows automatically.
Comment: I have just "manually" shown this fact. So the first identity should suffice. I wonder why Yosida has also shown that $\int \lambda^2 \, \mathrm{d} \| E(\lambda)x \|^2 = \|Hx\|^2$ holds?
Answer: If $\rho$ is a bounded measurable function on $[a,b]$, then $E(t)=\int_{a}^{t}\rho(u)du$ is a function of bounded variation and, for any continuous function $g$,
$$
             \int_{a}^{b}g(t)dE(t) = \int_{a}^{b}g(t)\frac{dE}{dt}dt = \int_{a}^{b}g(t)\rho(t)dt.
$$
In your case,
$$
          \|E(t)x\|^{2}=\int_{-\infty}^{t}|x(u)|^{2}du
$$
The above easily extends to
\begin{align}
         \int_{-\infty}^{\infty}t^{2}d\|E(t)x\|^{2} & =\int_{-\infty}^{\infty}t^{2}\frac{d\|E(t)x\|^{2}}{dt}dt \\ &=\int_{-\infty}^{\infty}t^{2}|x(t)|^{2}dt = \|Hx\|^{2}.
\end{align}
Comment: @R.Swan : $\int_{-\infty}^{\infty}\lambda d_{\lambda}\int_{-\infty}^{\lambda}x(t)\overline{y(t)}dt = \int_{-\infty}^{\infty}\lambda \frac{d}{d\lambda}\int_{-\infty}^{\lambda}x(t)\overline{y(t)}dt d\lambda = \int_{-\infty}^{\infty} \lambda f(\lambda)\overline{g(\lambda)}d\lambda = (Hf,g)$.
Comment: Thank you. I have two questions: (1) What kind of notation ist $\mathrm{d}_\lambda $? I have never seen that. (2) Why do we need two identities? Is it soley to prove that E ist a resolution of the identity?
Comment: (3) I am also having troubles understanding the formal manipulations of the differentials (i.e. kind of treating them as fractions)
Comment: @R.Swan : This is a classical work, and I'm using a classical interpretation as a Riemann-Stieltjes integral, $\int_{a}^{b}f(t)d\rho(t)$, though you can elevate this to Lebesgue-Stietljes with no serious issues. When I write $d_{\lambda}$, I am just reminding you that the variable of integration is $\lambda$. If $\rho$ is absolutely continuous and $f$ is continuous, then the Riemann Stieltjes integral of $f$ with respect to $\rho$ is $\int_{a}^{b}f(t)d\rho(t) = \int_{a}^{b}f(t)\rho'(t)dt = \int_{a}^{b}f(t)\frac{d\rho(t)}{dt}dt$. It looks like manipulation of symbols, but it's not.
Comment: @R.Swan : $x(t)\overline{y(t)}$ is absolutely integrable and measurable, which means that $\int_{-\infty}^{\lambda}x(t)\overline{y(t)}dt$ is absolutely continuous in $\lambda$ with derivative equal a.e. to $x(\lambda)\overline{y(\lambda)}$. (This is Lebesgue's differentiation theorem.) Note: absolutely continuous means the function is the integral of its derivative (which, of course, requires the derivative to be locally integrable.)
Comment: @R.Swan : The identity for $(Hx,Hx)$ follows from the one for $(Hx,y)$ with $y=Hx$. I had only given you one because the other follows the same pattern. But I decided later to give you the second because you did not seem to be very comfortable with the second one based on the first one only. Takes a bit of getting used to.
Comment: Don't we rather need to show $\int_{-\infty}^{+\infty} \lambda \, \mathrm{d} \langle E(\lambda) x, y \rangle = \langle Hx, y \rangle$ for all $x,y$?
Comment: @R.Swan : I gave you the first of the two. The second one is proved in the same way.
Comment: That makes sense. In my case $\rho(\lambda) = \int_{-\infty}^{\lambda} x(t) \overline{y(t)} \, \mathrm{d}t$. As this equals $\langle E(\lambda) x, y \rangle$ we know that $\rho$ is of bounded variation. But how do you know that $\rho$ is absolutely continuous?
Comment: Great! Is it also necessary to additionally show $\| Hx \|^2 = \int t^2 \, \mathrm{d} \| E(t) x \|^2$, as you have done in your answer? And if yes, why?
Comment: That's a good shortcut. Is the identity for $\langle Hx,Hx\rangle$ needed to show $H=\int_{-\infty}^{+\infty}\lambda\, \mathrm{d} E(\lambda)$? In my opinion it is enough to show the $\langle Hx,y\rangle$ identity. Then $H = \int \lambda \, \mathrm{d} E(\lambda)$ should directly follow, because we have $\left \langle \int_{-\infty}^{+\infty} \lambda \, \mathrm{d} E(\lambda)(x) , y \right \rangle = \langle Hx, y \rangle$ for all $x \in D(\int \lambda \, \mathrm{d} E(\lambda))$ (which is dense in $H$) and all $y \in H$. By subtraction the desired equality follows. Maybe I am forgetting something?
Comment: @R.Swan : The part that is probably missing without some careful attention is that $\mathcal{D}(H) = \{ f : \int_{-\infty}^{\infty}\lambda^{2}d\|E(\lambda)f\|^{2} < \infty \}$. That's a really important part of the Spectral Theorem.
Comment: Good point, so we actually have shown $\int_{-\infty}^{+\infty} \lambda \, \mathrm{d} E(\lambda) \subset H$? Ahhhhh... and with the identity for $(Hx,Hx)$ it follows $D(H) = \{ f: \int \lambda^2 d \| E(\lambda) f \|^2 < \infty \}$, because $\| Hx \|$ never is infinite.
Comment: @R.Swan : With a spectral measure $E$ for an unbounded selfadjoint linear operator $H : \mathcal{D}(H)\subset \mathcal{H}\rightarrow \mathcal{H}$, part of the statement of the Spectral Theorem is a characterization of the domain as above. And, that condition is equivalent to the convergence of $\int_{a}^{b}\lambda dE(\lambda)f$ as $a\rightarrow-\infty$, $b\rightarrow\infty$. It's a very tight correspondence. However, the form $(Hf,g)=\int_{-\infty}^{\infty}\lambda d(E(\lambda)f,g)$ is not as tight because, as you might suspect, it has more to do with $\sqrt{H}$.
Comment: As far as I see it, Yosida has not proven that "reverse" part of the spectral theorem at this point in his book. He has however established that for a given resolution of the identity $E$ there exists a self-adjoint operator, denoted by $\int_{-\infty}^{\infty} \lambda \, \mathrm{d} E(\lambda)$ with $D \left( \int_{-\infty}^{\infty} \lambda \, \mathrm{d} E(\lambda) \right) = \{ f : \int_{-\infty}^{\infty} |\lambda|^2 \, \mathrm{d} \| E(\lambda f \|^2 < \infty \}$. If we can show that $D(H)$ is exactely this set, we are finished. And this set-equality is shown by calculating $(Hx,Hx)$
Comment: @R.Swan - Your statement looks correct. I don't think there is anything remaining for this problem, is there?


Is it normal for logistic regression, to have predictors which have good Wald's Chi Sq, but still bad performance?

Question: I have trying to build a logistic model with some 10 variables. All of those variables have Wald Chi sq value<500. All are highly significant p-value<0.0001.
Event rate is about 3%.
The concordance: 55.1%, Discon:28%, Tied: 17%.
Is this behaviour normal? What can I do, to decrease the ties and increase concordance?
Comment: What is the sample size?
Comment: Sample size is about 2m
Comment: with 2m observations everything will be significant, making statistical tests pretty much useless.
Answer: This is very normal.  Think about ordinary least squares linear models on a large sample size where small effects can be detected but the overall $R^2$ is only 0.07.  An over-simplified but somewhat valid interpretation would be that you can't predict individual outcomes very well but you can describe tendencies.  For a binary logistic model, the $c$-index (concordance probability; AUROC) of 0.55 is indicating very mild discrimination ability, i.e., lots of overlap in predicted probabilities between observations with $Y=1$ and those with $Y=0$.
Assuming the number of candidate variables is 10, you may not need to build a model but rather just to specify one.  Be sure to not assume linearity.  You can often get more predictive ability using regression splines to relax linearity assumptions.  Then there's consideration of interactions ...
Be sure to look at the model's pseudo $R^2$ and especially at the model likelihood ratio $\chi^2$ statistic with degrees of freedom equal to the number of candidate variables.  If the LR $\chi^2$ statistic is not significant the whole exercise is on thin ice.
Comment: There are two overall ways to build a model.  One is using unsupervised learning (data reduction) masked to Y.  This is often a great idea.  The other involves "cheating" by using Y to select features and to specify the transformations for the features.  This leads to suboptimal performance on new data, and extreme instability in the set of selected predictive features.  Specifying a model means you specify all the terms and transformations to be used in fitting a fixed pre-specified set of regression coefficients.
Comment: This may be a dumb question, but what is the distinction between specifying a model vs building one. I have looked at your book and am pretty certain I understand what you mean by specifying a model - but what does it mean to "build" one, in contrast?


Calculate Frobenius Norm using Non-Negative Matrix Factorization

Question: After performing Non-Negative Matrix Factorization (using R's rnmf() function), I'm left with W, H, and the fitted matrix (W%*%H).
The Frobenius norm (squared error) is calculated by squaring the difference between our original X and fitted matrix WH.
So, how can I use norm("matrix",type="f")to get my Frobenius norm? I'm slightly confused as I thought calculating this norm includes two matrices (X and WH), but norm() only takes 1 matrix as an input. Do I use the fitted matrix WH as my input?
Answer: Non-Negative Matrix Factorization (NNMF) aims to factorise the non-negative $n \times m$ matrix $V$ into two non-negative factor matrices $W$ ($n \times k$) and $H$ ($k \times m$) such that :
\begin{align}
min_{W,H} || V - WH||_F
\end{align}
ie. the Frobenius norm of the residual matrix $D = V - WH$ is minimised, this suggests that $V \approx WH$. Sometimes additional constraints inducing sparsity and/or smoothness properties on the matrices $W$ and $H$ are added but these are not part of the fundamental task of NNMF. Therefore (using the example in the documentation of the function rnmf) after retrieving the NNMF results:
data("tumor")
tumor.corrupted <- tumor
set.seed(1)
tumor.corrupted[sample(1:4900, round(0.05 * 4900), replace = FALSE)] <- 1
res.rnmf1 <- rnmf(X = tumor.corrupted, gamma = FALSE, my.seed = 1)

We can calculate the associated Frobenius norm using:
norm( tumor.corrupted - res.rnmf1$W %*% res.rnmf1$H, type = 'f')

Notice that it is good practice to have a few runs using different random seeds to generate the initial solution when using an NNMF decomposition. The minimisation task solved has local minima which may lead to different matrices $W$ and $H$.
I strong recommend going through the Berry et al. paper "Algorithms and Applications for Approximate Nonnegative Matrix Factorization"; it is very nicely written and gives an all-round overview of NNMF's internal mechanics as well as applications.
Comment: Thanks! After looking at it a bit more I managed to realize it was much simpler than I had initially thought about it. Appreciate the descriptive answer.
Comment: My pleasure. Best of luck with the rest of your analysis! :D


Devo encriptar a password na aplicação ou no servidor?

Question: Eu estou a fazer uma aplicação que requer o registo dos utilizadores e a minha pergunta é se devo fazer a encriptação na aplicação e guardar no servidor ou enviar a password e fazer a encriptação no servidor na altura do registo?
Comment: Acho melhor na aplicação criar uma encriptação na aplicação depois no servidor decriptar e encriptar com outra criptografia, MD5 sei la. Porque pode ser que seja interceptada  antes de chegar no servidor
Answer: Toda informação sigilosa deveria sempre ser trafegada de forma criptografada, desde onde ela foi digitada até o servidor. Pode utilizar os mecanismos disponíveis nos sistema operacional e acessíveis pela API do dispositivo.
No servidor quando receber deve imediatamente transformar um hash e descartar a senha original.
Mais que isso só fazendo criptografia end-to-end, mas é um processo mais complicado, cria algumas dificuldades e só vale onde precisa de muita privacidade e precisa diminuir a área de ataque um pouco mais, o que nem garante nada porque a ponta pode estar comprometida de várias formas.
Comment: obrigado pela resposta
Answer: Respondendo de maneira clara e rápida: o password deve ser encriptado na aplicação.
Por que?
Quando a aplicação envia os dados para o servidor, nada impede que esses dados não sejam lidos ou interceptados no meio do caminho, como por exemplo, um ataque  Man in the middle. Quando esses dados transitam pela rede em plain text qualquer pessoa pode lê-la sem muitas dificuldades.
Mas e se a comunicação for feita usando https?
Com o uso do https entre serviços, é garantido a criptografia das mensagens trocadas entre os pontos, desde que os certificados e protocolos envolvidos estejam atualizados e operantes.
Por fim, o ideal seria a troca de mensagens usando criptografia end-to-end, como bem citou o @Maniero em sua resposta. Porém, devido ao alto custo e complexidade, se torna um pouco difícil de aplicar. Então, para o seu cenário, uma solução próxima do ideal seria: as informações partiriam do app já criptografadas diretamente para o seu servidor que usa o https.
Comment: obrigado pela resposta


mysql grouping select lmost recent date

Question: I want to select the most recent date per PropertyId and Type from the sample table below.
<code>|PropertyId | Type | ExpiryDate
|1          |1     | 2017-01-20

|1          |1     | 2016-01-20

|1          |2     | 2017-01-20

|1          |2     | 2016-01-20

|2          |1     | 2017-01-20

|2          |1     | 2016-01-20

|2          |2     | 2017-01-20

|2          |2     | 2016-01-20
</code>
So would be looking for the result :-
<code>|PropertyId | Type | ExpiryDate

|1          |1     | 2017-01-20

|1          |2     | 2017-01-20

|2          |1     | 2017-01-20

|2          |2     | 2017-01-20
</code>
Answer: you can use group by
<code>SELECT max(ExpiryDate),PropertyId , Type  from Table group by PropertyId , Type;
</code>
Comment: Thats Fabulous thank you.
Comment: How would i be able to select only the rows where the expiry date is greater than today
Comment: add following at the end of the query : having date(now())< ExpiryDate

mysql grouping select lmost recent date


Trapezoid and line connecting two sides

Question: Base sides of trapezoid are 8 and 6. Parallel line to base sides that connects two other sides splits trapezoid to two surfaces with equal area.
What is the length of this line?
My attempt: I tried drawing figure and manipulating formulas, to no avail for finding the length of this side.
Answer: Hint
"Complete" upto a triangle and work with triangles in Thales position.
Answer: Write area of each of the small trapezes in terms of the area of the original one. We use the bases of the original trapeze as $L_{1,2}$, the middle line is $L$, and the distance between $L$ and $L_{1,2}$ is $h_{1,2}$:$$\frac{L+L_1}{2}h_1=\frac12\frac{L_1+L_2}{2}(h_1+h_2)\\\frac{L+L_2}{2}h_2=\frac12\frac{L_1+L_2}{2}(h_1+h_2)$$
Now let's group terms with $h_1$ and $h_2$ on opposite sides of each equation:
$$\begin{align}\left(\frac{L+L_1}{2}-\frac{L_1+L_2}{4}\right)h_1&=\frac{L_1+L_2}{4}h_2\\\frac{L_1+L_2}{4}h_1&=\left(\frac{L+L_2}{2}-\frac{L_1+L_2}{4}\right)h_2
\end{align}$$
Simplifying the expressions in parenthesis, and taking the ratio of the two equations yields:
$$\frac{2L+L_1-L_2}{L_1+L_2}=\frac{L_1+L_2}{2L+L_2-L_1}$$
This is equivalent to $$(2L+(L_2-L_1))(2L-(L_2-L_1))=(L_1+L_2)^2$$
or: $$4L^2-(L_2-L_1)^2=(L_1+L_2)^2$$
Then the final answer is $$L=\frac12\sqrt{(L_1+L_2)^2+(L_2-L_1)^2}=\sqrt{50}$$

Trapezoid and line connecting two sides


Can the constant for log transformation log(x+c) be a value larger than 1?

Question: Background:
I want to explores the effect of 3 different treatments on pain felt during a medical procedure. Pain has been assessed using visual analogue scales. Pain values can be anywhere from 0 to 100. 0 = no pain felt.
What I am trying to do
I am trying to run a regression model so I can control for other factors which may influence pain.
The Problem
My data has lots of zeros (meaning no pain was felt), so even after log transformation (I tried log(x+1) and log(x+0.1)), I still have skewed histograms for each of the treatment groups.
The only time I am able to get an approximately normal distribution is when I have a higher constant... so I tried log(x+7), which gave me the approximate bell-shaped curve I was looking for in the histogram...
My question
Is it okay to do this statistically and in my case? I have not been able to find any websites that explain why the constant for a log transformation needs to be small, so I'd love to know if this is okay to use a larger constant than 1, and if not, why not?
Comment: If you have many 0's no transformation will solve that; all the values are equal no matter where you transform them to, and any monotonic transformation will leave them all at the low end of the range, so no matter what you do you will have a spike of probability at $t(0)$. Transformation is not a solution to this issue. It's possible that automatic choice of bin width and bin origin in your histogram has simply disguised this fact at some particular choices of $c$.
Comment: If you'd go for a nonparametric test like Wilcoxon but want to add covariates, a proportional odds model is an extension of the Wilcoxon test that allows for all of the usual covariate tricks that you get from linear regression.
Comment: Welcome to Cross Validated! To a large extent, doing a $\log(x+c)$ transformation of any kind means you've botched the modeling. Why do you want to do a $\log$ transform of any kind?
Comment: @Dave Thank you! :) I've also tried non-parametric tests... but they don't allow for controlling for other variables that may influence pain. My data is really skewed because of the 0s and so far, I've been taught in my course that log transformations can help "normalize" the data, which is what I've tried. I'm very new to biostats and very confused about this - apologies...
Comment: @Glen_b thank you for explaining this to me! :) I really appreciate it
Comment: Normal distributions are common because the Central Limit Theorem often applies - this says that the sum of many independent random variables has approximately a normal distribution. A log transformation is excellent if the physical process is naturally multiplicative rather than additive, e.g. population growth. If you have a few zero values, then adding a small constant allows you to use a log transformation without errors. Using a log transformation with a large additive constant is unusual - it is hard to think of common reasons why the data would be like that.
Answer: As the comments indicate, a $\log(x+c)$ transformation is probably not the best way to model your data. That said, if you want to use that type of transformation then there is no theoretical restriction on the choice of $c$. The difficulty is that the farther $c$ is from 0, the harder it is to interpret the coefficients of the predictors in the usual way, in terms of proportional effects on outcome.
It's also not clear that looking at histograms within treatment groups is the best way to evaluate the transformation. As you have multiple other predictors, what's ultimately of interest is the distribution of residuals between observations and model predictions.
@Dave's suggestion of a proportional-odds model can be a good way to handle ordered outcomes in a regression model without needing to transform outcome values. If you have a lot of 0 values, you might consider a type of hurdle model, which would combine a model of whether there was any pain with a model pain intensity when there was.


doubt in file path

Question: i tried a program comparing C:\Program Files and C://Program Files i checked with compareTo()==0 it comes they are equal. But i doubt if there is any difference between //&\
 Is there any difference? what is the difference between c:/program files and //?
Comment: Are you sure you don't mean ` \\ ` and ` / `?
Comment: i typed \\ only its not coming as i typed. I what to know the difference if any b/w // & \\
Comment: Is your question about filesystem or about Java string literals?
Comment: well, Skaffman is trying to correct your question but you keep changing it back. It's absolutely not clear what you really mean, but I suspect Skaffman's edit was right so please stop reverting it.
Answer: There is no difference, at least in Sun's implementation. The Win32FileSystem normalizes paths by converting slashes and removing duplicate slashes.
If you want to be 100% portable, use File.separator
Answer: The separator between path components depends on operating system. Java represents file path independently of operating system and that causes equality of values considered.
Conversion to native representation is done on lower level (as Bozho pointed out), and you should not worry about that. Nevertheless I'd recommend using "/" as separator, as it is more common OS-wise.
Comment: Don't hard-code "/", use `File.separator` or `System.getProperty("file.separator")`.
Comment: "conversion"+File.separator+"is"+File.separator+"more""+File.separator+"convinient"
Comment: and there is java.net.URL / File.toURL()

doubt in file path


Which strategies to use against aggressive tennis players?

Question: Aggression spread aggression. It is easy just to follow the other player and bang harder back. You need to outsmart the other player somehow particularly if you are about the same level or you feel you may not last long enough in the tempo.
What kind of strategies have you used to outsmart an aggressive tennis player?
Comment: Maybe the tags [meta-tag:strategy] and [meta-tag:technique] are applicable to this question. (Or at least some of them.)
Comment: @Martin agree. This is not about one specific technique so I think strategy is the best fit here :)
Answer: If they are at the same level as you, but more aggressive, they will usually make more errors, so if you hang in there, and keep getting the ball back, they will tend to make mistakes. If they are really aggressive, they like to come to the net, so keep them back by hitting deep shots as much as possible, don't give them short balls.
Comment: I like the view **"[i]f they are at the same level as you"** +1. I started totally amateur 1 year ago using too much power and losing easily, I realised that I need to be technically superior before using any power. Now when I see players using too much power, I gonna use this strategy *"let them do the mistakes"*, *"deep shots"* forcing them to the back and sensing the game. At some time, aggression stops and you have a time to revenge/point. It requires guts to play softly against aggressive players to avoid your mistakes: focus, focus and focus.
Answer: I list some basic strategies below, you can mix them to your needs.
General

Let him/her run out of energy? Continue deep baseline shots without risks (not letting him/her to net)?
Hard to come to net unless a mistake or a change in tempo (hit a slow shot to get some extra time to come to net)?
Surprise: do not make your intentions apparent, fool the other by acting to do something while you do something else.
Brute-force: you make the other to fear you. When he/she rises to the net, you bang as hard as possible (to the torso or side signalling do not come close to me) -- this can make the other totally paralyzed if she/he realizes aggression does not work against you.

Exploiting wide wingspan/arm span/reach

Hit against the torso with powerful topspin shots so the player does not get benefits due to his/her size: the player needs to hit further away stumbling more easily. When you play corners, make sure about timing -- you don't want the player to get maximum power due to the long lever (arm).

Serves

What is the safest technique to return very aggressive serves?
Techniques to return aggressive tennis serves?
Comment: I would like to know downvoter what is wrong with this?


Cascade algorithm for wavelet and scaling functions

Question: It has been described to me that the wavelet and scaling functions can be computed using the Cascade Algorithm applied to the low and high pass filter coefficients.
Where can I find some proofs of how this happens?
Answer: Some sources that may be useful include:

"Wavelets and Subband Coding" by Martin Vetterli and Jelena Kovacevic, which provides a comprehensive introduction to wavelets and subband coding, including the derivation of wavelet and scaling functions using the Cascade Algorithm.

"A Wavelet Tour of Signal Processing" by Stephane Mallat, which also provides a detailed introduction to wavelets and subband coding, and includes a proof of how the wavelet and scaling functions can be computed using the Cascade Algorithm.
Research papers on wavelet transforms and subband coding, which can be found through academic databases such as the IEEE Xplore Digital Library or the ACM Digital Library, many of them will provide detailed proofs of the theory behind the wavelet and scaling functions computation.
Comment: See https://scicomp.stackexchange.com/questions/42343/numerical-evaluation-of-fourier-transform-of-a-scaling-function/42421#42421 for a start on a faster converging cascade algorithm. My dissertation thesis has the general case, but that is too long for an SE answer.
Comment: Having hundreds of pages, would you be so kind to highlight the relevant sections and pages.