Kolmogorov's probability axioms

Question: Why Kolmogorov's axioms are considered such a breakthrough in probability theory? They are just 3 simple statements everyone can agree with.
When creating a system of axioms like this it's necessary the list of the axioms is complete. Suppose we forget about the 3rd Kolmogorov's axiom. Then we would have 2 axioms everyone could agree with when thinking about probability. Does it mean the 2 axioms are enough to claim this is a good axiomatic system of probability? We know it's not, because there's the 3rd axiom left out. But maybe these 3 axioms are not sufficient as well in a similar manner.
Look at Euclid's fifth axiom (parallel postulate). If we ommit fifth postulate, we get hyperbolic geometry, which is certainly no what we wanted to have. A similar question arises here - are those axioms sufficient? Are we sure we won't get any unintended results just following these 3 axioms?
Or maybe the statement that a given set of axioms agrees with our intuition of, let's say, probability must itself be treated as an axiom. We cannot prove it. Kolmogorov axioms survived so many years with no major complaints, then they are believed to match our intuition regarding what probability is accurately. But there are areas where it doesn't work (like quantum mechanics, which is well known for being weird and counter-intuitive). But why those axioms apparently do work in our 'common' and 'everyday' probability problems? Maybe we haven't discovered a case where they fail?
Quoting The Logico-Algebraic Approach to Quantum Mechanics Volume I: Historical Evolution, C.A. Hooker Editor, page 172:

It is obvious that since the Kolmogorov axioms are rooted in empirical
  experience, any change in the theory, if by such change one wants to
  extend its applications to the physical world, should spring directly
  from some phenomenological considerations. Anticipating our
  discussions in the subsequent sections one might say that the point of
  departure for the contemplated change in the model can be traced to
  the remarkable discovery that the physical systems arising in quantum
  physics are of such nature that one is no longer entitled to make the
  assumption that the associated experimental proposition constitute a
  Boolean sigma-algebra. As a consequence, the conventional i.e. the
  Kolmogorov formalism of probability theory is inadequate for a precise
  description of these systems. As a spectacular instance of such
  failure we may mention the facts that the notion of disjoint events is
  at a somewhat deeper level and that the identity
  $P(A+B)=P(A)+P(B)-P(AB)$ is not always true (the examples of Feynman are
  concerned with this failure among other things).
Comment: @Did I am not sure, but a possible interpretation could be: if $A$ is the $x$-coordinate and $B$ the $y$-coordinate of an electron in two dimensions, then we cannot compute $AB$ since this measurement is not feasible by the uncertainty principle - so actually the notion of $AB$ has no meaning in this context
Comment: The $x$- and $y$-coordinates of an electron commute and can be measured simultaneously. To make the prev comment physically correct one need for example the coordinate $x$ and the momentum $p_x$.
Comment: Does someone understand what the phrase *the notion of disjoint events is at a somewhat deeper level* means? *Spectacularly* or not...
Answer: You seem to be tackling several issues at once. First though, some inaccuracies. You write "when creating a system of axioms like these..." I'm not sure what 'these' refers to. Then you say "it's necessary the list of axioms is complete." Do you mean by 'complete' that there is only one model of the axioms (up to isomorphism)? if so, why is that necessary for modelling probability events? You comparison with the axioms of geometry is unclear as well. If you omit the fifth, you do not automatically get hyperbolic geometry, you can also get projective geometry. To claim that any of those is not what we wanted to have is peculiar, particularly from a modern perspective. Geometry encompasses much more than just Euclidean geometry. And again, even with the fifth there is not just one (up to isomorphism) Euclidean geometry, but infinitely many (of various dimensions).
Now I will try to address the question of what is so great about Kolmogorov's axiomatisation. The mathematics of probability is fraught with difficulties, both conceptual and technical. There are endless examples of seemingly simple questions that turn out to be very complicated or have severely counter intuitive answers (The Monty Hall paradox for instance). Problems that appear identical may turn out to be significantly different just because of changes in the protocol. In short, it's not easy.
Having said that, the probability theory of finite probability spaces is quite simple, at least in the sense that it is clear how to model finite probability spaces: Given a finite set of events, the probability of a subset of events is the ratio of that subset to the entire set. Sweet. From it flows quite a lot, but only when the total set of events is finite.
Often, the set of events is infinite. For instance, modelling throwing a dart at a dartboard is often done by imagining the dart board as a disk in $\mathbb R^2$, and then a throw of a dart corresponds to a choice of a point in the disk. Of course the disk has infinitely many points. What is the probability that the dart hits a given point, say the centre of the disk? Well, assuming the dart lands randomly at a uniform distribution over all points, the only possible answer is $0$. A point is just too small. This is already counter intuitive enough and raises the question of how to model all of this. Well, this is all related to the notion of how big a set is. An innocent question with a highly complicated answer. It's not simple at all to develop the theory that answers this question - measure theory. Issues related to the axiom of choice quickly creep up. A famous theorem of Vitali shows that it is impossible (assuming the axiom of choice) to meaningfully assign a measure to each and every subset of $\mathbb R$.
Now, measure theory was not developed to provide some foundations of probability theory. Instead it arose from questions of integrability. Kolmogorov's wonderful insight was that he realised the same formalism can be used to turn the intuition of what probability theory should be (as you say, pretty obvious axioms) into actual axioms. Before measure theory and Kolmogorov's seminal contribution nobody knew how to meaningfully and accurately work with infinite probability spaces. Thanks to Kolmogorov a formalism was born. Now that is truly wonderful.
Lastly, the paragraph you quote is talking about something all together different. Quantum mechanical considerations defy many conceptually obvious properties. Among them Kolmogorov's axiomatisation of probability. In the world of quantum mechanics even probability behaves differently than what we are used to. Such is life.
Comment: I guess the fact that a given set of axioms agrees with our intuition of, let's say, probability must itself be an axiom. We cannot prove it. Kolmogorov axioms survived so many years with no major complaints, then they are believed to match our intuition here. Would you agree with that?
Comment: @user4205580 I don't quite agree that it's an axiom. Just like in Physics, where a theory has predictive power and the predictions can be checked against reality, so is it with a mathematical theory. The chosen axioms have a predictive power (the resulting theorems) and those predictions can be checked against what we expect or what we like the theory to achieve. That last part, of checking the actual theorems against what we'd *like* the theory to achieve is outside of mathematics.
Comment: I've edited my question, explaining what I mean saying 'complete' in this context..
Comment: You. I thought it's obvious, sorry. It's a comment to your answer anyway.
Comment: @IttayWeiss, what do you mean by  "Problems that appear identical may turn out to be significantly different just because of changes in the protocol."?
Comment: @ConradoCosta: Classical Monty Hall: Three doors, one has treasure behind, two have nothing. Host knows where treasure is. You pick a door, host opens an empty door. Do you wish to switch? Answer: yes! Variation Same scenario, but host does not know where the treasure is, opens a door at random and just happens to be an empty door. Do you want to switch? answer: doesn't matter. So, even though the two scenarios look identical the protocol is different and that affects the probability computation.
Answer: Kolmogorov was both interested in axioms and how probability realizes in systems. For the latter, see this paper.
Probability is notoriously difficult to correctly axiomatize. Kolmogorov's probability was a revolution in that it laid the foundations for a theory that is not only rigorous, but very applicable. The only similar "easy" example I can think of is the notion of compact sets for proving stuff in real analysis.
Kolmogorov's axioms by themselves are nothing new. However, it was Kolmogorov's reinterpretation of probability through measure theory that was truly revolutionary. This allowed for a much broader and more rigorous foundation for probability theory. Everything from Kolmogorov's 0-1 Law, to interpreting $P(A|B)$ when $P(B)=0$, becomes natural and useful in this measure theoretic approach. A further example is Brownian motion, whose rigorous foundations are solely rooted in measure theory.
Whether or not Kolmogorov's theory works in quantum mechanics is a completely separate issue. Quantum probability is a generalization, and you can find ways of connecting it in Kolmogorov's theory here.
Answer: Isn't the reason for their success  precisely the fact that the Kolmogrov axioms are

small in number
simple staements
everyone can agree with?

(I repeat here the points of your statement, but doesn't your quote contradict the last of these points?)
It gets a bit problematic when we talk about completeness in this context: The intent of Euclid's axioms was to describe a single abstract object, "the" geometry of "the" plane (or "the" 3D space). We might also ask: Are the three group axioms (associativity, neutral, inverse) complete? In a sense they are not, for neither the statement $\forall x,y\colon xy=yx$ nor its negation can be proved from them. But that is because these axioms are there to describe many objects (i.e., models of the axiom system). And on the other end of the spectrum there are structures that fail to be groups (such as $\mathbb N$) and therefore do not suggests themselves to be treated with group theory methods.
Kolmogorv's axioms fall more in the second category: They are applicable to many different situations. And if $P(A\lor B)=P(A)+P(B)-P(A\land B)$ does not hold in real life, then this cannot be modelled as probability just like $\Bbb N$ is no group.
Comment: It may sound a silly question but why different mathematical topics have different axioms but they use each other? For example when we add probabilities we add numbers but numbers or addition and their axioms are not postulated in probability theory.
Answer: Concerning the Quantum Mechanical Probability, maybe this Wikipedia reference is a nice read:

Probability amplitude

Especially the sections   The laws of calculating probabilities of events    and    In the context of the double-slit experiment   are relevant. In the latter section we find the formula for addition of the complex probability amplitudes $\psi$ of two independent events, say $\psi_1$ and $\psi_2$, not resulting in the "common" probability $P$:
$$
P \ne \left| \psi_1 \right|^2 + \left| \psi_2 \right|^2
$$
But in the following:
$$
P = \left| \psi_1 + \psi_2 \right| =
\left| \psi_1 \right|^2 + \left| \psi_2 \right|^2
+ 2 \left| \psi_1 \right| \left| \psi_2 \right| \cos(\theta_1-\theta_2)
$$
Here $\,\theta_{1,2}$ are the (complex) arguments of $\,\psi_{1,2}$ . The last term
is crucial for describing Quantum Mechanical behavior. This is the "deeper level" as mentioned in the question. In fact, as Richard Feynman says: "it contains the only mystery" (The Feynman Lectures on Physics III section 1-1).
But Quantum Mechanics is not the only context where "probability" is different from Kolmogorov probability. There are two other issues related to this that I find bothering:

Double Think about Numerosity
Uniform Probability and Riemann Sum
Comment: Are you saying one of Kolmogorov's axioms are violated? From the Wikipedia page you site, the third axiom on the sum of probabilities of _mutually exclusive_ events is stated as applying to quantum probability amplitudes (see section on laws of calculating probability amplitudes). There is no rule in Kolmogorov's axioms requiring that probabilities of _independent_ events add.
Answer: Note that as stated, the 'rule,' mentioned above, has multiple interpretations.
$$(A) P(A\vee B)=P(A)+P(B)−P(AB)$$  as stated an axiom of Kolmogorov's system.
Unless you interpret  $$P(AB)$$ as $P(A\cap B)$ as set theoretic intersection, which is how its, or was, traditionally done.
Where $A\cap B$ is the event  $E;E \in F$.
$F$ being the Bool-ean algebra of events.
Where the event $E$ , is, denoted by a set of atomic events:
$\Omega_{i};\Omega_{i} \in \Omega$, generally if not always, mutually exclusive,  where $\Omega$ is the sample space .
Or in other words,  the  union of singleton sets: $\{\Omega_{i}\} \in F, \{\}$ ,denoting  said atomic events, which are often  measurable in finite cases,  and thus  $\in F$,  the 'Boolean or sigma algebra of measurable events'. This being   is often,  the union of the singleton sets (translate , dis-junction, of 'mutually exclusive 'atomic event's) , that are in  the common intersection of the sets $E_{A}\,,E_{B}$ .
These  are the  union of singleton sets in ${\Omega_{i}}\in F$ (translate , dis-junction, of 'mutually exclusive 'atomic event's; $\Omega_{i}\in \Omega$),  ' which denotes the events $A , B$ respectively.
So at the end of the day, one never consider composite events really, in basic Kol-mogorov's calculus, that are not mutually exclusive.
By which I mean they are always reducible to dis-junctions of mutually exclusive events. Whilst some events in $F$ may not be mutually exclusive, what those events consist in.
That is, the elements of the sets denoting each event individually, are generally if not always mutually exclusive,  are, so there are no compositions (intersection of union )or events consisting of non mutually exclusive atomic events,  or other partitions.
Unless you count  $\emptyset$ .
Otherwise union of singleton sets, or atomic events,  or countable partitions of them (unions) in the infinite cases, are generally always be analyzed set theoretically via as the disjoint union, and set co of mutually exclusive events, and set complementation so will $A\cap B$.
Although, the probability calculus was in a sense, extended later, by both Kol-mogorov and others, as it stands, the three axioms of probability $(1)$ , $(2)$ and$ (3)$ do not contain $$(A)$$, at least not explicitly.
Everything can be done by summing up only mutually exclusive events. Its just a quicker theoretical tool.
Perhaps the real,  difference is, at not so much at the level of axioms, the nature of the probability space. However, the underlying model theory, logic, measure theory and sets, on the one hand, versus, functions, vector spaces, and inner-products, and what is meant by disjoint, and complementary and closure under unions of certain forms
See Chapter 5 of 'Foundations of Measurement Volume 1: Suppes Krantz, Luce et al for more on the distinction in quantum mechanics.
and the  that quantum probability may be considered non-commutative, and may see a distinction in the logic between the events(1) and (2):
$(1)P([A\cup B ]\vee [B\cup C])$ and $(2)PR(A\vee B \vee C)$ .
Where  $A\cap B$  and $B \cup C=\emptyset $.
But, in the conventional system (such as kolmogorov), $P([A \vee B ]\land [B\vee C])$, is interpreted, set-theoretically as:$ P([A\cup  B ]\cap [B\cup  C])=P({B})$ for example.
Where $A , B C$ are the atomic, mutually exclusive and exhaustive events.
Thus, the probability calculus, really  only contains $$(2)$$ interpreted in terms of set theoretic intersection, comple-mentation and unions.
Although generally intersection is not required given specification of the unit.
$A\cap B$ will generally be an  event $\in \mathbb{F}\subseteq=2^{\Omega}$  , in  algebra of events $F$. That is a set of mutually exclusive elementary outcomes ${D,C...}$ or a singleton set,${D}$\in $F$, $D$\in $\Omega$
an atomic event, singleton,or union of said mutually exhaustive events, generally,  in the algebra of events, as will every other event, generally
$A\cap B=$ ,sing set theoretic comple-mentation.
Moreover,  $P(AB)$ is not interpreted as some kind of product or multiplicative event it is always either a union an atomic events, or the empty event or the unit event at the end of the day, when one using set theoretic intersection for a singular probability space.
There are no distinct product events in the algebra over and above these.
$$(1)P(A \vee B)=P(A)+P(B)−P(A\land B)$$.
$$(2)P(A\cup B)=P(A)+P(B)−P(A\cap B)$$.
It has been debated whether Kolmorogov's original axiom set is incompatible with quantum mechanics.
Maybe its official extension  to measure theory, to joint algebras, product sets, what have you, to definite laws of large numbers, independence and so forth. But the original axioms say nothing about.
A lot of the counter-examples I have sen in other articles, have nothing to with Kolmogorov's official formulation which says nothing about products, independence,Bayes' axiom or the multiplicative /product'axioms'.
Which are put forward as mere definitions, and by definition this means that:
$P(A|B)$ is a word that merely denotes  $\frac{P(AB)}{P(B)} .
Where $P(A|B)=\frac{P(AB)}{P(B)}$  then  says that the ratio of two probabilities $\frac{P(AB)}{P(B)} =\frac{P(AB)}{P(B)}$ equals the the ratio of the same two probabilities (ie nothing substantive).
This is because, conditional probabilities, are not explicitly part of the axiomatic structure derived from the measure theoretic interpretation of probability,if you can call it that.
Quite, unlike the addiv-itiy of probabilities over disjoint unions, which was 'derived' from the addivity of under-lying inter-pretation (measure).
Nor is, $P(A|B)$, the probability of a conditional even, at least in the canonical calculus of probability. Nor, are the definitions of independence and Bayes rule (definition really).
These, independence, Bayes rule, conditional probabilities etc, are  not officially not axioms of Kol-mogorov's system. hey are definitions!
There may have been reasons,why Kolmorogov, did not officially publish his results earlier, which were published instead at about the same time that Quantum probability-logic  of Von Neumann /Birk-hoff etc. These works,  have the same official vintage.
Kol-mogorov, may have been aware of some of the issues. Perhaps, part of the reason for his   his being tentative about considering or formalizing the product definition, Bayes rule, and independence, as axioms of probability.
Whilst, Kol-mogorov never did officially include these as  axiom but  only definitions,  the probability calculus  was extended later, by both himself and others to accommodate Bayes rule to put it on a more formal axiomatic like standing.
Nonetheless, as it stands, the three axioms of probability still do not contain  contain it (Baye's Rule) or independence, and thus the 'product rule' ,$(2)$, or the rule of 'total probability',  $(1)$ , as below, as axioms:
$$(1)P(A \\vee B)=P(A)+P(B)−P(A\land B)$$ .
$$(2)P(A\cup B)=P(A)+P(B)−P(A\cap B)$$.
The only official use of is $(2)$ , as an axiom, where roughly :
 $P(A\cup B)= P(A\\B)+P(B)$. But this makes no use of the notions of definitions of conditional probabilities, multip-licativity of probabilities as in the product rule, or independence.
Axioms: Where a Probability space is a triple :
$$\langle \Omega,\mathbb{F}, P\rangle$$.
Where, $\Omega$ is the sample space, the set  of mutually exclusive and exhaustive atomic events,  ,often called single-tons events,$\in$ the algebra $\mathbb{F} $.
 Where, $\mathbb{F} \subseteq \mathcal{P(\Omega)}=2^{\Omega}$, is an Bool-ean algebra events, a set of  measurable subsets, of  $\Omega$,  closed under the unit event (certain event:$\Omega$, complementation,  and countable union.
$$(1)P(E)\in \mathbb{F} ,P(E)\geq 0\quad \forall E\in F$$
$$(2) P(\Omega)=1$$.
$$(3)P (⋃^{i=\infty}_{i=1}E_{i}) = $$.
$$\lim_{n \to \infty} ∑^{i=n} _{i=1}P(E_{i})$$.
Where: $\forall A_{i}$ are mutually exclusive. That is, pairwise disjoint.
A countable sequence of , pairwise-disjoint sets, which requires an axiom of continuity, and sometimes is formalized as fourth axiom distinct from finite additivity.
If you read Kol-mogorov's main work, he states many tentative axioms such as axiom $4|5$ the frequency principle which he decided to reject in the end .
Whilst Kol-morogov is  often considered to be a frequentist in certain circles, in the end he rejected the formal frequent-ism of Von Mises/Reichen-bach, as did Von -Neumman in Quantum- Mechanics .Kol-morogov may have been still a frequentist at heart. He said explicitly that his model did not have a great deal to say, or was neutral about the world, and that frequency data, is how you obtain information, but formally speaking he rejected it in the end.
<code>Any countable sequence of disjoint sets:
</code>
with mutually exclusive events ,roughly:
 $E_{1} ,\, E_{2} \text{..}\in F$ , satisfies:
.
$$P(⋃_{i=1}^{\infty}E_{i})= \, \sum_{i=1}^{\infty }P(E_{i}\,)$$.
Comment: I thought you agreed this kind of logorrhea had nothing to do on the site?

Kolmogorov's probability axioms


Did J.S.Bach know the categories *major* and minor* when he wrote his WTC?

Question: Something interesting: I've read the other day that Bach when he wrote his WTC there he didn't know the terms *major" and "minor".
I can't find the source again but may be someone can help me. May be we'll find it in the comment of the Bach society or even in the faksimile.
I was wondering about this remark as I've also read that since Zarlino the modes have been reduced to this two kinds of tonics - even we know that Bach still was using church chorals in different modes.
Comment: He may not have known the terms major and minor, but he used Tierce de Picardie a few times, so must have been aware of the effect made by raising the m3.
Comment: I must have been unclear: I didn't mean the minor 3rd or major 3rd but the term for the scales in minor or major. Probably there doesn't exist an equivalent expression for the category as we have in German: Tongeschlecht. I have probably to clear this point before.
Answer: The Well-Tempered Clavier,
or
Preludes and Fugues
through all the tones and semitones
both as regards the tertia major or Ut Re Mi
and as concerns the tertia minor or Re Mi Fa.
For the Use and Profit of the Musical Youth Desirous of Learning
as well as for the Pastime of those Already Skilled in this Study
drawn up and written by Johann Sebastian Bach.
p.t. Capellmeister to His Serene Highness
the Prince of Anhalt-C�then, etc.
and Director of
His Chamber Music.
Anno 1722."
Translation from here:
https://www.qub.ac.uk/~tomita/essay/wtc1.html
Comment: Re Mi Fa identifies which octave a note lies in. It's a hexachordal-derived notation. However Bach (and several others around his time) did write in 24  "keys" even if these keys were not exactly what people think of now. Note that they are arranged in C-c, D-d, E-d,  ETC-etc. parallel rather than in C-a, D-b, E-c#... indicating the relative key (which terms are used differently in other languages.) I'd have to check but I think Bach did use the C-G and a-C them relations in overtures. Whats clear is that these are neither the church modes nor the Greek modes nor the modern concept.
Comment: this must have been the source I was reading but in German it means not exactly the same. Minor and major are surely concerning the thirds but as Bach writes: Re Mi Fa this indicates he didn't have a concept of the minor tonality based on A-minor as relative key like we he have today.
Comment: Isn't the point of only give the first three tones to show that is the main distinction between major and minor? The fourth and fifth being perfect in all modes needs no mention. The sixth and seventh being variable - indefinite - aren't convenient for a simple definition of major/minor tonality. The statement assumes a certain knowledge of those conventions.
Comment: It's not the first three tones rather where the key note lands in a solfege-hexachordal naming. Bah uses this elsewhere. https://books.google.com/books?id=njPVBAAAQBAJ&pg=PT475&lpg=PT475&dq=hexachord+notenaming&source=bl&ots=ePdicnApfk&sig=ACfU3U2RdJnKVtOWh1SfTrP3NymwimUbJQ&hl=en&sa=X&ved=2ahUKEwj60vT71s7nAhVGV6wKHZXpDHsQ6AEwAHoECAwQAQ#v=onepage&q=hexachord%20notenaming&f=false
Comment: As your other answer with the title page has been deleted I'd like to add that it is also to find in the Wiki site about the WTC. As it is very pale on the right site I had overseen this faksimile. https://en.wikipedia.org/wiki/The_Well-Tempered_Clavier


IPsec between Windows 2003 (server) and Redhat 5 (client)

Question: I need to setup data encryption within the network. Linux client machine will connect to a Windows 2003 server.
I need to enable IPsec on both the machines. Windows to Windows is working fine but Linux to Windows is failing.

Linux is Redhat 5.0
Windows 2003 Enterprise edition - MSSQL 2005 cluster server.

Steps to show how can we do this will be of real help.
Answer: I once did this using OpenVPN. Try to setup a connection using a symmetric key at the beginning. The major drawback was that this used lot of CPU-time on the Windows-Client (Linux was acting as server).
Can you give some more details - what did you use for w2w encryption and why don't you use ssh?


Corollary of Projection onto a closed convex set and geometric interpretation

Question: I need help with geometric interpretation of this theorem and  with the corollary of the theorem:

Theorem: projection onto a closed convex set
  Let $K \subset H$ be a nonempty closet convex set. Then for every $f \in H$ there exists a unique $u \in K$ such that  $|f-u|=mim|f-v|$
  Moreover, $u$ is characterized by the property  $u \in K \, and \, (f-u, v-u)\leq 0$ $\forall v \in K$

Corolary: Let $M \subset H$ is a closed linear subspace. Let $f \in H$, then $u=P_{M}f$ is characterized by  $u\in M$ \, and \, $(f-u,v)=0$ $\forall v \in M$
My attemp for corollary is, like subspace is convex we use the theorem, then i was thinking use. $|(f-u)-t(w-u)|=|f-u|^{2}-2t(f-u,w-u)+t^{2}|w-u|^{2}$ $f \in H, \, w, u \in K$ with $t=1$ , any help with corollary or geometric interpretion of theorem in $\mathbb{R}^{2}$ The angle between these vectors is obtuse, why?. Thanks in advance
Answer: Let $v \in M$. $\langle f, v \rangle=\langle (f-u), (v+u)-u \rangle \leq 0$ by the theorem because $v+u \in M$. Since $-v \in M$ we get $\langle (f-u), -v \rangle \leq 0$ or $\langle (f-u), v \rangle \geq 0$. Hence $\langle (f-u), v \rangle=0$.
Conversely the condition obviously implies $\langle (f-u), (v-u) \rangle \leq 0$ .
For a geometric interpretation take $M$ to be  a line in $\mathbb R^{2}$, draw a perpendicular from $f$ to $M$ and observe that the perpendicular line meets the space $M$ at the point where the distance form $f$ to $M$ is minimized.
For your last question take $K$ to be a line segment in $\mathbb R^{2}$ and you will easily see why the angle is obtuse.


CI Cart session is dropped because of '\' character

Question: I have a CodeIgniter cart that stores a URL in the options array. The problem is that when a URL with a '/' ( eg. www.website.com/page ) is added, the cart is emptied when the user leaves the cart contents page. This behavior is browser-independant.
This is what it looks like in the ci_session table after the item is added to the cart.
s:56:"{"aid":"111111","url":"www.testing.again.com\/whatisup"}"

Notice that the '\' escape character has been added to the URL.
So how can I fix this? My first thought is to do a str_replace to change the '/' to something else like '|' and then put the '/' back in later. I suspect there is a better way to do this.
Thanks.
Comment: What's the URL in the cart for? Normally you just put the object ID in the cart, and then fetch properties of each item as needed.
Comment: The URL is a product option, like a color or size would be for a shirt. So I grab some info from the user like the 'aid', the URL and sometimes a phone number and name. This all goes into the CI cart options array.
Comment: So I tried the str_escape idea and it works, but is there a more elegant way to do this?
Answer: You can base64_encode, base64_decode to encode/decode the URL. However, if you aren't using db_session, this will take up more room in the cookie pushing you towards the 5kb limit on cookie storage--so keep that in mind.
http://php.net/manual/en/function.base64-encode.php


bash script: search into file for value in column

Question: I did a search on the site but could not find something exhaustive.
I have a list of servers "hostA hostB hostc hostd" and a central host hostX
hostX connects to the servers via ssh, and obtained the following code
==============================================================================
----- Host Bus Adapters --------- ------ Storage System -----    - I/O Paths -
###  HW Path                         ID           Interface     Total    Dead
==============================================================================
   0 fscsi0                       CKM00130600171   CL1-06           10       0
   0 fscsi0                       CKM00130600171   CL1-02           10       0
   0 fscsi0                       CKM00130600177   CL2-06            1       1
   1 fscsi1                       CKM00130600171   CL1-03           10       0
   1 fscsi1                       CKM00130600171   CL1-07           10       0
   1 fscsi1                       CKM00130600177   CL2-07            1       1
   1 fscsi1                       CKM00130600177   CL2-03            1       1
   2 fscsi2                       CKM00130600171   CL1-06           10       0
   2 fscsi2                       CKM00130600171   CL1-02           10       0
   2 fscsi2                       CKM00130600177   CL2-02            1       1
   2 fscsi2                       CKM00130600177   CL2-06            1       1
   3 fscsi3                       CKM00130600171   CL1-03           10       0
   3 fscsi3                       CKM00130600171   CL1-07           10       0
   3 fscsi3                       CKM00130600177   CL2-07            1       1

I should finish a script that sees if there are dead path and sends an email allert.
but i don't know how to read the last column, I made the extrapolation of the last column but do not know how to compare
awk  '{print $(NF)}' /SERVER/hostA.txt  |grep -x '[0-9]*'

can you help me?
best regards
Isifer
Comment: Is that `grep` doing anything for you? Is your last column ever not a number?
Comment: `awk '$NF==1{print "is dead lol"}' file` ?
Comment: What test do you want to apply to the last column? What do you want to do with the lines that pass/fail that test?
Comment: if i do awk '$NF==1{print "is dead lol"}' file
he take:
count=11
==============================================================================
Dead
==============================================================================
1
1
1
1
1
1
Answer: awk '$NF==1' /SERVER/hostA.txt |
while IFS= read -r line
do
    mailx -s "Its dead, Jim: $line" ...
done

Complete/replace the mailx line as you see fit...
Answer: If you just want to grep lines that don't end in 0, you can use
grep '[^0]$\|[0-9]0$'

i.e. the last character on the line is not 0, or it's preceded by another digit.


Define Iterator type of template argument

Question: In function below, how to tell the compiler that Iterator is the iterator of Cont ?
template<typename Cont, typename Pred>
Iterator<Cont> find_if(const Cont &c, Pred p)
{
    return std::find_if(std::begin(c), std::end(c), p);
}

Comment: [std::experimental::ranges::find_if](https://en.cppreference.com/w/cpp/experimental/ranges/algorithm/find).
Answer: template<typename Cont, typename Pred>
auto find_if(const Cont &c, Pred p)
-> decltype(std::begin(c)) // HERE
{
    return std::find_if(std::begin(c), std::end(c), p);
}

Or since version C++14:
template<typename Cont, typename Pred>
auto find_if(const Cont &c, Pred p) //All you need is auto
{
    return std::find_if(std::begin(c), std::end(c), p);
}

Comment: Thanks, that's simple. When you say in newer version of C++ do you mean at least C++14 ?
Comment: @artm: I think so? I haven't done much C++ in the last ten years, so I'm a little fuzzy on which features were added which years


Adding check boxes to contact form

Question: I am attempting to make a contact form in Drupal 8 using "Contact forms" included in core.  I'm struggling to figure out how to really customize it, like adding radio buttons or check boxes - does this have to be done through the theme_name.theme file?  If so, can someone give me an example of adding elements to the page? I'm new to Drupal so thanks for helping out.
Answer: In Drupal 8, contact forms are entities listed in admin/structure/contact. Once you created the new contact form, on that page select Manage fields in the Operations column; it's a drop-down selector, so you will need to select it to see that operation, since the default operation for contact forms you create is Edit.

On the page you will see, you can add new fields.
The tricky part is understanding how to show checkboxes: You need to select the right field type. For example, if you want to show 4 checkboxes, then you select Text (list) as field type.

Enter the 4 values you want to show, and enter 4 as Allowed number of values.

To show it as checkboxes, you go to the Manage form display of your contact form (in my case, admin/structure/contact/manage/test/form-display, since test is the machine name of the contact form I created). For the field you created, it should show the following.

Change it to Check boxes / radio buttons and save.

Since the allowed values are 4, the contact form will show checkboxes, not radio buttons.
Comment: You sure are thorough!  Thank you very much for such a detailed answer on such a simple question, it worked perfectly.

Adding check boxes to contact form


What is the best way to deal with missing data in latent class models?

Question: What is the best way to deal with missing data in latent class models?
For example, Latent GOLD can estimate models with missing data (LG technical manual page 51). Simply put, the likelihood contribution is based on the observed indicators only, which means that for an observation with missing data, the likelihood function is maximized with only the remaining data available.
OK-that's fine, but does this mean for the parameters? Am I going to get better classifications because the parameters were estimated with as much information as possible (i.e. if the observation say only has a missing value), or am I going to get worse classifications because of the missing value?
Answer: Your model will be better for including the incomplete data. It will increase your sample size, which is good. But, even better, is that it will mean that your model is assuming the data is Missing At Random (MAR), which is a much safer assumption than Missing Completely At Random (MCAR), which is the implicit assumption you make if excluding incomplete data.


WinForms designer: Add control and make it visible for the designer

Question: I have a WinForms user control Host with a custom UI Editor.
Through that editor, a child control (Child) can be added to Host.
(The UI Editor creates Child and sets Child.Parent = Host)
Child is handled through a Holder<Child> helper class, which is set as Tag property of e.g. a ListViewItem.
The respective code - some of it, at least - gets added to the form: Holder is created, and set as Tag, which is enough to be created at runtime, too.
However, Child is not visible to the designer - it is displayed, but it can't be selected, nor does it occur in the drop down list with controls for the parent form.
I would like to:

see the Child control in the designer, so that I can modify properties
get notified if the control is removed

Is this possible?

[edit] Thanks all for your input. I've decided to skip the designer - I hoped to throw together something quickly, but apparently it requires more planning than I should allow myself to spend on it right now.
Comment: The default UserControl designer already does a lot of this.  How you broke it is quite unclear.
Comment: If your attempting to add controls dynamically, and then edit them through the designer, that is impossible, if thats not what you meant then please clearify
Comment: @sniperX: The TAB control allows to add pages, and then edit them through the designer - so I'd assume it is possible.
Comment: @petercen, Well I'm sorry, cannot add tab pages *DYNAMICALLY* and edit them in the designer, as that happens after the code is compiled.
Comment: @sniperX: of course, in design mode.
Comment: @peterchen The TAB Control is by design a container/host which uses internal TabPages, which are also containers : explanation and code for the TabPages ability to be design-time containers, and accept drag-drop of new controls, while being hosted in another container, is explained in the answer in Henry Minute's article on CodeProject in my answer to you below. It's not trivial, but it will work. Chapter #26 of Matthew McDonald's book on WinForms, "Pro .NET 2.0 Windows Forms and Custom Controls," titled "Advanced Design-Time Support," would also be of real help to you here.
Answer: I can't say I fully understand exactly what you are trying to do.
If you are dealing with the problem of how a "child" Control of a UserControl placed on a Form at Design-Time can be made to function as a container onto which you can drag-and-drop other controls from the Toolbox : this CodeProject article by Henry Minute may be helpful : Designing Nested Controls. For example : you have a UserControl with a Panel inside it : an instance of the UserControl is placed on a Form : in the Design-time view of the Form : you want to be able to drag-drop controls onto the Panel in the UserControl and have them become child controls of the Panel : Henry's article will show you how to do that.
This from Microsoft : How to make a UserControl object acts as a control container design-time by using Visual C#
Perhaps might also be useful, although it seems like you already have this step accomplished.
Comment: @Designing nested Controls - added to my "Designer cheat sheet"
Answer: Usethis.Controls.Add(/*Instance of the child*/); on the host class. Then for the notification add event handler for the host's ControlRemoved event (this.ControlRemoved += new ControlEventHandler(Host_ControlRemoved);).


Pre-select language (instead of "Language neutral") when creating a node?

Question: With core's Locale module you can enable Multilingual support for a content type. When creating/editing a node, this gives you a Language select list with all enabled languages and "Language neutral" as options.
The default (resp. first) value for this select list is always "Language neutral".
Is it possible to have a certain language as default value instead?
At best it would be a per-content-type setting, but I'm fine with a global one, too (e.g. always using the site-wide default language as default value).
Answer: The option for it is available in admin/config/regional/entity_translation

The Entity Translation configuration page provide an interface to select default language for all content types separately
Answer: Of course you can do what you want. You should install the next module: internacionalization. This module will give you a better support for the content translation.
Instructions:

You will have to enable the following modules in the packet internazionalization:

Internationalition module
String translation
Multilingual content.

You will find in the content types a new vertical tab called multilingual settings. There you can configure the content type like you want.
Answer: We have different environments we push our configurations through, so I chose to codify this into the hook_enable() of one of my modules like this:
<code>// Implements hook_enable().
function MY_MODULE_enable() {
    // Ensure that "entity translation" is setup so that my content item defaults to "EN"
    // instead of "Language Neutral" @see /admin/config/regional/entity_translation
    if (module_exists('entity_translation')) {
        $variable_for_entity_trans_nodes = 'entity_translation_settings_node__CONTENT_TYPE';
        $trans_settings = variable_get($variable_for_entity_trans_nodes);
        $trans_settings['default_language'] = 'en';
        variable_set($variable_for_entity_trans_nodes, $trans_settings);
        watchdog("MY MODULE NAME", "Setting 'default_language' of '@variable' to 'en' at /admin/config/regional/entity_translation", array("@variable" => $variable_for_entity_trans_nodes), WATCHDOG_DEBUG);
    }
}
</code>
You'll need to update the things CAPITALIZED to suit.


Angular function response in HTML

Question: I have an Angular component function which returns a string I need to show in my HTML. The function works, but the html tag generates as empty.
Function:
getTaskNameById(id: any): string {
  console.log('function start; id = ' + id);
  this.tasks.forEach(e => {
    if (e.idTask === Number(id)) {
      console.log('if statement true; name = ' + e.name);
      return e.name;
    }
  });
  return '';
}

HTML:
{{ getTaskNameById(form.value.tasks[i]) }}:

[Console log][1]
[Page look][2]
[Generated HTML][3]
[1]: https://i.stack.imgur.com/Pasl0.png
[2]: https://i.imgur.com/0CKhxLt.png
[3]: https://i.imgur.com/YSkJJrY.png

Comment: Can you share a copy in stackbiltz
Comment: I'm sorry about the bad format, the html part should be in a label tag, the page would not allow me to post no matter how I formatted the code
Comment: @AdritaSharma https://stackblitz.com/edit/angular-2pbass
Answer: Your string is empty because it is not possible to return inside of Array.forEach.

There is no way to stop or break a forEach() loop other than by
  throwing an exception. If you need such behavior, the forEach() method
  is the wrong tool.

See the docs for more information.
You need to change it to a normal for-loop or you can use some Array build in functions, like Array.find. See following:
getTaskNameById(id: any): string {
    console.log('function start; id = ' + id);
    const task = this.tasks.find(t => t.idTask === +id);
    if (task) return task.name;
    return '';
}

Comment: Great, happy to help =)
Answer: you don't need to use a method to get the task name because you already have an instant of the taks items when you loop throw the array like this

      id {{t.idTask}} , name {{ t.name }}

demo
Comment: This was just a demo to showcase the problem, i'm looping through different items in the html hence the need for function. But thank you anyway.

Angular function response in HTML


So I'm getting a little bored of pulling rabbits out of magic hats? (beginner)

Question: I'm an adult looking to learn programming - my intial desire was to learn to make Android apps and I began by buying a copy of Ivor Horton's Beginning Java - an 1100+ page tome on the subject a little over a month ago. I've since gone through 240 pages, with many hours poured into rereading sections, typing in all the examples and doing all the exercises as well as going through the exercises on CodingBat.com. I find the book a great way to learn all the nitty gritty details of the language and intend to eventually finish the book.
In that time I also got into programming AutoLISP routines (for AutoCAD) for my day job as a CAD drafter/designer to make life easier for me and my coworkers. Having a goal of actually making something useful really ignited a crazy manic energy in me and I would just work on those from when I got home from my day job until I went to bed and I'd wake up in the monring and work on them some more, and be thinking of them at work and looking up functions on break and such.
I realize that AutoLISP and Java are two different animals in terms of learning curve, but I'd really like to start making useful things in Java, and I have some ideas for some simple GUI programs I'd like to make again to help me at work.
With a basic knowledge of classes, inheritance, flow controls and the primitives would it be advisable to just skip to the Swing section of the book (with the intention of going through it all eventually) or read the Oracle tutorials (or get a faster paced book?) in an attempt to actually make something useful even if its very simple. Or should I just grind it out and progress in a linear fashion through the book? How did you guys learn? Like the title says doing silly things like putting rabbit objects in magic hat objects and dog.bark() gets a little boring.
Comment: I will only warn you that Swing is not the fairest territory for a beginner. Better start with something that just uses `System.out` and reads from a file.
Comment: If your goal is Android development, you can safely skip Swing because that's not used on Android.
Comment: [Teach Yourself to Program in Ten Years](http://norvig.com/21-days.html)
Answer: Java is an enormous programming language and you aren't going to master everything with it. It sounds like you've got a great foundation, so at this point I would suggest creating some useful application and looking up the information you need to implement it on an as needed basis.
Comment: I would argue that Java the language isn't very big at all. The Java library is vast, but that's a completely different thing.
Comment: It seems that the original poster was equating Swing and other parts of the library with the language itself, so yeah, I suppose I did mean the Java library.


Zero-inflated regression model for only independent variables?

Question: My independent variable has a huge proportion of zeros in the data, and I've been thinking of using a zero-inflated Poisson regression to account for this. However, this method is only specified for if the dependent variable has many zeros. Does it work if only the independent variable has the same issue? Are there any other methods to remedy this if not (like some sort of transformation on the independent variable)? Thanks.
Answer: A zero-inflated model is appropriate when the dependent variable has an excess of zeros that cannot be explained by standard models for count data such as Poisson.
There is no requirement, condition, or assumption regarding the distribution of the independent variable(s) in a regression model. We might like the distribution of the dependent variable, conditional on the independent variable(s) to be approximately normal, and for this we would normally inspect the residuals of the model.


Computing orbits in labelled graphs

Question: Given a labelled graph G = (V, E, L), L is function that maps vertices to labels. I want find subsets S  ⊆ V such that the mappings of vertices in S in all the automorphisms (should satisfy edge and label constraints) lie in the same set S. I am not sure if these constraints are enough to call S as an orbit of the graph G.
Are there any commonly used algorithms to compute these subsets ?
Answer: It looks like the nauty algorithm for the graph isomorphism problem can also be used to compute the orbits in vertex colored graphs( or labeled graphs).
Nauty
Official Nauty website

Computing orbits in labelled graphs


Trying to access and print the values from the fields within Paragraph

Question: I'm having trouble trying to access and print the values manually within the Paragraph. This is a snippet from the paragraph field template I have created. I wanted to access and print values manually instead of Drupal generating the markup using {{ slides.content }} so that I could customize the markup myself
{% for slides in items %}
    {{ slides.content['#options'].entity.field_label.value }}
{% endfor %}

Comment: Customize the markup by providing twig templates for the fields within the paragraph. Then no complex loops are really needed.
Comment: This looks like the standard loop of a field template, only that `item` was renamed to `slides`. Then `slides.content` contains the output of a field formatter configured by you in Manage Display of the paragraph type.
Comment: Aside from that is there anyway to access it directly instead of having to create multiple field twig templates?
Answer: Here's what worked for me to manually get parts of a field in a paragraph template.
This is in a field template for the actual paragraph, so for me field--field-paragraph.html.twig. I have an image field with the machine name field_image. This prints just the alt text of that image.
{% for item in items %}
  {{ item.content['#paragraph'].field_image.0.alt }}
{% endfor %}

I looked here for working with paragraph templates: https://www.drupal.org/project/paragraphs/issues/2662766#comment-12528934 and here for general drupal 8 field-getting: https://blog.usejournal.com/getting-drupal-8-field-values-in-twig-22b80cb609bd
Answer: I'd recommend not to use field templates for things like this, but use an entity template (like paragraph--BUNDLETYPE.html.twig) instead.
In an entity template you can access the rendered HTML output of any sub-field like {{ content.field_whatever }}, but you can also access raw field values for stuff like {% if paragraph.field_whatever.value == 'foo' %}


Tabview in android..?

Question: I am developing an app where i am using tabwidget with 2 tab views. When the app is visible on screen, in first tab some data needs to be displayed in listview which i gets it from database. If the data is empty in listview by default second tab needs to be visible.
when the activity starts if the list is empty i want to start the other tab. if list is not empty the present tab needs to be visible..
The below image gives some more detailed information about my question.

Here as per the above images when app is visible to the user for first time, the data will be empty. so, i want to display AddGroup Tab to add groups. How is it possible to focus on Add Group Tab if list is empty in Groups Tab...
Comment: Just trying to clarify what you want: you want to start on the other tab depending on if the list is empty or not when the activity starts(resumes)?
Comment: when the activity starts if the list is empty i want to start the other tab. if list is not empty the present tab needs to be visible..
Answer: Setting the currently viewed tab can be done with
myTabHost.setCurrentTab(tabPos);

How you get to this TabHost object depends on where you are initialising the list: if it is done in the parent activity, (which extends TabActivity), you can use
getTabHost().setCurrentTab(tabPos);
If you need access to the TabHost from inside another activity (ie. when your tabs are activities) or View implementation (inside the ListView), add a method to your parent Activity that can be called by the classes in it, or objects that have a reference to it. Put this
public void switchTab(int tabPos){
    getTabHost().setCurrentTab(tabPos);
}

in the parent activity, and then use something of the form
((MyParentTabActivity) MyChildTabActivity.this.getParent()).switchTab(1);

to access it, depending on where you want to switch it from.
Comment: actually i am initializing tabview in Group.java which extends tab activity and as per the the above pictures Groups tab is one activity and Add Groups tab is other activity. here i am initialising the list in Groups tab. so, as per your code where i need to add the following code in my following activities..
Comment: That is the situation this code is used for - add the switchTab method to your Group.java, and use the line below to access it, replacing MyParentTabActivity with Group, and MyChildTabActivity with GroupsTab

Tabview in android..?


Facebook SDK: retrieve User information in my Android application

Question: I am new in Android Development and I know there are many examples about what I am asking but I can't really understand them and the one in facebook doc https://developers.facebook.com/docs/android/graph/ is very complicated
I integrated Facebook in my code as below
package com.example.museum;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.model.GraphUser;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements  android.view.View.OnClickListener{
    Facebook fb;
    ImageView pic, button, signup;
    SharedPreferences sp;
    TextView welcome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        String APP_ID = getString(R.string.app_id);
        fb = new Facebook(APP_ID);

        welcome = (TextView)findViewById(R.id.welcome);

        sp = getPreferences(MODE_PRIVATE);
        String access_token = sp.getString("access_token", null);
        long expires = sp.getLong("access_expires", 0);

        if (access_token != null){

            fb.setAccessToken(access_token);
        }
        if (expires != 0){

            fb.setAccessExpires(expires);
        }

        button = (ImageView) findViewById(R.id.login);

        pic = (ImageView) findViewById(R.id.picture_pic);
        signup = (ImageView)findViewById(R.id.signup);

        signup.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(getApplicationContext(),One.class);
                startActivity(i);
            }
        });

        button.setOnClickListener(this);
        userInfo();

    }

    @SuppressWarnings("deprecation")
    private void userInfo() {
        // TODO Auto-generated method stub

        List<String> permissions = new ArrayList<String>();
        permissions.add("email");

        if(fb.isSessionValid()){
            button.setImageResource(R.drawable.logout_button);
            signup.setVisibility(ImageView.INVISIBLE);

            //pic.setVisibility(ImageView.VISIBLE);
            JSONObject obj = null;
            URL img_value = null;

            try {

                String jsonUser = fb.request("me");
                obj = Util.parseJson(jsonUser);

                String id = obj.optString("id");
                String name = obj.optString("name");

                Log.d("NAME", name);

                 // getting email of the user
                //String email = obj.optString("email");

                //for (int i = 0; i< 100 ; i++)Log.d("E_MAIL", email);

                welcome.setText("Welcome to Museum, " + name);

//              img_value = new URL("https://graph.facebook.com/"+id+"/picture?height=100&type=normal&width=100&redirect=0");
//              Bitmap bmp = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
//              pic.setImageBitmap(bmp);
//              pic.setVisibility(ImageView.VISIBLE);

            } catch (FacebookError e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("Error", "FacebookError");
            }catch (JSONException e) {
                Log.d("Error", "JSONException");
                e.printStackTrace();

            }catch (IOException e) {
                Log.d("Error", "IOException");
                e.printStackTrace();

            }catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                for (int i = 0; i< 50 ; i++)Log.d("Error", "Exception");
            }

        }else{
            button.setImageResource(R.drawable.login_button);
            pic.setVisibility(ImageView.INVISIBLE);

        }

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if(fb.isSessionValid()){
            // button close our session - log out of facebook
            try {
                fb.logout(getApplicationContext());
                userInfo();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }else {
            //login to facebook
            fb.authorize(MainActivity.this, new Facebook.DialogListener() {

                @Override
                public void onFacebookError(FacebookError e) {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onError(DialogError e) {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onComplete(Bundle values) {
                    // TODO Auto-generated method stub
                    Editor editor = sp.edit();
                    editor.putString("access_token", fb.getAccessToken());
                    editor.putLong("access_expires", fb.getAccessExpires());
                    editor.commit();
                    userInfo();

                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    fb.authorizeCallback(requestCode, resultCode, data);
}

}

And I need to retrieve user information such as his e-mail, his location, his birthday and most important the pages he like and I know I must use permissions can you please tell me how would I do that.
Any Help would be appreciated .
Answer: You need to make a new callback request. like this:
Session.OpenRequest openRequest = new Session.OpenRequest(Login.this);
    openRequest.setPermissions(Arrays.asList("email", "user_birthday"));
    openRequest.setCallback(new Session.StatusCallback() {
        // callback when session changes state
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (session.isOpened()) {
                // make request to the /me API
                Request request = Request.newMeRequest(session,
                        new Request.GraphUserCallback() {

                            // callback after Graph API response with user
                            // object
                            @Override
                            public void onCompleted(GraphUser gUser,
                                    Response response) {
                                if (gUser != null) {
                                    String email = gUser.getProperty("email").toString();
                                    String firstName = gUser.getFirstName();
                                    String lastName = gUser.getLastName();
                                    String username = gUser.getUsername();
                                    String birthday = gUser.getBirthday();
                                }
                            }

                        });
                request.executeAsync();

            }
        }
    }
    );

Comment: instead of my method userInfo() you mean or in addition to it ? where to add it I am a little bit confused
Comment: @مروانعلىفهمى you should be able to put that inside of your `userInfo()` method
Comment: so what is "user" is it a bundle ? because I don't understand what are doing !
Comment: I did this and tried to output it in the log and I got nothing... are sure I just replace this what is in userInfo() and it works
Comment: @مروانعلىفهمى What are you trying to log?
Comment: these parameters the first name and last name for instance and they don't appear in the logcat


Windows DNS Local and Internet domain

Question: We have our company domain hosted on the internet, call it mycompany.com
We have all our DNS records hosted on the internet for this. However, what we want is for one hostname to have a different address when we do the lookup from inside the network.
Our Windows network has a mycompany.local domain.
What we want is hostname.mycompany.com to resolve to our external router address outside the network and we want
hostname.mycompany.com to resolve to a local server address from inside the network.
Our dns server is currently 2012r2.
Any help would be appreciated
Answer: Create a DNS zone on your internal DNS server named hostname.mycompany.com.
Create an "empty" A record in the zone with the ip address of the internal server you want this name to resolve to.
Comment: Congratulations on the 100k Joe :)
Comment: Thanks! I didn't realize that it had "rolled over". I knew it was close but didn't know when it would happen.

Windows DNS Local and Internet domain


Given one inequality, prove second inequality

Question: I'm stuck on this homework problem. Can someone please give me a hint?

Given $2a^2+3ab+4ac<0$. Is the following expression zero, negative or
  positive?  $$9b^2-32ac$$

Thanks.
Comment: You can remove $a$ from the first inequality.
Comment: Is it possible you mean $2a^2+3ab+4c<0$ and $9b^2-32c$?
Comment: @Angie: Take a look at the polynomial $2ax^2 + 3bx + 4c$; if you compute it out, you'll notice that its discriminant is exactly $9b^2 - 32ac$. Now, the important thing about the discriminant is that if the discriminant is negative, the polynomial *never crosses the x-axis*; if it is exactly zero, then it only touches the x-axis once; and if it is positive, then the polynomial touches the x-axis twice....
Comment: ...Now, if $P(x)$ is our polynomial, then $a*P(1)$ is exactly $2a^2 + 3ab + 4ac$. Suppose $a < 0$; then it must be true that $P(1) > 0$. Since $a<0$, the polynomial opens downwards; since $P(x)$ was positive at $x=1$, the polynomial must therefore have two roots. **This says that the discriminant must be positive.** You should verify that, if $a > 0$, a similar argument shows that the discriminant is positive then, too. Since we cannot have $a = 0$ and $2a^2 + 3ab + 4ac < 0$, this says that *the discriminant must **always** be positive*. This gives you your answer!
Answer: Here's my suggestion: Consider the quadratic function $f(x) = 2a^2 x^2 + 3abx + 4ac$. Then your initial inequality can be expressed as $f(1) < 0$, and the discriminant of $f(x)$ is given by $a^2(9b^2 - 32ac)$. Now investigate the behavior of the roots of $f(x)$. It might be useful to observe that $f(x)$ is a "happy" parabola.
Answer: $$9b^2 - 32ac > 9b^2 + 8(2a^2+3ab) = ? \ge 0$$


Insert different Angular2 components programmatically

Question: I want to programmatically generate a report composed by multiple distinct components from a JSON file like:
<code>{
    components: [UserStatsComponent, ActivityChartComponent, NetworkGraphComponent]
}
</code>
I found this: Angular2: Creating child components programmatically
but my use case differs in that I need to represent different types of components, so I can't use a ngFor in my template because not every component have the same directive.
I'm new to Angular2 so I don't really know how to approach this: First I thought about component inheritance but looks like angular2 annotations are not inherited when extending a component's class. Don't know how to solve this using composition either.
Heard something about the content tag but don't really know if it's relevant to this use case.
tldr; How do I dynamically insert different components from an array?
Comment: su pregunta no es clara... it creates confusion. would you please make it better?
Comment: tldr; How do I dynamically insert different components from an array?
Comment: Do you want to go through json object loop and want to make dynamic components encountered?
Comment: The json object would be parsed somehow inside my main ReportComponent (doesnt matter how I get it), what I mean is that I don't know what children components I will be inserting beforehand.
Comment: If you say you don't know what children component you will be inserting, it means you are saying you don't know how @component decorator will be defined for  each component. So, I think It doesn't look straight and simple answer. But hopefully you can take a look at `DynamicComponentLoader` of angular2. But hope somebody else would be able to answer now or later.
Comment: Yes looks like i'll have to use some kind of factory that takes that json as input and uses the DynamicComponentLoader to populate the view. However, feels like a "generic" or "superclass" component would be the way to go.
Comment: But I wonder with how would you defined @component decorator dynamically for all components to be inserted dynamically. Moreover you don't know how many components will be there in the json object. So pretty awkward as of now.
Comment: Thought of using DynamicComponentLoader.loadNextToLocation()  so the the number of components its no longer relevant.
Answer: To insert components dynamically use the DynamicComponentLoader
<code>@Component({
  selector: 'child-component',
  template: 'Child'
})
class ChildComponent {
}
@Component({
  selector: 'my-app',
  template: 'Parent (<child id="child"></child>)'
})
class MyApp {
  constructor(dcl: DynamicComponentLoader, injector: Injector) {
    dcl.loadAsRoot(ChildComponent, '#child', injector);
  }
}
</code>


Bootstrap Modal > Loop While > Abrir item dentro do Modal

Question: Acredito ser questão de colocar o código no local certo, porém estou quebrando a cabeça e não consigo...
Fiz um teste com o código padrão do BootStrap, onde funciona sobre um botão. Inclusive coloquei as chamadas de dados dentro dele e funcionou.
A questão agora é, minha index retorna valores do banco pelo while:
  while ($posts = mysql_fetch_array($busca)){
                extract($posts);
                ?>

                                <a href="single.php?id=<?php echo $posts['id']?>" title="<?php echo $posts['titulo']; ?>" >
                                <?php echo $posts['titulo']; ?>

                        <a href="single.php?id=<?php echo $posts['id']?>" title="<?php echo $posts['titulo']; ?>" class="thumbnail">
                            <img src="uploads/<?php echo $posts['path'] ?>" title="<?php echo $posts['titulo']; ?>" alt=""  id="blc-img" />

Visitas <?php echo $posts['visitas'] ?>

                <?php
                    };
                ?>

Como posso adaptar este código para que ao clicar em um dos itens, ele abra no Modal, e não no single.php? como esta no momento.
Código do modal:`
<button type="button" class="btn btn-primary" data-toggle="modal"    data-target=".bs-example-modal-lg">Large modal</button>

      ...

`

Não irei modificar o código padrão do Modal(acredito não haver necessidade).
Gostaria que ao clicar em um dos itens retornados, ele abra em Modal.
Modal com botão funcionando:

Minha ideia é quando clicar no post(aquele abaixo do Catalogo), ela abra da mesmo forma que o do botão.
Agradeço desde já!
Comment: A sim, está correto é verdade, eu não havia reparado, mas você tem que enviar uma id para cada elemento do seu laço para que seja carregado dentro do seu modal, senão ele vai sempre carregar só o primeiro elemento div externo do seu modal. Olha esse exemplo: http://jsfiddle.net/Lyp615jw/5/
Comment: Coloque o modal e o botão que vai chamar o modal dentro do while e os respectivos retornor do banco em cada posição.
Comment: @RafaelAcioly desculpe, poderia ser um pouco mais especifico? no caso eu não quero usar o botão para chamada do modal, e sim o proprio post como chamada para o modal...
Comment: você quer que quando a consulta do banco seja realizada o modal ja apareça?
Comment: @RafaelAcioly coloquei uma print do modal com botão. A ideal é funcionar quando clicar no post(a capa que esta abaixo da palavra Catalogo)
Comment: @HenriqueSilva, o modal do Boostrap não permite executar múltiplos modais, por isso não está carregando o conteúdo que você quer, mas você pode criar blocos separados e chamá-los dentro de um único modal, dá uma olhada na minha resposta: http://pt.stackoverflow.com/questions/81050/como-usar-multiplas-modals-no-bootstrap/81095#81095
Comment: Essa imagem do catalogo me lembrou do [Sephiroth](https://www.google.com.br/search?q=final+fantasy+vii+sephiroth&espv=2&biw=1600&bih=775&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMIjojZjN3JxwIVyhaQCh1gnwGO#imgrc=d7kwk85lmfQRuM%3A) no Final Fantasy VII
Comment: @IvanFerrer desculpe, acho que não entendi...na lógica do php, isto não seria um único modal?
Comment: @IvanFerrer ! Obrigado pela ajuda. Consegui adaptar sua referencia com perfeição... só estou com um pequeno problema, quando eu clico fora do Modal ele fecha e a pagina index encolhe um pouco a lateral direita, e se eu continuar entrando em outros Modals e clicando fora ele vai encolhendo mais... Sabe oque pode ser?
Answer: Cria uma função em js que você chama ela passando o id do filme, ai essa função chama seu single.php por ajax passando o id e depois carrega o html vindo do single.php dentro do modal e depois abre o modal.
 function carregarItem(id)
    {
        $( ".modal-content" ).load( "single.php", { id: id }, function() {
            ('.bs-example-modal-lg').modal('show');
        });
    }

Chamada HTML:

   <a onclick='carregarItem(<?php echo $posts['id']?>)' title="<?php echo $posts['titulo']; ?>" >
   <?php echo $posts['titulo']; ?>

Comment: Srs, neste caso a unica alteração seria utilizando a chamada HTML e a function? Sem o uso do código do bootsstrap? Não entendi
Comment: Você deve manter o html do seu modal também, porque o js vai atualizar o conteúdo do modal já existente e apos isso, mostrar na tela.
Comment: extamente esta parte que fico perdido... o html do modal bootstrap deve ser incluso em qual local? Já coloquei a function dentro do script no head, e já modifiquei a linha do a com onclick
Comment: Aonde fica a listagem dos filmes, fora do loop.
Comment: Nada acontece... e com o código html para o a onclick, ele perde o "link" e não consigo clicar.
Comment: Tenta debugar, na primeira linha da função digita `console.log(id),` veja se chega o id, e também para o `.load` funcionar, você precisa do `jquery`.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/27473/discussion-between-henrique-silva-and-henriquedpereira).
Answer: Imagino pelo oq eu entendi que quando clicar nos links você deve fazer uma solicitação ajax para a url no caso para o single.php dai pegar o retorno que deve ser um html de preferencia e jogar dentro da div do modal depois abrir o modal. Agora tem o problema do parametro acho que teria que implementar assim:
Exemplo:
Seu link:

   <a class='linkmodal' id='<?php echo $posts['id']?>' title="<?php echo $posts['titulo']; ?>" >
   <?php echo $posts['titulo']; ?>

//vinculei a solicitação ajax ao click do a e pego o id na propriedade do elemento

$('a.linkmodal').click(function(){
        $.ajax({
            url: 'single.php',
            data: {id: $(this).attr('id')}
        }).done(function(data) {
            $('div.modal-content').html(data);
        });

//aqui chamar abertura da modal codigo depende do plugin

});

Comment: Opa! Obrigado pelo comentário. Esta parte: //aqui chamar abertura da modal codigo depende do plugin ... vc se refere ao código que coloquei do bootstrap?
Comment: Esse comentario se refere a abertura do modal por exemplo "modal.show()" não sei qual plugin vc ta usando. Mas a função do @henriquedpereira ai embaixo ficou mais elegante.
Comment: Na verdade como nunca trabalhei com o JS nem JQuery, não sei qual usar... estou tentando adaptar oq encontro no http://getbootstrap.com/javascript/#modals-methods
Comment: Eu editei a resposta dele pra servir direitinho pra tu, acho que ficou mais elegante, mas acredito que das duas formas vão funcionar.


calling function from constructor inside class

Question: I created the following class:
class GlobalModal {
    constructor(text) {
        this.modal = document.getElementById('Modal');
        this.span = document.getElementById("closeModal");
        this.text = text;

        //Show the GlobalModal
        this.modal.style.display = "block";

        // When the user clicks on  (x), close the modal
        this.span.onclick = function() {
            this.close();
        }

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == this.modal) {
                this.close();
            }
        }
    }

    // Function to close the GlobalModal
    close() {
        this.modal.style.display = "none";
    }
}

I'm trying to call the function this.close();
Error: this, close is not a function.
Is what I'm trying to do even possible? What am I doing wrong?
Comment: Inside the event listener, `this` refers to the element that fired the event, not your class instance. I'm sure there is a dupe for this on SO
Answer: If you want to use this in the callback you should use an arrow function which binds this to the lexical context:
window.onclick = (event) => {
   if (event.target == this.modal) {
      this.close();
   }
}

Answer: class GlobalModal {
    constructor(text) {
        this.modal = document.getElementById('Modal');
        this.span = document.getElementById("closeModal");
        this.text = text;

        //Show the GlobalModal
        this.modal.style.display = "block";

        // When the user clicks on  (x), close the modal
        this.span.onclick = function() {
            this.close();
        }.bind(this)

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == this.modal) {
                this.close();
            }
        }.bind(this)
    }

    // Function to close the GlobalModal
    close() {
        this.modal.style.display = "none";
    }
}

As was pointed out by @ibrahim mahrir, you lose the context of this inside the event listener. bind explicitly sets the this value to whatever you give it as a parameter.


Finding the kernel of a polynomial map.

Question: I was thinking about that:
Suppose we have two polynomial rings over an arbitrary field $K$, $R=K[x_1,...,x_n]$ and $S=K[y_1,...,y_c]$, and $T=[x_1,...,x_n,y_1,...,y_c]$.
Now let $I$ be an ideal in $R$ and $g=(g_1,...,g_c)$ a list of polynomials in $R$.
Consider the map $r:T\longrightarrow R/I$ which maps $x_i\mapsto\bar{x_i}$ and $y_j\mapsto\bar{g_j}$.
I think $\ker(r)$ is $IT+(y_1-g_1,...,y_c-g_c)$, but I can't prove the inclusion "$\subseteq$".
Any suggestion please?
I add some details to be more precise:
1) The bar over an element means the class in the quotient.
2) Indices $j$ and $i$ runs over $1,...,c$ and $1,...,n$, respectively.
3) $IT$ is the extension of the ideal $I$ in the ring $T$ (which contains $R$).
I have tried to decompose the map $r$ as the composition of $\pi$, the projection in the quotient $R/I$, and the map $r{'}$ which maps $x_i\mapsto x_i$ and $y_i\mapsto g_i$, so I get $F\in\ker(\pi\circ r_1)$ iff $r_1(F)\in I$, but I don't know how to prove this fact.
The problem is that I don't know how to prove $r_1(F) \in I$ iff $F$ is $0$ or $F\in IT$. I know that $\ker(r_1)$ is $(y_1-g_1,...,y_c-g_c)$.
Answer: If you are given an element in the kernel you can try to use the Euclidean algorithm to split of multiples of $y_j-g_j$ in order to reduce to the case where your element actually lies in $R$.

Finding the kernel of a polynomial map.


Show a menu item as expanded if on a certain node type

Question: I have a News menu item, which then has children. I need it to be expanded if it is on a news article page, but not expanded on other certain pages.
I'm not sure which hook to use. i've played around with menu_link_alter but i can't figure out how to choose the item i'm on in order to process it. Maybe this isn't the correct way.
Any ideas please?
Answer: I would go with the context module.
You can set a context to be active whenever a certain content type is shown, in this case, an 'Article'.
You can then set the reaction to 'menu' and choose an item which will get an active trail. You can then target using CSS or more likely, it's probably already expanded.
https://drupal.org/project/context
Answer: You can try one of these:

https://drupal.org/project/menu_position
Menu position based on configurable criteria such as node type, etc.
https://drupal.org/project/menu_trail_by_path
Menu position based on the node's url alias. Best in combination with Pathauto.
Comment: Someone showed me menu_position and that's the method i ended up using and it works.


UWP on desktop closed by top X button - no event

Question: An UWP app which runs on desktop can be closed from the top X button but it doesn't have any event for it. It is known that on phones and tablets an app should rely on Suspending event, no matter how it's triggered and then the app should rely on ApplicationExecutionState.
However, here is a (maybe) common scenario: on phones the Suspending event suffice and in case a Voip call is going on it will be operated by OS after the app is suspended. On desktop the close button is expected, by user, to completely close the app. So if a call is on going it should be hanged up and certain resources should be released.
How can I know when the user clicked the "close" button if (and only if) the UWP app is running on desktop?
Answer: A restricted capability confirmAppClose was added in Windows 10 version 1703 (build 10.0.15063) in order to provide apps the ability to intercept window closing.
Manifest namespace:
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"

Manifest:
<Capabilities>
  <Capability Name="internetClient" />
  <rescap:Capability Name="confirmAppClose"/>
</Capabilities>

It needs extra approval when submitting to the store.  But then will fire the CloseRequested event on a SystemNavigationManagerPreview instance.
Code:
    public MainPage()
    {
        this.InitializeComponent();
        SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += this.OnCloseRequest;
    }

    private void OnCloseRequest(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
    {
        if (!saved) { e.Handled = true; SomePromptFunction(); }
    }

You can get a deferral to do a bit of work here (save or prompt), or you can set Handled to true in order to stop the window from closing (user cancelled prompt).
Comment: There's a blog someone posted about it here: http://codeworks.it/blog/?tag=systemnavigationmanagerpreview
Comment: Interesting - Intellisense shows the rescap:Capabilty node in appxmanifest with a squiggly underline indicating the capability doesn't exist, however the code compiles and the capability becomes active with this addition.
Comment: @zax I'm not sure why VS can't figure out the pieces, but that's also why they have the `IgnorableNamespaces` tag on the Package.  You can add rescap there to remove the squiggles.
Comment: @MichaelHawker-MSFT The squiggles and associated pop-up error text are present *with* rescap added to IgnorableNamespaces.  VS 2017, 15.8.4.
Comment: I saw the documentation pages you shared the link to, but i still dont know how to do it. Can you guide me how to register a handler for that event, in my window?
Comment: Hmm, I'd log an issue with the VS feedback tools then.
Answer: From official page about app lifecycle:

There's no special event to indicate that the user closed the app.
Closed-by-user behavior:  If your app needs to do something different when it is closed by the user than when it is closed by Windows, you can use the activation event handler to determine whether the app was terminated by the user or by Windows.

So according to this there is no (clear) way to know if the user closed the app before the app is closed but only after it's restarted. Too bad.
Comment: This is outdated now, I posted an updated answer below.
Comment: I guess it sorta make sense not to fire a close event. What if someone re-open another window at Closed? Is it achievable? Probably.
Comment: @Hiro I'm not sure I understand what you mean by "re-open another window at Closed". Anyway, needs vary from case to case and therefore it might makes sense to have a Closed event or to ignore it. For the record WinForms and WPF have it.
Answer: This code helps you -
In App.xaml.cs
...
using Windows.ApplicationModel;
...

public App()
{
    InitializeComponent();
    this.Suspending += OnSuspending;
}
...
private void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    //Add your logic here, if any
    deferral.Complete();
}

Thanks!!!
Answer: I deleted my original answer with Window.Current.Closed event, because it doesn't seem to work if you have only one Window instance. There is also CoreApplication.Exiting, but judging by this topic it doesn't work either. Seems to be known issue which might be fixed in future. At the end, it appears there is no clear way to determine when the app is getting closed, only when it's suspended.
However, Window.Current does fire VisibilityChanged event when app is closed. Problem is, it's also fired when app is minimized and maybe in some other cases. But I think in combination with Suspending you can (more or less) safely determine that desktop app is closing. Good thing is, VisibilityChanged fired before Suspending and you can save it's value and check it in OnSuspending handler, after which decide if you need to do any cleaning up or other work.
Comment: But `VisibilityChanged` event will be fired when the OS closes the app as well. So there is no difference between OS-closing and user-closing.
Comment: Yes, OS can close the app as well, but it does so when it needs to free resources, which could be a quite rare case in desktop. Anyway, as I pointed before - it appears there is no clear way to determine when the app is getting closed by user.
Comment: So we can *guess* the app has been closed if we get the `VisibilityChanged` followed by the `Suspending` event.  Can this not occur naturally if the user minimizes the app and later Windows decides to suspend our app?  Then we would have incorrectly *guessed* the app is closing, as the user can later maximize it and resume?
Comment: Yes, in this case our guess will probably be incorrect. As I mentioned before, there seems to be no clear way to determine if app is closed by user unless you're checking it on the next launch.
Answer: For those who find this question looking for how to confirm closing of a Window in WinUI3:
The Window.Closed event args has a Handled property which can be set to true to cancel the close.
I was really confused that Closed, in contrast to WPF can still be cancelled.


C++ & WINSOCK - Recv two struct & two messages

Question: I try to recv all data which i send.
I send this:
wpisano = send(maindll_socket, (char *)"witam", sizeof("witam"), 0);
wpisano2 = send(maindll_socket, (char *)"Pozdrawiam", sizeof("Pozdrawiam"), 0);

and recv
unsigned __stdcall main_pipe_server(void* Args)
{
    Sleep(500);
    LRESULT uiMessage;
    char wiadomosc[512];
    char tmpbuff[1024];
    int bytesRecv = SOCKET_ERROR;
    while (true){
        bytesRecv = recv(mainmenu::getInstance().dll_clients[0], wiadomosc, sizeof(wiadomosc), 0);
        if (bytesRecv > 0){
            MessageBox(NULL, (LPCSTR) wiadomosc, "DONE", NULL);
            sprintf_s(tmpbuff, 1023, "%s = %d | %d", wiadomosc, strlen(wiadomosc),bytesRecv );
            OutputDebugString(tmpbuff);
        }
        Sleep(1000);
    }
//(...)
}

And the result was -
MessageBox - "witam"
Debug: "witam = 5 | 17"
So where is second msg?
Above was a simple question.
But i try to send two msg with data (which one was number of struct, and second is struct):
    int id=STRUCT_INIT_NUM;
    struct ST_ConInitChar a;
    a = { "BeCareful", python_func.py_getCurrentHp(), python_func.py_getMaxHp(), python_func.py_getMaxSp(), python_func.py_getMaxSp(), python_func.py_getMoney() };
    DWORD wpisano,wpisano2 = 0;
    wpisano = send(maindll_socket,(char *) &id, sizeof(id), 0);
    wpisano2 = send(maindll_socket, (char *)&a, sizeof(a), 0);

And recv - but it didn't working:
    unsigned __stdcall main_pipe_server(void* Args)
{
    Sleep(500);
    LRESULT uiMessage;
    char wiadomosc[512];
    char tmpbuff[1024];
    int bytesRecv = SOCKET_ERROR;
    while (true){
        bytesRecv = recv(mainmenu::getInstance().dll_clients[0], wiadomosc, sizeof(wiadomosc), 0);
        if (bytesRecv > sizeof(int)){
            char * p = wiadomosc;
            int *pId = (int*)p;
            p += sizeof(*pId);
            if (*pId == STRUCT_INIT_NUM){
                ST_ConInitChar * a = (ST_ConInitChar *)p;
                if (sizeof(a) > 0 && strlen(wiadomosc) > 0){
                    MessageBox(NULL, (LPCSTR)a->name, (LPCSTR) "DONE", NULL); // crash my program
                }
            }
        }
        Sleep(1000);
    }
//(...)
}

Comment: When you say "msg", can you explain *precisely* what you mean? If you're expecting your receive code to receive messages, where is the code that does this? The `recv` function on a TCP connection just receives bytes from the TCP connection. It has no idea what a message is. (And, I suspect, you don't either.)
Answer: In the first example, you are sending a total of 17 bytes and then reading 512 bytes.  Your wiadomosc buffer ends up receiving both messages.  You only see one message being displayed because you are including the null terminators in your sent data and then treating the received data as a null terminated string.  A string literal is implemented as a const char[] so you are effectively doing this:
const char str1[] = "witam"; // "witam\0"
wpisano = send(maindll_socket, (char *)str1, sizeof(str1), 0); // sizeof = 6, not 5

If you do not want your data to be null terminated then use strlen() instead of sizeof().
Your second example does not work because your struct's name member is a pointer to outside data that is not contained in the struct itself.  When you send the struct, you are sending the pointer itself, not the data that it is pointing at.  In this case, you cannot send the struct as-is, you need to serialize it into a transmittable format and send that instead, then receive it and deserialize it back into a meaningful struct.  You do not have to do that with POD types, like integers, but you do with pointers, like character strings.  I would suggest you send a string's length followed by the string's characters. That way, you can read the length first, allocate a sufficient buffer, then read the characters in to it.
Comment: Yes you have right :)

But tell me, how to distinguish first message between second message?

Now my "message" seems like "witamPozdrawiam"
Comment: Can you show an example, about second example?

My struct is [link](http://pastebin.com/BWWGMgWf)
Comment: In the first example, you need to delimit the messages. If you are just sending strings, the null terminator is fine for that. Or preceed each transmitted string with its length. In the second example, the id describes which struct is being sent, and the struct layout governs how the struct data is terminated. However, there are serialization formats that are more generic and flexible, such as TLD (type, length, data). I suggeat you adopt one.


Alternate Definition of a Derivative Question

Question: The alternate form of the derivative is

$$f'(a)=\lim_\limits{x \to a}\frac{f(x)-f(a)}{x-a}$$

Can this be rewritten to this and still be true?

$$f'(a)=\lim_\limits{x \to a}\frac{f(a)-f(x)}{a-x}$$

If what I wrote violates any limit rule please tell me.
Comment: The term "alternate form" in your text (not in your title) is not adequate : it is the classical definition of the derivative ! It would be an "alternate form" if you had given at first another definition of the derivative... but which one ?
Comment: The bleepin' expressions are equal! End of proof.
Comment: @zhw., I think the OP has the right to be cautious. Not everything that seems equal is always so. For example, in general $\frac{dy}{dx} \neq \frac{1}{dx/dy}$. And that's exactly because of the limit operation
Comment: @zhw., you did not consider the limit operation anywhere in this statement. And that's just the kind of reassurance the OP wanted. The rules of arithmetics may not hold under the limit in general
Comment: So you actually believe that if $u(x) \equiv v(x),$ the situations $\lim_{x\to a} u(x), \lim_{x\to a} v(x),$ can be different? I'm afraid in that case I must bid you adieu.
Comment: But $a/b = (-a)/(-b)$ is always true if $a,b \in \mathbb R, b \ne 0.$
Answer: Yes. But you're not using any properties of limits. Notice that the fractions inside the limits are actually the same:
$$\dfrac{f(x)-f(a)}{x-a} = \dfrac{-(-f(x)+f(a))}{-(-x+a)} = \dfrac{-1}{-1} \cdot \dfrac{f(a)-f(x)}{a-x} = \dfrac{f(a)-f(x)}{a-x}$$
Comment: They are the "same" fraction. If you want a more technical word, they are "equivalent" fractions.
Comment: Technical note: the fractions aren't the same, but their values are.
Comment: "Same" does not imply syntactic symbol for symbol sameness. For example, one can say $(1+1)/4$ and $2/4$ are both the same as $1/2$ even though all three use distinct lists of symbols.


Eigendecomposition factors relationship

Question: We know that the eigendecomposition of a square matrix $C\in\mathbb{R}^{n\times n}$, yields the following-
$$C=V\Lambda V^T$$
where
$V\in\mathbb{R}^{n\times n}$ is the matrix of eigen-vectors of $C$
$\Lambda\in\mathbb{R}^{n\times n}$ is the diagonal matrix containing eigen-values of $C$
Since the eigen-vectors happen to form an orthonormal basis, the product $V^TV=I_n$. This lets us conclude that $V^T$ is the left inverse of $V$. I have seen canonically $V^T$ being written interchangeably with $V^{-1}$, indicating that it's the right inverse of $V$ as well.
$$VV^T=\sum_{i=1}^nv_iv_i^T=I_n$$
where $v_i$ is the i$^{\text{th}}$ column vector of $V$ or eigen-vector of $C$.
I don't see why the above condition has to always hold true.
$v_i^Tv_i=1,~v_i^Tv_j=0:i\neq j$ immediately yields $V^TV=I_n$, but I'm struggling to see why this implies that the sum of their outer-products also has to equal the Identity matrix.
I can prove it mathematically using $Cv_i=\lambda_iv_i\implies CV=V\Lambda\implies V^{-1}=V^T$, but was looking for a proof that ties it to the orthonormality of the eigen-vectors.
Comment: Your initial assertion is not true in general. The eigendecomposition of an arbitrary diagonalizable matrix is $V\Lambda V^{-1}$, not $V\Lambda V^T$.
Answer: $$
A = \left[\begin{array}\
  a_1^T\\
  a_2^T\\
\vdots \\
a_n^T
\end{array}\right]
$$
$$
B = \left[\begin{array}\
  b_1&
  b_2&
\cdots &
b_n
\end{array}\right]
$$
$$
AB = \left[\begin{array}\
  a_1^Tb_1 & a_1^Tb_2 & \cdots \\
  &\\
&\ddots \\
a_n^Tb_1 & a_n^Tb_2 & \cdots
\end{array}\right]\qquad(1)
$$
So in your $V^TV$, the diagonal $a_i^Tb_i$ are ones and remaining elements are zeros. Thus forming an identity matrix.
$AB = I$ and so $B^TA^T = I$.
Now consider,
$$A^TB^T =  \left[\begin{array}\
  a_1&
  a_2&
\cdots &
a_n
\end{array}\right]
\left[\begin{array}\
  b_1^T\\
  b_2^T\\
\vdots \\
b_n^T
\end{array}\right]
$$
$$
A^TB^T=\left[\begin{array}\
  a_1b_1^T + a_2b_2^T+ \cdots + a_nb_n^T
\end{array}\right] \qquad(2)
$$
EDIT
So the term $\sum_{i=1}^nv_iv_i^T$ is the term in (2). So now if we prove that for $B^TA^T = I$, left inverse is same as right inverse, i.e. $A^TB^T = I$, our work is done.
For this proof, check out If $AB = I$ then $BA = I$
Now I know that this is not what you asked. You wanted to understand it in terms of orthogonality of the eigenvectors. For this I have tried to summate $\sum_{i=1}^nv_iv_i^T$ for different matrices and found that for orthonormal columns, the rows are also orthonormal. I have checked so many sources for its proof, but every proof is just utilising the $Q^TQ = Q Q^T = I$, which is what you wanted the proof of in the first place. Arithmetically everything is somehow falling into correct places to make it identity but I'm just unable to formulate it even after I tried with many examples.
So I think my above explanation is arithmetically correct enough for the proof, but in order to utilise the orthonormality of the eigenvectors (i.e. column space of $V$), I have imagined it in the following way:
We know that $v_iv_i^T$ is a projection matrix which projects on to the column space of this projection matrix, which in turn is essentially along the column vector itself since it is a rank-1 matrix.
Now $v_1v_1^T$ will project an n-dimensional vector $x$ along $v_1$, similarly $v_2v_2^T$ along $v_2$ and so on. So when you add all these n projections, you end up with the original vector $x$, thus in a way, sum of all these projection matrices, project the vector onto itself, so it must be identity matrix.
EDIT2:
Extending this visualization of projections to equations based on link provided by Amrit in the comments:
So the n-dimensional vector $x$ can be written as sum of all the projections, with each projection length as $c_i$, we get:
$$
x = c_1v_1+c_2v_2+\cdots+c_nv_n
$$
To find each $c_i$, we dot product $x$ with $v_i$
$$
x\cdot v_i = (c_1v_1)\cdot v_i+\cdots + (c_iv_i)\cdot v_i + \cdots + (c_nv_n)\cdot v_i
$$
$$
x\cdot v_i = 0+\cdots +c_i+\cdots +0
$$
So rewriting $x$ in terms of these calculated coefficients,
$$
x = (x\cdot v_1)v_1+\cdots +(x\cdot v_n)v_n
$$
$$
x = \sum_i(v_i^Tx)v_i
$$
$$
\Bigl(\sum_iv_iv_i^T-I_n\Bigr)x=0~\forall x \implies \sum_i v_iv_i^T=I_n
$$
Comment: Thanks for giving it an honest go. I was able to find precisely what I was looking for, i.e. $$\sum_{i=1}^nv_iv_i^T=I_n$$

where $v_i$ forms an orthonormal basis. This follows from observing that any general vector $a\in\mathbb{R}^{n\times1}$ can be written as $a=\sum_i(v_i^Ta)v_i$. Hence, $\sum_iv_iv_i^Ta=a$ for all $a$. $(\sum_iv_iv_i^T-I_n)a=0~\forall a\implies \sum_iv_iv_i^T=I_n$.

For further details, read [this paper](https://www.math.ucdavis.edu/~linear/old/notes21.pdf).
Comment: Aaah. It confirms my above visualization of projecting a vector along these n basis vectors. What I left out is the length of each projection, which brings the values of $vv^T$ into the equation. I will edit this part into my answer. You need NOT accept my answer, its just for anyone else who might stumble onto here and might not read your comment. (Basically its just for my peace of mind :p ). Most of all huge thanks to you for that link, now I can sleep happily :)
Comment: The $a_1$ in equation 1 is not equal to the $a_1$ in equation 2. If you define your matrix $$A=\begin{bmatrix}
a_1^T\\
\vdots\\
a_n^T
\end{bmatrix}$$ Then $$A^T=\begin{bmatrix}
a_1 & \dots & a_n
\end{bmatrix}$$

So equation 2 should be $A^TB^T$.

Equation 1 proves $AB=I$. Taking transposes, you get $B^TA^T=I$. Hence, equation 2 does NOT follow from equation 1 to be equal to the identity.
Comment: @AmritPrasad you are correct and I have edited my answer to correct the above mistake. Your question has sent me looking into the fundamentals of matrix multiplication and vector spaces but I could only come up with the above intuitive explanation. You have certainly given me food for thought and I thank you for asking this wonderful question. I hope that you will find my explanation useful.
Answer: Matrix product, usually defined as matrix of inner product of column vectors, coincide with outer sum of outer product (matrices) of column vectors. So you said

I'm struggling to see why this implies that the sum of their outer-products also has to equal the Identity matrix.

The sum of outer-products(of orthonormal basis) equals to matrix of inner products of orthonormal basis. Matrix of inner products of orthonormal basis, is the identity matrix.
Is this answer satisfies you?
Comment: @AmritPrasad Or maybe, the fact that orthogonal matrix having not only orthonormal column basis, but also having orthonormal row basis can help you? Sorry that I'm not sure I can help you.
Comment: No. You have just restated my question. I would like a proof or a paper which explains this.
Comment: @AmritPrasad I have essentially written in matrix form in my answer, what Jeong has written verbally in his answer.
Comment: @AmritPrasad At this moment, I am not clear what you are asking. If what you want is an orthonormality-related proof, I guess orthonormality has nothing to do with here: If you have left inverse matrix of a whatever square matrix, it's also a right inverse matrix. Orthonormality in this case, just implies transpose is a (left) inverse of itself.
Answer: While this answer won't give you any real insight, it does prove the fact. Assume $V^\top V= I$. Since we are dealing with square matrices, we have $VV^\top V = VI=V=IV$. But then we find that $VV^\top=I$ by comparing the left and right side of the previous equality. In other words, we get this fact for free.

Eigendecomposition factors relationship