A uniform continuity problem

Question: Let $A$ be a set of real numbers and $f:A \to \mathbb R$ be a function such that for every $\epsilon >0$ , there exist a uniformly continuous function $g_\epsilon :A \to \mathbb R$ such that $|f(x)-g_\epsilon(x)|<\epsilon , \forall x \in A$ , then how to prove that $f$ is uniformly continuous on $A$ ?
Answer: Let $\varepsilon>0$. Then, as $g_{\varepsilon/3}$ is uniformly continuous, there exists a $\delta>0$, such that $\lvert x-y\rvert<\delta$, implies that $\lvert g_{\varepsilon/3}(x)-g_{\varepsilon/3}(y)\rvert<\varepsilon/3$. Then, whenever  $\lvert x-y\rvert<\delta$, we have
$$
\lvert f(x)-f(y)\rvert\le \lvert f(x)-g_{\varepsilon/3}(x)\rvert+\lvert g_{\varepsilon/3}(x)-g_{\varepsilon/3}(y)\rvert+\lvert g_{\varepsilon/3}(y)-f(y)\rvert<\frac{\varepsilon}{3}+\frac{\varepsilon}{3}+\frac{\varepsilon}{3}=\varepsilon,
$$
which proves that $f$ is uniformly continuous.
Answer: Let $\tilde \epsilon > 0$, then there is some $g_{\epsilon}$ (take $\epsilon = \tilde \epsilon/3$) such that
$$ | f(z)-g_{\epsilon}(z)| < \frac{\tilde \epsilon}{3}$$
for every $z \in A$. Now $g_\epsilon$ is unformly continuous and so there are is some $\delta > 0$ such that $x,y \in A, |x-y|< \delta $ implies
$$ |g_\epsilon(x)- g_\epsilon (y)| < \frac{\tilde \epsilon}{3},$$
it follows that $x,y \in A, |x-y|< \delta $ implies
$$\begin{array}{rcl}|f(x)-f(y)| &=& |f(x)-g_\epsilon(x)+ g_\epsilon (x)+g_\epsilon(y)- g_\epsilon (y)-f(y)| \\ &\leq & \underbrace{|f(x)-g_\epsilon(x)|}_{< \tilde\epsilon/3} + \underbrace{|g_\epsilon (x)-g_\epsilon(y)|}_{< \tilde\epsilon/3} + \underbrace{| g_\epsilon (y)-f(y)|}_{< \tilde\epsilon/3} < \tilde \epsilon \end{array}$$
and thus $f$ is uniformly continuous.
Answer: Let $\epsilon>0$, and take $G:=g_{\epsilon/3}$. Since $G$ is uniformly continuous, there is $\delta>0$ such that for every $a,b\in A$ with $|a-b|<\delta$, $|G(a)-G(b)|<\frac{\epsilon}{3}$. thus for every such $a,b$:
$$|f(a)-f(b)|\leq|f(a)-g(a)|+|g(a)-g(b)|+|g(b)-f(b)|\leq3\cdot\frac{\epsilon}{3}=\epsilon.$$

A uniform continuity problem


Random samples within the Central Limit Theorem - why select with permutation with repetition?

Question: "The central limit theorem states that if you have a population with mean μ and standard deviation σ and take sufficiently large random samples from the population with replacement, then the distribution of the sample means will be approximately normally distributed." (from sphweb.bumc.bu.edu)
Reviewing the underlying fundamentals, I got puzzled by an example that attempts to explain how the CLT is formed. More specifically, I wonder why the "large random samples" here should be selected by the "permutation with repetition" method, not the "combination" method.
In this example (from a class I'm taking. Not a perfect example since the sample size is not large), we suppose there's a finite population with 8 numbers

54, 55, 59, 63, 64, 68, 69, 70

Then it said all possible samples of n=2 will be 64.
This is so because we can do 8C2*2+8 or 8^2
And all the samples will look like this

How do we understand the "sampling with replacement" here? Obviously the order matters here, but why does it?
When order matters, 2 samples with the same elements but different orders will produce the same means. For example, (55,57) and (57,55) both produce sample means of 56. Why would we want the same mean twice?
Comment: Your quote says "large random samples".  Your example has samples sized $2$, which is not usually regarded as large.  But your example does show the $8^2=64$ equally likely samples sized $2$.  Each of the $8$ values is equally likely to be the first sample, and independently each of the $8$ values is equally likely to be the second sample. The independence of each sample, together with a large sample size, help with the Central Limit Theorem.  Not allowing repetitions or allowing repetitions but making order not matter would remove independence
Comment: Henry, you are right that the example isn't the best since the sample size here is 2 and unacceptably small. This is an example I found from a textbook, I guess it's only for demonstration purposes.
Comment: I'm glad you mentioned the "independence" aspect as part of the CLT requirement. I believe this is the key. Thank you! (vs. the answer from the other places told me that "we needed to exhaust all possible combinations of sampling).
Answer: It would be nice to see the full example to answer with more precision, but I'm thinking that there is too much stress on the permutation part. For example, you are correct in noting that ${55,57}$ and ${57,55}$ give us the same average, but is it true that you will always retrieve these two instances of the population during random sampling? The interesting question for me trying to understand CLT is how the number of samples impacts the statistic under consideration, e.g., i might like to know how 'off' the mean of the first sample is from the actual mean (since in this case we know the entire population) and how many more samples are needed to approach the true mean. I'd also wonder how many instances should make up a sample...


Creating a script to install a Perl application and its dependencies automatically

Question: I have a Perl application that needs a lot of dependencies that i need to deploy on numerous servers
I would like to make a script that installs that Perl application automatically and quickly.
To be faster, i want to install most of my dependencies using my package manager instead of installing them with CPAN
Is there a way to determine automatically from a list of perl modules if there is a debian package for it? And if there is one, install the package, if not install the Perl module from CPAN ?
Comment: Did you try cpan's tools? What have you tried?
Comment: For now, I use cpan to install all the modules, but I would prefer to install the packages if they exists (faster, perfectly integrated to my system)
Comment: To be faster, is use cpanm, but it's still not as fast as the packages
Comment: Hem... And what's your system?
Comment: debian Squeeze for the most part of them
Comment: Good choice, my recommendation for a server!
Answer: Hmm, One way would be to look at writing a wrapper around the systems package manager, i.e. apt-get, and if packages not returned then install with cpan, cpanm, etc.

sub check_pre_req_package {
  my $package = shift;
  system("dpkg -s $package > /dev/null 2>&1");
  if ( $? != 0 ) {
    system("apt-get -y install $package > /dev/null 2>&1");
      if ( $? != 0 ) {
        system("cpanm $package");
      }
  }
  elsif ($? == 0) {
    print "Package $package is already installed \n";
  }
}

my @pre_req_packages = qw(strace nmap gcc);

foreach(@pre_req_packages) {
  check_pre_req_package($_);
}

Of course with that way you'd have to be case sensitive (or change the case) as I believe that debian uses a format of lib(package-name)-perl in all lower case and cpan will want a different format, etc, plus this code is untested and something that just thrown together.
Then there's good old bash scripting, as hell I used system commands in this example
My best suggestion is that you look into using something like cfengine or puppet and/or some other I'm sure is out there system configuration management. Then use svn or git or so... to make changes to push to a repo that will deploy to all your servers. If your going to be managing and making the changes to "numerous" servers then cfengine/puppet/etc will make your life a lot easier once set up. just my two.
Answer: My suggest:

First, take a look on .bash_history on target already installed, there is a great chance you will find a lot of already writted lines, ready to use,  of your script to install a Perl application and its dependencies automatically
Than you could install one target, using only one terminal (care not to use another session on same target for ensuring that every actions will correctly logged), and using script command.
script -t install-perl 2>install-perl.t
Try to not use interactive commands, or log each action to another text file in your desk.
From there, you must be able to retrace finely the whole process
scriptreplay install-perl.t install-perl
and to build a shell script, even by filtering the result file install-perl or simply the target's .bash_history.
Intermediate way Make one correct installation, than replicate them using tar. Sometime it's simplier to act so as all not debian packaged adds are confined in /usr/local.
Or even simplier, having /usr/local on separated partition shared and mounted in read-only mode on all targets.
Finaly, more Debian: From that correct installation, (could be called master), create a debian package, install them in your own enterprise repository (simple directory in some internal web or ftp server, containing exact directory structure and a public key your have to do.). Reference this reposit in your targets and maintain your master correctly.
Nota: Idealy you have to build one package per perl library you use (or one per familly of libraries), but this could generate some extra work and is not really needed unless you want to share or contrib with Debian packagers.

Nota: This last solution look a little overkill (implie some learning for maintener), but in fine:

this as to be learned one time only and is very quick after second, maybe third upgrade.
this is the most efficient and scalable solution.
this have to be done on already existant work without having to tinking about again.
if well done, this could exist longer than the hardware for which all this is done.
Answer: Might I suggest using perlbrew. In general I've found over the years that if you have an application that depends on a particular interpreter: Ruby, Perl, Python, etc. It's usually a better idea to setup a dedicated installation of the interpreter for your application rather than rely on the ones included in a particular distro.
Perlbrew maintains an entire installation of Perl in your $HOME directory. In fact you can have multiple versions of Perl along with its libraries so that you can perform testing, before you fully upgrade from one version to the next. By doing it this way your application is completely separated from upgrades that may occur when relying on your distro's version of Perl.
Excerpt from the perlbrew webpage:

perlbrew is a tool to manage multiple perl installations in your $HOME
  directory. They are completely isolated perl universes. This approach
  has many benefits:

No need to run sudo to install CPAN modules, any more.
Try the monthly released new perls.
Learn new language features.
Test your production code against different perl versions.
Leave vendor perl (the one that comes with OS) alone.

Installation is a breeze
curl -kL http://install.perlbrew.pl | bash

Usage
# Pick a preferred CPAN mirror
% perlbrew mirror

# See what is available
% perlbrew available

# See full help
% perlbrew help

# Install some Perls
% perlbrew install 5.14.0
% perlbrew install perl-5.8.1
% perlbrew install perl-5.13.6

# See what were installed
% perlbrew list

# Switch perl in the $PATH
% perlbrew switch perl-5.12.2
% perl -v

# Temporarily use another version only in current shell.
% perlbrew use perl-5.8.1
% perl -v

Resources

Managing Multiple Installations of Perl in your $HOME Directory using Perlbrew


Proving $P(|X+Y|\leq 2|X|) > \dfrac{1}{2}$

Question: We are given independent and identically distributed random variables $X,Y$ with probability density function $f(\cdot)$ that is symmetrical about $0$.
We need to prove that $P(|X+Y|\leq 2|X|) > \dfrac{1}{2}$
Starting with $P(|X+Y|\leq 2|X|)=P((X+Y)^2\leq 4X^2)=P(-3X^2+Y^2+2XY\leq 0)$
Now, $-3X^2+Y^2+2XY=0$ represents a pair of distinct real lines : $X=Y$ and $3X+Y=0$.
So, $P(|X+Y|\leq 2|X|)=P(-3X^2+Y^2+2XY\leq 0)=P[(Y-X)(3X+Y)\leq 0]$.
So two cases arise,
(i) $Y-X\geq0$ and $3X+Y\leq0$
OR
(ii) $Y-X\leq0$ and $3X+Y\geq0$
So, we have $P(|X+Y|\leq 2|X|)=\int_0^{\infty}\int_{(\frac{-y}{3})}^{y}f_{X,Y}(x,y)\:dxdy\:+\: \int_{-\infty}^{0}\int_{y}^{(\frac{-y}{3})}f_{X,Y}(x,y)\:dxdy$
Since $X,Y$ are independent $f_{X,Y}(x,y)=f_X(x)f_Y(y)$.
I am not able to move forward from here, in the solution the integral on the far right side is straight away written to be $(\dfrac{1}{2})$ and hence the sum becomes $\geq(\frac{1}{2})$.
Can anyone explain what just happened there ?
Comment: Are you assuming that $x$ and $y$ are continuous r.v.s?
Comment: The two cases have equal probability, since $(X,Y)$ has the same distribution as $(-X,-Y)$. The corresponding iterated integrals are therefore equal, so there's no way the far right one can be equal to $1/2$.
Comment: So, there are more than just these two cases ? @grand_chat
Answer: I think it's much easier to solve this problem using the triangle inequality rather than using a squaring approach. Since $|X+Y| \le |X| + |Y|$, we have that
$$P(|X+Y|\le2|X|) \ge P(|X|+|Y|≤2|X|)=P(|Y|≤|X|)=1/2$$
Do you specifically need to show that the probability is greater than 1/2?
Comment: Far better than my answer, which I shall now delete so as to avoid taking away well-deserved upvotes.  But a counterexample to the $> 1/2$ exists, namely, $x, y \sim \text{U}(-1,1)$ and $x=1/4 \implies y \in [-3/4, 1/4]$, which evidently has probability equal to $1/2$.
Comment: The inequality does not have to be strict if the distributions are discrete. If I calculated correctly, if A = probability the point (X,Y) lies between the lines Y= -X and Y = -3X or the lines Y=X and Y = X/3, then P(|X+Y|<2|X|) =(1+A)/2. So if A = 0, P(|X+Y|<2|X|) is exactly 1/2.
Comment: I'm not sure I follow you're counterexample. Can you elaborate. Based on my math, I have that if $X$ and $Y$ are uniform on $(-1, 1)$, then the probability of interest is 2/3. Are you sure that strict inequality doesn't hold?
Comment: When you said "Whoops, this is incorrect", what were you including in "this"?
Comment: I had meant the solution provided in the first edit. I just deleted the edits for clarity since they served no purpose.
Comment: @jbowman, what if $x \neq 1/4$, you would have to evaluate all possible pairs $x,y$ and not just the ones for which $x=1/4$.
Comment: @MartijnWeterings - I no longer have any idea why I thought my comment was relevant to the question (which, admittedly, presumes that at one point I did), so I'll delete it.
Answer: If you draw the lines Y = X and Y = -3X, the first has slope 1, and the second has slope -3. The two lines divide the plane into four quadrants, with the solution set being the left and right quadrants. So you just have to show that more than half of the probability mass is in those two quadrants. Call the two quadrants together figure1. Now rotate this by 90, and call this figure2.  Rotating by 90 degrees is the same as Y' = X, X' = -Y. The distributions are identical, so exchanging X and Y leaves the probability the same. They are symmetric about zero, so multiplying by -1 leave the probability the same. Thus, this transformation leaves the probability the same. Since every point in the plane is covered by either figure1 or figure2, and some points are covered by both, and this transformation doesn't affect the probability mass, it follows that figure1 contains at least half of the probability mass, and if you can proved that the overlapped areas contain a positive amount of probability mass, then it follows that figure1 contains more than half of the probability mass.
Answer: The image below demonstrates how a partitioning of the area $|x+y| \leq 2|x|$ helps to proof $P[|X+Y| \leq 2|X|] > \frac{1}{2}$.
The hatched region (region 2) corresponds to your area $$|x+y| \leq 2|x| \qquad \text{or} \qquad  (y-x)(3x+y) \leq 0 $$
Part of this region (the pink colored hatched region, region 2a) is a mirror image of the complement of region 2 (the pink coloured region, region 1). From this you can deduce that:
$$P[|X+Y| \leq 2|X|] = \frac{1 + P[(X-Y)(3Y-X) \geq 0] + P[(-X-Y)(3X+Y) \geq 0]}{2}$$
where the extra terms $P[(X-Y)(3Y-X) \geq 0]$ and $P[(-X-Y)(3X+Y) \geq 0]$ relate to the probability that X,Y are in the gray coloured hatched regions.

Note that the lines are not included in the complement region 1. Thus the discrete uniform example $x,y \sim U(−1,1)$ by jbowman does not work. The points (1,1), (-1,-1), (-1,1), (1,-1) are inside the gray hatched region and eventually inside the region for which $|x+y| \leq 2|x|$ is true.
In the same way for any distribution with finite pdf or probability mass at least somewhere. there will be some positive contribution near the lines Y=X such that the inequality is more strict $>$ instead of $\geq$.
For instance in the discrete case $P(X=x,Y=y)$ for $x=y$ is equal to $P(X=x)^2$ which is due to the property that $f_X=f_Y$
In the continuous case you could evaluate:
$$\begin{array} \\P[|X+Y| \leq 2|X|] &= \frac{1 + 4 \int_{x=0}^{x=\infty} \left( \int_{t=\frac{1}{3}x}^{t=x} f_X(t) dt \right) f_X(x) dx}{2}\\
& =  \frac{1 + 4 \int_{x=0}^{x=\infty} \left( F(x)-F(\frac{1}{3}x)\right) f_X(x) dx}{2} \\  \end{array}$$
where the integral must be non-zero if f_X(x) is non zero in at least some continuous region of non zero size (such that $F(x)-F(\frac{1}{3}x)$ is non-zero in a region with non-zero probability).
Some other equality is
$$P[|X+Y| \leq 2|X|] = \frac{1}{2} + P[\frac{1}{3} |Y| \leq |X| \leq |Y| ]$$
Answer: Changing this probability into an expectation is the key to solving this problem easily. As noted by @Accumulation and @Martijn Weterings, the absolute value function divides the (x,y)-plane into conic regions. Note that
$$ P(|X+Y|<2|X|)=E[I(|X+Y|<2|X|)] $$
where $I()$ is the usual zero-one indicator function. (Note that we can use "$<$" in place of "$\le$" by assuming $X$ and $Y$ are continuous - a requirement that's needed to ensure the strict inequality you want.) Then, the indicator can be rewritten as
$$I(|X+Y|<2|X|)=U+V$$
where
$$U=I(X < 0, -X < Y < -3X) + I(X > 0, -3X < Y < -X)$$
and
$$V=I(X < 0, X < Y < -X) + I(X > 0, -X < Y < X)$$
Based on the definitions of $U$ and $V$, it is clear that the regions on which each random variable equals one are non-overlapping (i.e. $P(V=1,U=1)=0$). Additionally, we can rewrite $V$ as
$$V=I(|X|+|Y| \le 2|X|)=I(|Y| \le |X|)$$
Therefore,
$$P(|X+Y|<2|X|)=E[I(|X+Y|<2|X|)]=E[U+V]=E[U]+E[V]=P(U=1)+P(|Y| \le |X|)=P(U=1)+1/2$$
All that remains is to show that $P(U=1)>0$. Let $A\times B\in \textbf{R}^2$ be a rectangle centered about the origin. Then, $P(X\in A, Y\in B)=P(X\in A)P(X\in B)$. Necessarily, there exist intervals $A$ and $B$ over which $f_X(x)$ integrates to some number greater than zero. Also, any such $A$ and $B$ will contain area over which $U=1$. This follows from the fact that the area over which $U=1$ takes the form of two cones extending from the origin. Therefore, $P(U=1)>0$ and the result follows.


Drupal core language module, language switcher block

Question: Can a preprocess hook convert the default ul of hyperlinks into a drop-down select list? Something like this hook.
function THEME_preprocess_links__language_block(&$variables)

Answer: You can copy the core/modules/system/templates/links.html.twig into your theme's templates directory, call it links--language-block.html.twig  and in this file adjust the output from the default ul/li structure into a different html structure.
NOTE: there is already 3 maybe more modules that convert the language switcher to dropdown lang_dropdown, dropdown_language and bootstrap_languages.
Comment: Thanks Glorgosk. I want to use the core language switcher because I had a pre process hook to hide languages if that language was not available on the node. But I ended up using the module Language Switcher Dropdown
https://www.drupal.org/project/lang_dropdown/releases/8.x-2.0-beta3. And the was a patch available for it that would hide languages.


Can I use headphones with tube guitar amplifier without headphone jack?

Question: Newbie here (no electrical knowledge).
Question: For a 15 watts tube amplifier without a headphones output, is it safe to use the external speaker out jack to plug it to headphones, mixer or USB interface, while short-circuiting the FX loop (that is, leaving a dummy jack plugged into the FX lopp In (Send), without it being connected to anything)?
I wanted to buy the Monoprice 15 Watts tube amp and I thought of using it with headphones when at home. But it has no headphones jack.
It does have: A) an external speakers out (so you can plug it to a cabinet), impedance 8-16 ohms; B) an FX loop.
I have both a mixer and an USB interface, so if I couldn't plug the "external speakers" output directly to the headphones, I imagine I could plug it into one of these. The problem is that sound still comes out of the regular cabinet when something is plugged to the external speakers jack. To mute the combo cabinet, one can insert a 1/4'' plug in the FX loop In (Send), without it being connected to anything (that is, nothing is plugged into the FX loop Out (Return)). My fear is that this might damage the amplifier.
I have read contradictory information on the internet regarding this. This post, for example, says it's OK to mute the cabinet by plugging something in the FX loop In (Send), and then use the external speakers output to connect it to headphones. But I also read people commenting this will blow the amp in due time.
Does anyone know what is the correct electrical information? Will I blow up the amp if I do the above?

EDIT: I apologize, I think I might have gotten some things wrong. This guy says he's doing the opposite of what I suggested: he's connecting his headphones to the "FX send" jack and plugging a dummy plug into the "external speaker" jack (to mute the amp). But the commentary right after his suggests it might blow up the amp
Relevant links:
https://www.tdpri.com/threads/monoprice-15-watt-tube-amp.609524/page-22#post-7561910
https://www.tdpri.com/threads/monoprice-15-watt-tube-amp.609524/page-43#post-8874099
http://talk.philmusic.com/index.php?topic=276298.0 (apparently, the Monoprice amp is a Laney Cub 12R clone)
Answer: To be sure I understand, you want to plug headphones into your speaker out on a tube amp head?
I would say absolutely not. It doesn't matter what you have plugged into your FX loop. If you want signal from your cabinet out, that comes from the power amp.
A speaker out sends a "hot" load from your power amp to the speaker. If that load is not resolved somehow (a load box or a speaker), you are going to blow up your amp. And there is no way your headphones are going to safely accept that amount of power.
There are amplifiers that have ways around this. I own four heads, two of them can be safely used without a cab/load box, one is "allegedly" safe to use but most don't recommend it, one absolutely can not.
Here's the breakdown of those heads:
Orange Microdark. When you plug headphones into the headphone jack, you get cabinet emulation and do not require a load on the cab out. There is no standby on this little wonder of an amp (frankly for the money I don't think you can get a better amp of this class), you just plug in the headphones and you're good for silent practice/recording. This amp is an EXCELLENT (!!!) choice for this purpose (and it sounds great).
Hugh and Kettner Tubemeister: Very smart amp, has onboard attenuator. You put it on standby and set the attenuator to "silent" and use the emulated out (which is not a headphone jack, it's meant for running to a PA or interface etc) and you do not require a cab/load. There is no headphone jack. Excellent amp for the silent recording/practicing purpose, but pricey.
Marshall JVM410h: Allegedly, if the presence and master volumes are at 0 and you are in standby, the power amp is not engaged (or at least, is engaged so minimally no damage is done), and you are fine to use the cabinet-emulated out or preamp send for silent recording. There is no headphone jack. This monster is a great amp, but very expensive and way, way more horse than you'd need unless you're playing a mid/large sized venue.
Randall Diavolo 45: Under no circumstances can you run this amp without a cab or load box. Standby, presence/master at 0, doesn't matter. Run it without a load and you're going to blow the transformer.
So how do I get headphone capability out of these amps (with the exception of the MicroDark, which has a headphone/cab emulation jack)?
Every single one of them has an speaker-emulated out. I run that into an interface (like a Scarlett or some such) and use the headphone jack on the interface. This lets me dial up the amp hard, but cut the gain going into the headphones by using the gain control on the interface. You can get any tone you want.
On the Marshall, for silent recording, I run my guitar into a Helix, run a send out of the Helix into the guitar input of the amp, run the parallel send of the amp back into the Helix receive, and on the Helix put a cabinet model in the path. I can then use the headphone jack on the Helix. Alternatively, I run the emulated out into an interface and again just use the headphone jack on the interface.
On the Randall, the same as the marshall; parallel send, or emulated out, into interface of some kind, use the headphone jack on the interface.
On any of the above, it is ALWAYS recommended to run a cab or load box on the cab out, even if the manufacturer says it's ok not to. This isn't so much because you don't believe them, it's because it only takes an unnoticed bump on a master volume, or an accidental flip of the standby, or (in the microdark) you unplug your headphones and forget to turn the amp off, to blow a tube amp that doesn't have anywhere to send the load. And again, some amps simply can't be run without a cab/load box under any circumstances.
To that end, getting a load box for people that want to use tube amps for silent recording/practice is a VERY GOOD IDEA. I have a Rivera load box that also acts as a cabinet emulator. You plug your cab out into the load box, pick the cabinet emulation you want, and either use the headphone jack on the Rivera, or run the Rivera out to an interface that has a headphone jack. The load box can eat the whole load of the power amp, so you can run your amp REALLY hot, dial back the output on the load box, and get a full-on tube signal at low output volume. This is a standard in studios.
But would I ever say "sure just plug a headphone into a speaker out?"
Total disclosure, I am not a pro amp tech. But I've been around them a long time, know some guys that are really knowledgeable, I'm really careful with my research but still made some of the rookie mistakes, and this really sounds like one of them. I would be willing to bet some money that if you asked the amp manufacturer "headphones into power amp out", there'd be a pause on the phone, followed by, "...you want to do what?"
Comment: It sounds like a hack, and Iam fairly certain would not apply to all amps, my Randall would still need something, a cab or load box. An FX loop feeds signal to the power stage but does not drive it, you could still have a load I wouldn't do it. Get a load box with cabinet emulation, and if it has a headphone jack use it, or run the load box out to an interface and use the headphone jack on that. It is absolutely the safest way to run a tube amp silently.
Comment: Thanks a lot for your answer! There's a lot I didn't know, thank you very much for taking the time write it. I do have some further questions though: this post https://www.reddit.com/r/Guitar/comments/3fji3h/listening_to_a_fender_hot_rod_through_headphones/ctp84b5/?context=8&depth=9 says it's safe to plug the "FX send" to an audio interface and a shorted cable to "FX return" to prevent any signal from going to the power amplifier. Do you think this would still harm the amp?
Answer: If you have 1/4" Headphones with 8-16 Ohm resistance, just plug them into the external speaker jack. You will need a 1/4 Mono to Stereo converter plug (Mono Male, Stereo female), but that's all.
Comment: Headphones are used to having mW put through them. Are they going to cope with all that extra power?Turn the volume right down, and it may sound awful.
Comment: Thank you! The only problem is that if the external speaker jack is used, it doesn't mute the regular speaker (sound will come out of it as usual, but now it's being duplicated to the external speakers, if I understood it correctly). To mute it, I need to to also plug something into the FX loop In, but I don't know if it damages the amp to have a plug in the FX loop that doesn't get plugged back into the FX loop Out
Comment: Ahh, I see. MonoPrice doesn't release wiring diagrams for that amp (or pretty much for anything), but you'd probably find that by plugging into the FX loop, you're losing the power amp side. If the power amp is transistor on that amp, and only the preamp has tubes, you're good. Otherwise, you need an electronics person to wire a new socket to the external speaker jack - one that breaks the thru connection when something is plugged into it. A simple enough job, and a common socket type.
Comment: Thank you again!:) People who have been dissecting the Monoprice said it's a copy of the Laney Cub (or something close to a Fender Blues Junior IV). I'm sure the power amp is all tube too. I'll try to see if someone in my university could wire the new socket
Answer: As far as I know, the external cabinet output must be after the power amp stage, otherwise your signal wouldn't have enough power to drive the speakers. So if you interrupt the signal path at the effects loop, you would mute both the internal and external speaker at the same time.
You might be able to plug the effects send from the amp into your USB interface or mixer and use headphones that way.
Comment: I don't have enough reputation to comment on TIm's post, but as far as I know, shorting the cable is the trick used by cables like these https://www.thomann.de/gb/cordial_csi3rpsilent.htm to mute the amp when the cable is disconnected. Unfortunately I don't have one available to try.
Comment: Further, my understanding is that since it is a combo amp, it always has a load for the power stage - the built-in speaker. Of course, at this point you're not using the amp as the manufacturer indended so everything is at your own risk. If you could get the manual frmo the manufacturer, maybe that will say something? I was only able to find the manual for the 5-watt version, and that one doesn't seem to have an effects loop or external cabinet connection
Comment: Great idea! I think you're right. Though I think there's the problem Tim mentioned in his answer, the amp will probably still create a load. I'm not sure of what would happen here if nothing is connected to the "FX return" and to the "external speakers" jack
Answer: Regarding the MONOPRICE Tube 112, as I understand it, and on the one I own, connecting anything to the speaker cabinet out plug disconnects the internal speaker. If yours does not, then I suspect someone has modified it, or an error was made in manufacture. Anything I plug into my speaker out, shuts down the internal completely. Advise what happens if you try a speaker cabinet in yours, if you have one. Good luck! Be careful too.
Comment: For Monoprice's price I wouldn't expect much quality control.
Comment: ojs Do you have one? The one I own, and the reviews I read, indicate the quality control seems exemplary. I have had mine for a year, play it daily, have gigged with it numerous times, and it is still in excellent condition. It runs cooler than many of the tube amps I have played in the past. I believe they are the bang for the buck. What equip do you use ojs? Just curious.
Comment: No, I don't have one but I can explain that poor quality control means that defective units make it to customers, not that all are defective. As you called it, "error was made in manufacture" and then not noticed.
Comment: Thanks! I don't have one myself, I wanted to buy one. But I think I saw a Youtube video where the guy would connect the amp to another cabinet and both would play at the same time. Or maybe I just got everything wrong, sorry but I can't remember anymore. From my edit in the first post, it seems you're right, plugging anything into the external cabinet should disconnect the internal speaker. Maybe there were different versions? I know the reverb tank was updated at some point. But probably I just got it wrong the first time


How to show that the sequence $(x^{(n)})$ weakly convergent in $l_p$, $1\le p\lt \infty$

Question: How to show that the sequence $(x^{(n)})$ weakly convergent in $l_p$, $1\le p\lt \infty$.
where $(x^{(n)})=(\underbrace{0,0,..0}_{n-1},1/n,1/(n+1),...,1/(2n),0,0,...)$ for $n\in\mathbb{N}$
Comment: It's not weakly convergent in $l_1$. It is norm-convergent in $l_p$ for $p > 1$.
Comment: I found that $||x^{(n)}-0||_p=(\sum_ {k=0}^n |\frac{1}{n+k}|^p)^{1/p}$ which converges to 0 as n goes to infnity for $p>1$. But for $p=1$ how to show it does not converges to 0.
Answer: Define for an  integer $k$ the linear functional $L_k\colon x\mapsto $ the $k$-element of the sequence $(x_j)_{j\geqslant 1}$. Since $\lim_{n\to\infty}L_k(x^{(n)})=0$ for each $k$, if $(x^{(n)})_{n\geqslant 1}$ is weakly convergent, the limit is the null sequence.
Using the linear bounded function $L\colon\ell^1\to\mathbb R$ given by $L(x)=\sum_{j=1}^{+\infty}x_j$, one can see that $L(x^{(n)})\geqslant 1/2$ for each $n$, hence $(x^{(n)})_{n\geqslant 1}$ is not weakly convergent in $\ell^1$.
Since for $p>1$ the series $\sum_{n\geqslant 1}n^{-p}$ is convergent, we obtain that $\lVert x^{(n)}\rVert_p\to 0$, hence the sequence $(x^{(n)})_{n\geqslant 1}$ is norm convergent in $\ell^p$.


How to add links to images within HTML dynamically with JS?

Question: I have 50 divs like the below, and the image is not clickable. I would like to make the image clickable, depending on what link the div contains: it is always the href link in the article_title tag.
How can I achieve this with adding just a few lines of JavaScript?
I was thinking of adding an ID to each img tag manually, and then use getElementById and do some magic, but that would take too long.

         Wealth Management

7 Tips For Lasting In Your Career

SmallCapPM -  Mar 10, 2016

            Many of you are hoping and planning for a long and successful career in finance...

Comment: what do you mean by it would take too long?
Comment: I could save time if its only a few lines of JS
Comment: you could use a for loop
Answer: Maybe this (using jQuery):

Comment: What should I put in place of "index, value"? I am asking bc I don't see them appear in the code below.
Comment: Nowhere. You may exclude them.
Comment: And instead of .block I should put in the class name right? Isn't it a problem that it's not an ID?
Comment: Its a class name because you have many of those for who you want to change stuff. Oops I made a mistake: you should wrap image with new anchor tag not change its src attribute. Let me fix it now...
Comment: Changed and tested. Now it should wrap the image in  tag with its href attribute.
Answer: if you use jQuery, you can simply wrapping the images with  element.

$(function(){
  // traversing all the images
  $('img').each(function(){
    // get the link by finding from parent
    var link = $(this).parent().find('.article_title a').attr('href');
    // replace the image with link + image
    $(this).replaceWith('' + $(this)[0].outerHTML + '');
  });
});

         Wealth Management

7 Tips For Lasting In Your Career

SmallCapPM -  Mar 10, 2016

            Many of you are hoping and planning for a long and successful career in finance...

Comment: This is very good, but it returns the href in the article_category div. I need the one in the article_title.
Comment: You are a god. Thanks so much.
Comment: I have another question. Can you tell me how can I remove the "canarywharfian.co.uk" part of the href in the article_category div dynamically? I need to remove that part otherwise if a user clicks canarywharfian.co.uk/canarywharfian.co.uk/path will load which is not ok.
Comment: @D.Richard with this function, you can get the domain >> http://stackoverflow.com/a/23945027/7572603. then you just simply use that to edit href >> $('[href]').each(function(){ link = $(this).attr('href'); domain = extractDomain(link); new_href = link.replace(domain, ''); $(this).attr('href', new_href); })
Comment: This one loops through ALL the hrefs? I only need it for the first appearing one within the div.
Answer: Per your tag of vanila Javascript, what you can do is to search for and cache all your articles. Within each article search for anchor inside your title and set its href to a newly created anchor. Append the image into the newly created anchor and prepend it into your article.
A simple example (H1 font-size reduced for demo):

var articles = document.getElementsByClassName('article');

[].forEach.call(articles, function(article) {
 var image = article.querySelector('img:first-child');
 var title = article.querySelector('h1.article_title > a');
 var anchor = document.createElement('a');
 anchor.href = title.href;
 anchor.appendChild(image);
 article.insertBefore(anchor, article.firstChild);
});
h1 { font-size: 12px; }

         Wealth Management

7 Tips For Lasting In Your Career

SmallCapPM -  Mar 10, 2016

            Many of you are hoping and planning for a long and successful career in finance...

         Wealth Management

7 Tips For Lasting In Your Career

SmallCapPM -  Mar 10, 2016

            Many of you are hoping and planning for a long and successful career in finance...

Notice, how the links to bing and google are picked up from the title anchors and inserted into a new anchor wrapping the images.


update specific field in text file in specific line

Question: Below is a code that I'm able to update the quantity of my book. But I cant seem to make it so that I can update my other things like book name, author, price etc.
Heres the code:
if grep -q "^$bookname:$author:" BookDB.txt
   then
   read -p "Update Qty to what?" newQty
   sed -i "s/^\($bookname:$author:[^:]*\):[^:]*:/\1:$newQty:/" BookDB.txt
   echo "Book's Qty has been updated successfully!"
   else
   echo "$0: BookDB.Txt: no '$title' by '$author'" >&2
   fi

My database would be like this:
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The Ring:Johnny Dept:56.80:100:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
haha:gaga:1:10:1

So how could i change certain fields like when i select the book name Lord of the ring author johnny Dept i can change the book name to maybe lord of the kings?
Lord of The King:Johnny Dept:56.80:100:38

Comment: You should consider using an appropriate language for something like this. I don't think that a shell is the right tool! For example manipulation of `csv` files is really easy and legible with `python` or `perl`...
Comment: An unordered csv file can hardly be called a "database".  At the very least, you need to put the entries in some usable order before you can use the word "database".
Answer: Like user1146332, I also suggest to switch to a more powerful language. Here an example using perl. It uses module Getopt::Long to read arguments and loops through the file for a matching line.
It seems to work but it's up to you to do a better checking of errors, for example, that both book and author variables are defined before using them in the regular expression.
One more thing, I use split() with a colon to extract fields, I don't know how you handle a book with a colon in its name but in that case you will need an additional module to parse CSV, like Text::CSV or fight harder with a better split expression.
#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Long;

my ($book, $author, $newbook, $quantity);

my $r = GetOptions(
        q|book=s| => \$book,
        q|author=s| => \$author,
        q|newbook=s| => \$newbook,
        q|quantity=i| => \$quantity,
) or die;

open my $fh, '<', $ARGV[0] or die;

while ( <$fh> ) {
        chomp;
        my @f = split /:/;
        next if @f < 5;
        if ( $f[0] =~ m/(?i)\Q$book\E/ &&
             $f[1] =~ m/(?i)\Q$author\E/ ) {
                $f[0] = defined $newbook ? $newbook : $f[0];
                $f[3] = defined $quantity ? $quantity : $f[3];
                printf qq|%s\n|, join q|:|, @f;
                next;
        }

        printf qq|%s\n|, $_;
}

An example with:
perl script.pl --book="lord of the ring" --author=dep --newbook="Lord of the King" --quantity=99 infile

Yields:
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of the King:Johnny Dept:56.80:99:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
haha:gaga:1:10:1

Answer: What about sed?

sed 's/\bLord of The Ring\b/Lord of The King/' file

$ cat file
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The Ring:Johnny Dept:56.80:100:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
haha:gaga:1:10:1

$ sed 's/\bLord of The Ring\b/Lord of The King/' file
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The King:Johnny Dept:56.80:100:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
haha:gaga:1:10:1

Send the output with redirection > to a new file or use sed's -i option for in place editing.

redirection
sed 's/\bLord of The Ring\b/Lord of The King/' file>newfile

in place etit with .bak file
sed -i.bak 's/\bLord of The Ring\b/Lord of The King/' file


List of all errors in project in CLion

Question: CLion 2016.2 helpfully detects potential errors in the file you're editing, which can be seen in the validation bar to the right of the code.
That's just a single file though, is there a way (like a tool window) to get a list of all such warnings in the whole project, or specific parts of it?
Bonus points if it also lists warnings and errors from the compiler, though that's less important, because the compiler output already includes any it found.
Answer: Yes, it is possible. The feature you are looking for is called the Inspector.
Do: Find Action... | Inspect Code. It will show a pop-up that will allow you to select the scope: file, whole project, custom, and the Inspection profile (you can choose the type of errors you want to see):

After clicking OK, this is an example of the output, that you can navigate with the mouse or with keyboard shortcuts:
Comment: Thanks. For beginners reading this: `Find Action...` can be invoked by double-tapping `Shift`.
Answer: In version 2017.2, I have it under Code | Inspect Code....
You can also right click a folder in Project view and select Inspect Code... there to be able to check only that folder.

List of all errors in project in CLion


Keep Spans Inline

Question:

Why Choose Ocho Rios?

Exceptional Quality

Each of our menu items is cooked
from fresh, high quality ingredients.
Our spices are
    in-
    house blends.

Exceptional Quality

Each of our menu items is cooked
from fresh, high quality ingredients.
Our spices are
    in-house blends.

Exceptional Quality

Each of our menu items is cooked
from fresh, high quality ingredients.
Our spices are
    in-
    house blends.

Trying to get these to display all on the same line, not staggered like a staircase.
Comment: You can't have a `p` tag inside a `span` . Check the rendered output of your browser, you will most likely have all these paragraphs outside of your `spans`. First step for you is to create a valid HTML structure.
Comment: You're generally better off using `div`s as content dividers, that's kind of what they're for.
Comment: https://validator.nu/
Comment: Thanks for the answers guys, but it still isn't displaying properly. I keep getting that staircase even with the edited code. I'm using Weebly's HTML editor. The spacing from left to right is fine, but I want them all on the same "row".
Answer: I recommend using a more conventional markup for your elements:

Then I would use css for the row and col classes to put them in a row.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
.row {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-around;
  align-items: center;
}

.col {
  flex: 1 1 33%;
}

img {
  height: 100px;
}

Comment: This will get you mostly there but you should read the guide in the link I sent so you knowhow to adjust the properties to your needs. Also I highly recommend letting the text flow without  tags and using css to size and position your icons and text inside the .col elements. Good luck hope this helps!

Keep Spans Inline


Understanding the position operator in Reed and Simon Mathematical physics vol 1.

Question: I am studying the subject of unbounded operators and I cannot understand some statements that appear in the book by Reed, Simon

Question 1. The statement "support near plus or minus infinity" means that $\text{supp}(\varphi)=\left\{x\in\mathbb{R}:\varphi(x)\neq 0\text{ and } x\geq R \text{ some } R>0 \text{ sufficiently large } \right\}$?
Question 2. Why we can make $\left\|T\varphi\right\|$ as large as we like while keeping $\left\|\varphi\right\|=1$?
Answer: I think "support near $\pm \infty$" is a poor choice is words. I would instead just take $\phi$ to be the characteristic function of the interval $[n,n+1]$ for $n$ large enough, and a simple computation would give $\|T\phi\|>n$, hence pretty large.


Use single xml layout for multiple activities with different datas

Question: I know this is a very basic question, however as a newbie i cant get to work around it.
So, I want to have multiple activities to use same the xml layout(consist for example of 1 imagebutton, and multiple textviews with different IDs). Now, for every activity, I want them to view the same layout but override the views with data unique to every activity. What is the best way to do this? And also, the imagebutton should open different URLs in a video player(youtube links).
And can somebody tell me what is the most practical way to learn android programming?
UPDATE
This is my current code:
public class TemakiActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contentviewer);
}

}
For example I have a textview with ID "descriptionviewer", and a button with ID "videolink", now, how do you code those in?
Comment: What exactly do you want your TextView and Button to do?
Answer: You can share the same layout file and the set the attributes for views in the onCreate(..) method of each activity.
If you want a different URL to open for each image button you could set it at runtime as follows
public void onCreate(Bundle b) {

    Button button =(Button)findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            //different action for each activity
        }
    });
}

Answer: Yes you can! I had multiple activities inflate the same layout but they save different shared preferences.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.same_layout);

    TextView urlDesc = (TextView)findViewById(R.id.descriptionviewer);
    urlDesc.setText("url_1"); //now in other activities-- urlDesc.setText("url_2");

    ImageButton aButton = (ImageButton)findViewById(R.id.videolink);
    aButton.setOnClickListener(aButtonListener);
}

private OnClickListener aButtonListener = new OnClickListener() {
    public void onClick(View v) {
        // go open url_1 here. In other activities, open url_x, url_y, url_z
        finish();
    }
};

Same code just swapping the text you want to set for the TextView and url to open in OnClickListener(). No more to change.


Objective-C HashMap equivalent

Question: I am trying to convert a piece of Java code which uses a HashMap that contains as a key an object and a value as an object.
private static HashMap<Class<? extends Component>, ComponentType> componentTypes = new HashMap<Class<? extends Component>, ComponentType>();

I've been reading on how to do this with Obj-C but I have not been successful, most people suggest using a NSDictionary, the problem is that they keys need to be strings and I need them as objects. The other option was NSMapTable, however it is not available on iOS. Would someone be able to assist on how I can convert this into an obj-c equivalent?
thanks,
Answer: The keys for an NSDictionary do not need to be strings. They can be any object that implements NSCopying. If the object is a custom object, however, it needs to produce sane responses to the -hash and -isEqual: messages, but this is the same as using an object in a Java collection so it shouldn't be much of a challenge.
Answer: An NSMutableDictionary (assuming that you also need to set values in the dictionary after its initialization) works in two ways:

As a traditional dictionary/hashmap in which you set values like this:
[myDictionary setObject: theValue forKey: anyObject];
As an object with KVC-compliant properties that happen to be defined dynamically:
[myDictionary setValue: theValue forKey: aString];

If the key is an NSString, then the two are interchangeable, with the exception that you can't set an object to nil with setObject:forKey:, but you can pass nil to setValue:forKey:.
Answer: You want to use an NSDictionary. You say that

they keys need to be strings and I need them as objects

The keys to an NSDictionary don't need to be strings -- they can be any object that conforms to the NSCopying protocol.
Comment: This is correct. Note that there is one common situation where `NSDictionary` *does* need string keys: if the `NSDictionary` is expected to be used in a Property List.
Answer: From NSDictionary reference

A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key's value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see "Key-Value Coding Fundamentals"). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull.

So any object that meets the NSCopying protocol can be used as a key. The string restriction is only for Key-Value Coding used for Cocoa bindings
Answer: I'm inferring that you are using a key that is does not conform to the NSCopying Protocol. In that case try using the Core Foundation equivalent of NSDictionary: CFDictionary.
http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html
Just make sure that when you are using CFDictionary that all of your objects are going to be retained in memory for the duration of the object. Since CFDictionary has to be set with weak references (at least in my experience) just be careful that you don't accidentally dealloc one of your objects whiles it's still in the CFDictionary.
While CFDictionary is "toll-free bridged" with its Cocoa Foundation counterpart, NSDictionary, I find that there are still problems with this. I've tried to add objects that were not part of the NSCopying protocol to my toll-free bridged NSDictionary and it came up with an error at run time.
CFDictionary docs: http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html
If you need mutability, use CFMutableDictionary instead like so:
    cfd = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFDictionaryAddValue(cfd, key, value);
    CFRelease(cfd);
CFMutableDictionary docs: http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFMutableDictionaryRef/Reference/reference.html#//apple_ref/doc/uid/20001497
Comment: Hi, Thanks for all the responses. If I'm using ARC and I use a CFDictionary, do I still need to handle memory?
Comment: If you use ARC with CFDictionary, you will have to handle the memory unless you decide to use the toll free bridging. I personally could not get the toll free bridging working properly for me since it kept trying to copy objects that did not conform to NSCopying
Comment: Here's more info on the matter  scroll down to the part on toll free bridging http://developer.apple.com/library/ios/releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html#//apple_ref/doc/uid/TP40011226-CH1-DontLinkElementID_5

Objective-C HashMap equivalent


What conditions have to be met for a subset $A$ of a measurable set $X$ to be also measurable?

Question: What conditions have to be met for a subset $A$ of a measurable set $X$ to be also measurable?
I understand that the union of measurable of sets is also measurable. But I am wondering if there is something about subsets of a measurable set. Are there any theorems regarding this?
Answer: You can define a measure on  a sigma field only. The subsets of $X$, that belong to the sigma-field are then measurable.


How do I combine known arguments and variable arguments to pass them to another function?

Question: I saw the following SO posts on variable arguments in Python:
What does ** (double star) and * (star) do for parameters?
function call with named/unnamed and variable arguments in python
Can a variable number of arguments be passed to a function?
None of them answered my question. So, here it goes:
I would like to define couple of functions:
def LogError(log_file, *args):
  print("USER ERROR:", ***NOT SURE ABOUT THIS PART***, file=log_file)

def LogWarning(log_file, *args):
  print("USER WARNING:", ***NOT SURE ABOUT THIS PART***, file=log_file)

I want to call them using:
error_file = open("somefile")
LogError(error_file, "Unable to find", username, "in the database.")

warning_file = open("somefile")
LogWarning(warning_file, arg1, arg2, arg3)

I want the call to LogError to be the equivalent of
print("USER ERROR:", "Unable to find", username, "in the database.", file=error_file)

and I want the call to LogWarning to be the equivalent of
print("USER WARNING:", arg1, arg2, arg3, file=warning_file)

What's the best way to accomplish that?
Comment: Since there are no other arguments to the call, `print("USER ERROR:", *args, file=log_file)`? (assuming Python 3)
Comment: @JeffMercado, I tried that. That is equivalent of `print("USER ERROR:", ["Unable to find", username, "in the database."], file=error_file)`.
Comment: The `*` is important. It will expand `args` as if the function was called with the items as individual arguments in their corresponding positions.
Comment: To get that `list` as an argument, you would have to do `print("USER ERROR:", list(args), file=error_file)`. I'm not sure what you're doing for `print("USER ERROR:", *args, file=error_file)` not to work, but I can't reproduce it.
Answer: The first link you have should provide the answer
def LogError(log_file, *args):
  print("USER ERROR:", *args, file=log_file)

def LogWarning(log_file, *args):
  print("USER WARNING:", *args, file=log_file)

That would expand the arguments as you want. But instead of crafting your own solution, you should take a look at python's built in logging feature instead.
Comment: I must've done something strange while testing. I thought I had tried that and it didn't seem to work. It works now :)
Answer: Just join them with a space, since that's the end result anyway:
print('USER ERROR: {}'.format(' '.join(*args)), file=error_file)

You really should be using the logging module, which will make your life easier:
import logging

# Create a logger
log = logging.getLogger(__file__)

# Set the output for different log levels
# this is optional, you can write out all errors to the
# console and do many combinations, such as sending emails

warning_logger = logging.FileHandler('warnings.log')
warning_logger.setLevel(logging.WARNING)

error_logger = logging.FileHandler('error.log')
error_logger.setLevel(logging.ERROR)

# Set the format of messages
# levelname will be WARNING or ERROR depending on the message
log_format = logging.Formatter('USER %(levelname)s: %(message)s')

# Set the formatters for the error loggers
warning_logger.setFormatter(log_format)
error_logger.setFormatter(log_format)

# Add the handlers to the master logger instance
log.addHandler(warning_logger)
log.addHandler(error_logger)

# Now all you need is

log.warn('This is a warning')
log.error('This is a error')

For more details check out the logging module documentation and for more recipes, the logging module cookbook is worth a read.
Comment: While that may work in this specific case, it wouldn't work for function calls in general.


Swift custom type conversion by using `as` keyword

Question: for example, I have two classes, named ClassOne and ClassTwo:
open class ClassOne {
    open var id: String?
    public init(id: String?) {
        self.id = id
    }
}

open class ClassTwo {
    open var id: String?
    open var title: String?
    public init(id: String?, title: String?) {
        self.id = id
        self.title = title
    }
}

then, create some instances:
let one = ClassOne(id: "1")
now, how to convert one to ClassTwo type by using one as classTwo?
I know I can implement a function like public init(classOne: ClassOne) {}, but I just wondering 'how to use as on custom types?'
I noticed something called _ObjectiveCBridgeable, is there anything similar for pure swift types?
Comment: And what would you expect that `(one as ClassTwo).title` evaluates to?
Comment: "string" as NSString is *bridging* between Swift and Objective-C types, see https://stackoverflow.com/questions/35893517/is-it-possible-to-replicate-swifts-automatic-numeric-value-bridging-to-foundatio on how that can be replicated for other types (using "hidden" protocols). – Very early Swift versions allowed to define custom conversions between arbitrary types, that feature has been removed long ago.
Comment: Do you mean *"custom type **conversion**"* ? – That are two unrelated types, there is no `as` conversion between them.
Comment: @MartinR yes, unrelated, but i'm wondering if I can implement some thing to convert them
Comment: @MartinR maybe the `id` in `ClassOne, or `nil`. like `String` and `NSString`, they all have some thing special and unique, but `"string" as NSString` does works
Comment: Using type conversion between unrelated types doesn't make sense.
Comment: @user5685969 yes, that's right. but this is just an example. What I'm asking here is how to use `as` on custom types to convert instances.
Comment: @MartinR thanks a lot
Answer: You don't, or rather, Swift can't.
(But in C++ on the other hand, you just need to create a constructor which takes the other type as parameter, and said constructor is called automatically (unless marked explicit).)
Your classes are not related in any way, programmatically speaking, however you have several solutions. For example:
Solution #1: Convert
You could add an init method to your ClassTwo, that takes a class one instance as a parameter.
convenience init(classOne:ClassOne) {
    self.id = classOne.id
    self.title = nil
}

You could also just have a non-init method that would do the same thing.
Solution #2: Subclass
Make ClassTwo a subclass of ClassOne
open class ClassTwo : ClassOne {
    open var title: String?
    public init(id: String?, title: String?) {
        super.init(id:id)
        self.title = title
    }
}

And now you'd see that you can use it interchangeably (but note that this can cause some headaches sometimes aswell):
func funcThatTakesA(classOne:ClassOne) {
}

let one = ClassOne(id: "1")
let two = ClassTwo(id: "id", title: "Instance")

funcThatTakesA(classOne: one)
funcThatTakesA(classOne: two) //It works!

Answer: No: they are unrelated types (even if on the surface, they share a similar internal layout).
Even if it were C structs, you force-casted a pointer of one stype into a pointer of the other, and padding/alignment were such that the "common" member id had the exact same memory layout (same type and offset from start address of the object) in instances of both types, the second member title would certainly lie outside bounds!
Swift is very strict regarding types. In your particular case, you should either:

Have both unrelated classes conform to a protocol that requires a property id of type String?
Have ClassTwo inherit from ClassOne.

...and yet, either of these approaches will only let you cast an instance of ClassTwo into one of ClassOne, not viceversa (storage for the extra property title can not be magically synthesized by the cast).
Answer: Basically, There is no relation between them so, first of all, you have to make the relationship in between two classes:
Here we show with the help of inheritance:
open class ClassTwo {
    open var id: String?
    open var title: String?
    public init(){
    }
    public init(id: String?, title: String?) {
        self.id = id
        self.title = title
    }
}

open class ClassOne:ClassTwo {
    public init(id: String?) {
        super.init()
        self.id = id
    }
}

let one = ClassOne(id:"hello") as? ClassTwo


How do I show the image in a node enlarged?

Question: I use the TinyMCE editor as site's editor. When I publish an image, I want the users click the image to view it enlarged.
How can I do this? The image is not a field; it is an image in the node.
Answer: This can be accomplished using Image Resize Filter
Here is a nice tutorial by Lullabot: Effortless Inline Thumbnails: Image Resize Filter
Answer: You can also try using Insert and Colorbox.


Dangerous convenience feature of sample function in R

Question: Please help me understand the reason for this convenience feature of the base R sample function before I submit a request to the R mailing list to modify.
set.seed(8675309)
sample(x=c(5,6), size=1, replace=T)
#[1] 6

sample(x=5, size=1, replace=T)
#[1] 3

The first example returns the expected output. However, I was puzzled as to why 3 (instead of 5) was returned in the second example. I found this reasoning in the documentation.

If x has length 1, is numeric (in the sense of is.numeric) and x >= 1,
sampling via sample takes place from 1:x. Note that this convenience
feature may lead to undesired behaviour when x is of varying length in
calls such as sample(x). See the examples.

I don't consider this convenient. In fact, due to this feature, I spent over an hour trying to dissect an issue I thought was related to a completely different code chunk. And, I would automatically write the described convenience feature as follows.
sample(x=1:5, size=1, replace=T)

I'm hoping someone can provide a decent, statistically-savvy, reason for this feature that outweighs the potential issues that could arise (like my own) before I attempt to petition for a change to a function. Also, feel free to offer reasonable alternatives.
Note: I understand that one would typically not use this function to sample from a single value (what's the point, right?), but in this case, my function was generating a random sample of IDs that were stratified and then passed to the sample function, and these IDs were occasionally of length 1.
Comment: Yeah, I hate this feature too, precisely because it can easily contribute to a bug like you described. But I really doubt R Core will get rid of it, because some people do regularly make use of it.
Comment: @bschneidr, thanks for this feedback. I wonder, though, if the convenience of not having to type 1:5 really outweighs potentially issues like my own. I was sampling patient IDs, which could have very unintended consequences for our research had I not caught the oddities in my output. Ugh.
Comment: Completely agree. I fully support changing it, it's just R Core is very conservative about changing things like this because they don't want to break R packages and other code that rely on that feature.
Comment: @whuber, you make a really good point. This could potentially be a cause for chaos in pre-existing `R` code and break a lot of `R` packages. I agree, then, with keeping as is.
Comment: It would take a book-length treatise to describe all the problems like this in `R`!  When you commit to using `R`, then -- whether you like it or not and whether you know it or not -- if you care about the quality of your work, you have also committed to constant, ongoing, testing and debugging to avoid problems like this.  Because your proposal would likely break a great deal of code, I strongly doubt it would go anywhere.
Answer: This is unfortunate, but it was that way even in Splus and people do use it, so it's unlikely to ever be changed. R Core is quite reluctant to break existing code that takes advantage of unambiguously documented behaviour.
You can always define your own version of sample that just leaves out the length(x)==1 branch
safer_sample<-function(x, size, replace = FALSE, prob = NULL)
{
        if (missing(size))
            size <- length(x)
        x[sample.int(length(x), size, replace, prob)]
}

Comment: Nice alternative function! I also used this workaround, although I prefer yours as it's more explicit about what I want to do. `unlist(sample(as.list(5),1,replace=T))`.


Catalan triangle created by $[t^{n+1}](\frac{1-\sqrt{1-4t}}{2})^{k+1}=\frac{k+1}{n+1}{2n-k \choose n-k}$?

Question: I tried to get the catalan triangle from its Riordan array. I failed at $d_{n,k}=[t^{n+1}](\frac{1-\sqrt{1-4t}}{2})^{k+1}=\frac{k+1}{n+1}{2n-k \choose n-k}$. How do I get there?
Answer: Working with the generating function $C(z)$ of the Catalan numbers
the claim is equivalent to
$$[z^{n-k}] C(z)^{k+1} = \frac{k+1}{n+1}
{2n-k\choose n-k}.$$
The generating function
$$C(z) = \frac{1-\sqrt{1-4z}}{2z}$$
has the functional equation
$$C(z) = 1 + z C(z)^2.$$
Note that $[z^0] C(z)^{k+1} = 1$ which matches the RHS of the claim
when $n=k,$ so we may suppose that $n\gt k.$ We then find
$$[z^{n-k}] C(z)^{k+1} =
\frac{1}{n-k} [z^{n-k-1}] (C(z)^{k+1})'
= \frac{k+1}{n-k} [z^{n-k-1}] C(z)^k C'(z).$$
We get from the Cauchy Coefficient Formula
$$\frac{k+1}{n-k} [z^{n-k-1}] C(z)^k C'(z)
= \frac{k+1}{n-k} \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{n-k}}
C(z)^k C'(z) \; dz.$$
Now we put $C(z) = w$ and get from the functional equation that
$(w-1)/w^2 = z.$ This yields the integral
$$\frac{k+1}{n-k} \frac{1}{2\pi i}
\int_{|w-1|=\gamma} \frac{w^{2n-2k}}{(w-1)^{n-k}} w^k \; dw
\\ = \frac{k+1}{n-k} \frac{1}{2\pi i}
\int_{|w-1|=\gamma} \frac{w^{2n-k}}{(w-1)^{n-k}} \; dw
\\ = \frac{k+1}{n-k} \frac{1}{2\pi i}
\int_{|w-1|=\gamma} \frac{1}{(w-1)^{n-k}}
\sum_{q=0}^{2n-k} {2n-k\choose q} (w-1)^q\; dw
\\ = \frac{k+1}{n-k} {2n-k\choose n-k-1}
= \frac{k+1}{n+1} {2n-k\choose n-k}.$$
This is the claim. Note that $C(z)$ is analytic in a neighborhood of
the origin. The above can also be obtained using Lagrange
Inversion,
in fact this entry treats the very same generating function.


Does $\lim_{x\to \infty}f(x)$ exist?

Question: For any $x\in \Bbb R$, $h(x)\le f(x)\le g(x)$ and $\displaystyle\lim_{x\to \infty}(g(x)-h(x))=0$. Then does $\displaystyle\lim_{x\to \infty}f(x)$ exist?
Thanks for your help.
Comment: What do you think? What does your heart tell you? Or your imagination? Try to visualize the situation.
Answer: If you're familiar with the Squeeze Theorem, then you know that $\lim_{x}h(x)=\lim_{x}g(x)$ (exists, is finite) implies $\lim_{x}f(x)$ exists and is equal to the former. Your condition is weaker. So for example $h(x)=g(x)=f(x)=x$ satisfies the problem assumption but clearly the limit is infinite. Or take $g(x)=h(x)=f(x)=(-1)^{[x]}$ where the limit doesn't exist at all.
Comment: "the limit doesn't exist" Should not be correct. But seeing that we can take $g$ and $h$ to be a little less likeable and we get what you say.
Comment: One can also take $f(x)=h(x)=g(x)=sin(x)$ and $x$ tends to infinity. The limit do not exists (even finite nor infinite for the three functions)
Comment: @AlexR: what if we take $g>h$ (except in the limit) and both g and h are differentiable everywhere? Does this still hold?

Does $\lim_{x\to \infty}f(x)$ exist?


Controlo de menu

Question: Eu tenho um menu num bundle e tenho quero acrescentar a esse menu uma parte que está noutro menu, mas quero que esses menus apareçam ambos em todas as páginas.
O menu principal é este:
{# src/RoqSys/BaseBundle/Resources/views/Default/base.html.twig #}
{% extends '::base.html.twig' %}

        {% block menu %}

                            Início

                            Configuração

Utilizadores

Postos

                            Encomendas

Registo de nova

Encomendas em produção

                            Produção

Postos

Workflow

Nova Ordem de Fabrico

Registo de Operação

        {% endblock %}

    {% block content %}{% endblock %}

E a outra parte do menu é:
{# src/RoqSys/ManutencoaBundle/Resources/views/Default/index.html.twig #}
{% extends 'RoqSysBaseBundle:Default:base.html.twig' %}

{% block menu %}
{{ parent() }}

Vista

                Intervenção

Lista das Intervenções

Nova Intervenção

                Previsões

Lista das Previsões

Nova Previsão

                Avarias

Lista das Avarias

Avaria

Consulta

    {% block content %}{% endblock %}

{% endblock %}

Só que a segunda parte do menu só parece quando ponho barra de endereço manutenção, e eu queria que aparece-se sempre.
Eu quero que fique assim

Mas aparece assim
Answer: Se o arquivo index.html.twig estende o arquivo base.html.twig, basta colocar o bloco que você quer no bloco pai.
base.html.twig:
{# src/RoqSys/BaseBundle/Resources/views/Default/base.html.twig #}
{% extends '::base.html.twig' %}

        {% block menu %}

                            Início

                            Configuração

Utilizadores

Postos

                            Encomendas

Registo de nova

Encomendas em produção

                            Produção

Postos

Workflow

Nova Ordem de Fabrico

Registo de Operação

Vista

                            Intervenção

Lista das Intervenções

Nova Intervenção

                            Previsões

Lista das Previsões

Nova Previsão

                            Avarias

Lista das Avarias

Avaria

Consulta

        {% endblock %}

        {% block content %}{% endblock %}

index.html.twig:
{# src/RoqSys/ManutencoaBundle/Resources/views/Default/index.html.twig #}
{% extends 'RoqSysBaseBundle:Default:base.html.twig' %}

{% block content %}{% endblock %}

Comment: pois mas isso já tem na quinta linha do base.html já esta o block menu.
Comment: Então: é só copiar o conteúdo do bloco menu de index.html.twig para o bloco menu do base.html.twig. Assim o menu que aparecia em apenas algumas páginas agora aparece em todas.
Comment: o problema é que no BaseBunble esse menu está a ser chamado em vários ficheiros e ManutencaoBundle esse menu também está a ser chamado em vários ficheiros, mas nos ficheiros que está dentro no ManutencaoBundle e no BaseBundle só o menu que está dentro do BaseBundle é que está a ser chamado.
Comment: Isso não é necessário. Deixe o bloco menu apenas no base.html.twig e apague o bloco dos outros arquivos. Assim você não estende o bloco e ele fica como está definido no arquivo inicial.
Comment: o que eu tenho nos ficheiros de ManutencaoBundle já está a chamar o menu base {% extends 'RoqSysControlManutencaoBundle:Default:base.html.twig' %}

{% block content -%} chama no base na penúltima linha
Comment: Como está sua hierarquia de arquivos do twig? E qual problema você está tendo atualmente?
Comment: Basicamente quero que os dois menus fiquem juntos num só e que apareçam em todas os meus ficheiros dos dois bundles.
Comment: Rodrigo Rogotti veja as imagens acima.
Comment: Fiz uma correção no código, pois o bloco `content` aparecia duas vezes e estava dentro do bloco `menu`. A solução que eu propus resolve seu problema: basta deixar o bloco `menu` apenas em `base.html.twig` (na verdade você nem precisa declarar o bloco `menu`, se ele não será estendido nos outros arquivos) e não declará-lo nos outros arquivos.

Controlo de menu


How do I put these on the same line?

Question: It's a stupid question, I'll give you that. For the life of me I can't figure out how to align the text and my colorpicker. How do I get everything to be on one line, rather than the two lines it is now. See my fiddle. I've tried getting rid of display:block and clear:both but that didn't seem to work. Here's my code:
<!doctype html>

<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />

<link href="http://evoluteur.github.com/colorpicker/css/evol.colorpicker.css" rel="stylesheet" />

    Select a color: <input id="color_picker" value="#92cddc"/>

Please see my fiddle for the css and js (I don't want to clutter everything up by posting everything here)
Answer: Try using this way: http://jsfiddle.net/C7hAY/6/
html:

  Select a color: <input id="color_picker" value="#92cddc"/>

jquery:
$(document).ready(function(){
    $("#color_picker").colorpicker();
    $("#color_picker").parent().css('float','right');
});

Although i suggest you to do it with css.
What happened there:
When you bind the colorpicker to the input element jQuery wraps it with div so if you don't style that div it will always be in the second line and i styled it dynamically with use of jQuery, using .parent().
Answer: Here is the simplest solution:
$("span > div").css("display","inline-block");

Demo: http://jsfiddle.net/C7hAY/12/
Comment: @ATOzTOA of course I just based on OP fiddle, I think he know to put a specific id or class for that span to make it unique. I don't think it's deserve to receive a downvote though
Comment: This is not scalable as this will set style for all divs inside a span.
Answer: The issue:
When you create the color picker, it wraps your <input> element inside a div. The generated code will look like this:
Select a color:

        <input id="color_picker" value="#92cddc" class="colorPicker evo-cp0">

That's why there is a newline in there.
Solution: Live Demo
Just set the style of the div to display:inline-block;.
Code:
$(document).ready(function(){
    $("#color_picker").colorpicker();

    $("#color_picker").parent().css("display", "inline-block");
});

How do I put these on the same line?


Weird URL when using my Asp.Net site

Question: I currently have a Asp.net site running, say on http://www.example.org/. When I go to http://www.example.org/, the URL in the broswer bar changes from http://www.example.org/Default.aspx to http://www.example.org/(S(atwnw1wd3kycxgocvovs1yui))/Default.aspx
What is happening here? is this a problem with my IIS 8.0 server setup? or is it my Asp.Net project?
Answer: Looks like your web.config has following setting:
<sessionState cookieless="true" />

More: http://msdn.microsoft.com/en-us/library/aa479314.aspx

Weird URL when using my Asp.Net site


Need an example of a basis for order topology on ordinals

Question: What is a basis  for the order topology on
$[0,\Omega)$ ?
$\Omega$ is the initial ordinal of cardinality $\aleph_1$
My knowledge of ordinals is very limited
I know the union of countable sets is countable
Since $\Omega$ is uncountable ,I don't
think a union can represent [$0$,$\Omega$)
and if that is the case no basis can be
found,but I am sure I am wrong.
I get this idea from
https://math.stackexchange.com/a/340091/919044
Source:A first course in Topology:Conover
Comment: What sort of basis do you want?  The order topology by definition is given by a certain basis...
Comment: The collection of all nonempty open sets is a base.
Comment: Union of *a countable family of* countable sets is countable. Obviously, for example, any set is union of the family of the singletons of its elements.
Comment: It's not a countable union of base elements, but $[0,\Omega)$ *is* a union of base elements (pick one for each element), just an uncountable one. Topologies are closed under *all* unions...
Comment: Any will do. The question is not specific and does not ask you to prove it.
Comment: Well do you know the definition of the order topology?  It by definition provides you with a basis.
Answer: First you need to realise how ordinals are built up from smaller ordinals, maybe read more on that on their Wikipedia page; I'm not sure how well your text by Conover covers this (or does he just assume this as required prerequisite knowledge?).
You basically start with the smallest ordinal $0$ (as a set, $\emptyset$) and for each ordinal $\alpha$ we already have we can form its successor, denoted by $\alpha+1$, which as a set is just $\alpha \cup \{\alpha\}$. As expected $1$ is defined as the successor of $0$, $2$ as that of $1$ etc, and so on for all natural numbers that are familiar. The first "new" ordinal number comes at the so-called limit stage: we have the ordinals $0$, $1$, $2$, $3$, $4$, etc. and we collect them (or union them, as sets, which is the same here, this justifies its existence from the union axiom) into $\{0,1,2,3,4,5,\ldots\}$ (the minimal infinite ordinal) and call it $\omega$. The new ordinal $\omega$ has a successsor $\omega+1$ which is just the set $\omega$ together with a new maximal element $\omega$, and this has a successor we denote by $\omega+2 = (\omega+1)+1$ (ordinal addition is defined to be consistent with this so that indeed $\omega$ plus $2$ becomes $\omega+2$ in this way), this has two maximal elements above the natural number ordinals in $\omega$; this goes on till we have a new limit stage when we have all ordinals $0,1, \ldots, \omega, \omega+1, \omega+2, \ldots, \omega+10000, \ldots $ and we form a union again to make an ordinal $\omega+\omega$ which has all natural numbers $n$ and all ordinals $\omega+n$ as elements; it's essentially two copies of $\omega$ one places after the other in order. But it's still a countable ordinal of course. $\omega+\omega$ is also denoted $\omega \cdot 2$ (which in ordinal multiplication is not the same as $2 \cdot \omega$!) which is a handy shortcut to denote the next countable sequence of ordinal successors $\omega \cdot 2 +1, \omega \cdot 2+2, \ldots, \omega \cdot 2+n, \ldots$ for all $n$ a natural number again. A new limit stage then gives us $\omega \cdot 3$, essentially $3$ copies of $\omega$ placed in consecutive order.
Of course this goes on and on and we get $\omega \cdot n$ for all $n =1,2,3,4,$ etc. (all made by limit steps; these ordinals do not have a predecessor $\alpha $ so that e.g. $\alpha+1 = \omega \cdot 2$, but are made from taking the union of all previous ordinals when we have formed all successors we can. This is a basic distinction that will come back in the order topology.
The limit step after all $\omega\cdot n$ is denoted $\omega \cdot \omega$ and this starts a whole new sequence again. It gets dizzying to visualise them after a while (as orders) but we still get countable well-ordered sets using these steps. It is part of the standard theory in sets and orders that every well-order has a unique "order type" and that the ordinals are sort of canonical representatives of them: every ordinal is well-ordered and every well-order is order isomorphic to a unique ordinal number (which we can define quite generically in ZFC as a transitive set, linearly ordered by $\in$ (or $\subseteq$).
There are also uncountable sets that are all-ordered so the theory tells us that there are not only countable ordinals (at all countable stages of what we did before, even if we get to $\omega^n$ and $\omega^\omega$ and beyond, we only still have countable ordinals and these get really big to visualise, as your linked post aptly tried to describe). But at some stage (by minimality) we have the smallest uncountable ordinal, usuallty denoted $\omega_1$ nowadays (older texts follow old Cantor in naming it $\Omega$, but it's only the first uncountable ordinal, hence te subscript $1$).
But now to the order topology: we have an uncountable set $X=[0,\omega_1)$, with a minimal element $0$ and no maximum ($\omega_1$ a limit ordinal).
If $\alpha$ is in the set, so is the next larger $\alpha+1$ (just $\alpha$ with a maximum added), and if $\alpha_n, n=1,2,3,$ is a sequence in $X$, their union is also an ordinal and larger than all of them, denoted by$\sup_n \alpha_n$ and also a member of $X$ as it still is a countable ordinal (a countable union of ocountable sets is countable).
All elemts are either $0$, a successor of the form $\alpha+1$ or a limit (having no predecessor). Remember how the base for the order topology works: a minimal element (here $0$) has a local base of the form $[0,x)$ where $x \in X$. In particular, $[0,1) = \{0\}$ is an open set and $0$ is an isolated point of $X$. If $x=\alpha+1$ is a successor ordinal, then $\{x\} = (\alpha, x+1)$ is also open. (open intervals are a local base, but this is clearly the smallest open set around $x$ that is possible; it's an open interval hence open.) So $0$ and all successors are open singletons and isolated. Limit ordinals are more interesting and indeed are limti poits of their predecessors: e.g look at $\omega \in X$. A basic neighbourhood is an open interval, so pick $n < \omega$ and $y=\omega+1 > \omega$, then $(n, \omega+1)=\{n+1, n+2, \ldots, \omega\}$, so a "tail" of the natural numbers plus $\omega$ itself. So basic neighbourhoods for limits  "look the left" : we pick some tail from the predecessors (by picking a left endpoint for the interval) and use the successor of the limit as the right hand end point of the open interval and the result is a "tail plus limit ordinal" set. This is basically (pun intended) what open neighbourhoods of limit ordinals look like. So it's un uncountable set, with loads of isolated points (as may as $|X|$) and scattered throughout them limits that have infinite left looking neighbourhoods and are not isolated, but sort of glue them together (also $|X|=\aleph_1$ many). If we take any incresing sequence in it, its limit is also in $X$; we cannot reach the "end" of the set merely by countable sequences; it's one of the main reasons (besides beauty, of course) to bring it into topology courses, to show that sequences are not always quite enough to do all things in topology.
Read up on ordinals and to help visualising I found the book "Infinity" (and the mind?, not quite sure of the full title) by Rudy Rucker very interesting as a high school kid and it tickled my imagination in these respects. It helped motivate me to study pure maths later.
Comment: @Plotinus well, the limit steps are the "innovation " of ordinal numbers and also where the order topology gets more interesting.
Comment: He gives a chapter on infinite sets ,but assumes you should know more
Comment: Thank you Henno for a great post . I knew the
Comment: You're welcome. I hoped it was clear enough to give an impression.
Comment: Thank you Henno for a great post . I knew how ordinals are built up. I studied natural numbers and Peano properties and proved basic stuff. I just didn't understand how it related to order topology.


React and Electron, Chaining event handlers

Question: Is there a way to chain event handlers in React/JavasSript to create more functionality?
In the code below, in the div class=resizer I am in need of an event that allows for 'mouse down click', then 'mouse drag' before the function is executed.
const remote = window.require('electron').remote

const TitlebarDev = () => {

    const window = remote.getCurrentWindow()

    // allows top side resizer with click to restore
    const resizerRestore = () => {
        window.restore()
    }

    const resizerMoveRestore = () => {
        window.restore()
    }

    return (

hi

Node Debug

    )
}

export default TitlebarDev

Comment: Alright I cleaned it up a lot, thanks.
Comment: Just add a boolean variable that states whether the first condition (click) is met
Comment: If you could abbreviate your question, I'm sure you'll get answers much more quickly
Comment: Right in the JSX? Like a ternary operator? Can you write a little example? Thanks
Answer: As I mentioned in the comment, you need to keep the state of your first condition and check it upon the second event taking place.
In the following basic Vanilla JS example, I allowed the movement of the foo element only after it's clicked (and only while the mouse is still down).
For this state check I've used the isClicked variable.

const element = document.getElementById('foo');
var isClicked = false;

element.addEventListener('mousedown', function() {
  isClicked = true;
});

element.addEventListener('mouseup', function() {
  isClicked = false;
});

document.addEventListener("mousemove", function(event) {
  if (isClicked) {
    element.style.left = (event.clientX - 25) + 'px';
    element.style.top = (event.clientY - 25) + 'px';
    // Please note that I arbitrarily chosen foo's
    // width and height to be 50px, hence the 25px offset
  }
});
#foo {
  width: 50px;
  height: 50px;
  background-color: tomato;
  position: absolute;
}

If you're using React, you can always (and preferably) use your state to store these... states ;)


What is "sneak attack by Roger" (SABR)?

Question: Recently there was a discussion about a new element in Federer's play which some journalists dubbed sneak attack by Roger or SABR.
What exactly this shot/point build-up is?
What type of player can successfully use this tactics? What abilities does a player need to be able to take an advantage of this? (Probably also weaknesses of the opponent play a role here?)
This recent post is, to some extent, related - although it asks about this with relation to tennis rules: How far is too far for Roger Federer?
Answer: First of all, I have to say, all this while, I thought SABR was an acronym for Super Aggressive Baseline Return. Sneak Attack By Roger sounds so much fun.
Back to the question, this is a very good blog on the effectiveness of SABR. Some excerpts follow

On average,
servers win about 64% of points and hold about 80% of service games.
For most players, breaks of serve rely more on the server's
occasional lapses. To put it in numerical terms: A passive returner is
playing the lottery in every return game–a lottery with only a 10% to
20% chance of winning.
The best way to earn more breaks of serve, of course, is to win more
return points.
The alternative is to change the rules of the lottery. Instead of
accepting a steady rate of 35% of return points, a hyper-aggressive
strategy is more likely to make the point-by-point results more
streaky, even if the overall rate doesn't change.

That basically means, even though, a player using SABR tactic occasionally, will win an overall same number of return points, but he is more likely to break an opponent's service game than with a passive return, because of the increase in the unpredictability factor.

A player who wins 35% of return points will, on average, break in 17%
of his return games.
If that same player wins 30% of return points in half of his games and
40% of return points in the other half, he'll break serve 18% of the
time.
Double the variation and say that the returner wins 25% of return
points half the time and 45% the other half. Now he'll break serve in
21% of games, or one extra break per 25 return games.
The real magic happens when we expand the variation to an even split
between 20% of return points and 50% of return points. In that
scenario–when, remember, our returner is still winning 35% of
points–the break rate improves to 26%, almost one more break per ten
return games. On average, that's an extra break per best-of-three
match, and closer to two extra breaks in a typical best-of-five match.

Many tennis writers have written about how SABR is more fruitful a tactic to unsettle an opponent's rhythm rather than to win return points. Take the case of Federer's win over Stan Wawarinka in the semifinals of US Open 2015. Stan was looking to repeat his comprehensive win over Federer at French Open semis 2015, connecting the ball well & making winners in the first 3 games of the set. Federer SABR-ed him 2 times in the 3rd game & took rest of the serves aggressively, inducing a double fault & subsequently a break. Stan was rattled & couldn't recover that touch on his strokes & Federer just ran away with it.
He did the same thing to Djokovic in Cincinati finals, unsettling his serve & putting pressure on the returns & winning 39% of return points
Coming to the shot itself, SABR is tried on an opponents 2nd serve & that too against average 2nd servers. Federer didn't try it against Isner in his QF match much, I think just once since Isner like Karlovic are heavy servers. Most of the rest of the players have average 2nd serves.
Federer moves in just when the opponent tosses the ball in the air so that the server cant change the direction in which he will serve & also to create a disturbance in the peripheral vision of the server to increase the chance of a double fault. This has happened on many occasions against Stan, Kolchreiber(spellcheck), even Djokovic in today's US Open finals.
Which players can try it? Well, those that are excellent movers on the court. Someone that comes to mind ahead of even Federer is Justine Henin who was much better mover on court but she never tried it. Other active players who could try it are Radwanska(excellent hand-eye coordination & silken touch). Nobody else comes to mind because most players on both ATP & WTA play from the baseline & are not good movers towards & away from the net while they can chase balls from one baseline corners to another without breaking a sweat. The perpendicular movement is crucial because the one SABR-ing has less time to cover an open court if the SABR return is short & within reach of the server
EDIT Here is an excellent video compilation of SABR with slo-mo reply
Comment: When searching for the origin of this name, I found this: https://twitter.com/staffsky/status/638105975610830848 Or course I do not claim that the name used in my question is correct one. I simply used the name which I heard.
Answer: Yes it's a new element of Federer's gameplay. To do this, he must time his opponent's serve correctly. He waits for the opponent to toss the ball into the air, and then when they are looking upwards to the sky, he rushes forward from the baseline toward the net. He is then able to take the ball early and catch the server by surprise. He does not win a large majority of points when he uses this tactic, but it does get in the opponent's head, usually causing them to make more errors on serve (double faults).
He mainly only used it in practice; when Severin Luthi advised him to use it in matches, Federer was not sure if it would work, but liked the results, and continued using the tactic throughout the US Open. It does not work well against high-pace servers, though (John Isner, Jo-Wilfried Tsonga, etc.), since Roger does not have ample time to react to the serve, often over 130-135 miles per hour.
Comment: "usually causing them to make more errors on serve (double faults)." Do you have a reference for this claim?
Comment: http://www.usopen.org/en_US/scores/completed_matches/day20.html. ( second match on page shows the men's final; click on Federer, then match & stats). This shows Federer caused Djokovic to have more double faults than any other of his matches in the tournament. This was also the case with Phillip Kohlschreiber, and it caused Leonardo Mayer to make 7 double faults.
Comment: I can drill down from that link to the actual [Federer vs Djokovic match](http://www.usopen.org/en_US/scores/stats/day20/1701ms.html), but that doesn't reveal anything very much at all. Federer lost, and made as many double faults as Djokovic. That's not particularly strong evidence, and certainly isn't a big enough sample size to prove anything.
Comment: We're not talking about how many double faults Federer made, that is irrelevant. Also, yes the sample space is indeed small, but he has only began utilizing the tactic with any significance very recently.
Comment: So what statistically significant evidence do you have for your assertion that Federer's tactics "get in the opponent's head" and "[cause] them to make more errors on serve"?
Comment: For both of these, you can refer to the above post: "Stan was looking to repeat his comprehensive win over Federer at French Open semis 2015, connecting the ball well & making winners in the first 3 games of the set. Federer SABR-ed him 2 times in the 3rd game & took rest of the serves aggressively, inducing a double fault & subsequently a break. Stan was rattled & couldn't recover that touch on his strokes & Federer just ran away with it.

He did the same thing to Djokovic in Cincinati finals, unsettling his serve & putting pressure on the returns & winning 39% of return points."

What is "sneak attack by Roger" (SABR)?


Form Tag is misplaced on adding dynamically using jquery in a table as a row

Question: I am trying to add a HTML Form as a table row dynamically using Jquery 1.3.2 (Please don't ask why such an older version). Hierarchy of tags should be as below since I need the form to be added as a table row.

<form><input/>	<button/>	</form>

The issue I am facing is that form tag is coming out of hierarchy

<form></form><input/>	<button/>

I have already tried some solutions but does not work. e.g. stackoverflow.com/questions/20000198

$('#addNewRow').click(function() {
  var form = '
<form action="add" method="post" id="id_frmAdd">' +
    '<input type = "text" cssClass="" name="col1" id="id_col1"/>	' +
    '<input type="submit" value="Add" name="addBtn" id="id_addBtn"/>	' +
    '<input type="button" value="Delete" name="rowDeleteBtn" id="id_rowDeleteBtn"/>	</form>
';
  $('#scrollTable tr:first').before(form);

});

$('#id_rowDeleteBtn').click(function() {
  $('#id_rowAddFlight').remove();
});
div.row_manipulator {
  float: left;
  background-color: #21405d;
  padding-left: 2%;
  padding-top: 0.5%;
  padding-bottom: 0.5%;
  padding-right: 2%;
}
div.row_manipulator a {
  color: #FCFF9D;
  font-family: sans-serif, "Courier New", monospace;
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  text-decoration: none;
}

    <s:a href="#" id="addNewRow">Add New Row</s:a>

          Column 1
          Column 2
          Column 3

Provided below is Screenshot of Dynamically Generated HTML from Chrome Dev Tool after Clicking the "Add Row" Link.

Can anyone help me point out what i might be doing wrong here and i how i can fix it? Thanks a lot in advance.
Answer: Although you can hand code a <form> tag inside a
 and the browser will allow it[1], behind the scenes it is complicated (and the browser is adjusting things for you).
Technically speaking (W3C Spec) the only valid children of a
 are  and  elements, so when you try to add a form via JavaScript the browser is likely going to complain.
TL;DR you will want to add your form to wrap the entire
 or, add it to be within a specific  element.
[1]: Re 'allow' - the browser 'accepts' it, but modifies the real DOM it works with to overcome this invalid nesting.
Comment: @DavidThomas *allow* in this case means you can do it, but the browser will modify the actual DOM that it is using such that it is valid. (e.g. the browser will move the form to wrap the table)... but the visible DOM in the dev tools will still show the invalid nesting.  Sadly most of this started from back in the day when developers didn't want the extra space (margin) above/below forms and they discovered a hack that nesting the form inside a table would remove the margins. Long story short, attempting to nest a form wrapping TR elements will cause trouble even if at first it appears to work
Comment: "*Although you can hand code a `` tag inside a `` and the browser will allow it*" - really? I'm on mobile currently, so checking this is painful, but I seem to remember that browsers rearrange things, for validity, when constructing the DOM from the invalid html.
Comment: @scunliffe :: add it to be within a specific  element -> Doing this I will not be able to use all elements to submit in form. Please note that i have multiple `` elements, gave only few for sake of simplicity. Also I am not sure putting form tag outside of table can help in my situation as i can have 1000s of rows in my table and I do not want to risk all rows to be submitted to backend.
Comment: @rockstar89 I understand... but unfortunately what you are trying to achieve *won't work*.  You likely need to make 1 form that wraps the entire table, and then uniquely name your form elements (added to each TD as needed)... then submit your entire form (or selectively find parts within it, and submit a subset via AJAX)
Comment: I have already done the same with loading few datarows dynamically from backend using a iterator in my JSP page so it is evident that `` can be placed inside `` and browser will not restructure the DOM elements.
Comment: It **looks** like it works, but it doesn't.  This is simply not valid HTML. If you inspect the actual nested DOM that the browser uses (not the view-source, and not the dev tools view) you will find that it modifies the actual DOM to attempt to make your code valid/usable.
Comment: @scunliffe Certainly that is true that it's not valid HTML to put Forms inside table rows where only `` elements belong. I will look into placing the `` nested by the `` but in the meantime will wait for other comments from other community members. Thanks for suggesting an alternative way. I will accept your answer if I cannot find another alternative which will match my requirements and yours work. Thanks once again.
Comment: This should have a million "up votes."  For two days I couldn't figure out why  a dynamic form wasn't submitting.  Hours and hours lost.  Most suggestions were to "bind" the form to the document, which I was already doing.  So, I decided to re-write the code in case there was something I was missing, like a type-o.  On the re-write, I left out the table for simplicity, and it worked fine.  So then, to get formatting back, I re-introduced the table mark-up.  BAM!! The form wouldn't submit again.  I wish I new to even look this up 3 days ago!!