Could incorporating locks degrade performance?

Question: I have to write an ETL program for event data which loads events into Kafka, so in loader call I get an array of events. Inside loader I need to look at each event and based on certain parameters I need to decide its category which has a one-to-one mapping with some Kafka topic, where it should be written. They are not more than 20 Kafka topic to write to.
So my doubt is whether I should cache topics seen in a map as below: (Lets assume that I have started a no. of threads to divide the events among them and try loading into Kafka in parallel)
<code>    class Loader {
      private static Map<String, String> eventCategoryVsKafkaTopic = new HashMap<String, String>();
      ReadWriteLock lock = new ReentrantReadWriteLock();

      public static void load(IEvent[] events) {
        for(IEvent[] event) {
        String eventCategory = getEventCategory(event);
        lock.readLock().lock();
        if(eventCategoryVsKafkaTopic.get(eventCategory) != null) {
          loadToKafka(event, eventCategoryVsKafkaTopic.get(eventCategory));
        }
        lock.readLock().unlock();
        String kafkaTopic = generateKafkaTopicFromEvent(event);
        loadToKafka(event, kafkaTopic);
        lock.writeLock().lock();
        eventCategoryVsKafkaTopic.put(eventCategory, kafkaTopic); // Its fine, if some other thread has written it in between, as the topic will be the same so overwrite is not an issue
        lock.writeLock().unlock();
      }
    }
}
</code>
I feel this much of locking would be an overkill and may degrade performance rather if I just create topic on the fly every time as below: (Again assume that I have started a no. of threads and distributed events among them to load in parallel)
<code> class Loader {

      public static void load(IEvent[] events) {
        for(IEvent[] event) {
        String kafkaTopic = generateKafkaTopicFromEvent(event);
        loadToKafka(event, kafkaTopic);
      }
    }
}
</code>
Please suggest which one is the better way to handle topic generation and is involving locks a good idea here.
Comment: How much work is involved in generating the kafka topic? If it takes a lot of resources and you need to avoid doing it repeatedly, but don't want to use locks, then make the hash map local to each thread. Best of both worlds.
Comment: Not much I feel, it is just appending some 3-4 properties with a field inside event (eventCategory), but just thinking if it could be big when done thousands of events.
Comment: Using local HashMaps is a good idea btw. :)
Answer: Short answer: Having all threads compete for one lock for every processed event will probably be slower. Without knowing more, generating a topic name is probably really quick.
Long answer:
If possible, try and build concurrent applications where threads communicate as little as possible. Sharing state like this across all working threads is going to create a lot of contention.
If generating that topic takes a lot of time then caching it is a good idea. However if there are only 20 topics then you should cache it locally to each thread to avoid each thread competing for the same lock for every event being processed.
A basic model would be to separate consumers and producers by some concurrent queue. Have consumers run in their own thread but share no state with other consumers. Consumers can cache the mappings locally if they need to.


What's the difference between a junior guitar and a normal guitar?

Question: I was planning to buy an electric guitar and amazon.com is offering Epiphone Les Paul Junior Guitars at a seemingly reasonable deals. The related question that I have is: what's a junior guitar?
What's the standard length of a fretboard on a guitar (and how many frets should it normally have)?
Does a junior guitar have lesser number of frets or is it that the fretboard is just scaled for young teenagers?
If one starts with a junior guitar, how difficult is it to switch to a normal guitar?
Answer: The Les Paul Junior is not a different size guitar, it's simply an entry-level Les Paul model. It was originally designed to be an affordable alternative to the Les Paul Standard, and thus is not as fully-featured. The main differences compared to a traditional Les Paul are:

flat top instead of carved top
only one pickup, usually a P90
consequently, also only one volume and tone knob
wrap-around tailpiece instead of the tune-o-matic bridge and tailpiece
in Epiphone's case, a bolt-on neck, rather than a set neck

You can read more about the Les Paul Junior in the Wikipedia article. Also, you can compare the specs of the Epiphone Les Paul Standard and Les Paul Junior. As far as I can see, they both have the same scale length (629 mm / 24.75") and number of frets (22).
If you start with a Les Paul Junior, you shouldn't have any difficulty switching to a higher-end Les Paul model, save perhaps having to adjust to a second pickup and more tonal options at your disposal.
Comment: I had confusion in three points: top, bridge and neck. I googled and understood what types of bridges are available in the market. Same about the necks. But I haven't understood the difference between flat-top and carved top guitar. Both look same to me in the pictures.
Thanks for the great answer!
Comment: @ShashankSawant See [this question](http://music.stackexchange.com/questions/6103/what-factors-affect-a-guitars-ability-to-sustain-a-note) for some discussion of carved-vs-flat-top.
Comment: @ShashankSawant In case you can't find the answer from the above link, carved (or arched) top means that the body of the guitar is not uniform in thickness - it's thicker in the centre, especially under the bridge, and thinner towards the edges. See [this image](http://reynold.net/images/lp3/img_2736_800.jpg) for a good example. This usually provides better sustain, but is more expensive to produce. Flat top, as the name suggests, means that the top of the guitar is completely flat.
Comment: I was confused as to what "top" is. In the 2D view all guitars (almost all - excluding those arrow shaped one perhaps) are curved.
Now I got it. Perfect!
Answer: Les Paul Jr's were built to a smaller scale when they were made originally, as an, entry guitar for children/teens/smaller adults. At the time, LP's were quite a bit more so many people started buying Jr's because of the cost difference. Because of this, Gibson ended up scaling the Jr up to standard size, which is what, we have today.
AFAIK, Epiphones are made in Indonesia, not China. Samick Music Co made Epiphone for Gibson and Samick is based in Indonesia, much like Cort.
Answer: Clarification: just because it is a "junior" guitar, does not necessarily mean that it is any worse of a guitar - or even in some cases a step down - than its standard counterpart. For example, Glenn Frey, legendary guitarist of the Eagles (Hotel California) played the majority of the band's earlier recordings on a Gibson Les Paul junior with an extra neck pickup (also a p90), including, if I'm not mistaken, the solo in Hotel California. Some people also prefer the Junior for other reasons, such as its light weight - a 4.5lbs compared to a roughly 12lb standard. Also, my personal preference is for the sound of the single coil p90s slightly more than the PAF humbuckers (silver pickups found in standard Les Pauls), because of their warm, crunchy midrange at more distorted volumes.
If you know what you are buying and what it is made out of, it can still be a fantastic sounding guitar. I'd definitely recommend trying them both out.
Cheers!
Answer: In guitar products jargon usually means reduced price in cost of features or quality. Usually Junior will be better than Special. Guitar companies use much more words as Standard, Deluxe, Modern, Professional, Studio, Vintage... It takes some time to learn what they usually mean.
Les Paul junior is on of the most professionally used junior guitars anyway.
Answer: A few years later, but still a solid question with some solid answers.  Did you get the guitar?
A few points for other readers who might stumble on these posts.

If you're talking Gibson then all of their guitars are good. Throughout the years there were a few models that were "lemons" by Gibson standards, but Gibson sets a high bar. In other words even a "bad" model Gibson will usually last longer and sound as good or better than a "good" model from some other brands.

The Jr models, were less costly than the full models, but they did this through simplifying the functions. So, you have volume and tone. Same wood, neck and other quality aspects of the full model, but simply less options.
As someone else mentioned there are many times the "Jr" was preferred, since there wasn't a lot of tone variation, the Jr had 1 set sound of its own, which for certain songs or styles was preferable.
You were going with the Epiphone? The Epiphone does use Gibson to base design on, but is made in China (as of 2004)  and is def a cheaper alternative to Gibson. If you're going with Epiphone then I'd say go ahead and get the top of the line Epiphone which will mimick the full Gibson in functionality (tone switches, buttons , volume and 2-3 pickups) IF you're looking at Epiphone & Jr, I'm thinking that's kind of a bare bones set up.
I'd save for an American made Gibson (Jr or Standard) or if you go Epiphone get the top line Epiphone if money is an issue (will be more affordable than Gibson) of course the Epiphone uses cheaper wood, wiring, paint + bold in neck instead of set neck and so forth.
Comment: "all of their guitars are good" - that is definitely not the consensus. Of all the top-tier guitar makers, Gibson is the one that gets ragged on the most often, for quality control issues, long-standing design issues and generally being way too expensive. No one doubts that the best Gibsons are excellent guitars; but there's no guarantee that any given Gibson (no matter the price) lives up to the name.


A derivation regarding kernel regression for the support vector machine

Question:
THis is from the Elements of Statistical Learning book page 437 in the section of support vector machine. Can anyone give me some hint for the missing derivation steps for why 12.49 is true (as seen in the attached screenshot)? I do not see why 12.48 gives rise to 12.49.
Many Thanks!
Answer: There's a matrix identity
$$
PB^T(BPB^T + R)^{-1} = (P^{-1} + B^TR^{-1}B)^{-1}B^TR^{-1}
$$
for matrices with concordant dimensions and invertibility.
Taking $P = I$, $R = \lambda I$, $B^T = H$, and $B = H^T$, we have
$$
H(H^TH + \lambda I)^{-1} = (\lambda I + HH^T)^{-1}H.
$$
Let
$$
h_x = \left(\begin{array}{c}h_1(x) \\ \vdots \\ h_M(x)\end{array}\right)
$$
so we have
$$
\hat f(x) = h_x^T\hat\beta = h_x^T(H^TH + \lambda I)^{-1}H^Ty \\
= h_x^TH^T(HH^T + \lambda I)^{-1}y \\
= \hat\alpha^T(Hh_x)
$$
by the aforementioned identity. Now
$$
(Hh_x)_i = \langle h_{x_i}, h_x\rangle = K(x, x_i)
$$
so all together we have
$$
\hat f(x) = \sum_{i=1}^N \hat\alpha_i K(x,x_i)
$$

To prove that identity, you can note that
$$
PB^T(BPB^T + R)^{-1} - (P^{-1} + B^TR^{-1}B)^{-1}B^TR^{-1} \\
= (P^{-1} + B^TR^{-1}B)^{-1}\left[(P^{-1} + B^TR^{-1}B)PB^T - B^TR^{-1}(BPB^T + R)\right](BPB^T + R)^{-1} \\
= C\left[B^T + B^TR^{-1}BPB^T - B^TR^{-1}BPB^T - B^T\right]D \\
= \mathbf 0
$$
Comment: Many thanks to you jld for the detailed proof


Why are these statements true?

Question: <code>Let
    A = { x | x is an odd integer and 0 < x < 30 }
    Which of the following are true?
  a. { 0,1,2,3 } ⊆ A
  b. { 5,3,1 } ⊆ A
  c.  ∅ ⊆ A
  d. A ⊆ { 5,3,1 }
</code>
Teacher said answers are : a. False , b. True , c. True , d. False
But for example in b, how can { 5,3,1 } be improper subset of A, if A has only 1 element?
And why is d False if it is possible that A might be either 5, 3 or 1, since it is can be an odd integer from 0 to 30?
Comment: $A=\{1,3,5,7,\cdots,27,29\}$
Comment: You should review set-builder notation. Not sure why this has down votes either. The asker has asked a question and shown their work.
Comment: Hmm, I see, so set A consists of many elements, not 1. That explains a lot
Answer: The big issue, here, seems to be a misunderstanding of set-builder notation. When you see $$A=\{x\mid x\text{ is an odd integer and }0<x<30\},$$ you should interpret this to say: "$A$ is the set of all $x$ such that $x$ is an odd integer and $0<x<30.$" Put more plainly, $A$ is the set of all odd integers strictly between $1$ and $30,$ meaning that $A$ is the set of all odd integers from $1$ to $29$ (inclusive). Hopefully, having an appropriate conception of what $A$ is, in the first place, will make this problem more sensible.
Answer: a) 0 not in set, and 2 not odd
b) 5,3,1 are all odd and are all within 0 and 30. Also, it doesn't say anywhere that your set A is of only one element. A is all x, such that x follows the set of rules outlined.
c) empty set is always a subset
d) A is not possibly a subset of 5,3,1, since 7, 9, ... , 29 are not part of 5, 3 or 1

Why are these statements true?


Mudar cor do produto MouseOver

Question: Bom dia...
Preciso de uma ajuda e não sei como fazer. Tenho um ecommerce. Na página incial meus produtos aparecem assim:

Quero, que, assim que o cliente passar o mouse sobre as cores, mude a cor da camiseta.
Como fazer: Por onde começo.
PS. Loja em PHP.
Comment: Tem o código do elemento? Vc tem acesso ao HTML e CSS para customizar as coisas? As bolinhas pode estar na parte de cima?
Comment: posso customizar tudo...
Comment: Quer um tutorial ou uma ajuda :D
Comment: Não ajuda muito você nos pedir algo e nem sequer exibir o código aonde você está tentando fazer com que isso aconteça
Answer: Esse é um modelo básico usando o seletor irmão ~ e filter para trocar a cor da imagem. Porém as bolinhas tem que vir antes da imagem para ficar legal. Para as bolinhas ficarem na parte de baixo e mesmo assim o seletor ~ funcionar como o esperado eu usei rotate() e flex jada ajustar.
Veja o código para entender melhor

.box {
    display: flex;
    justify-content: center;
    width: 300px;
    border: 1px solid #000;
    flex-wrap: wrap;
    transform: rotate(180deg);
    flex-direction: row-reverse;
}
.cor {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin: 10px;
    background-color: red;
    cursor: pointer;
}
.cor:hover {
    transform: scale(1.2);
}
.red:hover ~ img {
    filter: grayscale(100%) sepia(100%) hue-rotate(-60deg) saturate(8);
}
.blue {
    background-color: blue;
}
.blue:hover ~ img {
    filter: grayscale(100%) sepia(100%) hue-rotate(200deg) saturate(8);
}
.green {
    background-color: green;
}
.green:hover ~ img {
    filter: grayscale(100%) sepia(100%) hue-rotate(90deg) saturate(8);
}
.box img {
    width: 45%;
    height: 45%;
    object-fit: contain;
    margin: 20px;
    transform: rotate(180deg);
}

Comment: @BetinhoSilva não sei, não foi isso que vc perguntou... Para essa pergunta eu tenho essa resposta... Se vc precisa de algo de banco sugiro fazer outra pergunta explicando o que precisa para alguém que entenda dessa área de ajude
Comment: boa.... e se os produtos viessem de uma base de dados?

Mudar cor do produto MouseOver


Despertador em Python

Question: Olá!
Estou a tentar fazer um despertador em Python, mas estou com problemas ao comparar o horário atual com o horário desejado para despertar, ele só aciona quando faço a condição If com != ao invés de ==.
O meu código está assim:
def relogio(): #função relogio
    horario.config(text = strftime("%H:%M"))
    horario.after(1000,relogio) #atualiza o horario a cada 1 segundo
    return

def ligAlarme(hora,minuto): #função alarme

    print(localtime().tm_hour)

    while True:

        if  localtime().tm_hour == int(hora) and localtime().tm_min == int(minuto):

            pygame.mixer.init() #chama o iniciador da música
            pygame.mixer.music.load("alarm-clock-ringing.mp3")
            pygame.mixer.music.play(loops = 2)
            botaoParar.place(x=325, y=210)

            break

        return

def deslAlarme(): #função para desligar o alarme
    pygame.mixer.music.stop()
    return

janela = tk.Tk()
janela.title("Despertador relógio")
janela.geometry("500x250")
janela.resizable(0,0)
janela.config(bg = "white")

horario = tk.Label(janela, bg = "white", fg = "black", font = "arial 50 bold")
horario.pack()
relogio()

hora = tk.Entry(janela, width = 2, bg = "white", fg = "black", font = "arial 25" )
hora.place(x=195,y=155)

minuto = tk.Entry(janela, width = 2, bg = "white", fg = "black", font = "arial 25" )
minuto.place(x=255,y=155)

botaoIniciar = tk.Button(janela, text = "Iniciar alarme", command = lambda: ligAlarme(hora.get(), minuto.get()))
botaoIniciar.place(x=100,y=210)

botaoParar = tk.Button(janela, text = "Parar alarme", command = deslAlarme)

janela.mainloop()

Se alguém puder ajudar agradeço!
Answer: O possível problemas talvez estaria no tipo de variável, por exemplo:
x = 1    #int()
y = '1'  #str()

x == y   #retorna False

No seu codigo você pode transformar um valor para int() ou outro para str():
if  localtime().tm_hour == str(hora) and localtime().tm_min == str(minuto):

ou
if  int(localtime().tm_hour) == int(hora) and int(localtime().tm_min) == int(minuto):

Despertador em Python


Como reduzir o tamanho de um variável passada via POST, compactando-a

Question: Minha aplicação no Android pega a String envia para o arquivo.php que processa os dados.
Logo vi que não conseguiria passar o código em base64 para o arquivo.php.
Preciso de alguma função em java que compacte essa longa String e envie a mesma com um tamanho menor e que o arquivo.php possa descompacta-la ao seu estado original para que eu possa manipular os dados.
Existe alguma forma de fazer isso? Reduzir o código, compactando-o?
Segue o código que estou a usar.
public void postData(String html) {
    URL url = null;
    BufferedReader reader = null;
    StringBuilder stringBuilder;

    try {
        url = new URL("http://192.168.0.15/android.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    Uri.Builder builder = new Uri.Builder()
            .appendQueryParameter("par", html);
    String query = builder.build().getEncodedQuery();

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));

    writer.write(query);
    writer.flush();
    writer.close();
    os.close();

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            stringBuilder.append(line + "\n");
        }
        String output = stringBuilder.toString();
        Log.d("httpcliente", "BUSCANDO => [" + output + "]");
} catch (IOException e) {
    e.printStackTrace();
}

private class ParseURL extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {
        StringBuffer buffer = new StringBuffer();
        try {
            Log.d("JSwa", "Connecting to ["+strings[0]+"]");
            Document doc  = Jsoup.connect(strings[0]).get();
            Log.d("JSwa", "Connected to ["+strings[0]+"]");
            // Get document (HTML page) title
            String title = doc.title();
            Log.d("JSwA", "Title ["+title+"]");
            buffer.append("Title: " + title + "\r\n");

            // Get meta info
            Elements metaElems = doc.select("meta");
            buffer.append("META DATA\r\n");
            for (Element metaElem : metaElems) {
                String name = metaElem.attr("name");
                String content = metaElem.attr("content");
                buffer.append("name ["+name+"] - content ["+content+"] \r\n");
            }

            Elements topicList = doc.select("h2.topic");
            buffer.append("Topic list\r\n");
            for (Element topic : topicList) {
                String data = topic.text();

                buffer.append("Data [" + data + "] \r\n");
            }

            postData(doc.html());
        }
        catch(Throwable t) {
            t.printStackTrace();
        }

        return buffer.toString();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        respText.setText(s);
    }
}

Comment: @Florida eu tento criar um exemplo em java no android e te mando
Comment: Só que preciso enviar todo o conteúdo da página ao `php` para que ele consiga processar apenas os dados que desejo, não achei meio de conseguir isso no `Android/Java`, passar varias requisições simultâneas contendo toda a página não geraria uma carga maior? Ao meu ver sim, compactando o post aliviaria mais toda essa carga. Estamos falando de mais de **400** possíveis conexões. Ou não seria necessário tal compressão? Visto que a conexão é rápida, e a resposta também.
Comment: Tentei não usando o `StandardCharsets`, tentei de muitas formas, a principio seu código não era compatível com a qual o aplicativo é destinado. 4.0 em diante.
Answer: Conforme @Luídne e o @bfavaretto o erro 414 só ocorre quando os dados são passados pela URL (mesmo que esteja envia POST, ainda você pode enviar dados por GET).

O erro 414 Pedido-URI Too Long ocorre quando o URI fornecido foi muito longo para ser processado pelo servidor.
Fonte: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Enviando POST para um WebService
Conforme esta resposta no SOen, você pode fazer desta maneira:
//Suas variáveis POST
String urlParameters  = "param1=a&param2=b&param3=c";

//Envia usando UTF8, altere conforme a necessidade
byte[] postData       = urlParameters.getBytes(StandardCharsets.UTF_8);

//Endereço do seu servidor
String request        = "http://example.com/index.php";

int    postDataLength = postData.length;
URL    url            = new URL(request);

HttpURLConnection conn= (HttpURLConnection) url.openConnection();

conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );

//Necessário para o envio do POST
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");

conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );
}

Comprimindo string
Conforme está resposta do SOen, você pode usar o GZIPOutputStream para comprimir/compactar a string:
public static byte[] compress(String string) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
    GZIPOutputStream gos = new GZIPOutputStream(os);
    gos.write(string.getBytes());
    gos.close();
    byte[] compressed = os.toByteArray();
    os.close();
    return compressed;
}

Se estiver usando o método no arquivo MainActivity.java será necessário importar a bibliotecas necessárias, o inicio do MainActivity deve ficar algo como:
package ...;

import java.lang.String;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;
import java.nio.charset.StandardCharsets;
import java.net.HttpURLConnection;

O uso deve ser algo como:
compress('Meu texto');

No PHP para você descompactar use gzuncompress (não testei):
Deve ficar algo como:
echo gzuncompress($_POST['data'])

Se não funcionar use gzdecode
Comment: Me ajudou um pouco, porem não consegui implementar essa função. Me vem a seguinte mensagem `Required: java.lang.String` e `Found:byte[]`. O código está rodando normalmente, não consegui compactar o post, mas é funcional agora. Atualizei para o `HttpURLConnection` pois usava `HttpClient`. Continuarei procurando alternativas compatíveis.
Comment: Atualizei meu comentário. Adicionei, porem não adiantou de nada. Agora só me resta dormir. Ao menos de cabeça fria. Obrigado pela ajuda pessoal.
Comment: Sem sucesso, elas já estão incluídas. Este é o código que estou a suar, caso queira dar uma olhada http://pastebin.com/TQy4Lumz Nota:Minha aplicação usa a versão 4.0.1/4.1 em diante, então notei que algumas coisas como o `StandardCharsets` podem não funcionar. Volto mais tarde para tentar mais.
Comment: Estava usando um método ultrapassado pra conectar, fui procurar saber mais e vi que poderia ter problemas com ele, tive de mudar. Este código achei na **SOen**, achei estranho esse `connect`, mas não tinha usado-o antes, não saberia nunca que eram duas, parece que erraram lá ao postar isso. Vou remove-lo, obrigado por me avisar.


ItemsControl keeps reference to previous DataContext after DataContext set to null

Question: Update: To clarify, this is a question about memory leaks, not about the UI failing to refresh to reflect the new null DataContext (that part works fine).
It appears that if you set an ItemsControl's DataContext to null, it will continue to hold a reference to its old datacontext until such time as you assign it a new one that is not null. You can confirm this with the code at the bottom of the question. Click "Set DataContext to null", then click "Collect garbage" as many times as you want. The "Foo finalized" message will never appear. Then click "Set DataContext to empty object", collect garbage again, and you'll see the finalizer run right away.
I had a memory leak in my application due to a faulty assumption that one of my ItemsControls (a DataGrid) would release all its references to its old datacontext after TheGrid.DataContext = null. Why doesn't it? Is this expected behavior?
Update: The path to root provided by the VS2015 Diagnostic Tools after clicking "Set DataContext to null" looks like this. I don't think anything after the Foo itself comes from my code:

Foo
ListDictionary+DictionaryNode
ListDictionary
ListDictionary+DictionaryNode
ListDictionary
HybridDictionary
Object[] [Strong Handle]

XAML:
<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

    <StackPanel>
        <ItemsControl ItemsSource="{Binding Foos}" />

        <Button Content="Set DataContext to null" Click="SetDataContextToNullClicked"/>
        <Button Content="Set DataContext to empty object" Click="SetDataContextToEmptyObjectClicked" />
        <Button Content="Collect garbage" Click="CollectGarbageClicked"/>
    </StackPanel>
</Window>

C#:
namespace WpfApplication
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Windows;

    public class Foo
    {
        ~Foo()
        {
            Debug.Print("Foo finalized");
        }
    }

    public class FoosViewModel // implementing INotifyPropertyChanged here doesn't help
    {
        public FoosViewModel(IEnumerable<Foo> foos)
        {
            Foos = foos;
        }

        public IEnumerable<Foo> Foos { get; }
    }

    public partial class MainWindow
    {
        public MainWindow()
        {
            DataContext = new FoosViewModel(Enumerable.Repeat(new Foo(), 1));
            InitializeComponent();
        }

        private void SetDataContextToNullClicked(object sender, RoutedEventArgs e)
        {
            DataContext = null;
        }

        private void SetDataContextToEmptyObjectClicked(object sender, RoutedEventArgs e)
        {
            DataContext = new FoosViewModel(Enumerable.Empty<Foo>());
        }

        private void CollectGarbageClicked(object sender, RoutedEventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

Comment: @d.moncada Yes, the grid clears, but it is still holding a reference to the `IEnumerable` from the old DataContext somewhere, which means that entire list of `Foo`s is leaked (there's only one of them in this toy example).
Comment: "If there is binding to a collection that does not implement the INotifyCollectionChanged interface, WPF creates a strong reference to this collection. As a result, it stays in memory"
https://www.jetbrains.com/help/dotmemory/10.0/Inspections.html
Comment: Did you try to refresh `DataGrid` after binding `null` to it? `TheGrid.Items.Refresh();`
Comment: @SeM The result is still the same--finalizers from the old DC don't run until I assign something nonnull.
Comment: I'm not sure what you are doing, but using the code above, as soon as I click Set to null, my DataGrid clears. Does this not happen for you?
Comment: What happens if you declare your your ItemsControl in code instead of XAML? Put a placeholder like Grid inside your StackPanel, give it a name, add from code behind.  Wondering if WPF is keeping a reference to the binding...
Comment: @KoryGill I think you're on the right track. I'm tentatively concluding that it's the issue described [here](http://stackoverflow.com/q/19511341/3549027). At least, the problem goes away if I wrap the `IEnumerable` in an `ObservableCollection`.
Comment: @Ed.ward That must be it (I've seen the same claim from a few bloggers); it would be nice to hear what Microsoft itself has to say, but they don't seem to have said much.
Answer: you can get explanation in here
https://stackoverflow.com/a/19511796/2696230
Using list will result in a strong reference ( a memory leak ). the simple solution is just to change List to ObservableCollection, unless the view (itself) is released
Comment: I had reached this conclusion based on the comments, but no one made their comment into an answer, so you get the points! :)


Relation pairwise coprime and setwise coprime

Question: In a principal ideal ring:
$$\forall\, a,b \in \mathbb{Z},\quad a \wedge b = 1\ \text{ (notation for gcd)} \enspace \Longleftrightarrow \enspace (a) + (b)= \mathbb{Z}$$
where $(a)$ denotes the principal ideal generated by $a$.
So it is indeed obvious that if $\ (n_1,\cdots , n_r)$ are pairwise coprime then they are setwise coprime:
$$ (n_i)+ (n_j)= \mathbb{Z} \quad \Longrightarrow\quad (n_1)+ \cdots + (n_r)= \mathbb{Z} $$
(the reasonning is as intuitive with the definition of greatest common divisor).

First useless detail, I nevertheless wanted to have an explicit Bézout relation: starting from relations $\ u\, n_i + v\, n_j=1$ for every couple $(i,j), i\neq j$, find a systematic way to obtain an expression of the form
$$\ u_1\, n_1 + \cdots + u_r\, n_r=1$$

Secondly I was wondering whether an equivalence or just an implication relates the following properties:

$ (n_1,\cdots , n_r)$ are pairwise coprime.
$ \Big( \prod_{i\neq 1} n_i,\cdots ,\prod_{i\neq r} n_i \Big)$ are setwise coprime.

Edit: a relation as in the first $\ \bullet$ could be useful e.g. in the "kernel decomposition theorem". In addition to the comment and to the answer, an other way to obtain it is by induction to insert $1=u_1\, n_1 + \cdots + u_{r-1}\, n_{r-1}$ into
$$\begin{split}
1 &= n_r - (n_r-1)\times 1= n_r - (n_r-1)\times (u_1\, n_1 + \cdots + u_{r-1}\, n_{r-1})\\
&= n_r + \tilde{u}_1\, n_1 + \cdots + \tilde{u}_{r-1}\, n_{r-1}
\end{split}$$
Comment: The answer to the first question is obvious: if $un_i + vn_j = 1$, then $a_1 n_1 +\dotsb a_rn_r = 1$, where $a_i = u$, $a_j = v$, and all the other coefficients are $0$.
Comment: Maybe related, [this question](https://math.stackexchange.com/questions/1982395/n-1-n-k-pairwise-coprime-iff-lcmn-1-n-k-n-1-n-k)
Answer: Let us prove the equivalence of the second $\enspace\bullet$
1. implies 2.: in fact this will also give a relation of the form mentionned in the first $\ \bullet$
"$(n_1,\cdots, n_r)$ pairwise coprime" gives by the Bézout identity ${r\choose 2}= \frac{r(r-1)}{2}$ equalities of the form
$$ u_k n_i + v_k n_j = 1 \quad \text{for each pair}\ k:=(i,j),\ i\neq j$$
A first proof of the implication is to multiply all of these equalities and show that each of the $2^{{r\choose 2}}$ terms in the development of the product $\displaystyle \prod_{1\leq i<j\leq r} (u_k n_i + v_k n_j)$ into sums is of the form $\displaystyle \prod_{i\neq j} n_i $, i.e. contains at least $r-1$ of the $r$ factors $\{n_1,\cdots, n_r\}$.
In place of a formal proof, let us just picture ourselves the set of couples $(i,j)$ such that $1\leq i<j\leq r$ as the coordinates of ${r\choose 2}$ points which form a "triangle". (Or if they designate the components of a matrix, it would correspond to the strictly upper components).
Now for each factor $(u_k n_i + v_k n_j)$ of the product, choosing one of the summand correspond in our pictorial representation to projecting either on the absciss or ordinate (x or y axis). We keep this value and repeat this for each of the ${r\choose 2}$ points of the "triangle". The "worse" case where we have a few values as possible is obtained inductively by "deleting" the row or column after each step, which correspond to choosing the same factor as much as possible. What should be formally written is that "since it is an $r-1$ by $r-1$ triangle we will get at the end $r-1$ values".
As second proof is by induction on $r$. Assume the statement holds for $r-1$: "$(n_1,\cdots, n_{r-1})$ pairwise coprime" implies $\exists\ A_1,\cdots A_{r-1}\in \mathbb{N}$ s.t.
$$  A_1\prod_{i\neq 1} n_i + \cdots + A_{r-1} \prod_{i\neq r-1} n_i = 1 $$
With the additional hypothesis the $n_r$ is pairwise coprime with the other $n_j$ we have $r-1$ relations of the form
$$ u_j n_j + v_j n_r = 1 $$
which we "insert" in each of the summand: e.g.
$$ A_j \prod_{\genfrac{}{}{0pt}{1}{1\leq i\leq r-1}{i\neq j}} n_i \times 1 = A_j \prod_{\genfrac{}{}{0pt}{1}{1\leq i\leq r-1}{i\neq j}} n_i \times ( u_j n_j + v_j n_r) =  u_j\, A_j \prod_{\genfrac{}{}{0pt}{1}{1\leq i\leq r}{i\neq r}} n_i  + v_j\, A_j \prod_{\genfrac{}{}{0pt}{1}{1\leq i\leq r}{i\neq j}} n_i $$

Conversely: assume that
$$  A_1\prod_{i\neq 1} n_i + \cdots + A_r \prod_{i\neq r} n_i = 1 $$
Then $\forall\ k,\ 1 \leq k \leq r$ the rest of Euclidean division of $A_k\prod_{i\neq k} n_i$ by $n_k$ is 1: regroup all multiples of $n_k$
$$  A_k\prod_{i\neq k} n_i + B_k\, n_k = 1 $$
and for any $j\neq k$
$$  A_k \Big(\prod_{i\neq k,j} n_i \Big)\, n_j + B_k\, n_k = 1 \quad\text{i.e.}\quad n_j \wedge n_k = 1 $$


Swift 4 in Xcode 9 - How to do some animation during dragging UItextview

Question: I have make a animation in the view above UItextview, and it looks like very smooth. I used a timer to do this animation.
But there is a problem about when I drag the textview, the animation can be paused if it haven't ended. So, is there a way to permit a animation play smoothly with the textview scrolling or being dragged.

OK, I speak as clear as possible.
I'm poor in English, excuse me.
A UItextview, which can be scrolled. And a button on the other view (this view which is not associated with that UItextview). That two views are in a big view at the same time. the button become big when you touch it, this process is concerned about an animation.But when the textview scrolling, this animation can be paused if it start and haven't end.
A function called when button have touched, this animation is a timer, and it's location in a array in each frame.
And how to pause animation in detail:
Use a finger touch this button, and its animation can be triggered. And before this animation ended, use another finger drag the textview, I can find obviously this animation is paused ,and it continued when I lift up my finger in the textview.
So, why all animations were paused when a textview (or a scroll view) scrolled. is this a system program? How to solve this problem?
If you have any other doubts, please put questions in the comment field.
this animation like this:
var TimerCount = 0
var timer = timer()
timer = timer.scheduledTimer(withTimeInterval: 0.02, repeats: true, block: { (timer) in
    /*Some animation code*/
    if TimerCount >= 19 {
        timer.invalidate()
    }
    TimerCount += 1
})

Comment: Please share your code for what you have tried and possibly some screenshots as this question appears unclear
Comment: While I do have already an idea of which the problem might be, please give us some code to help you better. How do you actually animate this UITextView?
Comment: @GiuseppeLanza I have updated my question, could you help me?
Answer: While the "pausing" issue is resolvable within your code, I must say for the records that this is not the right way to perform an animation.
I suggest you to take a look at CABasicAnimation and the CoreAnimation framework way to perform correctly animation taking advantage of the GPU.
As always Ray Wenderlich makes amazing tutorial about this subject.
So said, the pausing occurs because the timer is scheduled using the schedule method. you must add your timer to the main runloop to avoid that this gets interrupted by user actions. Again, this is not the proper way to animate something on screen on iOS and most likely you will have performances issues.
var timerCount = 0
let timer = Timer(timeInterval: 0.02, repeats: true) { (timer) in
  /*Some animation code*/
  if TimerCount >= 19 {
    timer.invalidate()
  }
  timerCount += 1
}
RunLoop.main.add(timer, forMode: .commonModes)

While this code gives you a solution, I strongly recommend to not perform animations this way. It works, eventually you will have exactly what you want, but in the future you will probably have problems.
Comment: Thanks for your answer, I use timer to perform animation because CABasicAnimation is limited. It just used for location, frame, scale, color, etc. But it can not change such as, font size, kern, etc. in animation. So I think timer has no limitation, which is the best way to custom animations. So do you have any idea for custom animations? Thanks again.
Comment: Hey, with some code you can animate pretty much anything. If you don't want to write extra code there are animatable properties you can use for your purposes. for the case of font size you might animate the label's transform for example. a lot varies on the result you want to achieve, but this would be another question. Better not to go off topic here.
Comment: But the font size, even attributed text has no animation properties, but timer is the most way to custom these animations. No matter what animation I want to perform, it always performs more previously,and more beautifully. Because I can control the value every frame previously. That's all, thank you very much!


How to use :inverse_to in ActiveRecord

Question: :inverse_to doesn't work with my complex case
class Communication::Message < ActiveRecord::Base
  belongs_to :conversation_for_proposal, {
    :class_name  => 'Communication::Conversation::ForProposal',
    :foreign_key => :conversation_id,
    :inverse_of  => :messages_for_proposal
  }
end

class Communication::Conversation::ForProposal < ActiveRecord::Base
  has_many :messages_for_proposal, {
    :class_name  => 'Communication::Message',
    :foreign_key => :conversation_id,
    :inverse_of  => :conversation_for_proposal
  }
end

Problem: Communication::Conversation::ForProposal doesn't know about messages
Communication::Conversation::ForProposal.new.messages_for_proposal.build.conversation_for_proposal # => ok

Communication::Message.new.build_conversation_for_proposal.messages_for_proposal # => []

Reflections:
Communication::Message.reflect_on_association(:conversation_for_proposal).active_record
# => Communication::Message

Communication::Message.reflect_on_association(:conversation_for_proposal).inverse_of.active_record
# => Communication::Conversation::ForProposal

What I miss?
Answer: You need to specify the :inverse_of option.
class Post < AR::Base
  has_many :comments, :inverse_of => :post
end

class Comment < AR::Base
  belongs_to :post, :inverse_of => :comments
end

How to use :inverse_to in ActiveRecord


How do you play barre chords which are at an angle?

Question: I read about the concept of an angled/oblique barre chord, where you use your index finger to play 2 different frets across different strings like so:
<code>-4- 3rd
-2- 1st
-3- 1st
-4- 2nd
---
-4- 4th
</code>
(I am aware that this might be a nonsense chord, but I hope it gets the concept across)
The concept again appeared on the question Fingerstyle guitar - how to play this arpeggio?
I looked around the net and found this forum post, but nothing on SE.
So, Does anyone have any practical experience/guides on how to use such a technique?
Answer: I think it's very hard to do on neighboring strings. I do use it occasionally between the low E and the high E (that's the easiest combination for me) when playing a major 7 chord in drop-3 voicing, with an additional major 7 on the high E string:
(from low E to high E):

5 X 6 6 5 4

where I use fingers

1 3 4 5 1

so there's an angled barre chord from the low E 5th fret to the high E 4th fret.
The chord you gave as an example - which by the way is perfectly fine, it's an Ab9sus4 - I would play with the following fingering

T 3 2 1 4

(where T is my thumb).
Comment: Yes, I'm into jazz harmony.
Comment: Did you know that it was an Ab9sus4 off the top of your head?


"JsonResult" não contém um construtor que aceita 0 argumentos

Question: Estou tentando retornar um JsonResult para minha View, mas ele está retornando o seguinte errro.

"JsonResult" não contém um construtor que aceita 0 argumentos

Saberiam me ajudar amigos ?
[HttpGet]
public async Task<IActionResult> GetAllSchedule()
{
    var user = await _userManager.GetUserAsync(User);

    if (user == null)
    {
        throw new ApplicationException($"Não é possível carregar o usuário com o ID '{_userManager.GetUserId(User)}'.");
    }

    var events = _scheduleManager.GetAllSchedule(user.Id);

    return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

    }

Na linha do return estou recebendo o erro que citei acima, poderiam me ajudar ?
Comment: É .Net Core, certo? tente sem o `JsonRequestBehavior = JsonRequestBehavior.AllowGet`, assim `return new JsonResult(new { Data = events })`. Estou pelo celular e jaja gero uma resposta.
Answer: No .Net Core não tem a opção JsonRequestBehavior ele é gerenciado pelo atributo que fica em cima do IActionResult, no seu caso você já informa que é um Get com o HttpGet.
Há duas opções, primeiro retornar o JsonResult que é a classe e no seu construtuor espera um objeto ou um objeto mais uma instancia de JsonSerializerSettings ou usar o método Json que está dentro da classe Controller e irá retornar um JsonResult e este também espera um objeto ou um objeto mais uma instancia de JsonSerializerSettings
Sua IActionResult ficaria assim:
[HttpGet]
public async Task<IActionResult> GetAllSchedule()
{
    var user = await _userManager.GetUserAsync(User);

    if (user == null)
    {
        throw new ApplicationException($"Não é possível carregar o usuário com o ID '{_userManager.GetUserId(User)}'.");
    }

    var events = _scheduleManager.GetAllSchedule(user.Id);

    return new JsonResult(new { Data = events });
}

Ou
[HttpGet]
public async Task<IActionResult> GetAllSchedule()
{
    var user = await _userManager.GetUserAsync(User);

    if (user == null)
    {
        throw new ApplicationException($"Não é possível carregar o usuário com o ID '{_userManager.GetUserId(User)}'.");
    }

    var events = _scheduleManager.GetAllSchedule(user.Id);

    return Json(new { Data = events });
}

Quanto a classe JsonSerializerSettings você pode ver mais na documentação oficial


Limit of the fraction $\dfrac{n(n+1)^\alpha}{\sum_{k=1}^nk^\alpha}$

Question: I'm stuck in calculating the following limit:
$$L=\displaystyle\lim_{n\to\infty}\dfrac{n(n+1)^\alpha}{\sum_{k=1}^nk^\alpha}$$
For what values of $\alpha\in\mathbb{R}$ $L$ has a finite value?
Thanks.
Answer: For $\alpha>-1$, by the Stolz–Cesàro theorem,
\begin{eqnarray}
L&=&\lim_{n\to\infty}\dfrac{n(n+1)^\alpha}{\sum_{k=1}^nk^\alpha}\\
&=&\lim_{n\to \infty}\frac{(n+1)(n+2)^\alpha-n(n+1)^\alpha}{(n+1)^\alpha}\\
&=&\lim_{n\to \infty}\frac{(n+1)(1+\frac{2\alpha}{n}+O(\frac{1}{n^2}))-n(1+\frac{\alpha}{n}+O(\frac{1}{n^2}))}{(1+\frac1n)^\alpha}\\
&=&\lim_{n\to \infty}\frac{1+\alpha+O(\frac{1}{n})}{(1+\frac1n)^\alpha}\\
&=&1+\alpha.
\end{eqnarray}
Here
$$ (1+x)^\alpha=1+\alpha x+O(x^2). $$
For $\alpha<-1$, let $\beta=-\alpha$. Note that $\beta>1$ and $\{\sum_{k=1}^n\frac{1}{k^{\beta}}\}$ converges. Thus
\begin{eqnarray}
L&=&\lim_{n\to\infty}\dfrac{n(n+1)^{-\beta}}{\sum_{k=1}^nk^{-\beta}}\\
&=&\lim_{n\to \infty}\dfrac{n}{(n+1)^{\beta}\sum_{k=1}^n\frac{1}{k^{\beta}}}\\
&=&0.
\end{eqnarray}
For $\alpha=-1$, $\{\sum_{k=1}^n\frac{1}{k}\}$ diverges and hence
\begin{eqnarray}
L&=&\lim_{n\to\infty}\dfrac{n(n+1)^{-1}}{\sum_{k=1}^nk^{-1}}\\
&=&\lim_{n\to \infty}\dfrac{n}{(n+1)\sum_{k=1}^n\frac{1}{k}}\\
&=&0.
\end{eqnarray}
Comment: If $\alpha \le -1$, this development is invalid and the result is incorrect.
Comment: @Dr.MV, yes, you are right. Thanks.
Comment: @Dr.MV, the problem is fixed.
Comment: And a +1.  Well done.  -Mark


Load Data while Scrolling Page Down with jQuery and PHP

Question: Using mootools, created an aplication to load data while scrolling page down by handle the scroll event with following Mootools calculation
window.getScrollSize().y-window.getScroll().y-window.getSize().y < PRELOAD_DISTANCE;

Here
PRELOAD_DISTANCE = 150

What is the Jquery alternate for  following
window.getScrollSize().y-window.getScroll().y-window.getSize().y < PRELOAD_DISTANCE;

Any help please
Thanks in advance :)
Answer: Try this:
$(window).height() - $(window).scrollTop() - $(document).height() < PRELOAD_DISTANCE;


Minor Harmony doubts

Question: I've tried written a little chorale in four parts using minor harmony (Bb minor).

Established that for sure I have done several harmonic errors in terms of parts motion in the sense of traditional harmony, I have some troubles understanding some degrees which I intuitively assigned to some chords that I wrote (which correspond to the highlighted parts).
Basically I started with the melody and I decided to keep it without doing any further modifications.
So I harmonized keeping in mind the chords I wanted to use for each section by completing the harmony and also choosing some inversions for smooth bass movements.
QUESTION: Is it possible to MIX the harmonic possibilities (triads at this level) given by harmonic/melodic/natural minor together freely? Because I've done that depending on the melody note.
The highlighted notes.. they are not present in the harmonic possibilities notes of Bb minor, So I considered them as chromaticisms.. And I intuitively harmonized them using diminished chords.. Is this a common behavior? And if yes, why? Also, since diminished triads I used to harmonize them are not available in Bb minor, which degrees should assign to them?
Answer: You've asked a lot of this already HERE
Same answer.  Yes you can freely mix all forms of the minor scale.
But you've asked some new questions too.
Yes, diminished chords are often chromatic.
You've broken your own rule by departing from B♭ minor in bar 5!
But, all 'theory' apart, have you PLAYED this?   Do you like the sounds you've written?  Do you really like the Db in the second chord of bar 5?  Do you think the voicing of bar 1 sounds good?  And quite a few similar questions.
Comment: Laurence, if you feel like a question is already answered, please vote to close it as a duplicate rather than post a link to the duplicate as an answer.
Comment: Read ALL the answer, @Dom?
Comment: The rest of your answer is at best a comment by not really explaining. Please use the features of the site like closing questions as a duplicate and specifying a poster trim down parts of the question so it's easier for others to find.
Comment: Yes Ok I finally got that I can mix minor scales  but what about the notation of degrees I highlighted?
Comment: @JamesArten please ask as a separate question so others can easily find.
Comment: Why did you close it even if I asked also new questions I didn't get an answer yet. This was not a duplicate at all.

Minor Harmony doubts


How do I fix the missing top 1/2 inch of the content box?

Question: I made a number of formatting changes to several basic pages using a Bootstrap-based premium theme. The changes accomplished what I wanted but I subsequently noticed that, when I visited the site as an anonymous user, the top roughly 1/2 inch of the content part of each page is not displayed. It's as if the top of the page is hidden behind the horizontal menu bar at the top of the page rather than appearing correctly a 1/2 inch down.
I backed out all the changes I could remember making but it's still broken. It displays correctly when logged in as either admin or an authenticated user. I don't know how to even begin troubleshooting this issue. Can anyone point me in the right direction?
Comment: You will need more details before someone understands your question and is able to asnwer it
Comment: to expand on @GiorgosK 's comment, do you mean the content its self or mean the css or what ? is this site live if so share link as this has way way way way way way too many different issues that could cause the "problem"
Comment: Here is the site:  http://secondary.makeminechocolate.org/node/53. This is just one page where you can see that the top 1/2 inch doesn't display. So part of the cartoon character's head is cut off as well as text to the right of it. This happens on most of the pages when anonymous but displays correctly when logged in.
Answer: The body class in the custom-media.css is defining margin-top: 90px for the fixed header, you will need to increase this to match the size of your header.
You may need to include media queries to account for reactive menu changes.
It probably works when you are logged in because either the admin toolbar is modifying the margin or there is a rule specifically for being logged in that assumes the toolbar but you don't have it enabled.
Comment: Thanks for the response. The thing that confuses me is I have not touched anything in that file. It's a premium theme. So the file is the same for both secondary.makeminechocolate.net and tertiary.makeminechocolate.net. secondary is the broken one. tertiary uses the backup of the site from the day before the site broke. tertiary works properly, secondary does not. So I'm rebuilding the tertiary site to include the new code but, frankly, I'm spooked that the site could just break and not be fixable by simply removing the changes I had made to it that day.
Comment: The tertiary site has the same problem.  It is just not noticeable as the carousel image is larger and you don't see the cropping. Look at the raw image compared to what you see.  E.g. the rabbit toys have bright color items at the top that are cut off on the site.
Comment: Ugh. Thanks, everyone. I didn't catch that both sites are broken. I will try to make the changes and see how it goes. I hope it's okay for me to keep this question open until I get it figured out. My sincere appreciation!
Comment: Worked like a charm. I really appreciate the help.


Is NULL always false?

Question: Is it safe to assume that NULL always translates to false in C?
void *somePtr = NULL;

if (!somePtr) {
  /* This will always be executed? */
}

Or should an explicit check against the value of NULL be made?
Comment: Your code does not use the value if NULL
Comment: I simply refer you to [Question 5.3](http://c-faq.com/null/ptrtest.html "Question 5.3") of the C-FAQ. It answers this exact question.
Comment: `if (NULL)` is a direct test of `NULL`.  `if (!somePtr)` is not.
Answer: Yes.  NULL evaluates to false, since C considers any non-zero value true and any zero value false.  NULL is essentially the zero address and is treated as such in comparisons, and I believe would be promoted to an int for the boolean check.  I would expect that your code is readable to anyone familiar with C although I would probably make the check explicit.

In C and C++ programming, two null
  pointers are guaranteed to compare
  equal; ANSI C guarantees that any null
  pointer will be equal to 0 in a
  comparison with an integer type;
  furthermore the macro NULL is defined
  as a null pointer constant, that is
  value 0 (either as an integer type or
  converted to a pointer to void), so a
  null pointer will compare equal to
  NULL.

Ref: http://en.wikipedia.org/wiki/Null_pointer#Null_pointer
Comment: An explicit check may be clearer in some cases, but this is a C idiom that is guaranteed by the language to be valid.  :)
Comment: you don't cast to int though. you compare 0 to the pointer. 0 is a null pointer constant. and if you compare a null pointer constant to a pointer, the null pointer constant will become a null pointer of the right type. and a null pointer compares unequal to every valid pointer. that's what he wants
Comment: i would have cried if all my c code using those if stuffs is now invalid :)
Comment: yes jpalecek that's the whole point. a "null pointer" does not mean "zero bits". a null pointer is a black-box. In the if, the " != 0" is implicit, and in !ptr, the "== 0" is implicit. so if you do if(ptr), it will compare the pointer to a null pointer constant.
Comment: `NULL is essentially the zero address` this is not quite correct. NULL is 0 when converted to a numeric value, but the value of the null pointer may be non-zero [Is NULL always zero in C?](https://stackoverflow.com/q/9894013/995714). The address 0 may be valid, esp. on embedded systems
Comment: The standard isn't very clear on the issue: it's guaranteed that 0 cast to a pointer type will be a null pointer, but afaik it does not specify what will happen when a null pointer is cast to int!
Comment: The situation in the standard is more convoluted: it allows null pointer to have address eg. 0xdeadbeef, but IMHO still evaluate to false. That's because there is no conversion in the if-clause, the condition should have scalar type (pointer is a scalar type) and NULL pointer compares equal to 0
Comment: Perhaps tvanfosson could scratch the part about the promotion to an integer for the boolean check?
Comment: Referencing a Wikipedia isn't a good idea... Any ref to the standards?
Answer: The 'C' language dates from an era where (void*)0 could actually be a valid pointer.  It is not that long ago, the 8080 and Z80 microprocessors had an interrupt vector at address 0.  Faced with such architecture choices, it couldn't do anything but let a header file declare the value of NULL.  There were some compilers out there, now long forgotten, where NULL was not equal to (void*)0 (0xffff was the next alternative), thus giving your if() statement undefined behavior.
C++ mercifully put an end to this, a null pointer is assignable from and testable against 0.
Comment: C99 guarantees that 0 cast to a pointer type will be a null pointer as well - I never bothered to read previous standards, so no idea when this happened...
Comment: About your C++ sentence: that's wrong. 0 is not a null pointer. 0 is a null pointer constant. void *p = 0; now, p is a null pointer. it's a difference, because a null pointer has pointer type, where a null pointer constant has integer type and is a constant expression
Comment: 0 still remains a perfectly valid address on every arch I have written mmu-code for.  It is just a convention of many C runtimes that invalidate its use.   In modern linux, as root, you can mmap an object to 0 with MAP_FIXED.   In not-long-ago UNIX, it was common to map a read-only zero page to zero so that strcmp(NULL, ...) would not cause a fault, but would only match an empty string.
Comment: MMUs were probably more significant than C++ in the change.
Comment: *"giving your if() statement undefined behavior."* — [C FAQ disagrees](http://c-faq.com/null/ptrtest.html)
Comment: Not that long ago, the 8086 through the 80686 had an interrupt vector at address 0 in real mode.
Answer: It's never safe to assume anything.
An explicit check is also more clear about what you're testing.
Comment: @Peter Rowell: for quite a long time, I used #define NIL(x) ((x)0) to achieve roughly that effect:  NIL(foo), NIL(char *), NIL(bar), etc.
Comment: We used to take it one step further and define a type-specific nil value for each of our typedef'ed items: structs, int, longs, whatever. That way the conditional would read "if (foo != fooNil) { etc. }". Disclaimer: I used to work for Simonyi at Xerox so my brain was contaminated.
Comment: @Jonathan: in which language - C or C++? In C99, that's unnecessary, because 'Any two null pointers shall compare equal.'
Answer: Yes (at least for any standards compliant C compiler!)
From the comp.lang.c FAQ:

Q: Is the abbreviated pointer comparison ``if(p)'' to test for non-null pointers valid? What if the internal representation for null pointers is nonzero?
A: It is always valid.
Answer: My copy of ISO/IEC 9899:TC3 (Committee Draft — Septermber 7, 2007) says:

6.3 Conversions
1 Several operators convert operand values from one type to another automatically.
184.108.40.206 Pointers
3 An integer constant expression with the value 0 [...] is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

So far, ptr!=0 is true (1) for every non-null ptr, but it's still open, how two null pointers compare.

6.5.9 Equality operators
5 [...] If one operand is a pointer and the other is a null pointer constant, the null pointer constant is converted to the type of the pointer.
6 Two pointers compare equal if and only if both are null pointers, both are [...]

Hence, ptr==0 is 1 (and ptr!=0 is 0), if and only if ptr is a null pointer.

220.127.116.11 Unary arithmetic operators
5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

So the same holds for !ptr.

126.96.36.199 The if statement
1 The controlling expression of an if statement shall have scalar type.
2 In both forms, the first substatement is executed if the expression compares unequal to 0.

Note, that a scalar type is an arithmetic type or a pointer type (see "6.2.5 Types", clause 21). Putting it together, we have:

if (ptr) succeeds ⇔ ptr!=0 is 1 ⇔ ptr is not a null pointer.
if (!ptr) succeeds ⇔ ptr==0 is 1 ⇔ ptr is a null pointer.
Comment: The cited document is available on http://www.open-std.org/jtc1/sc22/wg14/www/standards
Answer: Yes, if(!p) is valid and guaranteed to work.

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

https://port70.net/~nsz/c/c11/n1570.html#184.108.40.206p3
This means that (void*)0 is a null pointer. It also means that if p is a pointer, then p==0 is equivalent to p==(void*)0.
It also means that if p is a not a null pointer, then p==(void*)0 will evaluate to 0.
So far, so good.

Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

http://port70.net/~nsz/c/c11/n1570.html#22.214.171.124p4
Note that "Any two null pointers shall compare equal." This means that if p is a null pointer, then p==0 will evaluate to true, because 0 will be promoted to (void*)0 which is a null pointer. It also mean that no non-null pointer can be equal to a null pointer.
Let's have a look at the negation operator.

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

http://port70.net/~nsz/c/c11/n1570.html#184.108.40.206p5
This tells us that !p is the same as p==0 by definition, which is the same as p==(void*)0 as mentioned above.
And taking the fact that all null pointers are equal into consideration, this means that p==(void*)0 can only evaluate to true if p is a null pointer and and only false if p is not a null pointer.
So yes, if(!p) is a perfectly safe way to check if p is a null pointer or not.
Answer: NULL is just a preprocessor definition.  It's in stdio.h.  Typically, only an insane person would redefine it, but it's possible.  An example:
#include <stdio.h>
#ifdef NULL
#undef NULL
#endif
#define NULL 1

void main()
{

        if (NULL)
                printf("NULL is true\n");
        else
                printf("NULL is false\n");
}

This code will print "NULL is true".  Try it if you don't believe me.  Your compiler might not even warn you that you're doing something weird.
Comment: That would be plain wrong. The compiler and the C standard library are bundled together for a reason. If you mess with it, you are breaking this.
Comment: But if you define NULL to 1 and assign somePtr = NULL, you'll at least get a warning that you're converting an integer to a pointer.
Comment: Interesting.  You can make it not warn by doing:

    #define NULL (void *) 1
Answer:
What is NULL?

The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant;

What is the value of the null pointer constant?

An integer constant expression with the value 0, or such an expression cast to type
  void *, is called a null pointer constant.

Example Definition:
#define NULL ((void*)0)

Evaluating if(NULL)

if ( expression ) statement
if ( expression ) statement else statement
In both forms, the first substatement is executed if the expression compares unequal to 0.
  In the else form, the second substatement is executed if the expression compares equal
  §18.104.22.168 Language 133
  ISO/IEC 9899:TC3 Committee Draft — Septermber 7, 2007 WG14/N1256
  to 0. If the first substatement is reached via a label, the second substatement is not
  executed.

So yes if the compiler is compliant with ISO C99 you can assume that the statement below will always execute.
if (!NULL) { statement; }

Above quotations are from ISO/IEC 9899:1999 (C99). You can read it here.
Answer: Yes it:
C standard 126.96.36.199

An  integer  constant  expression  with  the  value  0,  or  such  an
  expression  cast  to  type void *, is called a null pointer
  constant.If a null pointer constant is converted to a pointer type,
  the resulting pointer, called a null pointer, is guaranteed to compare
  unequal to a pointer to any object or function.

and 18.104.22.168

Any pointer type may be converted to an integer type.  Except as
  previously specified, the result  is  implementation-defined.  If  the
  result  cannot  be  represented  in  the  integer  type, the  behavior
  is  undefined.  The  result  need  not  be  in  the  range  of  values
  of  any integer type.

-

When any scalar value is converted to _Bool, the result is 0 if the
  value compares equal to 0; otherwise, the result is 1
Answer: NULL is defined as a constant pointer that is guaranteed to point to a useless/non-existent place in memory. Most implementations of NULL are ((void *)0) but it is not mandatory that this is so.
Comment: In any correct C compiler "NULL == 0" is true, even if a null pointer does not really contain 0.

What you can't do is memzero a pointer and then assume it will be NULL.
Comment: In C, that's correct.  Be aware that in C++, it is most frequently just 0, mainly because you can't convert a void pointer to any other type without an explicit cast.
Answer: According to me, it's not always safe to assume that. Since, depending on which headers have been included in a program, it can have been redefined. But according to the standard, the null pointer constant is guaranteed not to point to any real object and has a type void *.
In our case, the declaration void *somePtr = NULL could also be void *somePtr = 0 with 0 as null pointer.

"An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function." https://www.geeksforgeeks.org/few-bytes-on-null-pointer-in-c/

That simply means, evaluating *somePtr at that specific point could result to false.
Another reference can be https://www.gnu.org/software/libc/manual/pdf/libc.pdf at page 944 A.3 about NULL Pointer Constant
Answer: Yes, mostly.
First off, NULL is a typedef. I could royally screw you over by saying in a previously included header
#define NULL 1
This might not make a lot of sense, but since when has other people's code ever made sense? :)
Also, while it's probably syntactically safe, it's not semantically correct. NULL means "nothing", neither true or false or a boolean value or int or string. It means "a symbol for nothing". So testing for NULL is more like a philisophical issue: If a tree falls in the forest, and if(listener), does it make a sound?
Do everyone a favor and be clear about testing against NULL.
Comment: @Matt: Don't you mean a macro :-)?
Answer: *NULL always targets to 0x00L. You can consider that false, but to be sure always do an explicit check.
Comment: NULL is implementation specific. In some cases, such as embedded machines, you may want to access the very first byte in RAM which would be addressed as 0. NULL is defined by the standard as a pointer that is guaranteed not to point to any usable point in RAM.
Comment: Dereferencing either NULL itself or a null pointer invokes undefined behaviour -- or, on big enough machines with MMUs, a core dump or equivalent.  The "all the world's a VAX" syndrome died a while ago - there, derefencing NULL did yield a zero byte.
Comment: The lower 128 bytes of a vax machine give an access violation when you dereference them.   Do you have a program that demonstrates the symptoms you observed?

Is NULL always false?


If G is a subgraph of H then $p_c(G) \geq p_c(H)$

Question: I am trying to find a rigorous proof for If G is a subgraph of H then $p_c(G) \geq p_c(H)$
The statement is almost trivial but I cannot seem to prove it. Could anyone give some pointers for where to start?
Thanks :)
Comment: Please edit your question to say what $p_c$ refers to.
Answer: Ah, I see that you reformulated your previous question in a more general way. Because it might not be clear what $p_c$ means in a general graph setting, let me define it as
$$p_c(G) = \inf \left\{p \colon \inf_{x,y\in G} \mathbb{P}[x\leftrightarrow y] >0 \right\}\,, $$
i.e. the lower bound on $p$ for which connectivity throughout the whole graph is present with positive probability.
If $G$ is a 'subgraph' of $H$ (i.e. $G$ and $H$ have the same vertex set, while the edge set of $G$ is contained in the edge set of $H$), we can define a coupling between percolation on $G$ and percolation on $H$ in the following way:
For an edge $e\in G$, let $e$ be open with probability $p$ and closed otherwise. If open, also declare $e\in H$ as open, otherwise closed. For edges $f\in H$ that are not in $G$, declare them open in $H$ probability $p$. This process generates configurations according to the $p$-percolation measure on $G$ and $H$, with the additional property that
$$x\leftrightarrow y \text{ in } G \Rightarrow x\leftrightarrow y \text{ in } H $$
for all $x,y$. This implies
$$ \mathbb{P}[x\leftrightarrow y \text{ in } G] \leq \mathbb{P}[x\leftrightarrow y \text{ in } H]$$
for all $x,y$, and therefore $p_c(G) \geq p_c(H)$.
In words: The coupling shows that high connectivity in $G$ implies high connectivity in $H$.
Comment: Thank you very much! I ended up using the exponential decay theorem but this is soooo much cleaner!


Prove $\int_0^1 \frac{\tanh^{-1} (\beta t) dt}{t\sqrt{(1-t)(1- \alpha t)}}=\log (a) \log (b)$

Question: If we set:

$$\alpha= \frac{(ab-1)^2+(a-b)^2}{(ab+1)^2+(a+b)^2}$$
$$\beta= \frac{(ab+1)^2-(a+b)^2}{(ab+1)^2+(a+b)^2}$$

Then it follows that:

$$\int_0^1 \frac{\tanh^{-1} (\beta t) dt}{t\sqrt{(1-t)(1- \alpha t)}}=\log (a) \log (b)$$

I have derived this result in a very roundabout way, most of the details you can see in this post, however from the symmetry of it I suspect there may be better and more clear ways to prove it, which is why I'm asking a separate question.
Aside from the proof, I'm interested in deeper reasons or implications for this identity (if they exist) and some references to similar ones.
Answer: We can solve this integral using only substitutions and integration by parts, as follows:
$$I:=\int_0^1 \frac{\operatorname{arctanh} (\beta t) }{t\sqrt{(1-t)(1- \alpha t)}}dt=\int_0^1 \frac{\operatorname{arctanh}(\beta t)}{t(1-t)}\sqrt{\frac{1-t}{1-\alpha t}}dt$$
$$\overset{\large \frac{1-t}{1-\alpha t}=x}=\int_0^1 \frac{\operatorname{arctanh}\left(\beta \frac{1-x}{1-\alpha x}\right)}{\sqrt x(1-x)}dx\overset{x=y^2}=2\int_0^1 \frac{\operatorname{arctanh}\left(\beta \frac{1-y^2}{1-\alpha y^2}\right)}{1-y^2}dy$$
$$\overset{\large y=\frac{1-x}{1+x}}=\int_0^1 \operatorname{arctanh}\left( \frac{4\beta x}{(1+x)^2-\alpha (1-x)^2}\right)\frac{dx}{x}=\frac12 \int_0^1 \ln\left(\frac{\left(ab+x\right)\left(\frac{1}{ab}+x\right)}{\left(\frac{a}{b}+x\right)\left(\frac{b}{a}+x\right)}\right)\frac{dx}{x}$$
$$\overset{IBP}=\frac12 \int_0^1 \ln x \left(\frac{1}{\frac{a}{b}+x}+\frac{1}{\frac{b}{a}+x}-\frac{1}{ab+x}-\frac{1}{\frac{1}{ab}+x}\right)dx$$
In each of the integral from above we will simplify the denominator using the substitution $x\to kx$, where $k$ is the constant found in each denominator.
$$\Rightarrow I=\frac12 \left(\int_0^\frac{b}{a}\frac{\ln\left(\frac{a}{b}x\right)}{1+x}dx+\int_0^\frac{a}{b}\frac{\ln\left(\frac{b}{a}x\right)}{1+x}dx-\int_0^\frac{1}{ab}\frac{\ln\left(ab x\right)}{1+x}dx-\int_0^{ab}\frac{\ln\left(\frac{x}{ab}\right)}{1+x}dx\right)$$
$$\small =\color{red}{\frac12} \left(\ln\left(\frac{a}{b}\right)\ln\left(1+\frac{b}{a}\right)+\ln\left(\frac{b}{a}\right)\ln\left(1+\frac{a}{b}\right)-\ln(ab)\ln\left(1+\frac{1}{ab}\right)-\ln\left(\frac{1}{ab}\right)\ln\left(1+ab\right)\right)$$
$$+\color{chocolate}{\frac12}\left(\int_0^\frac{b}{a}\frac{\ln x}{1+x}dx+\int_0^\frac{a}{b}\frac{\ln x}{1+x}dx-\int_0^\frac{1}{ab}\frac{\ln x}{1+x}dx-\int_0^{ab}\frac{\ln x}{1+x}dx\right)$$
We can also rewrite the four integrals from above as:
$$\color{blue}{\int_\frac{1}{ab}^\frac{b}{a}\frac{\ln x}{1+x}dx}+\int_{ab}^\frac{a}{b}\frac{\ln x}{1+x}dx\overset{\color{blue}{x\to \frac{1}{x}}}=\color{blue}{\int_{ab}^\frac{a}{b}\frac{\ln x}{x}dx-\int_{ab}^\frac{a}{b}\frac{\ln x}{1+x}dx}+\int_{ab}^\frac{a}{b}\frac{\ln x}{1+x}dx$$
$$=\int_{ab}^\frac{a}{b}\frac{\ln x}{x}dx=\frac{\ln^2 x}{2}\bigg|_{ab}^\frac{a}{b}=-2\ln a\ln b$$
So with some algebra for the first term we finally get:
$$I=\color{red}{\frac12}\left(4\ln a \ln b\right)+\color{chocolate}{\frac12}\left(-2\ln a \ln b\right)=\boxed{\ln a\ln b}$$

An alternative approach using Feynman's trick can be found here, which shows:
$$\int_0^1 \ln\left(\frac{\left(ab+x\right)\left(\frac{1}{ab}+x\right)}{\left(\frac{a}{b}+x\right)\left(\frac{b}{a}+x\right)}\right)\frac{dx}{x}=2\ln a\ln b$$
It might be useful in the future so I'll also mention that, since $\int_0^1 \frac{\ln x}{t+x}dx=\operatorname{Li}_2\left(-\frac{1}{t}\right)$ the following Dilogarithm identity arises from above:
$$\boxed{\operatorname{Li}_2\left(-\frac{a}{b}\right)+\operatorname{Li}_2\left(-\frac{b}{a}\right)-\operatorname{Li}_2\left(-ab\right)-\operatorname{Li}_2\left(-\frac{1}{ab}\right)=2\ln a\ln b;\ a,b>0}$$
Answer: The given integral, after the substitution $t=\dfrac{(1-\alpha)x}{1-\alpha x}$, is equal to $$\int_0^1\tanh^{-1}\frac{\beta x}{1-\alpha+\alpha x}\frac{dx}{x\sqrt{1-x}}=\frac{1}{2}\Bigg(f\Big(\underbrace{\frac{\alpha+\beta}{1-\alpha}}_{=\frac{(ab-1)^2}{4ab}}\Big)-f\Big(\underbrace{\frac{\alpha-\beta}{1-\alpha}}_{=\frac{(a-b)^2}{4ab}}\Big)\Bigg),$$ where $$f(a)=\int_0^1\frac{\log(1+ax)}{x\sqrt{1-x}}~dx=\begin{cases}\color{blue}{2\log^2(\sqrt{a}+\sqrt{a+1})},&\phantom{-1\leqslant{}}a\geqslant0\\-2\arcsin^2\sqrt{-a},&-1\leqslant a<0\end{cases}$$ can be evaluated in many ways; a simple one is via "Feynman's trick": for $a>0$, $$f'(a)=\int_0^1\frac{dx}{(1+ax)\underbrace{\sqrt{1-x}}_{=y}}=2\int_0^1\frac{dy}{1+a-ay^2}\\=\frac{2}{\sqrt{a(a+1)}}\tanh^{-1}\sqrt\frac{a}{a+1}=2\frac{\log(\sqrt{a}+\sqrt{a+1})}{\sqrt{a(a+1)}}.$$
Answer: Probably there's a more elegant and concise solution, but this is what I've got:
$$I=\int_0^1 \underbrace{\frac{tanh^{-1}(\beta t)}{t\sqrt{(1-t)(1-\alpha t)}}dt}_{t\rightarrow\frac{1-t}{1+t}}=\sqrt{2}\int_0^1 \underbrace{\frac{tanh^{-1}(\beta \frac{1-t}{1+t})}{(1-t)\sqrt{(1+\alpha)t+1-\alpha}}\frac{dt}{\sqrt{t}}}_{\sqrt{t}\rightarrow t}$$
$$I=2\sqrt{2}\int_0^1 \underbrace{\frac{tanh^{-1}(\beta \frac{1-t^2}{1+t^2})}{(1-t^2)\sqrt{(1+\alpha)t^2+1-\alpha}}dt}_{t\rightarrow tanh(x)}=2\sqrt{2}\int_0^{\infty} \underbrace{\frac{tanh^{-1}\left(\frac{\beta}{2sinh^2(x)+1}\right)}{\sqrt{2sinh^2(x)+1-\alpha}}cosh(x)dx}_{sinh(x)\rightarrow x}$$
$$I=2\sqrt{2}\int_0^{\infty} \underbrace{\frac{tanh^{-1}\left(\frac{\beta}{2x^2+1}\right)}{\sqrt{2x^2+1-\alpha}}dx}_{x\rightarrow \sqrt{\frac{1-\alpha}{2}}x}=2\int_0^{\infty}\underbrace{\frac{tanh^{-1}\left(\frac{\beta}{(1-\alpha)x^2+1}\right)}{\sqrt{x^2+1}}dx}_{x\rightarrow sinh(z)}$$
$$\color{blue}{2tanh^{-1}\left(\frac{\beta}{(1-\alpha)x^2+1}\right)=log\left(\frac{x^2+\frac{1+\beta}{1-\alpha}}{x^2+\frac{1-\beta}{1-\alpha}}\right)=log\left(\frac{x^2+\frac{(1+ab)^2}{4ab}}{x^2+\frac{(a+b)^2}{4ab}}\right)}$$
$$I=\int_0^{\infty}log\left(\frac{sinh^2(z)+\frac{(1+ab)^2}{4ab}}{sinh^2(z)+\frac{(a+b)^2}{4ab}}\right)dz=\int_0^{\infty}\underbrace{log\left[\frac{\left(ab+e^{-2z}\right)\left(abe^{-2z}+1\right)}{\left(ae^{-2z}+b\right)\left(a+be^{-2z}\right)}\right]dz}_{e^{-2z}\rightarrow z}$$
$$I=\frac{1}{2}\int_{0}^{1}\log{\left[\frac{z^2+\left(ab+\frac{1}{ab}\right)z+1}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}\right]}\frac{dz}{z}\overbrace{=}^{IBP}$$
$$I=\frac{1}{2}\int_{0}^{1}{\log{\left(z\right)}\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz}$$
Notice that due to symmetry $\int_0^1 g(z)dz=\frac{1}{2}\int_0^\infty g(z)dz$. Therefore:
$$I=\frac{1}{4}\int_{0}^{\infty}{\log{\left(z\right)}\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz}$$
To evaluate this integral let's use Complex Analysis. First, let's consider a keyhole contour and the following function:
$$f(z)=\log^2{\left(z\right)}\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]$$
$$\oint f(z)dz=\left(\int_\Gamma+\int_\gamma+\int_{ir}^{R+ir}+\int_{R-ir}^{-ir}\right)f(z)dz$$

Applying the ML Inequality it's easy to show that $\int_\Gamma f(z)dz \rightarrow 0$ as $R \rightarrow \infty$ and $\int_\gamma f(z)dz \rightarrow 0$ as $r \rightarrow 0$.
The other two integrals from the RHS can be rewritten as:
$$\int_0^\infty [log^2{\left(z\right)}-(log(z)+2\pi i)^2]\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz$$
$$\int_0^\infty (-4\pi ilog(z)+4\pi^2)\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz$$
$$-4\pi i\int_0^\infty log(z)\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz+\color{red}{0}$$
$$\color{red}{4\pi^2\int_0^\infty \left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz=4\pi^2log\left[\frac{z^2+\left(ab+\frac{1}{ab}\right)z+1}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}\right]_0^\infty}$$
Computing the residues:
$$\oint f(z)dz=2\pi i\left[log^2\left(-\frac{a}{b}\right)+log^2\left(-\frac{b}{a}\right)-log^2\left(-ab\right)-log^2\left(-\frac{1}{ab}\right)\right]=-16\pi\ i log(a)log(b)$$
Hence, gathering the results:
$$\int_0^\infty log(z)\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz=4log(a)log(b)$$
From this is possible to conclude that:
$$I=\int_0^1\frac{tanh^{-1}(\beta t)}{t\sqrt{(1-t)(1-\alpha t)}}dt=\frac{1}{4}\int_{0}^{\infty}{\log{\left(z\right)}\left[\frac{2z+\left(\frac{a}{b}+\frac{b}{a}\right)}{z^2+\left(\frac{a}{b}+\frac{b}{a}\right)z+1}-\frac{2z+\left(ab+\frac{1}{ab}\right)}{z^2+\left(ab+\frac{1}{ab}\right)z+1}\right]dz}=log(a)log(b)$$
Comment: This solution also shows the symmetry, so I like it, besides I'm grateful for more examples of contour integration, since this is the subject that I'm not very good at
Comment: Thank you so much for the bounty @Yuriy S! I'm glad you liked the solution. If you want to learn more about contour integration it might be worthy checking out Ron Gordon's site (http://residuetheorem.com), I've learned most of what I know about the subject through this source ;)
Comment: @P.Teruo Nagasava Please, Is there any chance to find a closed form for this integral? $\int_1^\infty t^2 \operatorname{ArcTanh}  \left(\sqrt{\frac{t^2-1}{t^2}} \dfrac{k}{x}\right)\, e^{-a\,t} \, dt$
Comment: @P.Teruo Nagasava this is my post https://math.stackexchange.com/q/4605055/574934


.htaccess mod_rewrite not catching all RewriteRules

Question: There is a PHP application with a PHP router as entry point for all the requests placed inside index.php. I am trying to write a .htaccess file to forward every request to index.php except for API requests and for design resources.
So I am trying to obtain the following behavior:

example.com/api/v1/* should serve api_v1.php
example.com/any_path/resource.css => should serve resource.css if it exists (there are multiple extensions allowed; .css is just one example)
serve index.php for anything that did not fall for the conditions above

Given that .htaccess is evaluated from top to the bottom, from particular to general conditions and that flag [L] would break the execution if anything matched, I have managed to come up with the following .htaccess:
RewriteEngine On

# Prevent 301 redirect with slash when folder exists and does not have slash appended
# This is not a security issue here since a PHP router is used and all the paths are redirected
DirectorySlash Off

#1. Rewrite for API url
RewriteRule ^api/v1/(.*)$ api_v1.php [L,NC]

#2. Rewrite to index.php except for for design/document/favicon/robots files that exists
RewriteCond %{REQUEST_URI} !.(css|js|png|jpg|jpeg|bmp|gif|ttf|eot|svg|woff|woff2|ico|webp|pdf)$
RewriteCond %{REQUEST_URI} !^(robots\.txt|favicon\.ico)$ [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L]

#3. Rewrite enything else
RewriteRule ^(.*)$ index.php [L]

Using the code above, it seems that accessing example.com/api/v1/ does not execute api_v1.php. Instead, it would continue and execute index.php
example.com/api/v1/ would only work if I remove all conditions after line 8.
What am I doing wrong here?
Comment: It's a little unclear exactly what you are trying to do. Should certain requests be rewritten to `index.php` even if they exist as a physical file, but not one of the file types stated? Should requests for resources (`.css`, `.jpg`, etc.) still be rewritten to `index.php` if they don't exist? (ie. do you have legitimate URLs that have a "file extension" like this?)
Comment: @MrWhite Yes, if a .css file is not found, rewrite to index.php so I can properly handle 404 error from index.php. If .css file exists serve it, otherwise rewrite to index.php
Comment: But what about file types you've not explicitly stated? Should these be routed through `index.php` regardless of whether they exist or not? (Do you need to explicitly state a list of known file types?)
Comment: Yes, whatever is NOT in that list, whether it exists or not, it should be rewritten to index.php. The only complication here is that I also rewrite to index.php for the file names that are in the list but NOT existing on server. Basically, I try to serve directly .css files if these exists, otherwise rewrite everything to index.php (referring to conditions #2 and #3)
Comment: I've updated my answer with a complete solution based on your comments.
Answer:
it seems that accessing site.com/api/v1/ does not execute api_v1.php. Instead it would continue and execute index.php

Yes, because the first rule rewrites the request to api_v1.php and this ends up getting rewritten to index.php by the second rule (because php is not in the list of excluded extensions in the first condition, the second condition is also successful so the third condition is not processed - see below) during the second pass of the rewrite engine. In a directory context (ie. .htaccess) the L flag does not stop all processing, it just stops the current pass through the rewrite engine. The rewrite engine loops until the URL passes through unchanged.
You could resolve this on Apache 2.4 by using the END flag, instead of L, on the first rule to stop all processing by the rewrite engine.
For example:
RewriteRule ^api/v1/ api_v1.php [NC,END]

(I removed the trailing (.*)$ on the regex since it's not necessary here and makes the regex marginally less efficient.)
However, the fact that a request for an existing .php file is rewritten by your later rules really demonstrates that your second and third rules do not seem to be working as intended...

#2. Rewrite to index.php except for for design/document/favicon/robots files that exists
RewriteCond %{REQUEST_URI} !.(css|js|png|jpg|jpeg|bmp|gif|ttf|eot|svg|woff|woff2|ico|webp|pdf)$
RewriteCond %{REQUEST_URI} !^(robots\.txt|favicon\.ico)$ [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L]

#3. Rewrite enything else
RewriteRule ^(.*)$ index.php [L]

If you request something.php then the first condition is successful (because .php is not included in the list). The second condition is also successful (it's not robots.txt or favicon.ico). Since the second condition is explicitly OR'd with the third condition, the third condition is not processed. All the conditions are successful and the request is rewritten to index.php (regardless of whether something.php exists or not).
If, on the other hand, you request resource.css then the first condition fails (because it has a .css extension). Since this condition is implicitly AND'd, no further conditions are processed and the rule is not triggered. The third rule then unconditionally rewrites resource.css to index.php, regardless of whether it exists or not!
So, this doesn't check that a requested resource (css, jpg, etc.) "exists" as would seem to imply by the preceding comment. The third condition (that checks the request does not map to a file) is only processed when the preceding OR'd condition fails AND the first condition is successful. In other words, the 3rd condition is only processed when you request /robots.txt - which I'm sure is not your intention.
In other words, rules #2 and #3 (despite their apparent complexity) would seem to be rewriting pretty much everything to index.php.
Complete solution
Based on your additional comments:

For a subset of file types, serve the resource - if it exists. If the resource does not exist then send the request to index.php.

For other file types, send the request to index.php, regardless of whether that resource exists or not.

A few requests (ie. /robots.txt and /favicon.ico) should not be sent to index.php.

Try the following instead:
# Prevent 301 redirect with slash when folder exists and does not have slash appended
# This is not a security issue here since a PHP router is used and all the paths are redirected
DirectorySlash Off

# Since "DirectorySlash Off" is set, ensure that mod_auotindex directory listings are disabled
Options -Indexes

RewriteEngine On

#1. Rewrite for API url
RewriteRule ^api/v1/ api_v1.php [NC,END]

#2. Known URLs/files are served directly
RewriteRule ^(index\.php|robots\.txt|favicon\.ico)$ - [END]

#3. Certain file types (resources) are served directly if they exist
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule \.(css|js|png|jpe?g|bmp|gif|ttf|eot|svg|woff|woff2|ico|webp|pdf)$ - [END]

#4. Rewrite everything else
RewriteRule ^ index.php [END]

The rules finish early for anything that needs to be served directly, so we only need to rewrite to index.php once in the last rule.
Note that I've included index.php in rule #2. This is an optimisation, although not strictly necessary if using the END flag (as opposed to L) on the last rule.
Optionally, you might choose to redirect any direct requests to index.php back to the root (to canonicalise the URL for search engines). This is just in case /index.php gets exposed (or guessed) to the end user.
For example, add the following after the first rule for the API:
#1.5 Redirect direct requests to "/index.php" back to "/" (root)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index\.php$ / [R=301,L]

The condition that checks against the REDIRECT_STATUS environment variable is necessary to prevent a redirect loop - to avoid redirecting the rewritten URL. (Although, again, this is not strictly required if using the END flag on the last/rewrite rule.)
Comment: Thanks for the extensive explanations. This definitely solved my problem and brought some very useful info on this topic.
Answer: Try to place a rewrite condition before each rule and then break the rule. In other words every condition needs to have it own rule.
condition -> rule
condition -> rule
...


How to solve this : For what values of a , the major axis of $\frac{x^2}{\log_{1/3}a^2}+\frac{y^2}{\log_a9 -5}=1$ is x axis?

Question: For what values of $a$ , the major axis of $\frac{x^2}{\log_{1/3}a^2}+\frac{y^2}{\log_a9 -5}=1$ is x axis ?
How to solve such problems, I have no idea  about this , please guide will be of great help.. Thanks
Answer: For the major axis of the ellipse to be the $\,x\,$-axis, we need $\,\log_{1/3}a^2 \gt \log_a9 - 5 \gt 0.\,$ First, some manipulations:
$$\log_{1/3}a^2 = 2\log_{1/3}a = -2\log_{3}a$$
$$\log_a9 = \log_a3^2 = 2\log_a3 = \dfrac{2}{\log_3a}$$
Note that
$$\log_{1/3}a^2 \gt 0 \Rightarrow -2\log_{3}a \gt 0 \Rightarrow \log_{3}a \lt 0$$
but
$$\log_a9 - 5 \gt 0 \Rightarrow \dfrac{2}{\log_3a} \gt 0 \Rightarrow \log_{3}a \gt 0$$
which is a contradiction. So the major axis cannot be the $\,x\,$-axis.


Glide doesn't load images until scrolled or don't load at all

Question: Android Studio 3.0 Beta 5
glide:3.7.0

I am using glide to load images into a CircleImageView. However, the images don't load until the recyclerview is scrolled. And sometimes when scrolling it is not smooth.
This is my viewholder:
public class MovieActorsViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.civActorPicture) CircleImageView actorPicture;
    @BindView(R.id.tvName) TextView name;
    @BindView(R.id.tvCharacter) TextView character;

    private Context context;

    public MovieActorsViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);

        context = itemView.getContext();
    }

    public void populateActor(Actor actor) {
        Glide.with(context)
                .load(MovieImage.build(actor.getProfile_path(), MovieImage.ImageSize.w92))
                .placeholder(R.drawable.people_placeholder)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(actorPicture);

        name.setText(actor.getName());
        character.setText(actor.getCharacter());
    }
}

My layout I am using. TextView always gets populated. However, when I open the detail screen. I have to scroll forwards and backwards for the images to load.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="6dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/civActorPicture"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_gravity="center"
        android:scaleType="centerCrop"
        tools:src="@drawable/people_placeholder"/>

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        tools:text="Micheal Keaton"/>

    <TextView
        android:id="@+id/tvCharacter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        tools:text="Adrian Toomes / The Vulture"/>
</LinearLayout>

Answer: Try to add .asBitmap() method before .load() this solved my problem
Glide.with(context)
      .asBitmap()
      .load(MovieImage.build(actor.getProfile_path(), MovieImage.ImageSize.w92))


Jordan canonical form of $T: \mathbb{Q}(\alpha) \rightarrow \mathbb{Q}(\alpha)$ where $\alpha \in \mathbb{C}$ and $T$ is multiplication by $\alpha$

Question: Suppose $p \in \mathbb{Q}[x]$ is irreducible and $\alpha \in \mathbb{C}$ is a root of $p$. Then consider the linear transformation $T : \mathbb{Q}(\alpha) \rightarrow \mathbb{Q}(\alpha)$, $x \mapsto \alpha x$.
What is the Jordan canonical form of $T$, considering $\mathbb{Q}(\alpha)$ to be a $\mathbb{Q}$ vector space?
Suppose $\deg(p) = n$ and $p = x^n + a_{n-1}x^{n-1} + \cdots + a_1x + a_0$. Then $\mathbb{Q}(\alpha)$ has dimension $n$ with basis $\{1, \alpha, \alpha^2, \cdots, \alpha^{n}\}$. Moreover, obviously the transformation $T$ acts on the basis element as $\alpha^i \mapsto \alpha^{i+1}$ for $i < n-1$. But $\alpha^{n-1} \mapsto \alpha^n = -a_{n-1}\alpha^{n-1} - \cdots - a_1\alpha - a_0$ in $\mathbb{Q}(\alpha)$.
Thus $T$ is represented by the companion matrix, $C_p$
Not sure what the next steps would be- I'm confusing myself a bit here. It is well known that the companion matrix $C_p$'s characteristic and minimal polynomial is $p$ itself. Moreover, we know that $\alpha$ is thus an eigenvalue, which means that $\bar{\alpha}$ is as well. Thus $(x-\alpha)(x-\bar{\alpha}) | p$. One cannot conclude at this point that since $p$ is irreducible, $(x-\alpha)(x-\bar{\alpha}) = p$, since it is possible that $(x- \alpha)(x-\bar{\alpha}) \in \mathbb{R}[x]\setminus \mathbb{Q}[x]$.
Even if $p = (x-\alpha)(x-\bar{\alpha})$ after all, I'm still a bit confused. Now that we've expanded our scope to $\mathbb{C}$, it's pretty clear that $\alpha$ is the only eigenvalue, so would the JCF simply be $\alpha I$? I'm getting a bit confused with the JCF since we traditionally start with an algebraically closed field and $\mathbb{Q}$ isn't. Would appreciate some help - I believe the intent is to proceed as if $C_p \in \mathbb{C}^{n\times n}$.
Would appreciate some help.
Comment: Jordan form over what field? Over $\mathbb{C}$? Since an irreducible polynomial over $\mathbb{Q}$ is squarefree, the minimal/characteristic polynomial of the companion matrix splits and is squarefree over $\mathbb{C}$, hence the Jordan form is diagonal and contains just the roots of $p(x)$. For a Jordan form, you only need the characteristic polynomial to split, so all you need is to be working onver the splitting field of $p(x)$.
Comment: A matrix $A$ has a Jordan form over the field $F$ (assuming $A$ is defined over $F$) if and only if the characteristic polynomial of $A$ splits over $F$. This happens for *any* matrix over $\mathbb{C}$, but you can always ask whether a particular matrix happens to have a Jordan form over any field. In this case, the least field over which there is a form is the splitting field.
Comment: Over $\mathbb{C}$. I stated this in the comment to @markvs answer, but basically I'm confused about the irreducibility in $\mathbb{Q}$ 'transferring' to $\mathbb{C}$. Is it not possible that $(x-\alpha)^2 | p$ in $\mathbb{C}[x]$ but $(x-\alpha)^2 \not \in \mathbb{Q}[x]$ retaining the irreducibility of $p$.
Comment: No, it's not possible. Irreducible polynomials over the rationals never have multiple roots. Look up "separability", or note that a polynomial has multiple roots in its splitting field if and only if $\gcd(p,p')\neq 1$ (where $p'$ is the formal derivative). Because $p$ is irreducible and $p'\neq 0$, $\gcd(p,p')=1$, so $p$ has no multiple root sin $\mathbb{C}$.
Answer: Since $p$ is irreducible every root  of it has multiplicity $1$. Hence the Jordan form is a diagonal matrix.
Comment: If $p$ has multiple complex root, then it has a common nontrivial divisor with its derivative, and so it is not irreducible over $\mathbb Q$..
Comment: I hope I'm not being silly here but $\alpha$ is complex, and $p$ was merely chosen as irreducible in $\mathbb{Q}[x]$. Is it not possible that $(x-\alpha)^2 | p$ in $\mathbb{C}[x]$ but $(x-\alpha)^2 \not \in \mathbb{Q}[x]$ retaining the irreducibility of $p$.


Chrome Dev Tools - Elements Panel - Context menu stopped working

Question: I have been using the Elements page to edit html. It was all working fine; right-click brings up the full context menu then I can edit the html.
Now when I right-click, I only get 'Services' (an OS X item).
This only occurs on the site I am editing. If I do the same thing on any other site, I am able to edit the html.
Any ideas why this would be or how to fix it?
Edit - It started working. All I did was switch between pages and keep closing and opening the dev tools. No idea what really fixed it.
Comment: I know you solved it on your end, but can you please verify if [@Benjamin's scenario](https://stackoverflow.com/a/71574207/12015105) applies to your Chrome installation as well? I just reported it as a workaround to the [Chromium project's issues](https://bugs.chromium.org/p/chromium/issues/detail?id=1331197#c4).
Answer: I had the same issue and was able to remove it by changing the scaling of the developer tools with CMD + "+" and CMD + "-". It seems as if the context menu is inaccessible below certain font sizes.
Comment: Indeed, the context menu depends on the DevTools zoom level, and its high enough value enables the menu.
Comment: Thanks for this. I had blamed and cursed the whole universe, uninstalled extensions and whatnot before I found this question. I [just reported the zoom level as being related to this problem in Chromium](https://bugs.chromium.org/p/chromium/issues/detail?id=1331197#c4) and linked this SO question.
Answer: Someone reported this issue once in the past, but it was not easy for them to replicate it. If you find out how you got the issue, consider commenting on the issue so that it gets re-opened. Otherwise, if it's just a fluke, then I guess leave it as that.


How to compare values in a list with a specific integer value?

Question: I have a function which returns say either [1], [1,2],[1,2,3] or [1,2,3,4].  I want to compare the values inside the list with some value( say 0.2).
Before this, I had just an integer value coming from my function not a list of values to compare with 0.2.`
# this function gives a list as mentioned previously
iou_value = oneObject.intersection_over_union(image,humanPos,belongings_bb)

if iou_value is not None and iou_value > 0.2:

How should I write the if condition in such a scenario to compare list values with 0.2?
Thanks
Comment: @Sociopath I just do not know how to write it in an if condition
Comment: Possible duplicate of [How to compare all items in a list with an integer without using for loop](https://stackoverflow.com/questions/9254897/how-to-compare-all-items-in-a-list-with-an-integer-without-using-for-loop)
Answer: Depends what exactly you want, but most likely list comprehension will help you:
compared_list = [1 for elem in iou_value if elem > 0.2 else 0]

Will give you 1 and 0 at corresponding indices
Edit: if you want to separate the elements based on the comparison:
geq = [elem for elem in iou_value if elem >= 0.2]
less = [elem for elem in iou_value if elem < 0.2]

Edit 2: if you want a simple loop with if-conditions:
for elem in iou_value:
    if elem >= 0.2:
        #do what you want if geq
    else:
        #do what you want if less

Comment: `[bool(elem > 0.2) for elem in iou_value]` is a compact way of writing it, and you can use `filter()` to separate the lists.
Answer: You can use any()
Ex:
a = [1,2,3,4]

if any(iou_value > 0.2 for iou_value in a):
    print("Yes")
else:
    print("No")

Answer: You need to loop through the list to compare each value, like this:
if iou_value is not None:
  for v in iou_value:
    if v > 0.2:
      print(f'{v} is greater than 0.2')

You may want to adjust your method so that instead of returning None, it returns an empty list [], this way you can also delete the if io_value is not None check.
Answer: A simple if condition with  would do this:
In [2090]: l = [1,2,3,4]

In [2091]: val = 0.2

In [2093]: for i in l:
      ...:     if i > val:
      ...:         print('{} is greater than {}'.format(i,val))
      ...:
1 is greater than 0.2
2 is greater than 0.2
3 is greater than 0.2
4 is greater than 0.2

OR use list comprehensions:
In [2096]: ['yes' for i in l if i > val]
Out[2096]: ['yes', 'yes', 'yes', 'yes']