Creating a small struct in C - have some errors

Question: #include "stdio.h"
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

struct Clicker {
    int toggle;
    int average;
};

int main()
{
    struct Clicker *clicker;
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n", clicker->toggle, clicker->average);
    getchar();
    return 1;
}

There is the code.
Errors:
'_getch' undefined, assuming extern returning int
'scanf_s' format string '%d' requires an argument of type 'int *' but variadic arguemnt 1 has type int.
uninitialized local variable 'clicker' used.

What am I doing wrong?
Comment: `_getch` is in `conio.h` which you didn't include
Comment: You have at least one mistake on almost every line of this program. Do you have an instructor, with whom you can go over it in person, line by line? Because that is going to be much faster and more effective than trying to explain it all to you here.
Comment: What's unclear about the compiler messages?
Comment: `(*clicker).toggle = _getch();` - You are using its value here - a value that you have not initialised
Comment: `clicker` - You have not initialised it!
Comment: @zwol I'm reading Head First C and I have to like try I guess. Nobody to help me out.
Comment: @EdHeal I thought you didn't have to since I don't have the variables?
Comment: I'm unfamiliar with this book, but based on what I see I suspect it is not a good book.
Comment: @zwol It was recommended to me. I'm learning.
Answer: You say you are trying to learn C by yourself, so I will actually explain all the mistakes in this program.
#include "stdio.h"

stdio.h should always be included using the <> form of #include. (The "" form is for headers that are part of your program, and the <> form is for headers that come from system-provided libraries.  In complex programs the distinction can get fuzzy, but don't worry about that right now.)
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

These three lines all do things that are Windows-specific and should be completely unnecessary in a program like this.  Remove them.
struct Clicker {
    int toggle;
    int average;
};

There is nothing wrong with this structure definition.
int main()

For historical reasons, you need to write int main(void).  This is mostly harmless, but writing empty function parameter lists in C is a bad habit to get into.
{
    struct Clicker *clicker;

Here's your most important mistake: you have declared a pointer to a struct Clicker, when what it appears you wanted was to declare a local variable using the structure.  Write struct Clicker clicker instead.
Pointers are one of the most difficult aspects of the language, especially for people new to programming.  If your book doesn't devote at least a full chapter to pointers and nothing else, it's a bad textbook and you need to get a better one.
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();

Consistent with the above change, write clicker.toggle = ... instead of (*clicker).toggle = since you no longer have a pointer.
Do not use the nonstandard function _getch(), use getchar() instead.  (There are programs that actually need to use _getch but this isn't one of them.)
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);

Here's a place where you have to deal with pointers.  All of the arguments to scanf, after the format string, must be pointers to variables, because that is what makes it possible for scanf to write to the variables.  clicker is no longer a pointer, but what you wrote would be wrong even if we hadn't made that change, because (*clicker).average isn't a pointer even when clicker is.  What you need to write is
    scanf("%d", &clicker.average);

The & operator is said to take the address of the variable clicker.average, producing the pointer that scanf needs.
Similarly to what I said above about _getch, never, ever use the nonstandard function scanf_s.  (All of the functions whose names end in _s come from a well-intentioned but disastrously ineffective attempt by Microsoft to paper over a bunch of design errors in the standard C library.  They don't exist on most operating systems, and they don't fix the problems they were intended to fix.  Don't use any of them.)
When you get more experience you will come to realize that scanf is more trouble than it's worth, but for a trivial program like this it's OK.
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n",
           clicker->toggle, clicker->average);

Unlike scanf, printf takes values, not pointers to variables, so this is right except that we have to change clicker->toggle to clicker.toggle and clicker->average to clicker.average because clicker is no longer a pointer.
In text to be printed, do not put spaces immediately before \n.
Even nowadays, code should be no more than 80 columns wide, because that way you can get two files of code side by side on your screen at once and still use a reasonable font size.  This is an absolutely vital thing to be able to do when you are working with a complex program.  (Also, really wide text is harder to read in general.)
    getchar();

It is bad style to put a call to getchar immediately before the end of the program.  When the program is done running it should just exit.  If your IDE refuses to keep the "console" window around after the program exits, get yourself a better IDE.
    return 1;

The program has not failed, so it should return 0, not 1.
Comment: Hi, I am very grateful for your help. I totally understand everything you have said - and it does actually match up with what I've been reading, which I'm glad about! I was reading about how when you pass a struct through parameters you merely create a copy, so you have to have a pointer instead in order to make changes to the original struct. Thank you very much.
Comment: You're welcome, but I urge you to find _someone_ you can talk to in person about the difference between `struct Clicker clicker;` and `struct Clicker *clicker;` until you have it completely clear in your head.
Comment: I'll look around for anyone in my area. thank you
Answer: use getchar() instead of _getch(). also, you don't need to include "stdafx.h". remove it.avoid including headers you don't need.
Answer: It seems like you have created this code by copying different solutions and snippets without a real understanding of its usage.
There might be reasons to use _getch() but if you don't now why you should probably use more standard solutions like getchar().
Please consider the following solution using standard methods:
#include <stdio.h>    // use <...> instead of "..."
#include <stdlib.h>    // for malloc()
// #include "stdafx.h"     // not necessary
// #define _CRT_SECURE_NO_WARNINGS // not necessary
// #define getch() _getch()    // not necessary

struct Clicker {
    int toggle;
    int average;
};

int main(){
    struct Clicker *clicker = malloc(sizeof(struct Clicker));
    printf("Enter your toggle key: ");
    // (*clicker).toggle = _getch();   // use scanf()
    scanf("%d",&clicker->toggle);
    printf("Enter your average cps: ");
    scanf("%d", &clicker->average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n",clicker->toggle, clicker->average);
    // getchar();  // not nessecary
    // return 1;   // 1 is usually an error exit code, use 0 instead
    return 0;
}

Another thing you don't seem to understand yet is the proper usage of scanf(). It receives a pointer (to an int in this case). Since you declared clicker as a pointer to your struct Clicker you need do dereference if to get access to its members toggle and average. You do this using clicker->toggle. Then you need a pointer to this dereferenceation which you get using &.
Comment: Uh, you didn't fix the most important bug - you're still reading and writing through an uninitialized pointer!
Comment: Yes, except that if you're going to call malloc you need to add `#include `.
Comment: Ups, you are totally right. Hope I've fixed it now.


Proof that a certain condition is equivalent to convergence of a real sequence

Question: Show that Definition $2.6$ is equivalent to the following slight modification:
We write $\lim_{n \to \infty} s_n = L$ provided that for every positive integer $m$ there is a real number $N$ so that $|s_n − L| <\frac 1 m$ whenever $n \ge N$.
Definition $2.6$ says: (Limit of a Sequence) Let $(s_n)_{n\in \Bbb{N}}$ be a sequence of real numbers. We say that $(s_n)_{n\in \Bbb{N}}$ converges to a number $L$ and write
$\lim_{n \to \infty} s_n = L$  or    $s_n \to L$ as $n \to \infty$
provided that for every number $\varepsilon > 0$ there is an integer $N$ so that
$|s_n − L| < \varepsilon$ whenever $n \ge N$.
What I have so far is: By choosing a $M$ that is very large so that $\frac 1 m$ is similar to $\varepsilon$.
$|s_n − L| <\frac 1 m $
then we have $L-\frac 1 m < s_n < L+\frac 1 m$.
And here is where I draw a blank. To show they are equivalant I set them equal to show epsilon equals $\frac 1 m$?
Answer: The real $N$ versus natural $N$ is a silly matter easily disposed of using the Archimedean property. I call it silly because it's only a slight convenience to allow it to be real, and doing so breaks the proper mental model. The $\epsilon$ vs. $1/n$ thing is much more productive to think about: it should lead you naturally the the concept of a "neighborhood base" (also called a local base, or a neighborhood basis, or a local basis, or a base for a neighborhood system, etc.), which is fairly important. It also leads to the notion of "first countable". So pay close attention to that aspect of it.
Answer: You have the right idea:
If a sequence converges by Def. 2.6, it converges by the modified definition just by taking $\epsilon=1/m$.
Now suppose a sequence converges to L by the modified definition.  To show that it converges to L by Def. 2.6, given an $\epsilon>0$, choose a positive integer $m$ with $m>\frac{1}{\epsilon}$, so then $1/m<\epsilon$.
Answer: to show that both, definition 2.6 and its modification, is equivalent, you have to show that any sequence which converges in the sense of 2.6 also converge in the sense of the modification and vice versa.
Let $(s_n)$ be a sequence converging to $L$ (assume first that this convergence is meant in the sense of 2.6). You have to show that for each $m\in\mathbb N$ there is a real number N such that $|s_n-L|<\frac{1}{m}$ whenever $n\geq N$. We know that 2.6 is true, that is, for each $\epsilon>0$ there is a natural number $N'$ such that $|s_n-L|<\epsilon$ whenever $n\geq N'$. Can you continue?


apache2 with mod_fcgid randomly hangs

Question: I have had this config running on ubuntu 11.10 for more than one year. I had to move the service to a larger server, so I made a complete copy of the os disk with clonezilla and restored it to the new server.
I upgraded the OS on the new server to 12.04. All other things are identical on both systems.
My problem is this:
Apache runs fine and is far from the maxclients limit. Suddenly, php5-cgi spawns more and more processes , they are all in state "working" , and apache can not server requests anymore. All apache requests turn into "W" state, and sit there, while new requests are coming, and eventually all requests build up to the maxclients setting. 1 minute later all fcgi processes suddenly turn their state to "ready" and all is back to normal.
During the time this happens, Apache does not server the website. It looks like fcgi simply hangs and stops responding. "top" shows nothing at all, everything looks fine, no processes in D state or anything. Apache error log says that fcgid can't apply process slot, when this happens. But I dont understand why suddenly this started. My only thought would be that something is broken during the upgrade from 11.10 to 12.04. But why is it doing it so randomly, regardless of usage, load, or anything else?
Will very much appreciate any help!
Having said all that, I want to ask if anyone is aware why did the config break?
Answer: While it might be fascinating to delve into exactly why this combination hangs in your precise situation, it's a pretty unusual situation (years old OS, cloned to a different machine and then distro upgraded) and it might not even be any of that history that is the problem.
A more pragmatic approach would be to install 12.04 from scratch and reinstall everything else you require to rule out the long and colourful history of your OS as the cause of the trouble.
This is where a configuration management system such as Puppet or CFEngine or SaltStack or any one of a dozen others earns its keep.

apache2 with mod_fcgid randomly hangs


What does the 8 sign mean?

Question:
What does the 8 then dotted line mean? Starting from measure 9. Change of octave? Up or down?
Also the dotted line ends with a down turn? It turns sharply perpendicularly down. Does it mean one octave down?
Does it apply to only treble clef or both clefs?
Comment: May I ask what the piece is?
Comment: It's from a czerny piano exercise book
Answer: In general, when there is an 8 and a dotted line above the treble clef, then you play the right hand an octave higher.
When there is an 8 and a dotted line below the bass clef, then you play the left hand an octave lower.
So in this case, you would play the right hand an octave higher until the sharp down line. This signifies the end of playing in a different octave.

What does the 8 sign mean?


Drupal 6 will not use updated htaccess 301 information

Question: I'm not 100% sure that this is a Drupal problem, but I think there is any issue with my site not flushing the cache. I am trying to change a redirect. I was having some trouble with URL Redirect in the CMS, so I am using the .htaccess file directly. Previously I had set up
redirect 301 /renew https://OLDREDIRECT.com
I just changed that to
redirect 301 /renew https://NEWREDIRECT.com
However, no matter what I do, the site keeps redirecting to the old link.
I have flushed the cache in Drupal, I've flushed my own browser cache, and I even tried running cron, but it will not use the new redirect info in .htaccess.
Does anyone have any idea what might be going on?
Thank you.
Comment: Are you editing the correct .htaccess only (the one present in the drupal root folder)?
Comment: Yep, I double checked. I even removed 2 backup .htaccess files that the original developer had in there (".htaccess 2", ".htaccessBACKUP"), and it didn't help.

Is it possible that my ExpiresDefault time needs to run out first? I would have though that flushing browser cache, etc., would force the browser to find the new redirect rules.
Answer: .htaccess shouldn't require any cache flushes, restarts of the server, etc. They should just take effect.
If you want to check to make sure that your editing the right file (and your not on a production server) you can always throw and invalid line in your .htaccess file. If it throws back a 500 error, your editing the right file and something is wrong somewhere in it, if it doesn't your're working on the wrong file.
Comment: Weird. Instead of using an invalid line, I added a test redirect, and it is working—with a catch. When I add
Redirect 301 /renew3443 http://DIFFERENT_DOMAIN.com
Then that link takes me to DIFFERENT_DOMAIN.com/?q=renew3443
I wasn't expecting the query to show up in the final URL. Is something wrong with my syntax?
Answer: Whoops, it turns out the problem was with my URL. I had retained a "++++++" instead of using "%2B%2B%2B%2B%2B%2B"
That fixed it.


Point-to-point network between three servers

Question: I have a three servers, each of which has two network ports. I want to connect these servers using point-to-point connections without using a switch.
Here is a diagram of what the physical connections look like:
   +---------+
   |  Node A |
   |    |eth0}-----+
   |         |     | +---------+
   |    |eth1}-+   | |  Node C |
   +---------+ |   +-{eth1|    |
               |     |         |
               |   +-{eth0|    |
               |   | +---------+
   +---------+ |   |
   |  Node B | |   |
   |    |eth0}-+   |
   |         |     |
   |    |eth1}-----+
   +---------+

I want the servers to be able to talk to each other. What I mean by this is:

The servers should be part of the same IP network, e.g. 10.10.10.0/24.
Each server should have an IP address, e.g. 10.10.10.1 for node A, 10.10.10.2 for node B and 10.10.10.3 for node C.
The IP packets should take different routes depending on their destination. For example, when on node A, packages with destination 10.10.10.2 (node B) should be routed through eth1 and packages with destination 10.10.10.3 (node C) should be routed through eth0.
(Edit: The following is not a strict requirement, but would be nice to have.) Broadcasts should be routed through both physical ports. Packets to all other addresses can be discarded.

Is it possible to create a network configuration that achieves this?
One idea I had was that I could create a virtual ethernet interface on each of the nodes and then add some routing rules. But I'm not completely sure if this is the right way. And I'm also not sure how to achieve the correct routing of broadcasts.
Another idea was that I could create a network bridge (consisting of both ports) on each of the servers and configure spanning-tree to make sure that only one bridge is active.
But I guess that a bridge is not necessary, because all nodes can be reached directly.
Any ideas and suggestions are welcome!
Edit:
Some background information: (This information is not necessary to solve the problem, but I want to describe the context of the problem and make a point why this is question is relevant for this forum.)
What I'm trying to achieve here is to set up a Ceph cluster consisting of three nodes. Each node is equipped with an Intel E810-CQDA2 NIC and two 100GBASE-SR4 transceivers. I use  OM4 fibres for the interconnection. This is a business setup, with hardware costs of more than 30k (without the NVMe SSDs).
The purpose of all this is to create a test system with Ceph, to see if Ceph could be a relevant technology we could use in the future. At this point in time I don't want to invest money into 100G switches, because of the high costs of such an investment (from what I've seen so far, it's not possible to buy good 100G switches for less then 10k, and you basically need two of them to avoid a single point of failure). If we roll out Ceph into production at some point in the future, we already have the appropriate data centers with the switch infrastructure in place. But as of now, this is only a test environment, and I want to keep it strictly separated from production.
Comment: Why you complicate so much the things? Add switch between all the servers and you are in the business.
Comment: @Romeo Ninov: Well, I think point-to-point connections shouldn't be considered as too complicated. If 100 Gbit switches were cheaper, I would buy two of them and then connect the three nodes using LACP bonding to the switches. But they are very expensive (and an overkill if you only want to connect three nodes).
Comment: Business environment != unlimited budget
Comment: Why the requirement to keep them on the same subnet? (using different subnets for each pair seems to offer more scope for exploiting the configuration)
Answer: Yes, it is. Create bond interfaces on each host which enslave both physical NICs, and use bonding mode 3 broadcast. Each server will transmit all the thaffic to both counterparts. Connect them into a "ring" (or "triangle"). Then simply assign addresses from the single network block to all servers.
ip link add name bond0 type bond mode broadcast
ip link set eth0 master bond0
ip link set eth1 master bond0
ip link set eth0 up
ip link set eth1 up
ip link set bond0 up
ip addr add 10.0.0.1/24 dev bond0

Repeat on all servers, using different IP addresses from the same subnet on each. Voila!
Example: we used this technique around 10 years ago to connect three Proxmox VE nodes to run CEPH network over 10 gigabit between them. 10gpbs switches were very expensive, but we had 2-port 10gbps cards in our disposal.
Comment: Thank you for your answer! I will try it within the next few days. My use-case is the same as yours: I also want to use it for Ceph on Proxmox VE, but with 100 Gbit ports. And 100 Gbit switches are really expensive.
Comment: This solution acually was borrowed from Proxmox forum or wiki of that time. I don't know if it's still available in original location. Also I must warn you: 100 gbps links are really 4x25 gbps. It might be possible you only get 25 gbps for each single data stream.
Comment: This is bullshit. You're confusing NIC teaming with a bandwidth split @ the physical level. In a nutshell: With 100 GbE you can use splitter cable to have 4x25GbE or 2x50GbE, but you'll have ONE 100 GbE uplink if you want pumping ALL the traffic!
Comment: https://www.optcore.net/understanding-100g-ethernet/
Comment: 4x25G lanes
Next, we will talk about SR4 / LR4. It is 4 lanes of 25 G each. More precisely because of the encoding overhead, it will be 4 x 25.78125 GHz. It also stripes packets to 64b / 66b blocks before sending all connections, including BIP8 error detection (Note: error detection is not correct). However there is a habit here, there are actually two different standards for 4 x 25 G connection. IEEE 802.3 ba and IEEE 802.3 bm.
Comment: Key point: packets (Ethernet frames) will travel using ALL the lanes. This IS different from trunk or team or whatever.


Detectando cores ou formas geométricas de uma imagem

Question: Existe alguma framework para detectar cores ou formas geométricas dentro de uma imagem estática, como por exemplo um .jpg? De preferência para C# ou java
Cenário hipotético:

A framework identificaria que existem 3 objetos na imagem acima, sabendo diferenciar qual a cor de cada um deles.
Comment: Achar as cores é mais fácil do que achar as formas. No entanto, o que quero saber é que tipo de imagens são esperadas como entradas válidas. Por exemplo, se eu pegar uma imagem da Mona Lisa, a fotografia de um urso panda, ou trocentas formas geométricas de cores diferentes sobrepostas uma por cima da outra, isso é válido? Ou você só está interessado em figuras aonde as cores dos objetos são simples e uniformes, os objetos não estão encostados ou sobrepostos e o fundo também tem uma cor simples e uniforme?
Comment: Existem algumas bibliotecas que permitem o processamento digital de imagens. Para Java há a [JAI (Java Advanced Imaging)](http://www.oracle.com/technetwork/java/javase/tech/jai-142803.html). Outra mais completa e popular é o [OpenCV](http://opencv.org/) (que pode ser usada em Python, C++ e Java, em C# com um *wrapper*). O OpenCV é muito bacana, e existem [vários exemplos](https://opencv-code.com/tutorials/count-and-segment-overlapping-objects-with-watershed-and-distance-transform/) interessantes de identificação e contagem de objetos.
Comment: Eis um *wrapper* de OpenCV para C#: http://www.emgu.com/wiki/index.php/Main_Page
Comment: Além disso, se você transformar a sua imagem original em uma imagem binária (preto e branco, usando um limiar simples como o usado no algorítmo sugerido pelo @Victor), você pode separar os objetos usando algoritmos como os sugeridos nessa outra pergunta: http://pt.stackoverflow.com/questions/6978/como-determinar-o-menor-n%C3%BAmero-de-pequenas-%C3%A1reas-para-renderizar/7003#7003
Comment: Só mais uma dica (hehehe): se os seus objetos forem mais complexos (como uma imagem da Mona Lisa ou fotografia de um Urso Panda, tal como sugerido pelo @Victor), talvez o ideal seja mesmo usar o OpenCV com o algoritmo Haar Cascade. O OpenCV já tem Cascades treinados para detectar faces, olhos, boca, nariz... mas eis um tutorial de como treinar o seu próprio detector: http://coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.html
Comment: Hmm, não sei se existe um framework para essa finalidade, mas não é difícil bolar um programa para fazer isso se as suas figuras forem todas semelhantes a esta daí. Você pode dar mais exemplos de imagens?
Comment: Quais são as formas geométricas possíveis? Retângulos, círculos e estrelas de 6 pontas estão na sua figura. O que mais pode aparecer? Triângulos? Elipses? Linhas? Corações? Manchas aleatórias irregulares?
Comment: Por não existir um padrão, preferia identificar por cor. Caso não for possível, limitaria apenas a algumas formas geométricas como círculo, retângulos...
Answer: Vê se isto daqui te serve. Feito com java 8. Os comentários explicando como funciona estão no código:
<code>import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;

/**
 * @author Victor
 */
public class SeparadorDeImagem {

    // Usado para diferenciar o fundo das outras cores.
    private static final int LIMIAR = 232;

    // Cores conhecidas.
    public static final int VERMELHO = 0xFF_FF_00_00;
    public static final int VERDE = 0xFF_00_FF_00;
    public static final int AZUL = 0xFF_00_00_FF;
    public static final int BRANCO = 0xFF_FF_FF_FF;
    public static final int PRETO = 0xFF_00_00_00;
    public static final int AMARELO = 0xFF_FF_FF_00;
    public static final int CIANO = 0xFF_00_FF_FF;
    public static final int LIMA = 0xFF_80_FF_00;
    public static final int MAGENTA = 0xFF_FF_00_FF;
    public static final int ROSA = 0xFF_FF_00_80;
    public static final int VIOLETA = 0xFF_C0_80_FF;
    public static final int MARROM = 0xFF_80_40_00;
    public static final int LARANJA = 0xFF_80_40_00;
    public static final int CINZA = 0xFF_80_80_80;

    // Dá nome as cores.
    public static final Map<Integer, String> CORES = new HashMap<>(20);
    static {
        CORES.put(VERMELHO, "vermelho");
        CORES.put(VERDE, "verde");
        CORES.put(AZUL, "azul");
        CORES.put(BRANCO, "branco");
        CORES.put(PRETO, "preto");
        CORES.put(AMARELO, "amarelo");
        CORES.put(CIANO, "ciano");
        CORES.put(LIMA, "verde-lima");
        CORES.put(MAGENTA, "magenta");
        CORES.put(ROSA, "rosa");
        CORES.put(VIOLETA, "violeta");
        CORES.put(MARROM, "marrom");
        CORES.put(LARANJA, "laranja");
        CORES.put(CINZA, "cinza");
    }

    // Isola a quantidade de vermelho existente em uma cor.
    private static int vermelho(int cor) {
        return (cor & 0xFF0000) >>> 16;
    }

    // Isola a quantidade de verde existente em uma cor.
    private static int verde(int cor) {
        return (cor & 0xFF00) >>> 8;
    }

    // Isola a quantidade de azul existente em uma cor.
    private static int azul(int cor) {
        return cor & 0xFF;
    }

    // Reduz a cor dada para uma da lista de cores conhecidas.
    private static int reduzirCor(int cor) {
        int r1 = vermelho(cor);
        int g1 = verde(cor);
        int b1 = azul(cor);
        int melhorCor = 0;
        int melhorDistancia = Integer.MAX_VALUE;
        for (int talvez : CORES.keySet()) {
            int r2 = vermelho(talvez);
            int g2 = verde(talvez);
            int b2 = azul(talvez);
            int r3 = Math.abs(r1 - r2);
            int g3 = Math.abs(g1 - g2);
            int b3 = Math.abs(b1 - b2);

            // Calcula o quadrado da distância pitagórica ponderada entre a cor do pixel e a cor conhecida.
            // Usa como ponderação 3 para o vermelho, 6 para o verde e 1 para o azul.
            int distancia = r3 * r3 * 3 + g3 * g3 * 6 + b3 * b3;
            if (distancia < melhorDistancia) {
                melhorDistancia = distancia;
                melhorCor = talvez;
            }
        }
        return melhorCor;
    }

    // Reduz as cores da imagem para as que estão na lista de cores conhecidas.
    private static BufferedImage reduzirCores(BufferedImage input) {
        BufferedImage bi = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_ARGB);
        for (int y = 0; y < input.getHeight(); y++) {
            for (int x = 0; x < input.getWidth(); x++) {
                int cor = reduzirCor(input.getRGB(x, y));
                bi.setRGB(x, y, cor);
            }
        }
        return bi;
    }

    // Monta um histograma das cores presentes em uma imagem.
    private static Map<Integer, Integer> histogramaDeCores(BufferedImage imagem) {
        Map<Integer, Integer> histograma = new HashMap<>(50);
        for (int y = 0; y < imagem.getHeight(); y++) {
            for (int x = 0; x < imagem.getWidth(); x++) {
                int cor = imagem.getRGB(x, y);
                histograma.merge(cor, 1, (a, b) -> a + b);
            }
        }
        return histograma;
    }

    // Obtém a cor predominante de um histograma de cores.
    private static int corMaisFrequente(Map<Integer, Integer> histograma) {
        return histograma.entrySet()
                .stream()
                .reduce((a, b) -> a.getValue() > b.getValue() ? a : b)
                .get().getKey();
    }

    // Reduz a imagem para apenas duas cores: preto e branco.
    // Considera branco tudo que tiver vermelho, verde e azul maior ou igual a LIMIAR e preto todo o resto.
    private static BufferedImage pretoEBranco(BufferedImage input) {
        BufferedImage bi = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_ARGB);
        for (int y = 0; y < input.getHeight(); y++) {
            for (int x = 0; x < input.getWidth(); x++) {
                int cor = input.getRGB(x, y);
                int substituta = vermelho(cor) > LIMIAR && verde(cor) > LIMIAR && azul(cor) > LIMIAR ? BRANCO : PRETO;
                bi.setRGB(x, y, substituta);
            }
        }
        return bi;
    }

    // Preenche toda a área contígua que tenha uma mesma cor na figura dada com a nova cor informada.
    // O preenchimento é feito a partir das coordenadas informadas.
    private static void floodFill(int x, int y, BufferedImage input, int novaCor) {
        int corAntiga = input.getRGB(x, y);
        if (novaCor == corAntiga) return;
        // Cria uma fila de pixels ininicialmente com o pixel da coordenada dada.
        Queue<Coordinate2D> c = new ArrayDeque<>(200);
        c.add(new Coordinate2D(input, x, y));

        // Percorre a fila até acabar, colocando nela os pixels vizinhos do pixel retirado, mas apenas se este
        // puder ser recolorido.
        while (!c.isEmpty()) {
            Coordinate2D p = c.poll();
            if (input.getRGB(p.x, p.y) != corAntiga) continue;
            input.setRGB(p.x, p.y, novaCor);
            c.addAll(Arrays.asList(p.plusX(), p.plusY(), p.minusX(), p.minusY()).stream().filter(e -> e != null).collect(Collectors.toList()));
        }
    }

    // Retorna uma lista descrevendo as figuras que estão em uma imagem.
    // Cada item da lista é a descrição de uma figura.
    public static List<String> descrever(BufferedImage input) {
        // Cria uma cópia da imagem em preto em branco, para separar o fundo (branco) dos objetos (preto).
        BufferedImage pb = pretoEBranco(input);

        // Procura os pixels pretos, e sempre que achar um, pinta a área toda com uma cor diferente.
        // Isso faz com que cada objeto seja recolorido com uma cor única - ou seja, a segmentação é realizada aqui.
        int cores = 0;
        for (int y = 0; y < pb.getHeight(); y++) {
            for (int x = 0; x < pb.getWidth(); x++) {
                int cor = pb.getRGB(x, y);
                if (cor == PRETO) {
                    cores++;
                    floodFill(x, y, pb, cores);
                }
            }
        }

        // Cria uma descrição de imagens, uma para cada segmento.
        List<String> descs = new ArrayList<>(cores);
        for (int i = 0; i < cores; i++) {

            // Calcula o retângulo mínimo para enquadrar o objeto.
            // Como o objeto foi recolorido com uma cor única, basta procurar por todos os pixels com esta cor, ignorando os demais.
            // Esta parte do algoritmo é bem ineficiente e deve existir coisa muito melhor.
            // Mas o importante é que funciona. Se quiser otimizar isso depois, fique a vontade.
            int maxX = 0, minX = pb.getWidth() - 1;
            int maxY = 0, minY = pb.getHeight() - 1;
            for (int y = 0; y < pb.getHeight(); y++) {
                for (int x = 0; x < pb.getWidth(); x++) {
                    int cor = pb.getRGB(x, y);
                    if (cor == i + 1) {
                        if (y > maxY) maxY = y;
                        if (y < minY) minY = y;
                        if (x > maxX) maxX = x;
                        if (x < minX) minX = x;
                    }
                }
            }

            // Copia os pixels da imagem, criando duas imagens.
            // Uma imagem tem a figura preta a ser identificada.
            // A outra contém os pixels da figura original para identificar a cor.
            // Em ambos os casos, usa a cor única da figura recolorizada para saber quais são os pixels que interessam.
            int w = maxX - minX + 1;
            int h = maxY - minY + 1;
            BufferedImage segmentoPb = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            BufferedImage segmentoCor = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            for (int y = 0; y < h; y++) {
                for (int x = 0; x < w; x++) {
                    int cor = pb.getRGB(minX + x, minY + y);
                    segmentoPb.setRGB(x, y, cor == i + 1 ? PRETO : BRANCO);
                    segmentoCor.setRGB(x, y, cor == i + 1 ? input.getRGB(minX + x, minY + y) : BRANCO);
                }
            }

            // Descobre a cor. Para isso, pega a imagem colorida, aproxima as cores para cores conhecidas,
            // e então descobre qual é a cor predominante, excluindo o branco do fundo.
            Map<Integer, Integer> hist = histogramaDeCores(reduzirCores(segmentoCor));
            hist.remove(BRANCO);
            int corDaImagem = corMaisFrequente(hist);
            String nomeCor = CORES.get(corDaImagem);

            // Descobre a figura. Para cada tipo de figura há uma função para determinar se a figura é o não do determinado tipo.
            String figura = retangulo(segmentoPb) ? "Retângulo"
                    : elipse(segmentoPb) ? "Elipse"
                    : "Figura irregular";
            descs.add(figura + " " + nomeCor);
        }
        return descs;
    }

    // Decide se a figura dada parece corresponder a um retângulo preto.
    private static boolean retangulo(BufferedImage imagem) {
        floodFill(imagem.getWidth() / 2, imagem.getHeight() / 2, imagem, PRETO);
        Map<Integer, Integer> histograma = histogramaDeCores(imagem);
        int preto = histograma.get(PRETO);
        return preto > imagem.getWidth() * imagem.getHeight() * 0.99;
    }

    // Decide se a figura dada parece corresponder a uma elipse preta.
    private static boolean elipse(BufferedImage imagem) {
        int cx = imagem.getWidth() / 2;
        int cy = imagem.getHeight() / 2;
        floodFill(cx, cy, imagem, PRETO);
        int certoDentro = 0, certoFora = 0, erradoDentro = 0, erradoFora = 0;
        for (int y = 0; y < imagem.getHeight(); y++) {
            for (int x = 0; x < imagem.getWidth(); x++) {
                double a = (x - cx) / (double) cx;
                double b = (y - cy) / (double) cy;
                boolean dentro = a * a + b * b <= 1;
                boolean preto = imagem.getRGB(x, y) == PRETO;
                if (preto && dentro) {
                    certoDentro++;
                } else if (preto && !dentro) {
                    erradoFora++;
                } else if (!preto && dentro) {
                    erradoDentro++;
                } else {
                    certoFora++;
                }
            }
        }
        return certoDentro + certoFora > 50 * (erradoDentro + erradoFora);
    }

    private static BufferedImage carregarImagem() throws IOException {
        try {
            return ImageIO.read(new URL("https://i.stack.imgur.com/69Wj9.jpg"));
        } catch (MalformedURLException e) {
            throw new AssertionError(e);
        }
    }

    public static void main(String[] args) throws IOException {
        System.out.println(descrever(carregarImagem()));
    }

    // Classe que representa um par de coordenadas x,y. A ser utilizado no algoritmo de floodfill.
    private static final class Coordinate2D {
        private final BufferedImage imagem;
        private final int x, y;

        public Coordinate2D(BufferedImage imagem, int x, int y) {
            Objects.requireNonNull(imagem);
            if (x < 0 || x >= imagem.getWidth() || y < 0 || y >= imagem.getHeight()) throw new IndexOutOfBoundsException();
            this.imagem = imagem;
            this.x = x;
            this.y = y;
        }

        @Override
        public int hashCode() {
            return Objects.hash(imagem, x, y);
        }

        @Override
        public boolean equals(Object another) {
            if (!(another instanceof Coordinate2D)) return false;
            Coordinate2D c4d = (Coordinate2D) another;
            return imagem == c4d.imagem && x == c4d.x && y == c4d.y;
        }

        public int squareDistance(Coordinate2D another) {
            Objects.requireNonNull(another);
            if (imagem != another.imagem) throw new IllegalArgumentException();
            int dx = Math.abs(x - another.x);
            int dy = Math.abs(y - another.y);
            return dx + dy;
        }

        public Coordinate2D minusX() { return x == 0                      ? null : new Coordinate2D(imagem, x - 1, y); };
        public Coordinate2D plusX()  { return x == imagem.getWidth()  - 1 ? null : new Coordinate2D(imagem, x + 1, y); };
        public Coordinate2D minusY() { return y == 0                      ? null : new Coordinate2D(imagem, x, y - 1); };
        public Coordinate2D plusY()  { return y == imagem.getHeight() - 1 ? null : new Coordinate2D(imagem, x, y + 1); };
        public BufferedImage getImage() { return imagem; }
    }
}
</code>
Ele carrega a imagem pegando a URL da figura que está na sua pergunta. Eis a saída do programa:
<code>[Retângulo amarelo, Elipse vermelho, Figura irregular verde-lima]
</code>
Acrescentar novas cores é algo que deve ser fácil. Reconhecer as figuras é mais difícil, atualmente ele reconhece retângulos e elipses apenas, e o que ele não reconhecer como nenhum dos dois ele diz "Figura irregular".
Além disso, ele assume que as figuras têm uma cor uniforme ou quase uniforme e não irão obscurecer ou se sobrepor umas as outras. Ele também assume que o fundo sempre é branco.
Se o que você precisa for algo mais refinado, me avise e vamos ver como melhorar o programa.


Desirable and undesirable properties of Latin squares in experiments?

Question: A cursory search reveals that Latin squares are fairly extensively used in the design of experiments.  During my PhD, I have studied various theoretical properties of Latin squares (from a combinatorics point-of-view), but do not have a deep understanding of what is it about Latin squares that make them particularly well-suited to experimental design.
I understand that Latin squares are good at allowing statisticians to efficiently study situations where there are two factors which vary in different "directions".  But, I'm also fairly confident there would be many other techniques that could be used.

What is it, in particular, about Latin squares that make them so well suited for the design of experiments, that other designs do not have?

Moreover, there are zillions of Latin squares to choose from, so which Latin square do you choose?  I understand that choosing one at random is important, but there would still be some Latin squares that would be less suited to running experiments than others (e.g. the Cayley table of a cyclic group).  This raises the following question.

Which properties of Latin squares are desirable and which properties of Latin squares are undesirable for experimental design?
Answer: Imagine:

you were interested in the effect of word type (nouns, adjectives, adverbs, and verbs) on recall.
you wanted to include word type as a within-subjects factor (i.e., all participants were exposed to all conditions)

Such a design would raise the issue of carry over effects. I.e., the order of the conditions may effect the dependent variable recall. For example, participants might get better at recalling words with practice. Thus, if the conditions were always presented in the same order, then the effect or order would be confounded with the effect of condition (i.e., word type).
Latin Squares is one of several strategies for dealing with order effects.
A Latin Squares design could involve assigning participants to one of four separate orderings (i.e., a between subjects condition called order):

nouns adjectives adverbs verbs
adjectives adverbs verbs nouns
adverbs verbs nouns adjectives
verbs nouns adjectives adverbs

Thus, the Latin Squares design only entails a subset of possible orderings, and to some extent the effect of order can be estimated.
In a blog post I suggest the following simple rules of thumb:

"If order is the focus of the analysis (e.g., skill acquisition looking at effects of practice), then don't worry about order effects
If order effects are very strong, it may be better to stick to between subjects designs
if order effects are small or moderate or unknown, typical design strategy depends on the number of levels of the within-subjects factor of interest.

If there are few levels (e.g., 2,3,4 perhaps), present all orders (counterbalance)
If there are more levels (e.g., 4+ perhaps), adopt a latin squares approach or randomise ordering"

To specifically answer your question, Latin Squares designs allow you to get the statistical power benefits of a within-subjects design while, potentially at least, minimising the main problem of within subjects designs: i.e., order effects.


What's the "normal" opposite of flautando?

Question: I'm writing a piece in which I need string instruments to switch regularly between flautando and normal timbre. How do I denote this? Basically, I need a word which means "normal" with regard to where the bow falls.
Answer: Normale (norm.) or ordinario (ord.) are the standard methods for marking a return to regular articulation after using an alternative technique.
Answer: In doubt, you can always negate a specific playing instruction by mentioning it with a non prefix. In this case I'd probably write non flaut., if in your context ord. would not be clear enough.
Alternatively you could consider what particular sonic quality of "normal bowing" you want to contrast against flautando. Should it be the robust sound and attack? You might alternate between flautando and pesante. You want the opposite of the sweet airiness of a flautando? You could alternate between sul tasto and sul ponticello. Etc. etc..
Answer: In such cases, the notation arco is typically given to request that the performers play with standard technique.
So just as you specify flautando for some portions, simply specify arco for the other portions.
Comment: This is not the standard notation method, though most performers would probably understand what you're trying to say.
Comment: I would stick with *ord*.   *Arco* is pretty much reserved for not-pizzicato,  and occasionally for  not-colLegno.
Comment: As a violin player I would say do *not* type *arco* when you are alreadu using the bow, *arco* is Italian for bow. The term *ord.* is the standard indicating a return to ordinary playing after playing a special effect.
Comment: @Peter (and Carl): Thanks for the information! I'm not a string player, so I always assumed *arco* simply meant "normal." Today I learned!


Getting serializable extras from Intent producing blank screen for few seconds

Question: I want to move from my Splash Screen Activity to Main Activity. In Splash Screen Activity, I'm fetching data from Firebase and store it in ArrayList. After that, I use extras to passing the data to my MainActivity. But, when the activity changes, it shows blank screen for around 3 seconds before the MainActivity started. When I remove my code for getting the bundle from the extras, the Intent works perfectly fine.
SplashActivity.java
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.putExtra("itemList", (Serializable) arrayList);
        startActivity(intent);
        finish();

MainActivity.java (I passed the bundle to fragments)
        bundle = getIntent().getExtras();
        HomeFragment homeFragment = new HomeFragment();
        homeFragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, homeFragment, "home").commit();

HomeFragment.java
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        arrayList = new ArrayList();
        arrayList = (List<ItemModel>) getArguments().getSerializable("itemList");

        return view;
    }

I wonder why would that happen. Is it possible that the data I'm passing are too big (I tried to pass and get the smaller data and it works fine) or something and how should I solve it? Any help will be appreciated, thanks!
Answer: Do not fetch data while creating views i,e: onCreateView(...)
Correct way:
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       return inflater.inflate(R.layout.fragment_home, container, false);
    }

override onViewCreated(...) and fetch data inside this method
 arrayList = new ArrayList();
        arrayList = (List<ItemModel>) getArguments().getSerializable("itemList");

Comment: Hi, thanks for the answer! But sadly, it doesn't work. I'm still getting the blank activity before the activity changes.


Picasso + RxJava2: Method call should happen from the main thread

Question: This was my initial Question:
I am trying to show a few images in the AutoScrollViewPager. I am using Picasso to achieve the same. However, I would like to do the same with using Rxjava2 + Picasso. I am kinda new to this RxJava concept. So if anyone can help me with details if possible, to convert the below into RxJava code, I would really appreciate it.
This is what I do in onViewCreated()
imageAdapter = new ImageAdapter(getActivity());
autoScrollViewPager.setAdapter(imageAdapter);
autoScrollViewPager.setCurrentItem(imageAdapter.getCount() - 1);
autoScrollViewPager.startAutoScroll();
autoScrollViewPager.setInterval(4000);

This is my ImageAdapter
ImageAdapter(Context context){
    this.context=context;
    mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return GalImages.length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) container.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.pager_item,null);
    ((ViewPager) container).addView(view);
    final ImageView img = (ImageView) view.findViewById(R.id.imageView);
    Picasso.with(context)
            .load(GalImages[position])
            .fit()
            .into(img);
    return view;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((RelativeLayout)object);
}

How can I convert this into RxJava code? Any help will be appreciated.
This is what I tried to do
I changed my ImageAdapter a bit:
@Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) container.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.pager_item,null);
    ((ViewPager) container).addView(view);
    img = (ImageView) view.findViewById(R.id.imageView);
    loadImagesWithPicasso(position)
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe();
    return view;
}

public Completable loadImagesWithPicasso(int position) {
   return Completable.fromAction(new Action() {
       @Override
       public void run() throws Exception {
           Picasso.with(context)
                  .load(GalImages[position])
                  .fit()
                  .into(new Target() {
                            @Override
                            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

                            }

                            @Override
                            public void onBitmapFailed(Drawable errorDrawable) {

                            }

                            @Override
                            public void onPrepareLoad(Drawable placeHolderDrawable) {
                                img.setImageDrawable(placeHolderDrawable);
                            }
                        });
       }
   });
}

But this, unfortunately, did not work and I ended up with this error:
java.lang.IllegalStateException: Method call should happen from the main thread.
at com.squareup.picasso.Utils.checkMain(Utils.java:136)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:496)
at com.kaaddevelopers.myprescriptor.ImageAdapter$1.run(ImageAdapter.java:79)
at io.reactivex.internal.operators.completable.CompletableFromAction.subscribeActual(CompletableFromAction.java:34)
at io.reactivex.Completable.subscribe(Completable.java:1613)
at io.reactivex.internal.operators.completable.CompletableSubscribeOn$SubscribeOnObserver.run(CompletableSubscribeOn.java:64)
at io.reactivex.Scheduler$1.run(Scheduler.java:134)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:59)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:51)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)

Any help will be appreciated. :)
Comment: What if you remove `.subscribeOn(Schedulers.newThread())`? The error says "Method call should happen from the main thread", but you tell your code to subscribe on a new thread. Or maybe `.subscribeOn(AndroidSchedulers.mainThread())`, which might be the same...
Answer: You are loading the image from the executor thread, which Picasso doesn't allow (this is pour choice if you ask me, there are better ways to deal with sync issues, but that's the way it is now).
You can see the details of this decision in this thread:

It was a mistake from Picasso to allow external callers to invoke into() other than the main thread. Those methods deal with view recycling and canceling without synchronization, hence in Picasso 2.3 we added the checks.

There are several options for you. You can do the whole instantiateItem work in the UI thread, if you pass Looper.getMainLooper() in, or you can use RequestCreator.get() method instead of RequestCreator.into(), or wrap your Picasso work with:
context.runOnUiThread(new Runnable() {
    @Override
    public void run() {
         // Can call RequestCreator.into here
    }
});

Comment: I ended up using get() instead of into() which gets the Bitmap back,


Which is the longest own-goal in football?

Question: In an recent International Champions Cup match between Chelsea and Inter Milan, Inter's Geoffrey Kondogbia scored 45-yard own goal.
Is this the longest own-goal ever scored?
Answer: There have been many 40-yard+ own-goals, in my pick two own-goals that are definitely longer than Inter's Geoffrey Kondogbia is Quevilly Rouen's player half the pitch own goal for Pau in 3rd French league and Bleacher Report article claiming 50-yard own-goal of Borussia Monchengladbach's Christoph Kramer
Video links: Christoph Kramer, Quevilly Rouen's player
Other long range own-goals: Joshua Rose, José Ángel


Marshal.StructureToPtr crashes Visual Studio

Question: I'm working on a custom debug engine and when I marshal my structure to a IntPtr Visual Studio crashes (the one being debugged not the debugger).
My struct is little more than:
public struct DocumentContext : IDebugDocumentContext2, IDebugCodeContext2
{
    private string _fileName;

    //.....Implementation of interfaces
}

My marshalling code looks like this:
        var documentContext = new DocumentContext(_node.FileName);
        var size = Marshal.SizeOf(documentContext);
        IntPtr ptrDocContext = Marshal.AllocHGlobal(size);
        //This is what is crashing
        //I don't have a chance to catch anything, it just craps out
        //Event log says faulting dll is nt.dll
        Marshal.StructureToPtr(documentContext, ptrDocContext, true);

Am I missing something?
Answer: You should not use deleteOld if the unmanaged structure was never previously allocated.  deleteOld is only applicable when you're overwriting a previous structure (so as to deallocate string references, for example.)  This should work:
Marshal.StructureToPtr(documentContext, ptrDocContext, false);

Comment: The disclaimer in the documentation is a bit subtle. It clearly points out that you may leak memory if you pass false, but only further down does it clarify that if the structure does not contain valid data, then passing true will fail.  Essentially it tries to free the memory pointed to by the string reference in the structure, but the pointer is invalid and, voila, a crash.


Looping through each "If statement" in a jQuery function

Question: I wrote four functions to check to see if the current date is before or after a specific date (date1, date2, date3, date4). Originally, I tried to write this in one function but it would break out of the function after the first "if" statement because it was true. In my coding example below, it would show the div with ID 19700101-p but not the div with ID 20180501-p (because as I understand it, since the current date was greater than date1, the "if" statement was true and there was no need to execute the "else if" statements after it.
For greater context, I have a page of 19 courses with registration buttons. My goal is to write a script that will automatically "disable" the registration button when the date has passed. Additionally it will show some additional information (i.e., "This class has passed, the next class will take place on xxx").
Is there a simpler way to write this function?
$(document).ready(function() {

  var current = new Date();
  var date1 = new Date("January 1, 1970")

  if (current.getTime() > date1.getTime()) {
    $('#19700101-f').hide();
    $('#19700101-p').show();
  }
  $('#currentDate').html(current);
  $('#date1').html(date1);
});

$(document).ready(function() {

  var current = new Date();
  var date2 = new Date("May 1, 2018")

  if (current.getTime() > date2.getTime()) {
    $('#20180501-f').hide();
    $('#20180501-p').show();
  }
  $('#date2').html(date2);
});

$(document).ready(function() {

  var current = new Date();
  var date3 = new Date("January 7, 2019")

  if (current.getTime() > date3.getTime()) {
    $('#20190107-f').hide();
    $('#20190107-p').show();
  }
  $('#date3').html(date3);
});

$(document).ready(function() {

  var current = new Date();
  var date4 = new Date("May 1, 2019")

  if (current.getTime() > date4.getTime()) {
    $('#20190501-f').hide();
    $('#20190501-p').show();
  }
  $('#date4').html(date4);
});

Answer: A couple things to address here:
1 - You never need multiple $(document).ready( ... ) events. Anything that needs to occur after the document has loaded can be put in one single $(document).ready( ... ).
2 - Given your naming convention, you could loop through each of the courses, split their ID on the -, and the first piece would be something like 20160501. We can turn this into an actual Date object, compare it to the current date, and determine if it's in the past dynamically.
This would mean you don't need to hard code anything, and that as long as you continue to add your courses with the same ID naming convention, this will continue to work.

//".course" selects all elements with class" course"
//.filter() reduces that selection to only those in the past

let $pastCourses = $(".course").filter(function() {
  let dateString = $(this).attr("id").split("-")[0], //"20140502"
      year = dateString.substr(0,4),                 //"2014"
      month = dateString.substr(4,2),                //"05"
      day = dateString.substr(6,2),                  //"02"
      date = new Date(year,month,day);               //Convert to Date

  return date < new Date();                          //Select only those in the past
});

$pastCourses
  .addClass("inactive")
  .append(" - This course has passed.");
.inactive { color: #ccc; }

 2014-05-02

 2015-01-11

 2020-12-24

I realize that in your original post, you're hiding the initial course and showing a replacement element, however I might suggest doing that in code instead of having two of each and every element.


What's it called when harmony moves in the same intervals as the melody?

Question: What's it called when the harmony moves in the exact same intervals as a melody, even if it is chromatic? Here's an example:

My apologies, I would do actual notation but I am not currently able to.
Is there a name for this movement of harmony with the same intervals as the melody?
Here is the music:
Comment: I'd call it parallel harmony. Many special cases exist. Like parallel fifths, diatonic parallel thirds, chromatic parallel thirds, parallel sixth chords - a technique known as _faux bourdon_ in certain styles, especially when diatonic.
Answer: In addition to "parallelism", or "parallel motion", the term "doubling" is also used. "Doubling" often means the same note, possibly in a different octave, so to be specific one would say a part is doubled at a certain interval. The given example would be "doubled at the third". This could be further specified as "major third" above or below according to which line is considered the melody and which the harmony.
Answer: I'm adding an answer just to add the other basic motion types. You might as well learn those too.
The intervallic relationship of two voices in motion can be called relative motion. That is, rather than describing motion as ascending or descending, it is described in terms of one voice relative to the other.
The broad categories are: contrary, oblique, and similar. Contrary motion is voices both moving in opposite directions. Oblique motion is one voice not moving while the other moves. Similar motion is both voices moving in the same direction.
Similar motion also has a specific sub-category: parallel motion. Parallel motion is when the two voices move in the same direction but maintain exactly the same interval of distance between the voices.
Parallel motion also means that the melodic intervals of the two melodies are exactly the same. You can think of the two voices as merely an exact transposition of one for the other.
You may have heard, or will eventually come across, the idea that parallel motion is prohibited in music. In "classical" common practice era harmony, and in the old contrapuntal style of harmony, melodic variety was prized. The exact duplication of melodic material that comes from parallel motion is the reason those styles considered it a problem and tried to avoid it. The prohibition does not necessarily apply in other styles of music.
Answer: I would go with the word "parallelism."  The term would definitely apply with identical chromatic intervals, and (non-authoritative) I think I would call it that with diatonic harmomies as well, e.g.,

C-E-G -> D-F-A

even though E to F is just a half step.
Answer: 'Doubled a major 3rd above' (or below).  To describe your example accurately we have to specify the exact interval, just 'a third above' could imply a diatonic 3rd.


(Dis)Prove $\forall x \in \mathbb{R}, \sqrt{x^2} = x$

Question: I'm in my discrete math class, and I'm being asked to prove or disprove:

$\forall x \in \mathbb{R}, \sqrt{x^2} = x$

I think that would be false because I know that when you square a negative number, the result is positive. HOWEVER the reason that I'm uncertain is because I learned in algebra that every positive real number has $2$ real square roots, one of those being negative, which would make the above statement true.
Comment: It is highly unlikely that $\sqrt{\cdot}$ is meant to be a multivalued function, but it could be in some contexts. Without knowing your context, it is hard to be sure.
Comment: By definition $\sqrt{x^2}=|x|$.
Comment: Try $x=-1$ to see why it fails
Comment: It is true algebrically that $(\pm 2)^2 =4$ but by definition the function $f(x)=\sqrt x\ge 0$ for any $x\ge 0$.
Answer: Since the square root always takes the positive root, we get that $\sqrt{x}\geq0$ so for negative numbers, the statement doesn't hold.
Since you want that there is only one function value for each input, we "make a choice" and define $\sqrt{x}$ as the positive square root of $x$.
Comment: So that means that I can just go with a basic counterproof to finish that off, and use a negative value for x. Thank you so much.
Answer: Every positive real number $y$ has two real numbers $r$ and $-r$, each of which squares to $y$, i.e. the equation
$$
x^2 = y
$$
has two solutions, namely $x = +r$ and $x = -r$.
However, the square root of $y$, written $\sqrt{y},$ is the output of a function which (by convention) is chosen to be the positive root. In other words,
$$
\sqrt{y} = x
\quad\iff\quad
y = x^2 \text{ and } x \geq 0.
$$


What happens if we override only hashCode() in a class and use it in a Set?

Question: This may not be the real world scenario but just curious to know what happens, below is the code.
I am creating a set of object of class UsingSet.
According to hashing concept in Java, when I first add object which contains "a", it will create a bucket with hashcode 97 and put the object inside it.
Again when it encounters an object with "a", it will call the overridden hashcode method in the class UsingSet and it will get hashcode 97 so what is next?
As I have not overridden equals method, the default implementation will return false. So where will be the Object with value "a" be kept, in the same bucket where the previous object with hashcode 97 kept? or will it create new bucket?
anybody know how it will be stored internally?
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

class UsingSet {

  String value;

  public UsingSet(String value){
    this.value = value;
  }

  public String toString() {
    return value;
  }

  public int hashCode() {
    int hash = value.hashCode();
    System.out.println("hashcode called" + hash);
    return hash;
  }

  public static void main(String args[]) {

    java.util.Set s = new java.util.HashSet();

    s.add(new UsingSet("A"));
    s.add(new UsingSet("b"));
    s.add(new UsingSet("a"));
    s.add(new UsingSet("b"));
    s.add(new UsingSet("a"));

    s.add(new Integer(1));
    s.add(new Integer(1));

    System.out.println("s = " + s);

  }
}

output is:
hashcode called65
hashcode called98
hashcode called97
hashcode called98
hashcode called97
s = [1, b, b, A, a, a]

Comment: Internally a `HashMap` is used to store the values of a `HashSet`. Also, there is a method `hash()` under `HashMap` which applies a supplemental hash function to defend against poor hashCodes.
Comment: Should be same bucket, you can check in debugger.
Comment: ans will be s = [A, a, a, 1, b, b]
Answer: HashCode & Equals methods

Only Override HashCode, Use the default Equals:
Only the references to the same object will return true. In other words, those objects you expected to be equal will not be equal by calling the equals method.
Only Override Equals, Use the default HashCode: There might be duplicates in the HashMap or HashSet. We write the equals method and expect{"abc", "ABC"} to be equals. However, when using a HashMap, they might appear in different buckets, thus the contains() method will not detect them each other.
Answer: James Large answer is incorrect, or rather misleading (and part incorrect as well). I will explain.
If two objects are equal according to their equals() method, they must also have the same hash code.
If two objects have the same hash code, they do NOT have to be equal too.
Here is the actual wording from the java.util.Object documentation:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

It is true, that if two objects don't have the same hash then they are not equal. However, hashing is not a way to check equality - so it is wildly incorrect to say that it is a faster way to check equality.
Also, it is also wildly incorrect to say the hashCode function is an efficient way to do anything. This is all up to implementation, but the default implementation for hashCode of a string is very inefficient as the String gets large. It will perform a calculation based on each char of the String, so if you are using large Strings as keys, then this becomes very inefficient; moreso if you have a large number of buckets.
In a Map (HashSet uses a HashMap internally), there are buckets and in each bucket is a linked list. Java uses the hashCode() function to find out which bucket it belongs in (it actually will modify the hash, depending on how many buckets exist). Since two objects may share the same hash, it will iterate through the linked list sequentially next, checking the equals() method to see if the object is a duplicate. Per the java.util.Set documenation:

A collection that contains no duplicate elements.

So, if its hashCode() leads it to a bucket, in which that bucket contains an Object where the .equals() evaluates to true, then the previous Object is overwritten with the new Object. You can probably view here for more information:
How does a Java HashMap handle different objects with the same hash code?
Generally speaking though, it is good practice that if you overwrite the hashCode function, you also overwrite the equals function (if I'm not mistaken, this breaks the contract if you choose not to).
Comment: Well as I said, each bucket is a linked list. The hashCode is truncated with respect to the number of buckets to make it more efficient in conjunction to the number of elements stored. That means the smaller the number of elements stored, the more likely you will receive a collision. When the map find the bucket belonging to a hash it will iterate through each element in the linked list. If it gets to the end of the linked list and there are no matching elements, it will put the new element at the end. If the map reaches its load factor, then it refactors the entire map and increases the
Comment: You have mentioned that "if its hashCode() leads it to a bucket, in which that bucket contains an Object where the .equals() evaluates to true, then the previous Object is overwritten with the new Object". But i want to know, what will happen "if its hashCode() leads it to a bucket, in which that bucket contains an Object where the .equals() evaluates to (false)". I want to know how the two objects will be stored in the same bucket internally?
Comment: number of buckets. This is a little off topic, but the load factor is by default 75%. Also, off topic again, this is why you want to set an initial capacity that is reflected with the number of total elements you think will be in the map, because it gets increasingly expensive to refactor the map as the number of elements stored gets larger and larger. You want to set the initial capacity just over the maximum number of elements you think will be stored to alleviate this cost later on.
Comment: Re, "hashing is not a way to check equality...":  You can save a lot of time by comparing hash codes before calling .equals().  That's exactly what HashMap.get(k) does in OpenJDK 7 (Look up the source code.)  It always compares hash codes first, and if the hash codes of the given key and the key in the table are not equal, then it will not bother to call the .equals() method.  That saves a lot of time, especially for immutable objects (e.g., Strings) that only compute their own hash code once, and then just return the same value on subsequent .hashCode() call.
Comment: Re "the default implementation for hashCode of a string is very inefficient", The first call to String.hashCode() computes a hash code based on every character of the string.  And then it _saves_ it.  Each subsequent call to s.hashCode() simply returns the saved value.  For a String that is used as a HashMap key, the hashCode() method may be called many times.  Of course, the _other_ string might be a new string each time, but computing the hash code (i.e., fetching the bytes from) one string still is cheaper than fetching the bytes from two strings in order to compare them.
Comment: Re "[HashMap] uses the hashCode() function to find out which bucket [the key] belongs in [...then] it will iterate through the linked list sequentially next, checking the equals() method":  Actually, It will compare hashCodes before it calls equals(), and it won't call equals() if the hash codes don't match.  This makes sense because two keys in the same bucket may have different hash codes.  There are 2^32 possible hash codes, but any given HashMap probably has a much smaller number of buckets.
Comment: @ArunRaaj The first snippet I copied and pasted was right from the `java.lang.Object` documentation which dictates the contract.
Answer: Simply you can  Assume hashcode and equals methods as a 2D search like:-
Where Hashcode is the Rows and the object list is the Column.
Consider the following class structure.
public class obj
  {
    int Id;
    String name;
    public obj(String name,int id)
     {
         this.id=id;
         this.name=name;
     }
  }

now if you create the objects like this:-
obj obj1=new obj("Hassu",1);
obj obj2=new obj("Hoor",2);
obj obj3=new obj("Heniel",3);
obj obj4=new obj("Hameed",4);
obj obj5=new obj("Hassu",1);

and you place this objects in map like this :-
    HashMap hMap=new HashMap();
   1. hMap.put(obj1,"value1");
   2. hMap.put(obj2,"value2");
   3. hMap.put(obj3,"value3");
   4. hMap.put(obj4,"value4");
   5. hMap.put(obj5,"value5");

now if you have not override the hashcode and equals then after putting all the objects till line 5 if you put obj5 in the map as By Default HashCode you get different hashCode so the row(Bucket will be different).
So in runtime memory it will be stored like this.
|hashcode   | Objects
|-----------| ---------
|000562     | obj1
|000552     | obj2
|000588     | obj3
|000546     | obj4
|000501     | obj5

Now if you create the same object Like :-
obj obj6 = new obj("hassu",1);
And if you search for this value in the map.like
if(hMap.conaints(obj6))
or
hMpa.get(obj 6);

though the key(obj1) with the same content is available you will get false and null respectively.
Now if you override only equals method.
and perform the same content search key will also get the Null as the HashCode for obj6 is different and in that hashcode you wont find any key.
Now if you override only hashCode method.
You will get the same bucket (HashCode row) but the content cant be checked and it will take the reference checked implementation by Super Object Class.
SO here if you search for the key hMap.get(obj6) you will get the correct hashcode:- 000562 but as the reference for both obj1 and obj6 is different you will get null.
Answer: Without looking at your code...
The whole point of hash codes is to speed up the process of testing two objects for equality.  It can be costly to test whether two large, complex objects are equal, but it is trivially easy to compare their hash codes, and hash codes can be pre-computed.
The rule is:  If two objects don't have the same hash code, that means they are not equal.  No need to do the expensive equality test.
So, the answer to the question in your title:  If you define an equals() method that says object A is equal to object B, and you define a hashCode() method that says object A is not equal to object B (i.e., it says they have different hash codes), and then you hand those two objects to some library that cares whether they are equal or not (e.g., if you put them in a hash table), then the behavior of the library is going to be undefined (i.e., probably wrong).

Added information:  Wow!  I really missed seeing the forest for the trees here---thinking about the purpose of hashCode() without putting it in the context of HashMap.  If m is a Map with N entries, and k is a key; what is the purpose of calling m.get(k)?  The purpose, obviously, is to search the map for an entry whose key is equal to k.
What if hash codes and hash maps had not been invented?  Well the best you could do, assuming that the keys have a natural, total order, is to search a TreeMap, comparing the given key for equality with O(log(N)) other keys.  In the worst case, where the keys have no order, you would have to compare the given key for equality with every key in the map until you either find a match or tested them all.  In other words, the complexity of m.get(k) would be O(N).
When m is a HashMap, the complexity of m.get(k) is O(1), whether the keys can be ordered or not.
So, I messed up by saying that the point of hash codes was to speed up the process of testing two objects for equality.  It's really about testing an object for equality with a whole collection of other objects.  That's where comparing hash codes doesn't just help a little; It helps by orders of magnitude...
...If the k.hashCode() and k.equals(o) methods obey the rule:  j.hashCode()!=k.hashCode() implies !j.equals(k).
Comment: I recommend revising your answer or removing it. Most of what you said is wrong, if not all of what you said. EDIT: yes, all of what you said is wrong.
Comment: @searchengine27, OK, so you're saying that it's never costly to compare large, complex objects for equality, that it's always hard to compare hash codes, and that it's never possible/useful for an object to cache its hash code after computing it once.  You are saying that it's OK for two objects that have different hash codes to test as equal, and that if you put objects like that into a HashTable, the HashTable will do something predictable and useful with them.  Or, I guess, maybe, "all of what you said is wrong" could have some new meaning that I haven't heard about yet.
Comment: read my answer I posted. I wanted to address *some* things you mentioned in my answer, but I inadvertently addressed everything wrong about your answer in my answer. The summation is: you need to read the documentation. As far as comparing equality of a string, it will compare each char in the string which is a single operation per char. The hashCode will perform "h = 31*h + val[off++];" (which is 5 operations) on each char. That means, hashCode is ALWAYS 5 times more expensive than the equals. This is irrelevant anyway, because the documentation doesn't say that equal hashCodes mean equality.
Comment: I just looked up the source code for String.hashCode() in OpenJDK 7.  The first time you call it, it does what you said, but then it also saves the hash value in an instance variable.  On each subsequent call, it just returns the saved value.  Trivial.  Oh, and I did not say that equal hashCodes are supposed to imply equality: I said that _unequal_ hash codes are supposed to imply _non_ equality.
Comment: @searchengine27 re "5 operations".  The way you're counting, String.equals() does not do _one_ operation per character.  It does five:  It fetches one char from each array, it increments two indices, and it compares the chars.  But "operations" is not the right thing to count:  Fetches cost a lot more than adds, increments, and multiplications.  What you _should_ be pointing out is that `s.hashCode()` has to examine the _whole string_, but `s.equals(t)` stops as soon as it finds a difference (e.g., it will fetch only one char from each string if the first chars are different)
Answer: Set will behave differently.
Uniqueness wont happen. Because unique will be achieved by both hashcode and equals methods.
output will be liked this s = [A, a, b, 1] instead of early one.
Apart that remove and contains all wont work.


How to minify Javascript in D7

Question: I'm on rackspace's cloud sites service, so I can't modify my server environment. I'm also running Drupal 7. I've spent the last couple days looking for a way to minify JS in Drupal 7 and it is my conclusion that one does not exist yet. Am I wrong? Or do I need to wait for a D7 release of http://drupal.org/project/advagg?
Comment: possible duplicate of [What is the best way to minify drupal's aggregated javascript (automatically)?](http://drupal.stackexchange.com/questions/484/what-is-the-best-way-to-minify-drupals-aggregated-javascript-automatically)
Answer:
List of modules in D7 that might provide similar functionality.
http://drupal.org/project/core_library
http://drupal.org/project/agrcache

It is what reported in the project page for Advanced CSS/JS Aggregation, which is where your link takes to.
Comment: Core Library 1.x looks like it will do it, but it only serves static JS files. I've also had some minor problems with it in the past. Any other suggestions?
Answer: You can use Minify module to do the same. Minify module minify the JavaScript using Google compiler. It also works with "Aggregate JavaScript files" so you can also get advantage of combining multiple JavaScript files which is default option in Drupal 7.
Minify module also minify HTML.

How to minify Javascript in D7


Facebook graph api search results depends on location?

Question: I've tried to fetch results using Graph search API and I've notice that the results when executed in my computer (Argentina) are different from the results when I run it in a server (France).
Is this like this? How can I force a location for a search?
Comment: I also met this problem. start a bounty. Thanks.
Answer: Thanks @Sascha Galley. I also find another easy way.
Just add  &locale=en_US  in Facebook Graph search API query URL.
This is languages and locales list refrence
Answer: I don't know exactly which results are different and which skd version you are using, but one possible approach is to send the accept-language header with the cURL request. In the facebook api php file add the following line in the function makeRequest() below $opts = self::$CURL_OPTS;
$opts[CURLOPT_HTTPHEADER] = array('Accept-Language: en-us,en;');

This post is almost two years old: Get Facebook Graph API results in English
Actually, this issue should have already been solved: Return values from the graph-api depend on geographic server location
Comment: As u'r the first and right answer, give u the bounty. Thanks.


Update com o select concatenado entre duas colunas da mesma tabela mysql

Question: Eu estou tentando executar uma query em que eu vou concatenar duas colunas do mysql nome e sobrenome, e realizar o update desta concatenação na variável nome completo em todos os registros da tabela.
Segue o código:
UPDATE eskalera.curriculum
SET
nomecompleto = (

SELECT CONCAT(nome, ' ', sobrenome)

from eskalera.curriculum
)

Comment: @IngridFarabulini justamente a minha dúvida porque a query é para todos os registros como seria o correto para resolver o problema?
Comment: Está faltando um WHERE aí, não?
Answer: A maneira comum é usar o UPDATE:
UPDATE eskalera.curriculum SET nomecompleto = CONCAT(nome,' ',sobrenome);

Assim essa query será capaz de fazer a alteração em todos os registros da tabela em uma única transação. Mas para isso é necessário estar com a proteção contra atualizações indesejadas em toda a tabela desabilitada:
SET SQL_SAFE_UPDATES=0;

Então teríamos:
SET SQL_SAFE_UPDATES=0;
UPDATE eskalera.curriculum SET nomecompleto = CONCAT(nome,' ',sobrenome);

Ao terminar, seria interessante voltar a ativar a proteção:
SET SQL_SAFE_UPDATES=1;

Assim a proteção contra atualizações não desejadas de uma só vez em toda a tabela é reativada.
Comment: Obrigado é isto mesmo, agradeço pela resposta deu certo!


Is There a "Predefined Exception" for Handling ArrayOutOfBounds Indexing Errors in PHP?

Question: With this divideByZero() function, It errors out and triggers the catch method:

function divideByZero() {
    return 1/0;
};

try {
  divideByZero();
  echo "i dont run";
} catch ( DivisionByZeroError $err) {
  echo $err;  //"DivisionByZeroError: Division by zero in C"
}

Which is exactly what I want, but I can only get this message by using PHP's DivisionByZeroError "Predefined Exception".
Now, I am wondering how I can get this same functionality with this arrayOutOfBounds() function:

function arrayOutOfBounds() {
   $arr = ["", "", ""];
   return $arr[3]; //index doesnt exist.
};

try {
 arrayOutOfBounds();
 echo "I still run, even though the arrayOutOfBounds function has a problem";
} catch (Error $err) { // <-- is the issue here?
  echo $err; //I dont run.
};

With the second arrayOutOfBounds() function, It doesn't catch the error, It completes the rest of the code in the try block, but also automatically echo's "Warning: Undefined array key 3 in C:\Users on line #".
I would simply like for this arrayOutOfBounds() function to catch the index error, not run the rest of the code in the try block, and echo the correct $err message.
I've looked through the documentation and tried them all.
Comment: You can not catch an exception, when none gets thrown to begin with. Accessing a non-existing array element simply doesn't.
Comment: @CBroe Thank you for correcting my misunderstanding, is there a way I can check if this is an indexing error within the `arrayOutOfBounds()` function, and throw an error that will catch in the try block?
Comment: I am currently reading into this exception: https://www.php.net/manual/en/class.outofboundsexception.php
Comment: It might be that some of the other SPL functions/classes throw that kind of exception, but just simple array access doesn't. All the examples in the comments on that page are _actively_ throwing an exception of this type themselves.
Comment: @CBroe Yeah, I guess I will have to throw it manually. Ill post my solution, but I'm still open to an automatic solution.
Answer: I'm not sure if there's a better way to do this, but here is a manual solution. The error is not automatically generated such as in the divideByZero() function, so I threw an error manually.

function arrayOutOfBounds() {
  $arr = ["", "", ""];
  if (isset($arr[3])) {} else {
    throw new OutOfBoundsException("Index was outside the bounds of the array.");
  }
};

try {
  arrayOutOfBounds();
  echo "test"; //i dont run anymore
} catch (OutOfBoundsException $err) {
  echo $err; //i echo the $err message
};
Comment: `if ($arr[3])` will still create an `Undefined array key`/`Undefined offset` warning/notice, if you wanted to prevent that from showing as well, you should test if the element exists using `isset`.