Uncaught TypeError: r.getClientRects is not a function jquery.min.js:2

Question: Hi  I don't understand what the meaning of the error is in the web console.
Uncaught TypeError: r.getClientRects is not a function jquery.min.js:2

I am trying to build an autocomplete search form in laravel Based on a bootstrap theme i downloaded.
It works but the dropdown  is misaligned to the text box
I suspect JQuery because of that error and the fact that  in a different bootstrap theme I had, it worked
I have  my script links as follows
<link href="http://myurl.com/vendor/bootstrap/css/bootstrap.min.css"
rel="stylesheet">
<link href="http://myurl.com/vendor/fontawesome-free/css/all.min.css"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Varela+Round"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css
rel="stylesheet">
<link href="http://myurl.com/css/grayscale.min.css" rel="stylesheet">

My form:
 <form class="form-inline d-flex">

            <input class="form-control autocomplete_txt input-lg flex-fill mr-0 mr-sm-2 mb-3 mb-sm-0"
                   type='text' data-type="EmpService" id='EmpService_1' name='EmpService[]' autocomplete="off" placeholder="looking for...">

                       <button type="submit" class="btn btn-primary mx-auto">Search</button>

</form>

My Javascript:
$(document).on('focus','.autocomplete_txt',function(){
  type = $(this).data('type');

  if(type =='EmpService' )autoType='EmployeeService';

   $(this).autocomplete({
       minLength: 0,
       source: function( request, response ) {
            $.ajax({
                url: "http://spanibox.com/searchajax",
                dataType: "json",
                data: {
                    term : request.term,
                    type : type,
                },
                success: function(data) {
                    var array = $.map(data, function (item) {
                       return {
                           label: item[autoType],
                           value: item[autoType],
                           data : item
                       }
                   });
                    response(array)
                }
            });
       },
       select: function( event, ui ) {
           var data = ui.item.data;
           id_arr = $(this).attr('id');
           id = id_arr.split("_");
           elementId = id[id.length-1];
           $('#EmpService_'+elementId).val(data.name);

       }
   });

Comment: GREAT thats was the issue!
Comment: How do i vote your answer up - im a newbie
Answer: The problem is likely due to using jQuery 3.1.
Try to add :

Answer: If you don't want to downgrade jquery then I found this fix which works:
https://github.com/markdalgleish/stellar.js/pull/147/commits/2051858ab77eaec82abe5b287d740dcfbb3e7605#diff-5e6a197fd748dcc5d0c34558b8ecde5f6c61bccea987386d5f1844cfe3eb2162
If you have only jquery.stellar.min.js file you can find and replace these functions (minified):
refresh:function(c){var d=this,e=d._getScrollLeft(),f=d._getScrollTop();c&&c.firstLoad||this._reset(),this._setScrollLeft(0),this._setScrollTop(0),this._setOffsets(),this._findParticles(),this._findBackgrounds(),c&&c.firstLoad&&/WebKit/.test(navigator.userAgent)&&a(b).load(function(){var a=d._getScrollLeft(),b=d._getScrollTop();d._setScrollLeft(a+1),d._setScrollTop(b+1),d._setScrollLeft(a),d._setScrollTop(b)}),this._setScrollLeft(e),this._setScrollTop(f)},_detectViewport:function(){var a=this.$viewportElement.offset(),b=null!==a&&a!==d;this.viewportWidth=this.$viewportElement.width(),this.viewportHeight=this.$viewportElement.height(),this.viewportOffsetTop=b?a.top:0,this.viewportOffsetLeft=b?a.left:0},

for these:
refresh: function (c) {
        var d = this,
            e = d._getScrollLeft(),
            f = d._getScrollTop();
        (c && c.firstLoad) || this._reset(),
            this._setScrollLeft(0),
            this._setScrollTop(0),
            this._setOffsets(),
            this._findParticles(),
            this._findBackgrounds(),
            c &&
                c.firstLoad &&
                /WebKit/.test(navigator.userAgent) &&
                a(b).on("load", function () {
                    var a = d._getScrollLeft(),
                        b = d._getScrollTop();
                    d._setScrollLeft(a + 1),
                        d._setScrollTop(b + 1),
                        d._setScrollLeft(a),
                        d._setScrollTop(b);
                }),
            this._setScrollLeft(e),
            this._setScrollTop(f);
    },
    _detectViewport: function () {
        var a =
                this.$viewportElement[0] !== window
                    ? this.$viewportElement.offset()
                    : { top: 0, left: 0 },
            b = null !== a && a !== d;
        (this.viewportWidth = this.$viewportElement.width()),
            (this.viewportHeight = this.$viewportElement.height()),
            (this.viewportOffsetTop = b ? a.top : 0),
            (this.viewportOffsetLeft = b ? a.left : 0);
    },

Comment: Thanks a lot ! For me it was a perfect solution, because (if I understood well) I do not see the migration as a solution as I never used for my present website the old version, and it seems stupid to pretend the old jQuery version is the base (only for Stellar) and I migrate from there to the new one which is for the rest of the website codes.


Representing a martingale as the conditional expectation w.r.t filtration?

Question:
Let $M_t$ be an $\mathcal{F}_t$ martingale such that $\sup_t E|M_t|^p < \infty$ for some $p>1$. Show there exists a $Y\in L^1(P)$ such that $M_t = E[Y|\mathcal{F}_t]$.

I am not sure how to answer this question.
The problem suggests using the result that: the condition in the problem implies the existence of a limiting random variable $M \in L^1(P)$ such that $M_t \to M$ almost surely and
$$\int |M_t - M|dP \to 0$$
as $t \to \infty$.
But I'm not sure how to represent $M_t = E[g(M)|\mathcal{F}_t]$ given the corollary doesn't tell us the relationship between $M_t$ and $M$ other than that they converge almost everywhere.
Answer: Since $(M_t)$ is a uniformly integrable martingale, it converges a.s. and in $L^1$ to some limit $M$. Then for any $F\in \mathcal{F}_t$ and $s>t$,
$$
\mathsf{E}[M_t1_F]=\mathsf{E}[M_s1_F]\to\mathsf{E}[M1_F].
$$
Therefore, $M_t=\mathsf{E}[M\mid \mathcal{F}_t]$ a.s.


jquery class selector function won't accept date as arguement

Question: I'm using a function that successfully calculates and (should successfully) return the date for Tuesday if today is Tuesday, Wednesday if it's Wednesday, and if it's some other day today it should return next Tuesday.  This function is used to put this date into put into a datepicker input's default value.  I've verified that the function does in fact calculate the correct date to use.  However, when passing the return value to the selector's arguements, no date is displayed in the input object.
I tried entering strings and numbers into the second argument of the selector function instead of setDate() and it still doesn't display anything.
For a history of what led to this question, you can reference this question Original question that led to this question
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>My Title</title>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css" />

<form method="POST">

    Appointment Date:
    <input type="hidden" name="action" value="list_appointments" />
    <input type="text" id="datepicker" name="date" class="datepicker" />
    <input type="submit" value="Refresh List" name="Update" />

</form>

Comment: Don't use document.write, if called after the page has finished loading it will erase the whole page before writing
Comment: Doesn't work because you are calling that outside of a ready callback, the element doesn't exist yet when you make that call
Comment: @PatrickEvans Noted.  This problem still occurs though,  I'm just using it as a debugging device.
Answer: I believe this is what you need. Remember to keep your function calls within the same document load function, i.e. $(document.ready).


Proving that $\dim(R[t]) \leq 2 \dim(R) + 1$ using localization

Question: I'm studying for an exam, this is part of an exam question.

Let $S = R[t]$ where $R$ is an integral domain. Let $Q < P$ be prime ideals of $S$ such that $Q \cap R = P \cap R = P_0$. Let $Y = R-P_0$ Show that $P_0S$ is a prime ideal of $S$ and that:
$$\frac{SY^{-1}}{P_0SY^{-1}} \cong F[t]$$
For a field $F$. Hence prove that $P_0S = Q$

For this part, I think that $P_0S = P_0[t]$ is prime since if you take two polynomials from outside $P_0[t]$, $f$ and $g$, they have some coefficients not in $P_0$. Taking the product, you will at some point get a sum involving a product of two coefficients, neither in $P_0$. $P_0$ is prime, so this coefficient won't be in $P_0$, thus the result $fg$ isn't in $P_0[t]$. I think this works.
I really have no idea what's going on with this quotient. I think it's the same thing as:
$$\frac{RY^{-1}[t]}{P_0Y^{-1}[t]}$$
Because $Y$ lives inside $R$, so it only affects the coefficients. $P_0Y^{-1}$ is maximal in the localization of $R$, $RY^{-1}$ so this is how the field comes about. The "hence" bit presumably follows from the solution to this bit, but I'm not really sure how.
Here are the other parts of the question:

With $S$ as before, prove that $\dim(S) \leq 2\dim(R) + 1$

Not sure how the previous parts really help with this.

Now suppose $S$ is a finitely generated $A$ algebra where $A$ is a subring and $\dim(A)$ is finite. Prove that $\dim(S)$ is finite.

Here I guess since $S = A[s_1, \ldots, s_n]$, it's the homomorphic image of a polynomial ring, and we can use the bound from before to bound $\dim(S)$. I guess the exact numbers matter less since I'm only asked to prove it's finite.
Answer: I'm going to start backwards and first show how the first part yields the bound on the Krull dimension of $R[t]$.
An immediate consequence is that

Any proper chain of prime ideals in $R[t]$ lying over a prime ideal in $R$ has length at most $2$.

Indeed if $Q_1, Q_2 \subsetneq P$ is such that $P_0 = Q_1 \cap R = Q_2 \cap R = P \cap R$ then we saw that $Q_1 = P_0[t] = Q_2$.
So start with a chain of maximal length in $R[t]$, $$P_1 \subsetneq P_2 \subsetneq \ldots \subsetneq P_k$$ in $R[t]$.  Contraction gives us a chain $$Q_1 \subsetneq \ldots \subsetneq Q_m$$ in $R$ (after we remove redundancies), where each $Q_i = P_j \cap R$ for some $j \geq i$.
We know that each $P_i$ lies over exactly one or two $Q_j$s,
therefore $$dim(R[t]) + 1 = k \leq 2m \leq 2(dim(R) + 1)$$
Now for the justification....
Your argument that $P_0R[t] = P_0[t]$ is prime goes through fine, but I'll mention that a slick, traditional way to show this is by using the fact that $\frac{R}{M}$ is a domain iff $M$ is prime and the natural isomorphism $\frac{R[t]}{P_0[t]} \cong \left(\frac{R}{P_0}\right)[t]$.
For the main part of the question....
Start by noting that if $Q$ is $0$ then trivially $P_0 =0$ and $P_0R[t] = Q = 0$.  So we can assume $0 \subsetneq Q \subsetneq  P$.
Now let's break down the quotient, I'm going to change the notation to what is standard.
$RY^{-1}$ is usually referred to as the localization at $P_0$, and written $R_{P_0}$.
Now the two things we need to know about localization are: (1) for $\mathfrak{p}$ a prime ideal of $R$, we have a  bijection between ideals of $R_{\mathfrak{p}}$ and ideals of $R$ contained in $\mathfrak{p}$.  In particular $R_{\mathfrak{p}}$ is local ring with maximal ideal $\mathfrak{p}R_{\mathfrak{p}}$  (2) localization commutes with polynomial extension (check this by universal properties or direct computation)
Thus your quotient is
$$\frac{(R[t])_{P_0}}{(P_0 R[t])_{P_0}} \cong
\frac{R_{P_0}[t]}{P_0R_{P_0}[t]} \cong \left(\frac{R_{P_0}}{P_0R_{P_0}}  \right)[t]
$$
and therefore taking $F = \frac{R_{P_0}}{P_0R_{P_0}}$ we have the claim.
Lets break this up as $$R[t] \xrightarrow{\iota} R_{P_0}[t] \xrightarrow{\pi} F[t] $$
So what are we even doing with this quotient? The core idea here is that $F[t]$ is a $PID$ so every non-zero prime ideal in $F[t]$ has height $1$.  We can thus get information about $Q$ and $P$ by looking at their homomorphic images in $F[t]$ under the composition $\pi \cdot \iota$.  In particular, the equality $Q=P_0R[t]$ would follow immediately if we can show that $Q \subset ker(\pi \cdot \iota)$, which would mean every polynomial in $Q$ takes coefficients in $P_0$.
Of course there are some details to work out, but the path is pretty clear.  This amounts to a straightforward exercise, which i think is worth completing on your own. I'll outline details below in case that is helpful.

 We start with the observation that for $\mathfrak{p}$ a prime ideal of $R[t]$ and $\mathfrak{p_0} = \mathfrak{p} \cap R$, $\mathfrak{p}R_{\mathfrak{p_0}}[t]$ is a prime ideal of $R_{\mathfrak{p_0}}[t]$ (check this for yourself). (For the special case $\mathfrak{p} \cap R = 0$, this just says $\mathfrak{p}$ extends to a prime ideal of $K[x]$ where $K$ is the quotient field of $R$.) Moreover if $\mathfrak{p} \subsetneq  \mathfrak{q}$ for any ideal $\mathfrak{q} \subset R[t]$, then $\mathfrak{p}R_{\mathfrak{p_0}}[t] \subsetneq  \mathfrak{q}R_{\mathfrak{p_0}}[t]$.
 Thus the chain of prime ideals $$0 \subsetneq  Q \subsetneq  P$$ in $R[t]$ extends to a chain of prime ideals $$0 \subsetneq QR_{P_0}[t] \subsetneq  PR_{P_0}[t]$$ in $R_{P_0}[t]$. Letting $\pi$ be the projection $R_{P_0}[t] \rightarrow F[t]$, we look at the chain $$0 \subset \pi(QR_{P_0}[t]) \subsetneq \pi(PR_{P_0}[t])$$ (That this is a chain of prime ideals and that the second inclusion is strict are because $\pi$ is surjective and $QR_{P_0}[t]$ contains the kernel of $\pi$). Now since this chain is in a $PID$, we deduce $\pi(QR_{P_0}[t]) = 0$, and indeed $Q \subset ker(\pi \cdot \iota)$.


Images as Questions

Question: I couldn't decide whether this belonged as an answer to Do we need guidelines? or as its own question, but I decided it might be nice to have as its own question.
In a comment made by (@The Almighty Bob) here he says that images as questions qualify for low quality questions. I actually think this is a valuable observation. It makes it so that the question is unsearchable and imho shows very little effort at communicating their difficulties with the community (or at the very least the two are correlated). What do people think about closing questions where the main question is a picture from a textbook (obviously including graphs can be useful) as unclear?
Comment: Just to clarify: I voted to close because the question was very unclear. This had nothing to do with the picture in the first place. If it would have been clearer (i.e. who has access to the oil? What are the costs for what?) then I would have closed it as a low quality question (because of the picture).
Answer: I agree that images of text with no obvious justification are just a sign of laziness and do not contribute good, searchable, standardized content of the form we want.
I would suggest that before closing questions (for whatever reason) we should first post a comment and give the user at least some time to make the necessary improvements to their question. In this case, that was amount to asking the user to retype the offending material.
Comment: I agree (surprise) with closing "picture questions". I disagree with the not closing part however. Someone usually answers anyway and as soon as the question is answered the person who asked has no incentive to improve his question any more. However, we should write a nicer comment (e.g. This would be a good question but ... . As soon as you have done ... we happily open the question again.)
Comment: @TheAlmightyBob  I agree. We should not consider closing a question as something bearing a flavor of permanence (and so creating hesitation as to whether to apply it). It is just a "negative" incentive to improve question-content, and it should be applied, say _immediately_, when a question is problematic. Of course it should also be accompanied by a comment to explain the situation (the standard texts that go with closing are a failure in my opinion), and to indicate more precisely what kind of improvements are needed.
Comment: @TheAlmightyBob Yes, fair point and I agree with this. But we need to be diligent on encouraging the owners of closed questions to edit them (and on voting to reopen appropriately edited questions) to ensure we don't scare away potentially productive members of the community.
Comment: @TheAlmightyBob If you close quick enough, nobody can answer that question. And after the fact, if the OP does not care enough about the question, neither close nor "nice comment" will make him change his mind.
Answer: I was directed here by a debate spawned by a question of mine: Independence of price and wealth in Walras' Law
I'm strongly against the closure of questions centered on pictures. Pictures are an easy way to show, word-by-word, an author's definitions, which are important when dealing with concepts whose formalization differs across textbooks. For instance, whereas the concept "game" is defined only by words in elementary Microeconomic texts such as that of Pindick and Rubinfeld, graduate-level books like Mas-Collel and Whinston's designate game to be a tuple, or ordered set.
An alternative to the use of pictures is the typing of all texts word-by-word which is, more often than not, a tiresome, laborious task, particularly when the use of Latex is required. This would go against what I believe to be one SE's purposes, which is practicity. If one must go great lenghts to solve simple doubts, he or she had better take private classes instead.
Also, I have trouble believing users would truly transcript the author's text word-by-word. In order to save effort, they would rephrase passages, which would confuse other users. After all, if he or she who's asking had a clear understanding of the text, there would be little need in searching for help.
I've used pictures in most of my questions in Math SE, as my history can tell in https://math.stackexchange.com/users/222095/bruno-schiavo, and I've never been flagged for that. In fact, people seem to be pleased by the use of book prints, as it can be seen in (http://mathhelpforum.com/differential-geometry/249557-concept-dx-manfredo.html#post870742).
At last, I don't think question searchability would be greatly compromised by the use of images. Alongside with posting the image, the user must clarify his doubt in the passage and, by doing this, most keywords present in the excerpt should be used. Also, pictures often contain expressions in formal mathemathic language, which has zero search value. There is broad space for inputting keywords for the means of searchability, and this space is the Tag bar, which has, unfortunately, a very poor selection of options. We should focus on improving it.
Comment: The point that a question with an image is likely to contain in text most of the relevant keywords does, indeed, deal a serious blow to the "but images are not searchable" line of argument.
Comment: Also, because typing down the question and definitions often helps clarifying things. It has happened to me quite often to cancel asking the question here, while I was still phrasing my exact issue.
Comment: It may help to know why we (or at least I) felt this way about the image policy. A few months ago (I'm guessing it corresponded to the start of the the undergraduate semester), there began to be large quantities of questions that only had a picture of a question and said something along the lines of, "I don't understand please help." As a community, I think many of us felt that these questions did not fit with the goals of our SE site and so, as a way to filter through these types of questions and encourage people to think about the material on their own and ...
Comment: to at least be able to identify what it was that they were struggling with, we decided to close these types of questions and give the reason as we don't allow images. Is this a one size fit all policy? Probably not, but I still think that the policy should remain intact because it discourages the site from being spammed by low quality questions (view it as a signalling game of sorts). Additionally, your specific question only had a few lines that were necessary to type from the image and is it really that much trouble to type it?
Comment: All of the above is obviously my opinion, and ultimately, I'm happy to support whichever policy the site decides on together.
Comment: The *Tag bar* is **NOT** meant for searchability either. It is meant for grouping questions, yes. But grouping keywords are a subset of the relevant keywords. It is not true that "*The Tag bas has [...] a very poor selection of options*". It is rather true that it has a pretty good selection of options, but not for the purposes you intend to abuse it for.
Comment: I have never heard of *"practicity"* as a key feature of StackExchange, and I see it actually the opposite. Not that we want to purposefully make it hard to ask questions, but it is a way of increasing marginal costs, reducing the amount of "why bother to search and try on my own" type of questions.
Comment: @Ubiquitous I don't follow how that does happen. Instead, I see it as the opposite: *Especially* when the image contains all the relevant keywords (and the OP won't repeat them hence in searchable text), *less* of the question is searchable and will be useful to future visitors.

Images as Questions


Sorry is a little confuse, please help.

Question: Is the square root of $2$ divided by any integer (except zero), a rational or irrational number?
Comment: a mistype of irrational sorry..
Comment: $\rm n\in\Bbb Z,\,\ \sqrt{2}/n = q \in\Bbb Q\:\Rightarrow\:\sqrt{2} = nq\in\Bbb Q,\:$  contra [many well-known proofs.](http://math.stackexchange.com/q/4467/23500)
Answer: Here is a thorough explanation.
Take an arbitrary integer $n\not=0$.
Then $\frac{n}{\sqrt{2}}$ is the desired expression.
Assume for sake of contradiction that $\frac{n}{\sqrt{2}}=\frac{p}{q}$ for relatively prime integers $p$ and $q$.
Square both sides.
$$\frac{n^2}{2}=\frac{p^2}{q^2}$$
Multiply both sides by $2q^2$.
$$n^2q^2=2p^2$$
So $2|n$ or $2|q$.
Case 1: Let $n=2k$ for positive $k$.
Then, $\frac{n}{\sqrt{2}}=k \sqrt{2}$ which is obviously irrational.
Case 2: Let $q=2a$ for integer $a$.
Then, $$4n^2a^2=2p^2$$
$$2n^2a^2=p^2$$
Hence $2|p$ which is a contradiction as we have assumed $p$ and $q$to be relatively prime.
Hence it will always be irrational.
This is VERY long-winded, but hopefully it will completely clear it up for you.
Answer: It is a irrational, as a irrational diveded by any integers (but 0) is still a irrational.

Sorry is a little confuse, please help.


Media query is not working for 768px ipad portrait

Question: My media query is not working for 768px ipad portrait.
If I change for min-width works perfect but affects the size when is on desktop version or some another resolution more than 769px
@media only screen and (max-width: 768px) {
  .sidebar-container.pressed .content-container {
    width: 93% !important;
  }
}

Someone can explain me that, and help how to solve? I just want make it work on 768px.
Thanks
Answer: iPhone 6 Media Queries
/* iPhone 6 in portrait & landscape */
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px) { /* STYLES GO HERE */}

/* iPhone 6 in landscape */
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPhone 6 in portrait */
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : portrait) { /* STYLES GO HERE */ }

iPhone 6 Plus Media Queries
/* iPhone 6 Plus in portrait & landscape */
@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px) { /* STYLES GO HERE */}

/* iPhone 6 Plus in landscape */
@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px)
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPhone 6 Plus in portrait */
@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px)
and (orientation : portrait) { /* STYLES GO HERE */ }

iPhone 5 & 5S Media Queries
/* iPhone 5 & 5S in portrait & landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px) { /* STYLES GO HERE */}

/* iPhone 5 & 5S in landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPhone 5 & 5S in portrait */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : portrait) { /* STYLES GO HERE */ }

iPhone 2G, 3G, 4, 4S Media Queries
It's noteworthy that these media queries are also the same for iPod Touch generations 1-4.
/* iPhone 2G-4S in portrait & landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) { /* STYLES GO HERE */}

/* iPhone 2G-4S in landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px)
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPhone 2G-4S in portrait */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px)
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad
/* iPad in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

/* iPad in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) { /* STYLES GO HERE */}

/* iPad in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries
/* If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries. */

/* Retina iPad in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

/* Retina iPad in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

/* Retina iPad in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries
/* If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design! */

/* iPad 1 & 2 in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

/* iPad 1 & 2 in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

/* iPad 1 & 2 in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

iPad mini
/* iPad mini in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

/* iPad mini in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

/* iPad mini in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */ }

Source:
http://stephen.io/mediaqueries/#iPad
Answer: For iPads in portrait mode it is generally best to be more specific in the media queries, so try something like this:
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
    /* Styles Here */
}

This way you target devices with screen width between 768px and 1024px which is what the iPad is, then you filter your targets by specifying the orientation as portrait.
You could try something like this - reducing the max-width - to minimize any other screens that it could effect, but I haven't tried it so can't verify it works.
@media only screen
and (min-device-width : 768px)
and (max-device-width : 770px)
and (orientation : portrait) {
    /* Styles Here */
}


Criar uma dimensão calendário com o mês anterior ao do Sys.date

Question: Olá, o scrip abaixo cria uma CSV com uma dimensão Calendário do ano de 2015 até o mês atual. Ocorre que eu gostaria que a função retornasse o mês anterior ao da execução. Ex: Se o Sys.Data registra 14/11/2017, ele retornasse a data 14/10/2017.
Ou, se possível, a data 01/10/2017, já que o dia 01 é o padrão nessa dCalendário.
OBS: Se preferirem, podem sugerir a criação de outro script
        tabela_tcm_dCalendario <- list(mes = 1:12, ano = 2015:2017) %>%
                              purrr::cross_df() %>%
                              dplyr::mutate(data = as.Date(sprintf("%d-%02d-01", ano, mes))) %>%
                              dplyr::filter(data < Sys.Date())
                              readr::write_csv("parametros_scraping/tabela_tcm_dCalendario.csv")

Answer: Adicionei a função slice no seu código
list(mes = 1:12, ano = 2015:2017) %>%
  purrr::cross_df() %>%
  dplyr::mutate(data = as.Date(sprintf("%d-%02d-01", ano, mes))) %>%
  dplyr::filter(data < Sys.Date()) %>%
  dplyr::slice(1:(nrow(.)-1))

Comment: Muito obrigado. A sugestão foi muito boa
Answer: Você consegue fazer assim:
library(lubridate)
library(dplyr)

data_frame(
  data = seq(ymd("2015-01-01"), (today() - day(today()) + 1 - months(1)), by = "month"),
  ano = year(data),
  mes = month(data)
)

Veja que a parte (today() - day(today()) + 1 ) - months(1) retorna o primeiro dia do mês anterior. A partir disso, usei a função seq para criar uma sequência de datas a partir de janeiro de 2015.
Comment: Muito Obrigado. O script está excelente. Acabei substituindo o meu. Essa parte final, confesso que ainda terei que estudar mais um pouco para compreender. Estou iniciando no R tem cerca de 1 mês.


How to grant more permissions to android shell user?

Question: I build some command line tool with ndk and execute it in /data/local/tmp. Now it prompts me "requires android.permission.RECORD_AUDIO" when I call some OpenSLES API in my command line tool:
W/AudioRecord( 4226): AUDIO_INPUT_FLAG_FAST denied by client
W/ServiceManager(  207): Permission failure: android.permission.RECORD_AUDIO from uid=2000 pid=4226
E/        (  207): Request requires android.permission.RECORD_AUDIO
D/PowerManagerService(  964): handleSandman: canDream=false, mWakefulness=Asleep
E/AudioFlinger(  207): openRecord() permission denied: recording not allowed
E/AudioRecord( 4226): AudioFlinger could not create record track, status: -1
E/libOpenSLES( 4226): android_audioRecorder_realize(0x453430) error creating AudioRecord object
W/libOpenSLES( 4226): Leaving Object::Realize (SL_RESULT_CONTENT_UNSUPPORTED)

I have also tried to grant shell with pm grant:
pm grant "com.android.shell" android.permission.RECORD_AUDIO
pm grant "com.android.shell" android.permission.RECORD_AUDIO
pm grant "com.android.shell" android.permission.RECORD_AUDIO
Operation not allowed: java.lang.SecurityException: Package com.android.shell has not requested permission android.permission.RECORD_AUDIO

changing /system/etc/permissions/platform.xml has no effect too.
Can I just debug my OpenSLES demo in the android shell ? How can I get more permisson just in shell .
Must I create a jni and java project for every experimental code snippet and modify them together when I change some C++ interfaces ?
Can I access RECORD_AUDIO, CAMERA directly in a command tool from shell ?
Comment: @Samveen Your have a post about running C++ application in android shell. Do you know how to grant permissions to C++ application ?
Comment: Yes, you can run it as superuser. You need a rooted device for that.
Answer: This is the new permissions model in Android Marshmallow in action. To get this permission you'll need to prompt the user to grant it. Here's what I do:

Whenever I need RECORD_AUDIO permission I run a check to see if I have it:
private boolean hasRecordAudioPermission(){
    boolean hasPermission = (ContextCompat.checkSelfPermission(this,
        Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED);

    log("Has RECORD_AUDIO permission? " + hasPermission);
    return hasPermission;
}

If I don't have it then request it
private void requestRecordAudioPermission(){

    String requiredPermission = Manifest.permission.RECORD_AUDIO;

    // If the user previously denied this permission then show a message explaining why
    // this permission is needed
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            requiredPermission)) {

        showToast("This app needs to record audio through the microphone....");
    }

    // request the permission.
    ActivityCompat.requestPermissions(this,
            new String[]{requiredPermission},
            PERMISSIONS_REQUEST_RECORD_AUDIO);
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    // This method is called when the user responds to the permissions dialog
}


iPython Code Completion / Intellisense on Dot Possible?

Question: As someone trying to learn the ins and outs of Python (with emphasis on scientific computing - ie: pandas, numpy, scikit-learn), most of the gurus out there seem to recommend and use iPython notebooks.  My biggest sticking point as a beginner/intermediate coder is that I NEED code completion / intellisense -like functionality from an IDE to learn the function parameters.  I'm not hard-wired yet to just know what parameters are available at my current development.
In iPython, I noticed I can press Tab to show the drop-down of options (seen below as pd.) but I don't want to have to hit  each time.  That's not user-friendly for my needs.  Instead, I would like it to show only available classes and methods when I press dot.
Secondly, I notice that if I did say pd.read_csv(<TAB>, I get a lot more options than are the actual parameters in read_csv.
Question: Can iPython automatically show accurate code completion options instantly after pressing dot / period?  Also, is there a way to configure it to only show the available function parameters when within a function?
To make this question super-specific, I'm not asking about using any other IDE; I'm asking very specifically in regards to just iPython and wondering if there's a way to set some kind of configuration to achieve accurate "dot" display options instantly when pressing "dot" (no time delay).

Example below shows Desktop which is obviously not a parameter of pd.read_csv().
Comment: Just mentioning a solution for full IntelliSense for JupyterLab I am working on: https://github.com/krassowski/jupyterlab-lsp (including completion on dot and signature suggestion). Not sure if this would qualify as an answer... - should I post one?
Comment: @krassowski looks like a potential answer to this question. auto invocation on '.' (dot) is the primary pain-point and purpose of this question. If you think your library is a solution, by all means feel free to contribute an answer in the context of this question.
Answer: You can press <Shift>-<Tab> to get a tooltip showing the function's signature:

Alternatively, invoking zip? opens a documentation pane at the bottom of the window.
As far as having the tooltip open automatically, I'm unsure. I'd guess that it isn't possible via configuration.
Comment: Neither shortcut displays any hint for class members, functions parameters or anything. Is there anything else I've should install to enable?
Comment: @tutuca As far as I am aware, this should work without needing any packages other than jupyter. I'd suggest making sure that you have a recent version of jupyter installed, and perhaps looking to see if the shortcut is different on your operating system.
Comment: You are right, my libraries wasn't reloading, I just turned the notebook on and off and it started working. Thanks for replying :)
Comment: Is there a way to access this feature in the interactive IPython shell?
Comment: I have to write the complete function name to see its description. It doesn't show the list of functions to choose from.
Answer: Almost 3 years later, I've finally come across a potential solution.
Answer: Install nbextensions and enable the Hinterland extension.

Enable code autocompletion menu for every keypress in a code cell,
  instead of only calling it with tab.

Here's what you do:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
Start jupyter notebook (browser launches)
One of the tabs should now show "Nbextensions"
There, you will find "Hinterland". Check the box to enable.

Hinterland has some adjustable options like:

hinterland.hint_delay: delay in milliseconds between keypress & hint request.
hinterland.enable_at_start: Whether to enable hinterland's continuous hinting when notebook is first opened, or if false, only when selected from the help-menu item.
hinterland.hint_inside_comments: Whether to request hints while typing code comments. Defaults to false.
Other regex options: hinterland.exclude_regexp, hinterland.include_regexp, hinterland.tooltip_regexp
Comment: Thanks for the answer, just solved my problem!
Comment: How to turn off auto completion in it?
Comment: If you are in a conda environment install it like this instead `conda install -c conda-forge jupyter_contrib_nbextensions
`
Answer: Now there's a better way to get accurate code completion operation. It can be triggered by any character you typed. Inspired by TabNine, I developed a code auto-completion extension for Jupyter Notebook Jupyter TabNine.
It's available on pypi index now.  Simply issue following commands, then enjoy it:)
pip3 install jupyter-tabnine
jupyter nbextension install --py jupyter_tabnine
jupyter nbextension enable --py jupyter_tabnine
jupyter serverextension enable --py jupyter_tabnine

Comment: TabNine is the all language completer https://www.tabnine.com/. It works for .NET. And we can make this jupyter plugin work for .NET simply by changing one line code. You can create an issue here: https://github.com/wenmin-wu/jupyter-tabnine/issues
Answer: This is what worked for me:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter notebook

To see the Nbextensions tab if something has hidden it:
jupyter nbextensions_configurator enable --user

under Nbextensions uncheck "disable confirguration for nbextensions without explicit compatibility ..." (disclaimer - all risks are yours for doing this)
select only

"Hinterland" for the formatting ones. I had some other nbextensions selected and somehow it was not working.
"Nbextension edit menu item" & "Nbestenision dashboard tab" (in order to see this tab again next time)
Answer: If you are using Jupyter notebook and your Intellisense is not working then type below and give a press TAB after (.)
%config IPCompleter.greedy=True
it will work for you as well.
Comment: It's hard for me to tell if this answers their question or just suggests pressing tab after the `.` (which is explicitly what the user wishes to avoid in their question).
Comment: as of now we don't have anything that can avoid pressing Tab. May be in future...
Answer: If you are using JupyterLab, the jupyterlab-lsp extension (with pyls server installed) does invoke the completer automatically upon typing the dot (or any character if told so):

Pros:

completion suggestions are available even before the code gets executed (static analysis)
documentation panel can be displayed for the completion candidates
type icons (with different themes available)
other IDE features included (signature hints, diagnostics, rename, etc)

Cons:

not yet as configurable as Hinterland (but it is getting there)
some users prefer to only get completions for objects in already executed cells

Assuming Python 3.6+ and JupyterLab 3.0+ are already installed:
pip install jupyterlab-lsp    # client and server extension
pip install jedi-language-server     # fast language server, or
# pip install python-language-server[all]     # another language server

For more detailed and up-to-date installation instructions please see this link.
Disclaimer: I am one of the authors of this extension.
Comment: For those like me stuck on python3.6, the highest supported versions of the libraries above are: ``python -m pip install jedi-language-server==0.21.0 jedi==0.17.2 ipython==7.16.1``
Answer: For Mac in JupyterLab just press tab


Learning about Manifolds

Question: I am looking to learn about manifolds for use in signal processing. I have a engineering degree where I have covered calculus and basic linear algebra, with this background in mind, does anyone have a good recommendations for a introductory textbook on manifolds?
Comment: Given the background you stated (calculus and linear algebra, an engineering degree; presumably no advanced calculus, no topology, no undergraduate differential geometry, etc.), I think a more appropriate place to begin than Spivak's **Calculus on Manifold** or Lee's **Introduction to Smooth Manifolds** (the two books thus far suggested) is Dodson/Poston's [**Tensor Geometry**](http://www.amazon.com/dp/354052018X). After their book, and you can probably skip most of the physics relativity stuff in it, you will be in a better position to look at the other books suggested.
Answer: If you want an elementary introduction to manifolds, assuming very little background, I'd suggest you start with

Differential Geometry: Curves - Surfaces - Manifolds, Second Edition by Wolfgang Kühnel.

Then (or else)
You might want to look into one or more of the following:

Introduction to Smooth Manifolds by John M. Lee.  (It's a very well-known, loved, and highly recommended text.)

You might want to compare Lee's book (table of contents, etc) with

J. Munkres's text Analysis on Manifolds and/or
Spivak's Calculus on Manifolds.

You can preview each of the texts linked above at Amazon.com to see which best meets your needs, in terms of topics covered, apparent level of difficulty, etc.
Answer: Calculus on Manifolds by Spivak is a quality introduction if you haven't seen a lot of Analysis.
Answer: Beware - Spivak is very pretty but very concise; skimming Munkres' Analysis on Manifolds suggests it covers much of the same material but in a much more user-friendly way.

Learning about Manifolds


Jackson 2.0 Cyclic Relationship

Question: I'm using jackson 2.0 to serialize a class that has a reference to itself.
Class A{
  String identifier;
  List related;
}

I want the JSON to look like so:
{ identifier: "name",
  related [ identifier: "related to name",
            identifier: "also related to name"]
}

Essentially I want to go through one depth of recursion.  I've tried
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")

But it only stops recursion if there is a link back to the original object.  How can i fix this?
Answer: Jackson 2.0 identity handling is designed to include first instance of an Object as is, and only secondary references using id.
But you could define custom serializer (and deserializer) for your 'related' field, to use different serialization style:
@JsonSerialize(contentUsing=MyIdOnlySerializer.class) List related;

and implement MyIdOnlySerializer so that it only writes out identifier.

Jackson 2.0 Cyclic Relationship


How do I select items from an array using an array of indices with Linq?

Question: How do I select items from an array using an array of indices with Linq?
Following code works:
String[] A = new String[] { "one", "two", "three", "four" };
int[] idxs = new int[] { 1, 3 };
String[] B = new String[idxs.Length];
for (int i = 0; i < idxs.Length; i++)
{
     B[i] = A[idxs[i]];
}
System.Diagnostics.Debug.WriteLine(String.Join(", ", B));

output:
        two, four

Is there a LINQ way (or other one-liner) to get rid of the for loop?
Comment: Why do you want to get rid of the for loop?  Is it slow? Hard to read?
Answer: A LINQ way would be this:
var b = idxs.Select(x => A[x]).ToArray();

Answer: You can use it with Select your index and your A[index] Like:
String[] A = new String[] { "one", "two", "three", "four" };
int[] idxs = new int[] { 1, 3 };
var result = idxs.Select(i => A[i]).ToArray();

foreach(var s in result)
  Console.WriteLine(s);

Output will be:
two
four

Here is a DEMO.


Show 3 figures with captions next to each other using css

Question: I have 3 figures with captions. I want them horizontally aligned in the middle of the page, side by side, but all I can get is three vertical one. Using only HTML5 & CSS, how do I accomplish this?
Here is my HTML:

Running

Shopping

Spending time with friends & family

Here is my CSS:
    .row figure {
        display: flex;
        flex-flow: column;
        padding: 5px;
    }

   .row figure img {
       margin:auto;
       padding:auto;
       width: 30%;
       box-shadow: rgb(101, 101, 101) 10px 10px 25px;
   }

   .row figure figcaption {
       color: rgb(19, 7, 122);
       font: italic smaller sans-serif;
       padding: 3px;
       text-align: center;
   }

Comment: please check my post.
Comment: Here is the solution I came up with:
https://codepen.io/webdevgirl/pen/RmVWwy
Answer: Change flex-flow: column; to flex-flow: row; or flex-flow: row-reverse;
Answer: There is a missing closing figure tag that is one of the reasons why you could not achieve what you wanted.
I use display: flex and implicitly mention flex-direction: row(optional) to lay the figures out horizontally and by specifying width: 100%; it will take full width (100%) of the container; in this case, the body element.
justify-content: center will center the content of the div.

.row {
  display: flex;
  width: 100%;
  flex-direction: row;
  justify-content: center;
}

figure {
  margin: 0;
  margin-right: 20px;
  /*
  The below properties are demo purpose. Feel free to change it to fit your needs.
  */
  width: 100px;
  height: 100px;
  background: blue;
}

Running

Shopping

Spending time with friends & family


Proving soundness property of a Hilbert system

Question: Now that I have a better understanding of soundness, I'd like to try this again.
My goal is to prove that the classical Hilbert system has the soundness property:
$$\Gamma \vdash \varphi \implies \Gamma \models \varphi$$
For a set of wffs $\Gamma$ and wff $\varphi$.
This soundness property being "If $\varphi$ is provable from $\Gamma$, then $\varphi$ is also true under every interpretation where $\Gamma$ is satisfied (i.e. when all its propositions are true)."
We can induct on the length of the proof, which we denote as a sequence of wffs $\varphi_1, \varphi_2, \varphi_3, ..., \varphi_n = \varphi$.
We start with the case of $n=1$, where we only have a one-line proof $\varphi_1$. There are two cases:

$\varphi$ is an axiom of the Hilbert system. We can write out the truth tables and show that for every interpretation, the axiom is true.

Axiom I:
\begin{array}{|c|c|ccc|} \hline
(A & \to & ( B & \to & A )) \\
\hline
F & T & T & F & F \\
F & T & F & T & F \\
T & T & T & T & T \\
T & T & F & T & T \\
\hline
\end{array}
Axiom II:
\begin{array}{|ccccc|c|ccccccc|} \hline
((A & \to & (B & \to & C)) & \to & ((A & \to & B) & \to & (A & \to & C))) \\
\hline
F & T & F & T & F & T & F & T & F & T & F & T & F \\
F & T & F & T & T & T &  F & T & F & T & F & T & T \\
F & T & T & F & F & T &  F & T & T & T & F & T & F \\
F & T & T & T & T & T &  F & T & T & T & F & T & T \\
T & T & F & T & F & T &  T & F & F & T & T & F & F \\
T & T & F & T & T & T &  T & F & F & T & T & T & T \\
T & F & T & F & F & T &  T & T & T & F & T & F & F \\
T & T & T & T & T & T &  T & T & T & T & T & T & T \\
\hline
\end{array}
Axiom III:
\begin{array}{|ccc|c|ccccc|} \hline
((A & \to & B) & \to & (\neg & B & \to & \neg & A)) \\
\hline
F & T & F & T & T & F & T & T & F \\
F & T & T & T & F & T & T & T & F \\
T & F & F & T & T & F & F & F & T \\
T & T & T & T & F & T & T & F & T \\
\hline
\end{array}

$\varphi$ is a element of $\Gamma$. Since we only care about the situation where $\Gamma$ is satisfied, all elements of $\Gamma$ will be true.

Moving onto the case of $n > 1$, our inductive hypothesis is that $\Gamma \models \varphi_k$ holds for all $1 \leq k < n$ for all interpretations that satisfy $\Gamma$. It is possible that $\varphi_n$ is an axiom or an element of $\Gamma$, which are cases we've already covered. But since $n > 1$, we now look at a new possible case where $\varphi_n$ can be the result of modus ponens proven from two earlier wffs $\varphi_i$ and $\varphi_j = \varphi_i \to \varphi_n$ with indices $i, j < n$. By inductive hypothesis we know $\Gamma \models \varphi_i$ and $\Gamma \models \varphi_j$, i.e. $\varphi_i$ and $\varphi_j$ are both true in every interpretation where $\Gamma$ is satisfied.
Using truth tables:
\begin{array}{|c|ccc||c|} \hline
\varphi_i & \varphi_i & \to & \varphi_n & \varphi_n\\
\hline
F & F & T & F & F \\
F & F & T & T & T \\
T & T & F & F & F \\
T & T & T & T & T \\
\hline
\end{array}
We see in the last case where $\varphi_i$ is true and when $\varphi_i \to \varphi_n$ is true, $\varphi_n$ is true as well. Thus modus ponens is sound, and we have covered all cases. This closes the inductive step.
Now we can conclude that if $\varphi$ is provable from $\Gamma$, then $\varphi$ is true in all interpretations where $\Gamma$ is satisfied.
Have I proven that the Hilbert system has the soundness property?
Comment: Perfect.........
Comment: Quite perfect... "By inductive hypothesis we know $\varphi_i,\varphi_j$ are both true." NO; we know that they are logical cons of $\Gamma$, i.e. that $\Gamma \vDash \varphi_i$ and $\Gamma \vDash \varphi_j$.
Comment: Thus, because *modus ponens* is sound, we conclude that: in every int where all formulas of $\Gamma$ are true, also $\varphi_n$ must be true.
Comment: Updated with truth tables.
Comment: @MauroALLEGRANZA Is that not saying the same thing? Or I guess if $\Gamma \models \varphi_i$ then is it incorrect to say $\varphi_i$ is true, period -- or would it have been better to say "true under every satisfiable interpretation of $\Gamma$"
Comment: Edited my post, is that more accurate?
Comment: Thanks, @MauroALLEGRANZA
Comment: @MauroALLEGRANZA I don't agree.  The means by which axiom schema get instantiated could be unsound, or the rule for putting something in the place of letters could, a priori, be unsound.
Answer: Not quite.  First off, instead of using the abbreviated form for the axioms, you'll need to use the full form which satisfies the definition of a well-formed formula.  Why?  Because you will inevitably end up referring to either instantiations of those axiom schema, or substitutions of those axiom, and either of those require the use of the full form.
Also, it's not entirely clear if you use axiom schema or axioms and have a rule of substitution for those axioms.  If you use axiom schema, then you need to show that any instantiation of the axiom schema is sound.  If you use axioms, then you need to show that the use of the rule of (uniform) substitution is sound.
Comment: "any substitution of any the axioms is sound OR prove that any instance of any of the axiom schema is also sound" What's the difference? Aren't the truth tables I posted proof that the axiom schemas are sound?
Comment: I mean I understand but I don't see where it fits into proving the soundness property of the system, I thought these concepts of which you speak are already built into the system by definition. Where in my proof would I need to add more and what exactly? I don't understand what's technically missing
Comment: I don't follow. Isn't something like $A \to (B \to A)$ already presuming that $A$ and $B$ are wffs? And what do you mean by sound instantiation? That seems like a very different thing. What do you mean by "full form"? What substitution rule?
Comment: @user525966 A→(B→A) is not a wff, presuming that A and B are wffs, no.  Were it the case that such were a wff, then we could substitute each instance of A with A→(B→A) yielding A→(B→A)→(B→A→(B→A)), which is not uniquely readable, and thus not well-formed.
Comment: When you substitute AFAIK you use parentheses, so it's like substituting each instance of $A$ with $(A \to (B \to A))$, so you'd get $(A \to (B \to A)) \to (B \to (A \to (B \to A)))$
Comment: @user525966 By sound instantiation, I mean taking a formula such as (A→(B→A)) and say instantiating it as ((A→B)→(C→(A→B))).  The 'full form' is the form that includes all parentheses as specified by the definition of a well-formed formula.  The rule of uniform substitution says that for any axiom we can substitute any wff for any variable symbol, provided that each variable symbol in a formula gets replaced by the same wff.
Comment: @user525966 It does work that way, as you say, but only in infix notation, except the rule of substitution only applies when you start with a wff.  More generally, one is allowed to substitute any wff W1 for any letter provided that such happens uniformly within a wff W2.  So, if A→(B→A) were a wff, then it would be allowable to substitute A with A→(B→A) as I did above.
Comment: Or are you saying that instead of $A \to (B \to A)$ I have to say something like $((A)\to ((B) \to (A)))$ as the "full form"?
Comment: @user525966 Perhaps something like ((A)→((B)→(A))), yes.  I'd need to see the full formation rules to know better.  Also, you need to prove that any substitution of any the axioms is sound OR prove that any instance of any of the axiom schema is also sound.


GNU Screen: opening each screen buffer in a separate terminal tab

Question: I'm looking for a Linux terminal that is fully integrated with GNU Screen, i.e. mapping each screen buffer to a separate tab and with full scrollback support - all that inside a SSH session.
Is this currently possible?
Answer: Nope. There's currently no protocol that would allow Screen to control the terminal's tabs and to multiplex the I/O from multiple tabs over the same connection.
Answer: As ak2 said, there appears to be no such thing atm.  At the moment.
That said, I looked into the very same thing (I'd love to have GNOME (or whatever) terminal on the box when I'm in front of it, but a 1:1 mapping to screen tabs when working on it remotely).
What I did find was an old bug/discussion for GNOME Terminal.  Sadly, not much seems to have come of it, but at least there does seem to be some interest in such.  Maybe someone will be itching enoug at some point to scratch it.
Answer: It's a bit late, but I was looking for the same thing - and didn't find one. So I made my own which works with any terminal (Konsole, Tilix, Gnome-terminal, etc.). Check it out here: https://github.com/tycho-kirchner/remote-work


Kafka Streams topology with windowing doesn't trigger state changes

Question: I am building the following Kafka Streams topology (pseudo code):
gK = builder.stream().gropuByKey();
g1 = gK.windowedBy(TimeWindows.of("PT1H")).reduce().mapValues().toStream().mapValues().selectKey();
g2 = gK.reduce().mapValues();
g1.leftJoin(g2).to();

If you notice, this is a rhomb-like topology that starts at single input topic and ends in the single output topic with messages flowing through two parallel flows that eventually get joined together at the end. One flow applies (tumbling?) windowing, the other does not. Both parts of the flow work on the same key (apart from the WindowedKey intermediately introduced by the windowing).
The timestamp for my messages is event-time. That is, they get picked from the message body by my custom configured TimestampExtractor implementation. The actual timestamps in my messages are several years to the past.
That all works well at first sight in my unit tests with a couple of input/output messages and in the runtime environment (with real Kafka).
The problem seems to come when the number of messages starts being significant (e.g. 40K).
My failing scenario is following:

~40K records with the same
key get uploaded into the input topic first
~40K updates are
coming out of the output topic, as expected
another ~40K records
with the same but different to step 1) key get uploaded into the
input topic
only ~100 updates are coming out of the output topic,
instead of expected new ~40K updates. There is nothing special to
see on those ~100 updates, their contents seems to be right, but
only for certain time windows. For other time windows there are no
updates even though the flow logic and input data should definetly
generate 40K records. In fact, when I exchange dataset in step 1)
and 3) I have exactly same situation with ~40K updates coming from
the second dataset and same number ~100 from the first.

I can easily reproduce this issue in the unit tests using TopologyTestDriver locally (but only on bigger numbers of input records).
In my tests, I've tried disabling caching with StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG. Unfortunately, that didn't make any difference.
UPDATE
I tried both, reduce() calls and aggregate() calls instead. The issue persists in both cases.
What I'm noticing else is that with StreamsConfig.TOPOLOGY_OPTIMIZATION set to StreamsConfig.OPTIMIZE and without it, the mapValues() handler gets called in debugger before the preceding reduce() (or aggregate()) handlers at least for the first time. I didn't expect that.
Tried both join() and leftJoin() unfortunately same result.
In debugger the second portion of the data doesn't trigger reduce() handler in the "left" flow at all, but does trigger reduce() handler in the "right" flow.
With my configuration, if the number or records in both datasets is 100 in each, the problem doesn't manifests itself, I'm getting 200 output messages as I expect. When I raise the number to 200 in each data set, I'm getting less than 400 expected messages out.
So, it seems at the moment that something like "old" windows get dropped and the new records for those old windows get ignored by the stream.
There is window retention setting that can be set, but with its default value that I use I was expecting for windows to retain their state and stay active for at least 12 hours (what exceeds the time of my unit test run significantly).
Tried to amend the left reducer with the following Window storage config:
Materialized.as(
    Stores.inMemoryWindowStore(
        "rollup-left-reduce",
        Duration.ofDays(5 * 365),
        Duration.ofHours(1), false)
)

still no difference in results.
Same issue persists even with only single "left" flow without the "right" flow and without join(). It seems that the problem is in the window retention settings of my set up. Timestamps (event-time) of my input records span 2 years. The second dataset starts from the beginning of 2 years again. this place in Kafka Streams makes sure that the second data set records get ignored:
https://github.com/apache/kafka/blob/trunk/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryWindowStore.java#L125
Kafka Streams Version is 2.4.0. Also using Confluent dependencies version 5.4.0.
My questions are

What could be the reason for such behaviour?
Did I miss anything in my stream topology?
Is such topology expected to work at all?
Comment: that quite interesting problems, can you somehow share the code with the generated test
Comment: Thank you for looking, @TuyenLuong.
I will update the post in a bit with more details.
At the moment, my suspicion is that the reason is in the join() part. It seems that that piece can run into race condition so that message travelling one flow doesn't get its counterpart from the other flow in time.
Comment: Maybe record caching is the issue? It's disabled using the `TopologyTestDriver` -- can you try to set `cache.max.bytes.buffering=0` to disable caching? (cf: https://docs.confluent.io/current/streams/developer-guide/memory-mgmt.html)
Comment: Thank you @MatthiasJ.Sax, I did that at the beginning (also mentioned in the description)
Answer: After some debugging time I found the reason for my problem.
My input datasets contain records with timestamps that span 2 years. I am loading the first dataset and with that the "observed" time of my stream gets set to the maximum timestamp from from input data set.
The upload of the second dataset that starts with records with timestamps that are 2 years before the new observed time causes the stream internal to drop the messages. This can be seen if you set the Kafka logging to TRACE level.
So, to fix my problem I had to configure the retention and grace period for my windows:
instead of
.windowedBy(TimeWindows.of(windowSize))

I have to specify
.windowedBy(TimeWindows.of(windowSize).grace(Duration.ofDays(5 * 365)))

Also, I had to explicitly configure reducer storage settings as:
 Materialized.as(
    Stores.inMemoryWindowStore(
        "rollup-left-reduce",
        Duration.ofDays(5 * 365),
        windowSize, false)
)

That's it, the output is as expected.
Comment: Good find! I though you processed the old data before the new data. For processing the new data before the old that, that makes totally sense :)


Calculate the area inside the loop

Question: The question is - how to calculate the area inside the loop $(x+y)^3=axy$, using double integral?
In this case parameter $a$ is positive. It's easy to imagine how it looks like, depending on $a$ value. For example $a=1$:

or $a=100$

No idea how to do that.
Comment: Hint: area = $\frac12 \int_0^{\pi/2} r^2 d\theta = \frac12 \int_0^\infty x^2 dt$ where $t = \tan\theta = \frac{y}{x}$.
Answer: HINT:
In polar coordinates, the loop is described by
$$r(\theta)=\frac{a\sin(\theta)\cos(\theta)}{(\cos(\theta)+\sin(\theta))^3}$$
$\theta \in [0,\pi/2]$.  The area, $A$, is then given by
$$A=\int_0^{\pi/2}\int_0^{r(\theta)}r\,dr\,d\theta \tag 1$$

SPOILER ALERT:  Scroll over the highlighted area to reveal the solution

From $(1)$, we have $$\begin{align}A&=\frac{a^2}2\int_0^{\pi/2} \frac{\sin^2(\theta)\cos^2(\theta)}{(\cos(\theta)+\sin(\theta))^6}\,d\theta\\\\&=\frac{a^2}2 \int_0^{\pi/2}\frac{\tan^2(\theta)\sec^2(\theta)}{(1+\tan(\theta))^6}\,d\theta\\\\&=\frac{a^2}2\int_0^\infty \frac{x^2}{(1+x)^6}\,dx\\\\&=\frac{a^2}{60}\end{align}$$
Comment: Thanks a lot for a hint, I have also thought about polar coordinates. It's easy-to-understand for me, how to calculate the last integral, but if it's not too much trouble for you - can you explain, how did you convert my function in ortogonal coordinates to your $r(\theta)=...$ in polar coordinates?
Comment: For those, who have the same answer: just use $x = r*sin(\theta);y = r*cos(\theta)$
Comment: I see you have it.  Well done!  Yes, let $x=r\cos(\theta)$ and $y=r\sin(\theta)$.  Then, remember that $dx\,dy\to r\,dr\,d\theta$.

Calculate the area inside the loop


Interesting Applications of Interfaces

Question: Why are interfaces useful?
Actually, I have a [small] idea of why interfaces are useful/necessary but...
What are [interesting or realistic] applications of interfaces?
Comment: Do you mean the Java interface feature, or the interface concept?
Comment: well...both - is there a difference?
Comment: This question gets asked a lot, you should search for some relevant questions
Comment: sorry, i was hoping this question would get more practical applications
Answer: Interfaces are interesting because you can allow 2 classes to implement the same methods. Lets look at an example.
Say I have a base class called Animal. All animals breathe, and communicate. Now lets say I have 3 classes, called Dolphin, Human, and Tiger. All of theses animals breathe and communicate. But I want to implement a walking method for the Human and Tiger. Dolphins cant walk. So I inherit the IWalk method for the latter two, and when I compile the class, I HAVE to implement the methods specified in the interface, or it won't compile. It's a contract saying, "If I want to implement this class, I have to implement these methods."
Comment: -1: no mention of which interfaces are being implemented. Do you mean "implement the IWalk interface", not "inherit the IWalk method"?
Comment: @jamesbrady: Depending on your choice of language (e.g. C++) you inherit an interface, there is no implements keyword. Be a sport and remove the -1, the question is language agnostic.
Comment: How is this interesting or realistic.  People almost never write classes representing animals, unless it's for some class assignment.  How is this marked right, when it doesn't answer the original question.
Answer: One use that I have for interfaces is to help with unit testing framework classes that are hard to mock.  I will create an interface that works basically the same as the framework class and a wrapper class that implements the interface.  The constructor of the wrapper class takes an instance of the framework class as an argument.  The wrapper delegates the interface functionality it supports to the framework class, but I implement to my interface instead of the framework.   Using the interface makes it easy for me to mock out the wrapper class's functionality in my unit tests -- either using a mocking framework or by providing a fake class that also implements the interface and supplying it via dependency injection to any classes that would normally rely on the framework class.
Answer: They allow polymorphism without some of the bad sides of inheritance.
What do I mean by bad sides of inheritance?
Code and Data inherited down a long chain (making it less obvious).
Inherited members that are over-ridden somewhere in the inheritance tree.
How can you use polymorphism?
To avoid repeating yourself. Create functions, switches, or conditionals which use the interface instead of the objects that implement the interface.
Java Specific
In Java, it often makes sense to use interfaces as a way to get multiple-inheritance.
This makes sense if something naturally fits into two categories and you have separate behavior expected for both of them.
Some Java Examples from the Web
http://home.cogeco.ca/~ve3ll/jatutor5.htm
http://java.freehep.org/lib/freehep/doc/root/index.html
http://www.codeguru.com/java/tij/tij0080.shtml
Answer: An interface (or an abstract class) is a contract you pass with the compiler. This contract says :
-- Well, compiler, make sure that all the classes that will implement this will provide at least everything that is defined in this interface !
With this insurance, you can then write methods that manipulate objects of any class implementing this interface :
<code> void myGenericMethod( IAnInterface genericObject )
</code>
myGenericMethod method can use any member of the interface IAnInterface. It will never throw a runtime error (any missing member will have been caught by the compiler).
Utility : to give some common behavior to different objects. You may want for example to be able to call a method named GetID on any of your objects, being it a BankAccount, a ComputerCluster or an AirplaneTrip.
You will find a lot of useful interface usages in most design patterns. MSDN provides some hints about when you should use an interface here : http://msdn.microsoft.com/en-us/library/27db6csx.aspx
Answer: As tvanfosson mentioned, there very useful for mocking, also if you writing a library that depends on outside configuration you can make an IFooProvider and have the calling program implement it.
Answer: I assume you mean "interface" in the programming language sense rather than in the other senses, e.g. "User Interface".
An interface in languages like Java or C# serves two purposes. The first is to provide a contract for a type to implement; a suite of method names and signatures that the type provides to other types that use it. The second is to provide polymorphism upon that interface for the type. For example, if I have a type that implements the IFoo interface, I can pass an instance of that type to another class where the other class needs only know about the IFoo interface rather than every detail of my class that implements IFoo.
Answer: Interfaces are useful when you want to allow interoperability between two classes that do not share a common class hierarchy.
A good example of this is java.lang.CharSequence. Lots of other things can be abstractly treated as strings, but it wouldn't be correct to subclass String to do so. In fact String is final so it couldn't be done anyway.
Some time around JDK 1.4 (I beleive?) the CharSequence interface was introduced. Now String, StringBuffer, CharBuffer and lots of other existing classes in the JDK implement it. With that, new methods could be added to other APIs which accept CharSequence, allowing them to abstractly handle all of these in a unified way.
You can also implement this interface yourself and use it the same way. It's far more flexible to implement a common interface than try and force things to extend from a specific base class (or sometimes it's impossible).
Answer: I prefer to regard an interface as a description of a role to be fulfilled by each instance of an implementing class, independent of any implementation inheritance hierarchy.
By way of analogy, you can describe a "screen pass" football play in terms of how certain positions on the team interact. That description, in terms of position (or role or interface) is independent of which player happens to be playing the position at a given time. It's also independent of whether the team happens to have some talented players who can play more than one position.
The advantage of interface-oriented thinking is that it puts the focus on the role that an object fulfills in a given interaction with other objects, without concern for any other roles the object may play in other kinds of interactions. It also allows testing to focus on scenarios that are relevant to a role (and to mock or fake roles in a test scenario).

Interesting Applications of Interfaces


Difference between one violin and an ensemble of violins

Question: Can someone please explain to me the difference between the sound of one violin and the sound of an ensemble of violins? Take for example an ensemble of only violins playing a Concert C. Why is it that they not only sound louder, but slightly more like a choir rather than just one violin playing a Concert C. The reason for my question is that I am trying to synthesize the sound of a violin ensemble but it does not sound like many violins, rather than like an electric pad. It would be helpful if you had any knowledge you would be willing to share regarding different timbres in the same instrument.
My theory from what I know about music (I am a clarinet player myself): Each violin has a slightly different timbre because no violin is exactly identical, therefore causing an ensemble of violins to sound like more than one violin.
Here is the sound I'm going for (skip to the violins), and here is the sound that synthesizer software makes. You can quickly tell there is an important difference in the sound, I just need help pinpointing what exactly it is.
Thank you very much!
Comment: As for getting that "choir"-like sound from a synth, this is what chorus pedals were invented to do.  It (essentially) creates multiple copies of the input sound with slight delays added to get the different copies of the sound out of phase with each other.
Answer: There are at least two effects at work. They're related and connected, yet I'd keep them apart:
Transient smearing
Bowed strings have naturally a pretty bright, edgy sound – in synthesizer terminology, it's actually similar (albeit more complex) to a sawtooth wave. These hard edges in the signal sound kind of raspy. (Particularly pronounced when beginning notes with a hard attack at the frog.)
However, they only happen at discrete points in time. If multiple violins play together, then the transients will never be really in sync, even if all violins are playing exactly in tune. The result of this is a waveform that has the same spectral composition, yet sounds much smoother than a single violin, because the transients don't add up and are "lost in the crowd".
Note that this effect doesn't require there to actually be multiple violins at all: it can also be achieved if you only record a single violin with a close mic multiple times, and layer the recordings (doing that gives a result quite similar to 70's "string synths": thick and smooth, yet somewhat unnatural and not really like a true string section).
Spatial widening
If you hear a single violin, your ears can pretty well focus on it (the sharp transients help with this, but they aren't required). Your ear zoom in, if you will. This can give the kind of intimate closeness that's needed for a folksy fiddle tune, but it also brutally highlights any playing details that aren't so desirable.
If multiple violins play physically together, they will necessarily sound all a bit different: different instruments have different timbre, the players will be a few cents off in pitch, and they can't sit all on the same chair. Hence there is no single point in space to focus on: you get a wide ensemble effect. Reverb also factors into this.
I have in the past tried to also emulate this effect with single instruments. It's quite tricky; you can get an approximation when actually setting up mics in a large room as if recording an orchestra, but then skip from chair to chair for each individual voice. Ideally also switch between a couple of different instruments, but this is actually not that crucial.
http://dime-chime.bandcamp.com/track/remember-the-sun
You definitely need a bit of stereo spread to pull this off convincingly. Which is what's most lacking in the recording you linked to (that actually sounds a lot like good old mellotron strings).
Answer: Your hypothesis that the violins don't sound exactly alike because they are not perfectly identical is indeed part of the reason why a violin section has a chorus effect, rather than sound like a louder violin.
Here is the list of things that would cause a section of violins to have the chorus effect compared to an individual violinist:

No two violins are identical and have slightly different acoustic signatures (mainly in the overtones)
Players are ever so slightly out of tune with one another.  Hopefully this is minimized, but there will always be some slight pitch discrepancies.
Similarly to the previous reason, players won't always attack at the exact same time.  This is sometimes desired, if you do want a fuzzy attack.
Most violin work uses vibrato, unless specified otherwise.  More so than any of the above reasons, the differing vibrato speeds and intensities account for the difference between the sound of a single violin and a whole section of violins.
Comment: And the phase mismatch, as ttw pointed out.  BTW, not only are the violinists out of phase as they produce the sound (at the string), but they all are different distances from the listener!
Answer: Each violin in a section will be out-of-phase with the others. The peaks and troughs of the various sound waves will not occur at the same time. Thus N violins sound about Sqrt(N) times louder than one violin. Were the violins in phase, the sound would be N times louder.
The practical effect is that one needs a section to sound like a section. The string sections of an orchestra do not sound like a loud string quartette. For making electronic sounds, just being louder does not a section make.
There may also be differences in tuning that enhance this effect.
Comment: You are describing the increase in volume but not the other aspects of the question.  It's not just volume that the OP is asking about.  Is he/she wrong about the "other" effects?  Is an increased volume the only effect?
Comment: My point (though not fully explained) is that one gets less volume because of the phase difference between instruments in addition to the slight difference in tuning It's a different tone quality. I'm not sure my Sqrt(N) is correct on re-consideration (I guess I should look it up). It may be that pure in-phase tones would give an N^2 loudness rather than N. The ratio is correct but the formula may be wrong.


Como fazer download do conteudo blob no php

Question: Tenho arquivos xml armazenados em um campo blob de uma tabela mysql, gostaria de saber como faço para baixar esses arquivos no disco local do usuário de forma automatica utilizando o php.
Crie uma função porem baixa no servidor e não no disco local.
function baixarArquivos($res) {
    while ($arq = mysqli_fetch_array($res)) {
        $nomearquivo = $arq['CHAVEXML'];
        $arquivoxml  = $arq['XML'];

        $path = 'c:\Temp\\xml\\'.$nomearquivo.'xml';
        file_put_contents($path, $arquivoxml);

    }
}

Answer: Você não pode fazer isso no computador do usuário.
O que tem que fazer é fornecer o download do arquivo.
Exemplo:
<?php
    $path = 'c:\Temp\\xml\\'.$nomearquivo.'xml';
    $nomearquivo = 'seu_arquivo.xml';
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename="'.$novoNome.'"');
    header('Content-Type: application/octet-stream');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($path));
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Expires: 0');
    // Envia o arquivo para o cliente
    readfile($path);

Comment: Entendi amigo, eu preciso na verdade baixar tudo de uma vez, deixar bem simples pro usuário final. Um botão que o usuário aperta e o sistema faz o resto. Eu tenho isso no delphi, precisava ter o mesmo em php ou em alguma outra linguagem que rode com apache no linux.
Comment: while not dtmConexao.fdqXmlPdv.eof  do
begin       dtmConexao.fdqXmlPdvXML.SaveToFile('c:\teste\xml\'+dtmConexao.fdqXmlPdvCHAVEXML.AsString+'.xml');
      dtmConexao.fdqXmlPdv.Next;
  end;
Comment: PHP é executado do lado do servidor. Você não tem acesso a máquina cliente. Seu site pode criar um arquivo zip com vários arquivos e disponibilizar como download. Mas sempre o usuário do seu site vai precisar fazer o download.


MySQL select count

Question: I am trying to count the number of companies that have at least one product from the following query
SELECT count(*)
FROM company c
JOIN product p on c.id = product.company_id
WHERE p.is_deleted = 0
AND c.is_customer = 1
AND c.company_type_id = 5
GROUP by c.id

So, this shows me a list of all companies, and the count of products for each company.
What I am trying to achieve is a count of companies from the above result.
This can be achieved as follows:
SELECT count(*)
FROM (
    SELECT count(*)
    FROM company c
    JOIN product p on c.id = product.company_id
    WHERE p.is_deleted = 0
    AND c.is_customer = 1
    and c.company_type_id = 5
    GROUP by c.id) AS t1

So, this gives me the correct result, but I am just wondering if there is a more efficient way of doing things.
Comment: It seems that you have done a pretty good job here. i see no room for improvement unless you really suffer performance issues
Comment: Surely the above query will always return 1?! You have a `COUNT(*)` which returns a single field, then you `SELECT COUNT(*)` again for a single field...Am I missing something?
Comment: @another: the inner count(*) has a `group by` - it returns one count per company
Comment: Need to take more time in reading things! Missed the `GROUP BY` there.
Answer: I believe you can simplify it to this:
SELECT count(distinct c.id)
FROM company c
JOIN product p on c.id = product.company_id
WHERE p.is_deleted = 0
AND c.is_customer = 1
AND c.company_type_id = 5

Comment: Are you not just counting the distinct companies here? Not the distinct products per company?
Comment: @another I think that's what the question is asking for - number of companies with at least one product.
Comment: @anothershrubery: the query will count how many unique company ids are in the result, and the result is filtered to only the companies that have at least one product. very good job @Blorgbeard - i stand corrected
Comment: Yeah, I apologise I read the requirements wrong. Yes Blorgbeard would be correct.

MySQL select count


How to expect an asynchronously thrown exception in Jasmine / Angular2 / Typescript?

Question: Given an Angular2/Typescript method that returns nothing and implements a .subscribe() handler which might throw, such as this:
onSubmit() { // returns nothing
  this.service.someCall(this.someData).subscribe(
    data => {
      return Promise.reject('This is an asynchronously thrown error.');
    },
    err => {},
  );
}

(For the moment, let's assume that there's a good reason for this .subscribe() handler to (probably conditionally) reject without other testable side-effects, thus resulting only in an error message bubbling up to the top of the application.)
How would one go about testing that this method resulted in a rejected Promise?
I found some people with the same question, but no elegant answers:
How to deal with thrown errors in async code with Jasmine?
https://github.com/jasmine/jasmine/issues/529
https://gist.github.com/badsyntax/7769526
Comment: It's hard to know exactly how to make a good answer here. It may be a case were the difficulty in writing good tests indicates a refactor of the code is in order. For example, why is an observable throwing with a rejected promise rather than just throwing an error which you would catch in `err=>{}`. And what should `onSubmit` do in this case. The answer to that last question is what you should test. And who is returning the Promise, the code in the call back or the observable. Why isn't this handled anywhere in onSubmit?
Answer: I solved this problem by stubbing the console.error() method (in this case, I am using Sinon):
it('should throw exception from component on submit', (done) => {
  // Jasmine isn't capable of capturing an exception thrown from an *asynchronous* operation.
  // However, that error eventually finds its way to console.error(), so we can stub
  // that method and wait for it to be called.
  sandbox.stub(console, 'error').callsFake((...err) => {
    expect(err[1]).toEqual('This is an asynchronously thrown error.');
    done();
  });
  component.onSubmit();
});

Are there any other/better ways to go about this?
Comment: You need to be careful that you aren't testing your testing framework. When I run this, I get a console error from mocha about an unhandled promise, which is not what I want to test. If `onSubmit` should log an error, there should be code in the function to do that.


Existe algum equivalente de "$(document).ready()" com Javascript puro?

Question: No jQuery, precisamos utilizar $(document).ready() para saber se o documento foi carregado e, então, com segurança executarmos o nosso script jQuery.
Segundo a documentação do jQuery

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you.

Tradução:

A página não pode ser manipulada com segurança até que o documento está "pronto". jQuery detecta esse estado de prontidão para você.

Agora, no caso do Javascript puro, sem jQuery ou nenhum outro framework, existe alguma maneira de detectar que o documento foi carregado, para ter a mesma garantia que temos com $(document).ready()?
Comment: Existe um site específico sobre esse assunto: [YouMightNotNeedJQuery](http://youmightnotneedjquery.com/#ready).
Comment: Veja esse outro tópico [pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it](http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the).
Comment: Gostei @renan :D
Answer: O que o jQuery faz é lêr a propriedade document.readyState quando a página carrega, e caso ainda não esteja carregada escuta um dos eventos load ou DOMContentLoad. O primeiro evento a ser chamado dispara o ready.
Na prática simplificando seria assim (jsFiddle):
function ready() {
    // quando esta função correr o DOM está acessível
}

function completed() {
    document.removeEventListener("DOMContentLoaded", completed);
    window.removeEventListener("load", completed);
    ready();
}

if (document.readyState === "complete" ||
    (document.readyState !== "loading" && !document.documentElement.doScroll)) {
    ready(); // está pronto!
} else { // ainda não está pronto...
    document.addEventListener("DOMContentLoaded", completed);
    window.addEventListener("load", completed);
}

O IE 8 tinha um bug com o scroll e por isso essa linha que refere o Scroll. Há um artigo muito bom sobre isso (link), mas como o IE8 já não é suportado pode remover-se.
A versão do MooTools é parecida, um pouco mais complexa e por isso mais completa, e usa o mecanismo interno de eventos do MooTools. Toma ainda em conta browsers mais antigos que não têm readystatechange. Mas isso já não interessa nos tempos de hoje.

Para browsers modernos pode fazer-se assim (link):
var domReady = function(ready) {
    if (document.readyState != 'loading') return ready();
    document.addEventListener('DOMContentLoaded', ready);
    function _ready() {
        document.removeEventListener('DOMContentLoaded', ready);
        ready();
    }
}

Para browsers antigos poder-se-ia fazer assim (link), mantendo a coisa simples:
var domReady = function(ready) {
    var attacher = document.addEventListener ? {
        add: 'addEventListener',
        remove: 'removeEventListener'
    } : {
        add: 'attachEvent',
        remove: 'detachEvent'
    };

    function completed() {
        document[attacher.remove]("DOMContentLoaded", completed);
        window[attacher.remove]("load", completed);
        ready();
    }

    if (document.readyState === "complete" ||
        (document.readyState !== "loading" && !document.documentElement.doScroll)) {
        ready(); // está pronto!
    } else { // ainda não está pronto...
        document[attacher.add]("DOMContentLoaded", completed);
        window[attacher.add]("load", completed);
    }
}

Comment: Algumas versões abaixo do IE 9 também não funcionarão com `addEventListener`, por isso dá para substituir o método por `attachEvent` caso existir (uma nota caso alguém se preocupar com o suporte dos navegadores).
Comment: @KlaiderKlai verdade, fica aqui ([link](https://github.com/jquery/jquery/blob/1.12.4/src/core/ready.js#L67-L76)) a versão do jQuery para browsers antigos, tendo em conta esse aspeto. Outra possibilidade seria usar `window.onload = function(){ready();}` para o meu exemplo em cima, mas isso também para browsers muito antigos, por isso não junto à resposta, fica aqui.
Comment: @KlaiderKlai tem razão, um polyfill cairia bem
Comment: @GuilhermeNascimento juntei uma versão para browsers antigos.
Comment: Agora que percebi, document.readyState só tem 3 valores possíveis, e eu usando regex a toa (`/^(interactive|complete)$/`). Vivendo e aprendendo :D
Comment: @GuilhermeNascimento força.
Comment: @Sergio só pra constar, apesar de hoje não fazer mais diferenças nos navegadores modernos, o `doScroll` é uma função e não uma propriedade, eu queria atualizar seu código, mas a implementação do mesmo requer try/catch, então prefiro não modificar sua lógica, mas se puder ajustar fica melhor. Obrigado.
Comment: @GuilhermeNascimento exato. Daí o código ter `!` para converter num booleano se esse método está presente no `documentElement`, sem o invocar.
Comment: Acho que entendi, Então a intenção é que no IE só execute via load e se suportar via DOMContentLoaded?
Comment: @GuilhermeNascimento no IE8 (o que implica não ter `.doScroll`) tudo o que seja diferente de `loading` é uma página caregada.
Comment: @Sergio entendo, obrigado.
Answer: Pra ficar semelhante ao funcionamento do jQuery temos que adicionar uma checagem extra acaso.

Note que interactive não funciona bem no IE então usei doScroll
Note que document.readyState não é suportado por alguns navegadores, então mantive o onload como um "fallback"
Pra usar document.readyState é necessário setInterval ou setTimeout
A variavel isReady serve pra evitar rodar um script todo acaso já esteja carregado (também evitando problemas em navegadores sem suporte ao document.readyState)
O (function () { serve pra isolar a variavel isReady ficando dentro do escopo
O evento DOMContentLoaded é acionado quando o documento inicial HTML foi completamente carregado e analisado, sem aguardar por folhas de estilo, imagens, e subframes para encerrar o carregamento, mas não é suportado por alguns navegadores mais antigos, como IE8
No script abaixo o DOMContentLoaded corre paralelamente com as demais funções ou seja quem terminar primeiro irá disparar o callback.
O evento load no window é uma garantia acaso tudo falhar ou for um navegador sem suporte algum (é bem raro)

O código ficaria assim:

(function (w, d) {
    var isReady = false;

    w.domReady = function(callback)
    {
        /*
        Se a página já estiver carregada e já tiver rodado alguma vez
        o window.domReay então esta if evita fazer registro de eventos
        ou testes desnecessários, assim otimizando o tempo de resposta
        */
        if (isReady) {
             callback();
             return;
        }

        var done = false;

        var doc = d.documentElement;

        var attacher = d.addEventListener ? {
            add: 'addEventListener',
            remove: 'removeEventListener'
        } : {
            add: 'attachEvent',
            remove: 'detachEvent'
        };

        function completed() {

            /*
            A variável done impede que o script seja executado duas vezes
            */
            if (done) { return; }

            done = true;
            isReady = true;

            d[attacher.remove]("DOMContentLoaded", completed);
            w[attacher.remove]("load", completed);
            callback();
        };

        if (d.readyState === "complete") {
            /*Se o navegador suportar readyState e a página já estiver carregada*/
            completed();
        } else if (doc.doScroll) {

            /*interactive para IE8 não funciona bem, doScroll é um fallback para IE8*/

            (function doScrollTest() {
                try {
                    doc.doScroll('left');
                    completed();
                } catch(e) {
                    setTimeout(doScrollTest, 50);
                }
            })();
        } else if (d.readyState) {

            /*Checa se é interactive ou completed*/

            (function readyStateTest() {
                if (d.readyState !== "loading") {
                    completed();
                } else {
                    setTimeout(readyStateTest, 50);
                }
            })();
        }

        d[attacher.add]("DOMContentLoaded", completed);
        w[attacher.add]("load", completed);
    };
})(window, document);

//Usando:
domReady(function() {
    console.log("ready");
});

domReady(function() {
    console.log("olá mundo");
});

domReady(function() {
    domReady(function() {
        console.log("domReady dentro de domReady");
    });
});

window.onload = function () {
    domReady(function() {
       console.log("domReady dentro de Onload");
    });
};
Comment: Boa, `+1`, para browsers antigos fica aqui uma boa versão também.
Answer: Você também pode usar as tags de script no fim do body, como mostrado no código abaixo. Com o script dentro do body o código só será executado quando o body for carregado.
<!DOCTYPE html>

    <title></title>

Comment: Acho que `window.onload` equivale ao `$(window).load()`, não ao `ready`.
Comment: Tirando a parte "window.onload, como mostrada acima é o equivalente ao $(document).ready() do jQuery" que eu discordo, o resto da dica esta excelente André, sim colocar o script antes do `` e se colocar tudo dentro de um unico .js ainda poderá usar async o que ajuda a acelerar a renderização. Parabéns, só remove o trecho que eu citei.


Busca por relacionamento Laravel whereHas?

Question: Tenho uma Query no meu Criteria que retorna os id pertencentes ao relacionamento entre models
if ($this->request->has('notin_portal'))
{
    $portal = $this->request->get('notin_portal');
    if ($this->request->get('notin_portal'))
    {
         $model = $model->whereHas('portals', function($query) use ($portal)
         {
              $query->where('id', $portal);
         });
         return $model;
    }
}

Meu problema é que eu preciso retornar os ids que NÃO pertencem ao relacionamento portals nas models. Existe algo do tipo?
Answer: Sim é só colocar <> no where
Exemplo
$query->where('id', '<>', $portal);

Também existe a maneira de comparar com whereIn / whereNotIn
Exemplos:
->whereIn('id', [1, 2, 3]);

->whereNotIn('id', [1, 2, 3]);

no seu caso também funcionaria whereNotIn
Com whereRaw também pode satisfazer essa pesquisa:
Exemplo
->whereRaw("id <> {$portal}");

Na versão mais atual pode utilizar whereDoesntHave
Exemplo:
$model = $model->whereDoesntHave('portals', function ($query) use ($portal)
{
    $query->where('id', $portal);
});


Problemas com permissão 777 e PHP

Question: Eu estou com um problema envolvendo PHP e permissão 777. No meu servidor, existe uma pasta de uploads com permissão 777, e um hacker conseguiu subir um arquivo .php nessa pasta, que alterou tudo que estava no meu server. Eu gostaria de saber como se faz isso e como eu posso evitar essa vulnerabilidade.
Comment: Você precisa barrar o upload por extensão. A questão que você não pode permitir o upload de um arquivo com etensão .php, .py, etc. Pois esses arquivos são interpretado pelo servidor quando requisitados. A função sua que faz upload precisa ser tratada para não permitir que esses arquivos sejam upados.
Comment: obrigado, você me ajudou muito assim, acho que deve ser isso mesmo pois meu script está sem esse filtro.
Comment: Exemplo, se você precisa upar fotos, então coloque o filtro para arquivos que terminem com o nome (.jpeg, .png, .jpg, .bmp, etc), diferente disso o upload não pode ser feito.
Comment: Como  a invasao ja foi feito aconselho, trocar nome de usuario root do banco de dados, se tiver acesso ssh, trocar nome e senha do usuario.
Comment: você também trabalham com essa permissão ou você acha que é desnecessário?
Answer: Segue algumas dicas de segurança ao trabalhar com upload de arquivos no php:

Armazene os arquivos de upload fora do diretório raiz da sua aplicação web. Dessa forma os arquivos não poderão ser acessados diretamente pelo navegador.
Não armazene o arquivo de upload com o mesmo nome configurado no formulário de upload. Gere um nome randômico e faça o controle em banco de dados.
Verifique se o mime-type do arquivo corresponde ao tipo de arquivo que deseja receber como upload. Não confie somente na extensão do arquivo ou no header HTTP Content-type. Por exemplo, caso queira garantir que o arquivo de upload seja uma imagem do tipo gif:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, "image.gif");
finfo_close($finfo);

if($mime_type == 'image/gif') {
    // arquivo é gif
}

Problemas com permissão 777 e PHP


SQL Maintenance Plan - Send email on fail

Question: I have a maintenance plan on my SQL 2008 box -
I would like it to send an email address when (or if) it fails.
I've set up database mail, and can send a test email..
How can I do this?
Answer:
Configure SQL Server Agent to use database mail
Create operator(s) mail, pager, hours, etc.
Configure maintenance plan to email appropriate operator(s) based on exit condition.

http://msdn.microsoft.com/en-us/library/ms186358.aspx
http://technet.microsoft.com/en-us/library/ms175962.aspx
Comment: You don't.  Edit the SQL Agent job and configure the job to send you an email on job failure.
Comment: If you want to be notified per task (when a task fails, rather than when a plan fails), double click on a green arrow to open its properties and change the Value to Failure. You can create multiple arrows ("precedence constraints"?) from a single task, so you can have one which performs the next task upon Completion, and another which sends an email on Failure. If the task fails, the condition for both arrows will be met and both the next task and the email task will be run.
Comment: I've done this... but i can't seem to do number 3...?
Where do i find the exit conditions on my tasks? i only have a green arrow coming out of the event box on the designer...
Answer: Add an Execute SQL task to your maintenance plan that makes the call to sp_send_dbmail and connect the failure routes of any of your other tasks to this task.
Answer: We added am "Execute T-SQL Statement Task", which calls a stored procedure, with the name of the Maintenance Plan as a paramater:
EXEC server.schema.SP_SENDALERT 'plan.subplan';

In that stored procedure, we query back to the SYSJOBS and SYSJOBHISTORY for the plan to obtain the message for the last 'failure', which we then send to 'IT Support' as part of a send_dbmail (which is driven by a procedure that loop through unsent messages in the MESSAGING table), something along the lines of this:
CREATE PROCEDURE SP_SENDALERT (@plan VARCHAR(MAX))
AS
BEGIN

    DECLARE @error VARCHAR(MAX)

    SELECT TOP 1 @error = SJH.[MESSAGE]FROM MSDB.DBO.SYSJOBS SJ
    LEFT JOIN MSDB.DBO.SYSJOBHISTORY SJH ON SJ.JOB_ID = SJH.JOB_ID
    WHERE SJ.ENABLED = 1
    AND SJH.RUN_STATUS = 0
    AND SJ.[NAME] = @plan
    ORDER BY SJH.RUN_DATE, RUN_TIME DESC

    INSERT INTO database.schema.MESSAGING
    (MESSAGE_TYPE, MESSAGE_SUBJECT, MESSAGE_BODY, RECIPIENTS, RECORD_ADDED)
    VALUES  (1, 'ERROR: ' + @plan, @error, 'email@example.com', GETDATE())

END


How to direct alternating measures of 6/8 and 5/8 time signatures?

Question: This is a allegro piece eighth note = 204 and alternates measures from 6/8 and 5/8. My question is how to direct this? The 6/8 would be in two. Would the 5/8 also be in two with the next 6/8 measure coming earlier?
Comment: I've never conducted but if I saw alternating 6/8 and 5/8 I'd read it as compound time in two with a dropped eighth note every other measure.
Answer: Study the 5/8 measure and determine the subdivision.  Commonly, it'll be 2+3/8 or 3+2/8.  For conducting, you'll treat 5/8 like a 6/8 pattern, but dropping the appropriate 8th notes to match the subdivision.