Are inner products always dominated by the norm of tensor products?

Question: Prove or disprove the following possible generalization of Cauchy-Schwarz inequality: Let $H$ be a Hilbert space and let $A_1, \dots A_n, B_1, \dots B_n \in H$. Then
$|\sum_{i=1}^{n} \langle A_i, B_i \rangle| \leq || \sum_{i=1}^{n} A_i \otimes B_i ||$
where the norm is in the tensor Hilbert space $H \hat{\otimes} H$. In essence we are asking whether a bunch of inner products are always dominated by the norm of the corresponding tensor products.
I say that it is a generalization of Cauchy-Schwarz inequality because if one takes $n=1$ above, one gets
$|\langle A_1, B_1\rangle| \leq ||A_1 \otimes B_1||=||A_1||||B_1||$
which is the familiar Cauchy-Schwarz inequality. I have tried applying standard tricks used to prove Cauchy-Schwarz, such as using the fact that the norm of $A \wedge B = A\otimes B - B \otimes A$ is non-negative but to no avail.
Comment: Is it really a generalization of Cauchy-Schwarz?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: @kgw1984 Yes, I do.
Comment: I think the answer is positive. Use the fact that $A \otimes B$ can be identified with the rank one operator $x \mapsto \langle A, x \rangle B$ and the map $A \otimes B \mapsto \langle A, B \rangle$ is just the trace. So you want to bound the trace. Equivalently, you can use the self-duality of $H$ and the fact that every norm lifts to the projective tensor.
Comment: @timur I have edited the question to answer your comment. Thanks for pointing that out.
Comment: @JoséCarlosSantos I have tried to phrase the question better. Do you think this is sufficient?
Answer: Given a Banach space $X$, the quadratic form $q: X \times X^\ast \to \mathbb{C}$ given by $q(x,x^\ast) = \langle x, x^\ast \rangle$ is bounded. Indeed, it is contractive. Therefore it lifts to the projective tensor product $q: X \hat\otimes X^\ast \to \mathbb{C}$. Now, use that, when $X$ is a Hilbert space you have self-duality.
Another approach is that you can identify $H \hat\otimes H$ with the trace class operators $S^1[H] \subset B(H)$. It is easy to check that
$$
  \mathrm{Tr} ( A \otimes B ) = \langle A, B \rangle.
$$
So you only need to see that the trace is bounded in $S^1[H]$, which follows by definition.
Comment: Yes. Positivity of the element $S = \sum_k A_k \otimes B_k$ as an operator in $H$.
Comment: It does make a difference because the norms would be different. The Hilbert-Schmidt operators form a self-dual space, but the dual of $H \hat\otimes H$, for finite dimensional $H$ is given by $H \otimes_\epsilon H$, which can be identified with $B(H)$, a notoriously nonreflexive space. Just look in Ryan's Book Example 2.20 to see that $\ell^2 \hat\otimes \ell^2$ has a complemented copy of $\ell^1$ -something incompatible with it being the Hilbert-Schmidt operators.
Comment: No problem. The first two chapters of Ryan's book should be enough for you to get familiar with quadratic forms over Banach spaces
Comment: I think your answer is correct. Do you think one can come up with necessary and sufficient conditions for equality in terms of $A_i$ and $B_i$?
Comment: I think one can identify $H\hat{\otimes}H$ with the space of Hilbert-Schmidt operators and not trace-class operators, but I guess it makes no difference because we are interested in finite-rank operators. Do you think one can derive the result from more elementary considerations? Also, I can't understand the first answer. Can you give me a good reference to look up the relevant results on quadratic forms in Banach space and lifting?
Comment: Btw, the first argument works even if you don't believe $H \hat\otimes H$ to be the trace class.
Comment: Oh, I see. I had a serious confusion about the meaning of the symbol $H\hat{\otimes}H$. Thanks for clearing that up.
Answer: Certainly false. Here's a counterexample: Let $A_1 = B_1 = e_1$ and $A_2 = B_2 = e_2$ where $e_1, e_2 \in H$ and are orthonormal. Then
$$ \sum_{i=1}^2 \langle A_i, B_i\rangle = 2$$
but,
\begin{align}
\Big\| \sum_{i=1}^2 A_i \otimes B_i\Big\|
&= \sqrt{\langle e_1, e_1 \rangle\langle e_1, e_1 \rangle + \langle e_1, e_2 \rangle\langle e_1, e_2 \rangle + \langle e_2, e_1 \rangle\langle e_2, e_1 \rangle + \langle e_2, e_2 \rangle\langle e_2, e_2 \rangle} \\
&= \sqrt 2
\end{align}
which is a contradiction.
Comment: The second norm is the Hilbert-Schmidt norm.


Archer Poisson Process problem

Question: An archer wishes to shoot an arrow at a target. The prospective flight path of the arrow is subject to birds flying past at random times, according to a Poisson process with rate $\mu$ per second. To proceed with shooting the arrow, the archer requires a time frame of $b$ seconds without any distraction (i.e. no birds flying through the prospective path for $b$ seconds). He stops as soon as he has shot the arrow. Let $S$ be the total time required to finish. Solve for $E(S)$.
Hint: by parts,   $\int \mu x e^{−\mu x} dx = −xe^{−\mu x} − \frac1\mu e^{−\mu x}$
I feel that $S=$ time gone by waiting for the $b$ seconds + $b$ seconds, but I could be wrong. This about as much as I gather from the question.
The answer is supposed to be $\frac{e^{b\mu}-1}{\mu}.$
Answer: The archer waits for at least $b$ seconds.   If no birds have flown passed in that time she shoots.   Otherwise when a bird flies passed she starts again.
If the birds arrive in a Poisson process the wait time between birds, $T$, is exponentially distributed.
The expected time-til-shooting, $\mathsf E(S)$, is $$\begin{align}\mathsf E(S) ~=~& \mathsf E(S\mid T>b)~\mathsf P(T>b) + \mathsf E(S\mid T\leq b)~\mathsf P(T\leq b)
\\[2ex]
~=~& b~\mathsf P(T>b) + \big(\mathsf E(S)+\mathsf E(T\mid T<b)\big)~\mathsf P(T\leq b)
\\[4ex]
\therefore~\mathsf E(S) ~=~& b+\dfrac{\mathsf E(T\mid T\leq b)~\mathsf P(T\leq b)}{1-\mathsf P(T\leq b)}
\\[2ex]
 ~=~& b+\dfrac{\int_0^b t\mu\mathsf e^{-t\mu}\operatorname d t}{\mathsf e^{-b\mu}}
\end{align}$$
Can you now complete?
Answer: Hint: the last "cycle" contributes $b$ to the time. Each other cycle contributes $X_i$ to the time, where $X_i$ is exponential with rate $\mu$ conditioned on $X_i < b$. You can compute $E[X_i]$ easily enough. However, there are a random number of cycles, and you need to take that into account. Accordingly, what is the distribution of the number of cycles required?
(This is probably not the easiest approach, but it works.)
Answer: The archer is waiting for the first interarrival (time between birds) that exceeds b, so we compute the expected amount of time passed waiting for an interrarival of time greater than b, then add b to it to give him time to aim/shoot. The interrarival time is distributed as $exp(\mu)$ and if it is also $<b$ has expectation $\int_0^b x\mu e^{-\mu x}=-be^{-\mu b}+1/\mu-e^{-\mu b}/\mu$, using the hint. The probability that an interrarival time is in fact $<b$ is $\int_b^\infty \mu e^{-\mu b}=1-e^{-\mu b}.$ If we assume the interrarivals are iid, the expected number of them until one fails to be $<b$ is the mean of a geometric random variable with parameter $e^{-\mu b}$, i.e., $e^{\mu b}$. So on average $e^{\mu b}$ interrarivals of average duration $-be^{-\mu b}+1/\mu-e^{-\mu b}/\mu$, for a total duration $-b+e^{\mu b}/\mu-1/\mu$ and adding $b$ gives the indicated answer.

Archer Poisson Process problem


Pathfinding optimization in a network

Question: Actually I'm looking for some answers pointing me in the right direction and giving me some keywords to search and read in the right direction but I'm not sure if this is the right place to ask for it.
First I introduce the problem and then I explain what I'm looking for.
I have a couple of stations. Let's say hospitals (S1, S2, S3). I have a couple of transportation wagons. Let's say two cabs (C1, C2) and a couple of passengers. Let's say three dudes (P1, P2, P3).
Each of the passengers has a different path through the hospitals with different times being treated there. But only one passenger can be treated at a place at the same time. So one have to wait for another to be finished at a place before he can start being treated there.
Passenger P1 wants to go to S1, S2, S3 and afterwards home (Which means essentially he is out of the game) He needs 100 minutes at every station.
Passenger P2 needs 30 minutes at every station.
And Passenger P3 needs 30 minutes at S2 and 100 Minutes at S3. He is skipping Station 1.
Also a cab can only carry one person at a time. The treating processes of course can happen parallel but only one at a place. Otherwise it wouldn't be that difficult.
My problem is to find the perfect path (or near to perfect or at least good path) for the cabs to carry all the dudes around. Which means that all passengers should be treated in all there stations in the shortest total time.
But my problems already begin in modelling the whole system properly. Right now I'm reading a couple of stuff about network optimization but I'm quite unsure if it's the right direction.
Your help is much appreciated.
Comment: Looks a lot to machine scheduling to me.
Comment: Damn it i think that's exactly what i was looking for. Thank u so much. I needed just that word!
Answer: This is a classical planning problem.  I use the word classical there specifically.
Comment: Thanks for your answer. I just missed the right direction to go when i started. But after Erwin Kalvelagen droped the word scheduling and i googled it, i totally got the right direction to go. I just never heard about it before.

Pathfinding optimization in a network


Python string replacement except first character

Question: Writing a function that will replace every duplicate character of the first letter of a string with * except for the first letter itself - is there a more pythonic/elegant way to do it than this (lists, etc?)?
def specialreplace(s):
    firstchar = s[0]
    modifiedstr = s[1:].replace(firstchar, "*")
    print firstchar + modifiedstr

specialreplace('oompaloompa') ---> o*mpal**mpa

Comment: That looks like the best way according to the [KISS principle](http://en.wikipedia.org/wiki/KISS_principle). Why would you not use that?
Comment: `s[0]+s[1:].translate(string.maketrans(s[0],"*")))`, still have to index and slice, what you are using is pretty much the idiomatic way
Comment: wondering what other similarly simple ways of going about it there are, if there are any. how would one do it with lists?
Comment: You could also employ a string.translate method for speed:
https://docs.python.org/2/library/string.html

But that is the best way.

Also, +1 for the Arrested Development reference.
Comment: Simple, readable and pythonic, I doubt you'll find any thing better (putting personal preferences aside).
Comment: @AlexanderHuszagh mmm string translate.. with spicy club sauce. Can you show me how you would do it with string.translate?
Comment: The problem is it takes a few extra steps, so the speed improvements really only come if you're deleting characters (which you are not) or using the same protocol many times. I can post an answer below.
Comment: oh hey there again @PadraicCunningham! if i wanted to use a list of the string's characters, what would be the simplest script?
Comment: @SpicyClubSauce do you mean multiple mappings?
Comment: Possibly use a regex: http://stackoverflow.com/questions/3878555/how-to-replace-repeated-instances-of-a-character-with-a-single-instance-of-that
Comment: This question might have been a better fit on Code Review.
Answer: It's a simple problem, I'm not sure why you're trying to complicate it. Your solution looks good, except for the fact that you should use .join() instead of '+' to join strings together.
"".join((s[0], s[1:].replace(s[0], "*"))

Comment: `s[0]+ s[1:].replace(s[0], "*")`
Comment: No you shouldn't use join. There's no reason to incur a function call here. See my edit for this.
Comment: @AlexanderHuszagh I don't know what you mean by 'my edit', sorry.

What do you mean by 'function call'? The tiny overhead of calling join()?
join() is _the_ idiom for joining strings together, which is what we're doing here.
Comment: Check out the edit on this post:
http://stackoverflow.com/a/30741141/4131059

I basically use dis.dis (a python bytecode analyzer for functions) to determine how the two differ, which is how the code is translated to byte code which is then run by the machine. Your method requires a lot of steps, including making a tuple, then calling a function, and then actually joining the string, when "+" just joins the strings.
Comment: Yes, if the program that's using this function was running too slowly, then after profiling it and identifying this very function as consuming a significant amout of time, I'd look into improving its performance. Since that's not what we're doing here and it's very unlikely to happen, I suggest sticking to recommended Python idioms, as stated in PEP8: https://www.python.org/dev/peps/pep-0008/#programming-recommendations
Comment: That is for inplace string concatenation. This is not inplace. We are returning a new string here. We're not saying s = s[0] + s[1:].replace(s[0], "*")

We're returning a new string.
Comment: Right, so, what the OP asked for was " is there a more pythonic/elegant way to do it than this  (lists, etc?)". Now, what we're doing here is joining two strings together. It so happens that join() is the accepted Pythonic way of doing so. The performance differences between different methods of joining strings together are irrelevant here. Readability and conformance to the language's idioms is what counts. Now, you could argue that using '+' is as/more readable than join() in this case, since there are only 2 strings involved, but the decision should still be made based on readability.
Answer: Here is not a recommended way to do it, unless you are iteratively doing this (for each letter, many times), but another way to do it:
And I was wrong on the speed. Plus different in Python3.
import string
a = 'ababc'
firstchar = a[0]
trantab = string.maketrans(firstchar, '*')

def translate(mystr, firschar):
    trantab = string.maketrans(firstchar, '*')
    return firstchar + string.translate(mystr[1:], trantab)

def translate_iter(mystr, firschar, trantab):
    return firstchar + string.translate(mystr[1:], trantab)

def replace(mystr, firstchar):
    return firstchar + mystr[1:].replace(firstchar, '*')

In [29]: %timeit translate(a, firstchar)
1000000 loops, best of 3: 582 ns per loop

In [30]: %timeit replace(a, firstchar)
1000000 loops, best of 3: 240 ns per loop

In [32]: %timeit translate_iter(a, firstchar, trantab)
1000000 loops, best of 3: 376 ns per loop

EDIT: Don't use join on strings. There's no reason to.
import dis
In [36]: def add(a,b):
    return a+b
   ....:

In [37]: def join(a,b):
    return join((a,b))
   ....:

In [42]: dis.dis(add)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BINARY_ADD
              7 RETURN_VALUE

In [43]: dis.dis(join)
  2           0 LOAD_GLOBAL              0 (join)
              3 LOAD_FAST                0 (a)
              6 LOAD_FAST                1 (b)
              9 BUILD_TUPLE              2
             12 CALL_FUNCTION            1
             15 RETURN_VALUE

You're incurring a pointless function call that makes no sense, makes the code less readable, and overall slows performance.
I'm all for sacrificing performance for readability, but not when it sacrifices both performance and readability.
Answer: You could use enumerate:
print("".join(["*" if s[i] == s[0] and i != 0 else ch for i, ch in enumerate(s)]))

But that is just for fun, I would stick with your own solution.
To answer you comment, you can use multiple mappings to replace multiple characters with translate:
from string import maketrans
print(s[0]+s[1:].translate(maketrans(s[0]+s[2]+s[3],"*$!")))
o*$!al**$!a

In python3 you need a table using the ord of each character as the keys:
print(s[0]+s[1:].translate((dict(zip((ord(s[0]),ord(s[2]),ord(s[3])),"*$!")))))
o*$!al**$!a

You could also use re.sub ignoring the first character:
s = 'oompaloompa'

from re import sub

print(sub(r"(?<!^)"+s[0], "*", s))
o*mpal**mpa

But again a bit of overkill.
Answer: You already are using list indexing and slicing, and you have a clean answer. Still:
def specialreplace(s):
    chars = [ ('*' if c == s[0] else c) for c in s[1:] ]
    print s[0] + ''.join(chars)

and if you want to codegolf that a bit:
specialreplace = lambda s:s[0]+''.join(['*'if c==s[0]else c for c in s[1:]])

Edit with shovelling a dictionary lookup with a default return value into it, because why not use the kitchen sink:
specialreplace=lambda s:s[0]+''.join([{s[0]:'*'}.get(c,c)for c in s[1:]])

Edit: @Voo's comment, The list comprehension is reasonably Pythonic - if you must use the list of characters as SpicyClubSauce requested, then you have as close to a ternary operator as Python has, and a join to bring the list of characters back together. The lambda versions are very unPythonic. All of them are less elegant than the questioner's original solution.
Comment: Neither of those two is more elegant or more pythonic than the posted one.
Comment: it's ok - i later commented underneth that i'd also welcome creative alternatives.
Answer: Your code looks good and I think the one way that can improve it, is getting ride of multiple indexing, and for that you can use iter function to convert your string to an iterator that support next :
>>> def specialreplace(s):
...     it=iter(s)
...     first=next(it)
...     return first+''.join(it).replace(first,'*')
...
>>> specialreplace(s)
'o*mpal**mpa'

Also as another alternative you can replace the replace method with a list comprehension and join :
def specialreplace(s):
    it=iter(s)
    first=next(it)
    return first+''.join(['*' if i == first else i for i in it])

The following benchmark says that there is no much difference between them but the second approach is a bit better.(for 1000000 loop and not for a long string test )
from timeit import timeit

s1="""
def specialreplace(s):
    firstchar = s[0]
    modifiedstr = s[1:].replace(firstchar, "*")
    print firstchar + modifiedstr
"""
s2="""
def specialreplace(s):
    it=iter(s)
    first=next(it)
    return first+''.join(['*' if i == first else i for i in it])

    """

s3="""
def specialreplace(s):
    it=iter(s)
    first=next(it)
    return first+''.join(it).replace(first,'*')

    """

print ' first: ' ,timeit(stmt=s1, number=1000000)
print 'second : ',timeit(stmt=s2, number=1000000)
print '3rd : ',timeit(stmt=s3, number=1000000)

result :
first:  0.0531640987396
second :  0.0527780056
3rd :  0.0523271560669

Comment: @PadraicCunningham OMG!
Comment: @PadraicCunningham Yeah I have! why?
Comment: Are you wearing your stevie wonder glasses again? ;) Run your first function and add the output
Comment: lol, I am seriously going to buy you some fishbowl specs! Run it again, you realise what str(object ) does? `return first+ "".join(it).replace(first,'*')`
Answer: def specialreplace(s):
  return s[0]+s.replace(s[0],'*')[1:]

Comment: Welcome to StackOverflow.
Please consider to explain how this code snippet solves the issue stated in the original question.
Answer: Here is a pythonic way to do it using str.replace() method:
string_  = 'oompaloompa'
new_string = string_[0]+string_.replace(string_[0],"*",string_.count(string_[0]))[1:

Answer: inputString = input("Enter a String: ")

def changeCharToAsterik(inputString):
    char = inputString[0]     # Assigns character at first index to char
    inputString = inputString.replace(char, '*')   # Replaces every character that is same as that of char to '*'
    return char + inputString[1:]  # Again the first character which was already replaced by '*' changes to char(i.e original character) and concatenates with rest of the strings from index 1 to last.

result = changeCharToAsterik(inputString)
print(result)

Comment: This would be a better answer if you explained how the code you provided answers the question.
Comment: I have now added comments to explain every steps, if that was what you've wanted.


How do I set files uploaded with filepicker.io to s3 from other services (facebook, instagram, etc...) as public

Question: in the store_options that I provide to pickAndStore, setting:
<code>access: 'public'
</code>
works to make the uploaded file public for files i upload from my computer.
When I upload a file through the modal dialog from, say, facebook or instagram, the file uploaded to s3 has not been set as public.  S3 returns a 403 Forbidden when I try to access my file.
Am I missing something, or is this a bug on filepicker's end?
Comment: I'm also experiencing this issue. Similar question:  http://stackoverflow.com/questions/17417381/s3-access-public-not-working-for-files-from-internet-urls
Answer: Filepicker dev here. There was a bug on our side that has now been fixed. Thanks for the patience.


Handshake problem, each person can have 5 handshakes

Question: There are a total of $60$ handshakes in a party. Each person can only shake hands with $5$ other people. So, how many people are there? Is the answer $24$?
A group of $6$ is formed. One group can have $1+2+3+4+5=15$ handshakes. $\dfrac{60}{15}=4$
Hence, number of people is $4\times 6= 24$.
Comment: If a person doesn't _have_ to shake hands with five others, but is allowed to do fewer, then there could be more people. For instance, if everyone shakes hands with only one other person, then there are $120$ people. So $24$ is only the correct answer if each person must shake hands with _exactly_ $5$ other people.
Answer: The answer is truly 24, but your reasoning is wrong. 24 it is because each handshake includes two people, therefore total of 120 persons participate (though a lot of this participants are equal to each other) in a handshake, and each person did it 5 times, so there must be 24 different persons.
There are many ways to arrange the graph with 60 edges and having each vertex of degree five. You simply chooses two edges from different subcliques in your graph and delete current edges and cross-connect their ends (replace edges $(a,b),(c,d)$ with $(a,c),(b,d)$ ), what you get is a graph with the same number of edges and vertices and same vertex degrees, but different from your original graph. And you can repeat this step many times to create a lot of different graphs.


Synchronize System.out & System.err

Question: When debugging code I tend to use System.out & System.err quite a lot. The problem is when an exception is ocurring and i use System.out the same time the outcome doesn't look very organized.
[CLIENT]:postinit: vic.rpg.gui.GuiMain.init()
java.net.ConnectException: Connection refused: connect
[CLIENT]:Destroying Network Thread...
[CLIENT]:done!
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
...
[CLIENT]:Starting Server...

It's not very severe but it makes reading logs a little bit difficult sometimes.
Comment: You would not have that sort of issues if you used a proper logging framework.
Answer: You can avoid this issue by calling flush each time you write to either stream. e.g.:
System.out.println ("Writing to *out*");
System.out.flush ();

If you are logging from different threads, then your logging messages will naturally interleave. If you want to cleanly separate the output by threads, I'd suggest using a logging library such as log4j.
Comment: I was already wrapping System.out into my own PrintStream, adding a `super.flush()` to every method did work.

Synchronize System.out & System.err


Calculating the rotations necessary to make a 2D object match the perspective of a plane in 3D space

Question: I'm working with 3D rotations and extrusions in Adobe Illustrator. I have a square that I have extruded into a rectangular prism, which I've then rotated a known amount (x°, y°, z°) on each axis. I'm not using perspective, so I assume that makes the result some kind of axonometric projection (probably isometric?).
I have another 2D object that I want to also rotate in 3D space so that the perspective matches that of one of the other five sides of the original extruded cube.

Given what I know, it seems like I should be able to calculate the transformations needed on the new object. But various sensible-seeming combinations of simply adding 90° to/subtracting 90° from/inverting the sign of the old values don't seem to generate what I need.
So: Just how complicated is the math I need to do this?
Comment: A few disclaimers: Yes, I'm in way over my head on the math. Yes, I know that Illustrator and Photoshop have easier ways to do this without doing math. I don't care; I want to know how to do it properly for my personal enrichment. It's possible that I simply didn't do the right combination of simple math on the original angles; sorry if that's the case. Yes, I know that my title sucks and that I may not have used the right words about stuff like the kind of projection being used. Please feel free to edit my question to be more coherent and discoverable.
Answer: Composition of Euler angles is not simple.

Convert your Euler-angles to rotation matrices, and multiply them together.

R1 = rotate 90° around y-axis — Rotates to left side
  R2 = rotate 14° around x-axis
  R3 = rotate -14° around y-axis
  R4 = rotate -32° around z-axis
  R = R4 × R3 × R2 × R1

Recover the angles

x' = arctan2(R3,2,R3,3) = arctan2(cos(y)·sin(x), -sin(y))
  y' = -arcsin(R3,1) = -arcsin(cos(y)·cos(x))
  z' = arctan2(R2,1,R1,1) = arctan2(cos(z)·sin(x) - sin(z)·sin(y)·cos(x), -sin(z)·sin(x) - cos(z)·sin(y)·cos(x))

In your specific case, this evaluates to:

x' = 44.1°
  y' = 70.3°
  z' = 13.9°


Number of elements in the quotient ring $\mathbb{Z}_6 [x]/\langle 2x +4\rangle$

Question: I am confused about this quotient ring.
I know that $\mathbb{Z}_7 [x]/\langle x^2 + 1\rangle =  \{ f(x) + \langle x^2 + 1\rangle \mid f(x) \in \mathbb{Z}_7[x] \}$. Here $x^2 + 1$ is a zero element in $\mathbb{Z}_7 [x]/\langle x^2 + 1\rangle$, so if we replace $x$ by $i$ we get $\mathbb{Z}_7 [x]/\langle x^2 + 1\rangle =\mathbb{Z}_7 (i) $.
I know the distinct element of $ \mathbb{Z}_6 [x]/\langle 2x +4\rangle$ are $\langle 2x +4\rangle,\;x + \langle 2x +4\rangle, \;x^2 + \langle 2x +4\rangle, \ldots$ but I do not  know how to prove this.
Please tell what could we do similar here in case of $ \mathbb{Z}_6 [x]/\langle 2x +4\rangle$? Since $1$ is the zero element of the polynomial $2x +4 $. Why we can not replace here $x$ by $1$?
Any help would be appreciated. Thank you.
Comment: @Arthur: Your argument is not entirely convincing: $\Bbb Z [\Bbb i] \simeq \Bbb Z [X] / (X^2 + 1)$, so we "replace" $X$ by $\Bbb i$ despite the fact that $X^2 + 1$ has two roots, too.
Comment: We can't replace $x$ by $1$ since $4$ also is a zero point. So if we were to do any replacing, we would have to replace $x$ with both $1$ and $4$ at the same time. We can't do that, but we still know that $2x = 2$, regardless, so that is the substitution we can do.
Comment: think about the elements $x,x^2 , x^3 , x^4 , \ldots $ are any two of these equal in the quotient ring?
Comment: I will think about  both of your points
Comment: @AlexM. Which is why I put it in a _comment_, not an answer. Your example is a quadratic equation, which you would _expect_ to have two solutions, while this one is a linear equation which _still_ has two solutions.
Comment: @Arthur: Agreed. And this is why I haven't considered your argument false, but merely unconvincing. Anyway, what drives me mad in this problem (as opposed to all the similar others on this site) is that $2$ is not invertible modulo $6$, therefore I cannot use the usual argument based upon Euclidean division. If a polynomial has coefficients $0, 2, 4$ than it can be divided (with remainder) by $2x + 4$, therefore one only has to study polynomials of the form $a_0 + a_1 x + \dots + a_n x^n$ with $a_i =0$ or $1$, but how?
Comment: @baharampuri: Are there?
Comment: @Alex M. 2(x+4) does not divide $x^m-x^n$ as integer polynomials and a simple argument will show that it does not divide modulo 6.
Answer: Here is an isomorphism using the Chinese Remainder Theorem.
\begin{align*}
\frac{(\mathbb{Z}/6\mathbb{Z})[x]}{(2x+4)} &\cong \frac{\mathbb{Z}[x]}{(6, 2x+4)} = \frac{\mathbb{Z}[x]}{(2)(3, x+2)} \cong \frac{\mathbb{Z}[x]}{(2)} \times \frac{\mathbb{Z}[x]}{(3, x+2)}\\
&\cong (\mathbb{Z}/2\mathbb{Z})[x] \times \frac{(\mathbb{Z}/3\mathbb{Z})[x]}{(x+2)}  \cong (\mathbb{Z}/2\mathbb{Z})[x] \times \mathbb{Z}/3\mathbb{Z}
\end{align*}
The first isomorphism is the Third Isomorphism Theorem and the second equality follows since the ideals $(6, 2x+4) = (2)(3, x+2)$ are equal in $\mathbb{Z}[x]$.  Since $1 = -2 + 3 \in (2) + (3, x+2)$, then $(2)$ and $(3, x+2)$ are comaximal, so we can apply the Chinese Remainder Theorem.  Finally, the isomorphism $\frac{(\mathbb{Z}/3\mathbb{Z})[x]}{(x+2)} \cong \mathbb{Z}/3\mathbb{Z}$ is induced by the evaluation map at $-2$.
Comment: So this ring has infinitely many elements and the question in the title is misleading. I was suspecting something along similar lines but was colliding with the title.
Comment: More explicitly, the isomorphism is given the following way: given an element $f\in\Bbb Z_6[x]/(2x+4)$, there is a unique representative $\bar f\in \Bbb Z_6[x]$ of $f$ where all coefficients except perhaps the constant term are $0$ or $1$. That, together with whether the constant term of $\bar f$ is even or odd gives you an element in $\Bbb Z_2[x]$. The element of $\Bbb Z_3$ is given by the constant term of $\bar f$ modulo $3$.
Comment: @Arthur: This is what I was thinking when I wrote the comment under the OP's original question.
Comment: @Arthur I'm not sure about your description of the map in the second factor.  To get the entry in $\mathbb{Z}/3\mathbb{Z}$ in the isomorphism I've written down, one evaluates the polynomial at $-2 = 1$ (which amounts to adding the coefficients), then reduces mod $3$.  Or am I missing something?
Comment: @SpamIAm I suspect you are right. I wrote my comment without thinking much.
Comment: @Arthur: I've written an answer, is this what you had in mind?
Answer: In principle, problems of this type ar given either over fields, or at least for ideals generated by polynomials with invertible leading coefficient, and they are generally solved by using Euclid's algorithm for polynomial division. Alas, the fact that $2$ is not invertible in $\Bbb Z _6$ makes this approach infeasible.
Note though that if a polynomial $f$ has all the coefficients $0$, $2$ or $4$, then you would write it as $2g$ and you could perform the Euclidean division not of $f$ by $2x + 4$, but rather of $g$ by $x + 2$. This is the idea that we shall follow. Split any polynomial $f \in \Bbb Z _6 [x]$ into a part $f _\text{even}$ with even coefficients and a rest $f_2$with coefficients either $0$ or $1$ (this splitting is unique). Next, there exist $q \in \Bbb Z _6 [x]$ and $r_f \in \Bbb Z _6$ such that $f _\text{even} = (2x+4) q + r_f$. Note that $r_f = f _\text{even} (1) \in \{0,2,4\} \subset \Bbb Z _6$. Since this set is a subring isomorphic to $\Bbb Z _3$, identify $r_f$ with $\widehat {r_f} \in \Bbb Z _3$, its class modulo $3$.
Consider now the morphism $\Bbb Z _6 [x] \to \Bbb Z _2 [x] \times \Bbb Z _3$, given by $f \mapsto (f_2, \widehat {f _\text{even} (1)})$. Its kernel is made of all those polynomials that have no "odd" part and when divided by $2x+4$ produce no remainder, therefore are multiples of $2x+4$. Thus, the kernel is exactly the ideal $(2x+4)$ and by the fundamental isomorphism theorem this gives $$\frac {\Bbb Z _6 [x]} {(2x+4)} \simeq \Bbb Z _2 [x] \times \Bbb Z _3 .$$
In particular, this ring has infinitely many elements.
Comment: Thanks to all of them who give me your valuable time.


Drupal Module - Mailing List, cannot export list, get browser error

Question: I've just started using the mailing list module, but when I put it on my live site I get an error when I try to export the list of entries. I did get an actual Drupal error which is
<code>    Error
The website encountered an unexpected error. Please try again later.
</code>
this put an entry in my Log which I followed up on the net and found this page http://drupal.org/node/1206916 entry #11 led me to a link which should fix this, I tried this, but now I just get a Browser failure saying it cannot locate the file.
any ideas? or is there a better mail module?
Comment: If you are getting errors from a certain module, there may be a bug in the module and you should report the error in the module's [issue queue](http://drupal.org/project/issues/mailing_list)
Answer: If you are having trouble with the module you are using, there are other mail-type modules available.

MailChimp - Module to utilize subscriptions/emails with mailchimp.com
Simplenews - Publishes and sends newsletters to lists of subscribers (still in Alpha)
Notifications - Complete Subscriptions/Notifications Framework aiming at extendability and scalability (still in Alpha)
Comment: Thanks for the tip, I have a hard time locating appropraite modules within the Drupal.org pages. Will check out these modules I have basic needs, I hope one will serve. thanks.


How do I show a checkboxes form element that is selected by default?

Question: How do I show a checkboxes form element that is selected by default?
I tried setting #default_value as in the following code, but it doesn't work.
$form['ios'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#default_value' => 'checked',
);

Is #default_value the wrong attribute?
Comment: Have you tried this? `$form['ios'] = array('#type' => 'checkboxes', '#options' => $options, '#default_value' => array($value));` `$value` should be the option you want selected by default.
Comment: If you have a single field, you can use the following code. `$form['name']['terms_condition'] = array( '#type' =>'checkbox', '#title'=>t('Terms and conditions'), '#required'=>TRUE, '#default_value' =>TRUE);`
Comment: What happens here when the form is submitted with the checkbox unchecked but required set to `true`?
Answer: #default_value for checkboxes form elements should be set as in the following code.
$options = array();
$options["1"] = "One";
$options["2"] = "Two";
$options["3"] = "Three";
$options["4"] = "Four";

$form['ios'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#default_value' => array("1", "2", "3")
);

Answer: You have to give "#default_value" all $options keys
In your case:
$form['ios']['#default_value'] =  array_keys($form['ios']['#options']);

Comment: It depends on what _selected_ means for the OP, but to me it means at least one checkbox is selected. Since the OP already accepted an answer, I take he didn't mean that all the checkboxes needed to be selected.
Answer: If you want to checked all checkboxes values as default, you can use checked property in #attribute.
In your case:
$options = array();
$options["1"] = "One";
$options["2"] = "Two";
$options["3"] = "Three";
$options["4"] = "Four";

$form['ios'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#attributes' => array('checked' => 'checked'),
);

This work for me.


Este código está-me a conduzir a um ciclo infinito e não consigo perceber porquê

Question: Este código está-me a conduzir a um ciclo infinito e não consigo perceber porquê.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void
troca (double *n1, double *n2)
{
    double n;

    n    = *n1;
    *n1  = *n2;
    *n2  = n  ;
}

void
ordena (double *r, int size)
{
    int t;
    int i;

    while (1)
    {
        t = 0;
        {
            for (i=0;i<size-1;i++)
            {
                if(r[i] > r[i+1])
                {
                    troca (&r[i], &r[i+1]);
                    t      = 1          ;
                }
            }
        if(t == 0)
            break;
        }
    }
}

int
main(int argc, char **argv)
{
    FILE   *f1   ;
    int    i     ;
    int    j=0   ;
    int    N     ;
    int    k     ;
    double Min   ;
    double Max   ;
    double *reais;
    double n     ;
    char    c    ;

    sscanf(argv[1],"%d",&N)   ;
    sscanf(argv[2],"%lf",&Min);
    sscanf(argv[3],"%lf",&Max);

    f1    = fopen("f1.txt", "wb")            ;

    srand(time(NULL));

    while (1)
    {

    if (j == 0)
    {
        reais = (double*)malloc((N)*sizeof(double));
        j=1;
    }

    else
        reais = realloc(reais, (N)*sizeof(double));

    n = Max - Min;
    for (i=0;i<N;i++)
    {
        reais[i] = Max - ((double) rand()/(double) RAND_MAX )*n;
        //printf("%9lf",reais[i]);
    }

    ordena(reais, N);

    k = 0;
    for (i=0;i<N;i++)
    {
        printf("%9lf",reais[i]);
        k++;

        if (k == 5)
        {
            k = 0;
            printf("\n");
        }
    }

    printf("\nDeseja repetir as operacoes:\n1-Repetir\n2-Sair\nR:");
    c = getchar();

    if (c == '1')
    {
        printf("\nIntroduza novos valores de N, Min e Max:");
        scanf("%d %lf %lf", &N, &Min, &Max);
        continue;
    }

    if (c == '2')
    {
        free(reais);
        break;
    }

    }

    return 0;
}

O programa recebe três argumentos da linha de comandos, N, o número de reais que o user quer gerar, Max e Min os limites dos valores gerados. Com esses valores é gerado um vetor de doubles com o tamanho necessário que depois é ordenado. Até aqui funciona tudo bem. O problema é que quando peço novos argumentos, entro num loop infinito
Comment: Cara, primeiro me diz o que você pretende fazer.. com esses nomes de variáveis, não da para entender nada. Fora que, tem 2 `while(1)` no código, sendo que um já é o suficiente para te jogar dentro de um loop infinito.
Comment: O programa recebe três argumentos da linha de comandos, N, o número de reais que o user quer gerar, Max e Min os limites dos valores gerados. Com esses valores é gerado um vetor de doubles com o tamanho necessário que depois é ordenado. Até aqui funciona tudo bem. O problema é que quando peço novos argumentos, entro num loop infinito.
Answer: Se entendi bem o código o problema está no método ordena; como você tem um for que percorre todas as posições do r, não precisa do while(1).
O loop era porque o t == 0 nunca ocorre, já que sempre que entra na iteração for (i=0;i<size-1;i++) esse cara roda e o t = 1; também.
voi ordena (double *r, int size)
{
    int t = 0;

    for (int i = 0; i < size - 1; i++)
    {
        if (r[i] > r[i+1])
        {
            troca (&r[i], &r[i+1]);
            t = 1;
        }
    }
}

OBS: mantive a estrutura das variáveis e tal, mas tenta usar nomes mais intuitivos, fica bem mais fácil de entender o código.
Além disso, tem algumas coisas pra melhorar, por exemplo o FILE *f1;. Você só cria essa variável e abre um arquivo, mas não usa pra nada.
Comment: Eu sei que ainda não usei o ficheiro para nada, estava apenas a testar esta parte em particular. Não penso que o problema  seja por causa dessa função porque o loop infinito ocorre após ela atuar.
Comment: @VascoPinhão testou o método `ordena` assim?? Ainda segue em looping? Se sim, adiciona `printf()` em pontos que você acha que pode ser, ajuda a identificar.
Comment: Devo discordar sobre o laço infinito na ordenação. Em tese, com o `swap` e a operação de comparação funcionando como se espera, vai terminar após umas `size^2 - size` operações de comparação
Answer: Você está ordenando usando a estratégia da bolha, com direito a uma flag para marcar se houve trocas ou não.
Matematicamente, você precisa fazer no máximo o( (n^2 - n)/2 ) operações. Ao rodar uma vez o lado interno, há a garantia de que o maior número estará no final do vetor. Então o próximo lance de ordenação não precisaria ir até a última posição, apenas até a penúltima, então os dois maiores elementos estarão em suas posições definitivas. Nessa resposta, chamei essa estratégia de minimizar a quantidade de repetições de "bubblesort mínimo". Você pode por a flag para indicar que, se não houve nenhum swap, então o vetor já está ordenado e não se precisa mais trabalhar nele.
Essa operação do jeito que você está fazendo é lenta. Não se espante com isso. A minha sugestão de melhoria na melhor das hipóteses dobra a velocidade, mas também continua sendo lento (mais informações de performance relativa na outra resposta linkada).
Em tese, a sua ordenação um dia terminaria considerando que a operação de troca esteja correta e que a comparação esteja correta. Não consegui enxergar nenhum problema nessas operações. Se você quiser fazer um debug, porém não tem as ferramentas mais tradicionais para isso, você pode inserir um printf para indicar quando houver troca e quais são os valores sendo trocados. Obviamente esse seria um código de depuração que deveria ser removido na versão final.
Então, a falha do laço deve estar em outro ponto. O outro laço que há é na função principal. Você está usando o getchar(). O que acontece caso essa função retorne um valor que você não espera? Pelo que entendi do código, ele volta o laço debilmente, sem mudar nenhum dos parâmetros.
Ou talvez ele simplesmente não esteja reagindo ao você digitar? Segundo a referência da função, ela só retorna no momento em que você pressiona ENTER. Não ficou claro para mim o que acontece se você por acaso tiver lido algo anteriormente.
Comment: Já consegui resolver, esqueci-me de limpar o buffer após cada utilização do getchar(), é por isso que estavam a dar coisas estranhas


M:K and L:K are normal and finite extensions then M intersection L : K is also finite and normal.

Question: How to prove or disprove the following statement:
M:K and L:K are normal and finite extensions ->  M intersection L : K is also finite and normal.
Answer: In order to make sense of the statement, we need an overarching field extension $F:K$ which contains $L$ and $M$ (otherwise, if $L$ and $M$ are just abstract field extensions, then what does their intersection actually mean?).
Finiteness is straightforward: simply observe that $L\cap M\subseteq L$ is a subspace of a finite dimensional vector space over $K$, and so must be finite dimensional.
For normality: if a $K$-irreducible polynomial $f$ does not split into linear factors in both $L$ and $M$, then by the normality of each it must have no roots in one of $L$ or $M$, and thus has no roots in $L\cap M$. Otherwise,
$$f=(x-l_1)\cdots(x-l_d) = (x-m_1)\cdots (x-m_d).$$
Since each of these are factorizations of $f$ in $F[x]$, which is a UFD, the $l_i$ are just a reordering of the $m_j$, and thus $f$ splits into linear factors in $L\cap M$.


How to display table data into datagridview in c#?

Question: mySqlCnnection.Open();
 string list = "select * from login";
 MySqlDataAdapter dataadapter = new MySqlDataAdapter(list, mySqlCnnection);
 DataSet ds = new DataSet();
 dataadapter.Fill(ds, "login");
 dataGridView1.DataSource =ds.Tables[0];

I want to display the entire login table data in a datagridview but am getting an empty widget?some one could please?
Answer: Call DataBind() after assigning the DataSource.
Comment: with what object we shall call DataBind()?
Comment: Call it on the `Page` object is best practice.
Comment: Is the code you posted on a WebForm (ie. a class inheriting `Page`) ? In that case, just call `this.DataBind()` as the final statement. If not, you could call `dataGridView1.DataBind()`.
Answer: Try using DataTable instead of using DataSet to fill data. Or check your sql connection.
Answer: Where you are using this code. On which you are using it? Try it on on_load event.
Use Default view and then bind the data using DataBind() method.
dataGridView1.DataSource =ds.Tables[0].DefaultView;
dataGridView1.DataBind();
Answer: Your code:
    mySqlCnnection.Open();
    string list = "select * from login";
    MySqlDataAdapter dataadapter = new MySqlDataAdapter(list, mySqlCnnection);
    DataSet ds = new DataSet();
    dataadapter.Fill(ds, "login");
    dataGridView1.DataSource =ds.Tables[0];

And on the next line ...
dataGridView1.Databind();

Ugly though.
Answer: Try to Use binding source as datasource of your datagrid.
var bindingSource = new System.Windows.Forms.BindingSource();
bindingSource.DataSource = ds.Tables[0];
dataGridView1.DataSource = bindingSource;

Answer: string list = "select * from login";
SqlCommand command = new SqlCommand(list , db.connect());

SqlDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
dataGridView1.DataSource=dt;


Convex boundary of a symplectic manifold

Question: Given a symplectic manifold $(M,\omega)$, suppose that $\partial M$ is of contact type. A Liouville field on a symplectic manifold is a vector field $X$ such that $\mathcal L_X \omega = \omega$. We say that $\partial M$ is convex if there is an outward-pointing Liouville field near $\partial M$ (it will usually not be everywhere defined). We say that $\partial M$ is concave if there is an inward-poiting Liouville field. (We say that a hypersurface is of contact type if there is a Liouville vector field defined on a neighborhood of the hypersurface that is transverse to the surface.)
An exercise (3.60) in McDuff-Salamon says that any two Liouville vector fields near a hypersurface of contact type must point in the same direction. I can't see why this is true, and what's more, I seem to have found a counterexample. So it's not clear to me that the boundary of a symplectic manifold cannot be both convex and concave.
Consider $S^1$ embedded in any symplectic surface. Because this circle is automatically Lagrangian, we know that a neighborhood of it is symplectomorphic to a neighborhood of the zero section in $T^* S^1 \cong S^1 \times (-\varepsilon,\varepsilon)$, which has symplectic form $-dt\wedge d\theta$. Given a vector field $X = a\frac{\partial}{\partial t} + b\frac{\partial}{\partial \theta}$, the Liouville condition says that $a$ is never zero on the zero section, and that $\left(\frac{\partial a}{\partial t} + \frac{\partial b}{\partial \theta}\right) = 1$.
Now pick $X = (\pm 1 + t)\frac{\partial}{\partial t}$. These are two different Liouville vector fields that point in opposite directions.
Have I misunderstood the definition of convex boundary? Can the boundary of a higher-dimensional symplectic manifold, whose boundary has contact type, be both concave and convex, or is this a fluke of 2-dimensional symplectic manifolds? If not, what's up with the McDuff-Salamon exercise that says Liouville fields must all point in the same direction?
Comment: You mean $X=(\cdots)\frac{\partial}{\partial t}$, right?
Comment: @squirrel Yes. Thank you for the correction.
Answer: I found the following in "Convex Symplectic Manifolds" by Eliashberg and Gromov; you can find this article in Several complex variables and complex geometry (Proceedings of symposia in pure mathematics ; v. 52, pt. 2). I've translated it into different notation.
Let $S$ be a hypersurface of contact type bounding a symplectic manifold $M$. We say $S$ is convex if there is a Liouville vector field near $S$ that points outwards, and concave if there is one that points inwards.
The case of a surface with boundary $S^1$ is given as - and, as above, is - an example of a boundary that is both convex and concave.
Now let $\alpha$ be a compatible contact structure on $S$ - that is, that $d\alpha = \omega$ restricted to $S$. Call the Reeb field for this contact form $\delta$. Gromov says that if $G$ is a null-homologous closed Reeb orbit for $\alpha$, then $\int_G \alpha' > 0$ for all compatible contact forms $\alpha'$. This implies that $S$ cannot be simultaneously convex and concave. (From Liouville fields pointing in opposite directions, we can produce contact forms, compatible with $\omega$, that are homologically negative of each other.)
In particular, consider $S^3$ as the boundary of your favorite symplectic manifold with boundary $S^3$. Then it cannot be both convex and concave. In addition, there is a symplectically fillable contact structure on $T^3$ with no null-homologous Reeb orbits; so this does not provide an obstruction to being both convex and concave. In fact, it's both with respect to a certain symplectic filling. (Note that every closed 3-manifold with a given contact form has a closed Reeb orbit; this was proved by Taubes in 2007, and is a special case of the Weinstein conjecture.)
As a result of this, I don't understand the exercise in McDuff and Salamon. If I interpret it to say "Given a hypersurface of contact type (without a chosen orientation), every transverse Liouville vector field near this hypersurface points in the same direction", it's false. If I've already given it an orientation, I don't see how the question isn't trivial.


I want to study Numerical linear algebra

Question: Would you like to recommend a book to me?
the proof is explicit and easy to understand is preferred.
Comment: What is your background? Are you an undergraduate student?  Graduate?  High school?  Have you already taken some linear algebra course?  Do you have any particular motivation for learning this material, i.e. any application in mind?
Comment: Matrix Computations by Golub and Van Loan and Fundamentals of Matrix Computations by Watkins are excellent books to start with.
Comment: I will be a graduate next year and I have leaned the course names 'numerical linear algebra' including 'LU,backward error,classical iteration,qr for symmetric,least square'.I want to study further.but I find the book writed by Artkinson is hard to understand.@Omnomnomnom
Comment: In addition,I found the Sauer is easy to understand,But I don't think it is deep enough.@Omnomnomnom
Answer: Numerical Linear Algebra by Trefethen and Bau


Real analysis question on tangent and secant sets of function on an interval

Question: Let $f$ be a differentiable function in an interval $I$ in $\mathbb{R}$. Define
\begin{align}
X = \{f'(x) | x \in I\} \quad Y=\left\{\frac{f(x)-f(y)}{x-y};\; x,y \in I, x \neq y\right\}
\end{align}
Prove that $\overline{X} = \overline{Y}$.
Comment: $\overline{Y} \subset \overline{X}$ is clear to me, since $ Y \subset X $, but the converse isn't...
Answer: Hint: Suppose that $m \in X$.  Then $m = f'(c)$ for some $c \in I$.  If we take a sequence $x_n \to c$, then the definition of a derivative tells us that
$$
\lim_{n \to \infty} \frac{f(x_n) - f(c)}{x_n - c} = f'(c)
$$
Comment: If I understood correctly, then as $\frac{f(x_n) - f(c)}{x_n - c}$ is a sequence of Y, it's limit is in $\overline{Y}$, thus $X \subset \overline{Y}$, thus $\overline{X} \subset \overline{Y}$. Is that it?
Comment: That's right. Any closed set containing $X$ contains $\bar X$.
Answer: Hint:
By mean value theorem you have
$$\frac{f(x)-f(y)}{x-y}  = f' (c)  $$
Where $c \in (x,y)$ This shows $Y \subseteq X$ so $\bar{Y} \subseteq \bar{X}$
for other way take $f'(c) \in X$ then there exist the sequence, say  $\{ \frac{f(x_n) - f(c)}{x_n - c} \}  \in Y$ such that
$$\lim_{n \to \infty} \frac{f(x_n) - f(c)}{x_n - c} = f'(c)$$
Even you can prove $X = \bar{Y}$ .i.e, $X$ is closed set if $ I $ is compact interval.  I think!


A subgroup such that every left coset is contained in a right coset.

Question: Let $G$ be any group, and $H \leq G$ a subgroup.
Suppose that for each $x \in G$, there exists a $y \in G$ such that $xH \subseteq Hy$. In other words, every left coset of $H$ is contained inside some right coset of $H$.
Question: what can we say about $H$? In particular, does this imply that $H$ is normal?
I know that if $G$ is finite, then $H$ must be normal, because then $xH \subseteq Hy$ implies $xH = Hy$, since $|xH| = |Hy|$.
Answer: If $xH \subseteq Hy$, then in particular $x \in Hy$. But then $Hx \cap Hy \neq \varnothing$, so $Hx=Hy$, so $xH \subseteq Hx$, so $xHx^{-1}\subseteq H$. Since this is true for every $x$, $H$ is normal.
Comment: If $xH \subseteq Hy$ for some $x, y \in G$ (not all), then can we still have $xH = Hy = Hx$?
Answer: Theorem 1 Let $H,K \leq G$ and assume that a left coset of $H$ is contained in a left coset of $K$. Then $H \subseteq K$.
Proof Assume first that $x \in G$ with $xH \subseteq K$. Then $x=x \cdot 1 \in K$. Pick an $h \in H$, then $xh=k$ for some $k \in K$, so $h=x^{-1}k \in K$, and it follows that $H \subseteq K$.
Now suppose $xH \subseteq yK$ for some $x,y \in G$. Then $y^{-1}xH \subseteq K$ and from the previous it now follows that $H \subseteq K$.
Corollary 1 Let $H,K \leq G$ and assume that a right coset of $H$ is contained in a right coset of $K$. Then $H \subseteq K$.
Proof One can mimic the proof above, or, in general, if $Hx \subset Ky$ for some $x,y \in G$, this is equivalent to $x^{-1}H \subseteq Ky^{-1}$.
So what happens if we mix left and right.
Theorem 2 Let $H,K \leq G$, $x,y \in G$ and assume $xH \subseteq Ky$. Then $Kx=Ky$.
Proof Since $xH \subseteq Ky$, $H^{x^{-1}} \subseteq Kyx^{-1}$, so Corollary 1 yields $H^{x^{-1}} \subseteq K$, that is, $H \subseteq K^x$ and equivalently, $xH \subseteq Kx$. Hence, $\emptyset \neq xH \subseteq Ky \cap Kx$, implying $Kx=Ky$.
Corollary 2 Let $H \leq G$ and $x,y \in G$ with $xH \subseteq Hy$. Then $Hx=Hy$. In particular if $H$ is finite then $xH=Hx=Hy$.
Proof Take $H=K$ in Theorem 2, yielding $Hx=Hy$. If $H$ is finite then $xH \subseteq Hy$ implies $xH=Hy$ and the result follows.


How to show that each member of a sequence of functions is bounded?

Question: The question I am working on is: Let $f_n(x) := \dfrac{nx}{1 + nx^2}$ , for $x ∈ A := [0, ∞)$. Show that each $f_n$ is bounded on $A$.
I started by taking the derivative to get $f_n'(x)$= $n(1+nx^2)-2n(nx)$ but I'm not sure whether this is the right direction. I then noticed that $0<f_n(x)<nx$, but I'm not sure if this counts as an upper bound because it still has both of the variables $n$ & $x$ in it. Any help/direction would be appreciated!
Comment: Taking a derivative could be a good approach. Just keep in mind that taking derivatives just for fun wouldn't lead you anywhere. There must be a reason to do so. Perhaps, seeing where it vanishes, and what's going on elsewhere?
Answer: I think its more clear to break into two cases.  First, consider $x \geq 1$.  Then,
$$f_n(x) = \frac{x}{1/n+x^2} < \frac{x}{x^2} = \frac{1}{x}.$$  That is, for $x \geq 1$, the function is bounded above by the function $1/x$ which is in turn bounded by $1/1 = 1$.  Now, consider $0 < x <1$.  Then, we let $y = 1/x$, so that $y >1$.  Then,
$$f_n(x) = f_n(1/y) = \frac{n}{y+n/y} < \frac{n}{y} < n.$$
Finally, for $x = 0$, the function has value of zero, so bounded.
This way you avoid derivatives, but the answer above gives you a tighter bound.
Answer: If $0\le x < 1$ then
$$
f_n(x)
=
\frac{nx}{1 + nx^2}
\le
nx < n
$$
and if $x\ge 1$ then
$$
f_n(x)
=
\frac{nx}{1 + nx^2}
\le
\frac{nx^2}{1 + nx^2} < 1
$$
so $f_n$ is bounded above by $n$.
Answer: You had a good idea with derivatives. Note that $$ f_n'(x) = \frac{n(1+nx^2) - 2nx(nx)}{(1+nx^2)^2} = \frac{n-n^2x^2}{(1+nx^2)^2}.$$
It has unique zero point (on the set $A$) at a point $x = \frac{1}{\sqrt{n}}$. Moreover, $f_n'(x) >0$ for $x \in [0,\frac{1}{\sqrt{n}})$ and $f_n'(x) < 0$ for $x \in (\frac{1}{\sqrt{n}},\infty)$, hence $x = \frac{1}{\sqrt{n}}$ is a maximum of $f_n$. Hence $$  \sup_{x \in A} f_n(x) =  f_n(\frac{1}{\sqrt{n}}) = \frac{\sqrt{n}}{1+1} = \frac{\sqrt{n}}{2}. $$ From this we see that $f_n$ is bounded on $A$ (note that $\sqrt{n}$ is a constant for any given $f_n$, hence it isn't problematic. But as we see, $\sup_n \sup_x f_n(x) = \sup_n \frac{\sqrt{n}}{2} = \infty$, so that $(f_n)$ isn't uniformly bounded on $A$).


Backup of KVM guests when using qcow2 disk files

Question: I got a Ubuntu (hardy) system used for virtualization using KVM. Each guest got it's own qcow2 file used as disk. Guests are running Ubuntu (hardy). What would a good backup strategy be for such a setup? I would prefer not to shutdown the guests during backup.
Answer: You'll want to coordinate that within the guest .. ideally you:

Cause any RDBMS running in the guest to flush its cache
Tell Linux to sync disks (sysrq S or just type 'sync')

Then just make a qcow2 snapshot of the guest. You then have a read-only immutable copy of the guest FS as it was when you took the snapshot.
This page offers a lot more information than you probably wanted to know on how snapshots (and qcow2 itself) works. See also the accepted answer to this question.
Comment: Can I do the snapshot "online"? Do you know of any tools that can help?
Answer: I was looking for similar solution,
now I'm using software RAID+LVM2 volume for libvirt storage, I've taken a snapshot and few times (about 8-10) I had to revert to backup and it worked, even if Win guest said: unclean shutdown.
I'm not using hardware RAID anyway, software is enough but prorably SCSI/SAS + HW RAID + battery backup is the best solution for LVM2 snapthots (due to double write to different places on hard disks when snapshot is taken). I always use full-filled RAW volume files or even direct attached drive/partition, recenty I've enabled write cache for VMs drives which increased write speed A LOT!
Now I'm considering QCOW2's built-in snapshots to turn off LVM2, becouse it's very slow when compared to RAW partition, like EXT4.


Requirements for a valid neural network activation function?

Question: What rules define a valid neural network activation function, excluding biological plausibility?  What set of principles do softmax, rectified linear units, hyperbolic tangent, sigmoid,  etc. follow?
"Valid" in this case means that it maintains the universal approximation capability.
Comment: Thank you. I defined "valid." What makes you think that "monotonically increasing" is "not a must"?
Comment: Strictly speaking, you have to define your word 'valid'. Otherwise, any function can be an activation function. However, those you mentioned have in common that they are monotonically increasing (which isn't a must, as far I can see).
Comment: If you are thinking about training it by backprop, maybe add an extra condition that the network be optimizable by backpropagation. In that case, i think continuous and piecewise differentiable may suffice. But not sure if what the math rigor version should be.
Answer: It must be a function of its inputs. It can be univariate or multivariate (for example, softmax). The more useful ones are often non-constant and continuous.
(Approximately) Monotonic functions have been found, empirically, to be better.
A few very successful activations are not monotonic however (Swish for example).
It does not even need to be one to one (see the softmax again, it's many to many, and the concatenated RELU, CRELU, which is one to many).
I think continuity is pretty much a must. The more heterodox-but-still-highly-useful ones like Maxout (element-wise maximum between several parallel layers) are continuous.
Answer: This wiki page 1 answers the question succintly. The really short answer is that the function only needs to be "nonconstant and bounded function"2
Comment: I think we are over the "bounded" part now.
Answer: First note that a neural network usually has more than one activation functions (the activation function in hidden layers is often different from that used in the output layer).
Any function that is continuous can be used as an activation function, including linear function g(z)=z, which is often used in an output layer.
Since only activation function can introduce nonlinearity to a network, and nonlinearity is indispensable for a neural network to make untrivial predictions, activation functions in hidden layers are usually nonlinear, e.g. relu, which is a piecewise linear function that introduces the most simple nonlinearity.


Imagem sobrepor div navbar do Bootstrap

Question: Estou precisando colocar a logomarca de uma empresa sobre a div navbar do Bootstrap, fazendo com que a metade fique sobre essa div e a outra metade fora (parte cinza) e que acompanhe o topo quando o usuário descer a tela. Vejam:

Tentei colocar dessa forma, mas não consegui:
.logo{
    z-index:99999999999;
    position: relative;
}

O Bootstrap:

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            About

            Services

            Contact

              Portfolio

              1 Column Portfolio
              2 Column Portfolio
              3 Column Portfolio
              4 Column Portfolio
              Single Portfolio Item

              Blog

              Blog Home 1
              Blog Home 2
              Blog Post

              Other Pages

              Full Width Page
              Sidebar Page
              FAQ
              404
              Pricing Table

Comment: E em telas menores quando o menu fica respondido, como vai ficar?
Comment: Oi Hugo. Gostaria de que na versão responsivo, o menu ao ser expandido, ficasse sobre a logo.
Answer: Cara basicamente é só vc fazer uma regra de media querie que bata com o mesmo tamanho do breacking point da navbar. No caso em @media (min-width:992px), ou seja, apenas para telas maiores que 992px, vc usa um translateY() para jogar o link da logo com a imagem um pouco para baixo, ficando metade pra fora da navbar.

Segue o código da imagem acima:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />

                  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

                  </button>

                        About

                        Services

                        Contact

                          Portfolio

                          1 Column Portfolio
                          2 Column Portfolio
                          3 Column Portfolio
                          4 Column Portfolio
                          Single Portfolio Item

                          Blog

                          Blog Home 1
                          Blog Home 2
                          Blog Post

                          Other Pages

                          Full Width Page
                          Sidebar Page
                          FAQ
                          404
                          Pricing Table

Comment: @Fox.11 sem problemas meu caro!
Comment: Perfeito Hugo. Muito obrigado mais uma vez.

Imagem sobrepor div navbar do Bootstrap


Postfix: Modify sender address based on recipient

Question: We have a Postfix server that receives mail from our application servers.  Senders are in the form firstname.lastname@example.com (where host.fqdn can vary, depending on source server) and recipients can be internal or external users.
Messages going to external users should have the sender changed to email@example.com.  I have tried using canonical maps, but since that is handled by the cleanup daemon, before any transport decisions are made, it would affect all sender addresses.
I have also tried creating a custom smtp transport with generic mappings and configuring transport_maps to use that custom smtp transport for external domains.  However, generic mappings affect both sender and recipient addresses.
Lastly, I've tried the following:

Create a custom smtpd daemon that specifies sender canonical maps and a unique transport table.
Send all externally addressed mail to that custom daemon.  Ideally, sender canonical maps would transform the sender address and the unique transport table would relay messages to the internet.

However, evidently, only one transport table can be used per Postfix instance.
I want to avoid creating an entirely new Postfix instance to accommodate this rewriting.  Any suggestions? (and thanks in advance)
Answer: Disclaimer: this answer won't work as intended when process email which had multiple recipients with both internal and external domain in it
With postfix multi instance, the solution would be trivial. Just setup transport_maps to second instance, then do rewriting in second instance.
Without multiple instance, you need two smptd processes, two cleanup processes and access map.The idea is do filtering in access maps instead in transport_maps. When an email has external domain recipient, it transported to second smtpd daemon. Then second smtpd daemon would call second cleanup daemon. First cleanup daemon won't have canonical maps parameter, while in second cleanup daemon, we will add that parameter to do rewriting.
In main.cf, define check_recipient_access in smtpd_*_restriction. For example:
smtpd_recipient_restriction =
   ...
   check_recipient_access hash:/etc/postfix/external-filter
   ...

In external-filter file define a filtering mechanism
external.example.com    FILTER smtp:[127.0.0.1]:12525

In this example we will setup second smtpd daemon listen in 127.0.0.1 port 12525.
Now, setup second smtpd and cleanup daemon in master.cf
[127.0.0.1]:12525  ....  smtpd -o cleanup_service_name=cleanup_rewrite

cleanup_rewrite .... cleanup -o canonical_maps=hash:/etc/postfix/mysender_rewriting

File mysender_rewriting would contains a sender mapping as you intended.


AngularJS ngRepeat Watchers Paradox

Question: I pick news from several news sources approx. every 5-10 minutes. I use AngularJS 1.5 and ng-repeat works great for several lists of the over 500 news items which I populate to DOM from the server. Trouble is, although I have used track by I still have a very high CPU usage whenever I use filters on this lists.
I have tried bindonce library i.e. bindonce ng-repeat to no noticeable gains. I have also used AngularJS 1.3+ feature :: which works but after which server updates don't replace the old content because :: makes the content immutable in the process.
Am wondering is there a way to stop AngularJS watching the lists of item in the ng-repeat UNTIL (this is the caveat) the next time I get new content from the server??
Comment: try with this http://blog.thoughtram.io/angularjs/2014/12/22/exploring-angular-1.3-disabling-debug-info.html
Comment: also keep one time binding for ng-repeat variables not for the list in your case
Answer: I would suggest:

Keep the :: for one time binding where possible, specially the ng-repeat variables.
Load the data and keep it in a service.
After getting the data, use $route.reload() to refresh the controller.

This way you are using onetime binding, but your view will be refreshed with data because the whole controller will be refreshed.

AngularJS ngRepeat Watchers Paradox


Consulta não ordena os registros por Asc/Desc

Question: Tenho uma tabela chamada cadcha (cadastro de chamada) no banco de dados onde são guardadas todas as ligações realizadas pelos funcionários de uma determinada empresa.
cadcha
--------------------------------------------------
nreg    |telefone      |telpretot    |ramaldestino
1110     35420000       0,79          5065

telpretot = valor da ligação
Realizei uma consulta que traz a moda estatísca pelo valor das ligações, e precisava que a mesma fosse ordenada pela quantidade decrescente, ou seja, o registro com a quantidade maior, vem primeiro.
SELECT COUNT(telpretot) AS qtde,
(CAST(telpretot AS DECIMAL(18,0))) as       preco
FROM cadcha
WHERE teldata = '08/03/2015'
GROUP BY (CAST(telpretot AS DECIMAL(18,0)))
ORDER BY qtde DESC;

Está funcionando ok, porém é retornado o registro ordenado do menor para o maior. Já tentei alterar o DESC para ASC mas o resultado exibido é o mesmo.

Como posso corrigir o script para que os registros sejam ordenados do maior para ao menor?
Comment: tira o group by e tenta de novo.
Comment: qual o tipo do campo `telpretot` ?
Answer: Isso acontece porque a coluna qtde esta sendo preenchida no tempo de execução, pelo fato de você esta usando COUNT(telpretot), tente dessa forma.
declare @cadcha table
(
  nreg int,
  telefone int,
  telpretot numeric(18,2),
  ramaldestino int,
  teldata date

)

insert into @cadcha values
(1110,     35420000 ,      0.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      0.3   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      0.5   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      5.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      6.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      10.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      110.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      32.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      32.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      34.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015'),
(1110,     35420000 ,      44.79   ,       5065, '08/03/2015')

select * from
(
    SELECT COUNT(telpretot) AS qtde,
    (CAST(telpretot AS DECIMAL(18,0))) as       preco
    FROM @cadcha
    WHERE teldata = '08/03/2015'
    GROUP BY (CAST(telpretot AS DECIMAL(18,0)))
)D
ORDER BY qtde DESC;

Comment: @antunesleo_ fiz um teste utilizando o `sql server` e não tive esse problema, talvez o banco de dados que você esta usando possa ter alguma implicação para não estar ordenado da forma que você quer.
Comment: Descobri onde estava o problema. No sistema quando se está logado como ADM, tem uma tela onde podemos executar scripts SQL e estava realizando todos os testes por lá. Fiz um teste utilizando o IBExpert e o resultado veio ordenado do maior para o menor, como eu precisava!
Comment: Rodou de boa, porém ele continua ordenando apenas do menor para o maior.
Comment: você pode posta seus dados do select sem o group by  só os dados do  `SELECT telpretot AS qtde,
(CAST(telpretot AS DECIMAL(18,0))) as preco
FROM cadcha
WHERE teldata = '08/03/2015 `
Comment: Também desconfio que seja algum problema com o SBDB (firebird) ou alguma limitação do mesmo, pois quando eu mando a query ordenar pelo campo `preco` tanto ASC/DESC funcionam, porém pelo campo `qtde` ele sempre volta ordenado do menor para o maior. De qualquer forma, a ajuda de vocês abriu minha cabeça para outra lógica que deu certo aqui, obrigado pelo a ajuda!
Comment: @antunesleo_ o campo telpretot é de que tipo?:
Comment: tipo `DOUBLE PRECISION`
Comment: você já tentou retira o `CAST` do campo `telpretot` para ver como ele se comporta?
Answer: E esse group by ai, remove ele
SELECT COUNT(telpretot) AS qtde,
(CAST(telpretot AS DECIMAL(18,0))) as preco
FROM cadcha
WHERE teldata = '08/03/2015'
ORDER BY qtde DESC;

Comment: Eu preciso do group by na query para agrupar por valor, exemplo, agrupo todas as ligações de 1 real e quanto quantas ligações. Agrupo ligações de 2 reais e conto quantas ligações. Teria alguma forma de ordenar isto com o group by?


Integral of a piecewise function

Question:
Check whether the integral $\int_{-1}^2{f(x)[2x+1]}dx$ exists where
  $$f(x)=
\begin{cases}
x+2, &\text{$x<0$}\\
1, & \text{$x=0$}\\
xe^{x^2},& \text{$x>0$}
\end{cases}$$
  and $[x]$ denotes the greatest integer function. If it exists then calculate the integral.

I'm clueless about how to do the whole proof by definition stuff. Is there a way to prove that this function is integrable without any epsilon/delta and partition proofs?
Comment: Yes, you can split the interval $[-1,2]$ into finitely many subintervals, on each of which the function is continuous, hence integrable.  There may be finitely many points where the function is discontinuous, but they don't affect the value of the integral.
Comment: To be integrable why is continuity needed
Comment: It is integrable split the integral up into different bounds and plug in the corresponding value for $f$ defined in those intervals
Comment: Yeah I have an idea how to calculate it but is my argument valid
 ( integrable cause of the continuity)?
Comment: It is not continuous
Comment: Continuity is not the enough to have integrability. Here it is because you deal with compact intervals that also gives you boundedness. The argument would fail for other f(x)
Answer: Because of the fact that the discontinuities of $f(x)$ are of measure zero, the function is Riemann integrable. A proof of this exists here. This means we can validly take the integral of $f(x)$ on either side of the discontinuity and sum those:
$$\int_{-1}^{2} f(x)[2x+1]dx = \int_{-1}^{0}(x+2)[2x+1]dx + \int_{0}^{2}xe^{x^2}[2x+1]dx$$
Next, because $[2x+1]$ is the same value on for any x in the interval $[n, n+\frac{1}{2})$ where $n \in \mathbb{Z}$ and these new discontinuities are also of measure zero, we can seperate this into a larger sum with each value of $[2x+1]$ written out.
$$-1 \cdot \int_{-1}^{-\frac{1}{2}} (x+2)dx + 0 \cdot \int_{-\frac{1}{2}}^{0} (x+2)dx + 1 \cdot \int_{0}^{\frac{1}{2}} xe^{x^2}dx + 2 \cdot \int_{\frac{1}{2}}^{1} xe^{x^2}dx + 3 \cdot \int_{1}^{\frac{3}{2}} xe^{x^2}dx + 4 \cdot \int_{\frac{3}{2}}^{2} xe^{x^2}dx$$
Now we remove the term that is multiplied by $0$ and find $\int_{a}^{b} xe^{x^2}dx$ by setting $u=x^2$ and finding that $du=2xdx$.
$$-\int_{-1}^{-\frac{1}{2}} (x+2)dx + \frac{1}{2}\int_{0}^{\frac{1}{4}} e^{u}du + \int_{\frac{1}{4}}^{1} e^{u}du + \frac{3}{2}\int_{1}^{\frac{9}{4}} e^{u}du + 2\int_{\frac{9}{4}}^{4} e^{u}du$$
Finally we take the antiderivatives and evaluate.
$$-\left[\frac{x^2}{2}+2x\right]_{-1}^{-\frac{1}{2}}+\frac{1}{2}[e^u]_{0}^{1/4}+[e^u]_{1/4}^{1}+\frac{3}{2}[e^u]_{1}^{9/4}+2[e^u]_{9/4}^4$$
$$=-\left(\frac{1}{8}-1-\frac{1}{2}+2\right)+\frac{e^{1/4}-1}{2}+\left(e-e^{1/4}\right)+\frac{3e^{9/4}-3e}{2}+\left(2e^4-2e^{9/4}\right)$$
$$=-\frac{9}{8}-\frac{e^{1/4}}{2}-\frac{e}{2}-\frac{e^{9/4}}{2}+2e^4$$
$$=\frac{16e^4-4e^{9/4}-4e-4e^{1/4}-9}{8} \approx 101.326$$

Integral of a piecewise function


Godaddy hosted domain vs paid domain

Question: This is probably going to get downvoted into oblivion, but here it goes.  The company I work for has a deluxe hosting plan on Godaddy.  They have a hand full of domains registered under the same hosting account (for different product lines).  When I expand the "domains" tab, I can see only these few domains.  However under the hosing tab there is "9 Hosted domains"  Many of which I recognize as belonging to my boss' brother for his company.
All of the domains work perfectly fine.
I found this artice from godaddy : https://ca.godaddy.com/help/add-domains-8342
So, am I to understand that I can just add domains as I please for free? And if so, why would anyone bother paying for a second or third domain?  Is there some fundamental difference between a "hosted domain" and one I would have to pay for yearly?
Answer: You can ADD them to the hosting configuration. Unless you pay for them that is just a piece of junk configuration in the host. Did you bother reading the link you sent to the end? IN the "What's next" section it is quite clear that the domain does not magically get registered for free.
Adding the domain to the domains in your hosting account does not make it a registered domain - which has to be done separately and is paid for all relevant domain types.
Comment: I did read it.  It says "We automatically update the domain name's DNS. You don't need to do anything!"  So why is it when I navigate to one of those other domains, they work fine? Neither can I find billing history for them.
Comment: never mind, I ran a whois on those other domains to find they are hosted elsewhere.  Makes sense now, thanks.

Godaddy hosted domain vs paid domain


Error opening eclipse from android ADT bundle download

Question: I downloaded the ADT bundle for windows in the android developers website. I'm expecting that once I extracted them on my C: it will just run smoothly. Unfortunately, I'm getting this error

Any ideas on what's causing this? Already downloaded java from oracle website. C:\Program Files\Java\jdk1.7.0_25.
Edit:
For those asking the version of my OS. Here it is.

So I'm sure I downloaded the right version of the ADT.
Answer: It seems like you have downloaded wrong version of Adt. Are you sure that it is suitable for your pc? Is your computer 64-bit?
Comment: Yes. I can guarantee that.
Answer: Check if it's the 32-bit or 64-bit version. If that doesn't work, re-install java. The jvm.cfg file is an internal file and should not really be touched, but it seems Google might have a custom one for the emulator or something. If that still doesn't work, open SDK Manager and install everything they have. Otherwise I dunno.
Answer: I don't know what is the real problem but I uninstall JRE and install again ..Now its perfectly working .


Merge two keys of a single dictionary in python

Question: For a dictionary "a", with the keys "x, y and z" containing integer values.
What is the most efficient way to produce a joint list if I want to merge two keys in the dictionary (considering the size of the keys are identical and the values are of interger type)?
x+y and y+z ? .
Explanation:
Suppose you have to merge two keys and merge them into a new list or new dict without altering original dictionaries.
Example:
a = {"x" : {1,2,3,....,50}
     "y" : {1,2,3,.....50}
     "z" : {1,2,3,.....50}
    }

Desired list:
x+y = [2,4,6,8.....,100]
y+z = [2,4,6,......,100]

Answer: It seems like you're trying to mimic a join-type operation. That is not native to python dicts, so if you really want that type of functionality, I'd recommend looking at the pandas library.
If you just want to merge dict keys without more advanced features, this function should help:
from itertools import chain
from collections import Counter
from typing import Dict, List, Set, Tuple

def merge_keys(data: Dict[str, Set[int]], *merge_list: List[Tuple[str, str]]):
    merged_data = dict()
    merged_counts = Counter(list(chain(*map(lambda k: list(data.get(k, {})) if k in merge_list else [], data))))
    merged_data['+'.join(merge_list)] = [k*v for k,v in merged_counts.items()]
    return merged_data

You can run this with merge_keys(a, "x", "y", "z", ...), where a is the name of your dict- you can put as many keys as you want ("x", "y", "z", ...), since this function takes a variable number of arguments.
If you want two separate merges in the same dict, all you need to do is:
b = merge_keys(a, "x", "y") | merge_keys(a, "y", "z")

Note that the order of the keys changes the final merged key ("y+z" vs "z+y") but not the value of their merged sets.
P.S: This was actually a little tricky since the original dict had set values, not lists, which aren't ordered, so you can't just add them elementwise. That's why I used Counter here, in case you were wondering.
Comment: Thank you for the technique.
Answer: A very efficient way is to do convert the dictionary to a pandas dataframe and allow it to do the job for you with its vectorized methods:
import pandas as pd

a = {"x" : range(1,51), "y" : range(1,51), "z" : range(1,51)}

df = pd.DataFrame(a)
x_plus_y = (df['x'] + df['y']).to_list()
y_plus_z = (df['y'] + df['z']).to_list()

print(x_plus_y)
#[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]

Comment: Thank you! I really appreciate it
Comment: Thank you! I did it..I am unable to upvote because of the low reputation :P
Comment: I increased your reputation by upvoting your question. You should now have the privilege.
Comment: Thank you for your time, I upvoted the answer.


executar uma função quando for clicado no botao

Question: Estou tentando fazer que só mande para o banco de dados quando clicar no botão porem toda vez que a pagina e carregada ele envia mesmo não clicando no botão.  Esse e o código q estou usando

<button onclick="myFunction()">Click me</button>
";
        $TS2= $ts;
        $sql ="INSERT INTO `ss`(`nome`) VALUES ('$TS2')";
        $query = mysqli_query($link, $sql) or die(mysqli_error());
        ?>";
}
</script>

se tiver como fazer conexão com o banco de dados via javascript e seja seguro fico feliz em saber tambem
Answer: Não é possível executar códigos php no lado do cliente, vocẽ deve usar AJAX para isso:
No JavaScript (JQuery):
$('#input').on('click', function(){
    $.ajax({
        //Para aonde vai a requisição (um outro arquivo)
        url: 'arquivo_php.php',
        //Os dados que devem ser passados (adicione um id ao input e coloque no lugar de #input)
        data: {ts: $('#input').val()},
        //Como vai ser passados os dados (o mesmo method do form)
        method: 'POST',
    }).done(function(data) {
        //Quando finalizar a requisição com sucesso
        alert('Concluído com êxito');
    }).fail(function(error) {
        //Quando finalizar a requisição com falha
        alert('Erro: ' + error);
    });
});

No php (arquivo_php.php):
<?php
    include 'conect.php';
    //Dado passado por post pelo ajax
    $TS2= $POST["ts"];
    $sql ="INSERT INTO `ss`(`nome`) VALUES ('$TS2')";
    $query = mysqli_query($link, $sql) or die(mysqli_error());
?>

Observação: a tag <button> por padrão é do tipo submit, ou seja, ao ser clicada dentro de um formulário a página vai ser submetida, para que isso não ocorra defina o seu tipo como botão
<button type="button">Enviar</button>

Comment: obrigado ajudou muito


create Partition is not working in Azure Sql server

Question: I am trying to Create Partition in my azure Sql server.
my Sql server version is :- 11.0.9231
and my query is
USE [dbName]
GO

-- Create the partition function
CREATE PARTITION FUNCTION PF_HASH_BY_VALUE (BIGINT) AS RANGE LEFT
FOR VALUES (100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000)
GO

Below is my  error message:-
Msg 40510, Level 16, State 1, Line 5
Statement 'CREATE PARTITION FUNCTION' is not supported in this version of SQL Server.

now on this bloq says it's working with sql server which are later from 2008.
https://msdn.microsoft.com/en-us/library/ms187802.aspx
then why i got error message, can any one give me idea about it.
Regards,
vinit Patel
Comment: What is your sql server edition.is your database on SQL Azure ?
Answer: Azure SQL Server is not regular SQL Server. There are lots of queries that are not supported in Azure SQL. For example, Cross referencing different database within same Azure SQL server is not supported but was supported in regular SQL Server (or Express edition).
Also, I will advise to upgrade to v12 if it is compatible, as V12 has lot more query support and feature then v11 as you are running.
Comment: ok, but this same query is also not working in my local sql server, my local sql server version is 10.0.2531, in this i got issue is Partition function can only be created in Enterprise edition of SQL Server. Only Enterprise edition of SQL Server supports partitioning.
Comment: I am not sure of which Version support it, but yes I think Express edition might not support it, But if reply is what you get then surely there is nothing anyone can do about it. It is simply not supported. Upgrade to right version :).
Comment: ok let me talk with system admin and update it thank you so much for guideline


What is the Meaning of a Trivector

Question:
When we take the wedge product of 3 vectors result is, $$ {\displaystyle \mathbf {u} \wedge \mathbf {v} \wedge \mathbf {w} =(u_{1}v_{2}w_{3}+u_{2}v_{3}w_{1}+u_{3}v_{1}w_{2}-u_{1}v_{3}w_{2}-u_{2}v_{1}w_{3}-u_{3}v_{2}w_{1})(\mathbf {e} _{1}\wedge \mathbf {e} _{2}\wedge \mathbf {e} _{3})} $$
Scalar part is the volume of the parallelepiped and trivector part is the "direction" of that volume. But what's that mean at all?
I've no problem with directional lines such as vectors, we're using them in many fields and they're pretty useful.
But in the case of directional volumes it's really hard to imagine.
Are they practically used in any field? And what do they represent in real world?
Comment: Are you comfortable with the geometric interpretation of **bivectors** $\mathbf{u} \wedge \mathbf{v}$ to begin with?
Comment: @HansLundmark I can understand bivectors and i think they might be useful. my problem is trivectors.
Answer: Trivectors in $\mathbf{R}^3$ are perhaps not that interesting, just like a flatlander living in $\mathbf{R}^2$ would perhaps struggle to see what the point with bivectors is. After all, in $\mathbf{R}^2$ any wedge product $\mathbf{u} \wedge \mathbf{v}$ just equals a constant times the bivector $\mathbf{e}_1 \wedge \mathbf{e}_2$ (and that constant is of course plus or minus the area of the parallelogram whose edges are given by the vectors $\mathbf{u}$ and $\mathbf{v}$).
But in $\mathbf{R}^3$, the wedge product $\mathbf{u} \wedge \mathbf{v}$ is more interesting, since it somehow represents a "two-dimensional direction", the subspace (or plane) spanned by $\mathbf{u}$ and $\mathbf{v}$ (with an orientation). And there are infinitely many such two-dimensional subspaces here, not just one like in $\mathbf{R}^2$.
Similarly, in higher dimensions, like in $\mathbf{R}^4$ to begin with, a triple wedge product $\mathbf{u} \wedge \mathbf{v} \wedge \mathbf{w}$ not only has a magnitude (the three-dimensional volume given by the three vectors), it also represents a "three-dimensional direction", namely the (oriented) subspace spanned by $\mathbf{u}$, $\mathbf{v}$ and $\mathbf{w}$. And there are infinitely many such three-dimensional subspaces here, not just one like in $\mathbf{R}^3$.
That said, bivectors are actually conceptually useful already in $\mathbf{R}^2$. For example, one can use a complex number $a+ib$ to rotate another complex number $c+id$ (by multiplication), but it's conceptually better to use the bivector $a+b \mathbf{I}$ (where $\mathbf{I}=\mathbf{e}_1 \wedge \mathbf{e}_2$) to rotate the vector $c \mathbf{e}_1 + d \mathbf{e}_2$ (by conjugation), since that's how rotations work in higher dimensions, where the algebraic objects representing the rotations are of a different kind than the vectors being rotated. And it's also nice to have trivectors in $\mathbf{R}^3$, since they have a natural role to play in the Clifford algebra.

What is the Meaning of a Trivector


Como adicionar as informações de referência no Visual Studio 2017?

Question: Em algumas oportunidades vendo alguns colegas usando o VS 2017, e até mesmo quando eu usei um configurado por outra pessoa, notei que existem informações sobre as referências a uma classe.
No exemplo abaixo, veja como está hoje:
public class Email
{
    public string EnderecoEmail { get; set; }
}

E abaixo, como eu gostaria que ficasse:
0 references
public class Email
    {
        0 references
        public string EnderecoEmail { get; set; }
    }

Como configuro para que meu VS exiba esse tipo de informação?
Answer: Tools → Options → Text Editor → All Languages → CodeLens

ou
Ferramentas → Opções → Editor de Texto → Todos os Idiomas → CodeLens

O CodeLens não está disponível na Community Edition. Porém no Visual Studio 2015 pode ser instalado o CodeLens ao instalar o SSDT.
Referência:
https://stackoverflow.com/questions/42796941/visual-studio-2017-display-method-references


How to use grocery set_relation function to display content from two different tables in different columns

Question: I have to tables with these schema:
users(id, name, email)
user_details (id, user_id, physical_address, otherinfo)

I would like to display all contents of both tables in one grid using grocery crud
when i try to use set relation on the first table as shown: Note: I have reducted the part that does the rendering of the view;
$crud = new grocery_CRUD();
$crud->set_table('users');
$crud->set_relation('id', 'user_details', '{physical_address} + {otherinfo}');

the values of the id field as well as the referenced table don't appear in the grid, so it does not seem to work when using primary keys.
So I decided to start with the contents of the second table like so:
$crud = new grocery_CRUD();
$crud->set_table('user_details');
$crud->set_relation('user_id', 'users', '{name} + {email}');

This works, but the problem is that the values appear in one column in the grid. I would like to know how i can separate them to different columns and make them editable in separate input fields.
Answer: my way kinda ridiculous,
if i were really need the field to be separated, i might use callback_column then use active records to return the value using $row->user_id, and callback each record
just like:
return $this->some_model->get_name($row->user_id); for name field
and
return $this->some_model->get_name($row->user_id); for email field
but, as i tested with some dummy records, it can't be sorted, (i dont know if anyone could)
Answer: There is no direct way to show multiple columns but i found an work around for this problem.
here is how
set name column as follows.
$crud->columns('name','email'); // define all required columns
$crud->callback_column(unique_field_name('user_id'),array($this,'callback_set_user_name'));

function unique_field_name($field_name)
{
    return 's'.substr(md5($field_name),0,8);
}

public function callback_set_user_name($value, $row)
    {
        $row->full_name = $row->s447d3092; // before getting to know s447d3092 key return json_encode($row); you will key pair with {name} + {email} ex: {"s447d3092":"shiva + firstname.lastname@example.com"}
        return explode("+",$value)[0]; // here you will have only name
    }

$crud->callback_column('email',array($this,'callback_set_email'));

public function callback_set_email($value, $row)
    {
      return explode("+",$row->full_name)[1];
    }

I am 100% sure this will help you


What are these chords called?

Question: So I have these chords in my song, and was wondering what they're called. I've heard they might be classed as an 'inversion' or 'power chord', but I'm still learning musical jargon so any insight would be greatly appreciated. Thank you.
In the key of Bb Major/G Minor
G D Bb
I'm assuming this one is Gm inverted?
F F A
I think this one would be a power chord, or F Major but without the C? This one has really stumped me.
Eb Bb G
This feels like Eb Major Inverted.
D A F
D minor Inverted maybe?
Answer: Chord inversion generally refers to changing the bass note of a chord to something other than the root note of the chord.  Thus, if you played G minor chord with the notes G-Bb-D but put the Bb in the bass (so, Bb-G-D or Bb-D-G), then it would be called "inverted".
Power chords, meanwhile, tend to refer to open fifth chords.  That is, you only have the root and fifth of the chord.  If you played F-C by itself, that could be a power chord.  But F-F-A is more likely interpreted as an incomplete F major chord.
Anyhow, what you're really referring to here is known as chord spacing or chord voicing (which mean roughly the same thing for your examples).  Take a look at the examples in that Wikipedia link and see how you can move the notes of a chord to different octaves to create an "open voicing" or "open spacing" of a chord, versus the "closed voicing" or "close position" of a chord where the notes are right next to each other (e.g., G-Bb-D in the same octave).
Hence, your chords are simply G minor, F major (an incomplete chord, without the C), E-flat major, and D minor.  To make any of these "inverted" would require that you put a different note as the lowest (bass) note.
Comment: Thank you so much Athanasius! This has been really helpful. In terms of 'voicing' then, when does a chord become 'open', is it only after the chord is no longer a perfect triad? Or when one of the notes in that chord is in a different octave?
Comment: "Close position" means the voices are as close as possible, i.e., within the same octave.  Inverted triads can also be in close position, so G-Bb-D is "close position" but so would be Bb-D-G if they are in the same octave with Bb as the lowest note.  So yes, it becomes "open position" when you move a note to different octave so the notes aren't as close as possible.
Answer: These are the voicings I understand you are using...

...you can call those open voicing as compared to closed voicing where the closed voicing arranges the notes by thirds (or their permutations, ex. GBDF, BDFG, DFGB, etc...)

The second chord (F A) doesn't have three tones to make a complete triad. You can call that an implied or incomplete chord. Some degree of harmony analysis needs to be done to make a claim about what the incomplete chord is, but we will skip those details and just say this is an implied F major chord with the fifth of the chord omitted.
Power chord is a rock music thing where the third of the chord is omitted. Your progression as power chords would look like...

Inversion is when a tone other than the chord root is put in the bass. Another way to state that is: a bass line can be harmonized with chords other than root position chords. We could do that with your descending bass line G F Eb D like this...

...even though the bass is the same the chords are now Gm Dm Cm D7 where the Dm and Cm are in first inversion.
A typical reason for this kind of harmony is to avoid all the parts moving in parallel motion, meaning all the voice moving the same way.
Comment: Thank you so much for this Michael! It's been really helpful. And double thanks for providing me with examples on how to invert my chords, what they'd look like, and why they're used.
Comment: Closed voicings can also include a 4th. Consider a closed voiced 2nd inversion - G C E. 4th and 3rd.
Comment: @Tim, good point, I made an edit for that.

What are these chords called?


Uncaught TypeError: b(...).unload is not a function in jquery-3.2.1

Question: Getting the above error after upgrading jquery from 1.6.2 to 3.2.1. But not able to find the unload function anywhere in the library to make changes
Comment: Possible duplicate of [TypeError: $(...).unload is not a function - JQuery 3.1.0](http://stackoverflow.com/questions/39030910/typeerror-unload-is-not-a-function-jquery-3-1-0)
Comment: Please update your question and add the actual error to the body with proper formatting. Also, provide more information about your project.
Comment: Try and take a look at http://stackoverflow.com/questions/39030910/typeerror-unload-is-not-a-function-jquery-3-1-0
Comment: @Soviut the accepted answer on this question you link to is a bad practice.
Comment: use this
Answer: This function was first deprecated in 1.8 and then removed.
You could in theory replace it with
<code>.on("unload", function(){
</code>
which it was a shortcut for.
But it was removed for a good reason: listening for this event is usually a bad practice. The truth is there's no real cross-browser and reliable solution to handle page termination. The real solution is to avoid relying on this event.  You must design your application so that you don't have anything to do on page closing.
Comment: Maybe in another imported 3rd lib script?


How to configure addition library folders for Visual Studio 2013?

Question: I have legacy, non Visual Studio project. Its structure is:
-root_folder
-root_folder/folder1
-root_folder/folder1/main.cpp
-root_folder/folder1/fun.cpp
-root_folder/folder2
-root_folder/folder2/bar.cpp
-root_folder/folder2/foo.h
.... many different folders

I work with project under folder1.
root_folder/folder1/main.cpp:
#include <folder2/foo.h>
....

I have the error: Error can not open source file "folder2/foo.h>".
Of course, I added the folder root_folder in Project -> properties -> c/c++ section -> additional include directories.
I cannot change this source code, so I need right configure project settings.
Also, I have one more problem. Visual studio does not show my folders structure. It just show folder Source Files, which contains all thousands files.
Comment: you need to use `project properties -> vc++ directories -> include directories`; add the path you need there
Comment: @twentylemon, I added root folder in this place, The error still exists.
Comment: Try using `#include "folder2/foo.h"` instead of `#include `
Comment: About the folder structure, select the project in the Solution Explorer and press "Show all files" on the bar on top.
Comment: @Banex, it works, but I cannot change this code.
Comment: @Banex, About the folder structure, it works! Thank you.
Answer: Visual Studio looks in "VC++ Directories" -> "Include Directories" for the include files specified in angle brackets.
You need to add you path there:
https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k%28VS.ToolsOptionsPages.Projects.VCDirectories%29&rd=true
P.S. Just noticed that this answer was given earlier, and rejected.
However, it most certainly works; tested with VS2013.


PyCharm replaces characters in docstrings

Question: In the latest version of pycharm (2016.1)
There's a strange behavior - some characters in docstrings are mapped to other characters - only in the display - any workarounds?
Example:
<code>def main(self, args=None):
    """

    :param args: List of arguments, with the 'aws' removed.  For example,
        the command "aws s3 list-objects --bucket foo" will have an
        args list of ``['s3', 'list-objects', '--bucket', 'foo']``.

    """
</code>
looks like:
Comment: This looks like your theme font is corrupted. If you reset your profile to the default fonts and restart the IDE, do you see the same behavior?
Comment: @BurhanKhalid correct - the font changed somehow during the upgrade.
Write it as an answer and I'll accept it
Answer: This happens when your font gets corrupted in your profile. Due to many complications in font rendering in Java vs the OS, there are many things than cause such artifacts to be displayed.
The easiest way to solve this is to reset the font configuration for the theme and then restart the IDE.