Bayesian Biased Prior Formula

Question: I know that for a Bayesian uniform/flat prior, the formula is 1/n (and n=1), as each value has an equal chance of being chosen.
However, is there an equation for when the prior is biased/informative? For example, so that the prior is skewed to the left or to the right?
Comment: Right, and that has nothing to do with being uninformative.
Comment: Suppose I give you a weighted coin with some unknown bias probability $0\le p\le 1$, then you might argue that the uninformative belief over $p$ is uniform over $[0,1]$.  Now, suppose you travel to another planet where the aliens like to measure biases in *odds* $0 \le o = \frac{p}{1+p}$.   Then, you might similarly argue that the uninformative belief over $o$ is flat on $[0, \infty)$.  But, these aren't the same distribution.  So which one is uninformative?
Comment: @Neil G: In a finite parameter set, the uniform can more easily be argued to be "non-informative" as the change-of-variable argument does not apply so naturally.
Comment: uniform has nothing to do with uninformative
Comment: @NeilG when I say uniform I mean flat prior
Comment: @Xi'an You're right.
Answer: Yes, but just as there are many ways of a curve not being flat, there are many different non-flat priors. For example, a coin's bias could have a $\operatorname{Beta}(α, β)$ prior, which is only flat when $α$ and $β$ are both 1, or it could have a triangular prior with endpoints $0$ and $1$, which can't be flat no matter how you set the remaining parameter.

Bayesian Biased Prior Formula


How to get Total Number of Pages of a PDF using Ghostscript and Python

Question: I didn't found a python compatible script to count the number of pages inside a PDF using python with Ghostscript.
I want to save the number of pages in a python variable.
Command line scripts are alrady present but i want to use it with python.
Let me know if you have found any.
Answer: Originally, I wanted to do the same: to use ghostscript to count the number of pages in a pdf file. However, I came across another lib called pypdf, and eventually, I decided to use that instead. The following function returns the page count of the pdf available at the passed in path. I hope this helps.
import pypdf

def num_of_pages_for_pdf(pdf_file_path):
    """Returns the page count of the pdf available at the input path.

        Parameters:
            pdf_file_path (str): Local path of the pdf. E.g. '/tmp/example.pdf'
    """
    pdf_reader = pypdf.PdfReader(pdf_file_path)
    return len(pdf_reader.pages)

Comment: isn't there any method to count without pypdf library. i mean using ghostscript only


Performance of get a specific character of a string in Python 2.7

Question: Suppose I want to get a specific character of a string in Python 2.7, suppose
a = 'abcdefg...' # a long string
print a[5]

Wondering when access any specific character of a string, for example, access the 5th element, wondering what is the performance, is it constant time O(1), or linear performance O(n) either according the 5 (the position of the character we are accessing), or linear performance O(n) to the whole string (len(a) in this example)?
Comment: I like the idea that it might be linear performance on the length of the string. Like, accessing the first character of a huge string takes forever because it has to preload it all, or it's stored in some garbled dictionary/linked list thing :) Python has done weirder things I suppose...
Answer: >>> long_string_1M ="".join(random.choice(string.printable) for _ in xrange(1000000))
>>> short_string = "hello"
>>> timeit.timeit(lambda:long_string_1M[50000])
0.1487280547441503
>>> timeit.timeit(lambda:short_string[4])
0.1368805315209798
>>> timeit.timeit(lambda:short_string[random.randint(0,4)])
1.7327393072888242
>>> timeit.timeit(lambda:long_string_1M[random.randint(50000,100000)])
1.779330312345877

looks like O(1) to me
they acheive it because a string is consecutive memory locations so indexing into it is simply a matter of offsetting ... there is no seek (at least that is my understanding)  if you know c/c++ its something like *(pointer+offset) (its been a long time since ive done C so that might be a little wrong)
Comment: I assumed it because of the details at https://wiki.python.org/moin/TimeComplexity ... although they do not callout string specifically it is close enough to a list ...
Comment: I agree - anything in that table that talks about tuples can probably be applied to strings (didn't look that carefully, but probably). There are a bunch of places where the python docs draw analogy and the implementation is similar
Comment: Thanks Joran, vote up and I have the same feeling/result, and curious how it is implemented internally to have O(1) performance? Any detailed or high level idea is appreciated. :)
Comment: Nice reference Joran. Vote up, and will mark your reply as answer in 2 mins when SO allows me. You answered too fast. :)
Answer: In addition to Joran's answer, I'd point you to this reference implementation, confirming his answer that it is O(1) lookup
/* String slice a[i:j] consists of characters a[i] ... a[j-1] */
static PyObject *
string_slice(register PyStringObject *a, register Py_ssize_t i,
             register Py_ssize_t j)
     /* j -- may be negative! */
{
    if (i < 0)
        i = 0;
    if (j < 0)
        j = 0; /* Avoid signed/unsigned bug in next line */
    if (j > Py_SIZE(a))
        j = Py_SIZE(a);
    if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
        /* It's the same as a */
        Py_INCREF(a);
        return (PyObject *)a;
    }
    if (j ob_sval + i, j-i);
}

Why this should be your intuition
Python strings are immutable. This common optimization allows tricks like assuming contiguous data when desirable. Note that under the hood, we sometimes just need to compute the offset from the memory location in C (obviously implementation specific)
There are several places where the immutability of strings is something that can be relied on (or vexed by). In the python author's words;

There are several advantages [to strings being immutable]. One is
performance: knowing that a string is immutable means we can allocate
space for it at creation time

So although we may not be able to guarantee, as far as I know, this behaviour across implementations, it's awfully safe to assume.
Comment: lol ... great minds think alike ... (see my edit) nice link to ref +1 from me
Comment: @Joran haha ya +1 on yours too , that edit came in as I was typing mine up. I was hoping you weren't going to throw in my link otherwise I would have to cancel the post
Comment: @IharBury thanks for the feedback on an old question :) Why is PyString_FromStringAndSize not O(1)? Looking at the same reference implementation, I don't see any "loops"; there is a malloc call, is that what you consider to be "not O(1)"? I don't usually consider those proportional to the size of the string at all in, which seems consistent with other SO answers: https://stackoverflow.com/questions/282926/time-complexity-of-memory-allocation, https://cs.stackexchange.com/questions/83834/what-is-the-time-complexity-of-memory-allocation-assumed-to-be
Comment: @IharBury hmm where does that happen *on the entire string*? It's true that it might copy the slice of the string, but the OP Is asking about accessing a single character, so that would be a memcpy on one element (and the reference has a specific case, it looks to me, to *not* memcpy for size-1 objects, but intern them (line 104). Note that j-1==1 for the OP's case, we're not calling PyString_FromStringAndSize on the entire initial object


How to show/hide the prefix/suffix of fields in node templates?

Question: I previously asked a question about hiding the prefix/suffix in fields template here, now I want to understand how can I programmatically hide the prefix or suffix of numeric fields in nodes templates only?
Comment: You cannot. The field template that renders those values has no access to context in which it is being rendered(ie. access parent(s)). The only solution is to use hook_form_alter in your theme and alter specific fields in specific form.
Answer: On node level you can configure the content of prefix and suffix in the field settings and you can show/hide them for each view mode separately.
So you rarely need to override this programmatically and this is not easy, because the prefix and suffix is not added as extra render elements, but to the markup string of the formatted field value. So you need string manipulation to subtract the prefix and suffix again.
A simple solution could be to display the database value, and so bypassing the field template altogether, by using the node object:
{{ node.field_example.value }}

But then you lose all formatting options, not only prefix/suffix.
Answer: You could remove the prefix via
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_view_alter/8.2.x.
In case you need it for comments.
/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_comment_view_alter(array &$build, CommentInterface $comment, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($comment->getFieldName() === 'field_name') {
    unset($build['#prefix']);
  }
}


Solving recurrence relation in 2 variables plus constant

Question: I've encountered this question, asking to solve the recurrence
$$F(n,m) = F(n-1,m) + F(n,m-1)$$
for some initial conditions. I wonder how the solution would change if we add a constant, say
$ G(n,m) = G(n-1,m) + G(n,m-1)+2$.
One answer for the mentioned post suggested generating functions. What would change here? For simplicity, let's assume $G(1,m) = m − 1$ and $G(n, 1) = 0$.
Answer: Let $H(n,m)=G(n,m)+2$, then $$\begin{aligned} H(n,m)&=G(n,m)+2 \\ &=G(n-1,m)+G(n,m-1)+4 \\&=(G(n-1,m)+2)+(G(n,m-1)+2) \\&=H(n-1,m)+H(n,m-1) \end{aligned}$$
You can now solve the recurrence for $H$ and deduce the recurrence for $G$ by writing $G(n,m)=H(n,m)-2$.
Comment: It is the one you talked about in your question that can be solved using generating functions. A lot of calculus though !
Comment: Yeah, tried to use the method vonbrand gave in that post, but it's non-trivial to find an analytic solution. Will spend some time on it... Thanks again!
Comment: Thanks, nice trick! I'm afraid I cannot extract $H$ from the resulting equation though.


What is an example of a continuous function that doesn't have a derivative at any point?

Question: Please give an example of a continuous function $f:[0,1]\to\mathbb R$ which doesn't have a derivative at any point. I can't think of anything, can someone help please?
Comment: Most Brownian motion paths are like that.
Comment: Possible duplicate of [Function example? Continuous everywhere, differentiable nowhere](https://math.stackexchange.com/questions/31054/function-example-continuous-everywhere-differentiable-nowhere)
Comment: This was asked so many times, already the example I gave was closed as a duplicate.
Answer: There is a well-known example of a continuous function that is not differentiable by Weierstrass:
https://en.wikipedia.org/wiki/Weierstrass_function
Comment: Thank you! I didn't know that example.
Answer: For example, $f(x)=1$ when $x$ is rational, and $f(x)=0$ when $x$ is irrational.
Comment: Thats right, but I forget to write in condition that I need a continious function.
Answer: Just take any function which is nowhere continuous.
Finding an $f$ which is continuous but nowhere differentiable is much harder. The most famous example is the Weierstraß function, which was explicitely constructed to have that property.
Before its construction, it was conjectured, that every continuous function was differentiable except on a set of isolated points.
So its not surprising that you cannot think of anything


Computing Darboux Sums

Question: Let $f : [0,1] → R$ be defined by $f(x) := x^3$ and let $P :=$ {$0,0.1,0.4,1$}. Compute $L(P, f)$ and
$U ( P, f )$ .
(Notation meaning the upper and lower Darboux Sums)
Comment: This is so easy to compute them just using the definition of such sums, and the fact that you're dealing with a monotone function ($\inf$ is attained in the beginning of the interval, $\sup$ in the end) - perhaps, you can try doing it yourself now?
Comment: In class we went over an example where the delta $x_i$ remained the same so we could pull out a constant and then add up the sum. What would this case be since the partitions are not equal each time?
Comment: You have just 4 entries in the sum: find the lowest value, multiply by the partition interval length, add to previous result etc.
Comment: L(p,f) = (0.1)(0)+(0.3)(0.1)+(0.6)(0.4) correct?
Comment: Are you computing $x^3$?
Comment: so it would be (0.1)(0)+(0.3)(0.001)+(0.6)(0.064)?
Comment: Yes ${{{}}}{{{}}}$
Answer: I don't see how what you've typed is a partition but my answer below applies in general (perhaps the $P$ you've written down is the set of differences so the set of partition points is $\{0,1,5,6\}$ but then this isn't a partition of $[0,1]$; rather it's a partition of $[0,6]$ ...):
The function $f:[0,1]\to \mathbb{R}$ is monotonically increasing. Prove that for any such monotonically increasing function, and any partition $P=0=x_0<\cdots<x_n=1$, we have:
$L(P,f)=\sum_{i=0}^{n-1} f(x_i)(x_{i+1}-x_i)$
$U(P,f)=\sum_{i=1}^{n} f(x_i)(x_{i}-x_{i-1})$.
I hope this helps!
Comment: I don't understand your concern about partition: OP wrote $\{0,0.1,0.4,1\}$ which is an appropriate partition of $[0,1]$, isn't it?
Comment: @Ilya I thought that the points of a partition of $[0,1]$ must be elements of $[0,1]$ (i.e., a partition $P$ of $[0,1]$ is a sequence $0=x_0<\cdots<x_n=1$). If this isn't the definition of a partition, then could you please tell me the correct definition? (I learned about Riemann-Darboux integration from Rudin's textbook where this was the definition adapted.)
Comment: @Ilya Oops! Now, I see that the partition is $\{0, \bf{0.1}, \bf{0.4}, 1\}$. I didn't notice the decimal points; I thought they were commas.

Computing Darboux Sums


Why will my Javascript run fine normally, but minnified, it won't?

Question: I have a webapp that I'm developing that uses a front-end of HTML + Javascript (Angular 1.5.0) + CSS. The website performs fine when I run it on my localhost. I have an /index.html file. This file imports my javascript code like this:
But now I have just implemented automated linting, uglifying etc. using Grunt. Grunt very nicely converts my single Javascript file (/app/app.cs) to a minnified one (/dist/js/app.min.js). I changed my /index.html to include the minnified Javascript instead: . But now the application stops working. And in the Browser's dev console, I see the following error:
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:unpr] Unknown provider: a
http://errors.angularjs.org/1.5.0/$injector/unpr?p0=a
    at http://127.0.0.1:8080/bower_components/angular/angular.js:68:12
    at http://127.0.0.1:8080/bower_components/angular/angular.js:4397:19
    at getService (http://127.0.0.1:8080/bower_components/angular/angular.js:4550:39)
    at injectionArgs (http://127.0.0.1:8080/bower_components/angular/angular.js:4574:58)
    at Object.invoke (http://127.0.0.1:8080/bower_components/angular/angular.js:4596:18)
    at runInvokeQueue (http://127.0.0.1:8080/bower_components/angular/angular.js:4497:35)
    at http://127.0.0.1:8080/bower_components/angular/angular.js:4506:11
    at forEach (http://127.0.0.1:8080/bower_components/angular/angular.js:321:20)
    at loadModules (http://127.0.0.1:8080/bower_components/angular/angular.js:4487:5)
    at createInjector (http://127.0.0.1:8080/bower_components/angular/angular.js:4409:19)
http://errors.angularjs.org/1.5.0/$injector/modulerr?p0=raptorApp&p1=Error%…F%2F127.0.0.1%3A8080%2Fbower_components%2Fangular%2Fangular.js%3A4409%3A19)

Why will the normal Javascript file work fine, but the one minified by Grunt won't? How can I fix it?
Comment: Using grunt-ng-annotate before minnifying it worked for me. Thanks! https://www.npmjs.com/package/grunt-ng-annotate
Answer: Your angular component is being minified and there is no way to know what service to inject. You should decorate your controllers and other pieces to allow Angular to work properly. Read up on it here: Angularjs minify best practice
Comment: Using grunt-ng-annotate before minnifying it worked for me. Thanks! https://www.npmjs.com/package/grunt-ng-annotate


OpenVPN client source port keeps changing, TLS fails

Question: This problem only happens behind certain routers/gateways and i have no control over. this is my clients connecting over public internet. what seems to be the problem is that the source PORT changes almost instantaneously. and yes this is only specific to certain devices for example fortigate devices when they are the gateway. and yes i ruled out the devices, my gateway, my server, everything. since when they try over Cellular it works immediately. i don't know what's wrong with these gateways and why do they do that.
Also, could it be an issue when there is asymmetric wan routing taking place ?
i'm using TCP and NOT UDP. i tried UDP and still the same.

Tue Mar 12 00:11:47 2021 X.X.X.X:47804 TLS: Initial packet from [AF_INET]X.X.X.X:47804, sid=(bla bla bla )

Tue Mar 12 00:11:49 2021 X.X.X.X:47807 TLS: Initial packet from [AF_INET]X.X.X.X:47807, sid=(WHATEVER)

Tue Mar 12 00:11:51 2021 X.X.X.X:478XX TLS: Initial packet from [AF_INET]X.X.X.X:478XX, sid=(WHATEVER)

and it keeps on and on ( TLS failed and Client instance restarting ) and XX keeps incrementing
is there any way to "POKE" a NAT port open till the client finishes the negotiation ? i set Keep-alive to 1 second which is the bare minimum i think and still
thanks in advance, i'm losing my mind over this
EDIT :
someone also seems to have that exact problem HERE IS A SCREENSHOT
Comment: Then that's fortigate is a thing that does some DPI by default, that simple. Probably it monitors a port 443 and expects HTTPS protocol there, but when it sees something unexpected it drops that for security. Or even fortigate tries to do ssl bumping, I don't know. Anyways, OpenVPN doesn't do HTTPS protocol even if running on port 443, it always runs its own protocol, and it's easy to find out this is not HTTPS.
Comment: Yes, it could be caused by asymmetric wan routing. What's in the client log?
Comment: Two seconds difference suggest that the initial TCP handshake fails and the client is trying a second and a third connection. Can you take a packet capture at the server to verify this?
Comment: @MathiasWeidner
the client never receives the opposite packet. i can show you a screenshot on android. ( received packets = 0 , sent packets >0 and keeps on climbing. while on the server it replies to the same port..
Comment: @NikitaKipriyanov

just hangs on Authenticating.. keeps on sending packets and the ( recevied packets ) is zero, never increases
Comment: This is very strange. Could you please show more info, on how network on the server is configured and how it reaches an internet. Where affected clients are from (geographically)? If replies seem to be sent on the server but don't get received by the client, it could be that some deep inspection is going in the middle and it detects OpenVPN and drops it forcefully.
Comment: @NikitaKipriyanov yes i suspect that also. i'm running OpenVPN on port 443 and TCP, i thought that it'd pass any firewall like any HTTPS traffic and remain under the radar..  **PS** check the updated screenshot that i posted

server is running on an OpenWrt router and added to DMZ on the modem. **no** port translation takes place. i have access to the router's NAT table and traffic is directly forwarded to the server ( other router ). also verified using Tcpdumps. soo server side is fully functioning. and by the way in can connect from 98% of the networks

ONLY fortigate has that problem
Comment: @NikitaKipriyanov hmmm never knew that.. i thought it was disabled by default.
and i didn't even know it tries to intercept HTTPS traffic and verify it or literally MITM it. isn't that invading privacy ?

also can you suggest another port ? i tried TCP 53 and it didn't work at all i don't know why. i want it immune to locked down network and networks that run ACLs

also check the screenshot i updated the post. apparently someone has that exact problem
Comment: A skillful admin could disable any unwanted traffic, if they need. Especially if that is company security policy to deep inspect traffic, and admins get paid for exactly that. My opinion that's not invanding privacy. The corporate internet is for work, not for some suspicious VPNs, don't you think? If this VPN is for work, user could go to admin and explain them and they would permit it, but then why hiding at HTTPS port?
What to do? Try running a service on several ports (1194), configure several connection profiles in client configs (multiple `remote` lines at least), hope some would work.
Comment: Agred, I wouldn't use port 443 for OpenVPN. Try using its default port, or some random high port number.
Answer: You have no problem with the VPN, your problem is with the TCP connection that is probably restricted by the Fortigate firewall (fortigate device) you mentioned.
The way to solve this is to talk to the administrator of the firewall and ask for permission to contact the VPN server.
Comment: it isn't a workplace, they are literally public networks !

sometimes public networks put fortigate to block large downloads and "bandwidth consuming sites" just wanted to clarify that it is **not** Work internet or something like that. i just wanted to fix it so that a road warrior can connect to the network. nothing serious. sooo i can't talk to anyone. that's why i thought there is a method to make it work
Comment: If someone goes so far to block large downloads, this would be the one to talk to. If you just want to overcome the block for yourself, try different ports or UDP and set up your VPN server accordingly.
Comment: Hear this..! This is the latest updates. So I made 3 instances on ports 80, 53, 8080. I  went to a place which I know uses fortigate and I have that issue there. NONE of them worked... on the server the packets never made it...how on earth does fortigate monitor port 53 and blocks connections. ..is that even by default ?


FitNesse playing with variables using basic operation

Question: This is a very simple question, because I could create a method for do that but:
Could I do basic operations with a variable defined inside a Dofixture table?
Like:
Getting the var: |OperationResult|<<MyVar|
And then, use for example Check|>>MyVar+1|
I use >>MyVar+1, or for example  (>>MyVar / >>OtherVar)
Could I change if you are using SLiM or FitSharp plugin?
Answer: You can retrieve the String variables even objects in a fitness variable and then passing that variable to another method call. You can even do more tricky things with splitting the object execution but I am not sure about other operations.
This is are some examples of how I am using some variables in the fitness test pages:
Example 1:
this is how you get the value:
|$MyVar=|methodReturningMyVar|

this is how you can pass the value
|methodReceivingMyVarValue|$MyVar|

Example 2:
Splitting the execution of a script in 2 parts
|Scrip| MyScriptWithSplitedExecution|
|$MyScriptWithSplitedExecutionObject| get Instance |
|doFirstPartOfProcessing|

here you can do some other operations/tests

|Scrip|$MyScriptWithSplitedExecutionObject|
|doSecondPartOfProcessing|

For this to work you have to implement the getInstance method in your object and make it return a pointer to himself.
All this were tested with Slim, I don't know if are working with FitSharp.
Answer: No, operations like this are not supported.


Jarsigner War file

Question: I have an applet of a third party in *.war format, i want to jarsign it with my verisign certificate in order to change this:

Into this

I have tried this way
<code>jarsigner -storetype pkcs12 -keystore CompanyCert.pfx -storepass myStorePass FileApplet.jar myAlias
</code>
And it looks like signs well but i get still the advice of the first image.
Anybody knows how to do that?

And Key Usages:
Answer: Ok, i have found the problem, its needed an codeSignning cert in ExtendedKeyUsages. I get one and it works

Jarsigner War file


To show $a$ is removable singularity of $f$

Question: Let $X,Y$ be two compact Riemann surfaces. Let $a \in X$ and $f : X-\{a\} \to Y$ be a injective holomorphic map. Prove that $a$ is removable singularity of $f$.
I want to apply Riemann removable singularity theorem somehow but I am unable to get it. Any help will be appreciated.
Answer: I have an idea, but (UPDATE) with a gap:
Note that $f:X-\{a\}\to f(X-\{a\})$ is biholomorphic.
Let $\phi: U \to D$ be a chart from $U\subseteq X$ to the unit disc $D$ such that $a\in U$ and $\phi(a)=0$. Then $\psi:f(U-\{a\})\to D^\times$ defined by $\psi=\phi\circ f^{-1}$ is a biholomorphism from $f(U-\{a\})$ to the punctured unit disc. Define the sequence $z_n:=\frac{1}{1+n}$ in $D^\times$. Since $Y$ is compact, the sequence $\psi^{-1}(z_n)$ has a convergent subsequence with limit point $b$.
Here's the gap: I want to argue that $V:=f(U-\{a\})\cup\{b\}$ is open. Intuitively, $b$ fills the puncture in the open set $f(U-\{a\})$, just as zero fills the puncture in $D^\times$. However I struggle to translate that thought to topology.
If we assume it is true, then $\psi$ is a bounded holomorphic function on $V-\{b\}$ and thus, by the removable singularity theorem, $\psi$ can be extended to a holomorphic function on the open set $V$. In order for the map to be continuous, $b$ must be sent to zero: $\overline{\psi}:V\to D$ with $\overline{\psi}(b)=0$.
From then on, it would be simple: $\overline{\psi}^{-1}\circ \phi$ is a biholomorphism between $U$ and $V$. Hence the mapping $$F:X\to f(X-\{a\})\cup\{b\},\quad x\mapsto\begin{cases}f(x), & x\neq a\\ (\overline{\psi}^{-1}\circ \phi)(a)=b,& x=a\end{cases}$$ is biholomorphic. Since $X$ is compact and open, $F(X)=f(X-\{a\})\cup\{b\}$ is compact and open in $Y$, which is only possible if $F(X)=Y$.
Comment: Sorry for such a late reply. Could you please elaborate on "Since $Y$ is compact, there is a $b \in Y$ such that $:=(−\{\})\cup \{\}$
is isomorphic to the unit disc. Let $\phi :\toℂ$ be a chart of $Y$ with $b \in W$. Then $\phi ( \cap )$ is an open neighborhood of $\phi ()$"?
Comment: No worries, you posted the question years ago, so, if anything, it's my answer that's late ;)
Comment: Take a sequence $(z_n)_{n\in\mathbb{N}}\subseteq D^\times$ on the punctured unit disc $D^\times$ that converges to zero: $\lim_{n\to\infty}z_n=0$. By means of the isomorphism $\psi:D^\times\to f(U-\{a\})$, you get a sequence $\psi(z_n)$ of points in $f(U-\{a\})\subseteq Y$. Since $Y$ is compact, this sequence must have a limit point $\lim_{n\to\infty}\psi(z_n)=:b\in Y$ and we can naturally expand the isomorphism $\psi$ to $\overline{\psi}:D\to f(U-\{a\})\cup{b}$ by sending zero to $b$.
Comment: Then, since $V$ is isomorphic to the unit disc, $b$ is an inner point of $V$ and $V$ is an open neighborhood of $b$. Since $W$ is also an open neighborhood of $b$, the intersection $V\cup W$ is again an open neighborhood of $b$. Finally, charts are homeomorphisms and hence open maps. Therefore, in the image, $\phi(V\cup W)$ is an open set that contains $\phi(b)$, hence an open neighborhood of $\phi(b)$.
Comment: Everything in the above comments is clear except the uniqueness of $b$; $\psi(_)$ may have multiple limit points, right?
Comment: Well, I don't use the uniqueness of $b$ anywhere, so is there any point in showing it?
Comment: However, you could show it like this: let $(\tilde{z}_n)_{n\in\mathbb{N}}$ be another choice of a sequence that converges to zero and assume that $\lim_{n\to\infty}\psi(z_n)\neq\lim_{n\to\infty}\psi(\tilde{z}_n)$. Then define $(\omega_n)_{n\in\mathbb{N}}$ as the sequence $z_1,\tilde{z}_1,z_2,\tilde{z}_2,z_3,\tilde{z}_3,...$. This sequence does converge to zero, but $\psi(\omega_n)$ does not converge due to $\lim_{n\to\infty}\psi(z_n)\neq\lim_{n\to\infty}\psi(\tilde{z}_n)$. This contradicts the compactness of $Y$.
Comment: By compactness, you can only show that every sequence has a convergent subsequence, so I don't see any contradiction. Also, if $b$ is not unique then how to apply the Riemann removable singularity a nbhd of $a$?
Comment: Ah yes, I see the problem... Riemann surfaces are metrizable, so compactness does imply completeness. Therefore the Cauchy-sequences must converge in $Y$. This is what I was thinking of. However, it is not directly clear that the Cauchy sequence on the unit disc maps to a Cauchy sequence on the surface. This might get unnecessarily complicated.

However, we really only need the existence of $b$.
Comment: Removable Singularity Theorem:

Let $X$ be a Riemann surface, $U\subseteq X$ an open subset and $a\in U$. Let $f:{U-\{a\}}\to {\mathbb{C}}$ be a holomorphic function. If there is a neighborhood $T\subseteq U$ of $a$ such that $f$ is bounded on $T-\{a\}$, then there exists a unique holomorphic function ${g}:{U}\to {\mathbb{C}}$ with ${g}|_{U-\{a\}}=f$.
Comment: I updated my answer, thinking I found a way to simplify it, only to find that it does in fact contain a larger gap... :( Maybe you have an idea how to fill it?
Comment: Somehow I think the key of this is proving that the complement of $f(X-\lbrace a\rbrace)$ in $Y$ is a finite set (for example by showing it's discrete). That way, it would be reduced to https://math.stackexchange.com/questions/2554046/extending-isomorphism-of-punctured-riemann-surfaces?noredirect=1&lq=1
Comment: But seeing it's not already part of the hypothesis makes me suspicious... Are you sure this assertion is true? @MayureshL
Comment: Nevermind, the post I linked actually gives the solution (first answer). Advanced theorems like Riemann-Roch or Uniformization theorem were needed. @mgns Nice try, though.
Comment: @Compacto Yes, the assertion is true.
Answer: As the chain of comments is becoming too long, I'm gonna post as an answer that the problem was addressed (and solved) in this other post:
https://math.stackexchange.com/a/2554589/971932
It requires use of deeper theorems such as Riemann-Roch (or Riemann's existence theorem, I think) or Uniformization.


Conditional Ternary Operator for v-model

Question: I'm trying to do the following in my Vue application:
<template v-slot:cell(selected)="{ item }" >

</template>

I have to make sure item.selected is not undefined or else I get an error Cannot read properties of undefined (selected). When I use the conditional ternary operator in my v-model, I get a Syntax Error: Unexpected token. Why is that? How do I fix this so that I can still use item.selected even if it's not defined?
Answer: You can use v-if/else directives to define checkboxes for both cases:


How to setup custom breadcrumbs with taxonomy?

Question: I have content types that use taxonomy to categorize content. The Pathauto url alias structure is 'content type' / 'taxonomy term' For example:
Food/japanese - where food is the content type and japanese categorizes it.
I am using Custom breadcrumbs with great success except for when viewing a taxonomy page at it's alias. breadcrumbs don't work at all. The term does not show up, the parent does not show up, nothing happens. I have the 'custom breadcrumbs taxonomy' module enabled.
I saw that enabling that sub module created a place where I could create a custom path for each term. Technically I could go through and create a path, but I have 100s, if not over 1000 different terms and more added all the time. It would not be possible to use the term.
This would be very easy if I could just specify 'content type' / 'term' like I do for Path auto. One entry could take care of every situation. Is this possible? anyone know how I can configure this correctly?
Answer: Not sure if this is the best solution, but you can do that always with theme_breadcrumb() function in your theme like this:
function YOUR_THEME_breadcrumb($vars) {
    $breadcrumb = $vars['breadcrumb'];
    if (count($breadcrumb)) {
        if (arg(0)=='taxonomy' && arg(1)=='term') {
            $term = taxonomy_term_load(arg(2));
            if ($term->vid==YOUR_VOCABULARY_VID) {
                $breadcrumb[] = l('Your landing page', 'landing-page-url');
            }
        }
        return '

'.implode('»

', $breadcrumb).'

';
    }
}

I'm assuming you're using D7.
Comment: I found that doing this was sufficient for my purposes. I tried Hansel and it was far too convoluted.
Answer: I ran into a similar issue in D7 and opted to use Easy Breadcrumb: http://drupal.org/project/easy_breadcrumb.
Easy Breadcrumb compiles the breadcrumb from the URL, and is simple to set up.  But it seems like it should work in yours.
Here is an example of how it works:

URL: www.example.com/portfolio/french
Breadcrumb: Home › Portfolio › French

What is wonderful about Easy Breadcrumb is that it doesn't matter whether you are using content types, taxonomies, views, or whatever, because it only looks at the URL.  Because it relies strictly upon the URL, however, it won't be appropriate in many cases.
I wasn't comfortable with how it handled searches (Home › Search › Content › [Search term]) and recently messaged the maintainer about the possibility of being able to list instances in which Easy Breadcrumb would be omitted, and he obliged in the latest release.
Comment: The code in that module inspired a theme function to use the url structure as the taxonomy structure. Because my urls are 'hackable' this works great! Thanks for the direction.


Sample size function for McNemar test of repeated proportions in R

Question: I have been scouring CRAN and Google for a function (that I wouldn't have to code myself) that would calculate the sample size needed for a pre-post design with a dichotomous outcome - to no avail. If I'm wrong, please let me know!
I came across an R script from a university course and was wondering if someone wouldn't mind double-checking it for me - I've revised it a bit. (the URL is: http://www.statistik.lmu.de/institut/lehrstuhl/semwiso/bm-sose2009/CaCo/v8_4.pdf)
<code>samsize.mcnemar <- function(pi.01, pi.10, alpha, beta, sided)
                {
pi.d <- (pi.01 + pi.10)
N <- (qnorm(1 - alpha/sided) * sqrt(pi.d) + qnorm(1 - beta) *
    sqrt(pi.d - (pi.01 - pi.10)^2))^2/(pi.01 - pi.10)^2
return(ceiling(N))
}
# in my case, I am assuming that the 0 to 1 change will be 0.13 and that no
# one will change from 1 to 0

samsize.mcnemar(pi.01 = 0.13, pi.10 = 0, alpha = 0.05, beta = 0.2, sided = 2)
</code>
First, does this look correct?
Second, since this is not a matched-pairs design, I am not assuming that the intervention will cause people to revert back (if they are already performing the healthy behaviour). Should I be more conservative?
Thanks!
Comment: Hi, i think G*Power 3 provides power analysis for McNemar test too. You can take a look at it [here](http://www.gpower.hhu.de/en.html).
Answer: I compared the results I get with my function with this quick look-up table I found from StatsToDo (https://www.statstodo.com/SSizMcNemar_Tab.php#). I didn't try all combinations, but for the handful I did try, the sample size estimates were the exact same. I am pretty confident that the function is correct. Feel free though to add further comments


what is the relation between $\tau _1$ and $\tau _2$?

Question: Consider the space $\mathbb{R}^3$. Let $L$ and $P$ be the set of all lines and set of all planes in $\mathbb{R}^3$. Let $\tau _1$ and $\tau _2$ be topologies on $\mathbb{R}^3$ generated by subbases $L$ and $ P$ respectively.
Then what is the relation between $\tau _1$ and $\tau _2$? are they equivalent or one is finer than other.
My thought:
 Intersection of two lines give a point so $\tau _1$ is discrete topology. Intersection of planes gives us st. line. I thought $\tau _1$ is finer than $\tau _2$.
Comment: What happens in general when you intersect $3$ planes?
Answer: Intersection of three planes gives us a point, so $\tau_2$ is also discrete, and the two topologies are the same.
Note that usually, when we say one topology is "finer" than another, we don't exclude the possibility that they are equal. Thus you are right that $\tau_1$ is finer than $\tau_2$, even though they are both discrete.
Comment: So they are actually equivalent.
Comment: @GobindaGarai Yes, they are. Not just equivalent. _Equal_.


Django + Apache + mod_wsgi problems

Question: I have spent the last 2 days attempting to deploy a Django application I've built and tested using the development server built into manage.py. I've read countless tutorials and snippets, and cannot seem to get anything working correctly. At my wits end, I've come here seeking advice.
Can anyone point me toward a start-to-finish tutorial or blog post that will take me out of the development server and onto Apache + mod_wsgi?
Edit: Having read through the Apache httpd.conf file, I have begun to understand more what Apache is doing, and what the tutorials are doing. However, having completed the Django + mod_wsgi tutorial, substituting in my paths where appropriate, and restarting apache, my / is still mapping to "It works!", the standard Mac Apache success page.
Here is the code I took from the Django tutorial, converted for my purposes, and put at the end of my httpd.conf...
<code>    # Django configuration

WSGIScriptAlias / /Users/administrator/Developer/billing/apache/django.wsgi

<Directory /Users/administrator/Developer/billing/apache/django.wsgi>
Order allow,deny
Allow from all
</Directory>

AliasMatch ^/([^/]*\.css) /usr/local/wsgi/static/styles/$1

Alias /media/ /Users/administrator/Developer/billing/media/
Alias /static/ /Users/administrator/Developer/billing/static/

<Directory /Users/administrator/Developer/billing/static>
Order deny,allow
Allow from all
</Directory>

<Directory /Users/administrator/Developer/billing/media>
Order deny,allow
Allow from all
</Directory>
</code>
Edit #2: The "It works!" page must have been cached, because having changed nothing from the above posted code, I now get a permission denied error when I try to go to /.
Comment: What is the specific obstacle are you running in to? What tutorials have you tried? More specific information will help with getting your question answered.
Comment: The primary obstacle is how gosh darned simple it is to set up the development server, and how relatively complicated it seems to be to move from that simplicity into even a simple production environment. I have tried using the official django + mod_wsgi tutorial: https://docs.djangoproject.com/en/1.3/howto/deployment/modwsgi/ as well as a smattering of miscellaneous blogs and such. I think what is hurting me the most is that I have no experience deploying Apache. I've only ever used one-click/command development servers. It is hard for me to even know where to start. Most tuts assume a lot.
Comment: I'm starting to feel like coding the application is the easy part!
Comment: It is also worth noting that this application is entirely internal. Many tutorials are focused on outward-facing applications and web servers. What I need is something simple, really; it just needs to serve multiple Django projects on a small (~100 users), internal network.
Answer: Have you watched:
http://code.google.com/p/modwsgi/wiki/WhereToGetHelp?tm=6#Conference_Presentations
Otherwise, explain the exact problem you are having.
Comment: I have not, but please note the series of edits I've made up above. :] Thanks!
Comment: Watch it, is explains the reasons for the error you finally posted up.
Comment: Graham, having followed the slides and copied each one carefully, I am still not up and running. On slide 8, a forbidden error is shown - having followed each step up to this point, my server returns a configuration error instead of permission error.

The WSGIScriptAlias step produces a permission denied error as expected, but the next step gives me server config error.
Comment: Success! Using http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango, I noticed that they did two sys.path.append commands... one for the root folder containing the django project, and another for the actual project itself (which your slideshow uses)... adding in the root folder to the path solved the problem!

Django + Apache + mod_wsgi problems


write size threshold for select call return

Question: When the select Linux system call returns when provided with valid file/socket writefds , what are the write payload sizes for which a subsequent call to write will not block? E.g. is it 1B / 1kB / 1MB or some other threshold? And where is this threshold set?
int select(int nfds, fd_set *readfds, fd_set *writefds,
           fd_set *exceptfds, struct timeval *timeout);

Comment: I don't think there's any way to know in general. Some device types may have an ioctl that can be used to determine the available buffer space.
Comment: I don't think there's a threshold. The usual strategy is to make the fd non-blocking when you use `select/poll`. So if there isn't enough space, you'll get `EWOULDBLOCK`.
Comment: I guess the question is what is "enough" space?
Comment: It's at least the size that you try to send.
Comment: That doesn't make any sense, how does select know that?
Comment: It doesn't. I meant you call `send()/write()` to try to send the data, and there isn't room it will return `EWOULDBLOCK`.
Answer:
what are the write payload sizes for which a subsequent call to write will not block?

In simple words, select guarantees that the writable file is able to accommodate at least 1 byte without blocking.

Generally, after a successful select call a single non-blocking write call will succeed with any size of payload.
Note, however, that successful write could return just 1 with meaning that only 1 byte has been actually written. For write the rest bytes a write call should be repeated, but that second write is allowed to block (or return EWOULDBLOCK if called on non-blocking file descriptor).


Typescript generics for react component taking array of records and array of keys

Question: I'm trying to create a simple typed react component for rendering a table from an array of objects. The data input is in the format of:
// array of records containing data to render in the table
data = [
  {
    one: 1,
    two: 2,
    three: 3,
  },
  {
    one: 11,
    two: 22,
    three: 33,
  }
]

// subset of keys from the data to render in the table
labels = [
  'one',
  'three',
]

The component is as follows:
function Table<T extends Record<string, string | number>, K extends Extract<keyof T, string>>({
    labels,
    data
}: {
    labels: K[];
    data: T[];
}) {
    return (

            {/* ... */}

    );
}

Testing it, it seems to work only when the labels is created in the prop and not before:
// Works

// Does not work
const labels = ['one']

// Type 'string[]' is not assignable to type '("one" | "two" | "three")'

Does anyone know how to fix the typing so that the second method works and I don't have to create the labels array inline?
Answer: Typescript will not infer string literal types unless it has to. If you write const labels = ['one']; typescript will widen the type of labels to string[].
You can get araound this either by using as const in 3.4 (unreleased yet) but using as const which will make ts infer a read-only tuple for labels
const labels = ['one'] as const; // const labels: readonly ["one"]

Before 3.4 we can either use an explicit type:
const labels:  ["one"] = ['one'];

Or use an helper function to hint to the compiler  to infer string literal and tuples:
function stringTuple<T extends string[]>(...a: T){
    return a;
}
const labels = stringTuple('one'); // const labels:  ["one"]

Answer: By defining Data first
interface Data {
  one: number,
  two: number,
  three: number,
}

const labels: keyof Data[] = ['one']

By reading the type of Data
const labels: keyof Unpacked<typeof data>[] = ['one']

type Unpacked<T> =
  T extends Array<infer U>
    ? U
    : T;

By using a type assertion


How to hold a pointer/reference to abstract base class but still be copyable in c++

Question: So let's say I have some ABC in C++:
struct IRun {
    virtual ~IRun() {}
    virtual void run() =0;
};

And I have another class that I want to be provided an instance of this interface to work with:
struct Other {
    IRun* runner_;
};

The issue is that I have to hold runner_ as a pointer to get virtual dispatch (references are out as they aren't assignable).  I'd like to be "modern" in my usage, so runner_ probably belongs in a smart pointer.
I'd like Other to be copyable and not share state, so shared_ptr and unique_ptr are out.  The only option I can see is writing my own that copies the underlying object via a clone() virtual function?  Is there anything in standard C++ (<= C++11) that's meant for this use case?
Comment: Note that if you are OK with `Other` not owning `runner_` then the raw pointer solution would be fine and everything would work as you want it to. No need for smart pointers in that case.
Answer: That is correct, there is nothing built-in in C++ to do this.
You will have to create a clone() virtual function that creates a copy, and implement it in each subclass of IRun.


iOS 8 sound for app doesn't work like it did in iOS 7

Question: I developed my game app in Xcode 5.1.1. Yesterday i downloaded Xcode 6.1.1. in Xcode 6.1.1 when i upload any of the iOS 8.1 simulators the sound doesn't work. However, sound works perfectly fine for all iOS 7 simulators. I'm using AudioToolbox.framework for my .aiff sounds. Is there a coding difference between iOS 7 and iOS 8 apps? Or is it something else?
in my ViewDidLoad, code for sound...
<code> NSURL *SwishURL =[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"SwishSound" ofType:@"aiff"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)SwishURL, &SwishID);
</code>
Comment: IIRC you will need to test this on a device, not in the simulator.
Answer: I had the same problem with audio, but with a little searching I found a working solution that works in Xcode 6.1.1 here.
The implementation is like this:
<code>@import AudioToolBox;
@import AVFoundation;

NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"sound_effect" ofType: @"wav"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
AVAudioPlayer *sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];

[sound play];
</code>


Problemas com $.get e PHP

Question: Gelera estou me batendo um pouco apra descobrir o que está acontecendo com um código que montei.
Tenho um loop que baixa arquivos .csv de um servidor especifico para o meu servidor. São 9 arquivos.
Após termino dos downloads preciso apagar as bases, realizar as inserções novamente e apagar os arquivos, parecia simples mas algumas coisas estão saindo do controle.
No inicio o arquivo "insert_delete.php" recebia os 3 loops dos 9 arquivos, porém ele se perdia e registrava logs informando duplicata de inserções e delete de arquivos. Sendo assim separei em 3 arquivos, isso parou de acontecer.
Um questão estranha é que quando executo diretamente o arquivo "insert_delete.php" tudo acontece dentro dos conformes, porém quando executo pelo script a base está ficando em branco, como se o TRUNCATE acontecesse depois do foreach.
Me parece que está passando algo e não estou vendo.
Vamos lá a bagunça que eu fiz:
Script
//Contagem dos arquivos se houver mais que 8 arquivos realiza a solicitação de inserção, se não continua contando
function cont(){
    setTimeout(function(){
        $.get("query/cont_arquivos.php", function( data ) {
            if(data < 9){
                $('.box_loading').show();
                $(".cont").html(
                    "Aguardando arquivos "+data
                );
                cont();
            }else{
                $.get("insert_delete.php", function(){});
                $.get("insert_delete1.php", function(){
                    $('.box_loading').hide();
                });
                $.get("insert_delete2.php", function(){});

                $(".cont").html(
                    "Inserindo nas bases... "
                );
            }
        });

    },1000);
}

PHP(insert delete)
<?php
include "conn.php";

$files1 = glob('nomedosarquivos*.csv'); // obten alguns arquivos da pasta

$sql = "TRUNCATE TABLE nomedatabela"; //apaga a base
$conn->query($sql);

if(count($files1)>2){
  foreach($files1 as $file){ // loop dos 3 arquivos
    if(is_file($file))
    if (($base = fopen($file, "r")) !== FALSE) {
        $count = 0;
        $ok = 0;
        $erro = 0;
        while (($data = fgetcsv($base, 0, ";")) !== FALSE) {
            $data = array_map("utf8_encode", $data);
            $count++; //contar as linhas
            if ($count == 1) { continue; } //não inserir os titulos

            if ($data[0] == "") { break; } //sai do while se este campo estiver em branco

            //validações de campos

            $sql = "INSERT into nomedatabela (campos....) VALUES (dados..)";
            if($conn->query($sql)==TRUE){
                $ok++;
                //somente conta as linhas que foram inseridas

            }else{
                //conta os erros
                $erro++;
                //executa o log informando qual erro e em qual linha aconteceu
            }
        }
        fclose ($base);
        if(unlink($file)){
            //executa o log informando que o arquivo foi deletado
        }else{
            //executa o log informando um erro ao deletar o arquivo
        }
      }
    }
  }
 ?>

Comment: Você está usado chamadas ajax ($.get) assíncronas esperando que ele execute no servidor de forma síncrona. Tente encadear as chamadas.
Answer: Você ja tentou utilizar o $.get().done().always().fail()?
Pelo que eu vi, esses métodos teriam que ser chamados após o término do anterior ....
  function cont() {
    setTimeout(function () {
        $.get("query/cont_arquivos.php", function (data) {
            if (data < 9) {
                $('.box_loading').show();
                $(".cont").html(
                    "Aguardando arquivos " + data
                );
                cont();
            } else {
                $.get("insert_delete.php", function () { })
                .done(function () {
                    $.get("insert_delete1.php", function () {
                        $('.box_loading').hide();
                    }).done(function () {
                        $.get("insert_delete2.php", function () {
                        }).done(function () {
                            $(".cont").html("Inserindo nas bases... ");
                        });
                    });
                });
            }
        });
    }, 1000);
}

Comment: Acho que era isso mesmo, me parece que do modo que eu estava realizando o $.get ocorria mais de uma solicitação ao arquivo, resolvido. Muito Obrigado.

Problemas com $.get e PHP


Order By Last in SQL: Force a value to be last in the order

Question: In SQL, I have used
...ORDER BY name DESC NULLS LAST

which works quite awesome, yet is there any way that I can set a specific value to be last? Such as an empty string (@EMPTY).
...ORDER BY name DESC (@EMPTY) LAST

I am dynamically building SQL off of user choices on a table, and when the user changes the sort order, I change my sort order in my SQL. Also, the user can choose which column to sort by. The column that I am sorting by will either be type text or type int. I don't need any fancy ORDER BY when column is type int, but I do need to force all values of "" to the end of the ORDER BY when the type of the column is text.
Thanks!
Answer: You can use a case as the first element in the sort order:
order by
    case when name = '' then 1 else 0 end
,   name desc

Comment: hmm... will this work though since `name` is type `text`? If I cast `1` or `0` as `name`, the column types won't match. Good attempt though! I'll try it.
Comment: This answer is sorting on two different columns.  The first one has an integer type, the second one a text type.
Comment: @WebWanderer yes this works because you are comparing name (string) to empty string so types do match, you are then returning an entirely new thing based on that comparison which is used to sort your results.


Mousedown or touchstart called?

Question: There's one thing that disturbs me: suppose, I have a laptop with mouse and touch display. What event will be called when I touch some object in a browser on a screen? Mousedown or touchstart?
And another situation: what event will be called when I use a tablet with usb-mouse and make mouse-click at the browser?
Hope you can give me the answer.
Comment: Why not write some code and try it to determine what happens?
Comment: Then write some code in a jsfiddle (https://jsfiddle.net/) that will give the feedback you're wanting. Post it here and ask others to use their touch screens and USB mice. Ask them to let you know the results.
Comment: @JonathanM, because I don't have such devices
Answer: I've checked it and here are results:

Android Chrome caused 'touchstart'
Android FF caused 'touchstart'
Android browser (4.0.*) caused 'touchstart' and then 'mousedown'
Android Opera caused both of them
Laptop with Windows 8 and FF and touch display caused 'mousedown' when using touch
The same laptop with Chrome caused both of events

A bit fanny. You can check it by yourself: jsfiddle.net/z5cygsb4/2/

Mousedown or touchstart called?


Exchange 2013 database corruption with event 476 in ESE

Question: I'm having some random database corruptions on our Exchange Server 2013 with event 476 on ESE. This is the fifth time that this happens and the situation in already unacceptable. Here's an screenshot of Event Viewer with the incident.

The recovery procedure must be done from backups or done by eseutil /p which is a lossy procedure since the logs got corrupted too.
At this point I really want to isolate the problem and find which device I should blame. This Exchange Server is running inside a VM in vSphere 6.0. The VMDK is exported through iSCSI from a Dell Powervault MD3820i.
Due to the nature of the error, it appears to be a problem with the storage subsystem, but how can we investigate this? On the previous issues the folks on DELL said that everything was fine in the storage, but I don't know if the diagnostics run by them are trusty enough.
Thanks in advance,
EDIT: There are no AntiVirus software installed on the server. The host hardware running VMware vSphere 6.0 is a DELL PowerEdge R730 homologated from DELL to run vSphere. There are no errors on VMware or anything like this on the logs, or at least I wasn't able to find any issue on the logs.
Storage communication is done by iSCSI using two Cat6 cables in multipath mode with dual controllers on the PowerVault MD3820i, so it's a pretty default configuration and know to work, and again, it was homologated by DELL.
I know that things homologated by DELL doesn't mean that's good. But they sold the hardware and they recommended their best practices, and we followed all of them.
EDIT II: The PowerVault storage appliance is running the latest firmware from DELL, the version 08_20_09_60 which is one older than the latest has addressed one particular issue that leads to data corruption: Addressed a rare condition which has the potential of causing a processor fault that could result in a data integrity issue
About the network cards, we're using a dual Broadcom NetXtreme II BCM57810 10GbE. The card does not support TCP engine offloading and/or iSCSI offloading so this should not be the issue.
VMware is running with the recommended drivers for the local SAS controllers too: the megaraid_sas driver instead of the deafault tg3 bundled with VMware. I don't think this is could be the issue since the VM's are on iSCSI Storage and not on the local storage.
Comment: Are you utilizing jumbo frames in your environment?
Comment: Yes. 9000 MTU on the point to point iSCSI links.
Comment: My environment is completely different but we are having the same issues with Exchange 2013 (not the same errors though).   For the SAN I'm running a NetApp FAS2040, servers are 3 HP DL 360p's Gen8 with a Cisco Nexus 5000 connecting our 10GB iSCSI links (Cat6 cabling as well).  Strangely enough, when we enabled jumbo frames over a month ago we started to see Exchange DB errors (mailboxes going into quarantine).  We have an open ticket with Microsoft but "Neel" keeps pointing to disk errors on C:\ as a result of corruption issues on E: and G: (DB drives).  The plan is to disable jumbo frames.
Comment: This is really strange. I do have some other Exchange environments with other storage backends (mainly ZFS with FreeNAS) and even with jumbo frames everything runs smoothly. The other thing to consider is that the jumbo frames setup are deployed and recommended by DELL once again, so we're using their own recommendation...
Answer: As it says in the event log error description, this will almost certainly be a fault with the system hardware, which can be a rather nebulous concept when talking about virtual guests.
I would be looking very hard at the storage subsystem - Given my recent experiences with virtual clusters built on Dell servers I would suspect either an issue with network card firmware or storage system firmware in that order.
Having had a cup of tea and a think, I've looked again at your error, you're getting a 1019 error. This is specifically saying that the exchange server went to read some data in the database that it 'knew' had been written but was unable to find it (have you read https://support.microsoft.com/en-gb/kb/314917 - the errors are discussed there in some detail).
This can only be disk corruption of some kind and the root cause for that is very likely to be an issue with the storage system, especially considering that you mention this has happened before.
My other worry at this point is that 1019 errors can be rather insidious; it could be the end result of a write going wrong some time ago not being detected because the data wasn't needed for some time. Restoring yesterday's backup won't help if the corruption occurred last week, for example.
At this point, I'd be certainly contacting Dell and also, maybe, Microsoft.
Comment: I'm really dissatisfied with those storage appliances from DELL. I've already deployed the latest firmware which fixes "random data corruption when a CPU fault happens on the controller", but this haven't solved the issue.
Comment: Added additional infos on the question as requested.
Answer: With the limited information about the environment it is running on I would start by checking the following.
Make sure AV has the appropriate exclusions set for exchange.
Make sure the drivers for storage and network are the correct stable versions for the devices at the other end.
look for other events that precede the failure.
Try to include more info about the hardware, Server type, mem, cpu, network card types and config ( port-channel etc )
look close at your vsphere logs for any storage related errors.
Answer: There are problems in VMware 6 that can corrupt exchange stores (or anything active like a database). There are (related?) issues with the Changed Block Tracking (CBT) feature used by virtual backup software like Veeam.  Search against those topics and you will find others with corrupt Exchange stores.  It's a particularly nasty problem since after your store is corrupted the CBT errors may have made ALL of your backup restore points (including off-site) unusable.  From what I can understand VMware has a patch to prevent the corruption of the running server but at the time of this posting there is not a fix for the CBT issues and CBT-based backups of ESXi 6.0 are not reliable.  FWIW - I've had good experience with Dell's MD SANs.  They're not fancy, but I've got several clients running them and never had a problem.  Likewise I've got quite a few shelves of Equallogic that have been reliable.  Of course, I use only basic LUN features, nothing fancy like snapshots or replication; relying on Veeam for that.
Comment: We don't use Veeam... This problem is exclusively to Veeam? Or due to methods of backups done by Veeam?


Trying to read from file within existing for loop

Question: Hello I am having a hard time figuring out how to complete the existing script I have written. In a nutsheel I am trying to set disk quotas based on an existing user for any user that doesn't have a quota set to 100MB or 102400 as below in the script. The logic seems to work currently but I have ran out of ideas for how to populate the $USER variable. Any help would be appreciated.
AWK=$(awk '{ print $4 }' test.txt)

USER=$(awk '{ print $1 }' test.txt)

for quota in $AWK;
do
    if [ "$quota" = 102400 ];
    then
        echo "Quota already set to 100MB for user: "$USER""
    else
        echo "Setting quota from template for user: $USER "
        edquota -p username "$USER"
    fi
done

The test.txt file is below:
user1   --  245 0   0
user2   --  245 102400  102400
user3   --  234 102400  102400
user4   --  234 1   0

Answer: Use a single loop that reads both variables from the file:
while read -r user a b quota c; do
    if [ "$quota" = 102400 ];
    then
        echo "Quota already set to 100MB for user: "$user""
    else
        echo "Setting quota from template for user: $user "
        edquota -p username "$user"
    fi
done < test.txt

The a, b, and c variables are just used to skip over those fields in the input file.


Can a non-trivial conjugacy class in $A_n$ contains $<n$ elements?

Question: In one of the proofs of simplicity of $A_n$ ($n\geq 5$), a fact used is the following:

There is no (non-identity) conjugacy class in $A_n$ containing $<n$ elements.

I initially was using simplicity of $A_n$; but that was the aim behind use of this fact. Any hint for proving this fact?
Also, is there always a conjugacy class in $A_n$ with exactly $n$ elements?
Answer: The theorem is false eg. for $n=3$, so we'll consider only $n \geq 5$.
I'll make heavy use of the following fact about conjugacy classes in $A_n$:

Conjugacy classes are either of the form "everything of a given cycle type", or "half the things of a given cycle type"; this latter occurs iff the cycle type is all odd and all distinct.

If the former, we're immediately done, because there are at least $n$ things of any given cycle type. Indeed, let $A_n$ act on the set $\{1, 2, \dots, n \}$. Then by just varying the image of the element $1$, we get $n$ different elements.
If the latter: Let $\sigma \in A_n$ have the given cycle type $(m_1, m_2, \dots, m_k)$, where $m_1 > m_2 > \dots > m_k$. The cycle type is not just $(1)$ because the class is not the identity. Moreover, since $n \geq 5$, we have $m_1 \geq 3$. Wlog the $m_1$-cycle in $\sigma$ moves the element $1$.
We have two cases. If there are at least two of the $m_i$ which are bigger than $2$, then we have at least $n$ elements given by varying the image of $1$.
Indeed, say $a, b, c$ are in a cycle which does not contain $1$ in $\sigma$: that is, $$\sigma = (1 x y z \dots)(a b c \dots)\dots$$
with the first cycle longer than the second.
If $\sigma : 1 \mapsto 2$ (which wlog it does), we can conjugate $\sigma$ by $(2m)(ab)$ to obtain another member of $\sigma$'s conjugacy class which sends $1 \mapsto m$ for each $m \not = a, b$. In order to get $1 \mapsto a$, we can use instead $(2 a)(b c)$, and in order to get $1 \mapsto b$, we can instead use $(2b)(ac)$. Therefore we have found $n$ distinct elements of $\sigma$'s conjugacy class.
The only remaining case is that at most one of the $m_i$ is bigger than 2. That is, the cycle type of $\sigma$ is of the form $(n)$ or $(n-1, 1)$.

In the former case, the cycle type is $(n)$. There are $\frac{n!}{2n}$ elements of the conjugacy class, so we're done: $\frac{n!}{2n} = \frac{(n-1)!}{2} \geq n$ for $n \geq 5$.
In the latter case, the cycle type is $(n-1, 1)$. There are $(n-1)!/2$ of these also, so again we're done.

We have found $n$ distinct elements of the conjugacy class of $\sigma$.
Comment: Oh, actually I may have found only $n-1$ elements, because we can't necessarily send $1 \mapsto 1$. I don't have time to look at this at the moment - the reasoning may still go through correctly because we often can send $1 \mapsto 1$, but it'll probably need some tweaking.


How to calculate Theil–Sen estimator in R?

Question: I found a useful method named "Theil–Sen estimator" on wikipedia: here
This method seems to be covered with mblm function on the mblm library.
I just downloaded it to do some tests.
I have one doub about it, if I do:
x <- c(1,2,3)
y <- c(2,6,7)
mod <- mblm(x~y)

It work perfectly, but I don't understand how to remove the intercept (set it to zero).
With lm() I do lm(x~y+0) but in this case I still see the intercept value.
So the first question is: How to set the intercept at 0 ?
The second question is about using this function with a matrix, take a look at the code below:
> y
[1] 6 4 1 8 7
>
> t
     [,1] [,2]
[1,]    2   32
[2,]    5  762
[3,]    6    5
[4,]   23    9
[5,]   34   16
> mblm(y~t)

Call:
mblm(formula = y ~ t)

Coefficients:
(Intercept)            t
         NA           NA

Why those NA / NA ?
If I do the same thing with lm() I don't have problems.
> lm(y~t)

Call:
lm(formula = y ~ t)

Coefficients:
(Intercept)           t1           t2
  3.453e+00    1.247e-01    5.435e-06

So the second question is: Can I use a matrix on the right side of the formula?
Thank you
Answer: No, you can't use an intercept of zero.  It's not clear what that would mean for this test. As the wikipedia page describes, this test computes the slope for all pairs of points and then reports the median of those slopes.  If you know you want the fitted line to start at zero, this doesn't quite make sense.  Maybe you'd want to compute the slopes of all points compared with that zero point only, but that wouldn't be the Theil-Sen estimate anymore; it would just be the sign test.
And no, you can't use a matrix on the right side; this test is for one predictor only.  The slope between two pairs of points then has both a magnitude and a direction, and it's not clear how one would take the median of them.
Finally, the default for this function is to use Siegel repeated medians; for the Thiel-Sen test, you need to specify repeated=FALSE. See the help page for more information.


Are there equations which have solutions in all groups but which are not algebraicly solvable

Question: I am not sure exactly how to phrase this problem so I appologise if it is not clear, also this is somewhat long but I wanted to explain exactly where I was with the problem. If you have any questions feel free to ask.

Description of Problem
Given a set of variables $\{x,y,z,...\}$ and a variable $o$ is it possible to define a finite product of these variables and their inverses $\sigma(x,y,z,...,x^{-1},y^{-1},z^{-1},...,o,o^{-1})$ (i.e. a finite sequence made up of these variables and their inverses) such that;
1) For any group $G$ and any assignment of values from $G$ to $\{x,y,z,...\}$ there exists a unique element $g$ of $G$ such that if $o$ is set to $g$;
$\sigma(x,y,z,...,x^{-1},y^{-1},z^{-1},...,o,o^{-1})=1$
and
2) There does not exist a finite product $\gamma(x,y,z,...,x^{-1},y^{-1},z^{-1},...)$ such that;
$o=\gamma(x,y,z,...,x^{-1},y^{-1},z^{-1},...)$ for all groups $G$

Rough explaination as to why I am asking here
My intuition is no but I am unsure how to prove this. There are clearly examples of equations like these solvable in all groups (i.e. $xo=1$) but these have algebraic solutions (in that example $o=x^{-1}$) and there are examples of these equations which are solvable in wide classes of groups (i.e. $o^{n!+1}x=1$ is solvable in any group of order less than $n$ with $o=x^{-1}$) but these are not solvable in all groups. In addition some equations are solvable in all groups but not uniquely (i.e. $o^2=1$ has many solutions in groups with elements of order 2 but can always be solved with $o=1$)

Progress on proof (or proof of falsehood)
It can be shown that $\sigma$ must contain exactly $\pm1$ total occurences of $o$ (where $o^{-1}$ counts as $-1$ occurence of o) using the following argument.
If $G$ is abelian then $\sigma$ can be written as $Ao^n$ for some $A$ which is a product of the other variables. For this to be solvable $o^n=A^{-1}$ must be solvable in every abelian group. If $A=1$ $o$ is not uniquely defined for groups of order $|n|$. If $A\neq1$ and $|n|\neq1$ then $o$ is not defined for groups of order $|n|$ or $n=0$ and so $o$ is not unique. Therefore $|n|=1$ and so the total number of occurences of $o$ in $\sigma$ must be $\pm1$.
In addition it is clear that there must be an odd number of occurences of $o$ greater than $1$ (this time counting $o^{-1}$ as $1$ occurence). This follows as otherwise there is a clear definition of $\gamma$ (if there is $1$ occurence) or the observation above is violated (if there are an even number of occurences).
This is where I am and I am not sure how to proceed. Appologies again for this being overly long. Any information or advice would be appreciated.
Comment: Your 2nd question is unclear. For the first question, consider the equation $\sigma(x,x^{-1},o,o^{-1})= xx^{-1} ooo^{-1}=1$. It has unique solution $o$, namely $o=1$.
Comment: It perhaps wasn't clear that the two statements must both be simultaneously true. I am not sure how to clarify the 2nd statement
Comment: I see. The second part is unclear since you did not quantify $x, y$, etc.: Do you mean to say that there is no word $\gamma$ in formal variables ..., such that for each group  $G$ the equation $o=\gamma(...)$ has a solution in $G$?
Comment: I suppose it would best be described as given $\sigma(x,...,o,o^{-1})$ there is no function given as a word $\gamma(x,...)$ s.t $\sigma(x,...\gamma(x,...),(\gamma(x,...))^{-1})=1$ in any group under any assignment of values of x,y,...
Comment: Maybe another way to explain it is to give the intuition behind the idea. If when we define a word we don't allow inverses then the word$\sigma(x,o)=xo$ would be a valid solution as there is always a unique solution by definition of a group but there is no way of writing this solution without using $x^{-1}$ and so in terms of words only using $x$ we cannot write $\gamma(x)$ s.t $x\gamma(x)=1$ in all groups. Maybe this has made things more clear, maybe not. To clarify this is not a solution of the problem as in the problem we are allowed $x^{-1}$
Comment: This is even less clear now: The questions written in the comment seem to be different from the problem in the main body of your post. One more thing: There is now a substantial literature on equations in groups. Let me know if you want to see some references.
Comment: References would be great. To be honest I wasn't really expecting anyone to respond to this so I guess I wasn't too clear about what I meant. I expect that I will probably get the best results by looking into it myself but I would like to be able to explain my question clearly. Could you try to explain what makes the questions in the comments seem so differnt from the ones in the post. To be clear I think the the questions in the comments are more accurate to what I want to ask.
Comment: Take a look at references (equations in groups) on this web page: http://www.ma.huji.ac.il/~zlil/
Comment: Thank you for the references. They will be very helpful
Answer: If you require uniqueness of your solution, then I don't believe this is possible.
To shorten notation, for a set $X$ I'll write $\sigma(X)$ to denote a word in elements of $X$. Let $X$ be a set, let $o$ be a variable, and let $\sigma(X, o)$ be any word. Then the group
$$G = \langle X, s, t~|~\sigma(X, s) = \sigma(X, t) = 1\rangle$$
fails the uniqueness condition for solutions to $\sigma(X, o)$.

So, let's consider the case where we don't assume uniqueness. In this case, it is (uninterestingly) possible.
The requirement that $\sigma(X, o) = 1$ for all groups means that, in particular, this must be true for the free group $F(X\cup\{o\})$. This means that $\sigma(X,o)$ must reduce to a trivial word by the definition of free groups.
The only next requirement is that $o\notin \langle X\rangle$. Thus, we can produce a situation you want in the following way: let $G$ be any group with identity element $e$, and $\sigma(X,o)$ be any word that reduces to the trivial word.
Then, the assignment $x\mapsto e$ for all $x\in X$ and $o\mapsto g$ for any $g\ne e$ in $G$ satisfies your requirements.
Comment: Firstly thank you for the answer. I will first tackle the second part of your answer, I did not make it clear that the word should be solvable for all assignments of variables to X. i.e. we cannot simply say that all of them are e unless the group is only e. The first part of your answer is more of interest to me as I just want to prove it impossible. I'm not sure how one would explicitly construct the group you describe. As in for some particular $\sigma$ (for example $xox$) how would we construct the desired group. It would be nice if you could respond, so9rry again for how unclear I was.
Answer: Okay so I have no answered my question. If this doesn't seem like an answer it is probably due to me being unable to clearly describe the question I wanted to ask so sorry. Also I'm not sure how best to explain the answer.

It can be shown that no such equation exists by contradiction. First assume there exists $\sigma$ as is required by the problem. Let $n$ be the number of variables it takes (excluding $o$ and only counting $x$ not $x^{-1}$ for example). Take the group $F_n$ (the free group with $n$ generators) and assign to each of the variables that $\sigma$ takes $x_1,x_2,...$ a different one of the generators $g_1,g_2,...$. Find the value of $o$ corresponding to this situation. By definition of $F_n$, $o$ can be written as a finite product of $g_1,g_2,...$. Write $\gamma$ as this representaion of $o$ but where the generators are replaced by the corresponding variables. Therefore by definition of the free group in all groups $o=\gamma$ is a solution.

Sorry if this wasn't clear. Also thanks to Santana Afton for mentioning using the free group in there answer.


Como ajustar automaticamente uma JFrame ao tamanho de ecrã?

Question: eu tenho um programa e quando executo em diferentes computadores a janela fica toda desmanchada e não se consegue ver os componentes que tem na Jframe, gostava de saber se há alguma maneira de a janela ser automaticamente ajustada ao ecrã desse tal computador de maneira a que ficassem os componentes no seu lugar
Comment: Vai depender de como está montado seu layout. É um pouco difícil responder sua pergunta sem saber exatamente como esta seu código. Dê uma olhada no link do comentario que eu deixei na resposta.
Answer: Tenta fazer isso
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension tamTela = kit.getScreenSize();

//Pega largura e altura da tela
int larg = tamTela.width;
int alt = tamTela.height;

/* larg x 0.7; para ocupar 70% da tela por exemplo  */
/* alt x 0.7;*/

//Manda o JFrame utilizar suas dimensões
setSize(larg,alt);

Comment: Há entendi, pensei que queria que fizesse ela ficar full automaticamente em qualquer tela. Pois esse código faz isso. Mas seu problema parece ser com os posicionamento dos componentes dentro dela né.
Comment: Ja entendi mas nao e isso que pretendo ate porque quero que o programa ocupe todo o ecra
Comment: O ecra não seria a tela inteira?
Comment: e para ocupar a tela  inteira o unico problema e que por exemplo nos ecras dos pcs da minha escola sao quadrados e a jframe fica formatada diferente e eu queria que fosse sempre igual(ajustada automaticamnete)
Comment: exacto por exemplo o meu monitor do portatil onde fiz o programa e maior do que o da escola por isso alguns componentes desaparecem, sabe alguma maneira de fazer o que desejo?
Comment: Vou ver se acho e te passo ok. Usei poucas vezes jframes.
Comment: poderia me mandar o site com essa informacao ?
Comment: Estou procurando, vai pesquisando ai por GridBagLayout, leia isso http://javafree.uol.com.br/topic-5792-Tudo-sobre-o-GridBagLayout.html
Comment: Deem uma olhada nisso: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html A solução é provavelmente uma composição de vários desses layout managers
Answer: Coloque no initializeComponentes()
    setResizable(false);
    setLocationRelativeTo(null);
    pegarResolucao();

e Cria essa função
private void pegarResolucao() {
        Toolkit t = Toolkit.getDefaultToolkit();
        Dimension dimensao = t.getScreenSize();
        this.setSize((dimensao.width + 5), (dimensao.height - 38));

 }


Upload de Imagem Asp net MVC

Question: Minha dúvida é a seguinte: imaginem um cenário onde eu tenho uma tela que tem um formulário, e neste formulário também existe upload de imagens. Vamos supor que eu preencha todo o formulario, e selecione 3 imagens no input type file, ao dar o submit, lá no controller eu tenho os atributos do formulário preenchido, e também a lista de HttpPostedBaseFile com as 3 imagens dentro, para eu fazer upload, porém o modelstate está com algum erro, e ele vai retornar para a view para mostrar este erro.
Acontece que todos os outros campos são preenchidos novamente com os valores, mas as imagens se perderam. O usuário precisa selecionar de novo as imagens.
Qual a melhor maneira de resolver isso? Eu queria que as imagens voltassem também.
Comment: Pesquisei e infelizmente não existe meios de restaurar o estado de um input type file, sendo que todos os usuário optaram por guardar os arquivos enviados na sessão. http://forums.asp.net/t/1895657.aspx?ASP+NET+MVC+4+Browser+looses+uploading+File+after+Postback
Comment: Por isso que as validações cliente são importante, agora com `html5` pode ser menos traumático para o cenário dito. Não tem como voltar as imagens depois de enviar.
Answer:
Qual a melhor maneira de resolver isso? Eu queria que as imagens voltassem também.

Usando o Backload. É um pacote que faz o gerenciamento de uma sessão de upload de arquivos no ASP.NET (pode ser MVC ou Web Forms).
Um exemplo usando jQuery File Upload, retirado do próprio GitHub do Backload:
@using System.Web.Optimization

@{
    ViewBag.Title = "Exemplo de Upload";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section styles {

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

    @Styles.Render("~/backload/blueimp/bootstrap/BasicPlus/css")

    <link href="~/Content/demo.styles.css" rel="stylesheet" />
}

                File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery.
                Supports cross-domain, chunked and resumable file uploads and client-side image resizing.

            Add files...

            <input id="fileupload" type="file" name="files[]" multiple>

@section scripts {

    @Scripts.Render("~/backload/blueimp/bootstrap/BasicPlus")

}

O arquivo demos.blueimp.basicplus.js contém o seguinte (adaptado e traduzido por mim):
/*jslint unparam: true */
/*global window, $ */
$(function () {
    'use strict';

    // O Backload é um produto freemium, então algumas funcionalidades são fechadas.
    // O FileHandlerController é o controlador da sua sessão de upload.
    // No exemplo, definimos uma sessão de upload por um objectContext.
    // Esse objectContext deve ser definido pela sua aplicação. No exemplo,
    // foi definido com esse valor 'C5F260DD3787'.
    var url = '/Backload/FileHandler?objectContext=C5F260DD3787';

    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: false,
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator && navigator.userAgent),
        previewCrop: true,
        maxChunkSize: 10000000                                          // Opcional: tamanho de cada bloco de arquivo, em bytes, para facilitar uploads grandes.
    })
    .bind('fileuploadsubmit', function (e, data) {
        // Opcional: aqui geramos um uuid para identificar qual bloco de arquivo estamos enviando. O Backload reagrupa cada bloco de arquivo sozinho.
        data.formData = { uuid: Math.random().toString(36).substr(2, 8) };
    })

        // Aqui é a inicialização do tema Basic Plus do jQuery File Upload (https://blueimp.github.io/jQuery-File-Upload/basic-plus.html)
    .data('blueimp-fileupload').initTheme("BasicPlus");
});

Se ModelState.IsValid for true, você pode acessar o diretório do objectContext usando classes do namespace System.IO, manipular seus arquivos e depois excluir o diretório.
O local deste diretório pode ser definido pela configuração. Meus arquivos Web.Backload.config normalmente são assim:
<?xml version="1.0"?>
<backload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="urn:backload-schema" xsi:noNamespaceSchemaLocation="Config\Web.Backload.xsd">
  <fileSystem filesRoot="~/Uploads/Temp" />
</backload>

Answer: Não há como recuperar arquivos em input file.
Mas existem algumas 'soluções de contorno'.
Uma das soluções é o uso da 'simulação' de Ajax.
P: Por que simulação de Ajax?

R: Simples, o Ajax não suporta envio de arquivos, então simulamos criando um iframe invisível (ou flash, ou silverlight por exemplo) que recebe uma cópia do formulário e a responsabilidade de executar o submit.

Existem diversos plugins javascript que fazem todo este trabalho por
  você, além de fornecer uma API padronizada, como é o caso do jQuery
  File upload.

Desta forma é possível manter os dados do formulário intactos, já que não houve um page reload.
 Segue um pequeno exemplo de como seria usando o jQuery File upload:
$('#fileupload')
    .fileupload('send', {files: filesList})
    .success(function (result, textStatus, jqXHR) {
        console.log('Sucesso!');
        // Redireciona a página
        // ...
    })
    .error(function (jqXHR, textStatus, errorThrown) {
        console.error('Erro!');
        // trata os dados inválidos
        //...
    });

Documentação do jQuery File Upload

PS: Essa uma das soluções usada para manter retrocompatibilidade com
  browsers antigos, visto que o XHR2 já suporta o envio de dados
  binários.
Comment: Essa afirmação não é verdadeira, ok? "Ajax não suporta envio de arquivos". Ajax é o nome da técnica de usar JS para fazer requisições assíncronas. E é sim possível fazer upload de arquivos de forma assíncrona com JS. :)
Comment: Então, @ThiagoLunardi, você está certo. Na verdade, eu não quis ir pra esse lado mais, digamos, detalhado da coisa (falar de protocolo, diferenciar técnica de recurso, etc). Mas se você observar no final, eu até coloquei um 'PS' informando que o "XHR2" suporta o envio de binários. A minha ideia foi focar mais no resultado do que nos pormenores. De qualquer modo, é muito importante ter esse seu comentário, pode ajudar alguém a eliminar essa dúvida ;)

Upload de Imagem Asp net MVC


Ocultar parâmetro URL no MVC 5

Question: A minha dúvida é a seguinte:
Como ocultar o parâmetro Id da URL utilizando rotas ou máscara?
PessoaFisica/Edit/1

para
PessoaFisica/Edit

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

Answer: Vou discutir na resposta algumas formas e recomendar uma.
1. Usando slugs (recomendado)
Falo disso nestas respostas:

Montar URL sem aparecer o nome da Action ou da Controller ou ambas
Esconder parametro do ActionLink
Roteamento e Url amigáveis com asp.net mvc

O princípio é usar outro parâmetro para identificar a pessoa e passá-lo na rota. O CPF, por exemplo, é um bom candidato. O nome pode ser outro candidato, mas aí é preciso escolher alguma forma de desfazer ambiguidades em caso de duplicidade de nomes.
2. Usando POST
Esta não é uma boa forma porque, para acessar um registro, você sempre precisará submeter um formulário, validá-lo, para só assim encaminhar o usuário para a tela de edição.
3. Usando uma variável codificada
Esta lembra o método 1, mas implica em alguma implementação a mais. A ideia é uma URL assim:
/PessoaFisica/Acao/?codigo=A2B7649C100DB2F641

Utilizando algum algoritmo de criptografia reversível, você consegue mascarar o Id e a ação a ser executada dentro da variável criptografada.
Apesar de funcionar, é mais desvantajosa que o slug por não ser intuitiva.
Comment: Ok amigo! Vou utilizar a opção 3 mesmo. Pensei em utilizar Guid mas não fica usual no banco!

Ocultar parâmetro URL no MVC 5


puppet ignores ENC classes

Question: I am using a ruby script to retrieve the class parameters and my YAML output is as below:
classes:
  tomcat_install:
    tmp_dir: /tmp
    tomcat_home: /tmp/tomcat6

puppet.conf is as below:
[master]
node_terminus = exec
external_nodes = /etc/puppet/readnodedefinitions.rb

When I give the test command from puppet agent the log is:
Notice: Ignoring --listen on onetime run
Info: Retrieving plugin
Info: Caching catalog for puppet-agent
Info: Applying configuration version '1367987990'
Notice: Finished catalog run in 0.06 seconds

But the classes specified in ruby script are getting ignored. Any idea why its ignored?
debug mode gave this

Debug: Finishing transaction 69977541744660
Debug: Loaded state in 0.00 seconds
Debug: node supports formats: b64_zlib_yaml pson raw yaml; using pson
Debug: Using cached certificate for ca
Debug: Using cached certificate for puppet-agent.cs1cloud.internal
Debug: Using cached certificate_revocation_list for ca
Info: Retrieving plugin
Debug: file_metadata supports formats: b64_zlib_yaml pson raw yaml; using pson
Debug: Finishing transaction 69977541525360
Debug: catalog supports formats: b64_zlib_yaml dot pson raw yaml; using pson
Info: Caching catalog for puppet-agent.cs1cloud.internal
Debug: Creating default schedules
Debug: Loaded state in 0.00 seconds
Info: Applying configuration version '1367987990'
Debug: /Schedule[daily]: Skipping device resources because running on a host
Debug: /Schedule[monthly]: Skipping device resources because running on a host
Debug: /Schedule[hourly]: Skipping device resources because running on a host
Debug: /Schedule[never]: Skipping device resources because running on a host
Debug: /Schedule[weekly]: Skipping device resources because running on a host
Debug: /Schedule[puppet]: Skipping device resources because running on a host
Debug: Finishing transaction 69977541711700
Debug: Storing state
Debug: Stored state in 0.03 seconds
Notice: Finished catalog run in 0.07 seconds
Debug: Value of 'preferred_serialization_format' (pson) is invalid for report, u                                                                                sing default (b64_zlib_yaml)
Debug: report supports formats: b64_zlib_yaml raw yaml; using b64_zlib_yaml

Comment: Run puppet with `--debug` and paste the output please. That may give more clues.
Comment: have added the debug message to the question....
Comment: Why not use `hiera` instead? You can have custom facts if you need to using `facter-dot-d` or directly `/etc/facter/facts.d` if using a recent `facter`
Comment: I am using ruby script to pick the class parameters from DB , as I am gonna build a custom UI on top of it. I am not sure if Hiera supports this feature.
Answer: It seems your YAML output lost some - and Puppet can't recognize it as a YAML file.
Maybe it should like this?
---
classes:
  puppet-agent.cs1cloud.internal:
    tmp_dir: /tmp
    tomcat_home: /tmp/tomcat6

Comment: http://docs.puppetlabs.com/guides/external_nodes.html have refered this link and it clearly says array syntax cannot be used for parameterized classes. So I believe the yaml output that i construct is correct.
Comment: maybe you use the wrong node name. it should be `puppet-agent.cs1cloud.internal` instead of `tomcat_install`. i should just comment your question, but i don't have the privilege, sorry.
Comment: yaml consists of the class name("tomcat_install") and params ("tmpd_dir","tomcat_home").Node name is automatically detected by the puppet once the test command is run.

puppet ignores ENC classes


How do I fix this error about a missing class?

Question: I'm using the Commerce Canada Post module.
The code in the src/Plugin/Commerce/ShippingMethod/CanadaPost.php file uses a CanadaPost\Rating class which isn't defined that namespace and it causes an error.
The src/Api/RatingService.php file contains the following code.
/**
 * Returns an initialized Canada Post Rating service.
 *
 * @param array $api_settings
 *   The Canada Post API settings.
 *
 * @return \CanadaPost\Rating
 *   The rating service class.
 */
protected function getRequest(array $api_settings) {
  $config = $this->getRequestConfig($api_settings);

  return new Rating($config);
}

How do I fix this error?
Answer: The CanadaPost\Rating class is not part of the Commerce Canada Post module, rather it's part of a dependency, the PHP Canada Post API, that should be installed into your vendor directory by composer in the thejacer87/php-canadapost-api subdirectory.
If it's not there, then my best guess is that you tried to install Commerce Canada Post without using composer. Install it, the Commerce Canada Post module, with composer and the dependency will be installed and it'll resolve your error.
See Download contributed modules, themes and their dependencies using Composer on drupal.org for how to install a module with composer.
composer require drupal/commerce_canadapost

Comment: Thanks @sonfd for clear explanation
after install thejacer87/php-canadapost-api through composer now its working.
you save my day.


Usabilidade do useState e useEffect no react-TS

Question: Me perdoem de antemão caso tenham gafes no código rs.
Estou praticando react-TS criando um "deck maker" de Yu-gi-oh!. Por enquanto fiz apenas uma listagem de todas as cartas do jogo, mas me deparei com um problema. Usei o useEffect pra poder executar a chamada da API e inserir os dados para uma constante com o useState. Se eu tento listar os cards como componente em tela me ocorre um erro, porém se eu faço uma função pra listar os cards no console o resultado ocorre como o esperado.
Código com o print no console:
import axios from 'axios'
import { useEffect, useState } from 'react'
import { Loading } from '../components/Loading'

interface AllCardsProps {
    data: [
        {
            name: string
        }
    ]
}

export function Home() {
    const [allCards, setAllCards] = useState<AllCardsProps>({} as AllCardsProps)

    useEffect(() => {
        axios.get('https://db.ygoprodeck.com/api/v7/cardinfo.php')
        .then(response => {
            setAllCards(response.data)
        })
    }, [])

    function clickHere() {
        allCards.data.map(card => {
            console.log(card.name)
        })
    }

    return (

            {
                !allCards ?
                <Loading />
                : <button onClick={clickHere}>It's time to duel</button>
            }

    )
}

Código tentando exibir os cards em tela:
import axios from 'axios'
import { useEffect, useState } from 'react'
import { Loading } from '../components/Loading'

interface AllCardsProps {
    data: [
        {
            name: string
        }
    ]
}

export function Home() {
    const [allCards, setAllCards] = useState<AllCardsProps>({} as AllCardsProps)

    useEffect(() => {
        axios.get('https://db.ygoprodeck.com/api/v7/cardinfo.php')
        .then(response => {
            setAllCards(response.data)
        })
    }, [])

    function clickHere() {
        allCards.data.map(card => {
            console.log(card.name)
        })
    }

    return (

            {
                !allCards ?
                <Loading />
                : allCards.data.map(card => {
                    return (

{card.name}

                    )
                })
            }

    )
}

Erro ao tentar exibir o nome dos cards em tela:
@react-refresh:278 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
    at Home (Home.tsx:34:33)
    at renderWithHooks (react-dom.development.js:16305:18)
    at mountIndeterminateComponent (react-dom.development.js:20074:13)
    at beginWork (react-dom.development.js:21587:16)
    at beginWork$1 (react-dom.development.js:27426:14)
    at performUnitOfWork (react-dom.development.js:26557:12)
    at workLoopSync (react-dom.development.js:26466:5)
    at renderRootSync (react-dom.development.js:26434:7)
    at recoverFromConcurrentError (react-dom.development.js:25850:20)
    at performSyncWorkOnRoot (react-dom.development.js:26096:20)

Poderiam me dar alguma ideia, correção ou dica do que fazer a respeito?
Answer: Parece que o erro está ocorrendo porque você está tentando acessar a propriedade "data" de "allCards" antes de ela ter sido definida. Isso acontece porque a chamada à API é assíncrona, então, quando o componente é renderizado pela primeira vez, "allCards" ainda é undefined.
Uma forma de resolver isso seria adicionar uma verificação antes de acessar a propriedade "data" para garantir que ela foi definida antes de ser usada. Algo como:
{
    !allCards ?
    <Loading />
    : allCards.data && allCards.data.map(card => {
        return (

{card.name}

        )
    })
}

Dessa forma, o código dentro do "map" só será executado quando allCards.data for verdadeiro, e evitará que o erro ocorra.
Outra forma é usar o useEffect para garantir que a chamada da API foi concluída antes de tentar acessar allCards.data, e adicionar um estado que guarda se a chamada já foi concluída, e verificar esse estado antes de renderizar os dados.
const [allCards, setAllCards] = useState<AllCardsProps>({} as AllCardsProps)
const [isLoading, setIsLoading] = useState(true)

useEffect(() => {
    axios.get('https://db.ygoprodeck.com/api/v7/cardinfo.php')
    .then(response => {
        setAllCards(response.data)
        setIsLoading(false)
    })
}, [])

    return (

            {
                isLoading ? <Loading /> : allCards.data.map(card => {
                    return (

{card.name}

                    )
                })
            }

    )

Espero que isso ajude!
Comment: Agora eu entendi, e funcionaram ambos o métodos, valeu mano!


On evaluating variational autoencoders with prior likelihood and reconstruction error

Question: A common evaluation metric for variational autoencoders (VAEs) is estimating the marginal likelihood of some held-out data, i.e. $p(x)$. This is difficult and often one can only get a lower bound. It's also complicated when using some reconstruction loss $R$ as a log-likelihood for some complex data-type. Balancing the KL term and $R$ is itself a challenge, and this issue is seemingly built into the use of $p(x)$.
Theis et al, A Note on the Evaluation of Generative Models note some of these difficulties.
However, we can easily measure the likelihood of the generative model sampling the encoding of given data point $x$: it's just $p_z( E(x) )$, where $E$ is the encoder, and $p_z$ is the latent prior. However, this does not tell us if the output is good, i.e. if $\hat{x}=D(x)$ is close to $x$. In other words, we might be able to sample the encoded latent form of $x$, but this does not mean the reconstruction will be good. But we can use $R$ for that! In other words, if there is a good chance of sampling $E(x)$ under the prior AND the reconstruction performance is good, then (seemingly) we can say that the generative model is good.
So why not report the two values: the average $R(x)$ and $\log p_z(E(x))$ over the held-out set?
Are there any papers that do this?
Comment: i can't really tell where $p_z(E(x))$ came from. it isn't the probability that $x$ is drawn from the generative model
Comment: @shimao that was badly worded, sorry. I've edited it.
Answer: Well, $p_z(E(x))$ doesn't seem to be the best metric as it can be maximized with with a encoder network which disregards the standard normal prior and always outputs 0 (or some very small values close to 0, so that the decoder can do its job).
More broadly, when comparing VAEs to other generative models (RBMs, PixelRNN, PixelCNN, GLOW, NICE, many GAN variants, etc) which don't have any autoencoder structure and don't have any concept of "reconstruction loss" or "likelihood of the encoding of a data point", it doesn't make sense to use either of those measures. You can only really rely on 1. the subjective quality of the generated samples, and 2. likelihood of the model (although GANs don't allow this, and with VAEs it can be hard)
Comment: Thanks for your answer! Regarding para 1, that's why I suggested also reporting $R$. (Presumably $R$ would be poor under posterior collapse. The MI between x and its encoding would be small.) Anecdotally, I've found that the average $\log p(E(x))$ seems generally related to the quality of VAE samples I get (when $R$ is good). Regarding para 2, I suppose you're right. It's what I often see in papers, though some also report $R$. I was hoping for literature on other measures though (specifically these). For instance, in [this work](https://arxiv.org/abs/1707.02392) they define another metric.
Comment: @user3658307 well encoding a posterior of always ~0 wouldn't be posterior collapse -- just imagine a non-variational autoencoder, but where the weights are scaled so that the latent space has tiny value. in the VAE case, it would have a huge KL loss and poor samples, but good reconstructions.