What does it mean when commentators say batsman did not offer a shot to LBW?

Question: I have often heard when a batsman is adjudged LBW, if he did not play any shot, the commentators mention that everytime specirically. For example, the batsman is out! He did not offer a shot to this ball!
What does this mean? Is there a law that states anything regarding batsman not offering shot when the ball hits pad? Or is it easier for umpire to give the batsman LBW if he did not offer a shot ?
Answer: Under the normal laws for an LBW dismissal, the ball must impact the batsman inline with the stumps to be considered to be out LBW.
However, if the batsman makes no genuine attempt to play a shot at the ball, the ball does not have to impact inline with the stumps, though it must still impact on the off-side of the stumps.
MCC Laws of Cricket: Law 36 - LBW

36.1.4
the point of impact, even if above the level of the bails,
either is between wicket and wicket
or if the striker has made no genuine attempt to play the ball with the bat, is between wicket and wicket or outside the line of the off stump.

Handy MCC Animation


Draw Text Over Bitmap

Question: I'm trying to put text over map marker but it always appears under it.
First I convert drawable to bitmap and then draw text on it. drawable to bitmap conversion works fine, I only have a problem with text overlay.

I have already tried these:

Adding text to a bitmap in memory in Android
https://stackoverflow.com/a/7328777/3423468
https://stackoverflow.com/a/8831182/3423468

and many more with no luck.
This is my current method:
Bitmap drawableToBitmap(Drawable drawable)
    {
        var bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        var canvas = new Canvas(bitmap);
        if (shouldDrawText)
        {
            Paint paint = new Paint();
            paint.setColor(Color.WHITE);
            paint.setStrokeWidth(40);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern

            //canvas.drawBitmap(bitmap, 0, 0, paint);
            canvas.drawText("Testing...", 10, 10, paint);
        }
        drawable.SetBounds(0, 0, canvas.Width, canvas.Height);
        drawable.Draw(canvas);
        return bitmap;
    }

Any ideas what I'm doing wrong?
Comment: Have you considered using the drawable as a `compound drawable` **inside** the TextView?
Comment: yes but as long as I need that for map marker I skipped it.
Comment: Any updates on how you solved this issue please?
Answer: paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern

Here you use SRC_OVER, which means the source will be over the DST will be under. The DST is the new pixels to be drawn.
You should use DST_OVER to draw the new pixels on top of the old pixels.
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER)); // Text Overlapping Pattern

See here an overview of how porterduff works

Comment: Well elaborate .Move ahead
Comment: thanks for the answer but doesn't seem to be enough. I'm missing something
Comment: What's also important is to verify the order of drawing

Draw Text Over Bitmap


Selecting features for improving classification accuracy

Question: I have a dataset in which each sample has around 500 features. I know that in this feature set, some attributes are useful and may positively improve the classification accuracy. But some attributes are not useful and may even decrease classification accuracy. Problem is I don't know which of these attributes have positive effect. Can you please suggest some ways how I can find out those attributes which have positive effect and discard others which have negative effect?
Answer: First, it is important to notice that finding the optimal subset of features is NP-hard (see Wrappers for feature selection). Hence, you look for computationally efficient, sub-optimal approaches.
There are many, many possibilities. The two most basic approaches are particular cases of greedy search: start with all (resp. none) of the features, and remove (add) the feature which leads to a least (biggest) decline (improvement) in the recognition rate (this so called wrapper methods are discussed in the first reference).
Correlation methods (for example, based on mutual information, see references on the corrensponding wikipedia page).
More recently it random forest have proven to be efficient for this task (in addition to having a very good performance in many tasks). See Variable selection using Random Forests for a description of a couple of basic heuristics based on the ranking of features provided by the random forest.
See this blog entry for an intuitive explanation of the feature importance measure provided by the random forest algorithm.


Maximum likelihood estimator for model without the predictor variable

Question: We have the following simple linear model without the predictor variable:
$y_t = \beta_t + \epsilon_t \quad \text{ where } t = 1, 2, \ldots,n; \ \epsilon_t \sim N(0, \sigma^2)$
What is the maximum likelihood estimator for $\beta_t$?
Proceeding with the log-likelihood function and removing the constant term and the term with $\sigma^2$, we find that the problem reduces to the following minimization problem:
$\min_{\beta_t}\sum_{t=1}^{n}(y_t - \beta_t)^2$
The maximum likelihood estimator for $\beta$ is therefore the corresponding $y$. Is the interpretation correct?
Comment: Is $\sigma^2$ known?
Comment: I think I have followed, and described, an MLE method, but agree that the final result for a single $\beta_{MLE}$ in our model, if single $\beta$ were the case, would be the same as the least square solution of single $\beta$. But it is the MLE interpretation about different $\beta$s that I am not fully certain yet about.
Comment: Yes, $\sigma^2$ is know. Say, it equals 1.
Answer: If you're estimating a separate $\beta_t$ parameter for each data point, the maximum likelihood solution is to set $\epsilon = 0$, and so $\sigma = 0$. This model can perfectly fit your data, but is useless, since it has one parameter per data point.
A more useful model is
$y_t = \beta + \epsilon_t$, with only one $\beta$ parameter. The MLE of $\beta$ is just the mean of the $y$ values. The MLE of $\sigma^2$ isn't exactly the same as the sample variance, but it's close.
Comment: $\sigma = 0, \beta_t = y_t$ is the MLE, and has a likelihood of 1, since all values of $y$ are exactly where the model predicts them to be. If you restrict your analysis to, for instance, $\sigma \geq .1$, then $\sigma = .1, \beta_t = y_t$ is the MLE.
Comment: Thanks. I agree it's more interesting to have only one $\beta$ in the model for practical purpose. However, on a pure theoretical pursuit, if we have $\sigma \ne 0$ and hence $\epsilon = 0$ does not hold true, what can we say about the MLE of $\beta$?


apresentar mensagem dados salvo com sucesso para usuario!

Question: Gostaria que apresentase uma mensagemna tela assim que usuario salvar os dados, estou querendo um alert desses que está no link abaixo, segue o codigo:
https://www.w3schools.com/bootstrap/bootstrap_alerts.asp

CODIGO DA PAGINA:
<?php

 session_start();

$codUsuario = $_SESSION['UsuarioID'];
$ieqbairro = $_POST['ieqbairro'];
$pastor = $_POST['pastor'];
$lider = $_POST['lider'];
$celulaAtivas = $_POST['celulasativas'];
$participantes = $_POST['participantescelulas'];
$quantidadereunioes = $_POST['quantidadereunioes'];
$quantidaensamensal = $_POST['quantidaensamensal'];
$diaensaio = $_POST['diaensaio'];
$horaensaio = $_POST['horaensaio'];
$totalmembrosdepartamento = $_POST['totalmembrosdepartamento'];
$vocal = $_POST['vocal'];
$mulhercontralto = $_POST['mulhercontralto'];
$mezzosoprano = $_POST['mezzosoprano'];
$soprano = $_POST['soprano'];
$homensbaixo = $_POST['homensbaixo'];
$baritono = $_POST['baritono'];
$tenor = $_POST['tenor'];
$guitarra = $_POST['guitarrista'];
$baterista = $_POST['bateristas'];
$tecladista = $_POST['tecladistas'];
$violao = $_POST['violao'];
$baixo = $_POST['baixistas'];
$meialua = $_POST['meialua'];
$cajon = $_POST['cajon'];
$outros = $_POST['outros'];
$ministeriodecarreira = $_POST['ministeriocarreira'];
$descrinomemstcarreira = $_POST['nomeministeriocarreira'];
$connect = mysqli_connect('localhost','root','') or die('Erro ao conectar ao banco de dados');
$db = mysqli_select_db($connect,'db_uberlandia');
mysqli_set_charset($connect,'utf8');
$query = mysqli_query($connect,"INSERT INTO ficha_Cadastral_Musica (CodUsuario,ieqbairro, pastor, lider, celulaAtivas, participantescelulas, quantidadereunioes, quantidaensamensal,diaensaio, horaensaio, totalmenbrosminis, vocalquant, mulhercontralto, mulhermezzosoprano, mulhersoprano, homensbaixo, homensbaritono, homenstenor, guitarraqtd, bateristaqtd, tecladistaqtd, violaoqtd, baixoqtd, meialuaqtd, cajonqtd, outros, ministeriodecarreira, descrinomemstcarreira) VALUES ('$codUsuario','$ieqbairro', '$pastor', '$lider', '$celulaAtivas', '$participantes', '$quantidadereunioes', '$quantidaensamensal', '$diaensaio', '$horaensaio', '$totalmembrosdepartamento','$vocal', '$mulhercontralto', '$mezzosoprano','$soprano', '$homensbaixo', '$baritono', '$tenor', '$guitarra', '$baterista', '$tecladista', '$violao', '$baixo', '$meialua', '$cajon', '$outros', '$ministeriodecarreira', '$descrinomemstcarreira')") or die('Erro ao inserir ao banco de dados');

if($query){

    echo '
Dados Salvo com Sucesso!

';

    }

mysqli_close($connect);
?>

Bom aparece só a escrita na tela, mais não aparece o alert verde igual está no bootstrap
Comment: Nota que vc está fechando a div 2x no `echo`: ``.
Comment: E o que acontece quando você executa o código?
Comment: Coloque esse no seu if: `else { echo 'Falha ao Salvar os Dados!';}`
Comment: estou fazendo meu codigo na pagina php assim, mais da erro
if($query){
   ''

     ' '
      ''
    echo 'Sucesso ao Salvar os Dados!';

    }
Comment: ai da esse erro aqui

Parse error: syntax error, unexpected ''

E verifique se essa div irá reconhecer.
Tente modifcar sua div para: echo "
Dados Salvo com Sucesso!
"
Se não funcionar você trabalhar com sessões e verificar se o seu "IF" está correto.
Outra solução seria você mesmo criar os Style dentro da DIV. E ir personalizando do seu jeito. Não precisa necessariamente pegar a Class do Bootstrap - Faz uma sua que seja parecida.
Ex:
exemplo

Answer: Favor verificar se os scripts do Bootstrap estão sendo carregados na página.
Se o Bootstrap não for carregado na página não adianta usar as classes e tags do bootstrap, nenhum CSS vai ser aplicado.
Para utilizar o bootstrap é necessário incluir um import dos arquivos bootstrap.min.css e bootstrap.min.js (Verificar documentação do bootstrap).


steady state solution to differential equation - checking my work

Question: EDIT: fixed a stray negative sign.
The problem as given:
$y'' + 2y' + 5y = 10\cos t$
We want to find the general solution and the steady-state solution. We're using $\mu y'' +  c y' + k y = F(t)$ as our general form.
OK, so I first want the general solution to the 2nd order DE. That should be easy: the characteristic equation is $\lambda^2 + 2\lambda + 5$ and it has imaginary roots at $-1 \pm \sqrt{-4}$ which is $-1\pm 2i$.
So the general solution should be $y=C_1e^{-t} \cos 2t + C_2e^{-t}\sin2t$
The steady state solution is given by the Fourier series $y_p(t) = \alpha_0 + \sum_{n=0}^\infty \left( \alpha_n\cos \frac{n\pi}{p} t + \beta_n \sin \frac {n\pi}{p}t\right)$
We know the constants $c, \mu, k$ from the original equation, they are 1, 2, 5, respectively. So $\alpha_0 = a_0/k$ and $a_0 = \frac{1}{2\pi}\int_{-\pi}^\pi 10 \cos tdt$ and since $\cos t$ is an even function it goes to zero on any symmetric interval. so $\alpha_0=0$.
To get $\alpha_n$ and $\beta_n$: $$\alpha_n = \frac{A_n a_n - B_nb_n}{A_n^2+B_n^2},\ A_n = k-\mu\left(\frac{n\pi}{p}\right)^2, \beta_n = \frac{A_n b_n + B_na_n}{A_n^2+B_n^2},\ A_n = k-\mu\left(\frac{n\pi}{p}\right)^2$$ and the latter expression is $(5-1)(\frac{n\pi}{2\pi})^2$ which makes $A_n = n^2$. $B_n = c\frac{n\pi}{2\pi} = n$. That gets us $\alpha_n= \frac{n^2 a_n - nb_n}{n^4+n^2}$. Now to find $a_n$ and $b_n$.
From the other Fourier formulas $$a_n = \frac{1}{\pi} \int_{-\pi}^{\pi} f(x) \cos nx dx, \  b_n = \frac{1}{\pi} \int_{-\pi}^{\pi} f(x) \sin nx dx$$ or $$a_n = \frac{1}{\pi} \int_{-\pi}^{\pi} 10 \cos t dt \cos nt, \  b_n = \frac{1}{\pi} \int_{-\pi}^{\pi} 10\cos t \sin nt dt$$
We can make the integration simpler using some trig identities because integration by parts gets you a bunch of repeating integrals. $\cos a \sin b = \frac{1}{2}[\sin (a+b) - \sin (a-b)$ and $\frac{1}{2}[\cos(a+b)+\cos(a-b)] = \cos a\cos b$. That gets us $$a_n = \frac{10}{\pi} \int_{-\pi}^{\pi} \frac{1}{2}[\cos ((1+n)t) +\cos ((1-n)t)]dt, \  b_n = \frac{10}{\pi} \int_{-\pi}^{\pi} \frac{1}{2}[\sin ((1+n)t) -\sin ((1-n)t)]dt$$
Integrating all this stuff I got:
$$a_n=\frac{5}{\pi}\left[\frac{\sin (1+n)t}{1+n}+\frac{\sin (1-n)t}{1-n} \right]_ {-\pi}^{\pi}, \ b_n=\frac{5}{\pi}\left[\frac{-\cos (1+n)t}{1+n}+\frac{-\cos (1-n)t}{1-n} \right]_ {-\pi}^{\pi}$$
$a_n$ goes to zero since any integer multiple of $\sin \pi$ is zero. That leaves $b_n$, and leaves us with $b_n =\frac{5}{\pi} \left[\frac{2}{1-n^2}\right]$. We go all the way back to the equations for $\alpha_n$ and $\beta_n$ and when I plug the relevant values into the expression for $\alpha_n$ I got $\frac{-10}{\pi(n - n^5)}$. Meanwhile I got the  value for $\beta_n = \frac{-10}{\pi - \pi n^4}$.
After all that I end up with: $$y_p(t) = \sum_{n=0}^\infty \left( \frac{-10}{\pi(n - n^5)}\cos \frac{n}{2} t + \frac{-10}{\pi - \pi n^4} \sin \frac {n}{2}t\right)$$
Is that my steady-state solution? Or did I really screw things up someplace? I am sorry for the  long post but I like to make sure I work through all the steps.
And anyone brave enough to read this thanks a bunch for your time and patience.
Comment: Your roots of the characteristic polynomial should be $-1\pm 2\rm{i}$. If they were as you write, there would be no steady state solution.
Comment: I fixed that -- arg! the stray negative sign strikes again. More seriously, did the rest of it work?
Comment: I do not see any reason to look for a solution in the form of Fourier series. Just because $10\cos t$ has Fourier series $10\cos t$. I would suggest to look for a particular solution in the form $A\cos t+B\sin t$, find $A$ and $B$, and this will be your steady state solution
Comment: Fixed the general solution too. @Artem -- my sense was that was the point of the exercise. But yes, finding i your way is probably easier to do.
Comment: Jesse You are making a very common mistake: start using formulas before thinking for a second. You are looking for a Fourier series of $10 \cos t$ using your lecture formulas for $a_n$ and $b_n$. First, you find them wrong. But the point is that you do not need to look for them. $10 \cos t$ is _already_ Fourier series with $a_1=10$ and $a_n=b_n=0$ for any other $n$
Comment: I get that the 10 cos t is already a fourier, I was thinking about how to derive that result. But it would help a lot if you could tell me if I have done something wrong in the above outline and where. My sense was that if you go through this whole process you should end up with n A cos t + B sin t type of solution. And that is what I get, at least with a summation in it. But if I have messed this up form the get go then by all means tell me!
Comment: Again, $b_n=0$ for any $n$, $a_1=10$, $a_n=0$ for all other $n$.
Comment: @Artem -- i think i see where the mistake is! Thanks.
Comment: Actually, i should say I see where $a_n$ goes to zero -- and where $b_n$ goes to zero, but I am still not sure....
Answer: Answering my own question and taking Artem's advice, I tried this....
$y'' + 2y' + 5y = 10\cos t$
We want to find the general solution and the steady-state solution. We're using $\mu y'' +  c y' + k y = F(t)$ as our general form.
the characteristic equation is $\lambda^2 + 2\lambda + 5$ and it has imaginary roots at $-1 \pm \sqrt{-4}$ which is $-1\pm 2i$.
So the general solution should be $y=C_1e^{-t} \cos 2t + C_2e^{-t}\sin 2t$
The steady state solution is given by the Fourier series $y_p(t) = \alpha_0 + \sum_{n=0}^\infty \left( \alpha_n\cos \frac{n\pi}{p} t + \beta_n \sin \frac {n\pi}{p}t\right)$
But we needn't be that complicated, it seems to me, since could try looking for solutions in the form of $y_p = A \sin t + B \cos t$.
We differentiate and we get $y_p' = A \cos t - B \sin t$ and $y_p'' = -A \sin t - B \cos t$.
Substitute in $y_p$ to the original equation. We get $$-A \sin t - B \cos t + 2(A \cos t - B \sin t)+ 5(A \sin t + B \cos t) = 10 \cos t$$
And simplifying we have
$$(4A -  2B) \sin t - (4B+ 2A) \cos t  = 10 \cos t$$
And that leaves us with $(4A -  2B) = 0$ and $(-4B -  2A) = 10$. Solving for both we get $B = -2$ and $A =-1$.
So the steady state solution is
$$y=C_1e^{-t} \cos 2t + C_2e^{-t}\sin 2t - \sin t - 2 \cos t $$
Now here's the part where everyone tells me I messed this up :-) I just feel I have done something way off here. But it seems ok...
Anyhow, thanks for bearing with me.
Comment: The only thing is that your last $y$ is not the steady state. Steady state is something which is true for $t\to\infty$
Comment: So which would be the steady state solution? As $t \rightarrow \infty$ wouldn't my $y \rightarrow 0$? Or at least $-\sin t - 2 \cos t$?


Where is the error // why doesn't it work? (Java Chat program)

Question: I wanted to write a UDP java chat program where I can send and receive messages to and from another person using this program. I figured out socket programming by my own (google search etc.), so I don't completely understand every single part. The basic idea is to read a random IP you want to chat with as a String, converting it into an IP and starting two threads, one for sending messages from port A and one for receiving messages at port B (the threads are used for being both able to send and recieve messages at the same time). Every thread has it's own class. So far, so good. Now both classes have the method run which are both in a big try-catch block. At the two catch blocks, I added several error messages, first "Test123" and then "Test456" so I can understand what happens when. When compiling the code, I can type in the IP (I tried localhost for testing). But when I type in the message, I should recieve the message "chat partner sent: ", but instead I don't get anything. Now both threads are in an infinite loop, so when I force the program to terminate (by pressing Ctrl+C (I run the .class via command)), I get the error message "Test123" before the program terminates. My questions are: Why don't I receive any message and why does the program throw "Test123" when I force the program to terminate? Where are my errors?
Thanks in advance for helping. Here's the code:
import java.net.*;
import java.util.Scanner;

public class chat {
    static InetAddress IP;
    static int sPort=11111;
    static int rPort=11112;
    public static void main(String[] args) throws Exception{
        System.out.println("Zu welcher IP soll verbunden werden?");//"which IP do you want to connect with?"
        Scanner sc = new Scanner(System.in);
        String IPraw=sc.next(); //type in the IP address as String
        IP=InetAddress.getByName(IPraw); //converting the String into real IP address
        Thread sender = new sender();
        sender.start(); //start the sending thread
        Thread receiver = new receiver();
        receiver.start(); //start the receiving thread
    }
}
class sender extends Thread{
    public void run(){
        byte[] sendData = new byte[1024];
        Scanner scantext = new Scanner(System.in);
        try{
            DatagramSocket Socket = new DatagramSocket();
            while(true){
                String TextSend = scantext.next();
                sendData = TextSend.getBytes();
                DatagramPacket out = new DatagramPacket(sendData, sendData.length, chat.IP, chat.rPort);
                Socket.send(out);
            }
        }
        catch(Exception e){
        System.out.println("Test123");
        }
    }
}

class receiver extends Thread{
    public void run(){
        byte[] receiveData = new byte[1024];
        try{
            DatagramSocket socket = new DatagramSocket();
            while(true){
                DatagramPacket in = new DatagramPacket(receiveData, receiveData.length, chat.IP, chat.sPort);
                socket.receive(in);
                String message = new String(in.getData());
                System.out.println("Chatpartner sagt: " + message);//"partner said <message>"
            }
        }
        catch(Exception e){
        System.out.println("Test456");
        }
    }
}

Comment: Quick side-note, if you want a chat-application you probably don't want to use UDP. The TCP protocol ensures arrival of the packets, but UDP ignores packet distortion.
Comment: Don't catch exceptions and print next-to-useless messages. Use `e.printStackTrace()` instead.
Comment: You will get way more information about your errors if you do what hexafraction says. Once you do that, post the exception stack trace here and it will be easier to help you.
Comment: You may need another aproach, writing a server that can get connections, and then clients that can connect to that server.
Comment: When I put the try-catch block as comment, I get errors when compiling:
chat.java:24: error: unreported exception SocketException; must be caught or declared to be thrown
   DatagramSocket Socket = new DatagramSocket();
                           ^
chat.java:29: error: unreported exception IOException; must be caught or declared to be thrown
    Socket.send(out);
          ^
2 errors
Comment: @Exabytez Then unless you have a very good reason otherwise, declare those exceptions to be thrown. Catching the exceptions and printing out `"TestXXX"` is preventing you from seeing one of the most helpful things you can have while debugging.
Answer: the sender thread is wating for you to insert some data on System.in (just type something).
It is blocked here, on this line:  String TextSend = scantext.next();
Answer: It appears that your application does not work because you are sending the data to different ports.
static int sPort=11111;
static int rPort=11112;

You need to send it to the same port (and in case of sending it to your own computer, you need to specify either your local ip-address, localhost or 127.0.0.1).
As for your first question
Why don't I receive any message

Are you connecting to 127.0.0.1? What exactly are your parameters?
As for your second question
why does the program throw "Test123" when I force the program to terminate?

because at that very moment you break the while-loop
try{
    DatagramSocket Socket = new DatagramSocket();
    while(true){
        String TextSend = scantext.next();
        sendData = TextSend.getBytes();
        DatagramPacket out = new DatagramPacket(sendData, sendData.length, chat.IP, chat.rPort);
        Socket.send(out);
    }
}

Terminating the application like that results in an exception.
Comment: I both tried typing in localhost and 127.0.0.1, but no matter how many messages I type in afterwards, I don't receive any of those messages.
Comment: Yes I have, but no result. I printed sendData after scanning in the text, no matter what I type, I get some combination, always beginning with [B@ and going on with some random letters.
Answer: You are sending on one port, and receiving on another. If your intention is for this code to send and receive its own message, those ports will need to be the same.  If your intention is to actually chat with someone else (even with yourself on localhost), the other chat would have to receive on your send port and send on your receive port.
Also, what hexafraction said:

Don't catch exceptions and print next-to-useless messages. Use e.printStackTrace() instead.

That's where your error went, you caught it and printed your message instead
Comment: I do not have the reputation to comment on bas' answer, but what you are seeing is the result of trying to print a byte array as a string.  [B denotes a byte array. Print TextSent instead and you should see the  correct text
Comment: Now I sent the message to the receiving port and put in e.printStackTrace() at the catch block, this is what I got:
java.lang.NullPointerException: null address || null buffer
Do you guys have any clue?


Hausdorff dimension of Cantor set

Question: I know this is probably a easy question, but some steps in the proofs I found almost everywhere contained some parts or assumptions which I think may not be that trivial, so I would like to make it rigorous and clear enough. Here is the question:
Let $C$ be the Cantor set with delete the middle third of the interval and go on. The general Cantor can be considered similarly. We want to proof the Hausdorff dimension of $C$ is $\alpha:=\log2/\log3$. So we calculate the $d$-dimensional Hausdorff measure $H^d(C)$ for all $d$ to determine the Hausdorff dimension. Let $C(k)$ be the collection of $2^k$ intervals with length $1/3^k$ in the $k^{th}$-step of construction of Cantor set.
It is rather easy to show that $H^{\alpha}(C)<\infty$ by showing that for any covering $\{E_j\}_{j=1}^{\infty}$of $C$ the set $C(k)$ also covers $C$ for $k$ large enough, so we can bound $H^{\alpha}(C)$ from above. Which implies that the Hausdorff dimension of $C$ is less than $\alpha$.
To show the dimension is actually equal to $\alpha$, it suffices to show $H^{\alpha}(C)>0$.
Now let $\{E_j\}_{j=1}^{\infty}$ be any covering of $C$ with diameter $diam(E_j)\le \delta$ for all $j$. How do we show that
$$\sum_j diam(E_j)^{\alpha}>constant$$
One author (see this link) made the following assumption: $E_j$ be open, so one can find the Lebesgue number of this covering, and when $k$ large enough, any interval in $C(k)$ will be contained in $E_j$ for some $j$. Hence one can bound the $\sum_j diam(E_j)^{\alpha}$ from below by the ones of $C(k)$.
I got confused here: First why we can assume $E_j$ to be open?
Answer: I can elaborate abit why it is sufficient to show it for open ones. It might be that this is not exactly what the author was going after. If you wish, I may also continue this answer into a full proof which shows that $H^{\alpha}(C)\geq \frac{1}{2}$.
Choose for starters a $\delta$-cover $\{E_{j}\}_{j=1}^{\infty}$ of $C$ with $\sum_{j=1}^{\infty}\mathrm{diam}(E_{j})^{\alpha}\leq H^{\alpha}(C)+\delta$. Then for each $j$ we may choose a closed interval $I_{j}$ with $E_{j}\subset \mathrm{int}I_{j}$ and $\mathrm{diam}(I_{j})<(1+\delta)\mathrm{diam}(E_{j})$. Hence $\{\mathrm{int}I_{j}\}_{j=1}^{\infty}$ is an open cover of $C$, and in particular
\begin{align*}
H^{\alpha}(C)+\delta\geq \sum_{j=1}^{\infty}\mathrm{diam}(E_{j})^{\alpha}\geq (1+\delta)^{-\alpha}\sum_{j=1}^{\infty}\mathrm{diam}(I_{j})^{\alpha}.
\end{align*}
Thus to establish a lower bound for $H^{\alpha}(C)$ it suffices to establish a lower bound for $\sum_{j=1}^{\infty}\mathrm{diam}(I_{j})^{\alpha}$. (You may consider $\mathrm{int}(I_{j})$'s instead, which are open, as their diameter is the same as $I_{j}$'s.)
Comment: great, Thanks Thomas
Answer: It is a fact in general (i.e. true in any metric space and Hausdorff measures of any dimension) that you can assume your covering sets to be open or closed. See Federer. For closed version, it is easier: diameter of $\bar{S}$ and diameter of $S$ are equal, so, if a collection of $S$'s cover your set and each has diam less than $\delta$, then you can instead consider the collection of $\bar{S}$'s, which again have diam bounded by $\delta$ ans still cover your set.
For open version, you need some sacrifice! At a cost of arbitrarily small $\sigma$, you can enlarge every set of diam less than $\delta$ to an open one with diam less than $(1+\sigma)\delta$. The latter can be used to estimate $\mathcal{H}^s_{(1+\sigma)\delta}$ within $(1+\sigma)^s$ accuracy of $\mathcal{H}^s_{\delta}$. Since for Hausdorff measure $\mathcal{H}^s$, you will send $\delta \to 0$, and $(1+\sigma)\delta$ will as well, your sacrifices will not affect the ultimate measure. (However, as expected, for one fixed $\delta$, $\mathcal{H}^s_\delta$ can be different if you only allow open coverings versus all coverings.)
Comment: The point is that you didn't "chase down all the $\epsilon$'s and $\delta$'s", thereby making a notational mess that no one can follow (at least, in the sense of seeing the "big picture"). Your second paragraph in particular could easily have been written in a way that would be difficult to grasp the underlying idea (by making it mostly symbolic with many unnecessary "math-grammar" details), but you did not do this. Instead, you concisely described the underlying idea. Just now I tried to find an overly-cluttered answer and didn't, but if I see one in the near future, I'll provide a link.
Comment: I see! I completely see what you mean (without you finding the example!) Writing down explicit variables and sums and inequalities will not necessarily help much with seeing why a certain propositions is true. It may in fact obscure the "reason" why it holds. I am slightly flattered by your observation as well :)
Comment: The fact that I didn't even notice the original "typos" in your explanation (which you fixed 2 hours before I saw your latest comment, just now) is also an example of the what Tao meant by: "*The distinction between the three types of errors can lead to the phenomenon (which can often be quite puzzling to readers at earlier stages of mathematical development) of a mathematical argument by a post-rigorous mathematician which locally contains a number of typos and other formal errors, but is globally quite sound* $\ldots$" **(continued)**
Comment: There is an amusing [anecdote](https://en.wikipedia.org/wiki/Anecdote) about the algebraic topologist [Solomon Lefschetz](http://mathshistory.st-andrews.ac.uk/Biographies/Lefschetz.html) that is relevant to what Tao is talking about: "... *a joke which circulated about Lefschetz, namely that he never wrote a correct proof or stated an incorrect theorem* ...".
Comment: *Just now I tried to find an overly-cluttered answer and didn't, but if I see one in the near future, I'll provide a link.* --- [Here's one that I dealt with as an answer.](https://math.stackexchange.com/a/79222/13130) I happened to recently cite it in [this answer](https://math.stackexchange.com/a/4551055/13130), so it was on my mind when I saw and commented on [this answer](https://matheducators.stackexchange.com/a/25753/745).
Comment: (+1) Nicely written at [Terence Tao's third (post-rigorous) stage of mathematical education](https://terrytao.wordpress.com/career-advice/theres-more-to-mathematics-than-rigour-and-proofs/)!
Comment: I don't get the point of reference to Tao's post!
Comment: I was thinking globally similar to what I said in [this comment](https://math.stackexchange.com/questions/1362464/porous-sets-why-measure-zero/1362484#comment2771486_1362484) (begins with *Regarding (1) in my previous comment*).

Hausdorff dimension of Cantor set


bower ENOGIT git is not installed or not in the PATH, como resolver?

Question: eu estou desenvolvendo minha primeira aplicação na qual pretendo usar a framework AngularJS. Para baixar as dependências do front-end eu estou usando o Bower, no entanto quando eu escrevo o comando no CMD para que eu faça a instalação:
bower install angularjs --save

Está me retornando essa seguinte mensagem:
bower ENOGIT git is not installed or not in the PATH

Alguém poderia me explicar o porque disso? Lembrando que instalei o GIT em minha máquina, precisa fazer algum tipo de configuração? Ficarei grato se puderem me ajudar!
Answer: Para quem passar pelo mesmo problema que eu, descobri a causa e é muito simples, isso ocorre devido ao fato de você não possuir o GIT instalado, eu tinha instalado na minha máquina, portanto fiz a instalação com o servidor aberto, tive que reiniciar o server, após fazer isso eu consegui!


What is the sum of this series given the closed form?

Question: The closed form of a series I am trying to identify is:
$$
a_n=\frac{250}{2n -1}
$$
How could I get the sum of the series equation from this? I am used to geometric sequences and arithmetic sequences and this one is confusing me.
Comment: There is no known closed form for $\sum_{k=1}^n \frac{250}{2k-1}$. You can express it in terms of the closely related $H_m$ (the harmonic numbers). But there is no known closed form for the $H_m$.  Or maybe you mean that the **sum** $s_n$ is $\frac{250}{2n-1}$ and you want to identify the $n$-h summand. That can be done.
Comment: @AndréNicolas It seems to me that the OP is equating the general term of a series with its closed form. Perhaps I misinterpreted.
Comment: @amWhy: As is all too often the case, I do not know what OP intends. I have noticed in the past that you are very good at reconstructing intent.
Answer: If you mean that the general term of the series is $a_n = \dfrac{250}{2n - 1}$, then the corresponding series  IS the sum of the terms $a_i, \;1\leq a_i$ as $i\to \infty$. That is, the corresponding series is:
$$\sum_{n = 1}^\infty \dfrac{250}{2n-1}$$
This series is divergent; as $n \to \infty$, the cumulative sum blows up (is unbounded).
We can, however, compute a sum given some $n$: $S_n = \sum_{k = 1}^n \dfrac{250}{2n-1}$. $S_n$ is not, however, a series.
Answer: Suppose you want to find the partial sum $\displaystyle \sum_{n = 1}^m \dfrac{250}{2n-1}$ and then consider its limit as $m\to \infty$.  You could try $$\displaystyle \sum_{n = 1}^m \dfrac{250}{2n-1} = \displaystyle \sum_{n = 1}^{2m} \dfrac{250}{n} - \displaystyle \sum_{n = 1}^{m} \dfrac{250}{2n}=250H_{2m}-125 H_{m}$$
where $H_m=\displaystyle \sum_{n = 1}^m \dfrac{1}{n}\approx \log_e(m)+\gamma+\frac{1}{2m}$ is a harmonic number.  So the partial sum will be about $125\log_e(m)+245.4$ which slowly increases without limit as $m$ increases.


How to pinch zoom multiple UIImageViews inside UIScrollView

Question: I have to pinch zoom multiple images. I have added each of the UIImageView to UIView and added the UIView to UIScrollView. and returning the UIView image viewForZoomingInScrollView: delegate method, but images are not zooming as expected. is there any better way?
Comment: refere this https://developer.apple.com/library/ios/samplecode/Touches/Touches.zip
Comment: @keshav same issue here check link here is my code http://pastebin.com/4idGrBXR
Comment: @keshav paste some code here :)
Comment: I took the above reference and it helped me a lot now it is working better....thanks.
Comment: @keshav plz post yr code how its work :)
Comment: UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(300.0, 100.0, 500.0, 500.0)];
    [scrollView setBackgroundColor:[UIColor whiteColor]];
    scrollView = scrollView;
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    scrollView.bounces = NO;
    self.scrollView = scrollView;

    self.fullView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 500, 500)];
    [scrollView addSubview:self.fullView];

    // Tell the scroll view the size of the contents
    scrollView.contentSize = self.fullView.frame.size;
Comment: CGRect scrollViewFrame = self.scrollView.frame;
    CGFloat scaleWidth = scrollViewFrame.size.width / self.scrollView.contentSize.width;
    CGFloat scaleHeight = scrollViewFrame.size.height / self.scrollView.contentSize.height;
    CGFloat minScale = MIN(scaleWidth, scaleHeight);

    self.scrollView.minimumZoomScale = minScale;
    self.scrollView.maximumZoomScale = 5.0f;
    self.scrollView.zoomScale = minScale;
Comment: - (void)centerScrollViewContents
{
    CGSize boundsSize = self.scrollView.bounds.size;
    CGRect frame = self.fullView.frame;
    if (frame.size.width < boundsSize.width)
        frame.origin.x = (boundsSize.width - frame.size.width) / 2.0f;
    else
        frame.origin.x = 0.0f;
    if (frame.size.height < boundsSize.height)
        frame.origin.y = (boundsSize.height - frame.size.height) / 2.0f;
    else
        frame.origin.y = 0.0f;
    self.fullView.frame = frame;
}

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.fullView;
}
Answer: #define VIEW_FOR_ZOOM_TAG (1)

@implementation [SVViewController][1]

- (void)viewDidLoad {
    [super viewDidLoad];

    UIScrollView *mainScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    mainScrollView.pagingEnabled = YES;
    mainScrollView.showsHorizontalScrollIndicator = NO;
    mainScrollView.showsVerticalScrollIndicator = NO;

    CGRect innerScrollFrame = mainScrollView.bounds;

    for (NSInteger i = 0; i < 3; i++) {
        UIImageView *imageForZooming = [[UIImageView alloc] initWithImage:[UIImage imageNamed:
        [NSString stringWithFormat:@"page%d", i + 1]]];
        imageForZooming.tag = VIEW_FOR_ZOOM_TAG;

        UIScrollView *pageScrollView = [[UIScrollView alloc] initWithFrame:innerScrollFrame];
        pageScrollView.minimumZoomScale = 1.0f;
        pageScrollView.maximumZoomScale = 2.0f;
        pageScrollView.zoomScale = 1.0f;
        pageScrollView.contentSize = imageForZooming.bounds.size;
        pageScrollView.delegate = self;
        pageScrollView.showsHorizontalScrollIndicator = NO;
        pageScrollView.showsVerticalScrollIndicator = NO;
        [pageScrollView addSubview:imageForZooming];

        [mainScrollView addSubview:pageScrollView];

        if (i < 2) {
            innerScrollFrame.origin.x += innerScrollFrame.size.width;
        }
    }

    mainScrollView.contentSize = CGSizeMake(innerScrollFrame.origin.x +
    innerScrollFrame.size.width, mainScrollView.bounds.size.height);

    [self.view addSubview:mainScrollView];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return [scrollView viewWithTag:VIEW_FOR_ZOOM_TAG];
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)shouldAutorotate {
    return NO;
}

@end

  [1]: http://www.lyricspoints.com

Comment: Some information would be nice instead of posting just a bunch of code.
Answer:
Check the minimum and maximum zoom scale properties of the scroll view. (max should be greater than min for zoom to happen)
make sure that you are returning the corresponding UIImageView and not the UIView
Make sure that you have set the scroll view delegate as the object to which you want the delegate messages of the scroll view to be sent, like viewForZoomingInScrollView:
Comment: I think you have not set the `scrollView.delegate` as self. So the method `viewForZoomingInScrollView` would not be called.


What is 1.999999 in 4 significant digit arithmetic?

Question: Say you are doing some calculations in 4 significant digit arithmetic and at some point you get something like 1.9999999. You need to use this number in further calculations, also in 4 significant digit arithmetic. Do you use 2.000 or 1.999?
Answer: $$2.000$$
When calculating to $n$ significant figures, first write down the first $n+1$ digits of the number, and then round the first $n$ digits based on the value of the $n+1$th.
So I would write down $1.9999$ and then note that the $9$ at the end implies I round up, giving $2.000$ to $4$sf.
Comment: Awesome, that came up in an exam and I didn't know so I just guessed randomly. I made the right guess. Thanks.


How do I solve $\lim_{x \to 0-} \dfrac{\mathrm{e}^\frac{1}{x}}{x^2}$?

Question: I have the following limit:
$$
\lim_{x \to 0-} \dfrac{\mathrm{e}^\frac{1}{x}}{x^2}
$$
I encountered something like this during class and I can't quite remember what my teacher said. I think it was something along the lines of "$e^(1/x)$ gets faster to $0$ so the limit is $0$"
Comment: use l'hopitals twice
Answer: HINT
Make the substitution $\displaystyle u = -\frac{1}{x}$.
Answer: I think both series and L'hospital fail here.  (At least when applied in the usual way.)  But let $y = 1/x$ so that $y\to -\infty$ when $x\to 0^-.$  Then your limit is:
$$\lim_{y\to -\infty} \frac{e^y}{\frac{1}{y^2}} =  \lim_{y\to -\infty} \frac{y^2}{e^{-y}}. $$
Now you can use L'hospital's rule to get
$$=\lim_{y\to -\infty} \frac{2y}{-e^{-y}}  = \lim_{y\to -\infty}
\frac{2}{e^{-y}}  = 0.$$
Comment: I understand, thx a lot :)
Answer: As $x \to 0-$, $\frac{1}{x} \to -\infty$ which means that $e^{\frac{1}{x}} \to 0$ as $x \to 0-$. Therefore, the whole expression will tend towards $0$ as $x \to 0-$
Comment: How does one know that "the whole expression will tend to $0$."  You need to prove this here.
Comment: Since the numerator is $0$, it doesn't matter what's underneath. The result will be $0$.
Comment: You need to show the indeterminate form approaches $0$.  You haven't.
Answer: HINT:
Note that for $x<0$
$$\begin{align}
\frac{e^{1/x}}{x^2}&=\frac{1}{x^2e^{1/|x|}}\\\\
&\le \frac{1}{x^2\,\frac{1}{6|x|^3}}
\end{align}$$
since $e^t\ge \frac16 t^3$ for $t>0$.
Comment: This shows "how/why" $e^{1/x}$ goes to $0$ faster than $x^2$.
Comment: Was the "HINT" useful? If not, I am happy to either elaborate or delete. Which is better for you?


Algebra x in UILabel

Question: I am trying to get an algebra "x" in a UILabel, what can I do. Is there a font in swift that I can use, can you create one or is there a Unicode character for the algebraic "x".
Comment: Check out the "Emoji & Symbols" viewer in macOS. In the Keyboard section of System Preferences, turn on "Show keyboard and emoji viewer in menu bar". The viewer has a section called "Mathematical Symbols" which contains the Unicode character "MATHEMATICAL ITALIC SMALL X".
Comment: @GaryMakin Thank you, that works, can you post this as an answer please?
Answer: macOS has a "Emoji & Symbols" viewer that can be shown using a menubar item (Edit > Emoji & Symbols or (^ + ⌘ + Space)). The viewer has a section called "Mathematical Symbols" which contains the Unicode character "MATHEMATICAL ITALIC SMALL X": , as well as many other useful symbols.
The viewer has a small window version and a larger window version. The "Mathematical Symbols" section only appears in the larger window version. You can swap between the two with the icon that appears in the top right of the window.
You can also have a menu appear in the right side of the menu bar that contains this menu item. To get this menu to show, open System Preferences and go to the Keyboard section. In there, turn on "Show keyboard and emoji viewer in menu bar". By default, this menu items shows the larger version of the window.
Comment: The "Emoji & Symbols" menu appears in the Edit menu of virtually every macOS app you run.
Comment: Thanks for that. I was so used to the way I described that this `Edit` menu item had escaped me. The initial presentation is different, but the one you described can be turned into the other with the icon in the top right of the window.

Algebra x in UILabel


Gráficos no Android

Question: Preciso implementar um gráfico de barras em um app Android. Alguém conseguiria me ajudar? Encontrei somente o google-chart mas não entendi como aplicar ao app.
Comment: fiz uma pequena busca no google e encontrei outras opções com tutoriais
http://www.achartengine.org/
http://www.infragistics.com/products/android
http://www.jjoe64.com/2011/07/chart-and-graph-library-for-android.html

http://www.java4less.com/charts/chart.php?info=android
Answer: Pra você usar o Google-chart no Android, você precisa trabalhar encima de uma Webview
Aqui tem um slideshare bacana utilizando o Google-chart junto com este exemplo
Se você não quiser utilizar através de uma Webview, tenta usar o aChartEngine:
Nesse link com o source e um exemplo nesse post
Comment: Muito  obrigado cara.....ajudou muito...estou iniciando no android... ficou show de bola...

Gráficos no Android


*Some* Users Experiencing Login Failures

Question: A significant minority of our users repeatedly experience login failures and have to reset their passwords every time. Can anyone suggest possible solutions please? Details as follows.
Apparently, the behaviour is as follows:

User opens login page, enters valid username and password.
Login fails, repeatedly!
User requests password reset. Then, using link from e-mail able to: reset password, login and access their account
Next login, user has to repeat process.

Unfortunately, we can't duplicate the issue ourselves. But we have looked through Drupal logs and Apache access logs and observed the following:

The problem is not confined to a specific browser (seen on IE, Safari, Firefox) nor a specific OS (seen on Windows, Mac, iPad)
The users do generally have cookies turned on. We have inserted some custom code to warn users with cookies turned off and write "cookies disabled" to Drupal logs.
Clearing all caches in Drupal doesn't fix issue.
Clearing cookies in browser doesn't fix issue either, one of our users has tried.

We are running Apache on an Ubuntu server.
In settings.php, $base_url is commented out; $cookie_domain is also commented out. It was set, but we decided it was safer to remove it although, I'm not sure that made any difference.
We are using "Profile2" and "Profile2 Registration Path" modules. However, I doubt those modules are the source of our problems as I cannot find any record of anyone else having login problems with those modules.
Do you have any suggestion?
I should have mentioned, the site is running Drupal 7.13.
When the user clicks on the password reset link they are currently prompted to change their password.
We have also asked one user to try another browser but sadly, that didn't fix their problem. Also we have noticed that the problem on IE, Firefox & Safari so, we don't think it's browser specific
Comment: +1, good question. I have had the same problem, but couldn't reproduce the error in my local environment.
Comment: your version of drupal would be helpful.
Comment: I know this seems like a silly question, but are you sure the username/password entered by the users are valid? Maybe try this… After they use the password reset link, instruct them to immediately change their password on the account page that appears (this form does not require the existing password to change the account password). See if the problem persists for that user. Alternatively, see if they can log into the account from another browser/computer.
Comment: Do the users that experience problems comes from the same domain? Do they have a firewall, proxy, etc?
Answer: Not meaning to dig up an old thread, just trying to help anybody who finds it - we had the exact issue described here, on two occasions, on two sites. We finally figure it was caused by users trying to log in with their email address instead of their username, which is why they are able to reset the password but not log in.
Answer: I would ask one of the people who has had this problem to work through it with you. Do a skype screenshare or look over their shoulder while they experience the problem.
In my experience, these people are not clicking "save" after entering a new password so their password isn't actually getting changed.
Comment: It seems this is the more plausible explanation, especially considering the number of users with an account on a Drupal site.
Answer: Perhaps your users are being flood-locked.  Too many unsuccessful logins will cause the user to be blocked.  A less-well-known feature is that too many unsuccessful logins from a given IP will cause a user to be blocked.  This is set to 50 failed attempts per hour by default.
So if you have a lot of users accessing via a single IP (maybe they're on a company network) then a few people forgetting their passwords can inadvertantly lock each other out. The next time you get this problem it would be interesting to take a look at the flood table to see if they're locked.
To test this, you could also increase the flood lock values user_failed_login_ip_limit and user_failed_login_ip_window.  There's no UI for this in core but the Flood Control module provides one.  Or you can easily set the value from drush or in your settings.php file.


30 Day distance between dates in datetime64[ns] column

Question: I have data of the following form:
6460  2001-07-24 00:00:00    67.5      75.1   75.9   71.0   75.2    81.8
6490  2001-06-24 00:00:00    68.4      74.9   76.1   70.9   75.5    82.7
6520  2001-05-25 00:00:00    69.6      74.7   76.3   70.8   75.5    83.2
6550  2001-04-25 00:00:00    69.2      74.6   76.1   70.6   75.0    83.1
6580  2001-03-26 00:00:00    69.1      74.4   75.9   70.5   74.3    82.8
6610  2001-02-24 00:00:00    69.0      74.0   75.3   69.8   73.8    81.9
6640  2001-01-25 00:00:00    68.9      73.9   74.6   69.7   73.5    80.0
6670  2000-12-26 00:00:00    69.0      73.5   75.0   69.5   72.6    81.8
6700  2000-11-26 00:00:00    69.8      73.2   75.1   69.5   72.0    82.7
6730  2000-10-27 00:00:00    70.3      73.1   75.0   69.4   71.3    82.6
6760  2000-09-27 00:00:00    69.4      73.0   74.8   69.4   71.0    82.3
6790  2000-08-28 00:00:00    69.6      72.8   74.6   69.2   70.7    81.9
6820  2000-07-29 00:00:00    67.8      72.9   74.4   69.1   70.6    81.8

I want all the dates to have a 30 day difference between each other. I know how to add a specific day or month to a datetime object with something like
ndfd = ndf['Date'].astype('datetime64[ns]')
ndfd = ndfd.apply(lambda dt: dt.replace(day=15))

But this does not take into account the difference in days from month to month.
How can I ensure there is a consistent step in days from month to month in my data, given that I am able to change the day as long as it remains on the same month?
Answer: You could use date_range:
df['date'] = pd.date_range(start=df['date'][0], periods=len(df), freq='30D')

Comment: this is probably the best answer
Answer: IIUC you could change your date column like this:
import datetime

a = df.iloc[0,0]  # first date, assuming date col is first
df['date'] = [a + datetime.timedelta(days=30 * i) for i in range(len(df))]

Comment: What is `a`, my `Date` column?
Comment: Sorry, it's the first date value - clarified that now
Answer: I haven't tested this so not sure it work as smooth as I thought it will =).
You can transform your first day into ordinal, add 30*i to it and then transform it back.
first_day=df.iloc[0]['date_column'].toordinal()
df['date']=(first_day+30*i for i in range(len(df))).fromordinal


Intuition behind knowing how to use indentation in python

Question: I am completely new to programming and have decided to begin my journey by learning Python. Along the way I have been having some issues with knowing how code is behaving with respect to indentation. I will give an example:
Problem:
Given an array of integers, return the number of 9's in the array.
My first attempt did this:
def array_count9(nums):
    list_of_9 = []
    for num in nums:
        if num == 9:
            list_of_9.append(1)
        return sum(list_of_9)

This was wrong, and I discovered later (after trial and error) that the reason was because I hadn't properly indented my last line of code.
The correct answer should:
def array_count9(nums):
    list_of_9 = []
    for num in nums:
        if num == 9:
            list_of_9.append(1)
    return sum(list_of_9)

This is a problem I have run into repeatedly, and I think it's because I don't really understand how Python deals with indentation.
I understand now that the correct answer is correct because with my first attempt, I am telling Python to return the sum of the objects inside the list immediately after testing whether or not the first integer is 9. In the correct example, Python will run through all the numbers, and only when it is done, go back out to the previous indentation and return the list.
I don't know, I guess I am wondering if someone can provide a "walk-through" of what is happening in each line of good or direct me to a resource that discusses this further. I have looked for such a resource online but have been unable to find one.
Any help would be appreciated!
Comment: PythonTutor.com has an interactive visualizer that lets you step forward (and backward) through simple code one line at a time to see how it works. The builtin debugger `pdb` lets you step a line at a time—it can't go backward, and isn't as visually oriented, but it works on all code, and has all kinds of powerful features you'll come to appreciate over time. Most IDEs have a GUI wrapper around the debugger.
Comment: Hmm, what's exactly your question then? It seems that you've already understand the difference between your trials.
Comment: @ytu I guess I'm wondering how to avoid this mistake. I'm also wondering why the code doesn't work when return is indented the same as "for num in nums." Also, I am wondering if anybody knows of an additional resource where I can better understand how this works.
Comment: Meanwhile, any tutorial should have a section on how indentation works, so maybe try working through one. The basic idea is simple: all the code indented under a line ending with a `:` is part of a compound statement; anything dedented back to the same level as the line with a `:` is a separate statement. But what it means to be "part of" a for loop or an if… I'm not sure how to get that without working through a few examples.
Comment: BTW `sum([num == 9 for num in nums])` may be a better solution for your problem.
Answer: In many languages, indentation is used to make the code look neat and easy to read. However, this is not the case with Python. In Python, indentation is required for indicating what block of code a statement belongs to. For instance, let's look at the code below:
for i in range(0,5):
   print(i)
print("All done!")

The statement print(i) is indented under the for-loop; this means that the statement is under the for-loop. Therefore, the statement will be executed 5 times. Since the statement print("All done!") is not indented, it is not under the for-loop; therefore, it will only be executed once. The output for the above code is

0
1
2
3
4
All done!

Now, let's modify the code a little bit.
for i in range(0,5):
    print(i)
    print("All done!")

Now, since both the print statements are indented under the for-loop, they will be executed 5 times. Therefore, the output now will be this:

0
All done!
1
All done!
2
All done!
3
All done!
4
All done!

Now, let's look at the initial version of your code.
def array_count9(nums):
    list_of_9 = []
    for num in nums:
        if num == 9:
            list_of_9.append(1)
        return sum(list_of_9)

You have the return statement under the for-loop, due to the indentation. This means for every iteration of the for-loop, the return statement will be called. However, since return statements end the function, the for-loop stops at its first iteration. You want to return the sum of the list_of_9 array after iterating through nums. Therefore, the return statement will be after the for-loop, thereby not being indented under the for-loop. That is why the following corrected version of yours works:
def array_count9(nums):
    list_of_9 = []
    for num in nums:
        if num == 9:
            list_of_9.append(1)
    return sum(list_of_9)

Comment: Thank you so much! This was very helpful and exactly the answer I was looking for.


Sampling from dataset according to distribution obtained from another dataset

Question: Suppose we have dataset $A$ with several categorical and numerical features:
$A_{cat_1}$, $A_{cat_2}$, $\ldots;$ $A_{num_1}$, $A_{num_2}$, $\ldots;$
Also we have another dataset $B$ with the same features, but probably with less categories (i.e. unique values) in features.
We want to sample from dataset $B$ according to joint distribution of $A$. How can one do it?
I was thinking in the following direction:

We can LabelEncode categorical features. After that we can use  Kernel Density Estimation on both numerical and encoded categorical features. Is it the right way to estimate distribution of $A$ or maybe there is more correct procedure to estimate distribution in presence of categorical variables?
After we obtain KDE of $A$, we need to sample from $B$ according to that distribution. Could you describe (or maybe provide some code) how can one do it?

I admit this path itself could not be the best solution, so I am also open to better suggestions or any sources.
Answer: So I think if I understand you correctly, what you are trying to do is to sample points from $B$ according to the distribution of $A$. In which case I would take a different approach to what you have laid out here.
First of all you talked about label encoding $A$ and then doing a KDE. I don't think this makes sense unless your categorical variables can really present something continuous ie colour $\in$ [red, orange, yellow, green] as opposed to pet $\in$ [cat, frog, horse]. The problem here is that if you label encode these and apply the KDE filter, unless you set a small width for the filter you will end up with a lot of probability distribution between theses discrete categories. You will also end up blurring your distributions for the other variables.
I think a better approach would be this:

Randomly sample a datapoint $a$ from $A$
Find the datapoint $b$ from $B$ which minimises some distance $D(a,b)$
Repeat

Then all you need to do is define a distance function $D$. This could take into account both continuous values and the categorical values.
For categorical variables perhaps you decide the partial distance $d_{cat_1} = 0\textit{  if  }(a_{cat_1}=b_{cat_1})\textit{  else  } \infty$
and for continuous variables maybe you could use $d_{num_1} = (a_{num_1}-a_{num_2})/\sigma_{num_1}$ where $\sigma_{num_1}$ is the standard deviation of $[A_{num_1}, B_{num_1}]$ and so on.
Then you could set $D = \sum_x d_x^2$
Here is a minimum toy example in python
<code>import matplotlib.pyplot as plt
A = np.random.normal(0,1,(1000,2))
B = np.random.uniform(-3,3,(1000,2))

def distance(a,b):
    return np.sum((a-b)**2)

def resample(A, B, N):
    newsample = np.zeros((N,2))
    for i in range(N):
        # step 1
        a = A[np.random.randint(0,len(A))]
        #step 2
        mindist = np.inf
        mindistind = None
        for j in range(len(B)):
            d = distance(a,B[j])
            if d < mindist:
                mindist = d
                mindistind = j
        newsample[i]=B[mindistind]
    return newsample

C = resample(A, B, 300)

fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, sharey=True)
ax1.scatter(A[:,0], A[:,1], label='A')
ax2.scatter(B[:,0], B[:,1], label='B')
ax3.scatter(C[:,0], C[:,1], label='B from A')
[ax.legend() for ax in (ax1, ax2, ax3)]
plt.show()
```
</code>
Comment: Thank you for your answer ;)


m3u8 not playing offline - swift 3.0

Question: I am trying to stream an m3u8 url and save offline.
Then play from offline.
I am using  Apple HTTP Live Streaming
Start Download by using the below code
func setupAssetDownload() {
        // Create new background session configuration.
         configuration = URLSessionConfiguration.background(withIdentifier: DOWNLOAD_ID)

        // Create a new AVAssetDownloadURLSession with background configuration, delegate, and queue
         downloadSession = AVAssetDownloadURLSession(configuration: configuration,
                                                    assetDownloadDelegate: self,
                                                    delegateQueue: OperationQueue.main)
        let url = URL(string: urlString)
        let asset = AVURLAsset(url: url!)

        // Create new AVAssetDownloadTask for the desired asset
        let downloadTask = downloadSession.makeAssetDownloadTask(asset: asset, assetTitle: "asset_Title", assetArtworkData: nil, options: nil)
        // Start task and begin download
        downloadTask?.resume()

    }

Where,
let DOWNLOAD_ID = "downloadIdentifier"

let urlString = "http://domain/vod/mp4:sample1.mp4/playlist.m3u8"

// Saving the Download Location

    func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {

        print("didFinishDownloadingTo \(location.relativePath)")
        // Do not move the asset from the download location
        UserDefaults.standard.set(location.relativePath, forKey: "assetPath")
    }

When try to play Offline,
I can get the AVURLAsset,
<AVURLAsset: 0x1742319e0, URL = file:///var/mobile/Containers/Data/Application/79C0043F-6161-4231-9129-B71C95903E05/Library/com.apple.UserManagedAssets.bhVNRN/asset_Title_63128673BE57FBDD.movpkg/>

But, not paying from the asset.
func playOfflineAsset() {
        guard let assetPath = UserDefaults.standard.value(forKey: "assetPath") as? String else {
            // Present Error: No offline version of this asset available
            return
        }
        let baseURL = URL(fileURLWithPath: NSHomeDirectory())
        let assetURL = baseURL.appendingPathComponent(assetPath)
        let asset = AVURLAsset(url: assetURL)

        let player = AVPlayer(url:assetURL)

        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = videoView2.bounds
        playerLayer.backgroundColor = UIColor.purple.cgColor
        videoView2.layer.addSublayer(playerLayer)

        player.play()

        if let cache = asset.assetCache, cache.isPlayableOffline {
            // Set up player item and player and begin playback

            print("exist")

        } else {
            // Present Error: No playable version of this asset exists offline
            print("doesn't exist")
        }
    }

Comment: did you ever solve this?
Comment: yes, I could play offline
Comment: @VineeshTP How did you fix this?
Comment: @PallavTrivedi : NOt remenbering the fix, its been around 4 years.
Answer: you need add AVPlayerController to AVPlayer can play with sounds, i dont know why, but its work for me
// Set up player item and player and begin playback
let playerItem = AVPlayerItem(asset: asset)

player = AVPlayer(playerItem: playerItem)

// play without present playerController
self.player?.play()

// play with present playerController
// let playerController = AVPlayerViewController()

// playerController.player = player
// self.present(playerController, animated: true) {
//       self.player?.play()
// }

Edit: Make sure hls not encrypt.

m3u8 not playing offline - swift 3.0


Django Template Ternary Operator

Question: I was wondering if there was a ternary operator (condition ? true-value : false-value) that could be used in a Django template.  I see there is a python one (true-value if condition else false-value) but I'm unsure how to use that inside a Django template to display the html given by one of the values.  Any ideas?
Answer: You can use the yesno filter:
{{ value|yesno:"yeah,no,maybe" }}

You can learn more here
Comment: Very nice and simple, but when I want to use some variables it seems this filter is not applicable. For instance I would like to use `{{ expr_or_value | yesno : "the string", other_variable_value }}`
Comment: This should be the selected answer! This is exactly what's being asked.
Comment: Brilliant. Thank you for the answer. I knew this existed, but couldn't remember.
Comment: The documentation doesn't state it but you can also do `{{ value|yesno: "checked," }}` if you want to use this for presetting checkboxes
Answer: Why would you need a ternary operator within a template? {% if %} and {% else %} are all you need.
Or you could try the firstof tag:
{% firstof var1 var2 var3 %}

which outputs the first one of var1, var2 or var3 which evaluates to a True value.
Comment: I tend to disagree with Daniel.  I recently converted a django template to a simple javascript template: `{% if data_complete %}{{ data }}{% else %}{{ something_else }}{% endif %}` became  `<%= data_complete ? data : something_else %>`  ... the second is so much more compact and elegant.  It would be nice if there was an equivalent in django.
Comment: I would like to see ternary support, too.
Comment: "why would you" ... well, to do something in 30 sec instead of 10mn, for instance. Django templating isn't so developer-friendly, it's not always a good thing to have to do stuff in the view instead of the template.
Comment: I suppose you're right, I'll just use if/else.  Just addicted to ternary I guess.
Answer: Just because they haven't been mentioned here yet: the built in template tags default, and default_if_none can be useful in simple circumstances:

default
If value evaluates to False, uses the given default. Otherwise, uses the value.
For example:
{{ value|default:"nothing" }}
If value is "" (the empty string), the output will be nothing.
default_if_none
If (and only if) value is None, uses the given default. Otherwise, uses the >value.
Note that if an empty string is given, the default value will not be used. Use >the default filter if you want to fallback for empty strings.
For example:
{{ value|default_if_none:"nothing" }}
If value is None, the output will be the string "nothing".

https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#default
Comment: Too bad this doesn't work for unknown attributes, would have been nice.
Comment: See also: http://stackoverflow.com/questions/7590198/django-setting-for-default-template-tag-output-when-variable-is-none
Answer: I've just implemented the ternary operator for Django as a tag, see https://github.com/alexei/django-template-extensions
You can use it as:
{% ?: exp1 exp2 exp3 %}
{% ?: exp1 exp2 %}

Or:
{% iif exp1 exp2 exp3 %}
{% iif exp1 exp2 %}

I figured out that it makes more sense than the yesno filter, even though it's really not that Pythonic.
Comment: Awesome, thanks! Solves the issue that I can't pass context variables to `|yesno`
Answer: You don't. The Django {% if %} templatetag has only just started supporting ==, and, etc. {% if cond %}{% else %}{% endif %} is as compact as it gets for now.
Answer: I wonder if the python and/or trick would work?
condition and true_value or false_value

behaves a like the ternary operator - outputs true_value if condition evaluates to True, and false_value if not.
Comment: That was the first thing I tried; I'm surprised it doesn't work.
Comment: I learnt recently that  `true_value if condition else false_value` is also valid Python syntax, and it's much more readable -- will check if it works in templates...

Django Template Ternary Operator


The orthogonal projection over the subspace $V=\{f:f =0\text{ on }[0,1/2]\}$

Question: The orthogonal projection of an element $x_0 \in H$ over a convex set $C$ is the element $y_0 \in C$ such that $\|x_0-y_0\|=\min_{y \in C}\|x_0-y\|$. Find the orthogonal projection of $\gamma (x)=2e^{2\pi ix}$ over the subspace $V=\{f:f =0\text{ on }[0,1/2]\}$.
The orthogonal projection of $2e^{2\pi ix}$ onto the subspace $M=\{\lambda g: \lambda \in C\}$ is the unique $\lambda g$ such that
$$(2e^{2\pi ix}-\lambda g) \perp M$$
Equivalently we must find $\lambda$ such that
$$\int_0^1 (2e^{2\pi ix}-\lambda g)g \,dx=0$$
How do I continue with this problem?
Answer: You haven't stated the space $H$. I'll assume $H=L^{2}[0,1]$. The orthogonal projection $P_{V}\gamma$ of $\gamma$ onto $V$ is the unique $f \in V$--if it exists--such that
$$
          (\gamma-f,g)=0,\;\;\; g \in V.
$$
Every $g \in V$ has the property that $g\chi_{(1/2,1]}=g$ because such $g$ vanishes on $[0,1/2]$. You might guess that
$$
           f= P_{V}\gamma = \chi_{(1,2,1]}\gamma,
$$
but it can be directly verified because
$$
          (\gamma-\chi_{(1,2,1]}\gamma,g)=(\gamma\chi_{[0,1/2]},g\chi_{(1/2,1]})=0,\;\;\; g \in V.
$$
So $P_{V}(2e^{2\pi ix})=2\chi_{(1/2,1]}(x)e^{2\pi ix}$. Because the orthogonal projection exists for each $\gamma \in L^{2}[0,1]$, it follows that $V$ is a closed subspace of $X$, too. Automatically $P=P^{2}=P^{\star}$ on $L^{2}[0,1]$.


How to show different Views for the same URL with contextual filters

Question: I have 1 View with contextual filter: /catalog/%
% - is taxonomy term and it can be several terms (I use them for Porducts groups) like: Phones, Accesoiries, Tablets, etc.
So, when Views get URL with Phones argument it show all its stuff on /catalog/phones page.
Problem is, that I also want to have another Views for Tablets, which should have the same address with contextual filters: /catalog/%. It should show Tablets staff after getting Tablets as arguments.
I can not use only 1 Views for both product categories, because Phones and tablets will have different set of fields to show.
Right now only 1 Views is shown. Second is empty.
How to fix it?
Comment: You cant do this default with views.  You either need to create a module with a page using hook_menu that outputs the view programmatically or hack it.  It sounds like to me you need to rethink your logic or CSS
Answer: This can be done via a zero-coding solution using Page Manager (CTools), Views Content Panes (CTools) and Panels.

Delete your current view as we want to re-use its path.
Install the three modules.
Create a view as follows:

Create a view of type content (nodes) that shows content of your product type. Add a relationship to the 'taxonomy terms on node' and set it to your 'catalog' vocabulary.
Add a contextual filter of 'Taxonomy term name.' It will automatically select the relationship of 'term'. Hide the view when the filter value is not available.
Now add two 'Content pane' displays to this view.

Content pane 1: This is the view that will show tablets only. Click on 'edit' next to argument input in 'Pane setting' column. Select 'from context', and for the required context, select Taxonomy term->name.

Just above 'argument input' is a setting for 'Category'. Set it to something meaningful, such as 'View Panes - Catalog'.

This first pane will show 'tablets', so add fields that you want on this pane, and change its display Name to Tablets.
Content pane 2: Duplicate pane 1 exactly. It will show all the other terms, so alter the fields and display name.

Add a custom page at admin/structure/pages/add

Set it's path to : catalog/%term
During the wizard setup it will ask you to define the arguments (%term in our case). Set it to term name and limit to vocabulary 'Catalog' so that it looks like this:

Basically what we have done is to tell page manager what the argument %term represents, namely a taxonomy term that belongs to vocabulary 'catalog'.
When selecting a panel layout select single column.
Eventually you will get to the screen where you can add content to the single panel. Add content, and select 'View Panes - Catalog' (remember we defined a meaningful name for the category of our view panes. This is it). This will further display two content panes. You select the content pane you added first, ie the one to show tablets.
Now we need to limit it to only show for terms of type tablet. Select selection rules for your variant, and 'Taxonomy Term.'

Set it up so that it looks like this:

Now update and save your page and you can test that for the path that has an argument of tablet, it will show the view.
Now you need to add a second variant to this panel. To do this you can clone the first variant.

And all that remains now is for you to change this second panel variant slightly.
First, you need to remove the selection rule. As this is a catch-all variant, we do not need a selection rule at all.
Second, you need to remove the view from the panel pane single-column content, and replace it with the second pane that you added.
Now update and save. Make sure that the two variants are in the order: top variant has a selection rule and shows first view pane, and the second variant does not have a selection rule and shows second view pane. Page Variants are selected from top to bottom, with the first variant that matches being used.


Table data import in webpage using python possible?

Question: Please see the image below. I want to create a dynamic web page (using html, css and javascript) where the tables get values through a python script. Please tell me if this is possible? (Thorugh javascript, I have functionality that when I click a certain table name, data corresponding to that table only is displayed on right hand side.)
Comment: I just want to know whether its possible or not. Regarding code, I dont think it will be of any use.
Comment: @Era I have provided the answer for how I am doing it. Thanks for your interest :)
Answer: Yes this is possible with mako template.
Just use from mako.template import Template.
Now, using the Template functionality, you can do this. Here, make a html template having python in it.
Eg. % for COMPNAME in tpdob.scalar_not_adv:

        ${COMPNAME}

% endforThen create a html webpage using Template itself for showing the output.


How to define a custom function in deluge?

Question: I want to create an automated email in Zoho Cliq that sends a message to everyone every morning. In the message there is a button that should call the sendMsg function.
How can I define the sendMsg function?
The idea is that by pressing the button another message should be sent back to me.
Thanks for the help
response = map();
response.put("text","Wie startest du heute in deinen Tag?");
card = map();
card.put("title","Guten Morgen ☕");
response.put("card",card);
buttonsList = list();
buttonsList0 = map();
buttonsList0.put("label","Remote");
buttonsList0.put("type","+");
action = map();
action.put("type","invoke.function");
data = map();
data.put("name","sendMsg");
action.put("data",data);
buttonsList0.put("action",action);
buttonsList.add(buttonsList0);
response.put("buttons",buttonsList);

Answer: Well, to define a custom function, you need to start with the "function" keyword, followed by the name of the function and its parameters enclosed in parentheses.
For example:
function my_function(input1, input2) {

}


Period of repeating decimals

Question: Note: This question is base sensitive. Therefore, assume we have fixed a base $b$. By abuse of terminology, I will still use the word "decimal".
This question revolves around the period of repeating decimals. For an integer $i$, define $f(i)$ as the period of the expansion of $i^{-1}$, or $1$ if the decimal expansion of $i^{-1}$ terminates. As an example, $f(3) = 1$ or $2$, depending on $b$.
Now, the behaviour of $f$ is a delightful mix of pattern and chaos. I (think I) have found three things so far:

1) For any natural $i$, $f(i) \leq (i-1)$.
2) If $i$ divides a number of the form $b^{n-1} + 1$ or $b^n - 1$ (for applicable $n$) then $f(i) \leq n$ (I believe this to be an equality if $n$ is minimal).
3) If $i = j_1\cdot j_2$ with $j_1$ and $j_2$ coprime, then $f(i) \leq \text{lcm}(f(j_1), f(j_2))$.

Now, what I want to know is whether or not these three points are correct, and whether or not the upper bound of $f(i)$ given by these three points together is indeed the value.
Comment: Your point (2) can be formulated to say that if $(b, i) = 1$, then $f(i)$ divides $\varphi(i)$, where $\varphi$ is Euler's totient function.
Comment: @AndreasCaranti seems so, but that isn't as strict as the equality in point 2, granted that equality holds for minimal $n$.
Answer: By period, I assume you mean minimal period, otherwise there are inifinitely many periods.
Write $i=x_iy_i$, where every prime factor of $x_i$ divides $b$, and $\gcd(y_i, b)=1$. Then $f(i)=f(y_i)=ord_{y_i}(b)$, where $ord_{y_i}(b)$ is the multiplicative order of $b \pmod{y_i}$.
This is because:
$x_i$ does not affect the minimal period $f(i)$.
If $y_i \mid (b^n-1)$ for some $n$, then let $b^n-1=ky_i$, then
$$\frac{1}{y_i}=\frac{k}{b^n-1}=\frac{k}{b^n(1-b^{-n})}=\frac{k}{b^{n}}+\frac{k}{b^{2n}}+ \ldots$$
So $\frac{1}{y_i}$ has $n$ as a period. Since the smallest such $n$ is given by $ord_{y_i}(b)$, $f(y_i) \leq ord_{y_i}(b)$.
On the other hand, since $f(i)$ is a period, let $l$ be the number representing the repeating string, so we can write
$$\frac{1}{y_i}=\frac{l}{b^{f(i)}}+\frac{l}{b^{2f(i)}}+ \ldots=\frac{l}{b^{f(i)}(1-b^{-f(i)})}$$
Thus $b^{f(i)}-1=ly_i$, so $f(y_i) \geq ord_{y_i}(b)$.
Now back to your results.
1 is mostly correct, as we have $f(i)=f(y_i)=ord_{y_i}(b) \leq \varphi(y_i) \leq y_i-1 \leq i-1$ for $y_i>1$, and if $y_i=1$, $f(i)=1 \leq i-1$ for $i>1$. The only exception is $i=1$, as $f(i)=1>1-1$.
2 is partially correct. The $b^n-1$ part is correct, but not the $b^{n-1}$ part.
3 is correct. $y_i=y_{j_1}y_{j_2}$ so $f(i)=ord_{y_i}(b)=lcm(ord_{y_{j_1}}(b),ord_{y_{j_2}}(b))=lcm(f(j_1),f(j_2))$.
Comment: This does adress my concern about $i = b^n + 1$ too, as $b$ then has order $2n$, which is the length of the (yes, minimal) period of $i^{-1}$. I just didn't think very far when I wrote that point.

Period of repeating decimals


Sub class unable to change super class property in typescript

Question: I know this is probably a silly error or I am expecting something that's wrong, nevertheless I am stumped as to what I am missing here. I am new to typescript and I am trying to optimize my Angular app by doing some inheritance jazz.
So here is what I want to achieve. I have a base component that needs to provide data to one of its drop down boxes but the data is to be provided by a child component (only the child knows what the list values should be based on some login and other criteria). So here is what I did and what I thought would work
export class BaseComponent implements OnInit
{
  public list!: string[]; // this is needed for a drop down in my html

  constructor(protected service: SomeService) { //injecting service for other tasks in super}

  ngOnInit(): void {
    //console.log(this.list) is always empty
  }

  public setList(list: string[]) {
    this.list = list;
  }
}

export class SubComponent extends BaseComponent implements OnInit
{
  constructor(
    service: SomeService,
  ) {
    super(service);
    super.setList(this.service.getDropDownList1());//only sub class which method to call, like xxxList1 or xxxList 2 etc

  }
}

But on my ngOnInit in the super, list is always empty. I just do not understand why? Given that I am explicitly calling super to set a property on super why does this not work? I have been struggling with what I though was a rudimentary issue but I do not see any way around. Can you please help?
Thanks,
Ananth
PS : In the super class constr, if I explicitly call
this.service.getDropDownList1()

the list is populated and shows fine in the html. But via the sub class no luck :(
Also putting console.logs in both constructors and onInits, I noticed that base constructor is getting called twice, dont know why that is happening - probably due to my explicit super call????
EDIT 1:
Given that I am from a pure Java background, let me see if I can explain my problem with an example from there!
 class Super {
  String superStr = "";

  public Super()
  {
    System.out.println(" in super constr" + this.superStr);

  }

  public void setString(String s)
  {
  this.superStr = s;
  }

  protected void printStr(){
    System.out.println("in printStr of super" + this.superStr);
  }
}

public class Sub extends Super{

  public Sub(){
  super.setString("I am sub setting super str");
  }

public static void main(String[] args){
  Sub s = new Sub();
  s.printStr();
}

}

In this case, s.printStr prints the value set in the call to super's setString method. That is what I was expecting to happen in my TS code too. In constr the sub sets the super's list, and on onOnit being called the list will be used to display drop down values. Am I comparing wrongly? Just wanted to make sure I understand this. So would appreciate if you can help me understand what I am getting wrong.
EDIT 2:
I am accepting Chris' answer below - his guidance was the most helpful towards me getting a grip on how things work!
Comment: is  `this.service.getDropDownList1()` sync/async?
Comment: Actually that is populated right at login time. Long before the html displaying the drop down is even accessed. And anyway its sync (populated while user authentication)
Comment: If you pass in the same service that the sub uses to get the list, why not have the parent class do that?
Comment: Like I said, parent class has no idea what xxxListX method to call. Only the sub components know it based off the user login type and other criteria. Plus I want to abstract that responsibility to the sub components
Comment: Your java example is correct, but it is not the same as your typescript. Change `Sub s = new Sub()` to `Super s = new Super()`. This is the mistake you made by instantiating the base class instead of the sub class. In your html you put `` instead of `` correct?
Comment: @ChrisHamilton I am sorry but I still do not see it, apologies in advance. I want the sub comp to contain the base comp, so my sub comp html does have `````` in it. Are you saying that is wrong? When the components are rendered wont the constructors get invoked? Doing the change you suggest from Sub to Super in Java will never work as I expect because sub's constr is never called, hence no super setList. So that is clear. But in TS, the sub's constr will get called during the lifecycle right? I wish I understood this and not have to bug you more :(
Comment: Having the `` inside your sub component creates a separate component. So you have 1. An instance of a sub component and 2. An instance of a parent component. They are two separate instances, they do not communicate via inheritance, and they do not share html.

The sub's constructor gets called by the `` component and not the `` component. Changes you make to the sub component will not affect the html rendered by the `` tag.
Answer: I copied your code into stackblitz and it seems to be working fine.
https://stackblitz.com/edit/angular-ivy-spjlo9?file=src/app/sub/sub.component.ts
Does your html contain the tag for the sub component? In other words, are you sure you're displaying the sub component and not the base component?
Although I do see a discrepency here:
super.setList(this.service.getDropDownList1());

I needed to delete this or I got a compile error
super.setList(service.getDropDownList1());

Alternatively you can label the service as protected like the super. Not sure if that was just a typo while copying.
Comment: Actually the html I am using is for the base component. Not the sub component. The functionality is such that the base component displays a list of common filter drop downs (the various listXXX methods for different drop downs). So all the drop downs are defined in the base component's html only. Why is that a problem? And if that is a problem then inheritance is moot here right. I will end up replicating these filter drop down in each sub components' html files. That is what I am trying to avoid and hoping inheritance would solve the issue. I saw your code and your list is used in sub html :(
Comment: in fact the way my html is designed is to include the base comp html and then below it add a summary grid based off the values selected in the filter drop downs in the base comp. This way I was hoping that I can reuse the base comp for all other sub components that need the same filter panel. Is that design thinking wrong? Also the filter drop downs have some logic for enabling/disabling etc which I wanted to abstract into the base comp so that the logic is one place and no code duplication. Wonder what I am missing, please guide me!
Comment: Yes, you're misunderstanding inheritance. An instance of a child class (sub-component) inherits properties / functions of the parent class, but an instance of a parent class (base component) does not inherit anything from child classes. The constructor of the sub-component is inaccessible from an instance of the base component.
Comment: I think you may also be missing the point of components. There is generally no need for inheritance when it comes to components. If they have common properties such as a filter panel, you can make the filter panel its own component, and add the tag to the html of any other component.
Comment: Thank you Chris for the clarifications. I have 2 questions. Firstly, does the super.setList have no effect on the super's list property. If you remove inheritance as a concept, it is pure parameter passing, correct? So why does the base component lose the list data set by the sub component? Secondly, I started off by doing it the way you said - a new comp with the filter panel. But the overheads of passing data from the sub component into this common component led me to the point of using the base comp itself as the common component. From a design thinking, why is that wrong?
Comment: kindly see my edit, hopefully that clarifies my confusion! Or maybe is it all timing - when onInit of super comp is called to render the html the list is empty. GIven that I am new to angular this side of things are hazy for me. Maybe it works as I expect it to, just that while rendering the drop down has no values even though the sub comp has set them
Comment: See my comment on the main thread.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241706/discussion-between-ananth-and-chris-hamilton).


How to apply CSS class without affecting global behvior

Question: I am using a third party library which has its own CSS class. This is how the DOM looks:

 ....

This is the class I am overriding to fix the width
.toast-custom {
  top: 0;
  left: 30%;
  width: 50%;
}

This is the class already provided by framework
#toast-container > div {
  position: relative;
  pointer-events: auto;
  overflow: hidden;
  margin: 0 0 6px;
  padding: 15px 15px 15px 50px;
  width: 46%;
  -moz-border-radius: 3px 3px 3px 3px;
  -webkit-border-radius: 3px 3px 3px 3px;
  border-radius: 3px 3px 3px 3px;
  background-position: 15px center;
  background-repeat: no-repeat;
  -moz-box-shadow: 0 0 12px #999999;
  -webkit-box-shadow: 0 0 12px #999999;
  box-shadow: 0 0 12px #999999;
  color: #ffffff;
  opacity: 0.8;
  -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
  filter: alpha(opacity=80);
}

I am not able to modify the width of the dix without touching #toast-container > div but if I make change to #toast-container > div it will have a global impact. How can I make use of .toast-custom to make the required change?
Comment: #toast-container.toast-custom
Comment: Use greater CSS specificity (learn about that) as Steve G. wrote.
Comment: you want to overwrite `id="toast-container"` or child of `id="toast-container"`?
Answer: The issue that you're having is that an # "ID selector" (eg. #my-rule) is more specific than a . "class selector" (eg. .my-rule), and the [last] most specific CSS selector (rule) wins.
This should work on any #toast-containers that implements .toast-custom:
/* Note "no space" between */
#toast-container.toast-custom > div {
  ...
}

This is basically saying "select the direct descendant  div of #toast-containers elements that also have a .toast-custom class applied." Since that is more specific than the framework's rule, your rule will override, but only in that case. -- (#toast-containers that do not implement .toast-custom should not be affected.)
From MDN

Specificity is the means by which browsers decide which CSS property
  values are the most relevant to an element and, therefore, will be
  applied.

See CSS Specificity on MDN for more information.
Comment: this worked for me : `#toast-container.toast-custom > div {
`


Treating string field as numeric to use as an exposed filter

Question: I have a field in my users' profiles that has been defined as varchar initially even though it holds numeric values. I'm trying to use that field as an exposed filter and perform "greater than or equal" operation on it; however, since it's a varchar field, View doesn't give me that option.
In my module, I have come up with these two hooks to do a workaround:
function MY_MODULE_views_query_alter(&$view, &$query) {
    if ( $view->name == 'manage_users' ) {
        foreach($query->where[1]['conditions'] as $key => $condition) {
            if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
                $query->where[1]['conditions'][$key]['value'] = (int)$query->where[1]['conditions'][$key]['value'];
                $query->where[1]['conditions'][$key]['operator'] = '>=';
                break;
            }
        }
    }
}

function MY_MODULE_views_data_alter(&$data) {
    $data['field_data_field_count']['field_count_value']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_value']['argument']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['argument']['handler'] = 'views_handler_filter_numeric';
}

The first hook seems to be working fine and successfully changing the operator from LIKE to >=; however, that's not enough for me because it still thinks 2 is greater than 15. So I added the second hook to make sure the field is actually treated as numeric, but that doesn't seem to have any effect on how the results are returned and it still thinks 2 is greater than 15.
Comment: In the final SQL query a string and integer is being compared which will result in a string to string comparison. You need to cast the string to an unsigned which does not seem possible: [Drupal Views alter Filter to CAST() string as Float](http://stackoverflow.com/questions/33417033/drupal-views-alter-filter-to-cast-string-as-float)
Comment: Hey @J.Reynolds, I came up with an answer to this question, as well as the one you mention from S.O., added an answer there too.
Answer: Excellent question!
You only need the hook_views_query_alter function, here is what it should look like:
function MY_MODULE_views_query_alter(&$view, &$query) {
  if ( $view->name == 'manage_users' ) {

    // For filtering
    foreach($query->where[1]['conditions'] as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
        $query->where[1]['conditions'][$key]['value'] = array(':val' => (int)$query->where[1]['conditions'][$key]['value']);
        $query->where[1]['conditions'][$key]['field'] = 'CAST(' . $query->where[1]['conditions'][$key]['field'] . ' AS UNSIGNED) >= :val';
        $query->where[1]['conditions'][$key]['operator'] = 'formula';
        break;
      }
    }

    // For sorting as well
    foreach($query->orderby as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count_field_count_value' ) {
        $query->orderby[$key]['field'] = 'CAST(' . $query->orderby[$key]['field'] . ' AS UNSIGNED)';
        break;
      }
    }
  }
}

Most important parts in this code snippet:

Using CAST to change the varchar into an integer [doc]
Using the 'formula' operator to instruct views that you are using a complex SQL expression, check the source code of add_where_expression!  [doc]

Good luck!

Update Note: Even though this is working fine, the more elegant/readable way would be to have a function (equivalent to add_where_expression) that would allow overwriting a where/having condition.
Comment: Tell the person that asked the question how to __"fix the field"__, a detailed answer is better than a disclaimer placed in a comment.
Comment: Brilliant! So the trick was in setting operator to formula.
Comment: This 'fix' is addressing the symptom and not the issue. You should be recreating the field correctly. If you have data for it already you should be fixing the database. There are several tried and true methods of doing so. It will be less maintainable this way.
Comment: Hi @sareed : In the frame of the OP, this is a fully justified answer, focusing on the code problem presented by the user. In the frame of an alternative way to resolve the issue at its core (on the database level), the answer from No Sssweat is describing all the needed steps to fix it. You could add a positive comment to that answer and upvote it. Or even provide this post with yet another alternative alswer in order to enrich it. That way eveyone will benefit. Cheers!
Comment: I meant my comment as a disclaimer to benefit people who see it. **"that has been defined as varchar initially even though it holds numeric values"** tells me it is not a code but a configuration issue. To create another similar view you would have to go back and change the code snippet to include the new view as well. This creates a maintenance issue because you should not have to go to code every time you include this field as a filter. It could also cause problems elsewhere. Instead, fix the field.
Answer:
Alternatively, if the field is meant to hold numeric data why don't
  you just update the db so that the field is numeric?
Are you saying directly changing it from a varchar to an int? Would
  that not cause any issues? Should I still keep the "_format" column
  after I change the data type?

If you want to be safe, you can do it like this:
1) Go to your database and export your text field as a CSV file.

Note: If you're using  for your export, do not use CSV for MS Excel. Use the CSV option.
  As CSV for MS Excel displays the values in a comma format rather than columns.

2) Then open your exported .CSV file with Excel.
3) In Drupal delete the text field and create a new integer field.
4) Go to /user/1/edit and enter a number in your decimal field (do not enter 1 as you will not know which one is the uid and which one is the actual field) and save changes (this is so when we export we have the table structure)
5) Go back to your database and find the new decimal field, export as CSV. Then open on Excel.
6) Use the values from your 1st Excel to copy the node id's and the field values and paste them onto your 2nd Excel in the appropriate column(s) and save.
7) Import 2nd Excel to your integer field and check-mark ☑ replace table data with file.
8) In Drupal, clear/flush the cache to see the changes.
Answer: You could try using a hook_views_data_alter and changing the field and filter handlers to views_handler_field_numeric and views_handler_filter_numeric, that should work pretty well. I haven't personally tried it in hook_views_data_alter but the technique works great in hook_views_data.
Alternatively, if the field is meant to hold numeric data why don't you just update the db so that the field is numeric?
Assuming this is a site that is in production I would suggest using hook_update_N and db_update to change the type column for the field in field_config to number_integer and the module field to number. Definitely test this update locally before pushing to the main branch.
Comment: Are you saying directly changing it from a varchar to an int? Would that not cause any issues? Should I still keep the "_format" column after I change the data type?
Comment: If you use the [update system](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_update_N/7.x) correctly it should not cause any issues with a production site. This is assuming the you are _sure_ the field only contains numeric data. If the site is not in production yet you can just change the db directly and test to make sure there are no issues.