Polynomial map is surjective if it is injective

Question: A friend of mine told me the following fact:

If $k$ is any algebraically closed field, then a polynomial map $f\colon k^n\to k^n$ of affine space $k^n$ is surjective if it is injective.

The proof he told me was actually a logic argument, which I didn't really understand, so I can't fully reproduce it here. The idea was that since it is the first order statement, it is enough to prove it for fields of characteristic $p>0$ for infinitely many $p$. Then by some reason it was enough to prove it for locally finite fields, and it somehow reduces to the same statement about finite fields $k$, where it is already obvious.
I am very far from logic, so I would like to see a nice algebraic (or geometric) proof of this fact. Do you know how to do that?
Thank you very much!
Comment: Please see the Wikipedia article on the [Ax-Grothendieck Theorem.](http://en.wikipedia.org/wiki/Ax%E2%80%93Grothendieck_theorem)
Comment: Also sprach Terry Tao: http://terrytao.wordpress.com/2009/03/07/infinite-fields-finite-fields-and-the-ax-grothendieck-theorem/. See the Rudin's proof.
Comment: @AndréNicolas Thanks! I didn't know that this is such a famous theorem. Friend told me that just as some fact.
Comment: You are welcome. It is particularly famous in Model Theory, as an example of a non-trivial result in "ordinary" mathematics proved using model-theoretic techniques. There have been quite a few since.
Comment: When $k=\mathbb C$, a nice proof by Rudin appears in *Injective polynomial maps are automorphisms*, Amer. Math. Monthly, **102 (6)**, (1995), 540–543.
Comment: @SashaPatotski: you should correct the statement. Surjectivity does not imply injectivity, e.g. $x\mapsto x^n$ with $n\ge 2$ prime to the characteristic.
Comment: @Cantlog Thanks! I have corrected it.
Answer: I would like to comment, that the model theoretic proof really is not that complicated, and this is coming from someone who is very algebro geometrically minded.
While there are many places you can probably find this on the internet, let me rephrase the argument here. Perhaps I'll say it in some way that is, for some reason, more clear to you. I will be semi-informal about the intuitive stuff, in an effort to make it more comprehensible.
I will include many of the proofs of the important theorems, although they can be easily disregarded. It maybe worth reading them though just to convince yourself how trivial their proofs really are.
Also, I am no model theorist, by any standard of the term, so there is a possibility I'll make a mistake below. I hope, in that case, one of our resident model theorists could correct me :)

Recall that a language $\mathcal{L}$ is nothing more than a string of symbols over some "signature/alphabet" of base symbols. For example, consider the language of rings $\mathcal{L}_\text{ring}$ which is sentences formed out of the alphabet $\{+,\cdot,0,1\}$. Another example might be the language of groups $\mathcal{L}_\text{group}$ which is formed out of the alphabet $\{\cdot,e,i\}$ (where $\cdot$ is supposed to be a binary operation, $e$ the identity element of the group, and $i$ the inverse function).
Now, all of the elements of this alphabet are supposed to represent either a function (with some arity), a constant (just some element), or a relation. For example, in $\mathcal{L}_\text{group}$ the symbol $e$ is a constant, and the functions $\cdot$ and $i$ are functions with arities $1$ and $2$ respectively.
Now, why I am distinguishing between constant symbols and function symbols (since they are at that point just meaningless symbols) seems silly, until one defines an $\mathcal{L}$-structure. Namely, given a language $\mathcal{L}$, an $\mathcal{L}$-structure $S$ of that language is nothing more than a set $S$ with an interpretation of each of the symbols of $\mathcal{L}$ in terms of $S$. For example, an $\mathcal{L}_\text{group}$ structure is nothing but an interpretation of $e$, $\cdot$, and $i$ in $S$. What does this mean? Well, since $e$ is a constant symbol, it's interpretation should just be an element $e\in S$ that I've picked. Since $\cdot$ is a function symbol with arity $2$ an interpretation is just some function $\cdot:S^2\to S$.Finally, since $i$ is a function symbol with arity $1$ an interpretation is just a function $i:S\to S$.
Now, note that there was absolutely no restriction on how I interpreted my symbols in an $\mathcal{L}$-structure, and moreover there are many such interpretations. As an example, I can make $\{0,1\}$ an $\mathcal{L}_\text{group}$-structure by saying $e=0$, $\cdot:\{0,1\}^2\to\{0,1\}$ just sends everything to $1$, and $i:\{0,1\}\to\{0,1\}$ just sends everything to $0$. Indeed, at this point I have not dictated that the interpretations satisfy any properties. But, of course, this seems silly. We'd expect that the language of groups should have something to do with groups. This is precisely where a theory comes in.
A theory $\mathcal{T}$ in a language $\mathcal{L}$ is nothing more than a collection of sentences using only the alphabet,  the standard logical quantifiers (e.g. $\forall,\exists$), and the standard logical connectives (e.g. $\vee,\wedge$,etc.). For example, the theory $\mathcal{T}_\text{group}$ in $\mathcal{L}_\text{group}$ consists of the following three sentences
$$1.(\forall x,y,z)(x\cdot(y\cdot z)=(x\cdot y)\cdot z)$$
$$2.(\forall x)(\cdot(x,i(x))=e=\cdot(i(x),x)\text{ }$$
$$3.(\forall x)(\cdot(x,e)=x=\cdot(e,x)\quad\quad$$
A model of a theory $\mathcal{T}$ is then nothing but an $\mathcal{L}$-structure for which the interpretations of the symbols satisfy the sentences in $\mathcal{T}$ (where we are quantifying over the elements of the set). For example, my interpretation of $\mathcal{L}_\text{group}$ in the set $\{0,1\}$ is NOT a model of the theory $\mathcal{T}_\text{group}$. That said, the $\mathcal{L}_\text{group}$-structure on the set $\{0,1\}$ where $e=0$, $\cdot(0,1)=\cdot(1,0)=1$, $\cdot(1,1)=\cdot(0,0)=0$, and $i(0)=0$, and $i(1)=1$ is a model of $\mathcal{T}_\text{group}$. In fact, I think you can see that a model of $\mathcal{T}_\text{group}$ is nothing more than a group!
Now that all of the basic terminology is established, which really was quite intuitive, we can finally discuss something substantive. I've often been told that there are only two theorems in model theory. The first is the following:

Theorem(Godel,Malstev): A theory of first order sentences has a model if and only if every finite subset has a model.

This, from what I understand (I've never seen the proof) isn't really that complicated. In fact, if you interpret correctly in terms of Stone spaces it apparently comes directly from Tychnoff's theorem. It also has a very, intuitively obvious, formulation in terms of ultraproducts, in which case it follows from Łos's theorem. The intuition for the correctness of the compactness theorem follows much like the intuition in algebraic geometry that one can often descend problems about schemes $X/\mathbb{C}$ to a statement about some scheme $X'/R$ for some finitely generated subring $R$ of $\mathbb{C}$ (this is Grothendieck's trick of "passing to the limit").
The second foundational theorem of model theory is the following:

Theorem(Lowenheim-Skolem): If $\mathcal{T}$ is a theory which admits an infinite model, then it admits a model of size $\kappa$ for every $\kappa\geqslant \max\{\# \mathcal{L},\aleph_0\}$.

The above theorem actually is two theorems rolled into one: the "upward" Lowenheim-Skolem theorem, and the "downard" Lowenheim-Skolem theorem. The upward part says that if you have an infinite model of size $\kappa$, you have a model of size $\lambda$ for every $\lambda\geqslant\kappa$. The downward part should now have obvious meaning.
The downward part of Lowenheim-Skolem is annoying and elementary--you explicitly construct the models. This is also where the size of the language comes into play. Intuitively, the size of the language comes into play since your language could contain nothing but constant symbols, all of which are dictated by your theory to be distinct. The upward Lowenheim-Skolem theorem is easy to prove from compactness and the downward part of Lowenheim-Skolem.
Proof(Upward Lowenheim-Skolem) Let $M$ be your model of size $\kappa$, and let $\lambda\geqslant\kappa$ be a cardinal. Consider the language $\mathcal{L}'$ which is obtained from the language of $\mathcal{T}$ by appending the set of constants $\{c_i\}_{i\leqslant\lambda}$. Let $\mathcal{T}'$ be the theory obtained by appending the sentences $\varphi_{i,j}:c_i\ne c_j$ for all $i,j$.
Note then that for all finite subsets $\Delta$ of $\mathcal{T}'$, there is a model of $\Delta$. Indeed, consider the finitely many sentences $\varphi_{i,j}\in \Delta$, with $(i,j)\in I$ where $I$ some finite set. Let us define a $\mathcal{L}'$-structure $M_\Delta$, whose underlying set is the same as $M$. We interpret $\mathcal{L}$ in $M_\Delta$ the same way we interpretted it in $M$, and for each $\{c_i\}_{i\leqslant\lambda}$ we choose some element $c_i\in M$. We choose the $c_i$ though such that $c_i\ne c_j$ if $(i,j)\in I$. Note then that by the very construction of $M_\Delta$, that $M_\Delta$ is a model of $\Delta$ as desired.
Thus, by compactness, $\mathcal{T}'$ admits some model $N$. Necessarily, $\# N\geqslant\lambda$ since $N$ interprets $\lambda$ many symbols $c_i$ which, by virtue of modeling $\mathcal{T}'$, are all distinct. We then get a model of size exactly $\lambda$ by applying downward Lowenheim-Skolem. $\blacksquare$
The amazing thing is that given the Compactness Theorem everything else becomes very easy at least as far as the proof of Ax-Grothendieck is concerned.
Before we get to the Ax-Grothendieck theorem though, we first need to discuss some technically powerful, but surprisingly simple theorems.
Let us say that a theory $\mathcal{T}$ is complete if for every sentence $\varphi$ in the language, either $\varphi$ is in $T$ or $\neg\varphi$ ($\neg$ is negation) is in $\mathcal{T}$. This says that every model $M$ of $\mathcal{T}$ must either satisfy $\varphi$, or every model $M$ of $\mathcal{T}$ must satisfy $\neg\varphi$. For example, the theory $\mathcal{T}_\text{group}$ is NOT complete. Consider the sentence $\varphi$ given by $(\forall x,y)(x\cdot y=y\cdot x)$. Then, there are models of $T$ for which $\varphi$ holds (e.g. abelian groups) and those for which $\varphi$ does not hold (non-abelian groups). Thus, being a complete theory is a a very, very strong thing, yet an obviously desirable one. Why is it so desirable? Because, to check that some sentence is true for all models of the theory, one needs only check it is true for ONE model of the theory.
Now, while completeness seems like a very attractive property, it has some obvious immediate downsides. First, one would expect that most theories aren't complete (think of three theories--none of them are probably complete). Second, even if something is complete, it seems very difficult to prove it is such--think about how one might attack such a problem. That said, there is a very important model theoretic property of a theory which guarantees completeness, and is a property that is secretly familiar to us from our everyday mathematical lives. This property is $\kappa$-categoricity.
Let us say that a theory $\mathcal{T}$ is $\kappa$-categorical, if $\mathcal{T}$ admits, up to isomorphism, only one model of cardinality $\kappa$. Isomorphism between two models $M,M'$ of $\mathcal{T}$ is what you'd expect--it's a bijection, which preserves the structure dictated by the language (in all of the theories you'd care about, rings, groups, etc. isomorphisms are what'd you expect). Why is $\kappa$-categoricity so nice? Well, because of the following:

Theorem(Vaught's Test): Suppose that $\mathcal{T}$ is $\kappa$ categorical where $\kappa\geqslant \max(\aleph_0,|\mathcal{L}|)$, and every model of $\mathcal{T}$ is infinite. Then, $\mathcal{T}$ is complete.

Proof: If $\mathcal{T}$ were not complete, there would exist some sentence $\varphi$ in the language of $\mathcal{T}$ such that there are models $M$ and $M'$ of $\mathcal{T}$ for which $\varphi$ holds in $M$ and $\neg\varphi$ holds in $M'$. Consider then the theories $\mathcal{S}=\mathcal{T}\cup\{\varphi\}$ and $\mathcal{S}'=\mathcal{T}\cup\{\neg\varphi\}$. Note then that $M$ is a model of $\mathcal{S}$ and $M'$ is a model of $\mathcal{S}'$. Since $M$ and $M'$ are infinite (since all models of $\mathcal{T}$ are) we have by Lowenheim-Skolem that there is a model $N$ of $\mathcal{S}$ and $N'$ of $\mathcal{S}'$, each of size $\kappa$. Evidently $N$ and $N'$ are models of $\mathcal{T}$ of size $\kappa$, and so by assumption of $\kappa$-categoricity, isomorphic. But, this is a contradiction since $\varphi$ holds in $N$ but not in $N'$. $\blacksquare$
As an example of a $2^{\aleph_0}$-categorical theory, consider the theory of $\mathbb{F}_2$ vector spaces (defined in the way you'd expect). Since, by cardinality considerations, any $\mathbb{F}_2$ vector space of cardinality $2^{\aleph_0}$ must be dimension $2^{\aleph_0}$ any two are isomorphic.
It's interesting to note that, in fact, $\mathbb{F}_2$ vector spaces are $\kappa$-categorical for every uncountable cardinal $\kappa$. This is no mistake, since Morley's categoricity (a very deep theorem) says that if a theory in a countable language is $\kappa$-categorical for one uncountable cardinal, it's $\lambda$-categorical for all uncountable cardinals $\lambda$.

Ok, so now onto what you actually care about.
Let us define the theory $\mathsf{ACF}$ of algebraically closed fields. This is a theory in the language of rings $\mathcal{L}_\text{ring}$, with the obvious extra sentences dictating commutativity and existence of inverses, as well as the existence of roots of all polynomials. This last condition is a little annoying to encode with just $\mathcal{L}_\text{ring}$ and logical quantifies/connectives. It goes something like for each $n$ adding in the sentence $(\forall a_0,...,a_n)(\exists x)(a_0+\cdots+a_n x^n=0)$.
Now, the theory $\mathsf{ACF}$ is NOT complete. Indeed, consider the sentence $(\forall x)(x+x=0)$. Then, this sentence is modeled by $\overline{\mathbb{F}_2}$ but the negation is modeled by $\mathbb{C}$. Somewhat amazingly, this type of sentence (specifying characteristic) is the ONLY obstruction to completeness.
To clarify this statement, let us define the following theories. For each prime $p$, let $\mathsf{ACF}_p$ denote the theory $\mathcal{T}_\mathsf{ACF}$ with the extra sentence $(\forall x)(\underbrace{x+\cdots+x}_{p\text{ times}})=0$ thrown in. Evidently the models of $\mathcal{T}_{\mathsf{ACF}_p}$ are just the algebraically closed fields of characteristic $p$. Note though that we also want to define the theory $\mathsf{ACF}_0$ of algebraically closed fields of characteristic $0$. Now, how we do this is VERY important. Instead of throwing in the sentence $(\forall x)(\underbrace{x+\cdots+x}_{p\text{ times}})=0$ we throw in its negation FOR ALL $p$. In particular, we specify characteristic $0$ by specifying not characteristic $p$ for all $p$. In particular, it takes infinitely many sentences to specifying characteristic $0$.
Now, my statement that the only thing stopping completeness for $\mathsf{ACF}$ is justified by the following:

Theorem: For every $p=\text{prime},\infty$, $\mathsf{ACF}_p$ is $\kappa$-categorical for every uncountable cardinal $\kappa$.

This will imply by Vaught's test (since every algebraically closed field is infinite and the language of rings is countable) that each $\mathsf{ACF}_p$ is complete!
The proof is actually very simple.
Proof: Suppose that $K,K'$ are two uncountable algebraically closed fields of the same characteristic. Suppose that $k$ is the prime subfield of $K,K'$ (i.e. $k=\mathbb{F}_p$ or $k=\mathbb{Q}$). Then, by cardinality considerations we have that
$$\text{tr.deg}_k K=\# K=\kappa=\# K'=\text{tr.deg}_k K'$$
Thus, we know that there are embeddings $K\hookleftarrow k(\{x_i\}_{i\leqslant\kappa})\hookrightarrow K'$ such that $K/k(\{x_i\})$ and $K'/k(\{x_i\})$ are both algebraic. But, since $K,K'$ are algebraically closed, we can conclude that $K$ and $K'$ must both be algebraic closures of $k(\{x_i\})$ and thus isomorphic. $\blacksquare$
Just to reiterate, this tells us, for example, that to check whether or not a sentence is true for all algebraically closed fields of characteristic $0$, it suffices to prove it's true for $\mathbb{C}$ (this, and several other various forms, is known as the Lefschetz principle).
Ok, with this, we can finally state the "big theorem" you were alluding to

Theorem: Let $\varphi$ be a sentence in $\mathcal{L}_\text{ring}$ then the following are equivalent

The sentence is true for some algebraically closed field $K$ of characteristic $0$.
The sentence is true for all algebraically closed fields of characteristic $0$.
The sentence holds true for an algebraically closed field K of characteristic $p$ ,for arbitrarily large $p$
The sentence holds true for all algebraically closed fields of characteristic $p$ for arbitrarily large $p$.

Proof: The equivalence of 1 and 2, and the equivalence of 3 and 4, follow from the completeness of $\mathsf{ACF}_0$ and $\mathsf{ACF}_p$ respectively. To prove that 1 and 3 are equivalent, we merely use compactness. Indeed, we want to show that $\mathcal{T}_{\mathsf{ACF}_0}\cup\{\varphi\}$ (where $\varphi$ is our sentence) has a model. But, by compactness, $\mathcal{T}_{\mathsf{ACF}_0}\cup\{\varphi\}$ will have a model if and only if every FINITE subset of $\mathcal{T}_{\mathsf{ACF}_0}\cup\{\varphi\}$ has a model. But, any finite subset $\Delta$ cannot contain the statements $(\forall x)(\underbrace{x+\cdots+x}_{p\text{ times}})=0$ for all $p$, and so, in particular, for a large enough prime $p$, our finite subset cannot contain $(\forall x)(\underbrace{x+\cdots+x}_{p\text{ times}})=0$. In particular, choosing a $p_0$ large enough so that $\varphi$ has a model $M$ in $\mathsf{ACF}_0$ (which we can do by assumption), we can see that $M$ is a model of $\Delta$. Thus (by compactness once again), we obtain a model of $\mathsf{ACF}_0$ as desired. $\blacksquare$
So, with this, we can make rigorous the proof of Ax-Grothendieck:

Theorem(Ax-Grothendieck): If $K$ is an algebraically closed field, every injective polynomial map $f:K^n\to K^n$ is surjective.

Proof: I leave it to you to show that we can take the statement "every injective polynomial map $K^n\to K^n$ is surjective" can be phrased in the language of $\mathsf{ACF}$ (it's long, and arduous, but elementary). Thus, by the above theorem, to prove this statement is true for all algebraically closed fields, it suffices to show that for each prime $p$, there is SOME algebraically closed field $K_p$ such that the statement is true. Let's choose $K_p=\overline{\mathbb{F}_p}$.
To prove the statement for $\overline{\mathbb{F}_p}$ we proceed as follows. Let $f:\overline{\mathbb{F}_p}^n\to\overline{\mathbb{F}_p}^n$ be injective. Choose any $\overline{b}\in \overline{\mathbb{F}_p}^n$. Let $\ell$ be the field obtained by adjoining the coordinates of $b$ and the coefficients of the polynomials defining $f$ to $\mathbb{F}_p$. Observe then that $f$ restricts to an injective polynomial map $f:\ell\to\ell$. But, by cardinality considerations, we must have that $f$ is surjective there, and thus $\overline{b}$ is in the image of $f$ as desired. The Ax-Grothendieck theorem follows. $\blacksquare$
Let me point out something somewhat miraculous about the above proof. The most obvious "Wow!" factor came from our ability to prove a statement in characteristic $0$ by working solely in characteristic $p$, but to me there is something equally amazing happening. Our proof in the case of $K=\overline{\mathbb{F}_p}$ COMPLETELY relied on the fact that $K/\mathbb{F}_p$ was algebraic. It would have failed for any other algebraically closed field of characteristic $p$ (because it would no longer be algebraic over $\mathbb{F}_p$). We were only able to conclude the result for the other algebraically closed fields of characteristic $p$ by compactness. This, to me, seems like magic.

The thing to notice, for me, about the above is how everything even Lowenheim-Skolem (although, only the upward part) followed formally from the compactness theorem. It really is quite astounding. I mean, it's so formal, and dare I say trivial, that even someone like me (who knows almost no model theory) can deduce it.
Something else to keep in mind about the above is the limited range of its powers. Upon first glance, one might expect the techniques above to revolutionize mathematics. I mean, it seems like such a profitable course of action to prove things about fields/algebro geometric things, by reducing it to the finite field case. The problem with this is simple--many of the statements we care about as algebraic geometers are outside the purview of first order logic (or at least phrasing them would be nightmarishly difficult). Try stating Riemann-Roch in the language of $\mathsf{ACF}$. So, while the above is powerful, and there are some deep philosophical consequences, it is not the end-all-be-all of mathematical theorems.
It is worth noting that if there were a subject where model theory ought to have a strong power over, it's the algebraic geometry of algebraically closed fields. There, not only do we have a well-behaved theory (e.g. $\mathsf{ACF}_p$ is complete, it has quantifier elimination, etc.) but the structure morphisms are polynomial maps--they are definable.
This, by the way, is how I feel about much of model theory (from my very uneducated point of view). It seems like a philosophically powerful, but practically ineffective theory. Besides the work of those like Hrushovski, I haven't heard of model theory being a sledgehammer in more "mainstream" mathematics. Just a thought.
Comment: Dear Alex, I'm really impressed by the breadth of your culture and by your expository talent!
Comment: Just stumbled upon this, quite an interesting read.
Comment: @BenWest A little light reading...you know, for fun. ;)
Comment: @GeorgesElencwajg Thank you so much for your kind words, they are much appreciated :)
Answer: Please see the Wikipedia article on the Ax-Grothendieck Theorem.
Remark: This is really a comment, but I would not like to see the result disappear from MSE for lack of an answer.
Answer: For an argument that doesn't use model theory, see for instance paragraph 4.1 "Injective endomorphisms are surjective" in Arno van den Essen, Polynomial Mappings and the Jacobian Conjecture. Here the more general claim is proven that every injective endomorphism of an algebraic variety over an algebraically closed field is surjective.
It is still, as far as I can see, a similar argument to the model theoretic argument: injectivity and non-surjectivity can be described using polynomial constraints, which makes it possible to reduce this to the case of a finite field. But it is a purely algebraic argument.
If people are interested, I can try to reproduce the proof here; it will be shorter than the argument by Alex Youcis above, but still relatively lengthy.


Can walls stop mobs from entering my town?

Question: A recent update added Cobblestone Walls, which are basically cost effective decorative fences that prevent players from jumping over it.
I'm wondering if these same walls can protect me from mobs like creepers, spiders, and skeletons.
Thanks!
Answer: What are cobblestone walls?
Cobblestone walls are a decorative alternative to fences. They come in two varieties, cobblestone walls and mossy cobblestone walls. They are made by placing cobblestone or mossy cobblestone in a Crafting Table like so. S is a cobblestone/mossy cobblestone block, and E means empty.
S S S
S S S
E E E
How high are cobblestone walls?
Since their properties are very similar to fences, they are 1.5 blocks high. Nothing can jump it unless there is a half-slab, block, or other item close enough to the wall to be able to jump over it. Therefore, it is recommended to use them in a flat area.
They are also good for bridges on maps like Skyblock, where you would have to make bridges that people/mobs may fall out of.
Pros

It give you a better view than having two cobblestone/other material, since that would obstruct your view.
Fences can be burned by griefers, nearby lava, and so on, whereas this cannot be burned. Additionally, it would take a long time for griefers to break it since it is made of cobblestone.

Cons

Mobs such as Spiders and Spider Jockeys can climb over it.
Endermen can teleport into a 'secure' area.
If they are close to the wall, Creepers/TNT can blow it up.
Skeletons/players with a bow can shoot arrows over the fence.

Miscellany
To stop Spiders and Spider Jockeys, you can place a block on top of the wall. If you still want to see, use glass. When used with burning netherrack, you can make a nice alternative to torches.
Comment: Enderman can teleport pass walls or fences.
Answer: Cobblestone Walls works the same as Fences. It will prevent all non-flying mobs except spiders from climbing over. Enderman can also teleport pass Walls or Fences.
You can place a block/slabs/stairs to prevent spiders from climbing over.
To prevent Enderman from getting in, you need to have a roof that is not higher than 3 block.
Comment: @gnovice Yes you are right, forgot to mention the height of the roof :P
Comment: Roofs don't help with Endermen, unless they limit the inside height to less than three blocks. With three blocks or more of space, Endermen can teleport inside. I've had many a sticky-fingered, unexpected guest in my home. ;)


Cassandra Select Query for List and Frozen

Question: I have user define type like
CREATE TYPE point ( pointId int, floor text);

And I have table like:
CREATE TABLE path (
id timeuuid,
val timeuuid,
PointList list<frozen <point>>,
PRIMARY KEY(id,val)
);

And have create index like
create index on path(PointList);

But the problem is I am not able to execute select query where PointList = [floor : "abc"].
I google for 2 hours but not able to find the hint.
I am using this query to execute select query
Select * from path where val = sdsdsdsdsds-dsdsdsd-dssds-sdsdsd and PointList contains {floor: 'eemiG8NbzdRCQ'};

I can see this data in my cassandra table but not able to get that data using above query.
I want select query where we can only use floor and val. Because we only have data for floor and val
I tried many different ways but nothing is working.
I would appreciate any kind of hint or help.
Thank you,
Answer: Frozen point means point type is frozen, you can't partially provide point value, you have to provide the full value of point
Example Query :
select * from path where pointlist CONTAINS {pointId : 1, floor : 'abc'};

Comment: @ParthPatel Instead of using UDT, use separate field for pointID and floor, and then create index on floor
Comment: Ohh Means I need to define all value of the frozen.
Comment: But I am using spring boot with cassandra and I only have data of floor. Is there any way that I can fetch data base using floor. ?
Comment: Thank you for suggestion but, thisi is just a sample. I have big list. and I only have data of `floor` . Can you tell me that, In Cassandra, is it possible to fetch data from the list the contain frozen datatype using where clause?


All foreign keys are 'Null'

Question: When inserting data into the table that works as it should. However when looking at the tables I noticed none of the foreign keys are working. Here is the 'Pizza' table which should be taking the foreign keys of BaseID and ToppingID from the other tables:

As the picture shows above, the ToppingID is null. Whereas in the actual 'PizzaToppings' table as shown below, the ToppingID is not null:

This is currently happening to all my foreign keys throughout the database.
However this throws the error of:

Integrity constraint violation: 1452 Cannot add or update a child row:
  a foreign key constraint fails (pizzadelivery.pizza, CONSTRAINT
  FK_BaseID FOREIGN KEY (BaseID) REFERENCES pizzabase (BaseID))
Comment: Where is your insert code?
Comment: Are you asking why that `CONSTRAINT` doesn't prevent the column from being `NULL`, or are you asking why your `INSERT` query doesn't populate the column?
Comment: What do you get as a result of SHOW VARIABLES LIKE '%FORE%' and SHOW global VARIABLES LIKE '%FORE%'
Comment: And where is the definition of `PizzaBase`
Comment: @Script47 PHP insertion code: http://phpfiddle.org/main/code/j9nx-hzbh
Comment: **Side Note:** @BenFoster your code is actually quite well written compared to other questions. Consider working on your question formatting too in the future.
Comment: @deceze I am relatively new to MySQL and PHP so I am trying to get an understanding of why the value is null in the Pizza table, I am assuming there is something wrong with the insert query that linked above.
Comment: Looking at your linked code (put the code into the question itself!): you're never putting anything into the `ToppingID` column.
Comment: @deceze My understanding was that the `ToppingID INT AUTO_INCREMENT` would auto increment the value by 1 for each topping added? Also my screenshot of my PizzaTopping table itself shows the value to be '1', so why is it null in the 'Pizza' table?
Comment: @BenFoster yes, it is an AI field in the table that it has been DEFINED in, not the referenced table. In the reference table you have to pass the ID of the topping too. Consider reading up on [table relationships](https://dev.mysql.com/doc/mysql-tutorial-excerpt/5.7/en/example-foreign-keys.html).
Comment: Inserting something into `PizzaToppings` does not automatically put anything into `Pizza`! The database would have no way of knowing what row in `Pizza` to put the `ToppingID` into.
Comment: So my mistake was assuming a foreign key would transfer the `ToppingID` over, when in fact it would require something like a join to do so?
Comment: Each query stands on its own, the database can't infer that you are making some logical connection between two independent queries and would like to cross-insert some ids. Yes, making that assumption was the problem. You need to first insert into `PizzaToppings`, and then insert into `Pizza` with the new id you just got from `PizzaToppings`.
Comment: @deceze Okay I tried what you suggested and attempted to insert the foreign key values into the Pizza table using this code: http://phpfiddle.org/main/code/urdi-j2cb. However this throws the error of:  _Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`pizzadelivery`.`pizza`, CONSTRAINT `FK_BaseID` FOREIGN KEY (`BaseID`) REFERENCES `pizzabase` (`BaseID`))_
Comment: Update your question, don't expect to get this solved in a comments thread.
Answer:
$toppingID = $stmt -> fetch(PDO::FETCH_ASSOC);

$toppingID here is an array, probably ending up bound as the string 'Array' in your final query, which obviously is a non-existent ID and violates your constraint (that's what constraints do, they ensure the datum is present in the other table).
You also don't want to use MAX() to get the id; it is not guaranteed that the new id has the highest number in the column, and it's not safe from race conditions if you're doing several queries in parallel. What you want is to get the last insert id:
$stmt = $pdo->prepare('INSERT INTO PizzaToppings ...');
...
$stmt->execute();
$toppingId = $pdo->lastInsertId();

$stmt = $pdo->prepare('INSERT INTO PizzaBase ...');
...
$stmt->execute();
$baseId = $pdo->lastInsertId();

$stmt = $pdo->prepare('INSERT INTO Pizza (..., ToppingID, BaseID) VALUES (..., :ToppingID, :BaseID)');
...
$stmt->bindParam(':ToppingID',$toppingId);
$stmt->bindParam(':BaseID',$baseId);
$stmt->execute();

All foreign keys are 'Null'


How many perfect pandora seeds exist?

Question: I've been looking at Gamerpuppy's Pandora's Box seeds. This user generated, using a program that quickly tries the output of Java's random number generator with a given 64-bit seed, and tries to find one that has the most repetitions of a given number (modulo the number of cards) in the output, as well as an initial roll of pandora's box for Neow (1/22).
In slay the spire, the characters start with the following number of strikes and defends, and have this number of cards available:
ironclad:   9    72
silent:    10    71
defect:     8    71
watcher:    8    71

I'm interested in what the probability would be of there existing a 'perfect' pandora seed: one where every generated card is the same. Knowing exactly would mean brute-forcing the whole space, which seems computationally unfeasible without a collaborative effort. So instead, to simplify; you may assume the generation is perfectly random instead of only a PRNG.
Answer: Result
For the Ironclad, Defect, and Watcher one very likely exists for every card. (In fact, I believe the algorithm has already found most of the Defect and Watcher seeds, and has found a few of the Ironclad ones). The cause is the fact that adding one more card to the starting deck makes it 71 or 72 times less likely for a seed to succeed.
For the Silent, there's about a 22.7% chance any specific card has a perfect seed.
The following table details the chance there is at least one seed, the expected amount of them that exist, and the number of seeds you would have to try to find one by pure chance:
+-----------+-----------------+-----------------+----------------------+
| Character | Perfect chance  | Number of seeds |        Trials        |
+-----------+-----------------+-----------------+----------------------+
| Ironclad  | 0.9999999007... |       1144.8878 |  1143971351913037824 |
| Silent    | 0.2270808586... |         18.5458 | 71615358122217386422 |
| Defect    | 0.999999999999+ |      92191.0159 |    14206577687406742 |
| Watcher   | 0.999999999999+ |      92191.0159 |    14206577687406742 |
+-----------+-----------------+-----------------+----------------------+

That means the seed searching program must have searched a substantial fraction (1% or so) of the total seed space to find all the perfect seeds it found, showing the power of a GPU (and why 64 or even 80 bit keys are now insecure in crypto)
Reasoning
Let's break it down into two parts;

Figure out what the probability is that all cards are the same and the relic is pandora, denoted P(same).
Get the total number of seeds N.

Then, combine the two steps with the following proof:
The probability that all cards are not the same is 1 - P(same) by applying the Inverse Rule. For this to happen N times, multiply itself by N by applying the Multiplication Rule N times.
Thus the probability that no seed exists is (1 - P(same))^N. Apply the inverse rule again to find the probability that at least one seed exists:
P(one seed) = 1 - (1 - P(same)))^N

Corollary 1: The inverse 1 / P(same) is the amount of seeds you would have to try to find at least one success on average (expectation of geometric variable).
Corollary 2: By multiplying the probability P(same) with the number of seeds N and the number of cards C (each card is independent), you get the expected total number of perfect seeds.
1. P(same)
All cards need to be the exact same specific card. Let C be the number of cards available, and D be the starting deck size, then the answer is (applying multiplication rule):
P(same) = 1/22 * (1/C)^(D)

This yields the following result:
Ironclad:  1/1143971351913037824
Silent:   1/71615358122217386422
Defect:      1/14206577687406742
Watcher:     1/14206577687406742

2. Getting N
This is simply the number of unsigned integers 2^64 = 18446744073709551616, since each seed is a 64-bit integer.

How many perfect pandora seeds exist?


cURL request not working on localhost and no error

Question: I use php 7.* on my wamp server, each time i make a curl request it does not return any results or show error. I can't figure out the problem. The same code works fine on live server. How can i solve this problem?
Answer: Check your php/php.ini file
Search for extension=php_curl.dll and remove the comment.
Restart


GAE - Class not found: Caused by: java.lang.ClassNotFoundExceptionAppIdentityCredential$AppEngineCredentialWrapper

Question: I'm trying to launch a simple Java (Maven) Spring Boot application on GAE that communicates with an PostrgreSql server (also on the Cloud Platform) however I keep running into missing dependencies.
I had these dependencies in my pom:
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-gcp-starter</artifactId>
      <version>1.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-gcp-starter-sql-postgresql</artifactId>
      <version>1.1.3.RELEASE</version>
    </dependency>

But whenever I deployed the app to GAE and the FlyWay the following was thrown:
java.lang.ClassNotFoundException: com.google.appengine.api.ThreadManager

I mainly followed the Baeldung tutorial here: https://www.baeldung.com/spring-boot-google-app-engine.
Then I found this answer: AppEngine ClassNotFoundException: com.google.appengine.api.datastore.DatastoreServiceFactory
Which led me to adding the appengine dependency:
    <dependency>
      <groupId>com.google.appengine</groupId>
      <artifactId>appengine-api-1.0-sdk</artifactId>
      <version>1.9.77</version>
    </dependency>

Which then throws:
ClassNotFoundException: com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential$AppEngineCredentialWrapper

Which then led me to adding the client dependency.. and so on.. and so on..
My complete set of dependencies is now:
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud</artifactId>
      <version>0.47.0-alpha</version>
    </dependency>
    <dependency>
      <groupId>com.google.appengine</groupId>
      <artifactId>appengine-api-1.0-sdk</artifactId>
      <version>1.9.77</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-gcp-starter</artifactId>
      <version>1.1.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-gcp-starter-sql-postgresql</artifactId>
      <version>1.1.3.RELEASE</version>
    </dependency>

And that.. leads back to the exception above:
ClassNotFoundException: com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential$AppEngineCredentialWrapper

So it is probably a dependency problem but I cannot for the life of my find any documentation about which dependencies you need to add to get a simple Spring Boot application running to a PostgreSQL server.
I'm about to throw in the towel...
It might be a lack of sleep though
Answer: You are missing the App Engine plugin in your pom.xml :
<build>
  <plugins>
    <plugin>
      <groupId>com.google.cloud.tools</groupId>
      <artifactId>appengine-maven-plugin</artifactId>
      <version>1.3.2</version>
    </plugin>
  </plugins>
</build>

And for the exception you get, I do not know exactly where are you using this but you can add the dependency :
<dependency>
<groupId>com.google.auth</groupId>
  <artifactId>google-auth-library-oauth2-http</artifactId>
  <version>0.18.0</version>
</dependency>

Comment: Thanks for the reply; I already tried that, to no avail. (the appengine was already there). I'm not using the oauth2 myself but when I deploy to the GAE and visit the link generated (https://xxxx-something.appspot.com) it throws the exceptions
Comment: Can you check this [Github repo](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/cloud-sql/postgres/servlet) and tell me if this helps you. Though, it's a Tomcat app, I don't think it's much of work to change it to Spring App?. It's a simple app that connect your Java App Engine to PostgreSQL instance.


Handling of Multiple http request in a single click

Question: I am new to angularJS. I used Angular directive for block UI and it works as expected. My Problem is between two template get loaded it actually call 3 backend service. This all service has to be sequential. so that in error scenario it just skip the step. As per block UI design it does show loading page but it shows that 3 times (basically it start/stop on each http calls). I tried using it their manual start / stop but it does not effective. Even by following their direction I must be doing something wrong in configuration. Sorry if its dumb question but I am new to angular js and learning this all new stuff.
Here it more detail about directive which I am using.
github link
My code:
<code> angular.module('myApp').controller('MyController', function($scope, blockUI) {

//A function called from user interface, which performs an async operation.
 $scope.onSave = function(item) {

    // Block the user interface
     blockUI.start();

    // Perform the async operation
     item.$save(function() {
               //service call 1 $http.post
                 if success then
                     //service call 2 $http.post
                     if success
                       //service call 3 $http.post
                     else
                       //error scenario
                 else
                    //error scenario
      // Unblock the user interface
       blockUI.stop();
    });
  };
});
</code>
Above code will show blockUI 3 times. as (3 http calls)…wanted to have treated 3 different calls as one call when blockUI executed.
Comment: Have a look at this thread http://stackoverflow.com/questions/18010796/return-interdependent-async-promises-in-routeprovider-resolve and this one http://stackoverflow.com/questions/16284403/chaining-ajax-calls-in-angularjs
Answer: Its always make me happy when I find out answer of my question. Here its answer which I used for my implementation. Hope this helps others.
<code> angular.module('myApp').controller('MyController', function($scope,      blockUI) {

//A function called from user interface, which performs an async      operation.
 $scope.onSave = function(item) {

// Block the user interface
 blockUI.start();

// Perform the async operation
 item.$save(function() {

           $timeout(function() {
            blockUI.message('Still loading ...');

           //service call 1 $http.post
             if success then{
                   $timeout(function() {
                   blockUI.message('Almost there ...');

                 //service call 2 $http.post
                 if success then{
                   $timeout(function() {
                   blockUI.message('Cleaning up ...');

                   //service call 3 $http.post
                   if success then
                       //process save
                   else{
                       //error scenario
                       // Unblock the user interface
                       blockUI.stop();
                   }
                    }, 3000);
                 }else{
                   //error scenario
                   // Unblock the user interface
                  blockUI.stop();
                 }
              }, 2000);
             }else{
                //error scenario
                // Unblock the user interface
                blockUI.stop();
             }
  }, 1000);

});
  };
});
</code>
This will take care about my question…it user blockUI for full 3 calls as single blockUI. Now message I can have it or not it up to individual choice.


My house's perimeter drain system is full of water, why might that be and how do I fix it?

Question: It's been raining light to medium for the past 12 hours and this morning while I was walking around outside the house, I noticed that this drain tube, which I believe runs around the perimeter of the house and into my sump pump, is full of water.

I walked around the house to the only other spot where there's one of these green caps, and that tube does not seem to be full of water. When I went to the basement and checked the sump, there is a steady trickle of water from the incoming corrugated drain tube.
Presumably, this means I have a clog somewhere? Or could it be something else?
Is this something I might be able to DIY, or since water around the foundation is a big deal, should I call a professional- who would that even be, a plumber? Landscaper?
Thanks!
Comment: Where does the drain empty out? It could be plugged sometimes pushing a garden hose down will help clear a blockage other times I have found the end of the drain full of roots and even on city systems that drain at the pavement through a curb just a small wad of grass /weed roots plugging the drain. At my current home our barn drains were backing up and flooding stalls because the tractor crushed the pipe on the low side of the barn about 30' away from the barn. Most of the time I find roots causing the backup.
Comment: I *think* it goes into my sump in the basement, but I only say that because the sump has two large corrugated ABS inlets and I presume these are the same corrugate abs pipes running around the house. But, to be honest, I'm not even sure exactly where this ABS runs, I only have access to three of these green caps pictured above. At least three of my gutters do drain into the corrugated drainage, so blockage is a real possibility. I'll try the garden hose trick.
Answer: I had a similar recurring issue after long heavy rains. The drain pipe would fill and take a long time to drain. Turned out the dirt under the pipe where the drain hole was would turn to mud and essentially act as a seal. I ended up digging the drain end up and putting some gravel underneath. Drain pipe never stays full too long anymore.


Remove event target

Question: I connect a script with the event handler when the output of the found data occurs. But after I look again for the data, the script connects again and the handler is hung a second time. How can this be avoided?
$(document).on("click", "a[data-action='create']", function (e) {
    e.preventDefault();
    newContactInput(this);
});

Comment: When do you want `newContactInput` to be callable? Only once ever for a particular element, or repeatedly *if there is no ongoing* `newContactInput`?
Comment: You can use `.one` instead of `.on` for event to occur only once
Comment: @CertainPerformance repeatedly if there is no ongoing newContactInput
Comment: @AnkitAgarwal but I will have two .one event handler
Comment: `newContactInput` is an asynchronous function, and you want to prevent the default action only when the async function is not in process? And you actually don't want to remove the element listening to the click event?
Answer: First ensure that newContactInput returns a Promise that resolves once it's completed. Then, on click, you can put the clicked element into a Set, and check that the element is not present in the Set before calling newContactInput. Once newContactInput resolves, remove the element from the set. For example:
const ongoingActions = new Set();
$(document).on("click", "a[data-action='create']", function (e) {
  e.preventDefault();
  // An action is still in progress for this element, return immediately:
  if (ongoingActions.has(this)) return;
  ongoingActions.add(this);
  newContactInput(this)
    .then(() => ongoingActions.delete(this));
});

Remove event target


Copying data to another column in Python/Pandas

Question: I have a ip packet as a CSV file that I'm trying to extract sequence numbers from info field to a separate column that only has the sequence numbers. Sequence numbers are substring in the middle of info string. So here is my raw code.. First I create a new column fo sequence numbers, then I check if Info field contains a Seq number, then I split the info field so I only get the sequence number out. If I print after 'Seq = j.split...', I do get the correct values. How do I write it to the CSV file Seq column?
file = pd.read_csv(file.csv)

file['Seq'] = None
for i in file['Info']:
    if 'Seq' in i:
        split = i.split(' ')
        for j in split:
            if 'Seq=' in j:
                Seq = j.split('Seq=',1)[1]
                file.loc[i,'Seq'] = int(Seq)

Example CSV:
No. Time        Source      Destination Protocol    Length  Info
1   0.000000    sourceip    192.168.0.1 TCP         54      35165 > 80 [SYN] Seq=0 Win=16384 Len=0
2   0.000001    sourceip    192.168.0.1 TCP         54      14378 > 80 [SYN] Seq=0 Win=16384 Len=0
3   0.000003    sourceip    192.168.0.1 TCP         54      31944 > 80 [SYN] Seq=0 Win=16384 Len=0

Desired outcome:
No. Time        Source      Destination Protocol    Length  Info                                   Seq
1   0.000000    sourceip    192.168.0.1 TCP         54      35165 > 80 [SYN] Seq=0 Win=16384 Len=0 0
2   0.000001    sourceip    192.168.0.1 TCP         54      14378 > 80 [SYN] Seq=0 Win=16384 Len=0 0
3   0.000003    sourceip    192.168.0.1 TCP         54      31944 > 80 [SYN] Seq=0 Win=16384 Len=0 0

Comment: From quick glance it seems ok. Did you try `file.to_csv`? Did you have any exceptions?
Comment: I did try that. No exceptions, I do have the the Seq column but every value is empty. At what point should I write the file? After all the for loops or inside the for loops? I'm really new to all this stuff..
Comment: You should write the file in the end. After you've extracted everything you wanted. piRSquared'd method below didn't extract any output? You might want to check that the file is read correctly. Try `print(file.head())` to see the first 10 rows that were extracted.
Comment: Actually the Seq values are there but they are after the other data, not on the same rows.
Comment: Do you use the same code as before? piRSquared's code (dropping the `astype(int)` or replacing it with `astype(float)`) will solve it. [Your current code can't work - `file.loc[i,'Seq']` will raise an exception, as `i` is not in the index]
Answer: Use str.extract
file['Seq'] = file.Info.str.extract('Seq=(\d+)', expand=False).astype(float)

Comment: This should replace all the code below `read_csv` in the question
Comment: Even if there might not be a Seq value at all? I tried this and got ValueError: cannot convert float NaN to integer.
Comment: What do you want there to be in the event that `'Seq'` is not there?
Comment: Just empty value


AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

Question: I am working on Yolo3-4-PY to implement it with Tkinter.
I've looked everywhere but have not been able to resolve the issue.
When I run the program, the canvas is displayed, but when I click on Start Video(**btton**), I get the following error:
Loading weights from weights/yolov3.weights...Done!
/usr/local/lib/python3.5/dist-packages/PIL/ImageTk.py:119: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  if mode not in ["1", "L", "RGB", "RGBA"]:

    Exception in Tkinter callback
    Traceback (most recent call last):
    File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
    File "webcam_demo.py", line 13, in start_video
    show_frame()
    File "webcam_demo.py", line 39, in show_frame
    imgtk = ImageTk.PhotoImage(image=cv2image)
    File "/usr/local/lib/python3.5/dist-packages/PIL/ImageTk.py", line 120, in
    __init__
    mode = Image.getmodebase(mode)
    File "/usr/local/lib/python3.5/dist-packages/PIL/Image.py", line 313, in
    getmodebase
    return ImageMode.getmode(mode).basemode
    File "/usr/local/lib/python3.5/dist-packages/PIL/ImageMode.py", line 55, in
    getmode
    return _modes[mode]
    TypeError: unhashable type: 'numpy.ndarray'
    Exception ignored in: <bound method PhotoImage.__del__ of
    <PIL.ImageTk.PhotoImage object at 0x7f4b73f455c0>>
    Traceback (most recent call last):
    File "/usr/local/lib/python3.5/dist-packages/PIL/ImageTk.py", line 130, in
    __del__    name = self.__photo.name
    AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

Comment: In my case, I got this error when Python could not find the image file at the path I had put. I corrected the path and it started working.
Answer: in my case , correct with just simply add this line
root = tkinter.Tk()

complete code :
root = tkinter.Tk()
image = PIL.Image.open(r"C:\Users\Hamid\Desktop\asdasd\2.jpeg")
img = ImageTk.PhotoImage(image)
l = Label(image=img)
l.pack()

Comment: This worked for me, too. What was specifically happening for me was that, because a root `Tk()` instance couldn't be found, this exception was being raised: `RuntimeError(f"Too early to {what}: no default root window")`, which seems to be raised whenever one tries to initialize a `PhotoImage` object without having a `Tk()` instance.
Comment: Same problem here. Good solution!
Answer: Issue
In the line  imgtk = ImageTk.PhotoImage(image=cv2image), you are passing a numpy array (cv2image) as input to ImageTk.PhotoImage. But the source code of PIL.ImageTk mentions that it requires a PIL image.
This is what source code of PIL.ImageTk mentions for init() of PhotoImage.
class PhotoImage(object):
    .....
    :param image: Either a PIL image, or a mode string.  If a mode string is
              used, a size must also be given.

Solution
So basically, you will have to convert the numpy array to a PIL Image and then pass it to ImageTk.PhotoImage().
So, can you replace the line imgtk = ImageTk.PhotoImage(image=cv2image) with imgtk = ImageTk.PhotoImage(image=PIL.Image.fromarray(cv2image))?
This would convert the numpy array to a PIL Image and it would be passed into the method.
References
I extracted the code for converting a numpy array to PIL Image from this source.
Answer: Interesting.... there's apparently a nasty side-effect in Tkinter which can cause this.
Note (from hamidjahandideh's answer ) that it matters that you create your root window BEFORE cresting the ImageTk.
ie. this fails with AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
im_numpy = cv2.imread(ResourcePhotos.BLUE_PERSON_TRAIL_PHOTO)[:, :, ::-1].copy()  # Load BGR Image
im_pil = Image.fromarray(im_numpy)
imagetk = ImageTk.PhotoImage(im_pil)
window = tk.Tk()  # This line must come BEFORE crearting ImageTk
tk.Label(window, image=imagetk).pack()
window.mainloop()

But this works:
im_numpy = cv2.imread(ResourcePhotos.BLUE_PERSON_TRAIL_PHOTO)[:, :, ::-1].copy()  # Load BGR Image
im_pil = Image.fromarray(im_numpy)
window = tk.Tk()  # This line must come BEFORE creating ImageTk
imagetk = ImageTk.PhotoImage(im_pil)
tk.Label(window, image=imagetk).pack()
window.mainloop()

Answer: when you place the image variable in the label , you must initiate the image variable to "image".
Eg: (CORRECT APPROACH)
photo = PhotoImage(file = "C://Users//Carl//Downloads//download.png")
label1 = Label(image = photo)
label1.pack()

Eg : (WRONG APPROACH)
photo = PhotoImage(file = "C://Users//Carl//Downloads//download.png")
label1 = Label(photo)
label1.pack()


Who created the Mac Mickey pointer cursor?

Question:
I just found out why the mouse cursor is slightly tilted*, and asked myself why the pointer cursor is a little Mickey hand. Do you guys know why is it like this and who invented it?
Related Question: Why is the mouse cursor slightly tilted and not straight?
Comment: I think the original question is more focused on why it's a "Mickey Mouse" hand and not just a hand icon. Do a Google image search for Mickey Mouse hand. You'll see it was mostly drawn with the 3 lines as well.
Comment: *Mickey hand*? Your mouse cursor has only four fingers?
Comment: lol

I think it's only on Mac.
Comment: It is not a Mac-only thing.
Comment: The original question did not state anything about the mickey mouse hand.
Answer: The correct answer is Walt Disney, but tangentially. The Mickey Mouse watch famously used Mickey's hands as clock hands, which seems to be the earliest example I can find of using Mickey's hand as a pointer:

Image source unknown
As far as I can tell, the pointing hand cursor originated as a PC cursor in HyperCard as mentioned in Bart's answer, and was adopted for use on the web pretty much right from the beginning as noted by Mark Griffiths:

HyperCard was a big influence on some of Tim Berners-Lee's team at Cern, and many of the hypermedia conventions it established were carried through into Mosaic.

I'm struggling to corroborate that claim. He goes on to say:

Had the pointing-hand cursor never existed then a whole bunch of design assumptions might not have been transferred from HyperCard's 'link' to HTML's  and we might have preempted the many years of work done to sort out web accessibility for machines and the full spectrum of human beings.

The open/grabbing hand cursor, though, is much older, and was designed by Susan Kare (who did most of the icons for the original Mac). MacPaint (on the original 1984 Macintosh) used it as the "pan" icon:

That icon was tweaked slightly over the course of classic System/MacOS to add things like a countdown waiting animation:
]
Image credit: Bjørn Sortland, Ka of Isis
Old point-and-click adventure games also used hand icons quite a lot, often richly-designed gloved ones, which starts to hint at that direction. Final Fantasy is a famous example. It would seem likely to me that there's an old point-and-click adventure game somewhere—possibly even a Mickey Mouse themed one—that used a cartoon glove like this well before it became part of the OS, but I couldn't find any explicit examples (it's not a genre I am particularly knowledgeable about).
As far as I can tell, it was the pointer icon that first got the Mickey Mouse darts in the back on a computer, which happened on the Macintosh system software some time before Mac OS 9 (sadly I can't seem to find a more specific example than this, but it wouldn't have been much before that since the pointing icon was only made a system icon in Mac OS 8.5. That coincides with the launch of the Platinum UI in Mac OS 8.5, which was all about richer bitmap graphics throughout the OS):

Image credit: Nonme85851, DeviantART
The icons were brought into line at some point, but it's not clear when:

Image credit: Offscreen Graphics Worlds, Pictures, Cursors, and Icons Chapter 13 (PDF link)
It seems that the stylised hand icon was reverted to the original Susan Kare version in OS X all the way until Mac OS X 10.7.3 (when the two cursors were redrawn for Retina displays and brought into line stylistically):

Image credit: Marc Edwards, Twitter
I had a look at the metadata for those cursors in OS X and they don't seem to have any author credit specified (but it does say they were being worked on in Adobe Illustrator CS4 from the 17th of April 2008 at least until the 15th of September, 2011).
Comment: Hyper card really invented the 'stack' concept with linking.  It's probably not coincidental that the WWW protocol is called "HYPERTEXT transfer protocol" HTTP:
Comment: Hypertext predates hyper card by a *long* way. The [Memex](https://en.wikipedia.org/wiki/Memex) is from the 40s!
Comment: Thanks ! I hadn't realised that there is a long history to HyperText https://en.wikipedia.org/wiki/Hypertext#History
Answer: According to this article in wikipedia it was first used in HyperCard

As to why it is used... well, why not? What could be more natural than the index finger to point at something?
Comment: Ah Hypercard, that gives me a fuzzy warm feeling! Could have sworn it was used elsewhere than Hypercard, maybe not though, will have to dig out some old Mac stuff and check Resource files!
Comment: That's not the same cursor though. The HC cursor (minus its shadow) is what browsers (even the early IE for Mac) used for links. When Apple added a system-provided cursor (with OS 7.6's Appearance Manager) it was like this, I think. Though an earlier version might have even been the classic "counting hand" cursor like Installer used it.
Answer: I'm guessing here, but one advantage of the white glove, with the three lines to indicate that it is a glove, is that it doesn't prefer one skin color over another. This way, users of all types of skin colors wouldn't be immediately off put by, say, a caucasian ungloved hand.
Also, in the early 90s, the computer companies had to make home computing easy - that is, something a complete novice would not be afraid of spending $5000 on. Using a gloved hand was another way of making it seem like a butler or assistant was doing the work for you. Kinda like how Ask Jeeves worked. Or At Ease - if you can even remember that far back, lol.
Comment: I don't think there's any evidence for the 'skin tone' argument at all.


C bulk write multiple values at once

Question: I am trying to write a bunch of values to a FIFO pipe - which works fine, but the issue that I have is that the program on the other end of the FIFO pipe, ends up reading the values before all are written (I assume kernel scheduling isn't working in my favor). Below is what my code is somewhat like (this works well - half of the time):
write(out_fd, (void *)struct_1, sizeof(struct part_1));
write(out_fd, (void *)struct_2, sizeof(struct part_2));
write(out_fd, (void *)struct_3, sizeof(struct part_3));

However - what I assume is that - kernel scheduling essentially interrupts somewhere in-between the sequential writes, whilst on the other end of the FIFO pipe, another program reads all values as they come in, and when it does not match the expected full (multiple) values being written - at once, my programs fails to operate correctly, as the values do not match the format what is expected.
Does anyone have any ideas into how all write's can be written in bulk, such as preventing scheduling from switching between applications before all write's can be done. My initial attempt was to malloc enough space for all of the values, then to memcpy the values towards a respective offset - matching each interval position - and then writing that; however, this ended up causes heap memory corruption (after freeing all), which only became present further down the line.
Any suggestions? Thank you.
Comment: that is not code.  Please post a [mcve].  thanks
Comment: "at once, my programs fails to operate correctly" Doesn't `read` block on the pipe until the requested data is available? In any case, this is a bug in your reader program. You should be able to tolerate delays in data availability, such as when the system is under high load.
Comment: @Alexander it does not block as this is an asynchronous communication between the programs, and the `O_NONBLOCK` flag is set on the FIFO pipe.
Answer: A FIFO is just a stream of bytes; it provides no framing of any kind. In particular, there is no guarantee that read() will read the same chunks that write() wrote. Fix your receiver to handle this.

C bulk write multiple values at once


Get SQL Distinct Row Without NULL Values

Question: I'm trying to get a distinct row using SQL from set of records that have matching key/id value, but NULLs in different columns. Hard to explain so please see screenshot. Any ideas?

create temporary table my_table (
    id varchar(30), segmentdate1 date, converted1 varchar(10), segmentdate2 date, converted2 varchar(10)
);

insert into my_table (
    id, segmentdate1, converted1, segmentdate2, converted2
)
values
    ('Michael','9/15/2020','No',NULL,NULL),
    ('Michael',NULL,NULL,'7/1/2019','Yes')
;

Comment: Hi, when you are doing the select, do you do it like this : select distinct id, segmentdate, converted,... from your_table ? If yes, then you will get the result as you are getting. The distinct keyword is applying to all the columns. Can you share with us a query you are trying to execute ? Thanks!
Comment: Is this from a single table?  Or instead are you showing us the output from a join?
Comment: I've tried distinct and group by and neither work. And, this is a result from a more complex query, but I wanted to keep it simple
Comment: From a single table?
Answer: You seem to want aggregation:
select id, max(segmentdate1) as segmentdate1, max(converted1) as converted1,
       max(segmentdate2) as segmentdate2, max(converted2) as converted2
from t
group by id;

Note:  I made up names for the columns so they are unique.
This is probably a result set created from another query.  That query probably has the wrong group by keys.  You should probably fix that query.
Answer: declare @my_table table (
    id varchar(30), segmentdate1 date, converted1 varchar(10), segmentdate2 date, converted2 varchar(10)
);

insert into @my_table (
    id, segmentdate1, converted1, segmentdate2, converted2
)
values
    ('Michael','9/15/2020','No',NULL,NULL),
    ('Michael',NULL,NULL,'7/1/2019','Yes')
;

select id,max(isnull(segmentdate1,'1200-01-01')) segmentdate2
    ,max(isnull(converted1,'')) converted1, max(isnull(segmentdate2,'1200-01-01')) segmentdate2
    ,max(isnull(converted2,'')) converted2
from @my_table
group by id


jQuery mouse position

Question: I have a problem, with jquery's mouseover. I have an image with a map. When I hover the mouse on specific areas, a div should pop up at the position of the mouse, instead the div pops up at a position according to the scrolling height of the page.
This is when everything goes right.
And the next image shows what happens when I scroll a bit higher.

The hovered area is the same, but the div is not at the right place. The code I made is the following:
$(document).ready(function(){
               $('area').mouseover(function(e){
                   var x = e.clientX;
                   var y = e.clientY;
                   var id = $(this).attr("id");
                   $("div#map-popup-"+id).css({position: "absolute", top: y, left: x});
                   $("div#map-popup-"+id).show();
                   $(this).mouseleave(function(){
                       $("div#map-popup-"+id).hide();
                   });
               });
        });

I have never worked with maps and areas before, so I don't know what could be messed up. I got a plain html from web archive and I need to restore the site in wordpress. Here is an area from the html code:

<map id="chambers-map" name="chambers-map">
    <area id="ulm" shape="circle" coords="85,160,10" href="#" alt="" />
    <area id="passau" shape="circle" coords="232,136,10" href="#" alt="" />

So my question is: why does this happen and how can I fix it? Thanks in advance!
Answer: The mouse cursor's position is based upon it's X and Y co-ordinates on the page. You're looking for pageX and pageY: http://api.jquery.com/event.pagex/
So you're probably wanting to position: fixed; the element based upon the e.pageX and e.pageY
Answer: You want the positioning of pop-up to be relative to your viewport and not to the parent element. Hence use position as 'fixed' instead of 'absolute'.

jQuery mouse position


Polynomial subalgebras

Question: Let $K$ be a field and $A$ a finitely generated $K$-algebra such that
$\bullet\ A$ is a domain (i.e. zero is the only zero divisor, and $A$ is not the zero $K$-algebra),
$\bullet$ the units of $A$ are in $K$.

Is there necessarily an injective morphism $A\to K[x_1,\ldots,x_n]$, where $n$ is a nonnegative integer and the $x_i$ are indeterminates?

[In this post "$K$-algebra" means "commutative $K$-algebra with one".]
Comment: Not in general. The simplest example would be to take an abelian variety and remove an ample irreducible divisor. The coordinate ring of the affine open subset has both the properties you mention but any map to a polynomial ring will have image just $K$.
Comment: @Pierre-YvesGaillard What about this example: $A=\mathbb C[X,Y]/(Y^2-X^3+X)$? From Theorem 1 in the paper "A note on finite dimensional subrings of polynomial rings" of P. Eakin we learn that integrally closed affine domains are polynomial subalgebras only when they are simple, that is, generated by a single element. In the above example this is not possible (why?).
Comment: The chosen example is more "famous" and some of its important properties can be found in Hartshorne, but I think the other one is also fine.
Comment: @user26857 - I've just posted an edit to the answer.
Comment: Is $A$ assumed to be commutative?
Comment: @Berci - Yes. (See the last line.)
Comment: (ok, anyways commutativity would follow from the morphism being injective)
Comment: @Mohan - Thanks!!! Sadly, I don't have the background needed to understand your comment. Of course I have no doubt that you are right. I'd be most grateful if you turned your comment into an answer. If you don't feel like doing it, I'm planning to post your comment as a community wiki answer. In any case I'd like to wait a little bit before accepting an answer, to see if somebody finds a more elementary example.
Comment: @user26857 - Thanks a lot! This is just to tell you that I'm working on your comment. (I don't think I'll be able to see why your example works without your help, but I'll try to go as far as possible by myself.) I suppose you chose the polynomial $X^3-X$ because $X^2-X$ (for instance) wouldn't work...
Answer: The question was answered by Mohan in a comment. Here is a copy-and-paste:

Not in general. The simplest example would be to take an abelian variety and remove an ample irreducible divisor. The coordinate ring of the affine open subset has both the properties you mention but any map to a polynomial ring will have image just $K$.

(As I said in a comment, I don't know enough algebraic geometry to understand this example, but I trust Mohan.)
EDIT. In a comment user26857 gave a hint for an explicit example. Here is an attempt to follow this hint. (user26857 is not responsible for the possible errors in this edit.)
Let $K$ be a field of characteristic $\ne2$, let $X$ and $Y$ be indeterminates, and set
$$
A:=K[X,Y]/(Y^2-X^3+X)=K[x,y],
$$
where $x$ and $y$ are the images of $X$ and $Y$, so that we have
$$
y^2=x^3-x=x(x-1)(x+1)
$$
and $K[x]\simeq K[X]$.
Claim 1
(1a) $A$ is a Dedekind domain (in particular the Krull dimension of $A$ is one),
(1b) the units of $A$ are in $K$,
(1c) $A$ is not a unique factorization domain (more precisely, the elements $x,x-1,x+1$ and $y$ are irreducible).
In view of Theorem 1 in
Eakin P. A note on finite dimensional subrings of polynomial rings. Proceedings of the American Mathematical Society. 1972;31(1):75-80, Google Scholar link,
this will imply that $A$ is not a subalgebra of a polynomial algebra over $K$.
Claim 2 $A$ is the integral closure of $K[x]$ in $K(x,y)$.
This will imply (1a).
It is clear that $A$ is integral over $K[x]$. Let us prove the converse, namely that any element of $K(x,y)$ which is integral over $K[x]$ is in $A$.
Let $u$ be in $K(x,y)$. Then $u=u_1+yu_2$ with $u_i\in K(x)$, and this expression is unique.
In this notation, set $\overline u:=u_1-yu_2$. Then $u\mapsto\overline u$ is an order two automorphism of $K(x,y)$ whose fixed field is $K(x)$.
Let $u=u_1+yu_2\in K(x,y)$ be integral over $K[x]$. We must show $u_i\in K[x]$.
As $u_1=(u+\overline u)/2$ is integral over $K[x]$, which is an integrally closed domain, we have $u_1\in K[x]$.
As $u\overline u=u_1^2-(x^3-x)u_2^2$, the above argument shows $(x^3-x)u_2^2\in K[x]$. Since $x^3-x$ is square free, this implies $u_2\in K[x]$.
This proves Claim 2, and thus (1a).
Define $N:A\to K[x]$ by $N(a):=a\overline a=a_1^2-(x^3-x)a_2^2$. (Recall that $a_i\in K[x]$.) Then $N$ is a morphism of multiplicative monoids.
If $a$ is a unit of $A$ then $N(a)$ is a nonzero constant. This is easily seen to imply (look at the degree of $N(a)$) that $a$ is itself a constant. This proves (1b).
Finally, to prove (1c) it suffices to observe that if $0\ne a\in A$ is not a unit, then the degree of $N(a)$ is at least two, so that, if $a\ne0$ is the product of two non-units, then the degree of $N(a)$ is at least four.
Comment: As @user26857 has mentioned, the simplest abelian variety is an elliptic curve and the ring he wrote above corresponds to an affine open set of one such.

Polynomial subalgebras


How to extend storage space on VPS (LVM) 9GB to 40GB

Question: My VM came with a 9GB setup but a 60GB drive. I'm trying to extend it to it's full size. I have to do this on several servers. I tried to follow a guide else where but when creating a new partition I got this msg.

If you want to create more than four partitions, you must replace a
  primary partition with an extended partition first.

Here is some info you might find handy to help.
root@ubuntu:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            2.0G  4.0K  2.0G   1% /dev
tmpfs           396M  584K  395M   1% /run
/dev/dm-0        57G  3.0G   52G   6% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
none            5.0M     0  5.0M   0% /run/lock
none            2.0G     0  2.0G   0% /run/shm
none            100M     0  100M   0% /run/user
/dev/sda1       134M   68M   57M  55% /boot

root@ubuntu:~# fdisk -l

Disk /dev/sda: 62.9 GB, 62914560000 bytes
64 heads, 32 sectors/track, 60000 cylinders, total 122880000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00096132

Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      292863      145408   83  Linux
/dev/sda2          292864     2246655      976896   82  Linux swap / Solaris
/dev/sda3         2246656    20969471     9361408   8e  Linux LVM
/dev/sda4        20969472   122879999    50955264   8e  Linux LVM

Disk /dev/mapper/CAC_VG-CAC_LV: 61.8 GB, 61761126400 bytes
255 heads, 63 sectors/track, 7508 cylinders, total 120627200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/CAC_VG-CAC_LV doesn't contain a valid partition table`

Any help would be greatly appreciated. If you need additional info feel free to ask. I will be watching all morning.
Thanks
Edit- I'm actually thinking that script I ran earlier worked and did extend the drives, but one server has that partition error and the other doesn't.
Edit - Fstab output
root@ubuntu:~# cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/dev/mapper/CAC_VG-CAC_LV /               ext4    errors=remount-ro 0      1
# /boot was on /dev/sda1 during installation
UUID=1d92b194-7885-4b25-a4ba-a7b8683229e1 /boot           ext4  defaults 0 2
# swap was on /dev/sda2 during installation
UUID=be7625e5-2e2c-41f2-8d5f-331f90980b9e none            swap    sw  0 0
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0

pvdisplay and vgdisplay
root@ubuntu:~# vgdisplay
  --- Volume group ---
  VG Name               CAC_VG
  System ID
  Format                lvm2
  Metadata Areas        2
  Metadata Sequence No  7
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                1
  Open LV               1
  Max PV                0
  Cur PV                2
  Act PV                2
  VG Size               57.52 GiB
  PE Size               4.00 MiB
  Total PE              14725
  Alloc PE / Size       14725 / 57.52 GiB
  Free  PE / Size       0 / 0
  VG UUID               A4SRwW-Vqpz-qRLf-iXIm-yKny-tcyI-wYTMdg

root@ubuntu:~# pvdisplay
  --- Physical volume ---
  PV Name               /dev/sda3
  VG Name               CAC_VG
  PV Size               8.93 GiB / not usable 2.00 MiB
  Allocatable           yes (but full)
  PE Size               4.00 MiB
  Total PE              2285
  Free PE               0
  Allocated PE          2285
  PV UUID               al3A0j-NEpg-yjRd-2yzF-pMUm-fa42-XdcZmc

  --- Physical volume ---
  PV Name               /dev/sda4
  VG Name               CAC_VG
  PV Size               48.59 GiB / not usable 1.00 MiB
  Allocatable           yes (but full)
  PE Size               4.00 MiB
  Total PE              12440
  Free PE               0
  Allocated PE          12440
  PV UUID               phIhtw-wze3-IOTU-oiik-586P-ecJP-5KY913

Edit- Output of script cloud host said to run
root@ubuntu:~# sh zang.sh
Error: Can't create any more partitions.
Error: Partition doesn't exist.
partition: none, disk: /dev/sda, lower: 0, upper: 0
/dev/sda: partition table type 'dos' detected
partx: /dev/sda: adding partition #1 failed: Device or resource busy
partx: /dev/sda: adding partition #2 failed: Device or resource busy
partx: /dev/sda: adding partition #3 failed: Device or resource busy
partx: /dev/sda: adding partition #4 failed: Device or resource busy
partx: /dev/sda: error adding partitions 1-4
  Device /dev/sda5 not found (or ignored by filtering).
  Device /dev/sda5 not found (or ignored by filtering).
  Unable to add physical volume '/dev/sda5' to volume group 'CAC_VG'.
  New size (9725 extents) matches existing size (9725 extents)
  Run `lvextend --help' for more information.
resize2fs 1.42.9 (4-Feb-2014)
The filesystem is already 9958400 blocks long.  Nothing to do!

As you can see it looks like it doesn't work but when logging in I go from this
Usage of /:  13.1% of 8.66GB   to    Usage of /:   3.1% of 37.27GB

Thanks once again for your help.
Answer: The procedure is rather easy and it should even work on a running system.  Keep the word "should" in mind.  Normally, the procedure is as following:

Start off with resizing the LVM you need to resize:  sudo lvresize -l 100%FREE /dev/vg00/myvolume  This tells LVM to use up all free space to enlarge the volume /dev/vg00/myvolume
Now you need to resize the filesystem contained within: sudo resize2fs /dev/vg00/myvolume  It should detect that you have the disk mounted any then use it's online resizing mode.

That's it... You're done.
Did I tell you to backup your data before doing all that?  Here you go: backup your data before doing this.
Note that your output says something about a volume being about 61.8GB.  The output of both lvdisplay, vgdisplay and the contents of  /etc/fstab might give additional information regarding your system.  I'm also not very certain why you have two LVM marked partitions.  Did you create those?
Comment: No they all come with the VM upon creating it. My other servers all look similar.
Comment: Can you give me the output of `sudo pvdisplay` and `sudo vgdisplay`?
Comment: I added it to the post
Comment: I'm pretty sure after looking over all this the script I ran before I made this post worked. I do believe the drive has been extended now. I don't know what I get that partition error though.
Comment: Thanks for the update... I just noticed something.  In your fstab, it says that your root filesystem is `/dev/mapper/CAC_VG-CAC_LV` (this translates to `/dev/md0`, which you can check by issuinging `ls -la /dev/mapper/CAC_VG-CAC_LV`.   Furthermore, if you look at your   `df -h` command, your root partition is ...  `/dev/dm-0        57G  3.0G   52G   6% / `.  That means you already have your 60G mounted as root.  Those "missing" 3G, are the /boot and the swap parition.  I would conclude it is all in order.
Comment: Yes, it look absolutely as if it worked fine.
Comment: The partition error is normal.  `fdisk` thinks it is a block device like a normal disk, and as such it tries to read the partition table of that disk.  However, it is **not** a normal disk, but a volume containing a filesystem.  Due to this, there is no partition table it can read.  It issues an error, but the error is irrelevant.  You can safely ignore such errors on LVM volumes.
Comment: Just a little word on the two LVM partitions.  They are the physical disks (`/dev/sda3` and `/dev/sda4`) that together form the volume called `CAC_VG`.  You can see that the size of `/dev/sda3` and `/dev/sda4` (as seen in the `pvdisplay`output)  add up to the size of `CAC_VG` (as seen in the `lvdisplay` output).  No idea why exactly they chose to do it that way.
Comment: Well I really appreciate your help. I think the servers needed rebooted or something for it to appear or most likely I was doing it wrong. I don't understand linux file systems much. I was worried I was going to do permanent damage. I'm trying the script on one last server to see if it works.
Comment: You're welcome.  Normally a reboot should not be required to do this.
Comment: It wasn't required, but the only way I could see the space was to log in and log out because of my lack of Linux skills.... Check the update at the bottom of my questions to see what I mean. I also added the output of that script so you can see why I freaked out and made this question.
Comment: I can understand the confusion.  Well it works now. Off to new adventures! ;-)


Do speed boosts only apply when at full health?

Question: Or possibly, is there some other relationship between health and speed? I ask because I have some passive speed boosts: Windborne Dagger (elementalist trait passive +15% speed) and Signet of Air (+10% speed), and anytime I get damaged, I immediately slow down quite noticeably. It's a problem when I'm trying to just run through mobs without stopping to kill them. It's not like I'm crippled, I have no conditions and it happens with any enemy. The slowdown isn't as severe as a cripple or chill either. My speed comes back up when I heal. So it really feels like my passive boosts are simply ignored when I'm not at full health.
Am I correct? More importantly, is it a feature, or a bug?
Answer: Speed boosts still apply when you're under full health, however, you're noticing a slowdown because you've entered combat mode.
Your forward running speed when not in combat is 300~ units per second. However, this slows down to 210~ units per second when you've entered combat. So the relationship here is not between your amount of health, but rather, the fact that you have entered combat mode. This decrease will also stack with other movement speed debuffs (like Chilled), though it is the only one that does so.
For the record, strafing speed is 180~ units per second, while moving backward is 105~ units per second.
Source
Comment: And dodging forward is the same speed as withswiftness while not in combat.
Comment: Additional note: Swiftness doesn't apply a speed boost when strafing.


How to buffer events with Rx extentions for JS

Question: I wan't to get text change events from input but limit them to 3 per second.
Rx support my wish? how can I achieve this ability?
Answer: Assuming you already have the Observeable, insert a call to throttle(333) before you consume should do the trick. (333= miliseconds which is 1000/3 which gives you 3 chars per second).
a very simple sample:
<code> $(document).ready(function () {
   var mainCanvas = $("#TextBox1");
   var observable = Rx.Observable.FromHtmlEvent(mainCanvas.context, "keypress");

   var throttle = observable.throttle(333);

   throttle.subscribe(function (next) {
         $('div#test').append(String.fromCharCode( next.charCode));
        }
   );
 });
</code>


Can't get RTL8153 Gigabit Ethernet Adapter USB 3.0 working on Ubuntu 20.04

Question: I am striving to get a RTL8153 working.
I can see it as a USB:
<code>~$ lsusb
Bus 002 Device 005: ID 0bda:8153 Realtek Semiconductor Corp. RTL8153 Gigabit Ethernet Adapter
Bus 002 Device 004: ID 2109:0817 VIA Labs, Inc. USB3.0 Hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 008: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 006: ID 13d3:56a2 IMC Networks USB2.0 HD UVC WebCam
Bus 001 Device 004: ID 13fe:6300 Kingston Technology Company Inc. Silicon-Power16G
Bus 001 Device 007: ID 05ac:0250 Apple, Inc. Aluminium Keyboard (ISO)
Bus 001 Device 005: ID 046d:c542 Logitech, Inc.
Bus 001 Device 003: ID 05ac:1006 Apple, Inc. Hub in Aluminum Keyboard
Bus 001 Device 010: ID 2109:2817 VIA Labs, Inc. USB2.0 Hub
Bus 001 Device 009: ID 8087:0026 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
</code>
I can see the module is loaded, but not used:
<code>~$ lsmod | grep r8152
r8152                  77824  0
mii                    20480  1 r8152
</code>
I can see the hardware listed:
<code>~$ lshw -class network
  *-network
       description: Ethernet interface
       physical id: 3
       bus info: usb@2:3.3
       logical name: enx4ce173421ae9
       serial: 4c:e1:73:42:1a:e9
       size: 10Mbit/s
       capacity: 1Gbit/s
       capabilities: ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8152 driverversion=v1.11.11 duplex=half firmware=rtl8153b-2 v1 10/23/19 link=no multicast=yes port=MII speed=10Mbit/s
</code>
I can see the interface configuration:
<code>~$ ifconfig
enx4ce173421ae9: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 4c:e1:73:42:1a:e9  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code>
I can't bring the interface up:
<code>~$ sudo ip link set enx4ce173421ae9 up
menks@vivo:~$ ip -br -c link show
lo               UNKNOWN        00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
wlo1             UP             bc:17:b8:14:53:bb <BROADCAST,MULTICAST,UP,LOWER_UP>
enx4ce173421ae9  DOWN           4c:e1:73:42:1a:e9 <NO-CARRIER,BROADCAST,MULTICAST,UP>
</code>
I can see that it is missconfigured:
<code>$ resolvectl status
Link 4 (enx4ce173421ae9)
      Current Scopes: none
DefaultRoute setting: no
       LLMNR setting: yes
MulticastDNS setting: no
  DNSOverTLS setting: no
      DNSSEC setting: no
    DNSSEC supported: no
</code>
Any clue about how to configure it?
Answer: From the comments...
It looks like the interface is coming up at only 10Mbit/s, which might indicate a cabling problem, or a problem with a hub/switch/router. Are you using cat 5e or cat 6 cables?
Update #1: replacing the ethernet cable fixed the problem.


Unable to insert data in table using form to submit data

Question: I am unable to insert data in user_preferences table where as I am getting all the attributes in params. I tried inserting value from console by following way since association between User has_one user_preference and UserPreference belongs_to User:
user = User.find(1)
user.user_preferences.title = "MyTitle"

I am getting undefined method "title"
user_preference.rb
class UserPreference < ActiveRecord::Base
    belongs_to :user

    def self.bgcolor_options
      [["Orange", "#FF3300"], ["Green", "#00FF00"], ["Blue", "#0000FF"], ["Pink", "#FF0066"], ["Yellow", "#FFFF00"], ["White", "#FFFFFF"]]
    end
    def self.font_options
        [["Times New Roman", "Times New Roman"], ["Verdana", "Verdana"],["Arial", "Arial"],["sans-serif", "sans-serif"]]
    end
end

user_preferences_controller.rb
class UserPreferencesController < ApplicationController
    def new
        @user_preference = UserPreference.new
    end

    def create
        @user_preference = UserPreference.new(user_pref_params)
        @user_preference.save unless user_signed_in?
        render 'user_preferences/new'
    end
    def edit
    end
    def update
    end

    private
    def user_pref_params
        params.require(:user_preference).permit(:title, :bgcolor, :font, :description)
    end
end

routes.rb
Rails.application.routes.draw do

  resources :user_preferences
  post "/user_preferences/new"
  devise_for :users
  devise_scope :user do
    authenticated :user do
      root :to => 'user_preferences#new', as: :authenticated_root
    end
    unauthenticated :user do
      root :to => 'devise/registrations#new', as: :unauthenticated_root
    end
  end

user_preferences/new.html.erb
<%= form_for @user_preference, :url => { :action => "create" }  do |u|%>

    <%= u.label :title %>

    <%= u.text_field :title %>

    <%= u.label :description %>

    <%= u.text_field :description %>

 <%= u.label :back_ground_color %>

    <%= u.select :bgcolor, options_for_select(UserPreference.bgcolor_options) %>

    <%= u.label :font %>

    <%= u.select :font, options_for_select(UserPreference.font_options) %>

    <%= u.submit %>

    This is the changes made in background

<% end %>

schema.rb
ActiveRecord::Schema.define(version: 20150422034042) do

  create_table "user_preferences", force: :cascade do |t|
    t.text     "title"
    t.string   "font"
    t.text     "description"
    t.string   "bgcolor"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

Adding User.rb code
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  has_one :user_preference
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

Answer: You're accessing the wrong association on user:
user.user_preferences.title = "MyTitle"

user_preferences is a has_many association, and returns multiple objects. The error itself also mentions this (something like ActiveRecord_Associations_CollectionProxy).
Simply access the has_one association and it will work:
user.user_preference.title = "MyTitle"

Comment: Sorry, but I didn't get your point, how user_preferences is a has_many association
Comment: Right now I'm guessing `has_many :user_preferences` (plural) is also defined in your `User` class, as well as the `has_one :user_preferences` (singular). If this is not the case, post the code from your `User` model too, then I can help you better.
Comment: I added the User model
Comment: In Rails, has_many associations have plural names (`user_preferences`) whereas has_one associations have singular names (`user_preference`). Judging by the code you posted (`user.preferences.title`) you initially had a has_many association which you were accessing. You can find more information about associations in the [Rails documentation](http://guides.rubyonrails.org/association_basics.html#the-has-one-association).
Comment: leave apart setting the value from console but through form it has to save my attribute in database, so where I am doing mistake in code
Comment: Are you still getting the `NoMethodError` error or is it just not saving the value in the database? If you're having a different problem now, please ask a new question.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75945/discussion-between-cyborg-and-fivedigit).
Answer: for the console part its not a javascript if you want to set to relation you have to use a variabel to assign, and not to use user_preference(s) note the s and its has_one relation and it should be user_preference and in your User Model it should be
# User Model
has_one :user_preference

# Console
user = User.first
preferences = user.user_preference
preferences.title = "MyTitle"
preferences.save
user.reload.preferences.title  # should be "MyTitle"


unable to create a thread in python

Question: I have following code which compares user input
import thread,sys
if(username.get_text() == 'xyz' and password.get_text()== '123' ):
   thread.start_new_thread(run,())

def run():
  print "running client"
  start = datetime.now().second
  while True:
    try:
        host ='localhost'
        port = 5010
        time = abs(datetime.now().second-start)
        time = str(time)
        print time
        client = socket.socket()
        client.connect((host,port))
        client.send(time)
    except socket.error:
        pass

If I just call the function run() it works but when I try to create a thread to run this function, for some reason the thread is not created and run() function is not executed I am unable to find any error..
Thanks in advance...
Comment: Can you provide a minimal running example? This code won't run because the names `username` and `password` aren't defined.
Answer: you really should use the threading module instead of thread.
what else are you doing? if you create a thread like this, then the interpreter will exit no matter if the thread is still running or not
for example:
import thread
import time

def run():
    time.sleep(2)
    print('ok')

thread.start_new_thread(run, ())

--> this produces:
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr

where as:
import threading
import time

def run():
    time.sleep(2)
    print('ok')

t=threading.Thread(target=run)
t.daemon = True  # set thread to daemon ('ok' won't be printed in this case)
t.start()

works as expected. if you don't want to keep the interpreter waiting for the thread, just set daemon=True* on the generated Thread.
*edit: added that in example
Comment: I knew that thread.start_new_thread is a limited library and I initially used threading.thread, thread was created and run function was also called, but the problem was that the code was struck in while loop. There the whole purpose of thread is defeated, so I tried using thread.start_new_thread. In a nutshell my problem is still not solved. when I create a thread in my code, the code is getting struck in while loop. Also please try to solve my code, I know run() definition given by you is simple and it works.
Comment: of course it's stuck in a loop. if you don't want that, you must have a way to end the thread in some way.
[this](http://pastebin.com/YcRnyEbK) works by setting the thread to be a daemon thread which means it will be killed when no other (non-deamon) threads are running.
Comment: can you please explain that wid some code, i have heard about daemon thread but don kno how to use it..
thnx for replyin
Answer: thread is a low level library, you should use threading.
from threading import Thread
t = Thread(target=run, args=())
t.start()

unable to create a thread in python


Ninject binding based on the typeof a contract

Question: I'm not really sure how to solve this problem, or even really what to search for. Here is what I am trying to do.
Given a base class, that is a contract
public class BaseContract
{ }

Which has two sublcasses
public class Contract1 : BaseContract
{
    public string Name { get; set; }
    public string Surname { get; set; }

}

public class Contract2 : BaseContract
{
    public int Id { get; set; }
    public string Stuff { get; set; }
}

I would like to bind an interface IMyClass to either MyClass1 or MyClass2 depending on which contract I receive. So the invoking method will be something like.
public void Test(BaseContract contract)
{
   var classToGet = kernel.Get<IMyClass>(typeof(contract));
}

I have tried binding it as follows
        Bind<IMyClass>()
            .To<MyClasses2>()
            .WithMetadata("ContractType", typeof(Contract2));

but that didn't seem to help.
How can I achieve this type of binding with Ninject ?
Answer: You can achieve this using Ninject Named Bindings, as follows:
Bind<IMyClass>().To<MyClasses1>().Named(typeof(Contract1).Name);
Bind<IMyClass>().To<MyClasses2>().Named(typeof(Contract2).Name);

Then, you can perform the injection using one of the common injection patterns (Constructor, Property, Method, etc, by doing so:
public class ClassWithDependency
{
    // To achieve property injection
    [Inject, Named("Contract2")]
    public IMyClass Contract2Instance {get; set;}

    // Constructor injection
    public ClassWithDependency([Named("Contract2") contract2Instance)
    {
         //Save reference to your dependency here
    }
}

Or you can even use the Service Locator (like your example, but not recommended) to achieve what you want:
public void Test(BaseContract contract)
{
   var classToGet = kernel.Get<IMyClass>(typeof(contract).Name);
}

Hope that helps!


Will resource identification numbers stay the same for each install?

Question: my goal:
create an image gallery with each image having a description, name, title, other possible misc info.  as the user navigates through the gallery, image info will be displayed.  i plan to store the data in an arraylist of maps ArrayList<Map<String, String>> which is filled from the database. the list will include resource ID values among image info.
problem:
I am saving drawable resource ID values in an SQLite database when the app is opened for the first time.  from then on, i will be referring to the sqlite stored resource ID values, and not directly retrieving resources by this R.drawable.drawable_name fashion.  can i guarantee that the resource ID values will never change after the app is installed?
Answer:
I am saving drawable resource ID values in an SQLite database when the app is opened for the first time.

That is a bad idea.

can i guarantee that the resource ID values will never change after the app is installed?

No. They will vary from compile to compile.
Answer: The Resource IDs are generated when your application is compiled so they won't change after the application is installed.
However if you release a new version of your application the Resource IDs almost certainly will change.  So you will need to detect an upgrade and rebuild your DB or just not access resources this way.
If you say what problem you are solving by putting Resource IDs in the database someone may be able to give you a less brittle solution.
Answer: Yes.
If you open R.java you will notice that every property is defined as public static final.