Align text and image side to side with bootstrap

Question: How do i get the image to be centered aside the text & button? The image is on the left because i place float:left, but if i dont place it, the image is centered but the text goes below it. Using bootstrap 3.3.7

Some text heree

Title

Some text here

        <button>CTA</button>

CSS

Comment: I am a bit confused, Are you trying to put the image where the title is?
Comment: @WojtekT, yup.besides the text and button.
Answer: Your should use the bootstrap classes instead of your own css. Because they have handled a lot of cases and their css is stable. Here is pure bootstrap solution for you.
I have used another image, your image will fit well.
Note: Do let me know if you face any problem.

p{
    font-family:"Fjalla One", sans-serif !important;
    font-size: 20px;
}
h1{
  font-family: 'Knewave', cursive;
  font-size:40px;
  color:black;
  margin:0 !important;
  padding: 0!important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Some text heree

Title

Some text here

          <button>CTA</button>

Comment: Happy to help you.
Answer:

    .row img{
        width:300px;
        float:left;
        height:auto !important;
    }
    .container{
        text-align: center !important;
        width:100%;
    }
    .row{
        margin-top:0;
    }
    p{
        font-family:"Fjalla One", sans-serif !important;
        font-size: 20px;
    }
    h1{
    font-family: 'Knewave', cursive;
    font-size:40px;
    color:black;
    margin:0 !important;
    padding: 0!important;
    }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Some text heree

Title

Some text here

              <button>CTA</button>

This works for you... Bootstrap already has column classes.By applying them you can resolve the problem.
Answer:

Some text heree

Title

Some text here

           <button>CTA</button>

you should wrap your content to other div like col-md-8 or any class you want to.
There is two option for you

and other option is that bootstrap col automatically separate into two columns i.e side by side
Answer: To get the image in between the texts, you can just put the div between the
 tags or where ever you want to it then remove the float:left attribute be here is a example:

.row img{
    width:300px;
    height:auto !important;
}
.container{
    text-align: center !important;
    width:100%;
}
.row{
    margin-top:0;
}
p{
    font-family:"Fjalla One", sans-serif !important;
    font-size: 20px;
}
h1{
font-family: 'Knewave', cursive;
font-size:40px;
color:black;
margin:0 !important;
padding: 0!important;
}

Some text heree

Title

Some text here

        <button>CTA</button>

A better option would be to wrap your content additional info on wrap
  text
Answer: You just need to use display:flex; property to do this:-

.two-img{ display:flex;  justify-content: center;}

Answer: Not really sure if I understood correctly what you'd like to achive. If you just want to place an image where the title is, modify html to:

Some text heree

Some text here

        <button>CTA</button>

If that's not what you're trying to do, please provide more info about where exactly you'd like image to be.


beta-binomial as conjugate to hypergeometric

Question: According to the table of conjugate distributions on Wikipedia, the hypergeometric distribution has as conjugate prior a beta-binomial distribution, where the parameter of interest is "$M$, the number of target members." I interpret "target members" to mean, I am modeling as hypergeometric the number of blue balls in a sample from an urn containing $N$ total balls of which $M$ are blue, $N-M$ non-blue.
But then I cannot make sense of the claim of conjugacy. After the data is observed, say $b$ blue balls in the sample, then it is known that $M>b$. But a beta-binomial distribution is supported on $0,...,F$ (for some parameter $F$). So how can the posterior for $M$ also be beta-binomial?
Comment: @MossMurderer No, this is a bayesian setup.
Comment: I may be wrong but it looks to me like that there is a slight misunderstanding. Hypergeometric distribution describes the probability of drawing $k$ blue balls out of $n$ draws (without replacement) from an urn containing $N$ balls out of which $M$ are blue. It is not the probability distribution over $M$, the number of blue balls in the urn.
Answer: The problem with the Wikipedia article and the reference therein (Fink D., 1997) is that there is some key information missing.
Specifically, the given posterior is for $M-x$ (i.e. the number of target individuals in the population shifted by the number observed in the sample), not for $M$. Furthermore, the posterior parameter corresponding to the number of observations is missing and should be $N-n$ (i.e. the population size minus the sample size). These two corrections fixes the support problem that you correctly noticed, as shown below.
Suppose that $0 \leq X \leq n$ is the number of target
individuals in a sample of size $n$ from a population of size $N$ with
$0 \leq M \leq N$ total target individuals.
Then, $X \sim \text{HG}(n, M, N)$ with support in $[\max(0, n-N+M), \min(n, M)]$.
If $M \sim \text{BB}(N, \alpha, \beta)$ is the prior distribution of $M$, the posterior distribution for $M - x$ is also Beta-Binomial-distributed:
$$M - x\,|\,x,\alpha,\beta \sim \text{BB}(N-n, \alpha + x, \beta + n - x)$$
If you write the probability mass function for $M$ you will find @Tim's answer above.
As an illustration, for $N = 20$ and $n = 10$, let's assume a non-informative prior distribution for $M$ with $M \sim \text{BB}(N, .5, .5)$.
Suppose that we observe $x = 9$.
<code>library(extraDistr)
library(tidyverse)
N = 20
n = 10
a0 <- b0 <- .5
x <- 9
data.frame(
  m = 0:N
) %>%
  mutate(
    prior = dbbinom(m, size = N, alpha = a0, beta = b0),
    post = dbbinom(m-x, size = N-n, a0+x, b0+n-x)
  ) %>%
  gather(key, dens, -m) %>%
  ggplot(aes(m, dens, col = key)) +
  geom_line() +
  geom_point()
</code>

Created on 2018-10-10 by the reprex package (v0.2.1)
Note that the posterior support is correctly [x, N − n + x].

Dyer, D. and Pierce, R.L. (1993). On the Choice of the Prior
  Distribution in Hypergeometric Sampling. Communications in Statistics
  - Theory and Methods, 22(8), 2125-2146.
Answer: Hypergeometric distribution describes sampling without replacement from the urn containing $N$ balls, out of which $M \le N$ are target balls, let's say blue. The conjugate beta-binomial prior distribution leads to posterior distribution for unknown $M \in \{x,x+1,\dots,N-n+x\}$ in form
$$
f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x}
\frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-x)\,\Gamma(\alpha+\beta+n)}{\Gamma(\alpha+x)\,\Gamma(\beta+n-x)\,\Gamma(\alpha+\beta+N)}
$$
as described in

Dyer, D. and Pierce, R.L. (1993). On the Choice of the Prior
  Distribution in Hypergeometric Sampling. Communications in Statistics
  - Theory and Methods, 22(8), 2125-2146.
Comment: I agree it makes sense to have the prior distribution on $M$ be beta-binomial. What doesn't make sense to me is that the posterior is also beta-binomial (because of the different supports issue mentioned in the question).
Comment: @Hasse1987 I don't understand what do you mean, the support is $0,1,\dots,N$, where BB distribution is parametrized by $\alpha,\beta,N$, where $N$ is known population size.
Comment: But the posterior distribution of $M$ cannot have that support. After the data is observed you know there are at least $b$ target members. So the support of the posterior is contained on $b,\ldots,N,$ right?
Comment: @Hasse1987 *a priori* it has $0,\dots,N$ support, after you observe some data it gets centered on more realistic values.
Comment: Of course. The point is that those "more realistic values" preclude a beta-binomial distribution.
Comment: @Hasse1987 sorry, the description in Wikipedia is unclear and didn't have time to read it carefully, please check my edit, the reference I quote and https://stats.stackexchange.com/questions/269538/hypergeometric-distribution-when-k-is-unknown/269586#269586
Answer: As I cannot comment: the formula given by @Tom is not correct, the correct formula is :
$$
f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x}
\frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-M)\,\Gamma(\alpha+\beta+n)}{\Gamma(\alpha+x)\,\Gamma(\beta+n-x)\,\Gamma(\alpha+\beta+N)}
$$
The formula is also wrong in the reference:

Dyer, D. and Pierce, R.L. (1993). On the Choice of the Prior
Distribution in Hypergeometric Sampling. Communications in Statistics

Theory and Methods, 22(8), 2125-2146.

at p. 2131. It is clearly a typo because on the same page, few lines below, that formula (in its correct form) is used to derive equation (3.1.3)


Center of mass of semi-sphere

Question: I haven't calculated center of mass before and I'd like to know how I can do it in practise.
I want to find the center of mass of a semi-sphere. Could you explain me, step by step, what I have to do?
Many thanks
Comment: By "semi-sphere", do you mean half a spherical *solid* or half a spherical *shell*?
Comment: @dfeuer a spherical solid
Comment: @dfeuer: You could figure out the shell centre of mass from the solid centre of mass.
Comment: @copper.hat: you could, but it's best to be clear from the start, no?
Answer: We calculate the centre of mass of a half-ball of radius $1$.  Without loss of generality we may assume that the ball is made of material with density $1$.
Imagine that the ball is sitting on a table, flat side down.  By symmetry the centre of mass is on the vertical line through the centre of the ball. The only question is: How far up?
We will calculate the moment of the ball about the plane of the table, and divide by the mass of the half-ball.  By  a standard formula, the mass of the half-ball is $\dfrac{2\pi}{3}$.
Imagine now that the half-ball is an industrial ham. Imagine a very thin slice of that ham, sliced parallel to the table, but left in place.  Let the slice be taken from height $z$ to height $z+dz$, where $dz$ is extremely small.  The slice is almost a cylinder of very small height $dz$.
We first calculate the radius $r=r(z)$ of the slice. By the Pythagorean Theorem, we have $r^2+z^2=1$, so $r=\sqrt{1-z^2}$.
Thus the area of the slice is $\pi r^2=\pi(1-z^2)$.  The thickness is $dz$, so the volume, and therefore the mass, of the slice is approximately $\pi (1-z^2)\,dz$.
The slice is at perpendicular distance $z$ from the table. So the moment of the slice about the plane of the table is approximately $\pi (1-z^2)(z)\,dz$.
"Add up" (integrate) from $z=0$ and $z=1$. The full moment of the ball is
$$\int_0^1 \pi (1-z^2)(z)\,dz.$$
Calculate. We get $\dfrac{\pi}{4}$.
Finally, divide by the mass $\dfrac{2\pi}{3}$. We get $\dfrac{3}{8}$.
For a ball of radius $R$, just multiply by $R$. The centre of mass is $\dfrac{3 R}{8}$ above the centre of the half-ball.
Comment: Thanks, it would be nice to have one glitch-free post. Maybe next year.
Comment: You are welcome. To locate the center of mass in $3$-space, we have to find the moments about $3$ planes. If we are working with coordinates, the usual choices are the $x$-$y$ plane, the $y$-$z$ plane, and the $x$-$z$ plane. But in our half-ball example, *symmetry* tells us that the centre of mass is on a certain line. So our task is much simplified: we only need the moment about any plane parallel to the base. Might as well use **the** plane that contains the base. The description with slices of infinitesimal thickness parallel to the plane is very useful for the intuition. (More)
Comment: (Cont) Reasoning with slices of infinitesimal thickness can be replaced by more formal language. As a side remark, note that our calculation was needed for only one coordinate of the centroid. Symmetry took care of two,  so symmetry was the more powerful tool.
Comment: Yes, that's right.
Comment: Anything non-trivial will not be glitch-free :-).
Comment: I'm so grateful for your answer! It is written with simple language and lets you feel the kind aspects of Math :) Just a question (let's see if I have understood the general proceeding!): an infinitesimal moment is given by area of the infinitesimal slice*distance of the infinitesimal slice to the plane; then I have to integrate and divide for the total mass of the solid. Is it right? And I have to choose the plane so that I can have the most comfortable situation. Is it ok? many thanks again!!
Comment: Each moment calculated relating to a plane and divided for the total mass gives us one of the three coordinates of the center of mass, is it right?
Answer: Let $f(x) = \sqrt{r^2-x^2}$ and model the hemisphere as $H=\{(x,y) | x \in [0,r], \, |y| \le f(x) \}$.
Then compute $\overline{x} = \frac{\int_0^r 2 \pi xf(x)^2 dx}{\int_0^r 2 \pi f(x)^2 dx}$.
These integrals are straightforward to evaluate:
$\int_0^r 2 \pi xf(x)^2 dx = 2 \pi \int_0^r x ( r^2-x^2) dx =
2 \pi \frac{r^4}{4}$.
$\int_0^r 2 \pi f(x)^2 dx = 2 \pi \int_0^r ( r^2-x^2) dx =
2 \pi \frac{2 r^3}{3}$.
$\overline{x} = \frac{3}{8} r$.
Comment: @RonGordon Many thanks for your tolerance!
Comment: This is homework. Evaluate the integral above.
Comment: @copper.hat: nothing in the OP's question signals any familiarity with integrals or even calculus.  On the other hand, center-of-mass questions are straightforward enough to be asked by those without sufficient knowledge/sophistication.  You may wish to show your work to the OP in more detail.
Comment: I haven't worked with similar things before. Could you show me, step by step, the entire proceeding? (I'm not a matematician!)
Comment: This isn't an assignment (I don't go to school!). I'd want to understand how I have to proceed in similar cases. I said that I want to calculate the center of mass of a hemispere because I have started from this object. If you don't believe me, you can show me the proceeding step by step using another solid.. please, choose the solid that you prefer. I don't know the mathematical symbolism that you have used and I haven't "modelled" anything before.
Comment: Evaluating the above integrals is pretty straightforward. What exactly are you having a problem with? If there is a specific problem, I can help, but I am not going to provide basic material than can be found in most relevant textbooks.
Comment: @RonGordon: Can you elaborate a little please? Evaluating the centre of gravity of such an object without calculus is a lot of work. If the OP has calculus, the integrals are pretty straightforward (and I have evaluated them). Explaining the concept of centre of gravity is more physics/mechanics...
Comment: @copper.hat: Andres above did what I thought was needed.
Answer: 1- Assume the flat surface is located on a horizontal plane with the bowl (semi-sphere) below)
2- X = left/right
3- Z = frt/back
4- Y = vertical offset
Both X & Z coordinates will be on the axis of rotation, i.e. at 0 offset. The center of mass will be .1875 * D from the flat surface of the semi-sphere.
RJ
Comment: Please consider formatting your answer in LateX properly.
Answer: $a > 0$: radius.
\begin{align}
\vec{r}_{\rm cm}
&\equiv
{1 \over V}\int_{V}\vec{r}\,{\rm d}V
=
{1 \over \left(4\pi a^{3}/3\right)/2}\int_{V}{1 \over 2}\nabla r^{2}\,{\rm d}V
=
{3 \over 4\pi a^{3}}\int_{S}r^{2}\,\hat{r}\,{\rm d}S
\\[3mm]&=
{3 \over 4\pi a^{3}}\left[%
\int_{\Huge\frown}a^{2}\,{z \over a}\,\hat{z}\,{\rm d}S\
+\
\int_{\Huge\_}\left(x^{2} + y^{2}\right)\left(-\hat{z}\right)\,{\rm d}x\,{\rm d}y
\right]
\\[3mm]&=
{3 \over 4\pi a^{3}}\,\hat{z}\left\lbrack%
a^{2}\int_{0}^{2\pi}
\int_{0}^{\pi/2}\cos\left(\theta\right)\
a^{2}\sin\left(\theta\right)\,{\rm d}\theta\,{\rm d}\phi\
-\
\int_{0}^{a}\rho^{3}\,{\rm d}\rho\int_{0}^{2\pi}{\rm d}\phi
\right]
\end{align}
$$
\begin{array}{|c|}\hline\\
\color{#ff0000}{\large\quad%
\vec{r}_{\rm cm} = {3 \over 8}\,a\;\hat{z}
\quad}
\\ \\ \hline
\end{array}
$$
Answer: Archimedes might have done the calculation like this: he knew the volume of the half ball equals the difference between that of a circumscribed cylinder and an inverted cone inscribed in that cylinder, i.e. 2π/3 = π - π/3, because the area of a slice of the half ball is the difference of the areas of slices at the same height of the other two figures, again by Pythagoras. (This means the moments of the slices are related the same way.) He also knew the center of mass of the cylinder is at height 1/2 and that of the cone at 3/4.  Thus, if the center of mass of the half ball is at height t, the total moments are related by (2π/3)t = π(1/2) - (π/3)(3/4), so t = 3/8.

Center of mass of semi-sphere


$(x-4)^2+8|x-4|+15=0$

Question:
The sum of the roots of the equation $(x-4)^2+8|x-4|+15=0$ is

My attempt: Let $|x-4|=y$. So, the equation becomes $y^2+8y+15=0$. So, $y=-3,-5$. Both values should be rejected as $|x-4|$ cannot be negative. But the answer has been given as $16$.
Comment: I think you're working too hard. $(x-4)^2\ge0$, $8|x-4|\ge0$, $15>0$, so the equation can't have any solutions. If someone has asked you to solve this problem, I advise you to ask them to clarify. (But first check to see whether you have copied it down correctly.)
Comment: I have copied the statement correctly. But I see your point, it should be clear at the beginning itself that the equation has no solutions.
Comment: Your answer is correct as well. As stated it has no solutions. You can plug in $x=16$ and see that it doesn't solve the equation.
Comment: @quarague, $16$ is the sum of roots.
Answer: Since the answer has been given as $16$, I think that the equation should read
$$(x-4)^2-8|x-4|+15=0.$$
Now let $y:=|x-4|$ and proceed as above.
Comment: Thanks @Fred. I'll correct the statement in the book.

$(x-4)^2+8|x-4|+15=0$


What does a Clavinet "Register" mean?

Question: I've got a keyboard (Korg Krome 88) that has a few clavinet sounds. They're named "Clav Register AC", but also "AD", "BC" and "BD". Trying to figure out what these things mean. I can hear the difference, but don't quite get it.
Best I've found is this description, but I still don't get the single / parallel pickup business.
Answer: It's very much like the pick-up configuration on electric guitars.
A clavinet uses pick-ups that work in a similar way .Imagine a guitar with two pups. They are probably exactly the same as each other, but because of their positions, they produce different tones.A single coil pup will produce a thinner sound than a humbucker. When pups are in series (electrically) they produce a different sound from when they are in parallel.Or - in and out of phase.
So the AD, BC etc. are different configurations of the pups, changing the output sound.  A little academic as when you find a sound that's good, you don't need to know what pup is switched, only that it makes the sound you like. Sort of 'tone controls' on switches. Obviously rotary pots on your equipment can still be used to adjust tone more.
Comment: @MikeHildner: one of the settings actually has the pickups _out of phase_, which cancels a lot of the fundamental frequency so it sounds kind of almost an octave higher... but not quite. Read "register" like in different organ registers of the same pitch, one is supposed to sound like recorders, one like oboe etc..
Comment: @Mike - you'd think so, but it's not so.Timbre/tone change yes.
Comment: Thanks. So nothing to do with pitch? To me it sounds like the timbre is changing, but not the pitch. When I see "register", I'm thinking it would mean an octave shift or similar.

What does a Clavinet "Register" mean?


In Eclipse RCP Application, how can i push SWT code to launch a shell to open a Dialog box to get the File Name to the String varibale say fileName

Question: In Eclipse RCP Application, how can i achieve my view to launch a shell to open a Dialog box to get the FileName to the String varibale say fileName?
public class View extends ViewPart {
    public void createPartControl(Composite parent) {
         Display display = new Display();
         final Shell shell = new Shell(display);

         FileDialog dlg = new FileDialog(shell, SWT.OPEN);
         String fileName = dlg.open();
         if (fileName != null) {
              System.out.println(fileName);
         }
    .....
   }
}

Imported Shell and Display Packages already..Returns error at launch..
Answer: In an Eclipse RCP you never create a new Display. Only one display object is allowed and the RCP has already created it.
All you need to do here is open the file dialog with the current shell as the parent:
public void createPartControl(Composite parent) {

    FileDialog dlg = new FileDialog(parent.getShell(), SWT.OPEN);
    String fileName = dlg.open();
    if (fileName != null) {
        System.out.println(fileName);
    }
}

Comment: Thankyou so much, it worked. I needed it to open image file location and store it to the string.


Aplicar o CSS de um filho de elemento A em outro elemento B

Question: É possível de alguma forma usar regras de CSS aplicadas a #elemento > .filho num outro elemento #dots?
#elemento > .filho{...}

No caso eu precisaria que

 recebesse o estilo da classe filho.

O que eu eu tenho é dots fora da herança, e queria aplicar a ele o estilo filho.

Comment: Você não pode simplesmente fazer: `#elemento > .filho, #dots {...}` ?
Answer: Para isso você pode usar o plugin copyCss, exemplo:

(function($){

 $.fn.getStyles = function(only, except) {

  // the map to return with requested styles and values as KVP
  var product = {};

  // the style object from the DOM element we need to iterate through
  var style;

  // recycle the name of the style attribute
  var name;

  // if it's a limited list, no need to run through the entire style object
  if (only && only instanceof Array) {

   for (var i = 0, l = only.length; i < l; i++) {
    // since we have the name already, just return via built-in .css method
    name = only[i];
    product[name] = this.css(name);
   }

  } else {

   // prevent from empty selector
   if (this.length) {

    // otherwise, we need to get everything
    var dom = this.get(0);

    // standards
    if (window.getComputedStyle) {

     // convenience methods to turn css case ('background-image') to camel ('backgroundImage')
     var pattern = /\-([a-z])/g;
     var uc = function (a, b) {
       return b.toUpperCase();
     };
     var camelize = function(string){
      return string.replace(pattern, uc);
     };

     // make sure we're getting a good reference
     if (style = window.getComputedStyle(dom, null)) {
      var camel, value;
      // opera doesn't give back style.length - use truthy since a 0 length may as well be skipped anyways
      if (style.length) {
       for (var i = 0, l = style.length; i < l; i++) {
        name = style[i];
        camel = camelize(name);
        value = style.getPropertyValue(name);
        product[camel] = value;
       }
      } else {
       // opera
       for (name in style) {
        camel = camelize(name);
        value = style.getPropertyValue(name) || style[name];
        product[camel] = value;
       }
      }
     }
    }
    // IE - first try currentStyle, then normal style object - don't bother with runtimeStyle
    else if (style = dom.currentStyle) {
     for (name in style) {
      product[name] = style[name];
     }
    }
    else if (style = dom.style) {
     for (name in style) {
      if (typeof style[name] != 'function') {
       product[name] = style[name];
      }
     }
    }
   }
  }

  // remove any styles specified...
  // be careful on blacklist - sometimes vendor-specific values aren't obvious but will be visible...  e.g., excepting 'color' will still let '-webkit-text-fill-color' through, which will in fact color the text
  if (except && except instanceof Array) {
   for (var i = 0, l = except.length; i < l; i++) {
    name = except[i];
    delete product[name];
   }
  }

  // one way out so we can process blacklist in one spot
  return product;

 };

 // sugar - source is the selector, dom element or jQuery instance to copy from - only and except are optional
 $.fn.copyCSS = function(source, only, except) {
  var styles = $(source).getStyles(only, except);
  this.css(styles);

  return this;
 };

})(jQuery);

$(document).ready(function(){
  $('button').click(function(){
    $("#dots").copyCSS('.filho');
  });
});
#elemento > .filho{
  color:red;
  background-color:yellow;
}

filho

Dots

<button type="button">
Aplicar
</button>

OBS: O COLOQUEI O CONTEÚDO DO PLUGIN NA RESPOSTA POIS NÃO ENCONTREI O CDN
Answer: Se sua pergunta estiver certa é só fazer isso que o id dots receberá o estilo da classe filho.

$( "#dots" ).addClass( "outra" );
.filho, .outra {
 color:red;
}

filho

dots

Comment: Isso eu estou ciente (rs), o problema é que não quero / não posso jogar `.filho` para fora.
Comment: O *css* precisa estar assim: `#elemento > .filho{color:red}`
Comment: Não pode aplicar o mesmo Id duas vezes. Id é único.
Comment: Depois ve se a edição atende.


Disabling 'ping' response on Linux VPS

Question: I have a openvz linux vps and am trying to disable requests to 'ping' to my VPS.
How can i do this?
Comment: I hope you're not doing this because of "security" - ICMP echo is harmless, useful as a diagnostic tool and as far as DDoS attack vectors go is one of the least effective.
Comment: On top, ICMP has a usefull side feature so you are efficiently sabotaging parts of the IP stack. You basically disable PathMTU functionality.
Answer: You can use iptables rules to achieve this:
<code>iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
</code>
Answer: Add the following line to your init script for the network (the name depends on the distribution you use):
echo 1 >/proc/sys/net/ipv4/icmp_echo_ignore_all
This disables ping responses.
To reenable, use the following command:
echo 0 >/proc/sys/net/ipv4/icmp_echo_ignore_all
To make this permanent set the following into /etc/sysctl.conf (if you have such a file)
net.ipv4.conf.icmp_echo_ignore_all = 1
Answer: Simplest method of disabling ping response is to add an entry in /etc/sysctl.conf file. If the Iptables flushes or stop server will start responding to ping responses again. I suggest the following entry in your /etc/sysctl.conf file

net.ipv4.icmp_echo_ignore_all = 1

this will tell kernel to not respond any ping response, after this run sysctl -p on shell to implement the changes without reboot.
For more info please refer: http://www.trickylinux.net/disable-ping-response-linux/
Answer: You need iptables (or something similar) that blocks ICMP.
http://www.cyberciti.biz/tips/linux-iptables-9-allow-icmp-ping.html

Disabling 'ping' response on Linux VPS


Relationship between very ample divisors and hyperplane sections

Question: This question is based on a line in the proof of corollary IV.3.3 in Hartshorne's Algebraic Geometry.
The first line of the proof goes: "if $D$ is an ample divisor (on a curve $X$), then some multiple is very ample, so $nD\sim H$, where $H$ is a hyperplane section for a projective embedding."
This line suggests that there is some obvious relationship between hyperplane sections and very ample divisors, namely that any very ample divisor is linearly equivalent to a hyperplane section.
Why is this true? Is this done somewhere else in Hartshorne? (I've been looking for a long time, but I can't seem to find it anywhere else!)
Comment: The very ampleness stuff is back in Chapter II. The way a very ample sheaf is defined is that we can evaluate the global sections generating the sheaf to give projective coordinates for a closed immersion into projective space. Under that scheme, the hyperplane sections are precisely the elements of the very ample linear system.
Comment: Ok, thanks. I think I got it now!
Answer: Look at Chapter II Theorem 7.1, $\phi:X \longrightarrow P^n$ a very ample line bundle $\phi^*(O(1))$ is the pull back of O(1) bundle on $P^n$. But $O(1)$ is a hyperplance $H$, so in the image of $\phi$, the very ample divisor is the intersection of $X\cap H$
Answer: If $D$ is ample ($\Longleftrightarrow \deg(D)>0$) on a curve $X$, then $nD$ is very ample for a large $n$ and gives enough global sections to define an immersion $i: X \longrightarrow \mathbb{P}^n$ s.t. $\mathcal{O}_X(nD) \cong i^*\mathcal{O}_{\mathbb{P}^n}(1)$.
If your $X$ is proper in the first place then $i$ is a closed immersion.
Effective divisors on $\mathbb{P}^n$ corresponding to the invertible sheaf $\mathcal{O}_{\mathbb{P}^n}(1)$ (or say, "the complete linear system of $\mathcal{O}_{\mathbb{P}^n}(1)$") consists exactly of hyperplanes in $\mathbb{P}^n$.
Suppose $\xi_1,\dots,\xi_r$ are generic points of $X$ and $H$ is a hyperplane in $\mathbb{P}^n$ NOT containing any of them (so that "the pullback of $H$ by $i$ is defined"), then $i^*H = X \cap H$ is an effective divisor on $X$. Such divisors are called "hyperplane sections" and there are plenty of them.
Now $i^*H$ is a global section of $i^*\mathcal{O}_{\mathbb{P}^n}(1) \cong \mathcal{O}_X(nD)$, then of course $i^*H \sim nD$.


How to avoid multiple error at same time in parsley.js?

Question: How to avoid multiple error at same time in parsley.js? For example I want to validate the field with following condition email and require, min length ? but want to display one error at a time?
Comment: Please share the idea  .. thank for your response
Comment: This can be done through a simple if - else if structure
Answer: probably this would be of some help.
https://github.com/guillaumepotier/Parsley.js/issues/189
The basic idea was to get all messages in a list. Hide all and show only the one required out of it.


What is the image of $f:A\to B\times C\cup\{\emptyset\}$?

Question: Let $f:A\to B\times C\cup\{\emptyset\}$ be any function. My question is simple. Given some $a\in A$, is this function $f:A\to B\times C\cup\{\emptyset\}$ returning either a pair $(a,b)\in A\times B$ or the empty set; or is this function returning a pair $(a,b)\in A\times B\cup\{\emptyset\}$, where $b$ could be the empty set?
Comment: It is returning a pair $(b,c) \in B \times C$ or the empty set.
Comment: I think it's ambiguous, it depends on whether it's $(B\times C)\cup \{\emptyset\}$ or $B\times (C\cup\{\emptyset\})$.
Comment: @Héctor Yes, that would be reasonable. If you're reading this somewhere, you might be able to figure out what the author means from the context.
Comment: **Thank you**. Would you post it as an answer, along with some explanation of your liking?
Comment: So, to avoid confusion you'd write $(B\times C)\cup\{\emptyset\}$ or $B\times (C\cup\{\emptyset\}$ depending on what I want?
Answer: So the function is written as $f: A \to B \times C \cup \{\emptyset\}$ which means that the range of values is $B \times C \cup \{\emptyset\}$ (because that is the set "right of the arrow"). Now this set of possible values is a union of two sets meaning that the output $f(a)$ for some $a$ is in either one of those two sets (normally it could also be an element of both of the sets in the union, but here the two sets $B \times C$ and $\{\emptyset\}$ are disjoint). Therefore $f(a)$ is going to give you either a pair $(b,c) \in B \times C$ or a value in the set $\{\emptyset\}$ which can only be $f(a) = \emptyset$.


Determine if an asp:Placeholder is visible Jquery

Question: I have a program with twoasp:Placeholders with runat = "server". Only one will be visible at a time. I want to determine which on is through javasacript and jquery. I have tried a few commands but none have worked. So far I have tried (these are all in an if statement:
if ($'#showClosest').visible)
if ($'#showClosest').style.visibility)
if ($'#showClosest').css.visible)
if ($'#showClosest').css.visibility)

None of them have worked/returned true, even when the place holder is visible.
Is there a way to determine if the placeholder is visible?
I need to do this through placeholders to. The info I get from the pageload will determine what is visible and what is not.
EDIT:
Here are the placeholders:
<asp:PlaceHolder ID = "showClosest" runat = "server">
<asp:PlaceHolder ID = "showSelectedInformation" runat = "server">

and here is how I set the visibilities (page load):
if (Request.Params.AllKeys.Contains(src.Config.Title))
{
     //Code

     //Make correct divs visible
     showSelectedInformation.Visible = true;
     showClosest.Visible = false;

 }else{
     //Make sure correct divs are visible
     showSelectedInformation.Visible = false;
     showClosest.Visible = true;
 }

Comment: Please show us the corresponding mark-up. Placeholders won't be rendered as such, is `#placeHolder` a specific tag you've declared on the type taking over the placeholder? Overall, insufficient data.
Comment: Sorry about that. I edited it to show more code. Hopefully that should help
Answer: In answer to your question to  @Mr. Disappointment, yes if you add a div inside your placeholder you can check for it. It will only be in the page markup when the placeholder is visible.
<asp:PlaceHolder runat="server" ID="myPlaceHolder">

</asp:PlaceHolder>

Then in your JavaScript you just check if the element exists.
var placeholderVisible = ($('#foo').length > 0);

Answer: The answer can be exceptionally simple in comparison to some given.
Go from this:
<asp:PlaceHolder ID = "showClosest" runat = "server">
<asp:PlaceHolder ID = "showSelectedInformation" runat = "server">

to this:

Now the javascript and C# that you already have will work without modification, but note that referencing IDs in your javascript from controls that are set to runat="server" require a (.NET 4.0 only) static ID rendering mode.
Oh, and make sure your jQuery looks like this:
if ($'#showClosest').is(':visible'))

Comment: A possibility, but by that reasoning you could use `asp:Panel`.
Comment: I don't see your reasoning.  By yours, one could use _anything_.  .NET controls incur unnecessary overhead and I will always opt to have complete control over what markup gets rendered.  Thus, I stick with tags I can actually see and when necessary will set them to `runat='server'` to change their visibility.  If your logic is that you don't want to put the additional DIV on the page,  I think it's a valid concern, but the benefits of not having duplicate containers or wonky, unclear stuff going on is well worth it.
Comment: @Adam: The fact you use `runat="server"` essentially adds the overhead of it being a .NET control and a `Panel` renders to `div` so my _reasoning_ would be to keep the project .NETified.
Comment: It's true that it's not as good as a plain old HTML element, but the overhead incurred from a HTMLControl is less than a normal .NET control.  There's events that don't get fired, properties that don't exist, etc.  It's a more lightweight control.  Plus, regardless of the overhead, I value control over my markup and don't trust Microsoft to make it not be trash.  All of _that_ being said, the case is valid that if he does this nowhere else and it'd create a weird inconsistency, using it might not be worth the benefits.
Comment: See this link for more info: http://msdn.microsoft.com/en-us/library/zsyt68f1.aspx  You'll note that they explicitly call out that .NET Controls have a bunch more features (which means overhead) and state that you lose a one-to-one mapping between control and rendered HTML tags.
Comment: @Adam Fair enough, I'll take your word on the link content, it's not that I'm unaware, just not to concerned with the negligible overhead in this very instance. So long as the OP can get a working solution.
Comment: I'll agree to that!  It's negligible in the end.  My case is more for the "control" side of things.
Answer: OK - Javascript and jQuery won't work directly with an ASP.NET PlaceHolder control. This is because such a control is server-side only, and doesn't get rendered directly to the client but rather only what is either within it, or overriding it, so:
<asp:PlaceHolder runat="server" ID="myPlaceHolder">
    ???????????
</asp:PlaceHolder>

Is output as:
"

   ???????????

"

Spaces, and all. Therefore, the identifier you use in jQuery ($'#placeHolder') has no standing here as it doesn't identify anything. So, the short answer goes like this:
You can't determine directly, using jQuery, whether or not the PlaceHolder.
You might want to take some level of interest in @Tom's answer and he seems to have provided a script / client-side solution, albeit venturing away from the languages starting with j. ;)
Comment: Yea I was starting to get that feeling. Is there a work around to this? Say I had a div in the placeholder  is there a way I could attempt to get that id and determine what is visible that way ( if($('#foo').visible) or something like that)? Or would I run into issues when that placeholder is not visible because the div does not exist?
Comment: I'm no expert with jQuery so it would take a little experimenting on my behalf in order to definitively answer your comments, and also at work right now - however, I don't mind doing so at all, and if you don't have an answer by the time I get a chance to do so, then I certainly will and let you know. But, I would say look into how to determine if the `($'#id')` construct returns a known instance, or not.
Comment: You can definitely do that (have a nested DIV) and indeed someone else suggested that, but you _might_ want to check out my answer below and avoid all of this....
Answer: Easiest way is to do it on page generation.  On your ASPX page have that Javascript:

Then in your code behind once you have processed the page, do:
public string PlaceHolderVisibility;

... snip ....

if(SomePlaceholder.Visible)
    PlaceHolderVisibility= "true";
else
    PlaceHolderVisibility= "false";

Something like that anyway.  Note that Javascript and ASP/c# process bools slightly differently in different case so be aware of that.
Then you can simply call on the IsVisible variable when you want to know if the panel is visible or not.
With pure Jquery and none of the above solution, it's going to be hard as PlaceHolder doesn't actually render anything to the DOM.  You would need an element rendered inside it that acts as a flag, but you will have to deal with instances when it isn't there/can't be found, and when it is.  Can be hard to manage.
Comment: Bit of a harsh downvote whoever that was, if you explain why I'd appreciate it so I can make my answers better in the future.
Comment: I agree, a bit harsh (don't look at me, but maybe I caused it?).  This is true that it'll be True.  It's merely that whenever I see variables set to boolean values that are really strings, especially when it's in an `If` statement alarms go off all over the place.  Doing `SomePlaceholder.Visible.ToString().ToLower()` is well worth not having to do a property, etc.
Comment: I don't know why this got a down vote. I did it and the problem was fixed
Comment: Why wouldn't you just do `var IsVisible = <%=SomePlaceholder.Visible%>` and forget the whole property and wonky if/else statement (that uses strings for some reason)
Comment: @Adam, because ASP.net will render it as True I think, and Javascript will throw an error with that, it needs to read as true.  You can lowercase it and tostring it etc, but I just showed it this way for simplicity.
Comment: @Adam yeah you are right I probably could of written it better, `<%=SomePlaceholder.Visible.ToString().ToLower()%> is probably better
Comment: Might be worthwhile to edit your post just for future people?
Comment: @SsRide360: I think the downvote was probably a result of what someone considered to be an excessive amount of code to return a boolean that could already be accessed declaratively.  Harsh if you ask me, but if you're doing it this way you can simply do `SomePlaceholder.Visible.ToString().ToLower()` as @Adam Terlson suggested.  If you want to use a property then have a look at [my suggestion](http://stackoverflow.com/questions/5665012/determine-if-an-aspplaceholder-is-visible-jquery/5666061#5666061).
Answer: Have you tried this one?
if (jQuery('#showClosest').is(':visible')) {
Comment: This wont work as the Placeholder control doesn't render to any HTML
Comment: ha, ok, sorry for this. So you just have to test the length of the jQuery selector as @daniellmb stated
Answer: Following on from @Tom Gullen's harshly-downvoted answer, if your requirement is to determine which of the placeholders on the page is visible and there will only be one visible at a time, then you can use a property to return the ID of the visible one:
public string VisiblePlaceHolderID
{
    get
    {
        return this.Controls.OfType<PlaceHolder>().FirstOrDefault(p => p.Visible == true).ClientID;
    }
}

This will return the ID of the first placeholder on the page that has Visible="true", which you can then use directly in your JavaScript, something like this:
alert("<%= this.VisiblePlaceHolderID %>");


Can I return the value of document.getelementbyid inside a document.setcookie?

Question: <input type=button value='Do Stuff' onClick='document.cookie = "Note_<% Response.Write(arrTest(0,i)) %> = ' + (Document.getElementById("StuffTest<% Response.Write(arrTest(0,i)) %>").value) + '"'>

What I'm trying to do here is when the user hits the button, I want a cookie created with the values: Note_(value of arrTest) = (Value of the text box).
The code below works just fine:
<input type=button value='Do Stuff' onClick='document.cookie = "Note_<% Response.Write(arrTest(0,i)) %> = Awesome!"'>

It creates a cookie with the value of: Note_(value of arrTest) = Awesome!
What have I done wrong to get the value of my text box into the cookie?  I'm assuming it has to do with all those confusing single/double quotes, so I think I've just got typo-blindness, but part of me thinks I can't actually do what I'm trying to do here.
Any thoughts?
Answer: document.getElementById has document in all lower case. Your code example uses Document (with a capital D), which will fail.
Separately, your quotes such in the onClick attribute are not quite right. It's best to avoid putting any significant code in those attributes. Instead, define and call a function, like this:
<input type=button
       value='Do Stuff'
       onClick='setCookie("<% Response.Write(arrTest(0,i)) %>);'>

...where the function (inside a


Disable https to http redirect

Question: My site is using HTTPS only.
I allow using BBCodes to show images. Users are placing images like "https://imagehoster.net/img.png" and the imagehoster is using a redirect so the browser loads it via HTTP "http://imagehoster.net/img.png". This makes the browser showing annoying mixed content warnings. Is there a way to prevent this?
Answer: Short: NO
Long:
the have no really web server listening to ssl.
in fact, there is only a firewall/proxy which sends a http locate to the browser.
You can't intercept that request. even if you could, where to redirect to?
they don't provide a ssl server, because it takes to much resources for encryption or it takes to much traffic, because proxy#s can't cache.
An idea to solve that problem:
detect those links, download them and store a copy on your server.
replace the link. maybe you need only to store a preview. if the click on it redirect to the original link on a new browser window.

Disable https to http redirect


How can I apply the Neyman-Pearson Lemma for $f(x|\theta)=\frac{1}{2\theta}\exp[-|x|/\theta]$?

Question: Let $X_1,\cdots,X_n$ be a random sample from:
$$f(x|\theta)=\frac{1}{2\theta}\exp[-|x|/\theta]
\quad \quad \quad x \in \mathbb{R},$$
where $\theta>0$ is unknown. How can I find an MP size $\alpha$ test for $H_0:\theta=\theta_0$ versus $H_1:\theta=\theta_1$ when $\theta_1 < \theta_0$ are both known?

My working: By NPL, our MP level size $\alpha$ test is given by:
$$\phi(X)=\mathbb{I} \Bigg(\frac{f(\mathbf{x}|\theta_1)}{f(\mathbf{x}|\theta_0)}>k \Bigg),$$
where $k$ is some positive constant.  I then have:
$\frac{f(\mathbf{x}|\theta_1)}{f(\mathbf{x}|\theta_0)}=\exp[-\sum^n_{i=1}|x_i|(\frac{1}{\theta_1}-\frac{1}{\theta_0})]> k'$
$\implies-\sum^n_{i=1}|x_i|(\frac{1}{\theta_1}-\frac{1}{\theta_0})> k''$
$\implies \sum|x_i|<k'''$, where $\alpha=P_{\theta_0}(\sum|x_i|<k''')$
To finish solving this problem, I need to solve for $k'''$, but to do this, I would need to know the distribution of $\sum|x_i|$. However, I am not able to find this distribution, so how would I complete this problem?

Updated working: Let $Y =|X_i|$. Then, $f_Y(y)=f_x(-y)+f_x(y)=\frac{1}{\theta}e^{-y/\theta}, y > 0$
So, $Y_i=|X_i| \sim \text{Exp}(\theta) \implies \sum|X_i| \sim \text{Gamma}(n,\theta)$
Therefore, $\alpha = P_{\theta_0}(\sum|X_i|<k)=\int_k^\infty \frac{1}{\Gamma(n)\theta^n}y^{n-1}e^{-y/\theta}dy$.
Let $z=y/\theta, dy=\theta dz$. Then, we have $\frac{1}{\Gamma(n)}\int^\infty_{k/\theta}z^{n-1}e^{-z}dz=\frac{1}{\Gamma(n)}[\int^\infty_0z^{n-1}e^{-z}dz-\int^{k/\theta}_0z^{n-1}e^{-z}dz]=\frac{1}{\Gamma(n)}[\Gamma(z)-\int^{k/\theta}_0z^{n-1}e^{-z}dz]$
How would I evaluate the remaining integral?

More working: I noticed that my "updated work" section actually has a flaw in it, but I still cannot integrate. After StubbornAtom's suggestion, I tried the Chi-Squared route.
So if $\sum|X_i| \sim \text{Gamma(}n,\theta)$, then we know $\frac{2}{n}\sum|X_i| \sim \chi^n_{2\theta}.$ So,
$\sum|X_i|<k''' \implies \frac{2}{n}\sum|X_i| < c'$
So, $\alpha = P_{\theta_0}(\frac{2}{n}\sum|X_i|<c')=\int_0^{c'} \frac{1}{\Gamma(\theta)2^\theta}y^{\theta-1}e^{-y/2}dy$.
It is at this point that I arrive to the same problem as before: I cannot evaluate this integral.
Comment: This would be apparent once you find the distribution of $|X|$.
Comment: I would transform to chi-square and get $k$ in terms of  chi-square fractiles.
Comment: $\frac{2}{\theta}\sum |X_i|\sim \chi^2_{2n}$. So if your rejection region is $T=\sum |X_i|\frac2{\theta_0}c)=1-\alpha$. This gives $\frac2{\theta_0}c=\chi^2_{1-\alpha,2n}$. There is no integration to be done.
Comment: @StubbornAtom oh I see. So I should convert the inequality involving the sufficient statistic to $\chi^2$, normal, T-test, or F-test when possible so that I can use tabulated values. This makes sense. Thank you!
Comment: @StubbornAtom I found the distribution, but the integration to find $\alpha$ is causing me trouble. Added my updated work.
Comment: @StubbornAtom I like that idea and I added more work, but I arrive at the same problem as before, unfortunately.
Answer: It looks like you have mostly solved this problem, but you are left with a quantile function that you are not familiar with.  However, you also appear not to have recognised the simplicity of some aspects of the problem, and particularly the fact that when you are constructing the uniformly most-powerful test (UMP) you will ultimately implement this by deriving the p-value function for that test.  This method bypasses the need to ever compute the cut-off level for a particular rejection region, and so, in practice, we never really bother computing these.  Let me show you how to generate the UMP and implement this in statistical programming.

Deriving the UMP: In this problem you have data $X_1,...,X_n \sim \text{IID Laplace}(0, \theta)$ from the centered Laplace distribution.  Since this distribution is symmetric around zero, for all $x>0$ you have:
$$f_{|X|}(x) = 2 \times \text{Laplace}(x|0,\theta) = \frac{1}{\theta} \cdot \exp \Big( - \frac{x}{\theta} \Big) = \text{Exp}(x|\theta).$$
This means that you have $|X_1|,...,|X_n| \sim \text{IID Exp}(\theta)$, and the estimator of the scale parameter is:
$$\hat{\theta}_n \equiv \frac{1}{n} \sum_{i=1}^n |X_i| \sim \frac{1}{n} \cdot \text{Gamma}(n,\theta).$$
In your hypothesis test you are considering the case where $\theta_1 < \theta_0$, so your alternative hypothesis is that the observations have a smaller scale and therefore they will tend to be closer to the zero value than under the null hypothesis.  Thus, your most-powerful test should use the rejection region $\sum|X_i| \leqslant k$ where the cut-off value $k$ is determined by the requirement that $\alpha = F_\text{Ga}(k|n,\theta)$.  Letting $Q_\text{Ga}$ denote the quantile function for the $\text{Ga}(n,\theta)$ distribution, you therefore have $k = Q_\text{Ga}(\alpha)$.  That is, the cut-off value $k$ is the $\alpha$ percentile of the gamma distribution with shape $n$ and scale $\theta$.  There is no closed form expression for this quantile value, but it is programmed into standard statistical software.  For example, in R you can obtain this value with the function qgamma.
While this method can find the cut-off value for the test, in practice, there is no need to do this.  Instead of computing the rejection region for a stipulated significance level, it is more useful to generate the p-value function.  In the case where $\theta_1 < \theta_0$ a lower estimated scale constitutes evidence in favour of the alternative hypothesis, and so the p-value function for this test is:
$$p(\mathbf{x}) = \mathbb{P} \Bigg( \sum_{i=1}^n |X_i| \leqslant \sum_{i=1}^n |x_i| \Bigg| \theta = \theta_0 \Bigg) = F_\text{Ga} \Bigg( \sum_{i=1}^n |x_i| \Bigg| n, \theta_0 \Bigg).$$
(Note that in the contrary case where $\theta_1 > \theta_0$ a higher estimated scale constitutes evidence in favour of the alternative hypothesis, so the p-value would be one minus this amount.)  This gives you the p-value function for the test, which is sufficient to implement the test with any set of observed data.  An important point about the p-value function is that it does not depend on $\theta_1$, except to the extent of checking whether this value is larger or smaller than $\theta_0$.  We therefore see that it is not necessary to stipulate the value $\theta_1$ in the test --- we merely need to specify which direction of the one-sided test we are performing.

Programming the test in R: It is relatively simple to program this test in R using the standard method for programming a hypothesis test.  Here we will program a slightly more general version of the test, that allows you to stipulate a parameter $\mu$ in the Laplace distribution, or leave this parameter to be estimated from the data.  (Note that we use an approximation for the p-value for the case where this parameter is estimated from the data.)  Our test will be a one-side test that allows you to test for a larger or smaller scale parameter,
Laplace.scale.test <- function(X, mu = NULL, theta0, alternative = "greater") {

    #Check validity of inputs
    if(!is.numeric(X))      { stop("Error: Data should be numeric"); }
    if(length(X) == 0)      { stop("Error: You require at least one observation"); }
    if(!is.null(mu)) {
      if(length(X) == 1)    { stop("Error: You require at least two observations"); }
      if(!is.numeric(mu))   { stop("Error: Parameter mu should be numeric or NULL"); }
      if(length(mu) != 1)   { stop("Error: Parameter mu should be a scalar or NULL"); } }
    if(!is.numeric(theta0)) { stop("Error: Parameter theta0 should be numeric"); }
    if(length(theta0) != 1) { stop("Error: Parameter theta0 should be a scalar"); }
    if(theta0 <= 0)         { stop("Error: Parameter theta0 should be positive"); }
    if(!(alternative %in% c("greater", "less")))
                            { stop("Error: Alternative must be 'greater' or 'less'"); }

    #Set description of test and data
    if (is.null(mu)) {
      method    <- "Laplace scale test"; } else {
      method    <- paste0("Laplace scale test (with assumed mean of ", mu, ")"); }
    data.name   <- paste0(deparse(substitute(X)));

    #Set null hypothesis value
    null.value  <- theta0;
    attr(null.value, "names") <- "scale parameter";

    #Calculate test statistics
    n           <- length(X);
    if (is.null(mu)) { df <- n; } else { df <- n-1; }
    if (is.null(mu)) {
      estimate  <- sum(abs(X))/df; } else {
      mu.hat    <- stats::median(X);
      estimate  <- sum(abs(X-mu.hat))/df; }
    attr(estimate, "names") <- "estimated scale";
    statistic   <- estimate;
    attr(statistic, "names") <- "theta.hat";

    #Calculate p-value
    if (alternative == "less") {
      p.value   <- pgamma(df*statistic, shape = df, scale = null.value,
                        lower.tail = TRUE, log.p = FALSE); }
    if (alternative == "greater") {
      p.value   <- pgamma(df*statistic, shape = df, scale = null.value,
                          lower.tail = FALSE, log.p = FALSE); }
    attr(p.value, "names") <- NULL;

    #Create htest object
    TEST        <- list(method = method, data.name = data.name,
                        null.value = null.value, alternative = alternative,
                        estimate = estimate, statistic = statistic, p.value = p.value);
    class(TEST) <- "htest";
    TEST; }

This gives us a general testing function that we can use to perform a one-sided test for the scale parameter from data from a Laplace distribution.  We can either stipulate the mean parameter, or estimate this from the data.

Implementation of the test: We can implement this test on a set of mock data which I will set out in the code below.  We will input the vector DATA and test whether the scale parameter for this data is larger than the null value $\theta_0 = 10$ (we will assume zero mean for the Laplace distribution).
#Input the data for the test
DATA <- c( -3.48,  12.15 , -4.93, -28.91,  -8.62,  -8.91,
           -9.07, -23.96,  32.04,  -0.58, -25.93, -17.66,
            6.36, -16.18, -17.82,   5.12, -20.74,   7.96)

#Generate the scale test
TEST <- Laplace.scale.test(DATA, mu = 0, theta0 = 10);

#Print the test
TEST;

        Laplace scale test (with assumed mean of 0)

data:  DATA
theta.hat = 12.659, p-value = 0.1376
alternative hypothesis: true scale parameter is greater than 10
sample estimates:
estimated scale
       12.65882

Using the above data, we can see that the estimated scale parameter is $\hat{\theta}_n = 12.65882$, but there is no evidence to reject the null hypothesis that $\theta_0 = 10$ in favour of a larger value.  We would not reject the hypothesis that this is the scale parameter.
Comment: This is a great answer- thank you. There is a lot of new material that I will need to unpack here, but I think this is absolutely a great method. Further, I appreciate your R implementation. This is fun!


Write Statement in Relational Algebra

Question: I am having issues trying to write the following statement in relational algebra:
select A.name, A.gender, A.class, B.sid from A,B;

I dont know if it helps but A and B are connect through the sid primary key
When I was messing around with it I came up with this:
π A.name, A.gender, A.class, B.sid (A,B)

But I am not sure if that is correct
Comment: There are many RAs (relational algebras).They differ in operators & even what a relation is.  Give a reference and/or definition for yours. Eg textbook name, edition & page. Define "write in"--Same result? Same structure? How does a table correspond to a relation? What about nulls? PS No RA uses comma as an operator. So you don't seem to have made any effort to inform yourself. See [ask], hits googling 'stackexchange homework' & the voting arrow mouseover texts.
Answer: The notation FROM A,B in SQL is not frequently used as some time ago, it corresponds to the cartesian product (which is now more commonly written as FROM A CROSS JOIN B) that concatenates every tuple of A with all the tuples of B.
In relational algebra it can be expressed through the operator for the cartesian product, x, so the query can be translated as:
π A.name, A.gender, A.class, B.sid (A x B)

Note that in the relational algebra the two tables arguments of the x operator are in general required with attributes all different.
Finally, note also that the fact that the tuples of the two relations are connected trough some attribute (like for instance a foreign key) is ignored by this operator.
Comment: " tuples of the two relations are connected trough a foreign key is not used" True-ish. But if the two relations both have an attribute named `sid` (or in general same-named attributes), then a Cartesian product will fail. GeeGee doesn't give us the schema of the relations; so we don't know.
Comment: @AntC & Renzo Versions of RA with lists as headings can & do have a product operator taking inputs sharing attribute names. That is why they typically involve aliases & dots. As I've said before, there's no point in answering with an arbitrary fragment of the necessary precis on algebra options; tell the asker to define their algebra. Here the answerer talks about an operator denoted by a symbol & a name but they don't even know what operator they are talking about.

Write Statement in Relational Algebra


Evaluation of an integral associated with integral kernel of resolvent of Laplacian

Question: I came across evaluating the following sort of integral when I was considering the integral kernel for resolvent of Laplacian $(I-\Delta)^{-1}$:
$$
K(x)=\int_0^{\infty}\frac{\exp(-t-\frac{|x|^2}{4t})}{t^{\frac{n}{2}}}dt
$$
However, what I did know is that in the 1-dimensional case, i.e. $n=1$, the operator $(1-\partial_x^2)^{-1}$ has an integral kernel representation of the form:
$$
(1-\partial_x^2)^{-1}f=\int_{-\infty}^{\infty}\frac{1}{2}e^{-|x-y|}f(y)dy
$$
i.e. the integral kernel is$$
K(x)=\frac{1}{2}e^{-|x|}
$$
My question is, how can one evaluate the first integral for the case $n=1$ to obtain exactly the integral kernel in the third equation?
Comment: Small detail: in order to the first integral to be the same kernel as the last one it must have a $\frac{1}{2\sqrt{\pi}}$ factor infront as your first integral evaluates to $\sqrt{\pi} e^{-|x|}$.
Comment: Something is wrong in your first integral. Are you sure there isn't a negative in the exponent? Doesn't look very convergent to me.
Comment: @TrialAndError Yes you are right. Thanks for telling me that. However I still have no clue how to relate those two integrals. Can you help me with that? Thank you.
Answer: Plugging in $n=1$, the integral becomes
$$ K(x) = \int_0^{\infty} t^{-\frac{1}{2}} e^{-t-\frac{x^2}{4t}} \,dt.$$
Taking a Fourier transform, we have
$$\mathcal{F}K(y) = \frac{1}{\sqrt{2\pi}} \int_0^{\infty} t^{-\frac{1}{2}} e^{-t}\int_{-\infty}^{\infty} e^{-ixy} e^{-\frac{x^2}{4t}}\,dx\,dt.$$
The inner integral is the Fourier transform of the Gaussian with a dilation. In general, if $\mathcal{D}_{\alpha}f(x) = f(\alpha x)$ for nonzero $\alpha$, then a change of variable gives
$$\mathcal{F}\mathcal{D}_{\alpha}f(y) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty} e^{-ixy}f(\alpha x)\,dx = \frac{1}{|\alpha|\sqrt{2\pi}} \int_{-\infty}^{\infty} e^{-ix\frac{y}{\alpha}} f(x)\,dx.$$
Which is nothing more than $\frac{1}{|\alpha|}\mathcal{D}_{\alpha^{-1}} \mathcal{F}f(y)$, meaning if you dilate in one domain, you get the opposite dilation in the other domain (with a scale factor). In our case $\alpha = (2t)^{-1/2}$. Moreover, the Fourier transform of a Gaussian ($\exp(-x^2/2)$) is another Gaussian since the Gaussian is an eigenfunction of the Fourier transform, so we get that
$$ \mathcal{F}K(y) = \int_0^{\infty} t^{-\frac{1}{2}}e^{-t} \cdot (2t)^{\frac{1}{2}} e^{-ty^2}\,dt = 2^{\frac{1}{2}}\int_0^{\infty} e^{-(1+y^2)t}\,dt. $$
Letting $u = (1+y^2)t$, we get that $du = (1+y^2)\,dt$ and so
$$ \mathcal{F}K(y) = \frac{\sqrt{2}}{1+y^2} \int_0^{\infty} e^{-u}\,du = \frac{\sqrt{2}}{1+y^2}.$$
The Fourier transform is injective and the only function whose Fourier transform is $\frac{\sqrt{2}}{1+y^2}$ is $\sqrt{\pi} e^{-|x|}$.
I will leave it to you to argue that $K$ (as given in the first line) is in $L^1(\Bbb R)$ and that you can interchange the integrals as I did in the second line so that the use of the Fourier transform is justified.
Edit: Our constants do not quite match up. My guess is that your initial definition of $K$ has a constant factor out front which should take care of the factor of $\sqrt{\pi}$.
My reason for using the Fourier transform here is twofold. The main problem in your integral is the $e^{-\frac{x^2}{4t}}$ part. This is a Gaussian in $x$ - not $t$. So my thought was along the lines of: in the $t$-integral, the $\frac{1}{t}$ part is very problematic and hard to work with. Moreover the dilation property of the Fourier transform means that if I did a Fourier transform, the $\frac{1}{t}$ would appear in the numerator afterward which is infinitely easier to handle. Coupled with the Gaussian being an eigenfunction of the Fourier transform, it was clear that the Fourier transform was the way to go.
Comment: Thanks Cameron! This makes perfect sense and your use of Fourier transform is inspiring!
Comment: Gad I could help! It was a pretty tricky question :)


Passar um id "valor" para um campo input

Question: Utilizo a seguinte function:
public function autoCompleteCilindro($q){

    $this->db->select('*');
    $this->db->limit(5);
    $this->db->like('passo', $q);
    $query = $this->db->get('cilindros');
    if($query->num_rows() > 0){
        foreach ($query->result_array() as $row){
            $row_set[] = array('label'=>'Impressora: '.$row['impressora'].'    |    Cilindro: '.$row['engrenagens'].'    |    Passo: '.$row['passo'].'    |    Quantidade: '.$row['quantidade'],'quantidade'=>$row['quantidade'],'id'=>$row['idCilindro'],'engrenagens'=>$row['engrenagens']);
        }
        echo json_encode($row_set);
    }
}

Digito o valor aproximado de um passo, 200 por exemplo e me é apresentado os campos da tabela "cilindros".
Isso eu faço em um campo input.
Preciso que seja passado para o campo "altura" o resultado da divisão do campo "passo" dividido pelo campo "quantidade.

                                        Impressora  |  Engrenagem  |  Passo  |  Quantidade de Cilindros
                                        <input name="impressora" id="impressora" class="span12" type="text" value="" />

                                        Altura
                                        <input name="altura"  id="altura" readonly class="span12" type="text" value="" />

                                        Quantidade
                                        <input name="quantidade" id="quantidade" class="span12" type="text"  value="" />

Comment: Isso será feito por Ajax?
Comment: Acredito que sim. Dentro de uma estrutura de arquivos Models, tem um arquivo que tem as duas funtions public function adicionar e public function adicionarAjax().
Comment: "Acredita"? Vc não é o desenvolvedor da parada? Pelo visto, o Ajax retorna um JSON. Basta dividir um valor pelo outro e jogar no campo desejado.
Answer: Se eu não tiver entendido errado, seria desta forma.
Veja o exemplo: https://pastebin.com/x6DuuQRX
Answer:

function pesquisa(){
  var valorInput = document.getElementById('procura').value;
  $.post('/valida.php',{valor: valorInput},function(data){
    document.getElementById('resultado').innerHTML = data;
  })
 }

<form>
 <input type="text" id="procura" onkeyup="pesquisa();">
 <button>Pesquisar</button>
</form>

Comment: Bom dia. Não sou expert ainda em PHP. Este arquivo "valida.php", crio ele? onde e para que serve ? Qual seria o seu código ?
Comment: Sim, vc cria ele em qualquer pasta. Por exemplo, se ele tiver na pasta /SITE/VALIDA.PHP então vc tem q colocar $.post('/site/valida.php',[...], dai no valida.php vc pega o valor do input com $_POST['valor']  e faz as validações que quiser. Mas pra vc testar vc pode dar echo $_POST['valor'] e vc vai entender
Comment: e seu conteúdo ?
Comment: https://www.w3schools.com/jquery/ajax_post.asp


SSL certification for multiple domains

Question: For a serverfarm with a tracking solution for several clients, I need a SSL certificate for multiple domains (3 different ones) and on each of the domains for all the subdomains.
I do only need it to get the tracking pixels without any browser warnings when embedded in https pages on client side. It is NOT used for security issues or so.
What might be the best product for my use-case?
Thanks
Comment: are you saying you want a self-signed cert, or you just want us to tell you where to buy one?
Comment: i'd like to know if there is something like a "multi domain" certificate, whether it is a good idea to book this instead of 3 single domain certificates and if there is a recommendation also where to get it.
Answer: Yes, you can get SSL certificates that cover multiple domains -- they're usually called "multi-domain" or "universal communication" certificates, and they will have a single CN and a lengthy list of subjectAltNames.  Most providers will sell you one, but it might cost you stupid amounts of money.  We don't do provider recommendations, though (because who is who in the zoo changes so quickly).  They're popular for people who want to do SSL on a number of domains, but don't want to (or can't) chew a lot of IP addresses (EC2 hosting, for instance).
Comment: You should ask that as a separate question.  It's quite appropriate as a question in its own right.
Comment: is a multi-domain SSL cert also called a wildcard SSL cert, or is there a special name for the cert when it covers everthing under a TLD?
Comment: No, a multi-domain cert is differenr to a wildcard cert.  You're not (legitimately) going to get a wildcard cert that covers everything under a TLD, because that would allow you to MITM a large number of sites.
Comment: Sorry for the completely off-topic question, but what kind of SSL cert do people use for https proxies within an organization?  Those certs must cover all domains, no?
Answer: There are 3rd party companies issuing SSL certificates which can be used for multiple domains and subdomains. These are called SAN (Subject Alternate Names) certificates. These are priced bit higher than standard 1 domain based SSL certificates. You can buy those certificates for certain number of SANs (Subject Alternate Names or domains and sub-domains). Initially you can specify all the domains/sub-domains for which you need the certificate for. But if you dont know all the domains/sub-domains right in the beginning, you can get it for few domains and then during its validity period you can get it reissued by adding more domains as Subject alternate names.

SSL certification for multiple domains


Add a custom link to the contextual menu of every block

Question: I want to add a custom contextual link on the top of every block. there are many answers available on the site but these answers are about adding a contextual link to a specific block. and I need to add a contextual link which appears in the contextual menu of every block available in the site. I have tried this function.
function MYMODULE_contextual_links_view_alter(&$element, &$items) {
  if (isset($element['#element']['#block'])) {
    $element['#links']['animation'] = array(
      'title' => 'change animation',
    );
  }
}

I didn't get what I want.
Answer: The syntax of the link element is wrong.
This is a sample from the documentation of the Link render element.
$build['examples_link'] = [
  '#title' => $this->t('Examples'),
  '#type' => 'link',
  '#url' => Url::fromRoute('examples.description')
];

How do I create a link? has several answers with methods to produce the link.


Changing from rectangular coordinates to spherical coordinates (integration)

Question: I am taking calculus 3 and I have problems understanding how to change from rectangular coordinates to spherial ones (integration).
For example, I have this problem:
Find the volume of the solid $T$ enclosed by the surface:
$$(x^2 + y^2 +z^2)^2 = 2z(x^2 + y^2)\;.$$
How I change to spherical ones? Can someone resolve this one explaining it step by step??
Also if someone know a place in the web to learn this it will be appreciated!
Thanks!!
Comment: [What a nice shape.](http://i.imgur.com/L9B2jP0.png)
Comment: edit: Just how to set up the limits, do not have to integrate it!
Comment: Take a look at Apostol's Mathematical Analysis, Theorem 15.10, Example 2. He gives the full explanation. This is around page 507.
Answer: You can look at Wikipedia.  You have $x=r \sin \theta \cos \phi, y=r \sin \theta \sin \phi, z= r\cos \theta$  The volume element is $r^2 \sin \theta dr\;d\theta\; d\phi$  Your equation becomes $r^4=2r^3 \cos \theta \sin^2 \theta$ by plugging in the expressions.
Comment: yes but, how I find the limits of integration?
Comment: @Edwardo $\phi$ is $0$ to $2\pi$ and $\theta$ is $0$ to $\frac \pi 2$ as the part from $\theta=\frac \pi 2$ to $\pi$ is a duplicate when you revolve in $\phi$  [Here](http://www.wolframalpha.com/input/?i=polar+plot+r%3Dcos%28theta%29*sin^2%28theta%29%2C+theta+from+0+to+pi) is a plot with $z$ to the left


Maximum of a subharmonic function on it's boundary.

Question: I am trying to solve below problem of the book Partial Differential Equations(Third edition) written by jurgen just, problem 3.9. Can any one give an idea? Thanks in advance.
Let $\Bbb R^2:=\{(x_1,x_2)\}$, $\Omega$:=$B^{\circ}(0,R_2)$$\setminus$$B(0,R_1)$ with $R_2$$>$$R_1$$>$0. The function $\phi:= a + b \log(|x|)$ is harmonic in $\Omega$ for all a,b. Let u$\in$$C^2$($\Omega$)$\cap$$C^0(\bar{\Omega})$ be subharmonic, i.e.,
                          $\hspace{7.2cm}\Delta$u$\geq$0, $\hspace{0.6cm}$     $x$$\in$$\Omega$.
Show that
$\hspace{6cm}$M(r)$\leq$${M(R_1)\log({R_2\over r}) + M(R_2)\log({r\over R_1})}\over{\log({R_2\over R_1})}$
with $$M(r):=\max_{\partial B(0,r)} u(x)$$
and $R_1$$\leq$r$\leq$$R_2$.
Comment: Are you sure $M$ is the maximum on the circle with radius $R_2$ (rather that $r$)? If yes, what is it's depency on $r$?
Comment: You was right. it was r(rather than $R_2$).
Answer: Since you're given a hint in the form of function $\phi$, it's natural to relate it to the stated inequality. To this end, define
$$ \phi(x) = {{M(R_1)\log({R_2\over |x|}) + M(R_2)\log({|x|\over R_1})}\over{\log({R_2\over R_1})}}$$
which is a harmonic function. Observe that $\phi(x)=M(R_k)$ when $|x|=R_k$, for $k=1,2$. Thus, $u - \phi\le 0$ on the boundary. By the maximum principle, $u-\phi\le 0$ in the domain, which was to be proved.

Remark. This inequality, often known as the 3-circle lemma, expresses the fact that $M(r)$ is a convex function of $\log r$. Convex functions are distinguished by the property "graph lies below secant". Similarly, subharmonic functions "lie below harmonic". In this setting, $\phi$ is a harmonic function that plays the role of the secant.


Are linemen required to use a 3-point-stance in American football?

Question: In American football, are linemen required to use a 3-point-stance?
If they wanted to, could they stand (without moving) next to the line of scrimmage before the snap?
Are there different requirements for offense and defense in regards to lineman stance?
Any differences between professional NFL football and college football?
Answer: No, a 3-point stance is not required for offensive linemen. The NFL rules (7.4.2) cover how a lineman is allowed to switch between a 2-point stance and a 3-point stance before the play (but not the reverse, as that would be a false start).

Item 1. Interior Lineman. It is a False Start if an interior lineman (tackle to tackle) takes or simulates a three-point stance, and then changes his position or moves the hand that is on the ground.
Item 2. Change of Stance. An interior lineman who is in a two-point stance is permitted to reset in a three-point stance or change his position, provided that he resets prior to the snap.

The 2015 NCAA football rulebook does not mention stances at all.
But standing straight up would mean terrible leverage for blocking, and crouching for any length of time without flinching is difficult. So most of the time, linemen use a 3-point stance unless they are playing in a hurry-up offense and the ball is snapped quickly.
Defensive linemen are not required to be in any stance, or even to stop moving. They can do pretty much whatever they want as long as they don't cause the offense to false start.
Comment: I would update this answer.  There are multiple points untrue in this.   You might not find everything in the rulebook and may need to refer to referee notation guides.


OpenCL error: illegal implicit conversion between two pointers with different address spaces

Question: I have a function for float atomic_add:
inline void AtomicAdd(volatile __global float *source, const float operand)
{
    union{unsigned int intVal; float floatVal;} newVal;
    union{unsigned int intVal; float floatVal;} oldVal;

    do {
        oldVal.floatVal = *source;
        newVal.floatVal = oldVal.floatVal + operand;;
    }
    while (atomic_cmpxchg((volatile __global unsigned int *)source, oldVal.intVal, newVal.intVal) != oldVal.intVal);
}

Here is the main kernel, which calls the above function:
__kernel void main_kernel(__global float* image)
{
   AtomicAdd(&image[0], 1.0f);
}

The above function run correctly. Now I want to introduce a local variable to force the AtomicAdd done in one work group once and for all:
__kernel void main_kernel(__global float* image)
{
   __local tmpSum[1];
   if(get_local_id(0)==0) {
      tmpSum[0] = 0.0f; }

   barrier(CLK_LOCAL_MEM_FENCE);
   AtomicAdd(&tmpSum[0], 1.0f);
   barrier(CLK_LOCAL_MEM_FENCE);

   AtomicAdd(&image[0], tmpSum[0]);
}

The log gave following errors:
Build log:
:422:15: error: illegal implicit conversion between two pointers with         different address spaces
                            AtomicAdd(&tmpSum[0], 1.0f);
                                      ^~~~~~~~~~
:422:15: warning: passing 'float __attribute__((address_space(3))) *' to parameter of type 'float volatile __attribute__((address_space(1))) *' discards qualifiers
                            AtomicAdd(&tmpSum[0], 1.0f);
                                      ^~~~~~~~~~
:17:49: note: passing argument to parameter 'source' here
    inline void AtomicAdd(volatile __global float *source, const float operand)

As you can see, there seemed to be something wrong with the different address spaces between the global and local pointers. Does anyone has idea about what's happening here?
Answer: It's not possible to pass __local pointer into function taking __global pointer and vice versa. The copy of AtomicAdd function is needed taking __local pointer in order to build the kernel successfully.
Answer: I put my solution here. As pointed by doqtor, __local has different address space from _global. So the easiest way is overloading, which unfortunately opencl do not support. I have to define a new inline function and problem solved.


Defining routes in constructor

Question: I have a component called Root which renders the Routes for my index.js
const store = configureStore();
ReactDOM.render(
  <Root store={store} />,
  document.getElementById('root'),
);

I need to do this because I am connecting Root to redux, this is due to root authorization with onEnter, and it needs to work with redux state.
So here is the Root:
class Root extends React.Component {
  constructor(props) {
    super(props);
    // some stuff
  }

  requireAuthentication = (nextState, replace) => {
    // some stuff for managing auth
  };

  render() {
    const { store } = this.props;
    return (

        <Provider store={store}>
          <Router history={browserHistory}>
            <Route path="/" component={App}>
              <Route component={Dashboard}>
                <IndexRoute component={Home} onEnter={requireAuthentication}/>
              </Route>
              <Route path="login" component={Login} />
            </Route>
          </Router>
        </Provider>

    );
  }
}

// some definitions for connecting Root to redux

export default connect(mapStateToProps, mapDispatchToProps)(Root);

Ok... this renders well, but I have a warning:
Warning: [react-router] You cannot change <Router routes>; it will be ignored

routes, also works fine... but I want to solve the warning. So... googling I found the problem an a possible solution: declare routes inside the constructor and pass it to Router via props.
My constructor I did this:
import React, { PropTypes } from 'react';
import { connect, Provider } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Router, browserHistory, Route, IndexRoute } from 'react-router';
import { loginActions } from '../actions';
import { App, Dashboard, Home, Login } from '../features';
import adalHandler from '../services/adal';

class Root extends React.Component {
  constructor(props) {
    super(props);
    const routes = (
      <Route path="/" component={App}>
        <Route component={Dashboard}>
          <IndexRoute component={Home} />
        </Route>
        <Route path="login" component={Login} />
      </Route>
    );
    // some stuff
    }
  }

  requireAuthentication = (nextState, replace) => {
    // stuff
  };

  render() {
    const { store } = this.props;
    return (

        <Provider store={store}>
          <Router history={browserHistory} routes={this.routes} />
        </Provider>

    );
  }
}

// stuff

export default connect(mapStateToProps, mapDispatchToProps)(Root);

but now, it is no rendering well.
How can I solve it?
Comment: This may not be the issue but I do notice there is no route for `Dashboard` here: `` and because of this the nested `IndexRoute` had no index route to follow. Try setting a test route for `Dashboard` and see if that error goes away.
Answer: Object this.routes isn't defined in the render method.
For example you can replace const routes = (...); in constructor with this.routes = (...); to make object accessible in the render method.

Defining routes in constructor


Remove parts of items in a list?

Question: I have data stored in a list, basically in the following format:
['http://www.website.com/category/apples',
'http://www.website.com/category/oranges',
'http://www.website.com/category/bananas',
'http://www.website.com/category/pears']

There are about 900 unique links contained within this list. I want to return the text after category (e.g. apples, oranges, etc.)
This probably is done through a for loop like the following, but I'm getting stuck with the right functions to use. This is what I have so far, basically. The list is saved in links.
for l in links:
    new_list = l.search('category')
    return l

How can I optimize what is essentially "trimming" each element in my list?
Comment: Regular expressions, man.
Comment: I don't get how that applies to this issue
Comment: or simply l[31:] if your links all have the same start.
Answer: l = ['http://www.website.com/category/apples',
'http://www.website.com/category/oranges',
'http://www.website.com/category/bananas',
'http://www.website.com/category/pears']

li =  [ x[x.rindex('/')+1:] for x in l ]

print(li)

OUTPUT
['apples', 'oranges', 'bananas', 'pears']
Comment: Probably want to search for the term `category` rather than just the slash. Works for the basic example, but the requirements of the original question mentioned things after category specifically.
Answer: This is where you use regular expressions.  You match your string against a regular expression that matches "category/", then use the parenthesis operator to return the characters after that.
import re
for l in links:
    m = re.match('.+/category/(.+)', l)
    new_list.append(m.group(1))
return new_list

To optimize, you can pre-compile the expression, which is probably worth doing for 900+ strings:
import re
cat = re.compile('.+/category/(.+)')
for l in links:
    new_list.append(cat.match(l).group(1))
return new_list

And this can be done in a list comprehension instead of a for loop:
import re
cat = re.compile('.+/category/(.+)')
return [cat.match(l).group(1) for l in links]

Comment: That matches `/apples` btw
Comment: Are you sure?  It returns as expected when I ran the test. It's not robust to lines that don't have "category/" in them, which I'd fix before actually using, but it works for me on the test data.
Comment: According to [regex101](https://regex101.com/), I was gonna post an answer but seeing two on here I didn't.

Remove parts of items in a list?


Can modulo(remainder) be distribute over division?

Question: Let $a\%b$ be the modulo operation, returning the remainder of $a$ when divided by $b$. Is it true that:
$$\left(\frac{a}{b}\right)\% 5 = \frac{(a\% 5)}{(b\% 5)}$$
For instance, for $a=10$ and $b=2$ we have
$$\left(\frac{a}{b}\right)\%5=5\%5=0$$
$$\frac{(a\% 5)}{(b\% 5)}=\frac{(10\% 5)}{(2\% 5)}=0$$
Is this always true?
Comment: What do you mean by the "modulo" function? It is usually treated as a binary operator, or perhaps a function of two variables. Just what does modulo(a) mean?
Comment: From what I'm seeing in the question, I think you're implying modulo 5. Are you? If so, _mention_ it in your question.
Comment: modulo is remainder function(generally reffered as  % in programming languages).
Comment: @hii, I have provided a counterexample in the answers. :)
Comment: I edited the question; hopefully it will be clearer to other readers now. (I changed the modulo(a,b) notation to a%b, since you were already using both in the question; feel free to change it however you like though)
Answer: Counterexample:
Take $a=29$ and $b=27$.


storing objects in ResourceSelectionHistory of FilteredItemsSelectionDialog istead of string

Question: I have been following the tutorial here. In the advanced tutorial ResourceSelectionHistory stores the selected items and the retrieves it when the dialog is relaunched. I wanted the ResourceSelectionHistory to store objects and not just strings, is there i way to do that.
I also want the items to open in the editor when the user clicks on them. When I click on an item in the actual populated list it opens, but not when I click on the part showing history.
Thanks in advance
c yah!
Answer: The ResourceSelectionHistory is very specific to this dialog and can only store resources. It stores them using the IMemento mechanism. Probably the only way you can do what you want is to make a copy of the class (FilteredResourcesSelectionDialog) and have your way with it. These dialogs tend to be pretty restrictive if you just follow the API.
Comment: Oops! sorry I forgot to add the hyperlink. Now added. Well I am following that tutorial. Is there some other way to do this. I have extended `FilteredItemsSelectionDialog.`
Comment: You will probably need to make a subclass of `SelectionHistory` and then figure out how to store what you want in an `IMemento`. You will have to look into how `IMemento` works in terms of how to store your objects (you will probably need to somehow stringify your objects). I'm not sure what you mean by the second part of your question about opening the objects from the workbench history. Perhaps you can edit your question to clarify this?
Comment: second part of question edited. The answer I am looking for is how to figure that out. Can you please provide link to any example of `IMemento`. Can we store objects in `IMemento` or it must be string only?
Answer: You can store strings, integers and Boolean to IMemento. You can cleverly utilize them to reveal the type of object. For example you can use element.putInteger("objType", 1); if your object is of say type A and element.putInteger("objType", 2); if its of type B.


Duplicar uma associação em ruby on rails

Question: Estou com uma dúvida.
Envio a tabela que já fiz, mas tenho um problema, no caso do "Isolate's name" "catx" tenho dois "gene's name" associado, "catxx" e o "catxxx", mas eu estou a colocar os dois na mesma linha e gostava de duplicar a linha, uma para o "catxx" e outra para o "catxxx". Como faço, não estou a conseguir encontrar a solução. O código que tenho é:

    <% if @resists.any? == true%>
    <% @resists.each do |resist| %>

        <%= resist.isolated.organism.tax_org if resist.isolated%>
        <%= resist.isolated.organism.name if resist.isolated%>
        <%= resist.isolated.name if resist.isolated%>
        <%= resist.isolated.disease if resist.isolated%>
        <%= resist.drug.name%>
        <%= resist.drug.reference%>
        <%= resist.drug.atc%>
        <%if resist.isolated %>
        <% @genes.each do |gene| %>
          <%if resist.isolated.id == gene.isolated_id%>
            <%= gene.name%>
          <%end%>
       <%end%>
       <%end%>

@genes, vai buscar os genes todos.
estou a fazer
<% @genes.each do |gene| %>
          <%if resist.isolated.id == gene.isolated_id%>
            <%= gene.name%>
          <%end%>
       <%end%>

porque um isolado pode ter vários genes, e como tal, se fizer resist.isolated.gene.name vai-me dar erro porque tem mais que um. Mas como estou a fazer coloca-me na mesma linha os genes todos daquele isolado e eu queria colocar cada gene numa linha diferente, duplicando o isolado, claro.
Por exemplo:
123 xpto catx cenas12 navnav 2111 catxx
123 xpto catx cenas12 navnav 2111 catxxx

Answer: assumindo que no seu model Resist.rb você tem:
has_many :genes

e no seu Gene.rb
belongs_to :resist

basta por na view:
    <% resist.genes.each do |gene| %>
      <%= gene.name%>
    <%end%>


Site with Themekey has CSS cross-contamination

Question: I'm using Themekey with Context to enable one of three different themes on a site, depending on a themekey field. The homepage is set to use my main theme, called 'sitetheme'. Sitetheme is set as default, but many themes are enabled.

All the pages that I've tested look good, including the homepage. There's just one exception. My main menu, a horizontal header region menu block that uses Nice Menus to create dropdowns, has weird styling on it. When I inspect the element, I see that it has styling applied from a CSS file that lives in a different theme than the one that is enabled on the front page.
The front page is also of a nodetype that doesn't have the themekey field that some of the nodetypes have, that can be used to override the theme.
Why is my foo theme's CSS for Nice Menus getting applied on pages that use Sitetheme?
Comment: do you have a different nice menu block configured per theme(key), you nicemenu can have 1 "style" applied to it? Why do you think the main menu should look different per themekey?
Comment: No, the nicemenu block is the same block no matter what the themekey setting. Only the theme applied to it (and everything on the page) is different per theme.
Answer: I think Nice menus apply to all themes unless you have specified other.
Just go to the following location admin/appearance/settings/your_theme_A.
Then look for "Path to custom Nice menus CSS file"
Then go to your next theme admin/appearance/settings/your_theme_B
And also check "Path to custom Nice menus CSS file"
You might surprise, Nice menu use common CSS file regardless of your theme unless you have changed.


Position: fixed, usar ou não usar? Substitutos

Question: Recentemente assisti uma palestra do Sérgio Lopes , na qual ele fala que NÃO se deve usar position fixed no mobile. Segundo ele, esse position traz enormes problemas no navegador do celular, como o que acontece quando dar zoom.
No entanto, estou enfrentando um problema agora: preciso colocar uma barra fixa no fundo da página, que nem aquele bottom-bar do material design.
E agora, como fazer? Usar um js pesadão para manter ela sempre lá? Dividir em duas divs, e colocar a de cima com o conteúdo e width fixo e overflow, e a de baixo usar para o bottom bar?
Ou cagar para o Sergio?
Outra coisa que não faz parte dessa pergunta: nos apps nativos não existe zoom, então se tratando de um pwa, que é like-app, por que não desabilitar o zoom??
Comment: Ele tem os seus motivos pessoais, mas nunca existiu tal regra.
Comment: Realmente, mas os argumentos são bons. Então, se ele disse para não usar, como ele faria esse posicionamento?
Comment: Eu usuária sua dica de usar div separadas,e fazer scroll em somente uma delas.
Answer: Cara, realmente a palestra de 2013 já tá bem desatualizada. Não caga pra mim não, mas pode cagar pra palestra hahaha.
O cenário era bem caótico em 2013. Nada funcionava com fixed em praticamente nenhum browser. As coisas melhoraram bastante desde então.
Mas continuam um tanto caóticas.
A melhor referência sobre fixed em mobile que você encontra hoje são os testes detalhadíssimos do @ppk:
https://quirksmode.org/css/css2/mobile.html#link1
Repare que vários browsers modernos já suportam fixed com certa segurança. Mas tem os antigos, e tem os outros tipos de navegadores. Recomendo olhar lá pra entender as limitações atuais, e pra você decidir quais navegadores quer suportar.

Sobre o zoom, eu ainda defendo que sites não bloqueiem o zoom. É uma questão de acessibilidade. Realmente as Apps nativas não permitem zoom; isso é um bug. Ainda bem que na Web conseguimos ser melhores que eles :-P
Comment: Fala Sérgio, legal vc comentar aqui, e que bom que vc não levou para o lado pessoal. Esse tipo de debate só enriquece a comunidade. Apesar da metáfora qq um que contribua para o conhecimento alheio merece meu reconhecimento! []´s
Answer: Vc pode trocar o fixed por position:sticky apesar do suporte dos browsers ainda não ser muito grande.

Documentação: https://developer.mozilla.org/pt-BR/docs/Web/CSS/position
Suporte dos Browsers: https://caniuse.com/#feat=css-sticky (nao funciona no IE)

E lembre-se que essa palestra é de 2013!! 5 anos no passado!
OBS: O IE 7 já aceitava position:fixed https://caniuse.com/#feat=css-fixed
Nessa resposta tem algumas detalhes da diferença entre position:sticky e position:fixedhttps gostaria de saber como eu coloco esse cabeçalho fixo igual o menu deste site junto a logo
Sobre o Zoom isso é uma questão de acessibilidade e limitar o uso dele é péssimo para quem tem problema de visão, além disso existem apps mobiles nativos que dão zoom na tela de qq forma... Mas eu particularmente cagaria para o Sergio e faria com Fixed...

A variety of methods allow the user to control content size on mobile
  devices with small screens. At the browser level these methods are
  generally available to assist a wide audience of users. At the
  platform level these methods are available as accessibility features
  to serve people with visual impairments or cognitive disabilities.

Aqui tem o Guide Line oficial da WCAG 2.0 e W3C/WAI falando sobre o Zoom em dispositivos mobile https://www.w3.org/TR/mobile-accessibility-mapping/#zoom-magnification


Setting up SSH with the correct user rights

Question: I want to setup my SSH connection correctly. As many tutorials told me, it is not recommended to use the root account of Ubuntu server. So I would rather use my standard account "Simon" to upload files and transfer terminal commands.
When I run 'sudo su' I am prompted to type the standard password for my user account Simon in order to gain root permissions. I am pretty sure, that instead I should get asked for the root password, shouln't I? How can I fix this?
Answer: No, you should not.
If you were to type "su", then that would be true, you should be asked for the root password. Su basically means "switch user".
Sudo authenticates the logged in user again to make sure you did not leave the terminal open in order to allow you to use the permissions given to you via the sudo configuration (/etc/sudoers, /etc/sudoers.d/*).
As such, you cannot fix it because that is the desired behavior. If you still want the behavior you are describing to want/need, sudo has a configuration option called runaspw.
Also, try not using sudo su but rather, "sudo whatever command I'd like to run as root".
Comment: A root account cannot not exist. sudo does not necessarily switch you to the root account, I recommend you to read its documentation to understand what it does. If you type "sudo su", you will get a shell with root as process owner so you will get root privileges. You cannot disable the root account, but you can disable its password so that nobody is able to directly use it using a password.
Comment: So just to be sure: If I type sudo, I will always obtain rights to change everything on the system, whether or not there exists a root account on my system? So in case I type "sudo su" and I entered my user password correctly I will obtain god priviliges, so that I can skip the password of root. Then it would be the best to disable the root account and always use sudo? Thank you for your support.


Expressions logically equivalent to "such that"

Question: The question arises from the rewording of some theorems, by example continuity of a function $f$, we have that
$$f\text{ is continuous at }c\iff (\forall\epsilon>0,\exists\delta>0:|x-c|<\delta\implies|f(x)-f(c)|<\epsilon)\tag{1}$$
then I think I can reword this as
$$f\text{ is continuous at }c\iff ((|x-c|<\delta\implies|f(x)-f(c)|<\epsilon)\implies (\forall\epsilon>0,\exists\delta>0))$$
The last statement seem strange to read but the last implication seems logically equivalent to $(1)$. Anyway this is just an experiment.
My question is, there is some expression logically equivalent to "such that" that can be written with basic logical operators as $\lor$, $\land$, $\lnot$, $\iff$ and $\implies$? Thank you in advance.
Answer: No, you can't do that; that's not how quantifiers (or conditionals) work.
"$\forall \epsilon>0$" just means, "For all $\epsilon>0$." It doesn't assert anything - e.g. it doesn't make sense to say ""$\forall \epsilon>0$" is false". Similarly with "$\exists \delta>0$."
So an expression of the form "...$\implies (\forall \epsilon>0,\exists \delta>0)$" is meaningless: "$\implies$" connects two sentences.
The issues go further than this: quantifiers bind variables. The expression "$\forall x(x>5)$" is a sentence; the expression "$x>5$" is not, and the expression "$(x>5)\implies (\forall x)$" is really not.
Comment: (An anecdote: I was not too long ago giving a seminar talk with a certain older logician in the audience. He frequently fidgeted when I wrote, and I had no idea why. After the talk, someone came up to me and asked a question, and in the process of answering I wrote "$\exists x$ s.t." on the board; the older logician he got up and erased the "s.t." and gave me a short historical lecture on how that was redundant. :P)
Comment: @Masacroso I don't understand what you're asking. "Such that" is *implicit* in how quantifiers work - e.g. "$\exists x(P(x))$" *means* "There exists an $x$ such that $P(x)$." So I *think* the answer to your comment is "no?" But I don't really understand what you mean by "irreducible to other logic operators" . . .
Comment: Then the meaning of "such that" is irreducible to other logic operators, right?
Comment: Oh, Ok, I understand... "such that" is implicit to quantifiers, silly me.
Answer: Abstractions. The closest thing to "such that" is a lambda operator or an abstraction. You can actually define a quantifier using an abstraction operator and property of attributes being universal or non-empty. See details in Fitch's "Symbolic Logic: An Introduction". Lambda operator can be defined using combinators. See details in Fitch's "Elements of Combinatory Logic"
Examples.

Abstraction or lambda operator. Suppose you have statement "sky is blue and transparent" you can also can paraphrase this like "sky has properties of being blue and transparent", you can paraphrase this property like "(x\x is blue and transparent)". Now you can say that "sky is blue and transparent" is logically equivalent to "(x\x is blue and transparent)""sky". Here used convention that we write property first and argument second. So we can write "(x\ x is red)""ball", this is logically equivalent to "ball is red".

Universal properties. Lets consider statement "(x\x=x)", that is property of being equal to itself. This property has property of being universal. We can write this like "A(x\x=x)".

Existential properties. Lets consider property of being equal to five "(x\x=5)". This property has property of being non-empty, that is of having some objects that has this property. We can write this like "E(x\x=5)".

Quantifiers in terms of abstraction and universal or existential attributes."A(x\x=x)" is equivalent to $\forall x x=x$. "E(x\x=5)" is equivalent to $\exists x x=5$. More generally "A(x\P(x))" is equivalent with $\forall x P(x)$. "E(x\Q(x))" is equivalent to $\exists x Q(x)$.

Abstraction or lambda operator in terms of combinators. We have analyzed quantifiers by dividing them into universal or non-empty attributes and abstraction operator. We can also analyze abstraction operator too. It can be shown that every (x\ $\phi(x)$) where $\phi(x)$ is some logical expression can be expressed using this expression and operators called combinators. Basically, suppose you have a function of several variables. Using combinators you can obtain same function but only variable places are changed or some arguments are missing or doubbled. There are several combinators: I, C, K, T, W.

I P(x,y,z) is equivalent P(x,y,z).
C P(x,y,z) is equivalent to P(x,z,y).
K P(x,y,z) is equivalent to P(x,z).
T P(x,y,z) is equivalent to P(y,x,z).
W P(x,y,z) is equivalent to P(x,y,y,z).
By applying this operators to formula you can compute abstraction of it.

Be cautious combinatory logic is incompatible with all the rules of classical logic.

Descriptions.
Another thing that is very similar to "such that" is definite description operator $℩$. I found following information in Anderson's and Johnstone's book "Natural Deduction".
Examples.

Imagine you have a attribute of variable (we call it predicate) $\psi(x)$. It may be $x^2=0$. Expression $℩x(\psi(x))$ denotes "the x that has property $\psi(x)$". So $℩x(x^2=0)$ is equal to 0.
$℩$ operator can be expressed in terms of predicate logic.
Expression $n=℩\alpha(\psi(\alpha))$ is equivalent to
$\exists \alpha [\forall \beta [\psi(\beta)\equiv(\alpha=\beta)]\land(\alpha=n)]$.
Expression $\phi[℩\alpha(\psi(\alpha))]$ is equivalent to  $\exists \alpha [\forall \beta [\psi(\beta)\equiv(\alpha=\beta)]\land(\phi(\alpha)]$.
Lets us assume we have some function $f(x)$. We want to express statement "the x such that f(x) is continuous". We may want to have this expression to substitute it then in some other formula.
This expression can be written $℩x(\lim_{x \to c} f(x)=f(c))$
Be cautious. For descriptions identity relation may not be reflexive, symmetric or transitive.
Comment: The OP of the question makes no reference to combinatory logic. Their question is explicitly about representing 'such that' using operators under classical logic. This answer seems less like it addresses the question and more like a short description of the basics of combinatory logic.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/1747377)
Comment: I find your comment strange, may be my English was not clear enough. Question is:"My question is, there is some expression logically equivalent to "such that" that can be written with basic logical operators as ∨, ∧, ¬, ⟺ and ⟹?" My answer is "such that" can be thought as abstraction operator, which can be expressed using I, K, C, T, W operators. In my answer I tried to show these concepts on simple examples.
Comment: I understood "logical operators as..." as "logical operators as ... or something similar to logical operators ....". I find combinators similar to logical operators. Frequently when people are asking questions they not only don't know something, but they don't know that they don't know. Most of the question I ask my self are answered by correcting the question. So I think that broader answer will be better. So I thought that broader answer will be "how can I analyze 'such as' ". From my perspective it seemed evident that author of the question wants to formalize and analyze "such that".