Is it worth using Redis over just storing data in objects that are only needed during runtime?

Question: I'm creating a party system for a thing I'm working on,
using sockets the person can emit an accept, decline, invite, kick, changeLeader events for the party.
I needed some way to keep track of the users so I created an object that would contain all relevant information, e.g.
let partyManager = {};

partyManager[partyUUID] = {
    creator: username,
    creatorSID: g04wn0gn9w490g, // socket id
    members: [],
    invited: []
}

but I thought well maybe its hard on the program to store this information in the program itself and maybe a database is more suitable for this, but I wanted something fast and to be honest, just really wanted to try out Redis..
So I started working on my store / schema for redis to store the information I came up with something like
hmset party:uuid:owner   "creator" "username" "creatorSID" "socket id"
sadd  party:uuid:members "user1" "user2"
sadd  party:uuid:invited "user3"

Which gives me a hash containing the party owners information and 2 sets pertaining to the current members, and the users with pending invites (so people cant just join a party they haven't been invited to)
But then I remembered Redis stores in memory anyways, which storing in an object would store in memory as well, would it not?
I'm mainly wondering if using Redis to accomplish this is more effective/better than just storing the party in an object.
Answer: According to me, the main interests of using Redis in your case would be:

to make data persistent, if Redis persistence is activated
to allow sharing the data between several instances of the application server
to make this application server stateless (which is better for failover and scaling).

If you don't bother with these considerations, Redis has a low interest in the use case you described.


On hover  next div fadein and mouseleave on div this div fade out

Question: On hover of an  the next div fadein and mouseleave on div this div fade out but when div fade in and drag my mouse on dive it will go fade out

jQuery('.share_link').hover(function(event) {
  event.stopPropagation();
  jQuery(this).next('.quick-view-share').stop().fadeIn();
}, function(event) {
  event.stopPropagation();
  jQuery(this).next('.quick-view-share').not().fadeOut();
});

    Face Book
   Twittter
   G Plus

Answer: The issue is because the hover logic is attached to the a element. Therefore as soon as you leave the a to select something from the displayed div, it immediately disappears.
To solve this you could amend your HTML to hook the events to a containing element. Alternatively you can utilise CSS to make the hover logic work for both elements by using CSS's adjacent sibling operator, +:

a.share_link + .quick-view-share {
  position: absolute;
  opacity: 0;
  transition: opacity 0.4s;
}

a.share_link:hover + .quick-view-share,
a.share_link + .quick-view-share:hover {
  opacity: 1;
}

Share

    Face Book
   Twittter
   G Plus


Posicionamento de div com jquery

Question: Bom, com a ajuda de algumas pessoas aqui do stack eu estou modificando meu sistema de tooltip, ele esta quase pronto, porem estou tendo um problema.
Quando uso um texto muito grande na classe  'masterTooltip-left' o tooltip bug, ele não alinha direito e por isso não e exibido. alguém sabe como resolver isso?

$(document).ready(function() {

  $('.masterTooltip-right').hover(function() {

    var title = $(this).attr('title');
    $(this).data('tipText', title).removeAttr('title');
    $('

').html(title).appendTo('body').fadeIn('fast');
  }, function() {
    $(this).attr('title', $(this).data('tipText'));
    $('.tooltip-right').hide();
  }).mousemove(function(e) {

    // Posição
    var mousex = e.pageX + 25;
    var mousey = e.pageY + -25;
    $('.tooltip-right').css({
      top: mousey,
      left: mousex
    });
  });

  $('.masterTooltip-left').hover(function() {

    var title = $(this).attr('title');
    $(this).data('tipText', title).removeAttr('title');
    $('

').html(title).appendTo('body').fadeIn('fast');
  }, function() {
    $(this).attr('title', $(this).data('tipText'));
    $('.tooltip-left').hide();
  }).mousemove(function(e) {

    // Posição
    var mousex = e.pageX - 150;
    var mousey = e.pageY + -25;
    $('.tooltip-left').css({
      top: mousey,
      left: mousex
    });
  });
});
.tooltip-right, .tooltip-left {
    display: none;
    position: absolute;
    border: 1px solid #616161;
    background-color: #323232;
    border-radius: 4px;
    padding: 10px;
    color: #FFFFFF;
}
.tooltip-right::after {
    position: absolute;
    content: '';
    left: -20px;
    top: 3px;
    border: 10px solid transparent;
    border-right-color: #323232;
}
.tooltip-left:after {
    position: absolute;
    content: '';
    right: -10px;
    top: 3px;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #323232;
}

.right {
  float: right;
}

.w100 {
  width: 100px;
  background-color: #0091FF;
}

MOUSE

MOUSE

BUG

Comment: o bug é que o tooltip fica "sumindo e aparecendo"?

se for, a forma mais simples de resolver isso é em vez de vc posicionar o tooltip na tela, colocar o tooltip como filho do elemento que disparou.
assim o "mouseout" não vai acontecer se o mouse entrar dentro do tooltip.
Comment: ele fica sumindo porque não fica posicionado certo. O 'tooltip-right' funciona, já o 'tooltip-left' não, pois quando o texto e grande ele não fica a 10px do cursor. entendeu? a estrutura eu não quero mexer, pois assim ela e bem simples
Comment: então é isso mesmo que eu disse.. na verdade ele some pq o cursor entra dentro do tooltip e isso faz ele sair do elemento que dispara, por isso ele fecha.
Comment: hum, teria como vc alterar o código que eu postei com a sua solução?
Answer: dá para aplicar um css transform de modo a compensar a largura variável.
html:

MOUSE

MOUSE

BUG

css:
.tooltip-left {
  transform: translateX(-100%);
}

.div1 {
  float: left;
  width: 50%;
}

.div2 {
  float: left;
  width: 50%;
  text-align: right;
}

.right {
  margin-left: auto;
  margin-right: 0;
}

.w100 {
  cursor: pointer;
  width: 100px;
  background-color: #0091FF;
  margin-bottom: 25px;
}

javascript:
$(document).ready(function() {

  var w = $('body').width();
  var h = $('body').height();

  $('.masterTooltip').hover(function(e) {
    var mouse = {x: e.clientX, y: e.clientY};
    var t = e.target;
    var title = $(t).attr('data-label');
    if (mouse.x > w / 2) {
      $('

').html(title).appendTo('body').fadeIn('fast');
    }
    else {
      $('

').html(title).appendTo('body').fadeIn('fast');
    }
  },
  function() {
    $('.tooltip-left').hide();
    $('.tooltip-right').hide();
  }).mousemove(function(e) {
    var mouse = {x: e.pageX, y: e.pageY};
    $('.tooltip-left').css({
      top: mouse.y - 25,
      left: mouse.x - 25,
    });
    $('.tooltip-right').css({
      top: mouse.y - 25,
      left: mouse.x + 25,
    });
  });
});

Answer: Fiz um alteração no javascript tem que dar uma arrematada nos cálculos pra ficar perfeito, mas basicamente to calculando com base no tamanho da palavra e se ela está em maiúscula ou minuscula

$(document).ready(function() {

  $('.masterTooltip-right').hover(function() {

    var title = $(this).attr('title');
    $(this).data('tipText', title).removeAttr('title');
    $('

').html(title).appendTo('body').fadeIn('fast');
  }, function() {
    $(this).attr('title', $(this).data('tipText'));
    $('.tooltip-right').hide();
  }).mousemove(function(e) {

    $('.tooltip-right').each(function() {
      var mousex = 0;
      var mousey = e.pageY + -25;
      if ($(this).text()[0] == $(this).text()[0].toUpperCase()) {
        mousex = (e.pageX -10) + ($(this).text().length * 10)

      } else {
        mousex = (e.pageX) + ($(this).text().length * 7)
      }
      $(this).css({
        top: mousey,
        left: mousex
      })
    });
  });

  $('.masterTooltip-left').hover(function() {

    var title = $(this).attr('title');
    $(this).data('tipText', title).removeAttr('title');
    $('

').html(title).appendTo('body').fadeIn('fast');
  }, function() {
    $(this).attr('title', $(this).data('tipText'));
    $('.tooltip-left').hide();
  }).mousemove(function(e) {

    // Posição
      $('.tooltip-left').each(function() {
      var mousex = 0;
      var mousey = e.pageY + -25;
      if ($(this).text()[0] == $(this).text()[0].toUpperCase()) {
        mousex = (e.pageX - 40) - ($(this).text().length * 10)

      } else {
        mousex = (e.pageX - 40) - ($(this).text().length * 7)
      }
      $(this).css({
        top: mousey,
        left: mousex
      })
    });
  });
});
.tooltip-right,
.tooltip-left {
  display: none;
  position: absolute;
  border: 1px solid #616161;
  background-color: #323232;
  border-radius: 4px;
  padding: 10px;
  color: #FFFFFF;
}
.tooltip-right::after {
  position: absolute;
  content: '';
  left: -20px;
  top: 3px;
  border: 10px solid transparent;
  border-right-color: #323232;
}
.tooltip-left:after {
  position: absolute;
  content: '';
  right: -10px;
  top: 3px;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-left: 10px solid #323232;
}
.right {
  float: right;
}
.w100 {
  width: 100px;
  background-color: #0091FF;
}

MOUSE

MOUSE

MOUSE

BUG

Comment: Ok, deu certinho. Estou montando um projeto para design de pequenos sistemas, coloquei seu nome nas contribuições. Vlw https://github.com/hugovborges/HS-Design

Posicionamento de div com jquery


Is this problem calculable only due to the parameter choices?

Question: I am looking at a problem form Hogg, Tannis & Zimmerman (Ed. 10), and I am curious if the given problem is calculable (for an upper-level undergrad math/stats course) because of the choice of the parameters.
To respect the authors' copyright, I won't repeat the problem as written, but I will represent the key query:  $X_1$ and $X_2$ are i.i.d. with a gamma distribution with parameters shape $k=1$ and scale $\theta=2$ (using the parameterization shown on the Wikipedia page).  Let $Y_1=\min(X_1,X_2)$ and $Y_2=\max(X_1,X_2)$ and $Z=\alpha Y_1 + \beta Y_2$.  Compute the expected value of $Z$.
My strategy would be to do the following:

Find the cdf $G_2(y)=P(Y_2 \le y) = F(y)^2$
Find the pdf $g_2(y) = G_2^\prime(y)$ (using $f(y) = F^\prime(y)$ and the chain rule)
Find $E(Y_2) = \int_{S_{Y_2}} y g_2(y)\ dy$
Repeat for $E(Y_1)$ using $G_1(y) = (1-F(y))^2$
Use the linearity of the expectation operator to find $E(Z)$.

Because I hoped to solve a more general version of the problem, I left the parameters as $k$ and $\theta$ in the gamma function (instead of using the proposed values).  This appears to result in a problem that cannot be easily calculated in terms of these parameters (or the size of the random sample, which I also left as an unspecified value $n$).
However, when you plug these given parameters into the gamma function, you get an exponential function.  And, the resulting formula is easily calculated for a sample (at least for size $n=2$).
Again, my query is if a general solution is possible (in terms of the given parameters and closed-form solutions) for specific parameters...or perhaps I am missing something in my approach that would simplify the process.
Comment: Quoting a textbook problem constitutes fair use; it does not violate any (US) copyright law.
Answer: I won't demonstrate any more than you already know, but this approach might help confirm your suspicion that the parameter $k=1$ is special.  Along the way you might find some useful general shortcuts.

Let's begin far more generally: suppose only that $X_1$ and $X_2$ are independent with distribution functions $F_1$ and $F_2,$ respectively (which means for all real $x,$ $\Pr(X_i\le x) = F_i(x)$).  I will assume the expectations of the $X_i$ are known.
You can exploit $Y_1+Y_2 = X_1+X_2$ to express
$$E[Y_1] + E[Y_2] = E[X_1] + E[X_2]$$
and from this compute
$$\begin{aligned}
E[\alpha Y_1 + \beta Y_2] &= \alpha(E[Y_1] + E[Y_2]) + (\beta-\alpha)E[Y_2] \\&= \alpha(E[X_1]+E[X_2]) + (\beta-\alpha)E[Y_2].
\end{aligned}$$
This reduces the problem to finding $E[Y_2].$
The event $Y_2\le x$ is the event that both $X_i$ are less than or equal to $x,$ whence
$$F_{Y_2} = \Pr(Y_2\le x) = \Pr(X_1\le x)\Pr(X_2\le x) = F_1(x) F_2(x)$$
due to the independence of the $X_i.$
Consequently
$$\begin{aligned}
E[Y_2] &= \int_{-\infty}^0 F_{Y_2}(y)\mathrm{d}y + \int_0^\infty 1-F_{Y_2}(y)\mathrm{d}y\\
&= \int_{-\infty}^0 F_1(y)F_2(y)\,\mathrm{d}y + \int_0^\infty 1-F_1(y)F_2(y)\,\mathrm{d}y.
\end{aligned}$$
When at least one of the $X_i$ has nonnegative support (as in this question), the first integral is zero.  Thus, whatever the answer might be is tantamount to evaluating the second integral.  That's hard to do when the $F_i$ are incomplete Gamma functions--I don't know of any theory of integrals of products of those functions--but there is an easy special case: when they are exponentials (incomplete Gamma functions with parameter $1$).
Let's deal with that.  Let the scale factors be $\theta_i,$ so that $F_i(y) = 1 - \exp(y/\theta_i)$ for all $y\ge 0.$  Plugging into the foregoing expectation formula gives
$$\begin{aligned}
E[Y_2] &= \int_{0}^\infty 1 - (1 - e^{y/\theta_1})(1 - e^{y/\theta_2})\,\mathrm{d}y = \int_0^\infty e^{y/\theta_1} + e^{y/\theta_2} - e^{y/\theta_1 + y/\theta_2}\,\mathrm{d}y\\
&= \theta_1 + \theta_2 - \frac{\theta_1\theta_2}{\theta_1+\theta_2}.
\end{aligned}$$
Since $E[X_i] = \theta_i,$ the answer is
$$E[\alpha Y_1 + \beta Y_2] = \beta(\theta_1+\theta_2) - (\beta-\alpha)\left(\frac{\theta_1\theta_2}{\theta_1+\theta_2}\right).$$

There are other special cases you might enjoy exploring: for positive integral shape parameters $k,$ repeated integration by parts ($k-1$ times) establishes that the incomplete Gamma functions $F_i$ are polynomials times an exponential.  This makes the integrand $1-F_1(y)F_2(y)$ a polynomial (usually of higher degree) times exponentials, which is elementary to integrate.  There will be many terms, though: when the shape parameters are $k_i,$ expect around $(1+k_1)(1+k_2)$ nonzero terms.
Comment: This approach with $Y_1+Y_2 = X_1+X_2$ is great (hadn't considered that nice trick)...but it does seem to limit a generalization of this problem to random samples of size $n=2$.  Thnx for confirming that this problem does have some very strong reliance on the parameter choice for the gamma distribution.
Comment: The (useful) generalization is that the expectation of the sum of all the order statistics equals the sum of the expectations.
Comment: My thought is that if the problem retains the r.v. $Z$ defined as the sum of the min and max, then the full ordering won't help there.
Answer: You are correct that $\mathsf{Gamma}(\mathrm{shape}=1,\mathrm{scale}=\theta)$ is exponential, specifically $\mathsf{Expm}(\mathrm{mean}=\theta)\equiv\mathsf{Exp}(\mathrm{rate}=1/\theta).$
Using the CDF method, you can show that if
$X_1, X_2$ are IID $\mathsf{Exp}(1/\theta),$ then
$Y_1=\min(X_1,X_1) \sim \mathsf{Exp}(2/\theta),$ so that
$E(Y_1) =\mu_1 =\theta/2.$
Similarly but with a little more difficulty,
you can find $E(Y_2) = E(\max(X_1,X_2)) = \mu_2$ (in terms of $\theta).$
Finally, $E(\alpha Y_1 + \beta Y_2) = \alpha\mu_1 + \beta\mu_2.$

Here is a brief simulation with $\theta = 6, \alpha=5, \beta=10$ with sufficiently
accurate results (2 or 3 significant digits) that you can check each part as you go along.
<code>set.seed(121)
th = 6;  alp = 5;  bet = 10
x1 = rexp(10^7, 1/6)
x2 = rexp(10^7, 1/6)
mean(x1);  mean(x2)
[1] 5.999339   # aprx E(X1) = 6
[1] 6.000077   # aprx E(X2) = 6

y1 = pmin(x1, x2)
y2 = pmax(x1, x2)
mean(y1);  mean(y2)
[1] 2.999401   # aprx E(Y1) = 3
[1] 9.000015   # aprx E(Y2) = 3 + 6 = 9

z = alp*y1 + bet*y2
mean(z)
[1] 104.9972   # aprx E(Z) = 15 + 90 = 105
</code>
Note: An intuitive answer to $E(Y_2)$ is that
that the min averages 3, then by the no-memory property of
exponential random variables, the max must be 6 greater on average, so $E(Y_2) = 3+6=9.$
Comment: Thanks for sharing this response.  I think you mean in the note that the max averages 3.  First, I'm uncertain how the no-memory applies here.  Also, it appears you've provided a general solution for $k=1$, but this doesn't address my initial query for a general solution w.r.t. the given parameters.  (This seems to confirm my impression that this problem is an artifact of a special set of parameters for the gamma function).
Comment: The min averages 3. Consider modeling the lifetime of a type of device. Each device is subject to potentially fatal events at a rate of $1/6$ per year or one every 6 years. Then a series system of two devices is hit a rate of $2/6=1/3$ per year or one every three years. So the avg of minimum is 3 yrs. By the no memory property the surviving device has an avg life of another 6 yrs so the max will avg 9 yrs. // Because you haven't shown much of a start on a solution I hoped my Ans would give you a start. //  I had NO plan to work the entire textbook problem for you. // Sorry if this not helpful.
Comment: No sure what is meant by "haven't shown much of a start on a solution" ...as the strategy in the original post does indeed produce the correct answer (for $k=1$ and $\theta=2$). Though, as noted, the query was about generalizing the problem (if possible).  Thnx for your response.


Reference request and prerequisites for understanding the Sphere Theorem and the Loop Theorem in 3-manifold theory.

Question: As part of my directed studies project, my advisor has suggested that I completely understand the proof of the Sphere Theorem and the Loop Theorem in 3-manifold theory and explain it to him. I have done an introductory and advanced course in general topology, and introductory courses in algebraic topology (homotopy theory, fundamental groups and simplicial homology theory). I've also spent the past month studying surgery on 3-manifolds through Knot Theory and the proof of the Lickorish Twist Theorem and the Lickorish Wallace Theorem from Dale Rolfsen's book Knots and Links.
My question is that what other prerequisites would I need to understand both of these theorems. Any other resources (lecture notes, video lectures etc.) that explain these two theorems in detail would also be appreciated. Rolfsen suggests John Stallings book and paper for these two theorems.
Comment: @MoisheKohanonstrike I wasn't aware of it. Chapter 4 is entirely dedicated to these two theorems. I'll definitely check it out.
Comment: This book is in the reference list in the Wikipedia links that you gave.
Comment: Any reason you are not reading Hempel's book?
Answer: Sounds like you have the prerequisites, though it might help to learn some more homology. Most of the older arguments rely on some piece-wise linear topology, but you can pick that up along the way (or think of things smoothly).
When I learned the Loop Theorem in grad school, I used a combination of Calegari's notes, Papakyriakopoulos' original paper, Hatcher's notes on 3-manifolds, and Stallings' paper and text. Eventually I found it in Hemple's text, but this was well after I learned the proofs. Have fun with it! I've always loved these theorems, even if it took a bit of digging to find all the ins and outs of their proofs.


How to add direction on tracking path for google maps

Question: I am showing the tracking on map with marker points and line connecting them.
The problem is that i want to show the direction of travel on the links;
so I am not getting how to show the direction on the line between the marker points.
Is there any way to accomplish this task.
Answer: Showing the direction on the polyline can be accomplished with arrows.
There are some predefined paths that the google maps api3 provides.
See this section of the documentation -
SYMBOLS ON POLYLINE, that can be used other than an arrow.
Have a look at this fiddle that uses an arrow to indicate the direction on the polyline.
DEMO with a sigle symbol
You can also set the repeat property for the symbol so that it repeats for regular intervals.
DEMO with repeating symbols
JavaScript-
var iconsetngs = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
var polylineoptns = {
    path: markers,
    strokeOpacity: 0.8,
    strokeWeight: 3,
    map: map,
    icons: [{
        icon: iconsetngs,
        offset: '100%'}]
};
polyline = new google.maps.Polyline(polylineoptns);

The interesting feature of this predefined symbol(the forward arrow specially) is that the arrow points towards the exact direction of which your co-ordinates are located. So, that obviously serves the purpose of denoting the direction in a Tracking System.
UPDATE: Not sure about the point you are trying to tell in the comments. The markers can be displayed the same way. Here is the code that adds markers with a loop and also set the polyline with arrows:
DEMO WITH MARKERS AND POLYLINE
Javascript:
var polylineoptns = {
        strokeOpacity: 0.8,
        strokeWeight: 3,
        map: map,
        icons: [{
            repeat: '70px', //CHANGE THIS VALUE TO CHANGE THE DISTANCE BETWEEN ARROWS
            icon: iconsetngs,
            offset: '100%'}]
    };
    polyline = new google.maps.Polyline(polylineoptns);
    var z = 0;
    var path = [];
    path[z] = polyline.getPath();
    for (var i = 0; i < markers.length; i++) //LOOP TO DISPLAY THE MARKERS
    {
        var pos = markers[i];
        var marker = new google.maps.Marker({
            position: pos,
            map: map
        });
        path[z].push(marker.getPosition()); //PUSH THE NEWLY CREATED MARKER'S POSITION TO THE PATH ARRAY
    }

Comment: That's a different question. Consider posting it as a new question.
Comment: How can i get the total distance travelled upto last point.not calculated by start and end point but by the path of travel????
Comment: JSFiddles updated 2016: [DEMO with a single symbol](https://jsfiddle.net/q6eqV/115/); [DEMO with repeating symbols](https://jsfiddle.net/Pc9Rv/265/); [DEMO WITH MARKERS AND POLYLINE](https://jsfiddle.net/nX8U8/177/).
Comment: Is there any alternatives for OSM?


$\forall\varepsilon > 0\exists\delta > 0:(|f(x) - \ell| < \varepsilon)\implies(0<|x-a| < \delta )$. $f(x)=x$ satisfies this for all $a$ and $\ell$?

Question: This is to be found in the answer to problem 26 (b) of chapter 5 of Michael Spivak's Calculus 3rd edition. The problem reads as follows:

26 Give examples to show that the following definitions of $\lim_{x\to a}f(x)=\ell$ are not correct.
(b) For all $\varepsilon > 0$ there is a $\delta > 0$ such that if $|f(x) - \ell| < \varepsilon$, then $0<|x-a| < \delta$.

I thought of constant functions because they do not satisfy this condition, but approach a limit "everywhere". This means, let $f(x)=c, c\in \mathbb R$ and let $a\in \mathbb R$ and let $\varepsilon > 0$, then $|f(x) - c|=0 < \varepsilon$ for all $x$ satisfying $0<|x-a| < \delta$ for any $\delta > 0$ and not just some $\delta > 0$. (It is already shown in the text of this chapter that $\lim_{x\to a}c=c$.)
In his answer Spivak also mentions constant functions but then adds the following:

Moreover, the function $f(x)=x$, for example, satisfies this condition no matter what $a$ and $\ell$ are.

What does he mean by that? It seems to me that if $|f(x) - \ell| < \varepsilon$ holds, then $|x - \ell| < \varepsilon$ so $a=\ell$ does hold, which means it does matter what $a$ and $\ell$ are. Unfortunately, I really don't understand what he is getting at.
Answer:
If $|f(x)- l| < \varepsilon$ holds, then $|x-l|<\varepsilon$

This is true.

so $a = l$ does hold

This is also true, but not necessary. You have assumed that $\delta$ is small (equal to $\varepsilon$), but this need not be the case. We are free to chose $\delta$ as we please, so $|a-l|$ can actually be as big as we like (using this incorrect definition).
In the true definition, we are asking "Can we find $x$ close enough to $l$ such that $|f(x) - l| < \varepsilon$". In the bad definition above, we are asking "Can we find a $\delta$ big enough such that if $|f(x) - l| < \varepsilon$, then $|x - a| < \delta$".
The important thing to take note of is the order which each section appears. Let's break down the 'definition' given in the question step by step to see where we go wrong.
Step 1 - What is given?
We are trying to show that $\lim_{x\to a} f(x) = l$, so $a$ and $l$ are fixed.
Step 2 - Choose an epsilon
We have been told that what follows must hold for all $\varepsilon > 0$, so we let $\varepsilon > 0$ be arbitrary but, from this point onwards, fixed.
Step 3 - Find a delta
We want to find a $\delta$ that 'works'. By this we mean, can we find a $\delta$ such that, if |$f(x) - l| < \varepsilon$ then $|x-a| < \delta$?
Suppose that $|f(x) - l| < \varepsilon$. Then, by definition of $f$, $|x-l| < \varepsilon$, so we have $x$ being 'close' to $l$. Can we find a delta such that $|x-a| < \delta$? Sure we can! We just pick delta to be as big as we need. So, using this definition, as long as we pick $\delta$ large enough, it works for all choices of $a$ and $l$.
Example
Let's consider the following example:

Using this (incorrect) definition, show that $\lim_{x\to 5}f(x) = 27$, where $f(x) = x$

Let $\varepsilon > 0$ be arbitrary. We seek $\delta > 0$ such that, if $|x-27|<\varepsilon$, then $|x - 5| < \delta$.
If $|x - 27| < \varepsilon$, and $\delta > 22 + \varepsilon$, then
\begin{align*}
|x - 5| &= |x - 5 + 27 - 27| \\
 &\leq |x - 27| + |-5 + 27| \\
 &= |x - 27| + |22| \\
&< \varepsilon + 22 \\
&< \delta
\end{align*}
Hence $\lim_{x\to 5}f(x) = 27$.
Clearly, this is nonsense, but it is a good exercise in demonstrating why the order of the statements in the definition is important.
Comment: Thanks a lot! In your example, why is $\delta > 22 + \varepsilon$ and not $\delta \geq 22 + \varepsilon$?
Comment: @Carlevaro99 this is a good question! From the definition, I want to find $\delta$ such that $|x-5|<\delta$. On the fourth line of my proof, we see $|x-5|<\varepsilon + 22$, so any $\delta \geq \varepsilon + 22$ will work. I just decided to choose the strict inequality. It's important to note that we just have to find any $\delta$ that works, not the smallest one. I could have equally chose $\delta > 100 + 22 + \varepsilon$
Answer: Edit
JEdwards and fleablood already explained much of what I added. Sorry! Not trying to poach answers. I'll leave mine up in case it's useful but please don't give me points that should go elsewhere!
I've missed the main thrust of what Spivak's getting at. The bad stuff I pointed out is true, however there's a more general issue.
With $f(x)= x$, no matter what we choose for $\ell$, $a$, or $\varepsilon$, we can find some $x$ such that $0<|x-a|<\delta$ and $|f(x) -\ell| < \varepsilon$. We just have to make $\delta$ big enough.
For example, take $a = 0$, $\ell = 10$.
Now, For any $\varepsilon > 0$ there is a $\delta$ ($\delta \geq 11$ works) such that $|f(x) - 10| < \varepsilon$ and $0 <|x-a|< \delta$.
But this suggests that $\lim_{x\to 0}x = 10.$
In other words, this $f$ is such that it approaches every number somewhere so using the criteria of our bad limit definition, if we make $\delta$ big enough we can show that $f(x)$ approaches any value, anywhere.
Original Post

What does he mean by that? It seems to me that if $|()−\ell|<\varepsilon$ holds, then $|−\ell|<\varepsilon$ so $=\ell$ does hold, which means it does matter what $$ and $\ell$ are.

This is true, however, the bad limit condition also says that for all $x$ satisfying $|()−\ell|<\varepsilon$, that $0 < |x-a|$.
For $f(x) = x$, $\lim_{x\to a} x = a$.
For $x = a$, we have $|f(x) - \ell| = |a - a| = 0 < \varepsilon$, but, $0 \not<|x-a|< \delta$
The same thing happens for constant functions. They satisfy $|f(x) - \ell| < \varepsilon$ at $x = \ell$, which is not allowed.
As an aside, this bad limit definition also runs into problems with functions that have the same limit at multiple different points. For example, $f(x) = x^2$ approaches $1$ at both $x = 1$ and $x = -1$.
Here we're forced to make $\delta$ big enough to cover both of them. Consequently, the $\delta$ neighborhood includes many $x$ that do not satisfy the original $\varepsilon$ condition. For cases like this, the $\delta$ neighborhoods stop being useful (even setting aside the earlier $x=a$ problem.)
Edit: Another point: using this definition of limits and considering constant functions, if $f(x) = c$ then then for every $\varepsilon > 0$ and all $x$, $|f(x) - c| < \varepsilon$. The fact that every $x$ satisfies this $\varepsilon$ requirement means that for the limit $c$ to exist at any point $a$, we require some $\delta > 0$ such that $|x-a|< \delta$ for all $x$. No such $\delta$ exists. Constant functions cannot approach limits.
Comment: Could you explain why you think OP's statement 'so $a=l$' is true please? I can't see how we can make this inference from the given (bad) definition.
Comment: I read it to mean "for the function $f(x) = x$, if we apply this bad definition to the case $\lim_{x\to a} x = a$, the conditions that come out of this are: for all $\varepsilon > 0$ there is a $\delta > 0$ such that if $|x - a| < \varepsilon$, then $0<|x - a| < \delta$. OP correctly noted that $\delta = \varepsilon$ works in so far as $|x - a| < \varepsilon$, but this leaves off the $0< |x - a|$ condition, which is a problem.
Comment: Hey Ben, cool answer! "The same thing happens for constant functions. They satisfy $|f(x) - \ell| < \varepsilon$ at $x = \ell$, which is not allowed." I think you meant to say that they satisfy $|f(x) - \ell| < \varepsilon$ at $x = a$.
Comment: Furthermore, does your observation mean that Spivak is only partly correct and the correct given answer should be "Moreover, the function $f(x)=x$, for example, satisfies this condition no matter what $a$ and $l$ are, if $a\neq l$."?
Comment: One more thing. "For every $\varepsilon > 0$" contains also large $\varepsilon$ satisfying $\varepsilon > |\ell-a|$. With your reasoning it follows that $\lim_{x\to a} x = \ell$ is *always* false (using the wrong definition) , since there is always an $\varepsilon$ for which $x=a$ satisfies $|f(x) - \ell| < \varepsilon$. Is that correct?
Comment: Sorry my answer is so muddled! I think that if we use the Bad limit definition then: 1) limits do not exist for constant functions. 2) The Identity function $f(x) = x$ satisfies the limit conditions for any $\ell \neq a$, that is, we can show $\lim_{x\to a} x= \ell$ for any $a\neq \ell$, but $\lim_{x\to a} x \neq a$.
Answer: Oh, okay:
Consider this.  Using the weird wrong definition.
$\lim_{x\to 3} x = 591$.
Proof: For any $\epsilon > 0$ let $\delta = 588 + \epsilon$
If $|f(x) - 591| < \epsilon$ then $|x-591| < \epsilon$ so $591 -\epsilon < x < 591 + \epsilon$.  So $588 -\epsilon < x -3 < 588+ \epsilon$.
So $-\delta = -588 - \epsilon < 588-\epsilon < x-3< 588 + \epsilon=\delta$
So $|x-3| < \delta$.
So $\lim_{x\to 3} x = 591$.


how to call (invoke) onChildClick method of expandable listview?

Question: I'm working on expandable list view. I've set onClickHandler on imageview of the child row, because inline clicklistners not working in this case. But I need int groupPosition and childPosition for some processing in my program. And these are available from OnChildClick().
The problem is I need OnclickHandler and OnChildClick() (for groupPosition and ChildPosition) both. Is there anyway to get these two values? can we call (invoke) OnChildClick method manually?
public class ExpList extends ExpandableListActivity
  {
       /** Called when the activity is first created. */
         @Override
         public void onCreate(Bundle icicle)
          {
            super.onCreate(icicle);
            setContentView(R.layout.main);

            getExpandableListView().setOnChildClickListener(new OnChildClickListener()
            {
                public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
                {
                     // some calculations here....
                     return false;
                }
            });
  }

public void onClickHandler (View v)
 {
     switch (v.getId()) {
         case R.id.imgcall:

            //Here I need groupPosition and ChildPosition....

                 my_function();
                 break;

         case R.id.img_call_icon:

                 // some code here......
                break;
            }
     }
 }

My child_row.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
        android:id="@+id/img_call_type"

        android:layout_width="40px"
        android:layout_height="40px"/>

         <TextView
         android:id="@+id/space"
         android:layout_width="10px"
         android:layout_height="wrap_content"/>

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
             android:id="@+id/name"
             android:textSize="14px"
             android:layout_width="115px"
             android:layout_height="wrap_content"/>

        <TextView
             android:id="@+id/number"
             android:textSize="14px"
             android:layout_width="115px"
             android:layout_height="wrap_content"/>

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
             android:id="@+id/date"
             android:textSize="14px"
             android:layout_width="115px"
             android:layout_height="wrap_content"
             />

        <TextView
             android:id="@+id/time"
             android:textSize="14px"
             android:layout_width="115px"
             android:layout_height="wrap_content"
            />

    </LinearLayout>

     <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

            <ImageView
            android:id="@+id/img_call_icon"

        android:layout_width="40px"
        android:layout_height="40px"
        android:clickable="true"
        android:onClick="onClickHandler"/>

    </LinearLayout>

</LinearLayout>

Comment: I am doing something similar HERE!!!http://stackoverflow.com/questions/16621070/get-context-of-popupmenu-like-contextmenu
Answer: You can get Button Clicks on your child Click listner.
In Short just copy paste your switch case statement of 'onClickHandler' to 'onChildClick'.
So, your code will be,
public class ExpList extends ExpandableListActivity
  {
       /** Called when the activity is first created. */
         @Override
     public void onCreate(Bundle icicle)
      {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        getExpandableListView().setOnChildClickListener(new OnChildClickListener()
        {
            public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
            {
                 switch (v.getId()) {
     case R.id.imgcall:

        //Here I need groupPosition and ChildPosition....

             my_function();
             break;

     case R.id.img_call_icon:

             // some code here......
            break;
        }
     }
            }
        });
  }

Don't forget to mark this as Answer if its helpful to you..


Dynamic programming problem: Optimal growth with linear utility

Question: This is a question from Stokey-Lucas-Prescott "Recursive Methods in Economic Dynamics", question 5.3: Optimal Growth with Linear Utility.
Q. Consider the following model-
(1) $\underset{x_{t+1}}{max} \sum_{t=0}^{\infty} \beta^t U[f(k_t) - k_{t+1}]$
st $0 \leq k_{t+1} \leq f(k^t), t=0,1,2 \dots$
given $k_0 \geq 0$
(2) $v(x) = \underset{0 \leq y \leq f(x)}{max} U[f(x) - y] + \beta v(y)$
We are given U(c) = c, so $U[f(k_t) - k_{t+1}] = f(k_t) - k_{t+1}$.
We are also given that:
(T1) f is continuous
(T2)f(0) = 0 and for some $\bar{x} >0: x \leq f(x) \leq \bar{x}$, all $0 \leq x \leq \bar{x}$ and $f(x) < x$, all $x > \bar{x}$
(T3) f is strictly increasing
(T4) f is weakly concave
(T5) f is continuously differentiable
b. Define $k* = \underset{k \geq 0}{max} [\beta f(k) - k]$. Show that for some $\epsilon > 0$, $|k - k*| < \epsilon$ implies $v(k) = f(k) - k* + \beta\frac{[f(k*) - k*]}{1-\beta}$
I'm stuck at part b. I've worked out that if I set up my $\hat{v}= \frac{f(k) - k}{1-\beta} $, then I can get $v* = \lim_{n \rightarrow \infty} T^n\hat{v}$. But I am having trouble theoretically explaining why $\hat{v}$ should be of this form for $|k - k*| < \epsilon$.
Any help would be appreciated.
Comment: Why don't you write question 5.3 so that we could know what it states and help you with your problem?
Comment: Hey. Definitely. The book is available online so I thought linking might help. But let me just put the question down.
Answer: Resurrecting this old thread here since no one actually solved this problem and the solution isn't online. The idea behind the value function is that you want to start with a "guess" function and then use the Bellman Operator to iterate, figure out a pattern, and then figure out what the value function is.
In this case, the Bellman Operator on a function $g(x)$ would be given by:
$$T(g)(x) = \max_{y \in [0,f(x)]} f(x) - y + \beta g(y)$$
Usually you have a sup instead of a max, but since the feasible set is compact valued and everything is continuous, you can just use the max.
Now, think back to the problem. $k^*$ is such that it solves the equation $\beta f'(k) -1 = 0$ (as a critical point of the strictly concave function $\beta f(k) - k$), i.e. so $f'(k^*) = \frac{1}{\beta}$. Moreover, for $k$ substantially close to $k^*$, $f'(k) \approx \frac{1}{\beta}$. This is what the problem means for $|k-k^*| < \epsilon$. I think SLP don't necessarily want you to rigorously show what that $\epsilon$, the idea is that if you're close to $k^*$, the proper conditions hold.
The approach you should have to this problem is to start with a smart "guess" for the value function and then iterate. Look at the proposed value function $v(k) = f(k) - k^* + \frac{\beta}{1-\beta}(f(k^*) - k*)$. If you look at it long enough, you can come up with a pretty good guess for what the value function is. If you haven't figured it out what it is, check the spoiler below and I'll just tell you.

 Try the initial guess $g(x) = f(x) - k^*$. The first iteration under the Bellman operator $T$ will be: $$T(g)(x) = \max_{y \in [0,f(x)]} f(x) - y + \beta g (y) = \max_{y \in [0,f(x)]} f(x) - y + \beta (f(y) - k^*)$$ If you use calculus to maximize this function, you'll get the first derivative w.r.t $y$ to be $$- 1 + \beta f(y) = 0$$ Doesn't that look familiar? This is precisely the condition that gave us $k^*$, so the optimal choice of $y$ here is $y = k^*$. In turn, we have $$T(g)(x) = f(x) - k^* + \beta(f(k^*) - k^*)$$ Long story short, if you apply  $T$ again, you use the same trick and get $$T^2(g)(x) = f(x) - k^* + \beta(f(k^*) - k^*) + \beta^2(f(k^*) - k^*)$$ In general for $T^n$, you should get $$T^n(g)(x) = f(x) - k^* + \sum_{i=1}^n \beta^i(f(k^*) - k^*)$$ As $n \to \infty$, you'll converge to the value function $v(x)$, which is $$\lim_{n\to\infty} T^n(g)(x) = f(x) - k^* + \sum_{i=1}^\infty \beta^i(f(k^*) - k^*) = f(x) - k^* + \frac{\beta}{1-\beta}(f(k^*)-k^*)$$

Please excuse any typos and let me know if anything looks off!


How to post image on Pinterest?

Question: i want to post image on pinterest using  this link but i change coding Little bit according to my own Requirement here is my MainClass code
- (void)pInterest {
      UIImage *myImage;
      myImage=imgView.image;
      WebViewController *webViewController = [[WebViewController alloc] initWithNibName:@"WebViewController" bundle:nil];
      webViewController.mypimage = myImage;
     [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentModalViewController:webViewController animated:YES];
}

So after passing image to my WebViewController now my WebViewController class code is
- (void)viewDidLoad {
     //imageview.image=mypimage;
     [super viewDidLoad];
     NSString *description = @"Post your description here";

     // Generate urls for button and image
     NSString *sUrl = [NSString stringWithFormat:@"http://d30t6wl9ttrlhf.cloudfront.net/media/catalog/product/Heros/mypimage"];
     // NSLog(@"URL:%@", sUrl);
     NSString *protectedUrl = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(__bridge CFStringRef)sUrl, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
     NSLog(@"Protected URL:%@", protectedUrl);
     NSString *imageUrl = [NSString stringWithFormat:@"\"%@\"", sUrl];
     NSString *buttonUrl = [NSString stringWithFormat:@"\"http://pinterest.com/pin/create/button/?url=www.flor.com&media=%@&description=%@\"", protectedUrl, description];

     NSMutableString *htmlString = [[NSMutableString alloc] initWithCapacity:1000];
     [htmlString appendFormat:@" "];
     [htmlString appendFormat:@"

", buttonUrl];
     [htmlString appendFormat:@"

", imageUrl];
     [htmlString appendFormat:@""];
     [htmlString appendFormat:@" "];
     [mywebview setBackgroundColor:[UIColor clearColor]];
     [mywebview loadHTMLString:htmlString baseURL:nil];
     [mywebview setOpaque:NO];
}

When i use the above coding my webview show no image and my webview looks like below screenshow

When i assign the same image instance to image view in WebViewController its working imageview.image=mypimage;
So can some one suggest me why my webveiw not show the image.Thanks.
Comment: I should say that this is not a proper button url. Please try to make sure the url exists for the resource you are trying to load before actually posting the question.
Comment: when i click on pinit button which is on first screenshot it open second screenshot which means there is no problem about url.so only problem there is that it not pass my image.
Answer: use this code...... Hope it will help you.
- (IBAction)pinit:(id)sender {
    [self postToPinterest];
}

- (IBAction)closeWebVIew:(id)sender {
    [webViewPinterest setHidden:YES];
}

- (NSString*) generatePinterestHTML {
   NSString *description = @"Post your description here";
 NSURL* sUrl = [NSString stringWithFormat:@"http://4.bp.blogspot.com/-w4oTZjlpgwo/T5_pi-KJPuI/AAAAAAAAAoM/rKm3E0XCbgY/s1600/red_rose_flower3.jpg"];// pass your link here with your image name

    NSLog(@"URL:%@", sUrl);
   NSString *protectedUrl = ( NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,( CFStringRef)sUrl, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    NSLog(@"Protected URL:%@", protectedUrl);
    NSString *imageUrl = [NSString stringWithFormat:@"\"%@\"", sUrl];
    NSString *buttonUrl = [NSString stringWithFormat:@"\"http://pinterest.com/pin/create/button/?url=www.flor.com&media=%@&description=%@\"", protectedUrl, description];

    NSMutableString *htmlString = [[NSMutableString alloc] initWithCapacity:1000];
    [htmlString appendFormat:@" "];
    [htmlString appendFormat:@"

", buttonUrl];
    [htmlString appendFormat:@"

", imageUrl];
    [htmlString appendFormat:@""];
    [htmlString appendFormat:@" "];
    return htmlString;
}

- (void) postToPinterest {
    NSString *htmlString = [self generatePinterestHTML];
    NSLog(@"Generated HTML String:%@", htmlString);
    webViewPinterest.backgroundColor = [UIColor clearColor];
    webViewPinterest.opaque = NO;
    if ([webViewPinterest isHidden]) {
        [webViewPinterest setHidden:NO];
    }
    [webViewPinterest loadHTMLString:htmlString baseURL:nil];
    //[webViewPinterest loadHTMLString:@"" baseURL:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [busyIndicator startAnimating];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [busyIndicator stopAnimating];
}

Comment: Flagged your last post as duplicate and was removed by the moderator, so my compensation here, +1.Please dont post links as answers.
Answer: Before Posting a answer, I would like to pay special thanks to @Sudha who gave me idea that without posting image on server we can not post local image from app directly on pinterest. Hence moving in this way idea when I posted images on server and assigned appropriate URL Address to pinit button, then it worked for me. Cheers!
when I started search about iOS app integration with pinterest, I found very little help and material in this regard. I think most of the developers used this Method, but when I used this above quoted method it didn't post my local app images on pinterest. At the end, I would like to post my answers for those who will be most likely to post local images from app on pinterest.
Steps

Create a New Class WebViewController and add Following things.
#import <UIKit/UIKit.h>

@interface WebViewController : UIViewController
{
 IBOutlet UIActivityIndicatorView *UIHelper;
 IBOutlet UIWebView *mywebview;
 UIImage *mypimage;
 }
 @property(nonatomic,retain)UIActivityIndicatorView *UIHelper;
 @property(nonatomic,retain)UIWebView *mywebview;
 @property(nonatomic,retain) UIImage *mypimage;
 -(IBAction)closeClicked:(id)sender ;
 @end

Now WebViewController.m file Code
#import "WebViewController.h"

@interface WebViewController ()

@end

 @implementation WebViewController
 @synthesize UIHelper,mypimage,mywebview;
 NSString *username;

-(IBAction)closeClicked:(id)sender {
 [self dismissModalViewControllerAnimated:YES];
 }
 - (void)webViewDidStartLoad:(UIWebView *)webView {
   [UIHelper startAnimating];
   }
-(void)webViewDidFinishLoad:(UIWebView *)webView {
 [UIHelper stopAnimating];
  }
- (void)viewDidLoad
 {
   username = @"j&D";
[username retain];

NSData *imageData = UIImageJPEGRepresentation(mypimage, 90);
NSString *urlString = @"ServerURl/cap.php";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",username] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"serverurl :%@",returnString);

    NSString *htmlString = [self generatePinterestHTML];
    NSLog(@"Generated HTML String:%@", htmlString);
    mywebview.backgroundColor = [UIColor clearColor];
    mywebview.opaque = NO;
    if ([mywebview isHidden]) {
    [mywebview setHidden:NO];
    }
    [mywebview loadHTMLString:htmlString baseURL:nil];
     [super viewDidLoad];
     }
    - (NSString*) generatePinterestHTML {
      NSString *description = @"Post your description here";
      NSString *sUrl = [NSString stringWithFormat:@"SerVerUrl/cap/j&D.jpg"];
      NSLog(@"URL:%@", sUrl);
      NSString *protectedUrl = ( NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,( CFStringRef)sUrl, NULL, (CFStringRef)@"!'\"();:@&=+$,/?%#[]% ",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
      NSLog(@"Protected URL:%@", protectedUrl);
      NSString *imageUrl = [NSString stringWithFormat:@"\"%@\"", sUrl];
      NSString *buttonUrl = [NSString stringWithFormat:@"\"http://pinterest.com/pin/create/button/?url=www.flor.com&media=%@&description=%@\"", protectedUrl, description];

       NSMutableString *htmlString = [[NSMutableString alloc] initWithCapacity:1000];
       [htmlString appendFormat:@" "];
       [htmlString appendFormat:@"

", buttonUrl];
       [htmlString appendFormat:@"

", imageUrl];
       [htmlString appendFormat:@""];
       [htmlString appendFormat:@" "];
        return htmlString;
       }
      @end

Create a method to call when user taps your "Pinit" button, which shows that webView with the image, that you will post and the "Pinit" button on the UIWebView. This is my code:
 -(void)pInterest
 {
   UIImage *myImage;
   myImage=imgView.image;
   WebViewController *webViewController = [[WebViewController alloc] initWithNibName:@"WebViewController" bundle:nil];
   webViewController.mypimage = myImage;
   [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentModalViewController:webViewController animated:YES];
}

Note: In the Above Code Replace SerVerUrl with your Own Server url.

To Make description Clearer, I have provided few Screenshots at the end to remove any ambiguities and misconceptions that may arise.

For any query, please feel free to comment!
Comment: Bob Apple and Sudha Is there any way to fit sharing screen in my view means in 320X480 for Pinterest sharing?
Comment: Explain it what you want please ?
Comment: @BobApple I want fit in my screen means image and discription all are fit in my screen so plz give me any link or code and 1more query Is this possible to share video via Pinterest?Yes then How plz?
Answer: You can use the Pinterest iOS SDK
Pinterest *_pinterest = [[Pinterest alloc] initWithClientId:pinterestKey];
[_pinterest createPinWithImageURL:@"http://placekitten.com/500/400"
                        sourceURL:@"http://placekitten.com"
                        description:@"Pinning from Pin It Demo"];

For this however, you'll need to have the Pinterest app on the device.
Comment: i dont have url for uploading images on pinterest,how to upload gallery image on pinterest...

How to post image on Pinterest?


Divergence of $\lim \limits_{t \to \infty}\sum_{n=1}^t b^{\ln n}$ and the Monotonic Sequence Theorem

Question: As far as I understand, the Monotonic Sequence Theorem states that if a sequence is monotonic and the individual terms are bounded, then the sequence is convergent.
My book states that $\lim \limits_{t \to \infty}\sum_{n=1}^t b^{\ln n}$ is convergent only for b $\lt$ $\frac{1}{e}$. However, is $\lim \limits_{t \to \infty}\sum_{n=1}^t 0.5^{\ln n}$, for example, not a monotonically decreasing series, whose terms are bound by 0 below and 1 above? Therefore this series meets the criteria for the MST, yet diverges, and does not share the outcome predicted by the theorem.
Why is $\lim \limits_{t \to \infty}\sum_{n=1}^t 0.5^{\ln n}$ divergent when it appears to meet the Monotonic Sequence Theorem's criteria for convergence?
Comment: There is a difference between the sequence and the series. The sequence ${1 \over n}$ is bounded and monotonic and has a limit, but $\sum_k {1 \over k}$ does not.
Answer: You've confused sequence convergence (the $n$th term has a finite $n\to\infty$ limit) with series convergence (the sum of the first $n$ terms has a finite $n\to\infty$ limit).
Answer: $$\lim_{t\to\infty} \sum_{n=1}^\infty b^{\ln n}=\sum_{n=1}^\infty b^{\ln n}=\sum_{n=1}^\infty e^{\ln b\ln n}=\sum_{n=1}^\infty n^{\ln b}$$
This series converges iff $\ln b<-1$,i.e. when $b<1/e$.
Now, $0.5>1/e$. So, you certainly have that when $b=0.5$ this diverges.  This doesn't contradict monotonic sequence theorem, even though $ (0.5)^{\ln n}$ is bounded by $1$ for all $n$, you don't have that  $\sum_{n=1}^\infty (0.5)^{\ln n}$ is bounded for all $t$.


cURL PHP - Recuperando html da página

Question: Olá,
Estou treinando esse cURL. Vocês podem me dizer porque o seguinte trecho não funciona?

    <meta charset="UTF-8">
    <title></title>

    <?php
    $cURL = curl_init('http://fiesselecaoaluno.mec.gov.br/consulta/curso');
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
    $dados = array(
        'opcaoProcurar' => 'I',
        'noIes' => '10',
    );
    curl_setopt($cURL, CURLOPT_POST, true);
    curl_setopt($cURL, CURLOPT_POSTFIELDS, $dados);
    curl_setopt($cURL, CURLOPT_REFERER, 'http://fiesselecaoaluno.mec.gov.br/consulta/curso');
    $resultado = curl_exec($cURL);
    curl_close($cURL);
    echo $resultado;
    ?>

Eu queria pegar o html com o cURL, mas só dps dele ter preenchido o formulário corretamente. Alguma dica?
Tem alguma coisa a ver com o formulário da página, ou é por ser ajax e o curl não funciona pra isso ?
Comment: Em que ambiente você esta usando este script?
Comment: Como está o HTML do formulário?
Comment: Acabei de analisar o formulário e pelo que vi, ele é Ajax e não aceitaria a logica do script que você fez.
Comment: Era só eu entrar na url pra onde encaminha o post, muito obrigado
Answer: O serviço a que estás a fazer o post está errado, deve ser http://fiesselecaoaluno.mec.gov.br/consulta/consulta:
$cURL = curl_init('http://fiesselecaoaluno.mec.gov.br/consulta/consulta');
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
$dados = array(
    'opcaoProcurar' => 'I',
    'noIes' => '10',
);
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_POSTFIELDS, $dados);
curl_setopt($cURL, CURLOPT_REFERER, 'http://fiesselecaoaluno.mec.gov.br/consulta/curso');
$resultado = curl_exec($cURL);
curl_close($cURL);
echo $resultado;

Neste caso, consegues ver a que serviço se vai fazer post pela action do formulário
Comment: Era isso msm, resolvido.
Comment: só uma dúvida, ele escreve as tabela na página, tem como eu recuperar os dados do ajax sem precisar copiar todo o html da página ?
Comment: @MauricioMaletta agora não estou no computador, mas quais dados? Tu não querias o html?
Comment: não, achei umas funções legais: loadHTML() e getElementsByTagName(). Acho que dá pra fazer com elas, eu quero pegar os dados das tabelas e colocar em array, pra manter a estrutura da tabela, mas sem o código html.
Comment: @MauricioMaletta, mas tu já tens o html dentro de $resultado, mas como fazes o echo para o browser (navegador) ele randeriza isso... Podes comprovar isto se fizeres `echo htmlentities($resultado);` no fim
Comment: eu só queria limpar o html, parece q terei q usar expressões regulares
Comment: @MauricioMaletta podes usar http://simplehtmldom.sourceforge.net/

cURL PHP - Recuperando html da página


User roles and permission for 1 can publish and 1 can't

Question: I have 2 user roles which I created
<code>1] Article Creator  -> Can Create/Update/Delete
2] Article Publisher -> Can Create/Update/Delete/Publish
</code>
Article Creator can create content, but can't publish. While Article publisher can do that.
Can we manage it without any module or any custom coding?
Can manage from default Drupal Admin?
Answer: You are looking for Workflows and Content moderation. Those are features available out-of-box in Drupal 8 (stable form 8.4)


How can I loop over all minions in a pillar top file?

Question: I would like to add some generic pillar data to minions based on roles, but also offer a way to customize each machine based on hostname (minion id).
In my pillar/top.sls file I have
<code>base:
  '*':
    - pkgs/common-ubuntu-pkg
    - fail2ban/config
  'runit:True':
    - runit/package
  'is_virtual:True':
    - users/vmuser
  'role:database':
    - match: grain
    - mysql/defaults
</code>
And then I want to add something like this:
<code>{% for host in pillar %}
  '{{host}}':
    include:
     - {{host}}/passwords
{% endfor %}
</code>
Which works, but it only prints out 'master'.  I'm using master-less salt-ssh, so I believe that's why the minions in the roster are not already in the pillar.  I would like a different way to loop over defined minions, but I can't seem to easily get a view of what is in the salt dictionary.
<code>{% for key in salt %}
  '{{key}}':
     include:
       - foobar
{% endfor %}
</code>
Trying to debug using something like the above results in a KeyError
Answer: The solution relied not in using jinja in the pillar.top file, but using an external pillar plugin.
The external pillar plugin "file_tree" looks under a root_dir for directories hosts and nodegroups.  Matching minion_ids as directories under root_dir/hosts/, it will add all .sls files as pillar data to that host/minion.
<code>#in /etc/salt/master
ext_pillar:
  - file_tree:
      root_dir: /srv/salt/my-pillars/
      follow_dir_links: False
      raw_data: False

#on disk
/srv/salt/my-pillars/hosts/mydbserver/passwords.sls
</code>
https://docs.saltstack.com/en/latest/ref/pillar/all/salt.pillar.file_tree.html#module-salt.pillar.file_tree
Comment: Sorry for answering my own question, but I felt I was at my wit's end when I asked this question and I started pouring over all the module docs and found that the external pillar would solve my problem in a different way than what I was searching for.


Proving two statements regarding combinatorics and numbers

Question: So i want to prove these two statements:
1) In a set of $n+1$ natural numbers, there exist  two numbers, that if we subtract on from the other, the result is dividable by $n$.
2) For every natural number n, there exists a number m, that is made of only $0$ and $5$, there is no other limitation on how many $0$ and $5$ it is made of.
Any help would be appreciated.
I came across it in discrete mathematics, so there is probably some combinatorics or something similar behind the proves, maybe even Dirichlet's principle.
Thank you in advance.
Comment: Your second question is not clear, "for every n there is a natural number m", and then there is no relation between $n$ and $m$. Please make the correction. Also, for the first question, consider the possible set of remainders that the elements of the set can give upon division by $n$, and note that there are $n+1$ elements in the set, while only $n$ remainders $0,1, \ldots,n-1$ are possible upon division by $n$.
Comment: well i literally translated the qquestion from my mother language, there is nothing other than that stated. The relation is that n divides m, that is made of 0s and 5s. That's all there is. But it seems like i should construct a general algorithm or something, that gets a number m, dividable by n, and that's made of 5s and 0s. Probably that's how i could prove it, but i'm not sure how to start.
Comment: I have just checked your profile. I ,well, can make out a bit of Slovenian for you,if you like. There's no harm. Your question is more important than the language you speak. Somehow, I think I have understood the question as "for all $n$, there is a large $m$ consisting of only $0$s and $5$s such that $m$ is a multiple of $n$".
Comment: It's probably meant like that yeah. And yeah, i guess you could, but english isn't really a problem for me. Just a little rusty at first.
Comment: All right, so the answer of your question will be below in few minutes.
Answer: If your question is as spoken, then the answer is as follows.
First, the case of $n$ being odd.
To do this, we use the same principle as last time. Think about the numbers $5,55,555,5555,55555, \ldots$. Now, there are only $n-1$ possible remainders when you divide something by $n$, right? So suppose I take the following set: $5,55,555,\ldots,(55\ldots55)$, where $(55\ldots55)$ is the number which has $n+1$ fives. This set has $n+1$ elements.
By the first part of your question, there are two numbers in this set, say one with $k$ fives and one with $l$ fives, such that these leave the same remainder when dividing by $n$ (and $k > l$, say). Hence, their difference is a multiple of $n$. But then, when you take the difference of $55...55$ and $55...55$, then the number you will get will be like $55...5500...00$,right? (where there are $k-l$ fives and $l$ zeros). Hence, this number has only zeros and fives, and is a multiple of $n$.
Suppose that $n$ is even. We can write $n = m \times 2^k$, where $m$ is an odd number, and hence $k$ is the maximum possible power of $2$ that divides $n$. Then, since $10$ is a multiple of $2$, $10^k$ is a multiple of $2^k$. So what we do is the following:
1) Since $m$ is odd, find a number $555...555000..000$ which divides $m$.
2) Add $k$ zeros to $555...555000...000(000...000)$ (where $(000...000)$ is a new block of $k$ zeros), so that now this is also divisible by $2^k$.
This number, $555...555000...000(000...000)$ will be a multiple of $n$.
I'll give an example to illustrate.
Suppose $n=28$. Then $n = 2^2 \times 7$, so then $m=7$ and $k=2$.
For $m=7$, we consider the set $\{ 5,55,555,5555,55555,555555,5555555,55555555\}$. This set has $8$ elements, so two of them must leave the same remainder when divided by $7$. You can check that these two numbers are $5555555$ and $5$, because their difference is $555550$ ,and $5555550 = 7 \times 793650$.
Now, since $k=2$, just add two more zeros to $5555550$ to get $555555000$. This is a multiple of $28$, because $555555000 = 28 \times 19841250$.
This is the complete proof of the question.
Answer: Consider the remainders when the $n+1$ integers are divided by n. Since there are only $n$ possible remainders, $0, 1, ... ,n-1$, at least two of the integers must have the same remainder. The difference of two integers with the same remainder is divisible by $n$.


MongoDB: Is a range query possible using multikeys?

Question: var jd = {
  type: "Person",
  attributes: {
    name: "John Doe",
    age: 30
  }
};

var pd = {
  type: "Person",
  attributes: {
    name: "Penelope Doe",
    age: 26
  }
};

var ss = {
  type: "Book",
  attributes: {
    name: "The Sword Of Shannara",
    author: "Terry Brooks"
  }
};

db.things.save(jd);
db.things.save(pd);
db.things.save(ss);
db.things.ensureIndex({attributes: 1})
db.things.find({"attributes.age": 30}) // => John Doe
db.things.find({"attributes.age": 30}).explain() // => BasicCursor... (don't want a scan)
db.things.find({"attributes.age": {$gte: 18}) // John Doe, Penelope Doe (via a scan)

The goal is that all attributes be indexed and searchable via range queries and that the index actually be used (as opposed to a collection scan).  There's no telling what attributes a document will have.  I have read about multikeys but they seem only to work (by index) with exact-match queries.
Multikeys prefers this format for a document:
var pd = {
  type: "Person",
  attributes: [
    {name: "Penelope Doe"},
    {age: 26}
  ]
};

Is there a pattern where by one index I can find items by attribute using a range?
EDIT:
In a schemaless DB it makes sense to have potentially a limitless array of types, yet a collection name practically implies some sort of type.  But if we go to the extreme, we want to allow for any number of types within a collection (so that we don't have to define a collection for every conceivable custom type a user might imagine).  Searching, therefore, by attributes (of any sort) with just a single deep index (that supports ranged queries) makes this sort of thing far more feasible.  Seems to me a natural fit for a schemaless DB.
Opened a ticket if you wanna vote it up:
http://jira.mongodb.org/browse/SERVER-2675
Comment: I would post this question in http://groups.google.com/group/mongodb-user and get an answer from the developers themselves - they are *very* responsive.
Comment: Thanks for the tip.  I did just that. :)
Answer: Yes range queries work with multikeys.  However multikeys are for arrays rather than embedded objects.
In the example above try
db.things.ensureIndex({"attributes.age": 1})

Comment: The goal is to avoid indexing "age" or any one attribute in particular but to have all "attributes" indexed. The point is I could have any attribute key (e.g. "dob", "name", "hair_color") and I should have indexed access to them all.
Answer: Range queries are possible using multikeys; however, expressing the query can be tricky.


Representation for meaning of a text document

Question: Does anyone know a technique to represent meaning of a given text document, so that two documents having same meaning will have same representations?
Note: Typical systems like vectorization methods are not suitable for this because they only consider presence of vocabulary of the text, not the ordering of words.
Comment: You are probably looking for something like semantic embeddings.
Comment: Is there any paper or something published related to semantic embeddings?? can you post something regarding this??
Comment: Latent dirichlet allocation is used to detect topics in documents. You may find it useful.
Comment: I suggest you do a first round of Google searching yourself and then ask specific questions. LDA as Ian mentioned is also worth checking out.
Answer: We might need to know what exactly is your goal.
Meaning of a text needs to be a complex structure (whatever approach). So if you want two document with the same meaning to have exactly the same meaning representation, you need to go for a full semantic modelling using some sophisticated approach involving knowledge representation etc.
But how do you measure how much the meaning of two texts is the same / similar?
Typical representationl approach is to have some metric of similarity like cosing distance of two vectors. BTW there is a doc2vec that produces vector representation of the whole text. And doc2vec does care about the context of the words, maybe not strictly about word order but their proximities.


Does there exist a topological space which is not separable but has the Souslin property?

Question: Does there exist a topological space which is not separable but possess the Souslin property (i.e. there is no uncountable family of pairwise disjoint nonempty open sets)?
I guess it should be something really large, e.g.
$[0,1]^\mathbb{R}$ or even $[0,1]^\mathbb{2^\mathfrak{c}}$
Thanks in advance.
Answer: Yes, the product is a nice and standard example:
$[0,1]^I$ is ccc (i.e. has the Souslin property) for any $I$. This is a corollary of the theorem that a product $\prod_i X_i$ is ccc iff all finite subproducts $\prod_{i \in F} X_i$ are, where $F \subseteq I$ is finite). This is a consequence of the $\Delta$-system lemma. And as $[0,1]$ is separable, and so are its finite powers, we see that $[0,1]^I$ is ccc.
And $[0,1]^I$ is separable iff $|I| \le \mathfrak{c}$, so $[0,1]^{\mathfrak{c}^+}$ is an example.
Another example is $C_p(X)$ (the space of real-valued continuous functions on a Tychonoff space $X$, in the topology induced by the product $\mathbb{R}^X$), with $X$ a compact non-metrisable Hausdorff space, (like the Double arrow space or the one-point comPactification of an uncountable discrete space etc.), because all spaces of the form $C_p(X)$ are ccc (being dense in $\mathbb{R}^X$) and $d(C_p(X)) = w(X)$ for $X$ compact Hausdorff). This is another, but related, way to construct such spaces.
The classic is of course a Souslin line (the reason we call ccc the Souslin property, in a way), which exists in some but not all models of ZFC: a linearly ordered space (order-dense, unbounded) which in the order topology is ccc but is not separable.
The most boring example: $\mathbb{R}$ in the co-countable topology. This is not separable as all countable sets are closed and thus not dense and ccc because all non-empty open sets intersect.
Comment: Thank you for a detailed answer. In probability theory there is a lemma which claims that the family of pairwise disjoint sets with positive probabilities is countable. Is it also a nice example of Souslin property? Can we go in that direction to look for a counterexample?
Answer: Yes, $[0, 1]^{2^\mathfrak{c}}$ works, but $[0, 1]^ℝ$ is not enough. The point is that any product of separable spaces is ccc, because a product is ccc if and only if its every finite subproduct is ccc. At the same time the cardinality of a Hausdorff space $X$ is upper bounded by $2^{2^{d(X)}}$.
Also, the Hewitt–Marczewski–Pondiczery theorem says that a product of $≤2^κ$ many spaces of density $≤ κ$ still has density $≤ κ$. So $[0, 1]^ℝ$ is still separable.
In fact, it can be proved that $d(∏_{i ∈ I} X_i) = \log|I| ∨ \bigvee_{i ∈ I} d(X_i)$ if the spaces are Hausdorff and nondegenerate (and the vees denote suprema).


How to animate Table Item Entry using TransitionGroup and Material UI Tables in ReactJS

Question: I am having an issue where I can't seem to get TransitionGroup to work with Material UI ReactJS library
My expectation is pretty simple, upon entry into the table the row should be animated in like sliding into the table.
I have tried the following but this only end up scattering the table, the headers and everything becomes out of shape.
Here is what I have tried using the Material UI library for ReactJS
                   <TableContainer>

                            <TableHead>
                                <TableRow>
                                   {...}
                                </TableRow>
                            </TableHead>
                            <TransitionGroup
                                transitionName="fade"
                                transitionEnterTimeout={1000}
                                transitionLeaveTimeout={300}
                                transitionAppearTimeout={1000}
                                transitionAppear={true}
                                component="tbody">
                                <TableBody>
                                    {
                                        (rowsPerPage > 0 ? games.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : games
                                        ).map((row: Game) => (
                                            <SimpleTableRow row={row} key={row.id}/>
                                        ))}
                                    {
                                        emptyRows > 0 && (
                                            <TableRow style={{height: 53 * emptyRows}}>
                                                <TableCell colSpan={6}/>
                                            </TableRow>
                                        )
                                    }
                                </TableBody>
                            </TransitionGroup>
                   </TableContainer>

The moment I add the TransitionGroup, the entire table headers and body becomes scattered.
How can I make this work? Thanks
Comment: I'm not sure about this, but try putting the `TransitionGroup` be inside of the `map` around each `SimpleTableRow` rather than around the entire `TableBody`.
Comment: @LindaPaiste I tried your suggestion and I still get same issue. The entire table becomes scattered...The headers are shifted to the right and the body shifted to the left...
Comment: Having the same error. By inserting the transition elements inbetween, whole row moves to the first column of the table. By wrapping the cell content, it works but the rows borders are keept. Still looking for a good solution.
Answer: You can try to pass component={null} instead component="tbody".


How to sum multiple field with specific condition for each field

Question: I want to put condition to the SUM. For example SUM rates.negative will have condition where is_active = 0
This is the link DB Fiddle
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=cd6fe488fcefcd000274a3c67590dede
This is the sample query without the condition
SELECT
    comments.*,
    SUM(
        rates.score
    ),
    SUM(
        rates.negative
    )
FROM comments
    WHERE rates.comment_id = comments.id
GROUP BY comments.id

Output

If I put the condition using WHEN, I get this error.
SELECT
    comments.*,
    SUM(
        rates.score
    ),
    SUM(
        rates.negative WHEN rates.is_active = '0'
    )
FROM comments
    WHERE rates.comment_id = comments.id
GROUP BY comments.id

Error
Error syntax near WHEN rates.is_active = '0'

How to solve this?
Thanks
Answer: The proper syntax is to use CASE .. WHEN expression, for conditional aggregation. Moreover, for multi-table queries, it if preferable to use Aliasing for code clarity and readability.
SELECT
    c.id,
    SUM(
        r.score
    ) AS score_sum,
    SUM(
        CASE WHEN r.is_active = '0' THEN r.negative ELSE 0 END
    ) AS negative_sum
FROM comments AS c
LEFT JOIN rates AS r ON (r.comment_id = c.id)
WHERE r.comment_id = c.id
GROUP BY c.id

DB fiddle Demo: https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=6b344f7653249c53a38e64a9f81bee19
Answer: SELECT
    CS.id AS comment_id,
    SUM(RS.score) AS score_sum,
    SUM(CASE RS.is_active WHEN 0 THEN RS.negative ELSE 0 END) AS negative_sum
FROM comments AS CS
LEFT JOIN rates AS RS ON (RS.comment_id = CS.id)
GROUP BY CS.id

DB File Demo
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=696a1648f0d2a9baa8330ed9b686fd81
Hope This Will Help You


How to define custom date format in page.tpl.php?

Question: I would like to add a custom copyright footer to my site e.g. MONTH YEAR. I have set up a »short« date format for English, French and German in admin/config/regional/date-time/locale. Using <?php print format_date(time(), 'custom', t('F Y')); ?> in page.tpl.php is working great.
However I would love to go one step further. How do I print the short date format to page.tpl.php instead of adding them to *.tpl files separately?
Comment: Nope, it handles the language automatically as I explained in answer. Cheers.
Comment: Just ``, is it what you want?
Comment: Yes, do I have to add the  t() function for translation?
Answer: You are right using the correct API format_date(). What you need to do is passing correct value to it.
<?php print format_date(time(), 'short'); ?>

According to the API doc, the function signature is:
format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)

And it explained how you should handle the translation.

$langcode: (optional) Language code to translate to. Defaults to the language used to display the page.

$langcode is handled automatically if you keep it as default value.
Comment: Thank you, Jimmy Ko! This is exactly I was looking for. Now I am able to customize the date format for multiple languages.


How can I estimate the volume of the region inside an open bounded set in dimension n at distance less than 1/n from its boundary?

Question: How can I estimate the volume of the region inside an open bounded set in dimension $n$ at distance less than $1/n$ from its boundary?
Answer: Suppose that your region $R$ is contained in an open set $U$. Then you can rephrase the condition "the distance between $R$ and the boundary of $U$ is less than $1/n$" as
$$
U \supseteq R \supseteq \frac{n-1}{n} U
$$
which means that
$$
\operatorname{vol}(U) \geq \operatorname{vol}(R) \geq \left(\frac{n-1}{n}\right)^n \operatorname{vol}(U).
$$
Comment: I'm afraid that not much more can be said with the little information you provided in your question...


$\sum_{n=1}^\infty \frac{X_n}{2^n} \sim \mathcal{U}(0,1) $ for independent $X_n \sim Bern(1/2)$

Question:
Let $(X_n)_{n \ge 1}$ be independent and $\textit{Bern}(0,1)$ distributed. Show that $\sum_{n=1}^\infty \frac{X_n}{2^n}$ is uniformly distributed on $(0,1)$.
  Hint: Start with $\sum_{n=1}^{m} \frac{X_n}{2^n}$

I found a similar question, but I am unable to apply this on my problem. I don't have any other approaches, so I'm stuck.
Could anyone give me a hint? Thank you.
Edit:
This question was "put on hold" because "This question is missing context or other details". I am sorry. As you can see in the comments, I had a problem in understanding and didn't realize that the question I linked above basically is the same question.
Comment: This question you linked already has several answers plus hints in the comments. What part of the previous question were you having trouble with?
Comment: Ahhh... if by $P(S=p)$ you mean the density function then yes, but this is poor notation. Why bother with the density at all? Once we have the CDF we have the distribution.
Comment: The question I linked shows that $P(S \le p) =f(p)=p$. Since I try to show $P(S = p)=1_{(0,1)}$, I tried to split the interval to $p<1/2$ and $p \ge 1/2$ aswell. So \\
@Jason $P(S=p)=1/2P(S=p|X_1=1)+1/2P(S=p|X_1=0)$ \\
I have $P(S=p|X_1=1)=0$, which is ok, but I also have $P(S=p|X_1=0)=1/2^m$ and this goes to $0$. The other two equations are $0$ aswell.
Comment: Hmm, you seem to be confused. You are trying to show $S$ is uniformly distributed on $(0,1)$, which precisely means that $P(S\le p)=p$ for $p\in[0,1]$. In fact, you will have no luck with your method, since $P(S=p)=0$ for any $p$.
Comment: Yes, I am, sorry. Let me think about what you've wrote. $P(S \le p)=p 1_{(0,1)}$ describes the CDF, so by deriving, we get $P(S=p)=1_{(0,1)}$. Right?
Comment: Yes, I meant the density function. But you are right, there is no reason to deal with the density. Thanky you very much for you help.
Answer: What we want to prove is that for every $x\in[0,1]$, $\displaystyle\mathbb{P}\left(\sum_{n=1}^{\infty}\frac{X_n}{2^n}\leq x\right)=x$.
Assume that $\displaystyle\frac{i}{2^m}=0.y_1y_2\dots y_m$ for $(y_1,\dots,y_m)\in\{0,1\}^m$. Let us begin by computing the probability $\displaystyle \mathbb{P}\left(\frac{i}{2^m}\leq \sum_{n=1}^{\infty}\frac{X_n}{n}< \frac{i+1}{2^m}\right)$. Notice that this probability is precisely equal to $\displaystyle\mathbb{P}\left(X_1=y_1,X_2=y_2,\dots,X_m=y_m\right)=\displaystyle\prod_{i=1}^M\mathbb{P}\left(X_i=y_i\right)=\displaystyle\frac{1}{2^m}$.
Next, note that this implies:
$$
\mathbb{P}\left(\sum_{n=1}^{\infty}\frac{X_n}{n}\leq \frac{i}{2^m}\right)=\mathbb{P}\left(\bigcup_{k=1}^i\left\{\frac{k-1}{2^m}\leq \sum_{n=1}^{\infty}\frac{X_n}{n}< \frac{k}{2^m}\right\}\right)=\sum_{k=1}^i\mathbb{P}\left(\frac{k-1}{2^m}\leq \sum_{n=1}^{\infty}\frac{X_n}{n}< \frac{k}{2^m}\right) = \frac{i}{2^m}.
$$
Hence, for any dyadic rational, the claim is proven. Now, using the fact that dyadic rationals are dense in $\mathbb{R}$, take a sequence of dyadic rationals $q_n$ such that $q_n \searrow x$. From the right continuity of the CDF, we have
$$
x = \lim_{n\to\infty} q_n = \lim_{q_n \searrow x}\mathbb{P}\left(\sum_{n=1}^\infty \frac{X_n}{n}\leq q_n\right)=\mathbb{P}\left(\sum_{n=1}^\infty \frac{X_n}{n} \leq x\right).
$$
Remark This is a fundamental step that allows us to construct an infinite sequence of independent $U[0,1]$ random variables, and therefore, allowing us to construct a sequence of independent random variables with prescribed distribution functions. In particular, the idea is to consider $(\Omega,\mathcal{F},\mu) = ([0,1],\mathscr{B}_{[0,1]},\lambda)$, for any $\omega \in [0,1]$, expand $\omega$ in binary : $\omega = 0.\omega_1\omega_2\dots$, notice that $X_n = \omega_n$'s are independent $\rm{Ber}\left(\frac{1}{2}\right)$ random variables. Taking a bijection $f : \mathbb{N}^2\to\mathbb{N}$, we construct:
$$
Y_n = \sum_{k=1}^{\infty}\frac{X_{f(k,n)}}{2^k}.
$$
The argument above tells us that $\displaystyle \{Y_n\}_{n=1}^{\infty}$ is a sequence of uniform (over $[0,1]$) random variables, and then applying Skorokhod representation, we construct a sequence of independent random variables with CDF's we wish.


Views 2 - How to show exposed filters when results list is empty?

Question: I have a page that displays all events after the current date. It has an exposed filter where you can set the date - all events after that date will be shown. This all works fine.
However, if there are no results on the initial page load (i.e. no events listed that are after the current date) then the exposed filter isn't shown (so you can't set the date to some time in past and view past events).
I found the relevant view theme template and over-rode the If($exposed) conditional but this did not do it - obviously the decision to show filters or not is made before the template but I haver no idea where.
Please could somebody enlighten me?
Thanks
Answer: Ok. The ominous non-sound of tumbleweed lol
Well, after a bit of faffing and a >slap forehead< "D'Oh" moment I sorted it.
I added some text in the "Empty text" setting (under "Basic Settings") and the exposed filters now show when there is no result.


Can flat notes be played on a chromatic harmonica?

Question: Can we play flat notes on a chromatic harmonica?
I already know that a chromatic harmonica could play regular (natural) notes and sharp notes, but what about flat notes?
Answer: All flat notes are sharp or natural notes.

Ab = G#
Bb = A#
(Cb = B)
Db = C#
Eb = D#
(Fb = E)
Gb = F#

Or, to put it another way, any flat note you might want is covered by the four "settings" of a chromatic harmonica: no-side-key or with-side-key, each used with "blow" or "draw" (i.e. breathe-out or breathe-in). See this for a list of pitches when using these "settings".
EDIT: Just a couple of extra bits of info…

You can of course bend notes flat on chromatic harmonica, although there are limitations to this technique when compared to bending notes on a diatonic harmonica. However, by definition, chromatic harmonica allows all 12 chromatic pitches to be played without using this technique. Instead, this technique is used to add character and inflections of pitch; these need not be changes by exact semitones, but can be arbitrary changes of pitch, giving the "notes-between-the-notes". A good analogy would be guitar playing; all 12 chromatic pitches can be played using a standard technique, but use of bends and vibrato arm allow changes of pitch (either by exact semitones or other arbitrary distances), too.
Although the tuning you refer to seems to be considered standard, there are other tunings used for chromatic harmonica. In particular, Irish Tuning lowers the pitch of both blow and draw notes when depressing the side-key.
Comment: Just two quick observations: (1) "all flat notes are sharp or natural notes" in equal tempered tuning, not necessarily in other [temperaments](https://en.wikipedia.org/wiki/Musical_temperament). (2) Harmonica will let you "bend" notes by overblowing, which may permit reaching some of those alternatives.
Comment: That's true of most recent Western music. Not true of blues, nor of earlier forms. Not even true of all recent music; there are performers who take full advantage of the possibilities of other temperaments. I think it's worth noting that although the modern harmonica is designed around equal temperament, it can reach somewhat outside that space. (You don't have to go back very far, either. My own instrument, an Anglo concertina, was almost certainly not equal-tempered when it left the factory though it has been retuned since.)
Comment: @Tim: as "the original Blues instruments" I'd consider the human voice, which is not tuned in any temperament (most definitely not 12-edo), along with Blues harp (diatonic), Diddley bow (untuned), and slide guitar. Sure enough adaptions for piano and banjo / spanish-style guitar would quickly appear, but that's just approximations. "An instrument that plays G# out of tune to another's Ab is impractical" – no it isn't, e.g. flutes and clarinets certainly do that (though the player may trim manually). And let's not start with string instruments.
Comment: @keshlam - most of the time, particularly in the Western world, we play using equal temperament. Other temperaments maybe belong where they were before we compromised to what has become 'industry standard'.
Comment: @keshlam - with blues, the instruments are tuned to equal temperament even though notes are often bent to produce ones 'in the cracks', nevertheless they are rarely tuned to any other tuning.My point was that having, for instance, an instrument that plays G# out of tune to another's Ab is impractical. Possibly proved by your re-tuning the concertina.I'm well aware of the phenomenon - it just has no practical use in ensemble works - unless one is looking for authenticity in early Baroque etc. tunes.
Comment: @Bob - you may add (E#=F) and (B#=C) to complete the list.
Comment: @leftaroundabout: Bingo. Any temperament is a compromise; equal's compromise is that it is "equally out of tune in all keys". And in fact pianos are not usually equal tempered either; they're stretch tuned to be slightly of tune with themselves, to give the sound a bit more body, yet it's still "close enough" to play with other instruments. Sorry, Tim, but this really is more common than you may be aware of.
Comment: @kelsham - 'twould appear so. I need to look into this more.So when I get accused of being out of tune, my response can be 'It's supposed to be !'
Answer: Sharp notes and flat notes are the same thing.  If you have access to a piano or keyboard, look at the black key between F and G.  That key has two "enharmonic" names.  It is F# and also Gb.


Repetição até que a letra correta seja digitada

Question: Usando a função switch,
case 'T' :
case 'T' :

default:

Como é que faço para por exemplo os dois cases representam uma letra cada um, mas caso o utilizador escolha outra diferente então segue por default que vai voltar a refazer a mesma pergunta, (escolher uma letra entre T e F).

O que eu queria era por exemplo: Escolha uma letra entre P ou B, caso o utilizador escolha a Letra C o sistema diz que a letra está incorreta e volta a fazer a mesma pergunta.
Comment: Não entendi o que está pretendendo, pode explicar melhor?
Comment: Bem, quanto a parte do voltar e refazer, você pode tentar usar um `while`, `do-while`, separar em uma função a parte e usar um `return` ou até mesmo usar um `goto`. Mas para saber qual seria o melhor caso, você tem que explicar melhor o seu problema.
Answer: Essa é a sintaxe básica do switch:
switch (letra)
{
    case 'T':
        // Código;
        break;
    case 'F':
        // Código;
        break;
    default:
        // Código;
        break;
}

EDIT: Conforme seu comentário:
#include <iostream>
#include <string>
using namespace std;

int main()
{

    char letra;
    do
    {
       cout << "Digite a letra correspondente: \n";
       cin >> letra;
    }
    while((letra !='T')&&(letra !='F')&&(letra !='t')&&(letra !='f'));

    switch (letra)
    {
        case 'T':
        case 't':
            cout << "Digitou a letra T.\n";
            break;
        case 'F':
        case 'f':
            cout << "Digitou a letra F.\n";
            break;
        default:
            // Código;
            break;
    }

    return 0;
}

Veja funcionando no C++ Shell.
Esse código vai repetir até que as letras T ou t ou F ou f sejam digitadas. Essa condição é feita nessa linha: while((letra !='T')&&(letra !='F')&&(letra !='t')&&(letra !='f'));
Comment: @DiogoMartins, qualquer letra diferente de "T" ou "F" vai para o default. Se você quer que fique repetindo até que a letra correta seja digitada, você pode usar um while.
Comment: @DiogoMartins se você tem outra dúvida, crie uma [nova pergunta](http://pt.stackoverflow.com/questions/ask). Não adianta nada (para a comunidade) você alterar o foco da pergunta a cada 5 minutos. Não leve a mal e bem-vindo, faça um [tour] para entender melhor como funciona o Stack Overflow.
Comment: O que eu queria era por exemplo: Escolha uma letra entre P ou B, caso o utilizador escolha a Letra C o sistemas diz que a letra esta incorrecta e volta a fazer a mesma pergunta
Comment: Entao como ficaria o codigo utilizando o while? E sim queria que fosse repetindo ate a letra correcta ser digitada
Comment: @DiogoMartins, editei a resposta
Comment: Quando eu digito a letra certa ele nao da return ao inicio, mas em vez disso fecha a janela
Comment: @DiogoMartins, quando você digitar a letra correta, nesse código ele sai do while, como não tem mais nada, o programa é encerrado. Basta você colocar no seu código o que quer que seja executado depois que for digitado a letra T ou F.
Comment: @DiogoMartins, melhorei o código para você entender melhor.
Comment: Ok muito obrigado! So mais uma questao estou a utilizar o seguinte para gerar uma letra random, mas o print nao me devolve nada: {
       int n = rand() % 26;
       char h = (char)(n + 65);
       printf("\n %c", h);

       }
Comment: @DiogoMartins, sobre a geração de letras aleatórias, só com esse código não é possível eu te dizer com precisão o que está acontecendo.


How to remove title field from content edit page?

Question: i want remove field title in any content type on drupal 7. i use module display suite and hidden title but when i add new content that "title is required .......................................... ". thank you for help.

i want remove title field in any content type.
Comment: Hi, in the future for the `Question` just ask your question. do not write "hi I have a question" ... of course you have a question, that's why you are writing here :D. Just ask it. I have editing your writing to make it more clear for readers.
Answer: You want to either:

Remove the title field completely using the Fields UI. See this documentation page on the Fields UI. If you really don't want a title then just remove the field from the content type.
Use the Automatic Nodetitle module to create a title from a Token and hide the title in Edit Forms.
If not a Node, use the Automatic Entity Label module to create a title and then hide it from users in the Edit forms.

In general most content types need a title. Titles are the Names we give content to find them using Search forms and pages.


How to get subject from gmail and put into a google doc or spreadsheet

Question: I am trying to automatically extract subject lines to a Google doc or spreadsheet.  I found a basic example but don't know how to make this work.

function processInbox() {
    // get all threads in inbox
    var threads = GmailApp.getInboxThreads();
    for (var i = 0; i < threads.length; i++) {
        // get all messages in a given thread
        var messages = threads[i].getMessages();
        // iterate over each message
        for (var j = 0; j < messages.length; j++) {
            // log message subject
            Logger.log(messages[j].getSubject());
        }
    }
}

Comment: This doesn't look like Java. Isn't it JavaScript?
Answer: This is Javascript, not Java.  The script above gathers all your messages into a list, which is the right first step, but it won't write it to the sheet.
After that you'll need to add an additional function to write it out.  If you're in a spreadsheet, you could use something like this.  I've modified the above function to put the subjects into an array instead of logging them into the console, and having it return that array.
function processInbox() {
    var threads = GmailApp.getInboxThreads();
    var subjects = [[]];

    for (var i = 0; i < threads.length; i++) {

        var messages = threads[i].getMessages();

        for (var j = 0; j < messages.length; j++) {

            subjects[j] = [messages[j].getSubject()];
        }
    }

    return subjects;
}

function writeOutSubjects() {

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheets()[0];

    var subjects = processInbox();
    var range = sheet.getRange(1,1,subjects.length,1);

    range.setValues(subjects);

};

Answer: You will need to use a method like setValue().  You need to get a reference to the spreadsheet, then the sheet to act upon, and then the range to set the value in.
Google Documentation


Defining Category of Adjunctions

Question: $\newcommand{A}{\mathcal{A}}
\newcommand{B}{\mathcal{B}}
\newcommand{C}{\mathcal{C}}
\newcommand{ADJ}{\mathsf{ADJ}}
\newcommand{id}{\mathrm{Id}}$Morphism between a pair of adjunctions $(F : \A \leftrightarrows \B : G)$ and
$(F' : \A' \leftrightarrows \B' : G')$ is a pair of functors $H : \A \to \A'$ and $F : \B \to \B'$ such that $FK = HF'$ and $GH = KG'$, and either
(I) $H(\eta_{(\cdot)}) = \eta_{H(\cdot)}' $, where $\eta$ and $\eta'$ are unit natural transforms corresponding to the adjunctions.
(II) $K(\epsilon_{(\cdot)}) = \epsilon'_{K(\cdot)}$, where $\epsilon$ and $\epsilon'$ are coint natural transforms corresponding to the adjunctions.
(III) for all $A \in \A, B \in \B,f : F(A) \to B$, it holds that $H(f^\top) = (Kf)^\top$, where by $(\cdot)^\top$ I denote transposition associated with both adjunctions.
Conditions (I),(II),(III) are equivalent as I proved in the exercise recently.
However it seems to me that, as adjunctions have morphisms, they should have their own category:
Consider category $\mathsf{ADJ}$ with objects being pairs of categories supplied each with an appropriate adjunction i. e. $(F : \A \leftrightarrows \B : G) \in \mathsf{ADJ}$ and morphism defined as above. Then, composition is defined by a pairwise functor composition, and identity is a pair of identity functors. Associativity of composition is easily seen from version (III) of definition.
So It seems that $\ADJ$ is a category. But in fact it is not as it contains itself in form $(\id : \ADJ \rightleftarrows \ADJ : \id) \in \ADJ$. Moreover every category $\C$ has a canonical representative $(\id : \C \rightleftarrows \C : \id) \in \ADJ$, which means that $\ADJ$ contains all categories in certain sense. Both of these are bas things for a set theoretical reasons, thus $\ADJ$ should not be defined as a category.
This situation is simillar to the idea of category of categories here so I see two pathways:
1) Restrict $\ADJ$ to small categories or locally small ones.
2) Define $\ADJ$ as a 2-category by introducing 'nutaral transfoms' as morphisms of morphims.
I personally prefer the latter solution.

Are categories of adjunctons used somewhere? If so, how are these categories defined?

P.S.
While writing this question I took liberty to define command \A -> $\mathcal{A}$, \B -> $\mathcal{B}$, \C -> $\mathcal{C}$, \ADJ -> $\mathsf{ADJ}$; \id ->$\mathrm{Id}$. You can use them in your answers and comments.
Comment: https://ncatlab.org/nlab/show/2-category+of+adjunctions
Comment: Working with a category of small categories isn't as restrictive as you might think; when necessary you can switch which universe of sets you are taking to be the universe of small sets. (assuming you take foundations with enough universes)
Comment: Remark that 2) is no solution to your set-theoretic issue.
Comment: @DerekElkins Thanks, This is interesting. As I understood In my context, underlying 2-category would be $\mathsf{CAT}$ with categories as object, Adjunctions (of categories) as horizontal arrows, and morphims of adjunctions (as defined above) as vertical arrows.
Comment: @Pece I understand that this is not a solution, as 1-skeleton of the category will contain itself. I understand that this is incorrect, that I was thinking about, is that If 0-skeleton of $\mathsf{SET}$ is not a set itself, why can't I have (In certain specific foundations) a 2-category those 1-skeleton is not a category. What I'm trying to Introduce here is some type of structure that are like categories, but not count as categories then you quantify statements other categories. If I could do something like this with k-skeletons of n-categories I would get something akin Russells's hierarchy.
Answer: (note: I had misread the construction in the OP when writing this)
You can't get away from the size issues; an easy way to see definition 2 doesn't help is that you can extract from it the paradoxical 1-category simply by taking its 0 and 1-cells.
It is standard to define Adj on the same 'level' as Cat; e.g. given a cardinal $\kappa$, if you are working with the 2-category $\mathbf{Cat}_\kappa$ of $\kappa$-small categories, functors, and natural transformations, then you would normally take $\mathbf{Adj}_\kappa$ to be the 2-category of $\kappa$-small categories, adjunctions, and natural transformations. Or if you are working with Cat as a 1-category, then you do the same with Adj.
As Derek Elkins points out in comments, Cat isn't special here; given any 2-category $\mathcal{C}$ you can construct the 2-category of adjunctions in $\mathcal{C}$.
Comment: I think it's not exactly the 2-category defined by the OP, rather it is the full subcategory on adjunctions of the vertical category of the double category $CAT$ (with functors as vertical, and profunctors as horizontal arrows).

Defining Category of Adjunctions


AngularJS: Filter ng-options not having specific values

Question: I want to filter on a select like so :
<select ng-model="test" ng-options="c as c.label group by c.type for c in columns
| filter:{c.type:'!field'} | filter:{c.type:'!map'}"></select>

EDIT : Adding the column model :
Columns = [
{
    name: "name",
    label: "Label",
    info: "Information displayed in help",
    type: "type",
    view: "html template",
    style: "min-width: 10em;",
    show: true
},
{
 ...
}
];

Columns is used for several things and to optimize my code I need it to be also in a Select, but without the entries whose type are 'field' nor 'map'
Yet, I get to choose from everything, even the entries which types are 'field' and 'map'.
Is there a clean way to do it ?
Comment: please post your model `columns`
Answer: AngularJS NOT Filter
<select ng-model="test" ng-options="c as c.label group by c.type for c in columns
    | filter:{ type : '!field' }
    | filter:{ type : '!map' }">
</select>

Fiddle
From the docs:
"...The predicate can be negated by prefixing the string with !."
"A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1"..."
Comment: Thanks this helped . Specifically the part about using the filter variable "type" as is . rather than c.type .


SQL Server 2012, erro ao executar consulta

Question: Boa tarde, pessoal
ao executar a consulta abaixo:
select PRO_Descricao, PED_Numero
from pedido p, item i, produto pr
where p.PED_Numero = i.PED_Numero
and i.PRO_Codigo = pr.PRO_Codigo
and PRO_Descricao >= 'SA'
and pro_descricao < 'SB'

aparece a seguinte mensagem no SQL server 2012:
Nome da coluna 'PED_Numero' ambíguo.

O que há de errado?
Answer: PED_Numero é uma coluna que existe em pedido e em item.
Para desfazer a ambiguidade, defina identificadores de tabela para as colunas e para as tabelas envolvidas:
select pr.PRO_Descricao, p.PED_Numero
from pedido p, item i, produto pr
where p.PED_Numero = i.PED_Numero
and i.PRO_Codigo = pr.PRO_Codigo
and pr.PRO_Descricao >= 'SA'
and pr.pro_descricao < 'SB'

Comment: Agradeço amigo, deu certo aqui.