Load image from photo library into my UIImageView but image does not change when I restart the app

Question: I have imageView and a button to upload image from photo library and keep it in the imageView i do documentDirectory so when I upload a photo to the imageView it save the image in the imageView even if I close the application.
But my problem is whenever I upload new photo it change without any problem. But when I close the app and start it again the old photo returns.
func saveImage(image : UIImage, imageName: String){
    let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    let fileURL = documentDirectoryPath.appendingPathComponent(imageName)
    if let data = UIImageJPEGRepresentation(image, 1.0),
        !FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try data.write(to: fileURL)
            print("Image saved")
        } catch {
            print("Image save error:", error)
        }
    }
}

func getImage(imageName: String) -> UIImage?{
    let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileURL = documentDirectoryPath.appendingPathComponent(imageName)
    let image = UIImage(contentsOfFile: fileURL.path)
    return image
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    imageView.image = image
    saveImage(image:image!, imageName: "profile.jpg")
    picker.dismiss(animated: true, completion: nil)
}

override func viewDidLoad() {
    super.viewDidLoad()

    if let image = getImage(imageName: "profile.jpg"){
        imageView.image = image}
    }

I was expecting the image change and will be save even when I close app.
But actually it always return to the first image I upload.
Answer: It looks like in saveImage, you are checking that the file exists already, and not doing the save if it does exist. That would mean that the first time you selected an image, it will save properly, but any further image picks will update the control, but not the file, which would cause the old image to appear again the next time you open the app. So you probably want to remove that fileExists check from your if altogether.
You can verify that is what's happening by adding an else to that if statement in saveImage that does a print(), and that should end up in your log file the second time you select an image:
if let data = UIImageJPEGRepresentation(image, 1.0),
    !FileManager.default.fileExists(atPath: fileURL.path) {
    // ...
}
else {
    print("File exists -- image not saved")
}

Comment: Sure thing! Added to the original answer.
Comment: still same result when close and open the app shows the old image
Comment: Did you look in the log to see if that message appeared? If it did, then you know it's the fileExists check is the problem, and that removing it is the solution.
Comment: [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
Comment: now its saying File exists -- image not saved even for the new picture and the old one dosent change
Comment: Okay, that verifies that the `FileManager.default.fileExists` condition is the problem. Remove that and give it a try.


Possible bug in Visual Studio when using "display:inline-block" & "line-height" together in design view

Question: CODE:
<%@ Page Language="VB" %>
<!DOCTYPE html>

    <title></title>

            Block 1

            needs to

            have a

            few rows

            of text

            that we

            can show

            to our

            viewers

            Block 2

Description:

Create a simple .aspx file in Visual Studio 2013
Create a parent container div with a visible border.
Create two child divs sized 200px x 200px.
Add the property display:inline-block; to the child divs
Add the line-height property to the child divs such as line-height:22px;.

Expected Results:
In Design-Time, the Parent Container div should wrap around both child divs
Actual results:
In design-view the Parent Container div will collapse behind the child divs
Right-click file and select "View In Browser", Parent Container div renders as expected
NOTES:

If you remove the line-height property the Parent Container div behaves normally
If you leave line-height and change display:inline-block; to float:lefts and clear them the Parent Container behaves normally as well.
They all view normally when viewed live in a browser.
Answer: Below is the result from this being filed as a bug report on Microsoft Connect:

Greetings from Microsoft Connect!
This notification was generated for feedback item: Possible bug in Visual Studio when using "display:inline-block" & "line-height" together in design view which you submitted at theMicrosoft Connect site.
Thank you for passing along this issue to us. We evaluate all the feedback our customers submit, but unfortunately we cannot fix every item that comes in. We have evaluated the issue you submitted, and at this point, we do not anticipate releasing an update for it. If the issue is blocking you from using the product, please contact our support via the Visual Studio Help and Support (http://msdn.microsoft.com/en-us/vstudio/cc136615.aspx) page on MSDN.
You may receive a general "Feedback Item Updated" notification as well, if any other changes were made by Microsoft.
Thank you for using Microsoft Connect!
Regards,
the Microsoft Connect Team
Microsoft admitted the BUG and goes on to say they aren't interested in fixing it for a peon like myself.  This is what happens when we create work-arounds instead of reporting bugs in volume............


How to make DIG honour TTLs / use the local OS cache?

Question: When I run dig example.com the response comes back with SERVER: 192.168.0.1, even on subsequent runs. That implies DIG is always making a network call to resolve the DNS record.
I (rather ignorantly) assumed that my OS would be caching the DNS record according to its TTL, and that DIG would be using that cache.
Does DIG ignore the TTL / not make use of caches by default? If so, how can I get DIG to use a cache and honor TTLs?
Background / X-Y Problem:
I want a way to quickly resolve DNS TXT records for an nginx script that I'm writing. The script will route requests based on the content of those TXT records, so I'd like whichever method I'm using to honour TTLs and use locally cached records where appropriate.
Answer: dig  (domain information groper) as the manual explains, is a flexible tool for interrogating DNS name servers,  it does not query or use your local DNS cache (and/or hosts file) but directly queries the name server you point it at.  By default that will be the one(s) from /etc/resolv.conf.
To use your systems DNS cache from the command line use getent hosts [ip-address | hostname] or in scripts/code use a native version of the man 3 gethostbyname system call.
Admittedly that does not help your with anything else beyond A AAAA or PTR records.

In dig output the SERVER label is ip-address of the name server dig uses, which will never have a TTL...
dig ANY www.google.com

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.47.rc1.el6 <<>> www.google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 27695
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 4

;; QUESTION SECTION:
;www.google.com.                IN      A

;; ANSWER SECTION:
www.google.com.     173     IN      A       126.96.36.199

;; AUTHORITY SECTION:
google.com.         146915  IN      NS      ns2.google.com.
google.com.         146915  IN      NS      ns3.google.com.
google.com.         146915  IN      NS      ns1.google.com.
google.com.         146915  IN      NS      ns4.google.com.

;; ADDITIONAL SECTION:
ns2.google.com.     145115  IN      A       184.108.40.206
ns1.google.com.     145115  IN      A       126.96.36.199
ns3.google.com.     145115  IN      A       188.8.131.52
ns4.google.com.     145115  IN      A       126.96.36.199

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)    <========== My Name SERVER is localhost
;; WHEN: Tue Aug 30 22:51:26 2016
;; MSG SIZE  rcvd: 184

I run my own caching DNS server locally rather than using an ISP's or Google's public resolver (126.96.36.199) mainly for spamassassin, which has the advantage of being local, but the cache doesn't get pre-seeded/populated by other users either.
Answer: This is really an OS resolver question at its heart, but you did not specify the operating system. Since dig is mentioned, I'm going to assume that we're working with some flavor of UNIX here.
UNIX based operating systems do not implement a DNS cache within the kernel itself. There are a few topics that need to be summarized before we get into how it's actually implemented.
NSS
Calls to the resolver library typically implement their lookups using Name Service Switch (NSS), a modular system for specifying data sources to use and the order in which they are looked up. You can find a list of these module stacks in /etc/nsswitch.conf. For reference, the one we're concerned with here is hosts.
It is not recommended to play with the hosts entry in /etc/nsswitch.conf unless you really know what you're doing. Reordering these modules can result in funky things like DNS consulted before the /etc/hosts file!
nscd
Prior to consulting the module stack, NSS checks for the presence of a running nscd socket and attempts to query it. If nscd is configured to maintain a cache for the NSS database in question, it's possible that an entry cached by nscd will be returned without the NSS modules being consulted. Most Linux distros that I know of do not enable caching of the hosts database by default, and /etc/nscd.conf must be customized.
That said, it should be noted that many administrators consider the "stock" nscd daemon to be unreliable, at least under Linux. There is at least one alternate implementation out there. Your mileage may vary.
Putting it all together
Knowing the above, the lookup order for the hosts database works in this order:

nscd (if running, its socket is present, and caching of hosts is enabled)
NSS modules, in the order listed in /etc/nsswitch.conf
If not found in a NSS module, it doesn't exist.

This brings us to where dig falls into this equation. You can pretty much refer to HBrujin's entire answer (dig doesn't use NSS, only talks over TCP/IP), but the catch is that there is no cache for NSS at all unless 1) nscd is running, and 2) it is configured to cache the hosts database.
tl;dr
The complexity of getting DNS caching to play nicely within NSS is usually why most admins go with the "simpler" solution of running their own recursive DNS server. You don't need to know a darn thing about NSS. Just point /etc/resolv.conf at your shiny new DNS cache and let it hide the evils of NSS from you. (at least until you need to learn how LDAP integration works)


A direct proof of the properties of the matrix of minors

Question: Let $A$ be an invertible $n\times n$ matrix.  Define the matrix of minors $\Delta(A)$ of $A$ to be the matrix whose $(i,j)$ entry is the determinant of the minor of $A$ with the $i$th row and $j$ column omitted.
Certainly, the most important property of $\Delta(A)$ is that it is instrumental in computing the inverse of $A$:
$$ A^{-1}= \frac{1}{\operatorname{det}(A)}\sigma\cdot \Delta(A)^T\cdot \sigma$$
where here, $\sigma$ is the diagonal matrix whose diagonal entries alternate $1$ and $-1$.
From this fact and elementary properties of the inverse, it is easy to prove the following

Taking the matrix of minors is an involution up to scaling; that is, $\Delta(\Delta(A))=\operatorname{det}(A)^{n-2}\cdot A$
Taking the matrix of minors is an group homomorphism; that is, $\Delta(AB)=\Delta(A)\Delta(B)$.

If you actually write out either of these identities in terms of minors, you get a series of non-trivial-looking identities on the minors of an invertible matrix.
Is this the easiest way to obtain these identities on minors?  It would bother me if it was, for a couple of reasons.  First, it seems extremely likely that the second identity above holds for non-invertible matrices.  Second, if $A$ is totally positive or non-negative (that is, every minor of every size is positive or non-negative), then so is $\Delta(A)$.  However, the inverse of a totally positive matrix will almost never be totally positive, and so the above proof of the identities will stray off the totally positive path.
Therefore,

Can the identities on minors implied by the above relations on $\Delta$ be proven in a more direct way?

Ideally, this proof would be 'subtraction-free', to make it more natural in the totally-positive setting.
Edit: I should be a little bit more clear about what sort of thing I am looking for.  I am interested in spaces of totally-positive matrices and the corresponding algebras generated by minors on them (specifically, they are cluster algebras).  An important involution of these spaces and algebras is the matrix of minors defined above.  Note that taking inverses or cofactors does not preserve totally positivity, and so it doesn't act on this space.
Mainly, I asked this question because I was annoyed at using a map whose properties couldn't be proven without passing to a different, bigger space (not that this doesn't happen all the time in math).  I was curious if there was a proof along algebraic lines, following only from the simplest relations on minors (the 3-term Plucker relations).
Comment: Every identity which is polynomial in the entries of the matrices involved and which holds for invertible matrices in fact holds for all matrices. This is a consequence of continuity or, as Bill prefers, of universality.
Comment: What exactly you mean by 'subtraction-free'? Do you have a subtraction free way of defining the actual minors?
Comment: While definition of the minors involve subtraction, the 3-term Plucker relations are most naturally written in a subtraction-free way.  This allows you to write all the minors of a matrix as subtraction-free expressions in a relatively-small number of minors (say, for instance, solid minors touching the left edge or the top edge).
Comment: I was hoping for a proof involving simpler minor identities (like Dodgson's identity), and combining/iterating it in a way which preserved positivity.  It isn't supposed to be a specific request, as much as using tools more 'native' to a theory than the existence of inverses.
Comment: I misinterpreted how much you care about positivity, so I deleted my answer.
Comment: It was a fine answer, I'm just sorry I'm not able to convey the sort of thing I am looking for.  Mostly, I was wondering if there was a well-known 'simple' proof of these things independent of its relation to inverses and cofactors, and I suspect the answer is no.
Answer: Combinatorial interpretation
Let's start with a combinatorial interpretation of $\Delta(A)_{i,j}$. It is a weighted sum of terms, each of which corresponds to a directed $1$-regular graph. Each term is the product of the corresponding entries of $A$, only we don't count the $(j,i)$ edge. In other words, the graph is not really $1$-regular, since $i$ has no in-edge and $j$ has no out-edge; so there is an $i$ to $j$ path, and the rest are circles. Each term is weighted according to the sum of the permutation.
Multiplicativity
Now $\Delta(AB)_{i,j}$ is the same thing, only each $(x,y)$ edge really corresponds to a pair of edges $(x,z),(z,y)$, with $z$ arbitrary. Suppose a vertex $z$ appears twice, in both $(x_1,z),(z,y_1)$ and $(x_2,z),(z,y_2)$. Replace this wiring to the wiring $(x_1,z),(z,y_2)$ and $(x_2,z),(z,y_1)$. This corresponds to a transposition, and so the sign is opposite and the two cancel. We are left with only the terms where each vertex appears at most once as an intermediate.
Similarly, in $(\Delta(A)\Delta(B))_{i,j}$ we have two graphs superimposed, with an $i$ to $j$ path composed of an $A$ part followed by a $B$ part. We can now construct a $\Delta(AB)_{i,j}$ path in the obvious way; this is a reversible process (the missing $z$ vertex is the one in the middle of the $i$ to $j$ path). Since sign is multiplicative, the signs agree.
 Involution up to scaling
Consider now $(\Delta(\Delta(A))_{i,j}$. On the first level, we have an almost $1$-regular graph, with some $i$ to $j$ path. On the second level, each edge $x,y$ on the first level corresponds to some $1$-regular graph with some $x$ to $y$ path.
Let's count the in- and out-degrees of all the vertices. We start with $n-1$ each. For each edge $(x,y)$, remove $1$ from the in-degree of $x$, and $1$ from the out-degree of $y$. Every vertex other than $i$ has an incoming edge, and every vertex other than $j$ has an outgoing edge. Let's assume that $i \neq j$ (the other case is simpler). Thus the out-degree of $i$ is $n-1$, and of every other vertex it is $n-2$; the in-degree of $j$ is $n-1$, and of every other vertex it is $n-2$.
Suppose the path from $i$ to $j$ is not direct, for example $i$ goes to $k$ goes to $l$ (which might equal $j$). It is possible that if you're cunning enough, you will be able to permute $k$ and $j$ in such a way that the result will have the same value but opposite sign. Given that, we are left only with terms in which the $i$ to $j$ path is direct. The rest of the multigraph is just an arbitrary $(n-2)$-regular graph, which explains the factor $(\det A)^{n-2}$.
It remains for someone in the audience to find the correct cut-and-paste argument...


4 cards are shuffled and placed face down. Hidden faces display 4 suits: spades, clubs, diamonds, hearts. You turn over cards until win or lose

Question: Problem: 4 cards are shuffled and placed face down. Hidden faces display 4 suits: spades, clubs, diamonds, hearts. You turn over cards until win or lose. You win if you turn over spades AND clubs. You lose if you turn over hearts. Find P(win)
I can't seem to find what's wrong with my approach.
Law of total probability:
$P(lose) = P(lose | H_1) * P(H_1) + P(lose | H_2) * P(H_2) + P(lose | H_3) * P(H_3) + P(lose | H_4) * P(H_4)$
where $Hx$ denotes the Hearts card being in the $x^{th}$ position
$P(lose) = 1/4 * 1 + 1/4 * 1 + 1/4 * (1/4)^2 + 1/4 * 0 = 0.515625$
If Hearts is in either 1st or 2nd position, we always lose. If Hearts is in 3rd position, we lose if Spades & Clubs are exactly in 1st and 2nd position, which happens with $P = (1/4)^2$, in the last scenario we cannot lose
$P(win) = 1-P(lose) = 0.484375$
But the official answer is $2/3$, so I don't know where I went wrong. Please also explain the correct answer like I'm 5.
Thanks for your help!
Comment: Even after fixing $P(lose \mid H_3)$, your $P(lose) \ge \frac12$ while in the official answer $P(win) = \frac23$, so something is wrong in the official answer.
Answer: I think your problem is that your tree of possibilities needs pruning.  You also are missing a conditional probability: The probability of spades and clubs being the first two given the heart being 3rd is not 1/16 but rather 1/3.
This problem is more easily done by drawing the tree.
Comment: This helped me the most conceptually. Given there are only 3 spots left, P(spades & clubs are the first two cards) can be calculated 2 ways: 1) P(spades 1st clubs 2nd) + P(spades 2nd clubs 1st) = 2 * (1/3)^2 = 2/3.  ;;;;; 2) P(diamonds not in 4th position) = 1-(1/3) = 2/3
Answer:
If Hearts is in either 1st or 2nd position, we always lose.

Correct. This happens with probability $\frac{1}{2}$.

If Hearts is in 3rd position, we lose if Spades & Clubs are exactly in 1st and 2nd position.

This is not correct. You lose if Diamonds is in either 1st or 2nd position. This happens with probability $\frac{1}{4}\times \frac{2}{3}=\frac{1}{6}$.
The probability of losing is therefore $\frac{1}{2}+\frac{1}{6}=\frac{2}{3}.$
Answer: Think about where the diamond may be when given that the heart is somewhere.
We lose if the heart is in position 1 or 2, or if the heart is in position 3 and the diamond is not in position 4.
$$\begin{align}\mathsf P(L)&=\mathsf P(H_1\cup H_2\cup(H_3\cap D_4^{\small\complement}))\\[1ex]&=\mathsf P(H_1)+\mathsf P(H_1)+\mathsf P(H_3)\;\mathsf P(D_4^{\small\complement}\mid H_3)\end{align}$$
When given that the heart is in position 3, the probability that the diamond is not in position 4 is: $2/3$.
$$\begin{align}\mathsf P(L)&=\tfrac 14+\tfrac 14+\tfrac 14\cdot\tfrac 23\\[1ex]&=\tfrac{2}{3}\end{align}$$


Maximising the area of a parallelogram

Question: Let $A=(p^2,-p), B=(q^2,-q), C=(r^2,-r)$ be the vertices of a $\Delta ABC$. A paralellogram $AFDE$ is drawn with $D, E, F$ on line segment $BC, CA, AB$ respectively. Show that the maximum area of such a parallelogram is $\frac{(p+q)(q+r)(p-r)}{4}$.
I have tried bashing with coordinates and exploiting the midpoint theorem of triangles but none of them have led to this elegant result. Our teacher says that an approach using vector geometry may work. How do I go about this problem?
Answer: I think the key here is that you have specified that $AFDE$ must be a parallelogram. So once you have decided on, say, the point $F$, the other points $D$ and $E$ are uniquely determined (draw a picture to see why).
Lets do this problem with vectors.
If $F$ must be on the edge $AB$, then we have the vector
$$\vec{AF} = t\vec{AB} = t(q^2-p^2,-q+p)$$
for some $t \in [0,1]$. Similarly, $E$ lies on $AC$, so
$$\vec{AE} = u\vec{AC} = u(r^2-p^2,-r+p)$$
for some $u \in [0,1]$.
Here, it might be easier to switch back to cartesian coordinate system for a moment. We know that $D$ lies on $BC$, so
$$D = vB+(1-v)C = (vq^2+(1-v)r^2,-vq-(1-v)r)$$
for some $v \in [0,1]$. We then obtain
$$\vec{AD} = (vq^2+(1-v)r^2-p^2,-vq-(1-v)r+p)$$
But note that we can express the vector $\vec{AD}$ in a number of different ways. The most important observation here is that $\vec{AD} = \vec{AE} + \vec{AF}$ due to the parallelogram law. Plugging in what he had:
\begin{align}
& \vec{AD} = \vec{AE} + \vec{AF} \\
\implies & (vq^2+(1-v)r^2-p^2,-vq-(1-v)r+p) = u(r^2-p^2,-r+p) + t(q^2-p^2,-q+p) \\
\end{align}
$$ \implies \begin{cases} vq^2+(1-v)r^2-p^2 = u(r^2-p^2) + t(q^2-p^2) \\
-vq-(1-v)r+p = u(-r+p) + t(-q+p) \end{cases} $$
$$ \implies \begin{pmatrix} r^2-p^2 & q^2-p^2 \\ -r+p & -q+p \end{pmatrix} \begin{pmatrix} u \\ t \end{pmatrix} = \begin{pmatrix} vq^2+(1-v)r^2-p^2 \\ -vq-(1-v)r+p \end{pmatrix}$$
$$ \implies u = 1-v \qquad t=v$$
Plug these back into the expressions for $\vec{AF}$ and $\vec{AE}$:
$$\vec{AF} = t(q^2-p^2,-q+p) = v(q^2-p^2,-q+p)$$
$$\vec{AE} = u(r^2-p^2,-r+p) = (1-v)(r^2-p^2,-r+p)$$
Finally, the area of the parallelogram is given by the magnitude of the cross product:
\begin{align}
\text{Area} & = |\vec{AF} \times \vec{AE}| \\
& = v(1-v) \Bigg|\begin{pmatrix} q^2-p^2 \\ -q+p \\ 0 \end{pmatrix} \times \begin{pmatrix} r^2-p^2 \\ -r+p \\ 0 \end{pmatrix} \Bigg| \\
& = v(1-v)|(q^2-p^2)(-r+p)-(-q+p)(r^2-p^2)| \\
& = v(1-v)|(q-p)(p-r)(r-q)|
\end{align}
and this expression is maximized when $v=\frac 12$, giving
$$\text{Area} = \frac{|(q-p)(p-r)(r-q)|}{4}$$
hmmmmm...

Maximising the area of a parallelogram


Comparing powers and factorials

Question: Let $a_n = \frac {1000^n}{n!}$ for $n \in N$. Then $a_n$ is greatest for:-
(A) $n=998$   (B) $n=999$ (C) $n=1000$ (D) $n=1001$
How to approach? Need hints.
Comment: Hint: $\frac{a_{n+1}}{a_n}=\frac{1000^{n+1}/(n+1)!}{1000^n/n!}  = \frac{1000}{n+1}$. Provided that this ratio is $>1$, you will have $a_{n+1}>a_n$. If this ratio is $=1$, then $a_{n+1}=a_n$, and if this ratio is $<1$ then $a_{n+1}<a_n$.
Comment: A? $n=998$? is the answer?
Comment: Try it, by calculation, for $\frac{3^n}{n!}$ instead
Comment: @TheDeadLegend, I don't know, sorry. But please give me some hints.
Comment: @kccu . So $n=1000$ and $n=999$ should be the answers, right? Nice method though. Thanks.
Comment: Yes, I believe so.
Comment: Which means it is not a good question unless multiple answers are allowed.  There is not a single correct answer.
Comment: @RossMillikan. The question is supposed to be multiple correct answer type. In India, these type of questions come in IIT-JEE examination.
Answer: In general the maximum value is between $n$ and $n-1$.
$sup(\frac{c^n}{n!})$ and using Stirling approximation $n! \approx n^n e^{-n} \sqrt{2 \pi n}$.
Which is approximately $sup(\frac{c^n}{n^n e^{-n} \sqrt{2 \pi n}})$ , the maximum value is when $(\frac{c^n}{n^n e^{-n} \sqrt{2 \pi n}})' =0$, we reach at $\frac{e^n n^{-n-\frac{1}{2}} c^n}{\sqrt{2 \pi }}+\frac{e^n n^{-n-\frac{1}{2}} c^n
   \log (c)}{\sqrt{2 \pi }}+\frac{e^n n^{-n-\frac{1}{2}} c^n
   \left(\frac{-n-\frac{1}{2}}{n}-\log (n)\right)}{\sqrt{2 \pi }}=0$ with a little bit of manipulation we arrive at $\log (c)-\frac{1}{2 n}-\log (n)=0$,which gives the answer $n=-\frac{1}{2 W\left(-\frac{1}{2 c}\right)}$, which can be easily bounded between $n$ and $n-1$.

Comparing powers and factorials


Dúvida com criação de campos dinâmicos com jquery + php

Question: Olá!
Estou fazendo um programa simples para o gerenciamento de minhas cervejas e vendas.
Na view de pedidos, eu consegui fazer a adição de uma nova linha para a inclusão de um novo item para o pedido.

Campos: id_item(select) | id_lote_item(select) | quantidade (text) | valor unitario(text) | subtotal(text)

Código jquery que faz a adição dos campos:
var campos_max = 10;   //max de 10 campos
var x = 1; // campos iniciais
$('#add_field').click(function (Event) {
    Event.preventDefault();     //prevenir novos clicks
    if (x < campos_max) {
        $('#listas').append('\

\n\

\n\

\n\
                        Cerveja\n\
                        <select name="id_item_estoque_pedido[]" id="id_item" class="select2 form-control">\n\
                            <option>Selecione</option>\n\
                        </select>\n\

\n\

\n\

\n\

\n\
                        Lote\n\
                        <select name="id_lote_pedido[]" id="id_lote_item" class="select2 form-control">\n\
                            <option>Selecione o lote</option>\n\
                        </select>\n\

\n\

\n\

\n\

\n\
                        Qtd. Pedido\n\
                        <input type="text" name="quantidade_item_pedido[]" id="quantidade_item_pedido" class="form-control">\n\

\n\

\n\

\n\

\n\
                        valor Unitario\n\
                        <input type="text" name="valor_unitatio_item_pedido[]" id="valor_unitatio_item_pedido" class="form-control">\n\

\n\

\n\

\n\
                    Subtotal\n\
                    <input type="text" id="subtotal_item_pedido" class="form-control" readonly="true">\n\

\n\

'
        );
        x++;
    }
});

Até ai tudo bem... a minha duvida vem agora...
O campo id_lote_item é alterado para exibir os lotes do item selecionado.
Codigo jquery:
$('#id_item').change(function (e) {
    var item = $('#id_item').val();
    var base_url = '<?php echo base_url(); ?>';
    $.getJSON(base_url + 'pedido/GetLoteByIdItem/' + item, function (dados) {

        if (dados.length > 0) {
            var option = '<option>Selecione o lote</option>';
            $.each(dados, function (i, obj) {
                option += '<option value="' + obj.id_lote + '">' + obj.nome_lote + ' - ' + 'Qtd: (' + obj.quantidade_garrafas_lote + ')</option>';
            })
        } else {
            option = '<option>Selecione o lote</option>';
        }
        $('#id_lote_item').html(option).show();
    });
});

Eu consegui fazer para somente uma linha. Agora com esse esquema de linhas dinamicas eu não consegui nem a pau.
Obrigado pela ajuda!
Comment: No HTML que estás a gerar há mais do que 1 `#id_item`? Ou seja, estás a adicionar várias vezes o HTML que tens na pergunta é isso? e funciona só para o primeiro certo?
Comment: @Sergio, quando chamo a view pela primeira vez, os campos não são criados, somente quando clico em um botão (#add_field).

Nesse caso teriam várias linhas com os mesmos campos, entendeu?
Comment: Ok, e `$('#id_item').change(function (e) {` funciona para 1 campo, mas não para os proximos certo?
Comment: não.... eu consegui fazer a busca pelos lotes do item somente escrevendo a linha onde ela ficaria. Agora, quando adicionei a funçao para adicionar as linhas com o jquery não consegui fazer nem para a primaira
Answer: Qual é o problema?
Há dois problemas no código:
Um deles é $('#id_item') não corre pois o '#id_item' ainda não existia quando esse código correu, é preciso usar delegação de eventos.
O outro é que juntar várias linhas com #id_item vai gerar IDs duplicados, e isso é sintaxe HTML inválida.
Como resolver:
Como não podes usar IDs duplicadas sugiro mudares tudo o que é ID (nesse código HTML de cada linha) para classes, ou retirando IDs e usando name (como fiz no exemplo).
Assim podes sempre trabalhar linha a linha com jQuery usando 3 ferramentas:

.closest() para encontrar o topo da linha
.find() para encontrar um elemento no DOM descendente
.on() para delegar os eventos.

Assim o teu código jQuery ficaria:
$('#listas').on('change', '[name="id_item_estoque_pedido[]"]', function(e) {
  var item = this;
  var base_url = '<?php echo base_url(); ?>';
  $.getJSON(base_url + 'pedido/GetLoteByIdItem/' + this.value, function(dados) {

    if (dados.length > 0) {
      var option = '<option>Selecione o lote</option>';
      $.each(dados, function(i, obj) {
        option += '<option value="' + obj.id_lote + '">' + obj.nome_lote + ' - ' + 'Qtd: (' + obj.quantidade_garrafas_lote + ')</option>';
      })
    } else {
      option = '<option>Selecione o lote</option>';
    }
    $(item).closest('.linha').find('[name="id_lote_pedido[]"]').html(option).show();
  });
});

Assim no HTML só tens de mudar
id="linha"

para
class="linha"

Comment: Mandou bem. Agora esta funcionando.. Muito Obrigado.
Answer: Você só vai conseguir user o evento em algo criado depois, se for iniciado assim:

$(document).on('change','.elemento_da_interação', function(e) {

Detalhe que ids não se duplicam, use className.
Comment: Obrigado. Vou precisar disso também.


How to sample when the size of the two populations differ greatly

Question: I have to compare the distributions (means, variance, ratio of specific features, etc.) of two populations. However, the sizes of the two populations differ a lot, one with only 30,000 observations, another with nearly 1 billion observations. Retrieving all 1 billion data from population 2 costs too much, but getting 30,000 data from population 1 is affordable. What is the proper way to sample two populations so that the statistical hypothesis testing methods stay meaningful and robust?
Should I sample 30,000 observations from population 2 and compare that with population 1, or sample 33 million from population 2 (which is still considered too large to me) and 1,000 from population 1 so the ratio of sample sizes is consistent with that of the populations, or maybe some other ways to do the sampling?
And, what if I don't know the exact size of population 2, all I know is it's at least 1 billion, is there any good method to sample it?
Comment: Most two-sample procedures work best when the two sample sizes are equal. If you know a great deal about Pop. A and very little about Pop. B, then the inference can't be a lot stronger than the information about Pop B. // You may feel that a larger sample is necessary to get a representative sample of the larger population, but you should rely on an appropriate sampling plan for that.
Answer: A key part of designing a study is to use a 'power and sample size' procedure to determine what sample size is necessary in order to have a good chance of a useful result---such as detecting a difference of a certain size it it exists. The procedures for determining sample sizes in 2-sample experiments usually assume that you will use equal sample sizes for the two samples.
Suppose I am planning to do a two-sided, two-sample t test to analyze my data. I will test at the 5% level, looking for a difference as small as 2 units, and knowing or assuming that the population variances are 5 units. I would like to be 90% sure that I will detect this difference, if it is present. (That is, I want power $0.9.)$
The power and sample size procedure in a recent version of Minitab gives the following results for the necessary sample size in each group.
Power and Sample Size

2-Sample t Test

Testing mean 1 = mean 2 (versus ≠)
Calculating power for mean 1 = mean 2 + difference
α = 0.05  Assumed standard deviation = 5

            Sample  Target
Difference    Size   Power  Actual Power
         2     133     0.9      0.901483

The sample size is for each group.

Now suppose I wonder what additional power my test would have if I were to spend the money/effort to
use a sample size of 300 in one of the two samples (keeping the other group at 133).
I can do a simulation in R to get an approximate answer.
set.seed(523)
pv = replicate(10^5, t.test(rnorm(300, 100, 5),
               rnorm(133, 102, 5), var.eq=T)$p.val)
mean(pv <= .05)
[1] 0.96939

The extra observations in the first group have increased my power from 0.90 to about 0.97.
But what would have happened to the power if
I had split the 433 observations equally between
the two groups? The answer from simulation is about
0.985.  For this balanced design, Minitab gives 0.986.
set.seed(2020)
pv = replicate(10^5, t.test(rnorm(217, 100, 5),
               rnorm(217, 102, 5), var.eq=T)$p.val)
mean(pv <= .05)
[1] 0.98541

Minitab
...
             Sample
 Difference    Size     Power
          2     217  0.986000

Answer: You should use all data from Population 1, since it is practical to do so.  I can scarcely think of an analysis in which it would be preferable to preserve uncertainty about Population 1 rather than definitively to establish its parameters.  Just because there will "certainly be uncertainty" about Population 2 does not mean your knowledge about Population 1 should be reduced to match that level.  Recall that, e.g., a Z-test of means that relies on a comparison to a known parameter will be more efficient than an corresponding T-test that compares two samples.
Power considerations as discussed by@BruceET may come into play, most likely if you are analyzing rare events or "narrow distributions."  How power might be affected by having unequal sample sizes is a matter that varies by type of procedure.  But it will never hurt power to collect a larger sample from one population, even if the two sample sizes differ.  I disagree with @BruceET when he writes, "Most two-sample procedures work best when the two sample sizes are equal."  Instead I'd say that most conveniently available guidelines about power assume equal sizes; that is not the same thing.
There's another consideration.  You may be using the term "population" to mean "sampling frame."  Beyond the groups of ~ 30,000 and ~1B that you describe, are there still larger groups to which you seek to generalize?  In that case the latter would be the true "populations", while the ~30,000 and ~1B would be sampling frames -- initial or realistic samples from which you might draw still smaller samples to analyze.


Comparing three groups for one variable when two of the groups' values are zero

Question: I'm trying to compare three groups but the fact that two of theml only show values of zero is giving me a hard time. Specifically, I'm comparing the production of a metabolite (M3G) by three cell lines. the results are as follow :
<code>Line 1 : mean = 0 SEM = 0, n=10
Line 2 mean = 0, SEM = 0, n=10
Line 3 : mean = 2.89, SEM = 0.23, n=10
</code>
Here are the values for cell line 3 :
<code>> 3,52 4,37 2,51 2,71 2,48 2,09 2,73 2,92 2,80 2,66
</code>
All the values for cell lines 1 and 2 are 0.
What test should I use to compare these cell lines ? I've been trying to find an answer and came up with a thread recommending a one-sample t-test, but I have three groups... I'm not sure what to do as I'm no expert in statistics ! For my other analyses (comparing groups with means different from zero), I usually use Mann-Whitney : is this applicable here ?
Answer: The one-sample t-test would presumably show that cell line 3 has a non-zero production of the metabolite. If you are sure that the other 2 lines have 0 production, then your problem is solved. Two lines have no production, and the third does.
In practice, however, a value of "0" typically means below the limit of detection. A limit of detection of 2 units would be consistent with your data. In that case you would have to know more about how the detection method handles samples that are close to that limit, both in terms of the mean value reported and the variability in the values that might be reported.
Comment: Hi, thanks for the answer !

My method of detection is L-MS/MS (HPLC coupled to tandem mass spectrometry) so it's more or less the most sensitive apparatus available right now.

I don't really understand what you mean by "a limit detection of 2 units" ??

Thanks :)
Comment: Something mention : My data are actually an extrapolation of the results to the total content of the metabolite : the signal detected by the LC-MS/MS was 10 times lower (I inject only 10µL out of 100, and the values obtained are in pmoles).
Comment: From your comments, your raw LC-MS/MS numbers are evidently 0.352 pmol, 0.437 pmol, etc. My point about the limit of detection of "2 units" then becomes: what would happen if you injected 0.2 pmol in your 10 ul? Would you see a signal? Even if this is the most sensitive technology, how sensitive is it? What's the lowest amount you can distinguish from a true 0 value?


Migrate existing dev desktop site from PC to Mac without existing db dump

Question: I have a PC with dev desktop on it where I had a local install of a drupal 7 site.
I needed to reinstall windows on the PC and it wiped out my local install except I kept the old windows files, so I have access to the original site files.
What I don't have is a database dump of the local install.
With the old files, is there a way I can find the database table data?  I can see in the old install of dev desktop the mysql/data content for the site, but I think I need additional files to complete the database tables, etc.
Thanks.
Answer: DevDesktop stores the mysql databases in its application installation folder.  Assuming, you installed to the default location, in your PC backups, navigate to C:\Program Files (x86)\DevDesktop\mysql\data
This folder contains a copy of the MySQL databases.

Restoring to PC for use or export:

On the PC (assuming you haven't installed any other devdesktop sites), copy all the files and folders from the mysql/data backup directory into a fresh install's MySQL's data directory.
For export:  Start MySQL and export a copy for backup purposes/importing elsewhere as needed.
For immediate use/development on PC: Start MySQL and your DevDesktop to confirm the site is running; resume normal dev desktop development on PC

Loading directly to a fresh install of DevDesktop, MAMP, Vagrant, or other MySQL service on Mac

You could also copy the contents of that backup folder directly to the corresponding mysql/data backup directory on your Mac.  NOTE: copying the entire directory will wipe all existing databases/user accounts in MySQL on your Mac's MySQL server, be sure to back it up first if you have existing data).  If it's a fresh install of DevDesktop (or other) on the Mac, copy all the files and folders from the mysql/data backup directory of the PC to the corresponding folder on the Mac.
Start DevDesktop or other local webserver app to confirm the site is running; resume normal dev desktop development on Mac

Merging with existing mySQL data, hosting database along side others on existing install of DevDesktop, MAMP, Vagrant, or other mySQL service on Mac

If you do have existing MySQL data on the Mac (be it MAMP, DevDesktop, Vagrant instance or other), backup the corresponding /mysql/data folder from that application.
Replace with the backup folder from the PC
Start MySQL and export the database.
Then swap the original Mac MySQL data back into place.
Restart MySQL and import the database backup you just exported.
Now you have both your PC devDesktop database and Mac databases available on the Mac.


Is the double integral equal to the area?

Question: I have to compute the double integral $\int_0^{\sqrt{\frac{\pi}{2}}}\int_x^{\sqrt{\frac{\pi}{2}}} 2\sin(y^2)dydx$.
I drawed the region $0\leq x\leq \sqrt{\frac{\pi}{2}}$ and $x\leq y\leq \sqrt{\frac{\pi}{2}}$. This is a triangle with height and base equal to $\sqrt{\frac{\pi}{2}}$, right?
The double integral is equal to the are of the triangle, or not?
So, is the double integral equal to $\frac{1}{2}\cdot \sqrt{\frac{\pi}{2}}\cdot \sqrt{\frac{\pi}{2}}=\frac{\pi}{4}$ ?
Comment: Think what would happen if the integrand would be another function. What if the integrand is zero?
Comment: Ah... Can we no use the graph of the region to compute the double integral? @jinawee
Comment: Isn't the integrand zero at $y=0$ and $y=\sqrt{\frac{\pi}{2}}$ ? @jinawee
Comment: If you assume that the area of a region is unique and since an integral depends on the integrand (the integral of x is different than the integral of an exponential or of  the number seven, right?) your assumption must be wrong. The answer is that if you integrate the constant one, you get the area (length in one dimension, volume in three).
Comment: An analogy: Do you also think that $\int_a^b f(x) \, dx$ is always equal to $b-a$ (the length of the interval)?
Comment: I think of it as a signed volume. I think of a "single" integral as signed area.
Answer: You have a heap of sand on a triangular lot. The height of the heap at the point $(x,y)$ is defined to be $2\sin(y^2)$.  The integral you are told to compute is the volume of that heap.
Answer: Hint. Note that the double integral over that triangle can be written as iterated integrals in two ways.
\begin{align*}
\int_{x=0}^{\sqrt{\frac{\pi}{2}}}\left(\int_{y=x}^{\sqrt{\frac{\pi}{2}}} 2\sin(y^2)dy\right)dx
&=\int_{y=0}^{\sqrt{\frac{\pi}{2}}}\left(\int_{x=0}^{y} 2\sin(y^2)dx\right)dy\\
&=\int_{y=0}^{\sqrt{\frac{\pi}{2}}}2\sin(y^2)\left(\int_{x=0}^{y} dx\right)dy\\
&=\int_{y=0}^{\sqrt{\frac{\pi}{2}}}2y\sin(y^2)dy.
\end{align*}
Can you take it from here?
P.S. The final result is different from what you have found. It is not the area of the triangle.
Comment: @Mary Star Yes, the change of variable is fine.
Comment: @Mary Star Yes, the result is $1$: http://www.wolframalpha.com/input/?i=int(int(2sin(y%5E2),y%3Dx..sqrt(Pi%2F2)),x%3D0..sqrt(Pi%2F2));
Comment: Do we change the variable $u=y^2$ so that computing the integral is easier? Or is there an other way maybe by the area?
Comment: Then we get $\int_{u=0}^{\frac{\pi}{2}} \sin(u)du$, which is easy to compute, right?
Comment: The result is then $1$, or not?
Comment: But according to Wolfram the result must be $\frac{1}{2}$, or not?
Answer: The triangular region you found is called the domain of integration. The integrand function is a two variable function: $f(x,y)=2\sin(y^2)$. The double integral of a two-variable function shows the volume under the graph (surface) of the two-variable function in the given domain of integration. (Similarly, the integral of a one-variable function shows the area under the graph of the one-variable function in the given domain (interval) of integration). One of the methods of calculation of a double integral is to change the order of integration. (See here for examples). Hence you should apply this method for your double integral.


Pandas Group then rolling and sum get wrong results

Question: I want to group column A then sum last 3 rows of column B.
df = pd.DataFrame()
df['A'] = [1, 1, 1, 1, 2, 2, 2, 2]
df['B'] = [1, 2, 3, 4, 1, 2, 3, 4]

I tried.
df['sum_B_previous_3'] = df.groupby('A').B.shift(1).rolling(3, min_periods=0).sum()
df

    A   B   sum_B_previous_3
0   1   1   0.0
1   1   2   1.0
2   1   3   3.0
3   1   4   6.0
4   2   1   5.0
5   2   2   4.0
6   2   3   3.0
7   2   4   6.0

But I want.
    A   B   sum_B_previous_3
0   1   1   0.0
1   1   2   1.0
2   1   3   3.0
3   1   4   6.0
4   2   1   0.0
5   2   2   1.0
6   2   3   3.0
7   2   4   6.0

Why row 4 and 5 get wrong results? How to correct this?
Answer: You can call lambda function per groups with GroupBy.apply:
f = lambda x: x.shift(1).rolling(3, min_periods=0).sum()
df['sum_B_previous_3'] = df.groupby('A').B.apply(f)
print (df)

   A  B  sum_B_previous_3
0  1  1               0.0
1  1  2               1.0
2  1  3               3.0
3  1  4               6.0
4  2  1               0.0
5  2  2               1.0
6  2  3               3.0
7  2  4               6.0

Another solution is call groupby again:
df['sum_B_previous_3'] = (df.groupby('A').B
                            .shift(1)
                            .groupby(df['A'])
                            .rolling(3, min_periods=0)
                            .sum()
                            .reset_index(level=0, drop=True))
print (df)

   A  B  sum_B_previous_3
0  1  1               0.0
1  1  2               1.0
2  1  3               2.0
3  1  4               3.0
4  2  1               0.0
5  2  2               1.0
6  2  3               2.0
7  2  4               3.0

Comment: @yolox - because `df.groupby('A').B.shift(1)` return new `Series` and `.rolling(3, min_periods=0).sum()` working with it, same like `df['sum_B_previous_3'] = df.groupby('A').B.shift(1)`

`df['sum_B_previous_3'] = df['sum_B_previous_3'].rolling(3, min_periods=0).sum()`
Comment: Thank for the answer! But I have a question. Why my answer get the result from the last group?
Answer: The problem is that the only group operation you are applying is .shift. The result of df.groupby('A').B.shift(1) is a DataFrame which is then subject to normal rolling (not grouped).
Here is a solution that doesn't use apply, albeit a slower one:
B_shift = df.groupby('A').B.shift()
df['sum_B_previous_3'] = B_shift.groupby(df.A).rolling(3, min_periods=0).sum().values


Shortcut with x0 for taylor expansion

Question: I am confused about the point $x_0$ in Taylor Series Expansion.
$f(x) = 1/(1-x)$ and $\sum_n^\infty x^n$ at $x_0=0$
so I thought that if $x_0$=2 I don't need to go through all the process solving for $f^n(x_0)$
and I have a shortcut for $x_0=2$  like :
$$f(x) = 1/(1-(x-2))$$ and series for it is$$\sum_n^\infty (x-2)^n$$ but it is not true.
My exercise was to find $f(x)$ for $\sum_n^\infty((x-1)/2)^n$. So I see here that $x_0=-1$ and
immediately I thought of this:
$$1/(1-(x-1)/2) = \sum_n^\infty((x-1)/2)^n$$
so I just got lucky with this example.
Question : Isn't there a shortcut to find the series of a function like $1/(1-x)$ where $x_0=const$ without going through all the pain of finding the derivative for $f^n(x_0)$ ?
Thanks
Comment: $\sum_n^\infty((x-1)/2)^n$ is the sum of terms in geometric progression, isn't it ? Then ....
Comment: I don't understand , I am saying that using my bad logic I got lucky only with this example
Answer: Consider the general case where you need the Taylor expansion of $$f(x)=\frac{1}{1-x}$$ built at $x=a$. The derivatives are easy to compute and you arrive at $$f(x)=\sum_{n=0}^{\infty}\frac{(x-a)^n}{(1-a)^{n+1}}$$
Answer: You didn't get lucky in the second example, you just didn't do it properly in the first.
Let's see.
You have $f(x)=\frac{1}{1-x}=\sum x^n$. You want to obtain $f(x)=\sum a_n(x-2)^n$.
Then $\sum x^n=\sum a_n(x-2)^n$. Put  $x=y+2$.
So $f(y+2)=\sum (y+2)^n=\sum a_ny^n$.
Therefore, to obtain the coefficients $a_n$ we just need to expand $f(y+2)$ at $y_0=0$.
But $f(y+2)=\frac{1}{1-(y+2)}=-\frac{1}{1-(-y)}=-\sum (-y)^n=\sum(-1)^{n+1}y^n$. Therefore $a_n=(-1)^{n+1}$. Therefore
$$f(x)=\sum (-1)^{n+1}(x-2)^n.$$
Summarizing: To expand $f(x)$ at $x_0$ (assuming that what we know is to expand things at $0$) is to expand $$f(x+x_0)=\sum a_nx^n$$ at $0$ and take those coefficients to get
$$f(x)=\sum a_n(x-x_0)^n.$$
Answer: Why would you think it is a pain?
Set $x_0=0$
$f^1(x)=-(1-x)^{-2}$
$f^2(x)=2(1-x)^{-3}$
$f^3(x)=-2*3(1-x)^{-4}$
So, as you can see, $f^n(0)=(-1)^{n}*n!$
And even if you don't want to set $x_0=0$, for any $x_0$, you'd have $f^n(x_0)=(-1)^n*n!*(1-x_0)^{n-1}$
For other cases, I am not an expert at this, but there are some helpful "tricks".
Assume that the expression for the derivative is easy to obtain, so that we have the coefficients $c_0',c_1',\ldots$ then we have $(f')^{(k)}(0)=c_k'*k!$ and thus $f^{k+1}(0)=c'_k*k!$ which would make it easy to get the coefficients for $f$
After simplification, you'd get $f(x)=f(0)+\frac{c_0'}{1}x+\frac{c_1'}{2}x^2+\ldots$
This would be helpful in the case of getting the taylor series for $arctan(x)$ for example.
Comment: for this function it is not a pain , but for others might be ,
I wanted to know if I can short it out :)
Comment: I'll edit my answer.

Shortcut with x0 for taylor expansion


Viewer para PDF com jquery

Question: Como eu faço para abrir PDF no google chrome por jquery sem a necessidade de instalação de plugins? Não há a necessidade de código fonte, apenas como devo fazer. Pode ser um link e etc...
Comment: Sem plugin de PDF não dá pra abrir PDF. É mais ou menos querer ouvir som sem alto falantes. Você teria que converter no servidor o PDF para HTML como o Gmail, Outlook, Office Web fazem e como o jQuery só roda no cliente, não há solução para a sua pergunta.
Comment: @MarcosRegis, eu já consegui um e estou homologando. O TobyMosque também me enviou um que ainda não tive a oportunidade de testar, pois ainda estou testando o que eu havia conseguido anteriormente.
Answer: Criei um link apontando para um pfd e usei a opção target="_blank" para abrir em uma nova aba.
Tente:
Clique aqui para ver o link

Comment: Da forma que você colocou, se eu desativo o PDF Viewer, ele não abre, ele pede para fazer download do arquivo. O que eu quero é algo que abra no browser(chrome) o arquivo e com o plugin desativado ou não instalado. Achei algo que faz o que eu quero e depois de testar eu posto a solução.
Comment: @pnet Não entendi porque a pessoal iria desbloquear o PDF Viewer e porque você quer força-lo a ver de qualquer maneira.
Comment: É o seguinte: O empresa tem uns 600 operadores que precisam ver documentos(relatórios) dos clientes, enquanto atendem. A matriz(EUA) não quer homologar o Chrome e no Brasil, temos a necessidade de apresentar relatórios no Chrome por força de clientes e fornecedores. Esses operadores, muitos são terceiros. Então há uma "briga" aqui entre a filial nossa e a matriz e para não parar o trabalho que já foi feito(fazer o site funcionar no chrome), nós estamos aplicando o nosso plano "B", que é usar esse recurso do jquery e contornar a falta do plugin.
Comment: Outra coisa, não que é que o pessoal vai desbloquear. O pessoal da segurança de TI já bloqueia tudo e remove o que é usado no chrome por Default. Não tem choro, se é Chrome não pode ter nada nele, nada mesmo. Eles não deixa nenhuma opção para o usuário. Usuário é apenas usuário mesmo, no bom sentido da palavra.
Answer: Marconi, vou ver seu exemplo. Dessa forma aqui que eu peguei na internet, funcionou, usando um cara chamado ZohoViewer.
<!DOCTYPE html>

    <title></title>

    Read PDF File

Comment: Em realidade a minha solução não funcionou. Por que? Porque fui nas configurações do Chrome e lé havia um plugin PDF Viewer ativado. desativei e com o recurso acima, não funcionou. Ativo o plugin e funciona.  Aqui na empresa, a maioria dos operadores não possui o plugin PDF Viewer e procuro uma solução que funcione no "tapa" mesmo, sem plugin e sem nada. Tá osso, eu sei, mas peço ajuda dos colegas.
Comment: Da forma, com o plugin desativado não dá erro, apenas não abre o arquivo, ele sugere fazer download do arquivo para a máquina.
Comment: Fiz o download nesse link e funcionou com o plugin desativado que é o que eu quero. http://www.jqueryscript.net/other/Touch-enabled-jQuery-Web-PDF-Viewer-TouchPDF.html
Comment: ja pensou em usar o [pdf.js](https://mozilla.github.io/pdf.js/)? veja se você consegue visualizar a pagina demo do mesmo sem o plugin ativo.
Comment: @TobyMosque, vou testar e na segunda, conforme for, eu posto. Mas o link que eu passei no comentário, parece que resolve a questão, mas preciso de mais testes.
Comment: @TobyMosque, aparentemente esse é o cara que vamos trabalhar. Mais simples o uso do que o anterior que eu peguei e muito mais completo. Ainda estamos homologando.
Comment: O PDF.JS é mantido pela Monzila e usado como visualizador padrão no Firefox, então ele já é um visualizador de PDF bastante utilizado.

Viewer para PDF com jquery


Why Gibbs Sampling for mixture models?

Question: I am studying MCMC and in the book I'm reading there is this example on Gibbs algorithm for inferring the posterior of a gaussian mixture. I understand how the algorithm works and the fact that its convenience relies in the simplicity of sampling from the full conditionals for the parameters, however I was wondering whether and why this method should be preferable to others that were introduced in previous chapters and with which I am less familiar (like Variational methods, or others I don't know).
Furthermore, the book starts by explicitly writing the full joint $p(x,z,\mu,\Sigma, \pi)$ for the gmm (assuming semi-conjugate prior), am I right to say that even knowing this explicitly, sampling directly (using for instance rejection sampling) is inefficient because of the curse of dimensionality, while Gibbs suffer far less from this phenomenon? Is this the only reason why Gibbs is to be preferred?
Any help on understanding pros and cons of the various existing methods for inferring the posterior is well accepted.
Comment: Gibbs sampling was introduced by Geman and Geman (1984) as a way to fight the curse of dimensionality. Devising a random walk Metropolis-Hastings algorithm in dimension $3k-1$ for a $k$ component Normal mixture is quite the challenge.
Answer: Gibbs sampling is possibly the first MCMC algorithm implemented for mixture models (Gelber, Gelman and Goldhirsch, 1989), inspired from the data augmentation of Tanner and Wong (1987) and ultimately from the EM algorithm. It takes advantage of the latent variable structure in producing nice, low dimension, and natural conditionals that can be simulated quite efficiently, much more than a default MCMC algorithm like random walk Metropolis-Hastings.
However, here is a slide from my MCMC course, where I illustrate the potential pitfall of using plain Gibbs for a mixture of two Gaussians with unknown means, namely that it may get trapped in a local mode because the latent variables are practically if not theoretically stuck at a fixed value.

Why Gibbs Sampling for mixture models?


JavaScript clock (timer) to start from the provided time span stored in asp hidden field

Question:

    <title>Digital clock</title>

    <link href="../Styles/jquery.alerts.css" rel="stylesheet" type="text/css" />

Total Elapsed Time

90

                    <form runat="server">
                        <asp:Button ID="btnStop" runat="server" Text="Stop"
                            style="width:150px;height:30px;font-weight:bold;background-color:#104E8B;color:White;border:1px solid"
                            onclick="btnStop_Click" /></form>
                            <input id="HiddenTaskname" type="hidden" value="" runat="server" />

Above you can see that when the above page opens a timer(Clock) is starting from 00:00:00 .
I want to update it in such a way that it will start from the specified time as mentioned .
For example if we pass an argument to this page as 14:30:58 then the timer will start from 14:30:58 and so on.
I ll pass this argument from the query string and storing it in an asp hidden field in this page .Please help me to update above code so that it fulfills my requirement.
Comment: Do you want the argument to be processed on the server side or the client side?
Answer: var digiclock = "<%= Request.QueryString["QueryStringVariableName"] %>";
Should work, Haven't tested it, you might need to change the double quotes to single. I'm not a pro so play with it.


Delete rule for one-to-one relationship

Question: I have 2 entities: Department <---->> Employee. So, the department has a one-to-many relationship with employee, and employee has a one-to-one relationship with department.
What should be the delete rule of the one-to-one relationship? If I choose cascade, I can see that the department is deleted when I delete an employee and of course I don't want that. I think the logical option for the delete rule would be "No Action", but then I get a warning. Am I missing something, or should the delete rule really be "No Action" in this scenario?
Answer: Nullify.
If you choose no action, then the employee will still be in the department's list of employees, but will be deleted. Likely a crash.
Nullify in this context means when you delete an employee, remove that employee from the inverse relationship (employees) of its department.
Comment: Thanks. Does the relationship department in the entity employee have to be optional? When I try to remove an employee, I get a crash if the department isn't optional. It works fine if it's optional, but I don't see the logic.
Comment: It sounds like you removed the employee from the department but you didn't delete the employee object. So, it depends what you intend. If you want to keep the employee object around (record of a former employee) then make the department optional. If you want to delete the employee object, then do so, and the department doesn't have to be optional I think. A deleted object doesn't have to pass validation.
Comment: Thank you very much! Your 2 answers were very useful to clarify how the delete rules work.

Delete rule for one-to-one relationship


Printing char multi dimensional arrays not working like I want to

Question: #include <stdio.h>

int main()
{
    FILE *fisier;
    fisier = fopen("cnp.txt", "r");

    int cnpuri = 0;
    char cnp[10][13];

    while(1){
        fscanf(fisier, "%s", cnp[cnpuri]);
        cnpuri++;

        if(feof(fisier))
            break;
    }

    int i;
    for(i = 0; i < cnpuri; i++){
        printf("%s \n", cnp[i]);
    }

    fclose(fisier);
    return 0;
}

This is the text I'm reading:
1234567890123
1763578126765
4156156546489
5749684631654
5498654168763

And this is what it shows in terminal:
12345678901231763578126765415615654648957496846316545498654168763
1763578126765415615654648957496846316545498654168763
415615654648957496846316545498654168763
57496846316545498654168763
5498654168763

Comment: Strings in C need to be NUL terminated. So a 13 digit string requires a 14 char array to store. Increase the second dimension of the array by at least 1.
Answer: The problem is that the second size of the array
char cnp[10][13];

is not large enough to store the terminating zero character of entered strings.
Declare it at least like
char cnp[10][14];

Also change the while loop the following way
while( cnpuri < 10 && fscanf(fisier, "%s", cnp[cnpuri]) == 1)
{
    cnpuri++;
}

Comment: thanks, i was dumb to forget about the \0 character


Private Cloud: Debian and OSS vs vmware vSphere, which is best for corporate use?

Question: I'm hoping someone can shed some light regarding the current state of
virtualization on Debian. Since I like my information first-hand, i
thought I'd ask here for some real-world use cases. I am currently
gathering some data in order to redesign the network infrastructure of
the company i work for. I've been directed by some fellow sysadmins
towards  ESX and ESXi, but the pricing seems a bit over the top and
honestly, i don't know if i actually need the whole thing, also
considering that i am not familiar with enterprise-grade virtualization
solutions.
Basically I'm looking for a robust system that will allow me to deploy,
host and manage virtual machines. The need for different services is
growing in my company and having virtual machines for each would be ideal.
I'm looking at a really small setup so the performance is not that big
of an issue, but I am definitively looking at reliability and
flexibility. There will probably be a main physical server running about
a dozen machines, not all of them concurrently.
Being a corporate environment, I am also concerned with data and network
security, but i don't really know where I should be looking for
information, as designing a system with no real-use knowledge of the
components can be quite a hard task.
I've worked with hosting control panels and I like the idea of being
able to manage the system through a web browser. To be more specific,
I've worked with ISPConfig which has support for OpenVZ containers.
I never had to actually use that so far, but from what I saw on the
management interface it seems like it would be a pretty simple solution
and I like that. The issue is that i need to host Windows server VMs on
it and OpenVZ does not seem to be supporting it oob.
I am also currently looking at the various pages on the debian wiki on
Xen, QEMU, OpenVZ and the suggested softwares to work with
virtualization. If you have other valid sources of information, they
would be really appreciated.
EDIT:
The proposed solutions are:

The free vmware ESXi
Proxmox VE
VirtualBox with phpVirtualBox
Openstacks
Comment: This is a question and answer site, I'm struggling to see your actual question. Can you read the FAQ, look at how others have asked questions then re-write this one with some actually answerable questions please.
Comment: If you're not looking for a specific answer, then you're in the wrong place. From the [faq] that you seem to have neglected to read: `You should only ask practical, answerable questions based on actual problems that you face`
Comment: That's cause i'm not looking for a specific answer, i need to set up a private cloud enviroment and i wanted to know which are the possible software solutions. I'll rewrite the title if that helps.
Comment: One warning against ESXi: it's pretty much Windows only for management. If you're a heavy Mac or Linux shop, you may not like it.
Comment: @D4rKr0W - but this site is FOR specific questions and answers - i.e. my concern - this isn't a discussion site.
Comment: I'm looking for a private cloud software stack or a virtualization software stack: i think it's a practical, answerable question based on the actual problem i have.
Answer: Basically, there is no such thing as "Debian" virtualization. There is a Linux Kernel hypervisor called KVM. A number of projects have arisen around it, one of them which is a rather well supported "install & run" package is Proxmox VE - it includes web-based management and even has support for the more sophisticated features like live migration of virtual machines. PVE is Debian-based and also supports OpenVZ for "thin" Linux containers.
Your reluctance towards ESXi is unsubstantiated - it indeed is rather easy to set up and manage, also a free ESXi version is around (it has limits, though - check out if this version would fit your needs).
The advantage in using a well-established solution like ESXi is clearly that you would be able to find a lot of people (including VMWare support) being able to help with setup, operations or troubleshooting. If you are going to use the free version, you might end up hitting the limits or missing features though.
Comment: As a nitpick, Proxmox VE seems to be Debian based, not CentOS.
Comment: I love debian and the Proxmox VE project seems like a really valid alternative to using the fre ESXi.
The point you made on vmware is the only thing that is keeping me from deploying it. As i am concerned with the feature set, i wanted to know if there are alternatives.
I've also been told to look at openstack: www.openstack.org ( http://vimeo.com/20787736 ), but it does not seem to fit my specific case, even though it seems like a direct alternative to the whole vmware package.
Comment: @D4rKr0W you might well start with ESXi free - it is quite solid and well-performing. As time passes or if the need arises, you can simply shift to KVM - transition between hypervisors is not all that hard - the VMs are always convertible with reasonable effort, no matter the direction. What you *do* need though is a spare physical machine with vacant RAM and disk space since a conversion is always a copy.
Answer: Definitely standalone ESXi to start with - the product is free, has really small footprint and is very robust, stable and flexible. Also you can do most of the management using either web browser or powershell. Basically (IMHO) the best available virtualization platform available at this moment.
Also, just to clarify before you start playing with it: with free standalone version you will have only basic set of features, plus it has really strict HCL, so you won't be able to run it on every machine.
Comment: Keep in mind that Proxmox is not a real barebone hypervisor - basically, under the hood, this is a Debian running KVM, so if you want to host non-linux machines then sorry, no bonus here. ESXi on the other hand is a real one - you can run almost every OS withing the guests (VMs), it has a really small footprint, etc. Basically, a decent enterprise-class product. RE HCL - if you want to just play a bit with it for start, standard modern virtualization-capable dektop will be fine, the only issues you might have is an onboard NIC (I don't imagine you will need a huge raid arrays for your POC).
Comment: I agree here, whilst there are other solutions VMwares ESXi5 standalone is going to be the easiest to get up and running.
Comment: You're the only one that mentioned the HCL! I'm planning to test out both proxmox and esxi on a desktop system, so that i have an idea about how much resources i'm gonna need for the server - which i don't have yet. I suppose that's gonna be another issue :(
Comment: you surely **can** run Windows machines on KVM - you even get [downloadable optimized drivers](http://www.linux-kvm.org/page/WindowsGuestDrivers). As for the "play around a bit" with ESXi - there is a ["whitebox HCL"](http://www.vm-help.com//esx40i/esx40_whitebox_HCL.php) listing hardware without official support status but tested working.
Comment: OK, that was some bad choice of words :) you can run non-linux guests, of course, but personally i wouldn't do that as the stuff is not fully supported (or, to be more accurate, not supported as well as on the VMware platform). I know that (for example) Red Hat is pushing that really hard, but personally I wouldn't stick to it in heterogeneous production environment :)
Answer: Mindshare and experience is very important. That's true from a hardware, support and personnel perspective. You want to pick the winner, and VMWare really "Just Works". I've had the same discussion/argument with coworkers who were open-source fanatics... But honestly, your time is worth something. Go with the established solution.
VMWare can be expensive for all of the highest-end features, but for most small businesses, you have a free price point, a ~$600 price point, a $4000 price point all the way up to $$$$$! But there's still a low barrier to entry...
Comment: See the version comparison chart: http://www.vmware.com/products/vsphere/buy/editions_comparison.html
Comment: The thing that worries me is the pricing, as i'm not working with that big of a budget and i surely do not intend on spending it all on licenses. I don't want to find myself in need of a feature that is included only in the enterprise packages that cost 30k USD (i'm exaggerating but it's an example). I have no doubt vmware works perfectly, but i'm concerned about the feature set of this free version. I'm gonna look for a comparison chart.
Answer: Whilst I agree with siupakabras that ESXi is your best solution, the alternative is Virtual box from Oracle:
https://www.virtualbox.org/
Which also has some nice UI's.  But is not as feature complete as ESXi in my humble opinion.
Comment: VirtualBox is really more of a workstation platform rather than running servers from it. If you're using virtualization in a business, get a hypervisor that's made to handle this task. Hyper-V, KVM or ESX(i).
Comment: Virtualbox was one of the first things that popped into my head and there seems to be others that had the same idea: this looks like a nice management interface for the software: [link](http://code.google.com/p/phpvirtualbox/)


inserting content into node using field

Question: I am really stuck and need some advice, I'd like to know how I can go about doing this, simply put:
A website contributor enters a value into a field which is placed into the html.
eg. I have say two fields that will determine an image name and the file type. In field 1 the user enters [ABC], in field 2 the user enters [123].
The output of this would be
I have never worked with my own custom modules/fields etc before, a point in the right direction would be a big help.
Comment: This would be hard to do without writing some PHP. Would you be able to write a template file for the relevant content type?  if so, you can do it.
Comment: Thanks olyN, would you say that is the best way to go about this? I have simplified matters a great deal in the above example but hope if I can work out how to achieve the above then I should be able to do the rest.

Each field will be used multiple times on the node. Is a custom template file still the best way knowing this? I've not been able to find a definitive answer.
Comment: It would be fairly straightforward to do it that way. is the image URL eternal to the drupal site, as well? I'm adding some instructions in an answer below. :)
Comment: I have a group of fields: http://oi57.tinypic.com/wi0z8i.jpg

Each field will correspond to an element, some need to be incorporated into the html (like in my op example) some are fine as text fields.

The group of fields can be used multiple times in the article. This I already have in place.
Comment: It may help to understand it is a way of my contributors posting multipile images in a list style article (like buzz feed), but giving each image a title, source etc.

The added issue is that the images all live on an external server but they will all live in the same folder and have a unified file name. eg folder/image_01, folder/image_02 etc
Answer: To do this in a template,
1. create a file inside your /sites/all/themes/YOURTHEME folder, called node--CONTENT_TYPE.tpl.php.
2. copy the contents of node.tpl.php into that file.
3. add something like the following to the template file, where you want to print the image:
<img src="http://example.com/<?php
    print $node->YOUR_FIELD_1[$node->language][0]['value'] .
    '.' .
    $node->YOUR_FIELD_2[$node->language][0]['value'];
    ?>
 alt="..." ... >

Another possibility (probably better), would be to use the filefield sources module, and let the users upload the image to your drupal site by pasting the url.
Comment: Thank you olyN, I am going to try this method in the hope I can get it to work. My main concern is that I have things set up to post multiple images and it looks like this way will work for one static image.
Comment: if you have more images, you'll have to loop through them. You can allow multiple values for a field, and/or use the multifield module, if you need to group together multiple fields into one group.

inserting content into node using field


Use Series names as xAxis in Highcharts

Question: I want to use my series names as xAxis. I have tried it like the code below. This code is creating multiple series but only one x axis value. Let's say in my code I want to create series for every fund and plot fund values in xAxis as well.
    function draw(fund, zreturn) {

    zreturn = [12.75, 11.77, 13.76];
    fund = ['abc', 'xyz', 'pqr'];

    var options = {};
    options = {

        chart: {
            renderTo: 'graphDiv',
            type: 'line',
            Height: '400px'

        },
        credits: {
            enabled: false
        },
        title: {
            text: 'Fund Performance Graph',
            x: -20
        },

        subtitle: {
            text: '',
            x: -20
        },

        xAxis: {
            categories: fund
            }
        },

        yAxis: {
            labels: {
                enabled: true,
                format: function () {
                    return (this.value + '%')
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0,

        },

        series: zreturn.filter(function (zreturn, i) {

            return fund[i]

        }).map(function (zreturn, i) {
            /* Then return as series */
            return {
                //type: 'line',
                name: fund[i],
                data: zreturn,
                dataLabels: {
                    align: 'center',
                    enabled: true,
                    format: "{y:.2f}" + '%',
                    style: {
                        fontSize: "8px",
                        fontFamily: 'Arial',

                    },

                }
            }
        })
    }

    var chart = new Highcharts.Chart(options);

};

Comment: I have corrected your code so it will work like you want: http://jsfiddle.net/worg6jLz/26/
Comment: @GrzegorzBlachliński Its working perfectly. could you please explain what you have done?
Comment: I have posted answer with explanation of changes
Answer: I think that right now you have small mistakes in your code.
First of all you are using yAxis.labels.format as a function. It should be formatter if you want to use it as a function:
yAxis: {
  labels: {
    enabled: true,
    formatter: function() {
      return (this.value + '%')
    }
  }
},

Next, you have mistake in your data, it should be an array:
data: [
  [i, zreturn]
],

I am here adding x value of your point as well as y value. If I will not add x value, points will always start from 0 and because you have added only one point to every series, all of them will be on the first category.
Here you can find an example how your chart may work with these small corrections:
http://jsfiddle.net/worg6jLz/29/

Use Series names as xAxis in Highcharts


Sobre a passagem de parâmetros em linguagens de programação compiladas

Question: O que seria mais vantajoso ao chamar uma função, colocar na pilha da direita para esquerda ou vice-versa? E a limpeza da pilha? A função que chama (caller) ou a que é chamada (calee) deve ficar responsável por isso?
Meus dois centavos:
Quando a função que chama fica responsável por limpar a pilha, é possível a criação de funções com a quantidade de parâmetros variáveis, pois não é necessário saber tal quantidade antes do tempo de execução, sendo somente necessário alguma lógica a mais. (ex: printf)
Em relação a ordem em que se põe o argumentos na pilha, da esquerda pra direita permite que os primeiros argumentos sejam usados para determinar a quantidade de argumentos que a função vai receber, no entanto, isto é possível na outra ordem colocando tal informação nos últimos argumentos, sendo então uma questão de convenção, somente.
Algum complemento ou correção?
Comment: Está confuso de entender sua dúvida e, isso é uma pergunta? Você mesmo parece estar tentando responder...
Comment: Desculpem se está confuso... sim, estou tentando responder, é uma questão de prova, mas percebo que pode ser complexo a reposta, depende de o quanto quem vai corrigir a questão quiser aprofundar nos detalhes. Estou tentando não fazer afirmações na resposta, mas apontar o que usualmente acontece na maioria dos compiladores, arquiteturas, convenções etc...
Answer:
O que seria mais vantajoso ao chamar uma função, colocar na pilha da direita para esquerda ou vice-versa?

Se entendi o que deseja saber, no seu código, de uma maneira geral, faz pouca diferença como coloca. É interessante se preocupar com isso só por causa de alguma otimização para alguma situação específica, afinal tem convenção de chamada que colocar os primeiros parâmetros diretamente em registrador, se possível.
Estamos falando de qual arquitetura? Pode variar. O que pode ficar bom em uma pode não ser o melhor em outra. Até como compila pode variar. Na verdade está falando de duas linguagens e isso muda também. Pode variar de acordo com a API que está usando.
Note que há uma diferença entre você escrever seu código e o que o compilador fará. E o que o compilador tomará uma decisão de acordo com a convenção padrão ou outra se o código indicar isto.
C costuma usar da direita para a esquerda. Pascal costuma usar da esquerda para a direita. Mas não é problema do seu código, a não ser que precise interoperar ou precise de otimização extrema.
Note que a convenção típica da linguagem não precisa ser necessariamente a usada nele, e nem é exclusiva dela.
Se não está pensando em otimização, não importa como coloca os argumentos.

E a limpeza da pilha? A função que chama (caller) ou a que é chamada (calee) deve ficar responsável por isso?

Depende da convenção usada, pode ser responsabilidade de ambas, cada uma cuida de uma parte, que é o caso da cdecl, embora estritamente se considere que é a chamadora que é responsável.
Boa parte das convenções deixam a função chamada tratar da preservação e limpeza dos registradores, incluindo o ponteiro para a pilha, o que tende deixar o código mais eficiente, com a stdcall.

Quando a função que chama fica responsável por limpar a pilha, é possível a criação de funções com a quantidade de parâmetros variáveis

Na verdade é possível ter quantidade variável de argumentos, não de parâmetros.
Fora algo que eu não sei ou não tenha me atentado ou entendido na pergunta, o resto parece correto.
Comment: É uma questão que tenho que resolver de uma prova e que está aberta a muitas interpretações, pois tudo pode influenciar: a linguagem, a  arquitetura, a convenção utilizada e a própria interpretação da convenção utilizada, como ocorre com cdecl, por parte do compilador escolhido.  Conclusão: usualmente, o "cleanup" pela função que chama é mais vantajoso por possibilitar argumentos variáveis, mas pode ser aberto a interpretação pelo fato de um stdcall, por exemplo, ser mais eficiente e a ordem de inserção não importa. É uma questão de uma cadeira de microcontroladores com um professor casca...
Comment: Obrigado pela resposta!
Comment: Não é fácil responder algo complexo aqui, ainda mais sem detalhes.
Comment: Pois então! Não existem muitos detalhes, infelizmente! A questão simplesmente afirma que *usualmente* C usa uma convenção e pascal usa outra e pergunta qual convenção é mais vantajosa e o porquê. Visto que a própria questão não entrega tantos detalhes, acho que a resposta deve ser escrita se baseando no que se é esperado *usualmente*. Então vim aqui pedir ajuda para saber se minhas afirmações tem algum fundamento ou não, junto de uma possível correção.
Comment: Sem detalhes a pergunta tende ficar baseada em opiniões e sequer dá para responder, não há critérios claros. Pode ser que dê com o que foi passado em aula, mas não temos essa informação.
Comment: O pior que nem foi passado em aula, e não tem muito haver com a disciplina, mas acho que esse assunto não é de muito interesse da comunidade stackoverflow, de qualquer forma, obrigado pela ajuda. abs


Can't upload 2 images in a single NSURL request in POST method

Question: We are sending right post request to API by multi parting both the image data.So,there  is an issue  both image are not uploading, just  a single image is uploading to server. I have checked the parameter name which are as same provided from API team, here is it:-
<code>#define IMAGE_DP @"Content-Disposition: form-data; name=\"profileimage\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"

#define IMAGE_COVER @"Content-Disposition: form-data; name=\"coverimage\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"
</code>
Building request to upload two images in a single NSURLMutable request
<code> if ([isprofilepicupdated isEqualToString:@"1"]) {

        [postBody appendData:[IMAGE_DP dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[NSData dataWithData:profileimage]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    if ([iscoverpicupdated isEqualToString:@"1"]) {
        [postBody appendData:[IMAGE_COVER dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[NSData dataWithData:coverimage]];
        [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    }
</code>
So how can we append two images in single body of NSURLMutable request?
Answer: <code> NSString *urlString = @"<PostImage-url>";
        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSMutableData *body = [NSMutableData data];

        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

        // file
        for (int i=0;i<(YOUR _ARRAY).count;i++)
        {
            UIImage * myimg=[YOUR _ARRAY objectAtIndex:i];
            NSData *ImageData = UIImagePNGRepresentation(myimg);

            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Disposition: attachment; name=\"img1[]\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[NSData dataWithData:ImageData]];
            [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        }

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"vin\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        // close form
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        // set request body
        [request setHTTPBody:body];

        //ASynchronous request

        [[NSURLConnection alloc] initWithRequest:request delegate:self];
</code>


Will SSL passthrough cause all traffic on the backend server to appear to originate from the load balancer?

Question: When using a load balancer I understand that using SSL termination will result in the backend server seeing all connections as originating from the load balancer itself.  I'm not sure however if the same is true with SSL passthrough.  Since SSL passthrough operates at the TCP layer would it still see the actual originating IP address on the backend server?
Answer: It depends on what exactly your "load balancer" does.
If your load balancer is operating as a form of router then the servers will see the real client IPs.
OTOH if your load balacer is terminating one TCP connection and passing the traffic off to another TCP connection then the backend servers will see the load balancers IP.


Every ribbon graph can be embedded into an oriented surface such that its cyclic orderings are induced from the orientation of the surface.

Question: I have trying to understand the proof of the lemma (Page 14, Lemma: 2.2.4) which is stated as follows:
Every ribbon graph can be embedded into an oriented surface
such that its cyclic orderings are induced from the orientation of the surface.
I have the following confusions:

In the first paragraph, it is written that : for every vertex $v$ define a subset $U_v \subset \mathbb{R}^2$ with $|E_v|$ (the geometric realization of the star of $v$, see  definition 2.2.2) $\textbf{boundary components}$
labelled by the elements of $E_v$ of the form depicted in Figure 2.6 (Only the
straight lines of the boundary are part of the surface.)

In the above context I have the following figure.

What are the boundary components here? Are the red lines boundary components labelled by the elements of $E_v$? As written in the first braket. only the red lines are the part of surfaces

In the second paragraph, it is written  that: Similarly we attach to each edge $e$ a strip $V_e$ as depicted in Figure 2.7
whose two boundary components (again only the straight lines are part of
the surface) are labelled by $e_+$ and $e_-$.

So, in the following figure, which are the boundary components lebelled by $e_+$ and $e_-$? Also, it is written that "again only the straight lines are part of the surface". Which straight lines are only the part of surface in this case?
Please help.
Answer: I'll first answer (2): $e_-$ and $e_+$ are the two horizontal dotted sides. By convention you can take the bottom one to be $e^+$ and the top $e_-$. Do a simple example: look at the ribbon graph with 2 vertices $v$, $w$ and just one edge $e=\{v,w\}$. Represent the vertices as closed disks. The boundary of these disks has an orientation, for example counter-clockwise, which has to be the same for all vertices. Now take the edge $e$ represented as a ribbon and attach it to these disks. For the orientation to make sense, this ribbon must have one horizontal side oriented towards $v$ and the other horizontal side must be oriented away from $v$. These are your $e_-$ and $e_+$.
Regarding (1) and boundary components: Pick a vertex and an edge. Trace the outgoing arrow out of the edge until you return to where you started from. The path that you traced is one boundary component. To find a different boundary component you would pick a different vertex-edge pair that hasn't already been traced. When you trace out all the vertices and edges, you are done.
The simple example from above of two vertices and one edge has just one boundary component. For a more elaborate example, take a triangle represented as a ribbon graph. You will have 2 boundary components, the "inner" and the "outer" sides of the ribbons.

The definition that you're working with is very formal and very difficult and obsucres what otherwise is a relatively simple concept. I think that you would benefit by understanding first a simpler approach.
An orientable cellularly embedded graph (which is equivalent to a ribbon graph) is a graph $G$ embedded (drawn) on an orientable closed surface $X$ such that $X\setminus G$ is a disjoint union of topological disks. This means that
(i) vertices are points on the surface,
(ii) edges are curved segments between vertices,
(iii) crossings happen only at the vertices and
(iv) $X\setminus G=F_1\cup\dots\cup F_k$ for some $k\in \mathbb N$ and each $F_i$ is homeomorphic to an open disk. The sets $F_i$ are called the faces of $G$ (to be more precise, the faces of a particular embedding of $G$).
Let $G$ be cellularly embedded on $X$. We can represent this embedding as follows: let $e=\{v,w\}$. To each edge assign two labels called half-edges in the following way: if you're standing on the vertex $v$ and looking towards $w$ along $e$, then on the left side of $e$ (where left is defined by the orientation of your surface) place a label $i$. And if you're standing on the vertex $w$ and looking towards $v$ along $e$, place a label $j$ on the left side.
In this way you have represented an edge $e$ as a pair of half-edges $i$ and $j$.  This is written as the transposition $(i~j)$. Hence every edge is represented by such a transposition. Now each vertex can be represented by a permutation cycle $(i_1~\cdots i_k)$ which you obtain just by reading the half-edges incident to it in a preferred order (e.g. counter-clockwise).
So what does this have to do with your questions? The $e_-$ and $e_+$ correspond to the half edges $(i~j)$ that we are using to represent an edge. Hence in (2) the $e_-$ and $e_+$ can also be considered as the two vertical dotted sides of an edge which you glue to a vertex (represented as a disk) so that the orientation makes sense. The boundary components are identified with the faces $F_i$ which can be read simply by reading the labels inside a particular face (and if you've done your labeling according to the convention that I've described before, you should have the same number of labels in a face as there are edges bordering it).
Now to obtain a ribbon graph from a cellularly embedded graph, you "inflate" the vertices into closed disks and edges into ribbons and remove the faces. Conversely, to obtain a cellularly embedded graph from a ribbon graph, you glue in the faces, contract the disks into points and ribbons into curved segments.
Comment: @user1138886 that means that the edges can't intersect at any point except at the vertices. For example, you can embed $K_5$ as a cellular graph on the sphere because it is non-planar, so there would be a pair of edges that intersect at a point that is not a vertex. But on a torus this intersection can be resolved so you can embed it cellularly.
Comment: Thanks for your answer. But I have one confusion regarding $(1)$. What are the boundary components in my first figure?
Comment: The boundary components are what you get by tracing the red dashed lines in your figure along the directions given by the arrows. Presumably there's more to that surface than what's shown, so you would need the complete picture to trace the components in full.
Comment: Thanks for your four previous answer. I have one more confusion. In the paragraph you have explained about an orientable cellularly embedded graph or a ribbon graph.  But I cannot understand what we mean by "crossings happen only at the vertices". is that mean that edges may cross, over or under?
Comment: In the answer you have defined the faces of the ribbon graph as follows: $X\setminus G=F_1\cup\dots\cup F_k$ for some $k\in \mathbb N$ and each $F_i$ is homeomorphic to an open disk. The sets $F_i$ are called the *faces* of $G$. Now is it true that each oriented edge is contained in a unique face?
Comment: Do the following figure has $5$ faces?
Comment: In the definition that I gave there are no oriented edges. The role of oriented edges is played by half-edges, and it is true that each half-edge is contained in a unique face, namely that half-edge whose label belongs to the face.
Comment: Can you please write that why it is true?


Can't target specific div with onclick if else event

Question: I have what feels like a simple problem with a portfolio site I'm building. When a user clicks a project image, a hidden containing div should slide down at the top of the page with large images and a description of the project. I've gotten most of it to work except that when I click either of the sample project images, both large versions (the hidden images and project descriptions) slide down, even though I am targeting unique IDs on click. I only want one project to display at a time, obviously. Any help is greatly appreciated.
zoe
http://www.zoeminikes.com/james

email

facebook

behance

PORTFOLIO

BLOG

WIND UP COMICS

PROFILE

<?php include("windup.php"); ?>

<?php include("spill.php"); ?>

WIND UP COMICS

Pen and ink, digital

SPILL

Pen and ink, watercolor

© Copyright 2011   |   James Larson

Made with love by Zoe Minikes

Answer: There is a problem in your if and else code. what value is there inside declared var project?? Please check this.
Here always project = 1. By default you assign this value. So never else condition works. always get project = 1 and if condition works. So your if else condition is wrong. solve this issue i think it works properly.


Shanken (1992) correction for t-statistics

Question: I have done a cross-sectional regression of time-series average returns on estimated Betas (over the same time horizon) to determine average premiums. So far so good. But I was told that the standard t-statistics can be biased, due to the fact that betas are estimated.
There is a solution by:

Shanken (1992) - On the estimation of beta-pricing models [Review of Financial Studies].

It does some small adjustments to the formula of the estimated covariance matrix. However I don't understand how to implement this in R. The paper is also very mathematical, but the solutions are supposed to be easy if you look e.g. at Cochrane Asset Pricing, chap 12 or Lozano "Estimating and evaluating the Fama-French & Carhart models" (2006). I cannot find anything close to that in the original paper though. I think the notation is very different.
Does anyone know how to do it, or has done it already? I needed the adjusted formula in my context (in-sample regression), or even better the R-code.
Comment: @User1865345, thank you! I have included a more complete reference.
Comment: Your link is dead. This is why the recommended practice is to include a full reference in addition to the link. Otherwise it gets very difficult to track down the source.
Comment: I have added the archived version @RichardHardy.
Answer: I sent a similar question to the R-help mailing list only a few days ago. Today, I believe to have found an answer. See my post here.
My problem was not to include a coefficient of the first regression but the residuals. Still, my example seems to be easily adaptable to your case.
Comment: Welcome to the site, @philipp. An answer like this is fine, but note that CV is not a discussion forum. We aim to build a permanent repository of high-quality statistical information in the form of questions & answers--they aren't supposed to be chatty. Since you're new here, you may want to read out [about page](http://stats.stackexchange.com/about), which contains info for new users. There is also some information about answering questions on CV on our [help page](http://stats.stackexchange.com/help/on-topic).
Comment: Apologies, I just wanted to make sure Rian1987 got linked to a similar problem which I hope could be solved now. I wanted to comment but was unable to do so (due to a lack of reputation/ credit points?). Nevertheless, thank you for editing my post!
Comment: No problem, @philipp. Unfortunately, you can't comment everywhere until your reputation >50.
Comment: @philipp thanks for the link, maybe someone can clarify this for us ;)