Overlapping background Graphics in a Memory Game Applet

Question: Okay I have been working on this memory game applet in java for a while now and I have all the sorting and matching algorithms all figured out, I am just having a wretched time trying to get my GUI to function properly.  Whenever I click on one of the "cards" to "flip", I end up with a column of the cards being created while their backs counterparts remain under the cards until you go over it with the cursor.  It is all very frustrating as I am not quite sure why half of this is happening or how to stop it.  Here is my Display class:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.*;

public class Display extends JPanel implements MouseListener {

private String[] Colors = Card.validColors();
private String[] Shapes = Card.validShapes();
private Component[] place;
private JButton[][] buttonGrid= new JButton[6][6];
private Rectangle[][] triggers = new Rectangle[6][6];
private Board game;
private Polygon star = new Polygon();
private Card pick;
private boolean turnPhase2 = false;
private Font serifNames = new Font(Font.SERIF, Font.PLAIN, 18);
private Font serifCards = new Font(Font.SERIF, Font.ROMAN_BASELINE, 36);
private JPanel panel = new JPanel();

public Display() {
    this.setBackground(Color.BLACK);
    this.setLayout(new GridBagLayout());
    panel.setSize(590, 410);
    panel.setLayout(new GridLayout(6, 6, 10, 10));
    panel.setOpaque(false);

    generateStar();
    buildBoard();
    fillButtonArray();

    this.addMouseListener(this);
    this.add(panel);
    System.out.println(getFontMetrics(serifCards));
    System.out.println(getFontMetrics(serifNames));
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    place = panel.getComponents();
    for (int i = 0; i < place.length; i++) {
        paintBack(g, place[i].getX() + 25, place[i].getY() + 35);
    }
    displayNames(g);
    displayTurn(g);
    if (game.flippedCard() != null) {
        int[] xy = game.flippedCardLocation();
        paintCard(g, game.flippedCard(), xy[0], xy[1]);
    }
}

/**
 * This method builds the game board.
 *
 *
 */
private void buildBoard() {
    game = new Board(buildDeck());
}

/**
 * This method creates a "deck" of cards with which we can create the game board.
 *
 * @return deck Returns the deck of Card objects in the form of an ArrayList.
 */
private ArrayList<Card> buildDeck() {
    ArrayList<Card> deck = new ArrayList<Card>();

    for (int i = 0; i < Colors.length; i++) {
        for (int s = 0; s < Shapes.length; s++) {
            Card first = new Card(Shapes[s], Colors[i]);
            Card second = new Card(Shapes[s], Colors[i]);
            deck.add(first);
            deck.add(second);
        }
    }
    System.out.println(deck.size());
    return deck;
}

private void fillButtonArray() {
    for (int i = 0; i < 6; i++) {
        for (int n = 0; n < 6; n++) {
            JButton button = new JButton();
            button.setPreferredSize(new Dimension(90, 60));
            button.addMouseListener(this);
            button.setOpaque(false);
            button.setContentAreaFilled(false);
            button.setBorderPainted(false);

            buttonGrid[i][n] = button;
        }
    }
    fillGrid();
}

private void fillGrid() {
    panel.setBounds(25, 35, panel.getSize().width, panel.getSize().height);
    int count = 0;
    for (int i = 0; i < 6; i++) {
        for (int s = 0; s < 6; s++) {
            panel.add(buttonGrid[i][s]);
            place = panel.getComponents();
            int x = panel.getComponent(count).getBounds().x;
            int y = panel.getComponent(count).getBounds().y;
            Rectangle rect = new Rectangle(x, y, 90, 60);
            triggers[i][s] = rect;
        }
    }

}

private void paintBack(Graphics g, int x, int y) {
    g.setColor(Color.WHITE);
    g.drawRoundRect(x, y, 90, 60, 2, 4);
    g.fillRoundRect(x, y, 90, 60, 2, 4);
    g.setColor(Color.BLACK);
    g.setFont(serifCards);
    g.drawString("M", x + 28, y + 42);
}

private void paintCard(Graphics g, Card card, int x, int y) {
    g.setColor(Color.GRAY);
    g.drawRoundRect(x, y, 90, 60, 2, 4);
    g.fillRoundRect(x, y, 90, 60, 2, 4);
    String color = card.getColor();
    String shape = card.getShape();

    if (shape.equals("Star")) {
        g.setColor(pickColor(color));
        star.translate(x + 25, y + 10);
        g.drawPolygon(star);
        g.fillPolygon(star);

    }
    else if (shape.equals("Circle")) {
        g.setColor(pickColor(color));
        g.drawOval(x + 25, y + 10, 40, 40);
        g.fillOval(x + 25, y + 10, 40, 40);
    }
    else if (shape.equals("Square")) {
        g.setColor(pickColor(color));
        g.drawRect(x + 25, y + 10, 40, 40);
        g.fillRect(x + 25, y + 10, 40, 40);
    }
}

private void displayNames(Graphics g) {
    g.setFont(serifNames);
    int[] scores = game.getCurrentScores();

    for (int i = 0; i < scores.length; i++) {
        if (i == 0) {
            g.setColor(Color.CYAN);
            g.drawString("Cyan: " + scores[i], 10, 24);
        }
        else if (i == 1) {
            g.setColor(Color.ORANGE);
            g.drawString("Orange: " + scores[i], 560, 24);
        }
        else if (i == 2) {
            g.setColor(Color.MAGENTA);
            g.drawString("Magenta: " + scores[i], 10, 470);
        }
        else {
            g.setColor(Color.WHITE);
            g.drawString("White: " + scores[i], 569, 470);
        }
    }
}

private void displayTurn(Graphics g) {
    int player = game.getCurrentPlayer();

    if (player == 0) {
        g.setColor(Color.CYAN);
        String str = "Cyan's Turn";
        g.drawString(str, 640 / 2 - 48, 24);
        //System.out.println(getFontMetrics(serifNames).stringWidth(str) / 2 + " Cyan");
    }
    else if (player == 1) {
        g.setColor(Color.ORANGE);
        String str = "Orange's Turn";
        g.drawString(str, 640 / 2 - 52, 24);
        //System.out.println(getFontMetrics(serifNames).stringWidth(str) / 2 + " Orange");
    }
    else if (player == 2) {
        g.setColor(Color.MAGENTA);
        String str = "Magenta's Turn";
        g.drawString(str, 640 / 2 - 57, 24);
        //System.out.println(getFontMetrics(serifNames).stringWidth(str) / 2 + " Magenta");
    }
    else {
        g.setColor(Color.WHITE);
        String str = "White's Turn";
        g.drawString(str, 640 / 2 - 47, 24);
        //System.out.println(getFontMetrics(serifNames).stringWidth(str) / 2 + " White");
    }
}

private void findTrigger(int x, int y) {
    for (int i = 0; i < 6; i++) {
        if () {

        }
        for (int s = 0; s < 6; s++) {
            Rectangle rectTest = triggers[i][s];
            if (x >= rectTest.getMinX() &&
                    x <= rectTest.getMaxX() &&
                    y >= rectTest.getMinY() &&
                    y <= rectTest.getMaxY()) {
                Graphics g = getGraphics();
                paintCard(g, game.flip(i,s), buttonGrid[i][s].getBounds().x, buttonGrid[i][s].getBounds().y);
                break;
            }
        }
    }
}

private void generateStar() {
    star.addPoint(20, 0);
    star.addPoint(25, 15);
    star.addPoint(40, 15);
    star.addPoint(28, 24);
    star.addPoint(32, 40);
    star.addPoint(20, 30);
    star.addPoint(8, 40);
    star.addPoint(12, 24);
    star.addPoint(0, 15);
    star.addPoint(15, 15);
}

private Color pickColor(String color) {
    if (color.equals("Black")) {
        return Color.BLACK;
    }
    if (color.equals("Yellow")) {
        return Color.YELLOW;
    }
    if (color.equals("Green")) {
        return Color.GREEN;
    }
    if (color.equals("Blue")) {
        return Color.BLUE;
    }
    if (color.equals("Red")) {
        return Color.RED;
    }
    if (color.equals("Purple")) {
        return new Color(128, 0, 255);
    }
    return null;
}

@Override
public void mouseClicked(MouseEvent e) {
    System.out.println("Mouse Clicked");
    int x = e.getX();
    System.out.println(x + " is x");
    int y = e.getY();
    System.out.println(y + " is Y");
    System.out.println(panel.getWidth() + 25);
    System.out.println(panel.getHeight() + 35);

    System.out.println("Finding the trigger rectangle");
    findTrigger(x, y);
}

@Override
public void mouseEntered(MouseEvent e) {
    //System.out.println("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
    //System.out.println("Mouse Exited");
}

@Override
public void mousePressed(MouseEvent e) {
    System.out.println("Mouse Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
    System.out.println("Mouse Released");
}

}
Some side notes is that the actual game is handled by the board object and has all the methods needed to create and run a multiplayer memory game and the Card object only contains two strings of the shape and color of what is to be matched by the game.  And finally the last class is the Memory class which I will provide:
import java.awt.Color;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JApplet;

public class Memory extends JApplet {
private Display _theDisplay;
final int width = 640;
final int height = 480;

private Action reDraw = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
};

public Memory() {
    _theDisplay = new Display();
}

public void init() {
    setSize(width, height);
    setBackground(Color.BLACK);
    this.add(_theDisplay);
}

}

Please any tips would be incredibly helpful, thanks in advance!
Answer: Your graphics appear messed. Problems I see:

You call getGraphics() on a component to draw with its Graphics context, but please understand that a Graphics object obtained in this way will not persist, and can thus mess up or even cause a NPE to be thrown.
Better to do all-passive Graphics via your paintComponent(...) method. If you need any pre-made drawings, do these in BufferedImages, and draw the BufferedImages in the JComponent's paintComponent(...) method.
Rather than have your Display JPanel do all the painting of the cards and the backs, I suggest that each Card be its own separate object with its own state, that paints itself correctly depending on its state. You may wish to have this extend a JComponent, or have it be a logical entity that is then painted by your Display JPanel, up to you, but separate out the logic from the display to simplify your coding and debugging.
A major problem looks to be in your findTrigger(...) method and that is where you should concentrate your efforts. You should use the mouseClick to change the state of the logical Card (as described above) that is clicked and then call repaint() on the Display JPanel (this) if the Cards are painted in paintComponent(...).
Else if the Cards paint themselves, consider having them be JLabels and simply swap ImageIcons, likely the easiest way to "flip" cards.
Your main problem is that of a program mis-behavior. I have not seen the cause of this on a quick overview of your code, and suggest that you use a debugger or println statements to first and foremost try to isolate the problem.
Comment: I figured out what the problem was.  I have the invisible JPanel panel which houses a full 2d array of JButtons.  The buttons have their own listeners so whenever someone clicks on any of the buttons, the if statement is immediately proven correct because the X and Y of the MouseClicker is considered a whole other panel on its' own.  You definitely pointed me in the right direction mate.  Cheers!
Comment: @Dusquad: glad you've got things going in the right direction!


Fabric8 KubernetesClient sends volumeName as empty string for PersistentVolumeClaim causing Forbidden: spec is immutable after creation

Question: I want to apply the following yaml multiple times with the fabric8 kubernetes-client
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  storageClassName: my-storage-class
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi

I apply the yaml using createOrReplace()
Config config = new ConfigBuilder()
        .withMasterUrl("https://my-kubernetes-root:6443")
        .withNamespace("my-namespace")
        .withOauthToken(token)
        .withTrustCerts(true)
        .build();

KubernetesClient client = new DefaultKubernetesClient(config);
ClasspathResource resource = new ClasspathResource("my-pvc.yaml");

client.load(resource.getInputStream()).createOrReplace(); // this works
TimeUnit.MINUTES.sleep(1); // volumeName is dynamically assigned during this period
client.load(resource.getInputStream()).createOrReplace(); // this fails

This works the first time (when the PVC does not exist in the namespace) but fails the second time that createOrReplace() is called for the same yaml with the following error
io.fabric8.kubernetes.client.KubernetesClientException: Failure executing: PUT at: https://my-kubernetes-root:6443/api/v1/namespaces/my-namespace/persistentvolumeclaims/my-pvc. Message: PersistentVolumeClaim "my-pvc" is invalid: spec: Forbidden: spec is immutable after creation except resources.requests for bound claims
  core.PersistentVolumeClaimSpec{
    AccessModes:      []core.PersistentVolumeAccessMode{"ReadWriteMany"},
    Selector:         nil,
    Resources:        core.ResourceRequirements{Requests: core.ResourceList{s"storage": {i: resource.int64Amount{value: 1073741824}, s: "1Gi", Format: "BinarySI"}}},
-   VolumeName:       "",
+   VolumeName:       "pvc-b79ebfcb-d5cb-4450-9f17-d69ec10b8712",
    StorageClassName: &"my-storage-class",
    VolumeMode:       &"Filesystem",
    DataSource:       nil,
  }

Notice how "volumeName" is not present in the yaml (nil) but in the error message "volumeName" is changing from empty string to the dynamically assigned volumeName.
I can reproduce this exact same behavior using kubectl and empty string for volumeName
I can kubectl apply the following yaml as many times as I like
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  storageClassName: my-storage-class
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi

But if I kubectl apply a yaml with volumeName of empty string it works the first time and fails the second time (The error message is the same as above)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  storageClassName: my-storage-class
  volumeName: ""
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi

How can I get KubernetesClient to behave the same as kubectl apply? Is there any way that I can apply the same PersistentVolumeClaim yaml multiple times with KubernetesClient?
Answer: As a workaround, I have switched to using a StatefulSet to manage my Pod which allows me to specify volumeClaimTemplates
eg the following yaml can be applied multiple times:
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  selector:
    matchLabels:
      app: nginx
  serviceName: "nginx"
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "my-storage-class"
      resources:
        requests:
          storage: 1Gi

Answer: Kubernetes API doesn't allow you to change some fields for a certain resource type at a certain state. For a PVC, after its state is Bound, the volumeName field in its spec is immutable; you can't change the volume your PVC is referencing.
When you apply a bare PersistentVolumeClaim manifest like the one in your question (a manifest that has no volumeName key or the value of its volumeName is nil), If the cluster has a default StorageClass, it automatically creates a corresponding PersistentVolume object that's the abstraction of your volume in Kubernetes from the underlying storage provider, then assigns its name to your PersistentVolumeClaim with the volumeName key.
After a PersistentVolumeClaim gets bound to a PersistentVolume and its volumeName field gets populated, you can not edit or patch its volumeName field anymore; that's the reason your kubectl apply command fails for the second time.
It's now clear that a Replace verb is not gonna work for a PVC in Bound state. You can Create one and edit or Patch 'some' of its fields (like increasing the size). I'm not familiar with Java SDK, but it should include some APIs for creating, getting, patching, and deleting a PVC.
You can first check for the existence of your PVC using the GetNamespacedPersistentVolumeClaim API; then, if it's not in the cluster, create it using CreateNamespacedPersistentVolumeClaim API. Referencing the axiom: "Explicit is better than Implicit."
Comment: Yes, I understand this which is why the volumeName is absent from the yaml so should not be sent in the request to kubernetes. As I've shown above I can apply the yaml via `kubectl apply` as many times as I like (even though the volumeName has been dynamically allocated). I can reproduce the error message via `kubectl` if volumeName is empty string in the yaml. So the question is, why can't fabric8 do the same as `kubectl apply`?
Comment: @lance-java I think that the flaw here is in the SDK's ```createOrReplace()``` API. As I said in the final paragraph, you can first explicitly ```Get``` your PVC using its name and namespace, check for its existence, and if it's not already created, explicitly ```Create``` it. These are the two verbs every Kubernetes client SDK must support.
Comment: If `createOrReplace()` is not the equivalent of `kubectl apply` then I'd like to know which method in `KubernetesClient` is the equivalent of `kubectl apply`. I don't want to write logic to get the existing entity, diff it with the yaml then apply a delta/patch based on the non-null fields. I'd hope `KubernetesClient` would give me the option to invoke the `apply` logic without having to roll-my-own solution
Answer: I raised this issue on the facric8 kubernetes-client codebase and got an interesting response which may do what I want. Please note that I haven't tried yet since I have a workaround using StatefulSet and volumeClaimTemplates (see my other answer)

The problem is the replace operation. It is not a substitute for apply / patch. Instead of createOrReplace you can use the new support for server side apply

And the relevant section from the link

Server Side Apply Basic usage of server side apply is available via
Patchable. At it's simplest you just need to call:

client.services().withName("name").patch(PatchContext.of(PatchType.SERVER_SIDE_APPLY), service);

For any create or update. This can be a good alternative to
using createOrReplace as it is always a single api call and does not
issue a replace/PUT which can be problematic.
If the resources may be created or modified by something other than a
fabric8 patch, you will need to force your modifications:

client.services().withName("name").patch(new PatchContext.Builder().withPatchType(PatchType.SERVER_SIDE_APPLY).withForce(true).build(), service);


Defining variables inside macro initialized to shell output

Question: This question is similar to Defining Variables inside macro.
I've tried this with both GNU Make v3.82 and v4.3.  In the snippet below, I'm getting an error when I have a variable initialized with output from a shell statement from within a macro.  On my system, __LINUX_GCC_MAIN_VERSION should be initialized with 11, which I then expect to be used in the initialization of __LINUX_GCC_V7_OR_LATER.  This does not appear to be happening, resulting in the syntax error from expr.
I've added $(info) statements to help with debugging.
LINUX_CC = gcc -m32

define __DECLARE_VERSION_FLAGS_GCC
$(info [1])
__$(2)_GCC_MAIN_VERSION = $(shell $($(2)_CC) -dumpversion | sed -e 's/\..*//')
__$(2)_GCC_V7_OR_LATER  = $(shell expr $(__$(2)_GCC_MAIN_VERSION) \>= 7)
$(info [5])
endef

$(info [6])
$(eval $(call __DECLARE_VERSION_FLAGS_GCC,linux,LINUX))

$(info [7])
# This outputs '11' as expected
$(info $(__LINUX_GCC_MAIN_VERSION))

$(info [8])
# This should be the result of "expr 11 >= 7", but the result is "FALSE"
ifeq ($(__LINUX_GCC_V7_OR_LATER),1)
V7 = "TRUE"
else
V7 = "FALSE"
endif
$(info $(V7))

$(info [9])

.PHONY: all

all:
    @echo Done

~/temp/tmp$ make -f Makefile3
[6]
[1]
expr: syntax error: unexpected argument '7'
[5]
[7]
11
[8]
"FALSE"
[9]
Done

What I expect to see is this:
~/temp/tmp$ make -f Makefile3
[6]
[1]
[5]
[7]
11
[8]
"TRUE"
[9]
Done

Why is this not working as desired, and what do I need to do to correct it?
Answer: The right way to debug eval issues is with info.  Repeat the same line as the eval but replace the eval with info, and make will print out the section of makefile that eval will parse.
The problem, as with basically every eval issue that ever existed, is not fully understanding how expansion works.  Consider this line:
$(eval $(call __DECLARE_VERSION_FLAGS_GCC,linux,LINUX))

How does make handle it?  As with ALL expansion, it works from the "inside out".  So first the innermost variables are expanded, moving from left to right (but here we don't have any values at the same level so that doesn't matter).  This means that the first thing make does is expand this:
$(call __DECLARE_VERSION_FLAGS_GCC,linux,LINUX)

This is very simple string replacement here: call has no concept of makefile syntax.  It's just expanding the value of the first argument interpreted as a variable name __DECLARE_VERSION_FLAGS_GCC with $1 set to linux and $2 set to LINUX.  How does this work?  The variable value is:
$(info [1])
__$(2)_GCC_MAIN_VERSION = $(shell $($(2)_CC) -dumpversion | sed -e 's/\..*//')
__$(2)_GCC_V7_OR_LATER  = $(shell expr $(__$(2)_GCC_MAIN_VERSION) \>= 7)
$(info [5])

so we start expanding.  Remember, for call this is just a string.  It has no concept of make syntax.  So first it expands the $(info [1]) and prints out [1].  Then it expands __$(2)_GCC_MAIN_VERSION =  and the result is __LINUX_GCC_MAIN_VERSION = .  Then it expands the shell command, which first expands the arguments to the shell, which will expand $($(2)_CC) to gcc -m32, so it will run the shell command:
gcc -m32 -dumpversion | sed -e 's/\..*//'

which will print 11, so so far we've expanded the call function to:
__LINUX_GCC_MAIN_VERSION = 11

But crucially, and I repeat, this is just a string.  We have not actually set the make variable __LINUX_GCC_MAIN_VERSION to 11.  As far as make is concerned this could be zippity doo dah 11.
Then we go to the next line:
__$(2)_GCC_V7_OR_LATER  = $(shell expr $(__$(2)_GCC_MAIN_VERSION) \>= 7)
$(info [5])

Now we expand this the same way, and here when we get to $(__LINUX_GCC_MAIN_VERSION) this variable is not set, because we're still in the call.  And so it expands to empty, and the shell runs expr  \>= 7 which is invalid syntax and you get the error you see.
Here's the trick when working with eval and call together:
As a general rule the content of the variable should escape all $ except for the call arguments ($1, $2, etc.)
This way, all those $ are passed through the call and not expanded, and then the eval will expand them.  So rewrite your define like this:
define __DECLARE_VERSION_FLAGS_GCC
$(info [1])
__$(2)_GCC_MAIN_VERSION = $$(shell $$($(2)_CC) -dumpversion | sed -e 's/\..*//')
__$(2)_GCC_V7_OR_LATER  = $$(shell expr $$(__$(2)_GCC_MAIN_VERSION) \>= 7)
$(info [5])
endef

(whether you escape the $(info ...) is up to you since it has no impact on the result of the expansion).
Now after the call, the shell etc. will not have run yet and you'll pass this string to the eval:
__LINUX_GCC_MAIN_VERSION = $(shell $(LINUX)_CC) -dumpversion | sed -e 's/\..*//')
__LINUX_GCC_V7_OR_LATER  = $(shell expr $(__LINUX_GCC_MAIN_VERSION) \>= 7)

and then it will work: eval will first set the __LINUX_GCC_MAIN_VERSION variable, then when it gets to the second line it will be set.


python recursion out of memory

Question: When this code runs, OSX notifies me that I'm out of application memory and pauses the application.  The amount of space that is used by Python breaks 10 gigs very quickly. This code never hits Python's max levels of recursion, it should only hit 525 worst case, but due to caching it should be much smaller. I have a feeling that the list chain is getting copied with every level of recursion, but it seems like it's a global variable that should be shared with every call of collatz().  I've looked for similar questions on stackoverflow, but I haven't found any that are the same.
# The following iterative sequence is defined for the set of positive integers:
#  n = n/2  (n is even)
#    = 3n+1 (n is odd)
# Using the rule above and starting with 13, we generate the following sequence:
#  13,40,20,10,5,16,8,4,2,1
# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10
#  terms. Although it has not been proved yet (Collatz Problem), it is thought that
#  all starting numbers finish at 1.
# Which starting number, under one million, produces the longest chain?
# Comments: I'm using dynamic programming to avoid computing the same values over and over
#            again.

lim = 1000000
chain = [1,1]
maxL = 0

def collatz(i):
   if i >= len(chain): chain.extend([None]*(i-len(chain)+1))
   if chain[i] == None: chain[i] = 1 + collatz(i/2 if i%2==0 else 3*i+1)
   return chain[i]

for i in range(1, lim):
   maxL = i if (collatz(i) > chain[maxL]) else maxL
   print i, chain[maxL]
print "collatz chain of {} is {} terms long.".format(maxL, collatz(maxL))

EDIT: See my working dictionary implementation here: https://stackoverflow.com/a/20229855/1084773.
Comment: I edited my answer, and in the last paragraph I explain where your memory issues come from.
Comment: I would prefer if questions and code related to Euler Project problems actually linked to the problem presentation and discussion (and made search friendly references to the terms, e.g. "Hailstone" in this case):
http://projecteuler.net/index.php?section=problems&id=14
http://blog.functionalfun.net/2008/07/project-euler-problem-14-hailstone.html
Answer: To see your memory error, run your code with limit = 100 and then print out chain.
Maybe you want to serialize your recursive code:
lengths = {1: 1}

def collatz(i):
    i0 = i
    acc = 0
    while True:
        if i in lengths:
            lengths[i0] = acc + lengths[i]
            return acc + lengths[i]
        acc += 1
        i = (i * 3 + 1) if i % 2 else i // 2

longest = 1
for i in range(1, 1000000):
    c = collatz(i)
    if c > longest:
        longest = c
        print(i, c)

This surely can still be optimized in many ways, but it yields the expected result in 4 seconds.

EDIT:
Your approach creates a list with a length of the highest term ever reached. For limit = 100, this is 9232. Which is not that much. But for limit = 1000000 it is 56991483520 (the chain starting with 704511), which is quite a whopper. If it were a mere array over int32, this would already be 212 GB of memory, and in reality it is more than that.

Here the troublesome chain: 704511, 2113534, 1056767, 3170302, 1585151, 4755454, 2377727, 7133182, 3566591, 10699774, 5349887, 16049662, 8024831, 24074494, 12037247, 36111742, 18055871, 54167614, 27083807, 81251422, 40625711, 121877134, 60938567, 182815702, 91407851, 274223554, 137111777, 411335332, 205667666, 102833833, 308501500, 154250750, 77125375, 231376126, 115688063, 347064190, 173532095, 520596286, 260298143, 780894430, 390447215, 1171341646, 585670823, 1757012470, 878506235, 2635518706, 1317759353, 3953278060, 1976639030, 988319515, 2964958546, 1482479273, 4447437820, 2223718910, 1111859455, 3335578366, 1667789183, 5003367550, 2501683775, 7505051326, 3752525663, 11257576990, 5628788495, 16886365486, 8443182743, 25329548230, 12664774115, 37994322346, 18997161173, 56991483520, 28495741760, 14247870880, 7123935440, 3561967720, 1780983860, 890491930, 445245965, 1335737896, 667868948, 333934474, 166967237, 500901712, 250450856, 125225428, 62612714, 31306357, 93919072, 46959536, 23479768, 11739884, 5869942, 2934971, 8804914, 4402457, 13207372, 6603686, 3301843, 9905530, 4952765, 14858296, 7429148, 3714574, 1857287, 5571862, 2785931, 8357794, 4178897, 12536692, 6268346, 3134173, 9402520, 4701260, 2350630, 1175315, 3525946, 1762973, 5288920, 2644460, 1322230, 661115, 1983346, 991673, 2975020, 1487510, 743755, 2231266, 1115633, 3346900, 1673450, 836725, 2510176, 1255088, 627544, 313772, 156886, 78443, 235330, 117665, 352996, 176498, 88249, 264748, 132374, 66187, 198562, 99281, 297844, 148922, 74461, 223384, 111692, 55846, 27923, 83770, 41885, 125656, 62828, 31414, 15707, 47122, 23561, 70684, 35342, 17671, 53014, 26507, 79522, 39761, 119284, 59642, 29821, 89464, 44732, 22366, 11183, 33550, 16775, 50326, 25163, 75490, 37745, 113236, 56618, 28309, 84928, 42464, 21232, 10616, 5308, 2654, 1327, 3982, 1991, 5974, 2987, 8962, 4481, 13444, 6722, 3361, 10084, 5042, 2521, 7564, 3782, 1891, 5674, 2837, 8512, 4256, 2128, 1064, 532, 266, 133, 400, 200, 100, 50, 25, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

Using your exact recursive idea, but using a dict (which is sparse) instead of a list (runs with no probs):
lengths = {1: 1}

def collatz(i):
    if i in lengths: return lengths [i]
    j = (i * 3 + 1) if i % 2 else i // 2
    c = collatz (j) + 1
    lengths [i] = c
    return c

longest = 1
for i in range(1, 1000000):
    c = collatz(i)
    if c > longest:
        longest = c
        print(i, c)

Comment: I completely underestimated how much extra memory the None values consumed in the list implementation. Thanks.
Comment: @brozak See my last edit which implements exactely your idea, just using a dict instead of a list.
Comment: After you pointed out the list issue I also implemented it with a dictionary: http://stackoverflow.com/a/20229855/1084773.

Thanks again.
Answer: The list implementation used a horrible amount of extra memory (as pointed out by Hyperboreus, thanks!).  Switching to a dictionary reduced the memory usage from ~212GB to ~70MB with 32byte ints and solved the problem in two seconds.
lim = 1000000
chain = {1:1}
maxL = 1

def collatz(i):
   if i not in chain: chain[i] = 1 + collatz(i/2 if i%2==0 else 3*i+1)
   return chain[i]

for i in range(1, lim): maxL = i if (collatz(i) > chain[maxL]) else maxL
print "collatz chain of {} is {} terms long.".format(maxL, collatz(maxL))

python recursion out of memory


Como pegar o numero de usuarios com menor tempo em cada clan?

Question: Tenho 2 tabelas:
CREATE TABLE `deathrun_records` (
    `sid64` STRING,
    `mapname`   STRING,
    `seconds`   REAL
);

CREATE TABLE `clan_members` (
    `sid64` STRING,
    `nome_clan` STRING,
    `prop`  STRING
);

A primeira tabela guarda o tempo dos usuarios em cada mapa, e a segunda guarda o clan dos usuarios.
Preciso de um SELECT que retorne os clans com usuarios que mais possuem recordes(menor tempo em um mapa).
O que eu fiz até agora:
SELECT COUNT(*) AS recordes FROM deathrun_records d JOIN clan_members c ON c.sid64 = d.sid64 GROUP BY c.nome_clan ORDER BY recordes

O meu problema é para criar um WHERE CLAUSE para pegar somente o jogador com menor tempo em cada mapa. Como fazer?
Answer: Primeiro você precisa fazer uma consulta agrupando o menor tempo por clan, e depois uma consulta por fora para pegar quem é que tem o menor tempo desse clan, então a consulta ficaria assim:
SELECT
    d2.*,
    c2.*
FROM deathrun_records d2
INNER JOIN clan_members c2
ON c2.sid64 = d2.sid64
INNER JOIN(
SELECT
    d.mapname,
    d.sid64,
    d.seconds,
    c.nome_clan,
    MIN(d.seconds) seconds_join
FROM deathrun_records d
JOIN clan_members c
ON c.sid64 = d.sid64
GROUP BY c.nome_clan
ORDER BY nome_clan, seconds DESC) as aux
ON (aux.nome_clan = c2.nome_clan
    AND seconds_join = d2.seconds
)

Sendo assim você pode contar o resultado da query agrupando por d2.seconds e c2.nome_clan ai você terá quantos players por clan possuem o menor tempo, dessa maneira estamos retornando os usuários com menor tempo por tempo do clan, se quiser ver por tempo global só retirar do GROUP BY da primeira consulta o campo nome_clan.
Na query que eu fiz acima você terá os players com menor tempo do CLAN nessa que fiz agora você qtd players por clan tem o menor tempo GLOBAL, segue:
SELECT
    COUNT(*) AS qtd_player,
    c2.nome_clan
FROM deathrun_records d2
INNER JOIN clan_members c2
ON c2.sid64 = d2.sid64
INNER JOIN(
SELECT
    d.mapname,
    d.sid64,
    d.seconds,
    c.nome_clan,
    MIN(d.seconds) seconds_join
FROM deathrun_records d
JOIN clan_members c
ON c.sid64 = d.sid64
ORDER BY nome_clan, seconds DESC) as aux
ON seconds_join = d2.seconds
GROUP BY nome_clan

Comment: "você terá quantos players por clan possuem o menor tempo", exatamente isso que eu quero. Tentei fazer do jeito que você falou aqui e não consegui...
Comment: @Francisco você quer pegar o menor tempo global? e depois ver por clan? ai eu edito a query e envio aqui


Computational complexity of the MATLAB's solver for solving nonlinear equation $f(x) = 0$.

Question: I have to solve a nonlinear (trigonometric) equation (that always has only one solution) $$f(x)=0$$ where function $f: D \subset \mathbb{R} \to \mathbb{R}$ is strictly increasing. I used the MATLAB function fsolve with the "trust-region-dogleg" method to solve the equation and the result is fine.
I would like to know the computational complexity of the algorithm used by MATLAB (i.e. trust-region method) in my case. Can I say that the CPU's computational time for solving such problem is the complexity of the algorithm?
I very much appreciate any answer or suggestion!
Comment: It may be a good idea to post at http://scicomp.stackexchange.com too. Cross-link the questions, please.
Comment: When you say that $f$ is strictly increasing, this seems to imply that $D$ is ordered. Is $D$ a subset of the real line?
Comment: Yes, actually, the set $D$ is $D := [0~a]$ where $a > 0$, so $D$ is a subset of $\mathbb{R}$. I have edited the question.
Comment: @Rodrigo de Azevedo: My function comprises of some basic sine and cosine functions.
Comment: Thanks @Rodrigo de Azevedo for your recommendation. I never know that forum before. But I think I have an answer now so is a cross-link needed?
Answer: You can have a grasp on the required time by comparing execution times under different conditions.
For instance, what happens if $D$ was twice the dimension, or you required twice the precision?
Let's put a simple example: adding two binary numbers $a,b$ of length $k$ requires $\mathbb{O}(k)$ operations to be computed. But $k$ is roughly $\log_2{a}$, so you can say the computation is $\mathbb{O}(\max{(\log_2{a},\log_2{b})})$
Note that, if we work with $a+1$ and $b+1$ rather than $a$ and $b$, we don't expect to need any extra opreations, except in the case one of them happens to be $111....111$ (or $999...999$ if we work in decimal)
If we need numbers with an extra digit (like $2a$ and $2b$), we will need one more operation. If we need numbers twice as long (like $a^2$ and $b^2$) we will need twice as many operations. Note that this fits well into the log-order complexity, since:
$$\log{(x+1)} \cong \log{(x)}$$
$$\log{(2x)} \cong 1+ \log{(x)}$$
$$\log{x^2} = 2 \log{(x)}$$
This types of relationships is what we usually check to find computationanl complexity in practice. Note that time is to some extent proportional to the number of basic operations (bit-additions), so we can use time as a "proxy" and work with it instead. That's why I suggest to check what happens when you have one more variable or twice as many variables in order to grasp the relationship between execution time and number of variables.
EDIT: Now that we know $D \subset \mathbb{R}$ the number of variables comparison does not apply. But you may want to use the complexity of $f$ (for example, adding a few degrees is $f$ is a polynomial), or the precision of the solution
Comment: @lyhuehue01 : You can add a print statement in the function $f$, for instance printing the argument it is called with. Also, there should be an option to get an info object in the result of `fsolve` that contains the number of function evaluations, Jacobian computations etc.
Comment: @lyhuehue01 When there are many factors that can vary the output (for example if the method is stochastic), I would repeat the execution a few times under slightly different conditions and use some statistics on the results (it may be good enough to just work with the average time if differences are not big)
Comment: Thanks David! I understood that the algorithm complexity should be performed by counting the total basic operations. However, in this case, I used the function _fsolve_ of MATLAB so I don't know the algorithm in detail.
Comment: Thanks @LutzL! That is a good point! But I think the number of function evaluations, Jacobian computations will vary with different initial guess of the solution, so we cannot know the complexity of the algorithm in general. Is it correct?
Comment: Thanks @David! Now I understood the idea of your answer. I think in my case, since I know the solution from the solver and the range of the variable $x$, I can gradually vary the initial guess of $x$ away from the solution and output the computational time. If we assume that the distance between the initial guess and the solution is proportional with the computation time, then we can derive the complexity of the algorithm. But I think it is quite rough and not reasonable to assume so.
Comment: Another way I can think of is just using the bisection (or interpolation) method because their computational complexities are known. A little bit longer computation time is not a problem in my case.


Analisar 4 selects e exibir mensagem

Question: Fala ai pessoal, blz?
Gostaria de saber como fazer a seguinte lógica em SQL:
if( 1 = select * from tblA or
    1 = select * from tblB or
    1 = select * from tblC or
    1 = select * from tblD or )
    Print 'ABC'

Comment: Sua pergunta não está clara. Você não informou o `SGBD` utilizando nem o que seria o `Print`. Você quer mostrar no console? Por que não usar uma `query` para isso?
Comment: Então, o quero apenas um modo como fazer isso, não sei mt de SQL, se tiver outra foma(mais eficiente) pode mandar, será bem vinda :D
Comment: O print não importa é apenas uma mensagem qualquer que vou escolher, acredito que para resolver isso, isto é irrelevante
Answer: SELECT 'ABC'
 WHERE EXISTS(SELECT 1
                FROM tblA)
    OR EXISTS(SELECT 1
                FROM tblB)
    OR EXISTS(SELECT 1
                FROM tblC)
    OR EXISTS(SELECT 1
                FROM tblD)

Comment: https://pedrogalvaojunior.wordpress.com/2013/05/02/entendendo-o-comportamento-de-trigger-dml-instead-of-no-microsoft-sql-server-2008-r2-e-2012/
Comment: A sim, entendi.
Você parece ter bastante experiência na área de Desenvolvimento, gostaria de saber se tem como você me ajudar num problema que tenho:

Estou desenvolvendo uma aplicação(não só desenvolvedor), mas programo razoavelmente bem em c# .
Vamos lá:

O problema é o seguinte
Tenho uma Tabela chamada Escala:
http://prntscr.com/mp25qt <-- Design dela
Comment: Quero criar uma trigger que Bloqueie o insert ou update nela
Se tiver alguma escala no mesmo intervalo e for do mesmo tipo.
Conseguiu entender bem?
Pode me ajudar?
Comment: @GustavoPedro então, tem algumas perguntas sobre `triggers` que bloqueiam aqui no SO já, mas sem saber qual o `SGBD` não consigo nem te indicar quais são
Comment: É SQL Server 2012
Comment: A sim, vou dar uma estudada lá vlw :D

Analisar 4 selects e exibir mensagem


How to specify that a property type must extend another type?

Question: I'm trying to declare a type which it should only accept objects where they extend another type.
For example:
export interface A extends B {
  aProp: string;
}

export interface B {
  bProp: string;
  // Feels wrong but how to tell something like ReadonlyArray<subClass extends B>?
  // I need children to contain A (or anything that extends B) & B properties
  children: ReadonlyArray<any & B>;
  childrenThatDoesntWork: ReadonlyArray<any extends B>; // <-- error here
}

class SomeClass {
  fun(obj: any extends B) { // <-- error '?' expected

  }
}

How to do this?
Thanks!
Comment: any is a type that you will use when you want to bypass type checking, doing `any & T` is useless, it means `any` at the end.  `any extends T` is also does not make any sense
Comment: Yea, but bypassing typecheck is what I'm trying to avoid.. Any solution?
Answer: Here is my solution:
export interface A extends B {
    aProp: string;
}

export interface B {
    bProp: string;
    // Feels wrong but how to tell something like ReadonlyArray<subClass extends B>?
    // I need children to contain A (or anything that extends B) & B properties
    children: ReadonlyArray;
    childrenThatDoesntWork: ReadonlyArray;
}

class SomeClass {
    fun<T extends B>(obj: T) {

    }
}

Please check if it works for your case. If not, please provide the code for tests
Comment: I'm trying to accomplish that anything could extend B, so A | B isn't the solution.


É uma má prática colocar números como id em elementos HTML? Se sim por quê?

Question: Eu tenho um loop printando elementos HTML, por exemplo:
for($i = 0; $i < 3; $i++){ echo "
$i
"; }

É uma má prática colocar números como id em elementos HTML? Se sim por quê?
Comment: E que tal concatenar? Como `id='info_$i'`?
Comment: O id deveria ser único. Se você garantir essa unidade, não vejo problemas nesse quesito. Eles também deveriam ser mnemônicos, fáceis de lembrar. Se você conseguir se organizar com números, também não vejo problemas. Eu sou incapaz de me organizar apenas com números, prefiro identificador textual
Comment: A partir do HTML 5 a W3C permite o uso de `ids` numéricos, vide [primeira nota da recomendação](https://www.w3.org/TR/html5/dom.html#the-id-attribute). A especificação  [WHATWG](https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute) também permite isso. Mas ainda a recomendação é que o `id` inicie com uma letra, para manter a compatibilidade com o HTML 4.
Comment: Então no meu caso, eu vou identificar elementos pelo numeral e inserir em uma tabela o conteudo desse elemento, como tenho N elementos vou utilizar uma estrutura de repetição. prefiro também um indetificador do tipo texto.
Comment: Pra todo mundo que está chegando agora: sim, é uma má prática, mas não, não é proibido. Um dígito é um caractere alfa**numérico**.
Answer: Como o @Renan disse, um número é um caractere alfanumérico. Eu concordo que usar apenas números é má prática, mas não vai contra o que a W3C estabelece.
Realmente "não há nenhum problema técnico", mas como você perguntou sobre "má prática", sim existe um problema.
Veja que na seção 3.2, os elementos do HTML5, sobre o atributo ID, é dito:

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

Que em tradução livre seria:

O atributo id especifica o identificador exclusivo (ID) do elemento. O valor deve ser exclusivo entre todas as ID na subárvore de origem do elemento e deve conter pelo menos um caractere. O valor não deve conter nenhum caractere de espaço.

Com isso é estabelecido as normas para uso do ID:

Não deve conter nenhum caractere de espaço;
Deve ser único;
Deve conter pelo menos um caractere;

E de brinde deveriam ser mnemônicos, fáceis de lembrar. Eu também sou incapaz de me organizar apenas com números, prefiro identificadores textuais.
Muito dificilmente eu conseguiria lembrar, a posição de uma tabela somente com números, por exemplo

 para representar a linha 1 e coluna 2. Seria muito mais simples

 e/ou derivações semelhantes.

O identificador exclusivo de um elemento pode ser usado para vários propósitos, principalmente como uma maneira de vincular a partes específicas de um documento usando identificadores de fragmentos, como uma forma de segmentar um elemento quando está usando scripts e como forma de modelar um elemento específico de CSS.

Particularmente vejo muito mais praticidade através de caracteres alfanuméricos. A quantidade de vezes que me perderia procurando pelo número em um arquivo HTML com JavaScript, CSS e outras tecnologias, ficaria inviável o trabalho, enquanto que com caracteres alfanuméricos ou somente textuais traria muito mais praticidade. Imagine procurar por uma div com ID número 1, e procurar por uma div com ID div-da-esquerda. A chance de repetição, que o editor de texto, possa encontrar, é bem menor e improvável em elementos com ID não numéricos.
Como recomendação, sempre que possível, tente utilizar nomenclatura que reflita o atributo de conteúdo id. E evite utilizar nomes desconhecidos e/ou estranhos. Não é porque eu posso criar variáveis com nomes aleatórios como:
String qualquercoisaquequisercolocaraleatoriamente = 'qualquervalor';

Que eu vou criá-las assim. Programadores escrevem código, mas bom programadores escrevem códigos que sejam compreensíveis tanto por humanos como por máquinas.
Comment: Um número é um caractere alfa**numérico**. Eu concordo que usar apenas números é má-prática, mas não vai contra o que a W3C estabelece.
Comment: Neste caso, devo concordar com o @Renen, caracter está sendo usado no sentido amplo neste caso. De qualquer sorte, +1 pelo `id='l1c2'`
Comment: Acho que "caractere" é qualquer caractere, incluindo números. Tanto que esse mesmo documento menciona "U+000A LINE FEED (LF) characters"  ou "each U+002D HYPHEN-MINUS character (-)". Se fosse apenas letras e números ele iriam mencionar, como fizeram em outros trechos " character in the range U+0041 to U+005A", ou seja especificando quais são os caracteres.
Comment: A norma diz ***must contain at least one character***. Eu entendo que ela não explicitamente diz, como você diz, mas como o AP perguntou sobre  "*má prática*", achei interessante ressaltar os motivos que isso "*fere a norma*".
Comment: @Renan ainda acredito que se fosse o caso a W3C teria colocado como *alphanumeric character*. E não somente um *character*.
Answer: Realmente não há nenhum problema técnico em se utilizar somente números como seletores no CSS desde que você garanta que nunca irá se repetir os seletores de ID para diferentes elementos. Agora, imagine um cenário mais complexo, com inúmeros elementos HTML e inúmeros seletores para se "decorar", afinal, você não pode contar que irá lembrar de todos os seletores de cabeça quando estiver desenvolvendo.
Por isso existem algum design patterns e boas práticas que são altamente recomendados para que seu processo de desenvolvimento flua e acabe sendo mais rápido, afinal, tempo é dinheiro.
Achei este artigo bastante interessante sobre como nomear IDs e classes no CSS para facilitar no desenvolvimento.
Existe também este link de um style guide do Google, que é bem interessante também.
Quanto a design patterns, recomendo este livro que aborda diferentes design patterns de desenvolvimento para HTML5 e CSS.
Comment: Um número ainda é um caractere. Por isso dizemos alfa**numérico**.
Comment: A resposta está correta, não há necessidade dos negativos. A regra da W3C informa apenas que **deve conter pelo menos um único caractere e que seja distinto dos demais `id`,** dessa forma utilizando números pode não ser uma boa prática falando de semântica, porém não há nada que impeça isso além do próprio desenvolvedor.
Comment: Peço desculpa a todos pela forma como interpretei a regra. Não existe de facto impedimento para html5 em usar `id` apenas númerico, e sim apenas em html4. Se poderem remover os -1 dados nesta resposta por esse motivo eu agradeço.
Comment: @Isac de mim você tem +1, sua resposta é boa.
Comment: Verdade @Isac realmente havia esquecido deste detalhe. Obrigado pelo seu adendo!
Answer: Minha resposta tende a desprender do contexto HTML, embora seja totalmente aplicável. Isso porque as respostas existentes já respondem esse lado da pergunta. Quero abordar um conceito mais amplo.

Uma das coisas mais importantes (e para a maioria não é tão importante assim) que o livro "Clean Code: A Handbook of Agile Software Craftsmanship", do Robert C. Martin, aborda é a nomenclatura que você dá para variáveis, classes e tudo mais. Isso você encontra no capítulo 2,  "Meaningful Names".
Seja expressivo e auto-explicativo ao nomear. Mas por que?
A mentalidade que você tem que ter ao programar é que está programando para outras pessoas lerem seu código mais tarde. Um dia aquele trecho de gambiarra que nem você entende terá que ser mantido por alguém. O mais engraçado é que esse alguém pode ser tanto você daqui a alguns meses como uma equipe inteira.

A única medida válida de qualidade de código: WTFs por minuto
Para provar o que eu estou dizendo, me responda: o que é que esse código faz?
for (int j = 0; j < 34; j++) {
    s += (t[j] * 4) / 5;
}

Da sala da revisão de código:

"WTF?! WTF?! WTF?!"

Provavelmente você não sabe e nem os revisores! Não é só porque você não sabe de que projeto ele é, ou nem a linguagem de programação. É porque as variáveis estão pessimamente escritas. Veja o mesmo código com um pouco mais de expressividade e auto-explicação:
const int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j = 0; j < NUMBER_OF_TASKS; j++) {
    int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
    int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
    sum += realTaskWeeks;
}

Não só as variáveis estão melhor nomeadas mas como aqueles números que estavam fixos e fazendo cálculos foram movidos para constantes. Isso para deixar o código explicar-se por si mesmo e não precisar de milhares de comentários explicando o que ele faz.
Escrevendo nomes significativos
Não é uma tarefa fácil. Os fragmentos abaixo foram retirados do livro que citei no início.
Os nomes devem revelar suas intenções
Só como você irá nomear uma função, classe ou variável você consegue transmitir a quem lê o que ela faz, como faz, por que faz e como ela é usada.
int tmm; // não use
int tempoMedioMinutos; // use
int tempoMedioEmMinutos; // use

Evite desinformação
Para as linguagens que são fracamente tipadas, como JavaScript, isso pode causar um problemão. Por que você nomearia uma variável de listaContas se ela nem é uma lista?
Faça distinções com significado
Às vezes utilizamos palavras que não adicionam em nada ao nomear uma classe.
O que você me fala das classes Produto, ProdutoInfo e ProdutoData? Elas são diferentes? Em que? Nesse caso, volte lá para "Os nomes devem relevar suas intenções" e reescreva com significado.
Use nomes procuráveis
Lembra lá atrás que falei da constante depois de te perguntar o que aquele código significava? É o mesmo caso.
if (visitor.CountryCode == '1237') {
    visitor.redirectTo('/al');
}

contra:
const BLOCKED_COUNTRY_CODE = '1237';
if (visitor.CountryCode = BLOCKED_COUNTRY_CODE) {
    visitor.redirectTo('/al');
}

Conseguimos dar significado para um valor que era acoplado de uma maneira fixa, constante. Assim fica fácil de ler e de achar também.
Mais...
Aqui falei sobre o pouco do pouco que o livro aborda. É um leitura mais que recomendada para programadores. Boa leitura :)
Além do Clean Code
Não é só o livro que aborda isso. A PEP 20, do Python, comumemente "The Zen of Python", que pode ser aplicada não só ao Python, fala que:

Legibilidade de código conta
Explícito é melhor que implícito

Dos 19 pontos que essa PEP fala, esses dois são bem aplicáveis nesse contexto.

Prefira a legibilidade, escreva para que os outros ou o futuro-você entenda
Seja explícito ao nomear os membros e ao utilizar as características de uma linguagem.

Das premissas levantadas aqui, você pode inferir se nomear:

1

2

3

é uma má prática ou não. Pode até concluir se $i = 0 é bom ou não.
Agora sempre que programar, pergunte a si mesmo: quantos WTFs por minuto você receberia na revisão de código?
Tem um vídeo do Filipe Deschamps sobre a importância dos nomes e o Clean Code. Na verdade tem uma série de vídeos sobre o Clean Code. Disse ele:

Se a gente pensar que tirando a sintaxe de um código, basicamente o que resta é um monte de nome atrás de outro nome, chamando outro nome e assim por diante.


What does "Position in a stream" mean in C#?

Question: I have trouble to understand the word "Position of a stream". My question is somehow related to the concept of the stream method Seek(); it is kind confusing to me what this method does, they say its purpose is to set the position of the stream to a given value but yet its name describes the seek operation not set operation. Does anyone understand clearly what these two words are for and how they work together? Thanx
Comment: It is not the "Position of a stream" but the "Position _in_ a stream".
Answer: Think about a file as a sequence of bytes, and a stream as a view over that sequence, with a cursor marking the current position - so as you read data, the cursor is advanced. The Position property is simply the position of that cursor. So when you open a stream it's typically at 0, and as you read it increases. For seekable streams, you can "rewind" to the start of the stream with
stream.Position = 0;

or maybe skip 10 bytes using:
stream.Position += 10;

etc.
Answer: A stream is basically a sequence of bytes - the position is the point in the sequence that the stream is in.
The point of Seek is to "jump" to a location in the stream - a specific index (aka Position), similar to seeks done in a hard drive. With Seek you can specify an offset to start seeking from, so how many bytes to "jump".
Answer: The following 2 statements do exactly the same:
s.Position = 100;
s.Seek(100, SeekOrigin.Begin);

And they both determine the position (as a bytecount) where the next Read or Write will occur.
The Seek() name is very ancient.
Comment: Hey Henk! Can you explain to me what the SeekOrigin is all about? Say s.Seek(100, SeekOrigin.End) ; will it set the cursor starting from the end of the stream ?
Comment: Yes. I think those names a re pretty self-describing. You will very rarely need them (and therefore Seek() ). Just use `Positon`.
Answer: I actually agree that, at first glance, Seek is not the best name for what it does. SeekAndSet or SeekAndMove would make more sense to me because that is what the method does - it seeks the position you want in the stream and sets the cursor to that position.
However, when you think of Seek in Computer Science terms in relation to hard disk drives it becomes obvious what this method does. It seeks and moves to the position.
Answer: Also, for the record with NAudio, this used to be stream.GetPosition() as well. It's since changed to just stream.Position


Express + Passport : How to use req.user variable in MYSQL query

Question: I hope someone can help with.  Apologies if its simple, I've been searching the web for hours and havn't round the right answer.
I'm using Express with Passport.  I have logins working and req.user is being populated with the user_id from the database which comes out in this format when console.log'ing it:
req.session.passport.user: {"user":{"user_id":18} }

So that's good.  Now I'm moving onto another page and trying to use that variable in a new MYSQL query to get more information from the user out of my database like so:
user = req.user;
db.query("SELECT * FROM users WHERE id = 'user'", function(error, results, fields) {
        if (error) throw error;
        console.log(results)
      });

I can't get this to work after trying to strip the user_id variable down to just numbers, etc.  Can anyone suggest a method to get the req.user variable into a usable format fitting a MYSQL query (being just the number so I can match it against the proper field)?  Any assistance would be greatly appreciated.  Thanks for reading!
Regards,
Daniel
Comment: What about : "SELECT * FROM users WHERE id =  ${user}"
Answer: You can use template literal just as follow,
db.query(`SELECT * FROM users WHERE id = ${req.user.user_id}`, function(error, results, fields) {
  if (error) throw error;
  console.log(results)
});

Or
"SELECT * FROM users WHERE id =" + req.user.user_id

Comment: DININDU, Winner winner, chicken dinner.  Thank you sir your edit of ""SELECT * FROM users WHERE id =" + req.user.user_id" did the trick.  Thank you so much, that's been driving me freaking crazy, now I can move forward, have a great day!


Set value of List field of a node with multiple values

Question: I'm attempting to programmatically generate nodes of a custom content type from a form plugin. For most fields I don't have any trouble at all. For example for the title field I can set the value like so.
<code>$node->title->value = t('My title');
$node->save();
</code>
However there is also a list(text) field that allows for multiple values. And I'm not sure how to go about saving values of field with multiple values. I'm assuming if there was only one value allowed I could do it just like I set the title in the previous example, but how do I deal with it when the field is an array? As a test I performed a die statement of the field on a node that already had values in that field to take a look at what it looks like and this was generated:
<code>Array ( [0] => Array ( [value] => test_3 ) [1] => Array ( [value] => test_4 ) ) 1
</code>
But I'm not sure what to do with that. How would I set the field value of a list field with multiple values allowed?
Answer: You can replace the complete content of a field by assigning an array:
<code>$node->field_multivalue = [
  ['value' => '1'],
  ['value' => '2'],
  ['value' => '3'],
];
</code>
If you want add another value to the field you can use the field like a php array:
<code>$node->field_multivalue[] = ['value' => '4'];
</code>
You can omit the main property of a field:
<code>$node->field_multivalue[] = '5';
</code>
Now you have 5 values in the field.
Comment: Another option: $node->field_multivalue->appendItem(5);


Having issue with click function for

Question: HTML

<input type="checkbox" name="checkbox[]" method="post" value="" class="checkbox" />

JS
$("tr").not('.checkbox').click(function(){
    window.location = $(this).attr("url");

});

Want to disable click function inside clickbox, but code above doesn't work: it redirects even when I click in checkbox. Where  did I go wrong?
Comment: I advice you use the `data-` syntax. `` and access it as `$("selector").data("custom-url");`. By the way, if I'm not mistaken you must also indicate the protocol of the url.
Answer: $("tr").not('.checkbox')

This code will match all tr elements which do not have a class of checkbox.  As you can see, your tr does not have that class, so this tr will match.
There are 2 basic approaches to doing what you are trying to do.  You can either check in the function what the original clicked element was and don't redirect if it was a checkbox.  Or, you can add a click handler to the checkbox and call e.stopPropagation().
$("tr .checkbox").click(function(e){
    e.stopPropagation();
});

Answer: Add a separate handler that stopps propagation.
$("tr").click(function(){
    window.location = $(this).attr("url");
})
  .find(".checkbox").click(function(e) { e.stopPropagation(); });

Answer: Simply stop event propogation on checkbox like below,
$('.checkbox').click(function(e){
   e.stopPropagation();
});

Fixed the typo.
Comment: @sks but I selected as answer. First answer with stopPropagation(); suggestion was his. Bravo. Works!
Comment: I am not able to remove the dv even though you edited it, edit it again I will try.
Answer: Stop the event propagation on checkbox click. Try this.
$('.checkbox').click(function(e){
   e.stopPropagation();
});

And change your code to
$("tr").click(function(){
    window.location = $(this).attr("url");

});

Alternatively you can check for target and act accordingly. Try this.
$("tr").click(function(e){
    if(!$(e.target).is(':checkbox')){
       window.location = $(this).attr("url");
    }
});

Having issue with click function for


Winning Probability Question

Question: 2 people are in a competition. Jars are placed in a row and are labelled from left to right 1, 2, 3... A ball is concealed in one of these jars and all jars have the same chance of having the ball inside of them.
Each contestant takes turns to guess which jar the ball is inside of. If one of them guesses the right jar, the anchor will say 'correct', which indicates that the contestant has won. However, if the guess is wrong, the anchor will state 'smaller' or 'bigger' (referring to the numbers) to show the direction the ball is hidden. The contestants always obey the anchor's directions. For example, if ten jars are presented (labelled one to ten) and the ball is concealed in jar seven, the contest may go like the following (follow the link to see the example):

A contest has jars labelled one to nine. Why is it that regardless of which jar Person B picks, Person A has a method where he picks jar five on the first go and guarantees his probability of victory is higher than $1/2$.
I thought that if Person A picks 5 on the first go, he would have $2/3$ chance of winning. This is the equation I used to arrive at that:
$1/9 + 8/9 \cdot 3/4 \cdot 1/3 + 2/3 \cdot 1/2 \cdot 1/1$
However, I do not know if this is correct.
Comment: Okay, there is something you do not know is correct.  It would be helpful to say what your Question actually is.  Just copying a problem you found elsewhere doesn't give Readers much idea what you would like help with.  For example, you might be interested in the case of ten jars, or you might be interested in a more general case.  Once a strategy is chosen (as the copied material already outlines) there is a problem of calculating the chances of winning and comparing that probability to one-half.
Answer: The correct probability will be 5/9, but since you do not provide an explanation how you arrived at the various fractions in your answer, I can't tell you what the mistake is that you made. But here is a possible way to arrive at the answer.
It is important for these type of problems to mention how both participants play the game. Since there is an optimal strategy, we are going to assume that both players use it.
Let $n \geq 1$ be the number of jars that is used in the game and $P(n)$ be the probability that the first player that is allowed to choose a jar will win using the optimal strategy. It is clear that in the case $n=1$ we have $P(1)=1$ and also the case $n=2$ is easy and we have $P(2)=\frac{1}{2}$ regardless which jar is chosen.
Now consider a general game with $n$ jars and the first player chooses the $k$th jar ($1 \leq k \leq n$). What is the probability $P(k|n)$ that this will result in winning the game? There is a probability $\frac{1}{n}$ for this to be the correct one. More likely it will be wrong and it is either too high or too low. It could be too high with a probability $\frac{k-1}{n}$, which will give the other player the chance to win with a probability $P(k-1)$, because he/she is the first player in a game with only $k-1$ jars. Alternatively, the number $k$ was too low with a probability  $\frac{n-k}{n}$ and the second player has probability $P(n-k)$ to win using the optimal strategy. So we find:
$P(k|n) = \frac{k-1}{n} \left[1 - P(k-1) \right] + \frac{1}{n} + \frac{n-k}{n}  \left[1 - P(n-k) \right]$
where we used the probabilities $1 - P(k-1)$ and $1 - P(n-k)$ for the second player to loose. From this we obtain the value of $P(n)$ by finding the maximum value of $P(k|n)$ among all $1 \leq k \leq n$.
What I will leave as an exercise is to show that:
1) The winning probability with optimal strategy:
$P(n) = \left\{ \begin{array}{ll} \frac{1}{2} & \text{for $n$ even} \\ \frac{n+1}{2n} & \text{for $n$ odd} \end{array} \right. $
2) For even values of $n$, we have $P(k|n) = \frac{1}{2}$ for all $k$
3) For odd values of $n$, we have $P(k|n) = \frac{n+1}{2n}$ for odd values of $k$ and $P(k|n) = \frac{n-1}{2n}$ for even values of $k$
You can prove this by induction and considering the four cases $n,k$ being even/odd.
In the particular case $n=9$ and $k=5$, you only need the value of $P(4)$ and it is a bit easier.
Comment: Is there any simpler way of doing this as I do not how to do induction?
Comment: Induction is the name of the method to prove the expression is general and valid for all $n$ (See for instance the wikipedia "mathematical induction"). You can of course use the formula to get $P(1|3)=P(3|3)=2/3$ and $P(2|3)=1/3$ from which it follows $P(3)=2/3$, followed by $(.|4)=1/2=P(4)$. After that you get $P(5|9)=5/9$, essentially this is just induction written out in detail for the cases $n=3,4$. A more cumbersome approach is to write out all scenarios in order to obtain $P(4)$.
Comment: When you say "More likely it will be wrong and it is too high with a probability (k−1)/n", shouldn't it be (n-1)/n as there are (n-1)/n chance that the prize is in another box?
Comment: Yes you are right, it was a bit of a poor formulation.
Comment: Wouldn't the rest of the method/justification be incorrect then?
Comment: No the calculation was OK,I just corrected the formulation. There is a probability $(n-1)/n$ that the choice $k$ is wrong, after that one needs to distinguish the two possible cases that $k$ is too high or to low, with a probability $(k-1/n)$ and $(n-k)/n$ respectively.

Winning Probability Question


Find the equation of a circle whose diameter is the chord of another circle

Question: I am studying maths as a hobby and have just come to the last end-of-chapter question on parabolas and circles.
The straight line through the point $A(-a,0)$ at an angle $\theta$ to the positive direction of the x-axis meets the circle $x^2+y^2=a^2$ at P, distinct from A. The circle on AP as diameter is denoted by C.
i) By finding the equation of C, or otherwise, show that if C touches the y-axis, then $\cos2\theta=2-\sqrt 5$
ii) C meets the x-axis at M, distinct from A, and the tangents to C at A and M meet at Q. Find the coordinates of Q in terms of $\theta$ and show that as $\theta$ varies, Q always lies on the curve $y^2x +(x+a)^3=0$.
I really don't know how to begin here. To find the equation of C I am thinking I need two points so I can use the equation: $$x^2+y^2+2gx+2fy+c=0$$
But I only have one definite point, at A. The value of y at B is unknown. I could call P (x,y) but this is too vague.
This is my visualisation of the situation for the first part:

I can see that $\angle ABP$ is a right angle.
Answer:
Instead of solving equations of circle and straight line, using a bit of geometry make things easier. You do not need to use equation of the circle for any of the two questions if you do not want to.
$AP$ is a chord of the circle centered at $O$. So perpendicular $OT$ from $O$ to $AP$ bisects $AP$ and $T$ is the center of the new circle $C$.
Then $AT = OA \cos\theta = a \cos\theta$
So, $AP = 2 a \cos\theta$
$PH = AP \sin\theta = 2 a \cos\theta \sin\theta = a \sin2\theta$
$OH = OA - AH = a - AP \cos\theta = a - 2 a \cos^2\theta = - a \cos2\theta$
So coordinates of $P$ is $(a \cos2\theta, a \sin 2\theta)$
As $T$ is the midpoint of $AP$, coordinates of $T$,
$ \left (\frac{-a + a \cos2\theta}{2}, \frac{a\sin2\theta}{2}\right)$
If the circle $C$ touches y-axis, $AT = TB$ as both are radii of circle $C$.
Solving it, you  will get the value of $\cos2\theta$.
For the second part, you know center $T$ and radius so you can use the equation of circle $C$, then find tangents and intersection point. But I prefer the following -
Points $A$ and $M$ are both on x-axis and  tangents at those points would meet at a point which is on the vertical line going through the center of the circle, $T$. Can you see why?
Also, the tangent at point $A$ is perpendicular to $AP$ and as we know the slope of $AP$, we can find the equation of tangent at $A$ and its intersection $Q$ with the vertical line through center $T$.
Then show that $Q$ satisfies the equation of the given curve.
Can you take it from here? If you get stuck, please let me know.
Comment: After much work on this, I have found your geometric approach very helpful to understand this problem more fully.
Comment: @Steblo glad it was of help.
Answer: Equation of $AP$ is given by:
$$ y = (x+a)\tan\theta$$
Now find the coordinates of the points of intersection of this line with the given circle.
$$ x^2 + y^2 = a^2$$
$$ x^2 + (x+a)^2\tan^2\theta = a^2$$
$$ x^2 \sec^2\theta + 2a\tan^2\theta x + a^2(\tan^2\theta-1) = 0$$
This is a quadratic whose roots are the abscissae of $A$ and $P$. And we already know that the abscissa of $A$ is $-a$, we can easily find the other root using Vieta's formulae.
$$ P_x = \frac{a^2(\tan^2\theta-1)}{-a\sec^2\theta} = a(\cos^2\theta - \sin^2\theta) =a\cos2\theta$$
From the equation of the line,
$$ P_y = a(1+\cos2\theta)\tan\theta = a\sin2\theta$$
Now you know the coordinates of both $A$ and $P$. Thus you can write the equation of circle $C$, which will be:
$$ (x-A_x)(x-P_x) + (y-A_y)(y-P_y) = 0$$
$$ (x+a)(x-a\cos2\theta) + y(y-a\sin2\theta) = 0$$
Since this circle touches the y-axis, its intersection with the line $x=0$ must have a unique root.
$$ a(-a\cos2\theta) + y(y-a\sin2\theta) = 0$$
$$ y^2 -ya\sin2\theta - a^2\cos2\theta=0$$
Equating the discriminant of this quadratic to zero,
$$ a^2\sin^22\theta+4a^2\cos2\theta=0 $$
$$ 1-\cos^22\theta + 4\cos2\theta=0$$
$$  \color{red}{\boxed{ \color{black}{ \cos2\theta = 2 - \sqrt{5}}}}$$

For the second part of the question,
Tangents at $A$ and $M$ meet at $Q$. Thus, it is clear that the line $AM$ is the chord of contact of the point $Q$ with respect to the circle. Let $Q$ be some $(h,k)$
The circle's equation is (from above)
$$ (x+a)(x-a\cos2\theta) + y(y-a\sin2\theta) = 0$$
$$ x^2 + y^2 + 2ax\sin^2\theta - 2ay\sin\theta\cos\theta - a^2\cos2\theta = 0 $$
Equation of chord of contact is given by $T=0$
$$ hx + ky +a\sin^2\theta (x+h) - a\sin\theta\cos\theta (y+k)- a^2\cos2\theta = 0$$
$$ x(h+a\sin^2\theta) + y(k-a\sin\theta\cos\theta) + ha\sin^2\theta - ka\sin\theta\cos\theta - a^2\cos2\theta = 0$$
This is the equation of $AM$. But we know that $AM$ is nothing but the x-axis. Therefore, this equation must be equivalent to $y=0$
On equating the coefficient of $x$ and the constant term to zero, we get:
$$ h+a\sin^2\theta = 0$$
$$ ha\sin^2\theta - ka\sin\theta\cos\theta - a^2\cos2\theta = 0$$
Solve for $h$ and $k$
$$ h = -a\sin^2\theta $$
$$ k = -a \frac{\sin^4\theta - 2\sin^2\theta + 1}{\sin\theta\cos\theta} = -a \frac{(1-\sin^2\theta)^2}{\sin\theta\cos\theta} = -a\frac{\cos^3\theta}{\sin\theta} $$
Now you have the coordinates of $Q$ in terms of $\theta$
$$ \color{red}{\boxed{\color{black}{Q \equiv \left(-a\sin^2\theta, -a\frac{\cos^3\theta}{\sin\theta} \right)}}}$$
It is easy to show that $Q$ always lies on the curve $y^2x +(x+a)^3=0$. Just plug in the values of $h$ and $k$ into the locus and verify if the equation is correct.

Proof for $T=0$ being the chord of contact:
Keep in mind that this is for any conic (parabola/ellipse/hyperbola), and not just for circles.
For a general conic $ax^2 + 2hxy + by^2 + 2gx + 2fy + c = 0$,
At a point $(x_1,y_1)$, $T=0$ is written as $$ axx_1 + h(xy_1 + x_1y) + byy_1 + g(x+x_1) + f(y+y_1) + c = 0$$
I have already linked the proof for why this represents the equation of the tangent to the conic if $(x_1,y_1)$ lies on the conic, in the comments. We will use this result to prove that this represents the chord of contact of the point if $(x_1,y_1)$ lies outside the conic.
First, let me make it clear what I mean by chord of contact. Suppose there is a point $(x_1,y_1)$ outside the conic. Draw tangents to the conic from this point. There are clearly 2 such tangents possible. Let these 2 tangents touch the conic at the points $(x_2,y_2)$ and $(x_3,y_3)$ respectively.
Using the above property, the equation of the tangent to the conic at $(x_2,y_2)$ is given by:
$$axx_2 + h(xy_2 + x_2y) + byy_2 + g(x+x_2) + f(y+y_2) + c = 0 $$
Similarly, the equation of the tangent to the conic at $(x_3,y_3)$ is given by:
$$axx_3 + h(xy_3 + x_3y) + byy_3 + g(x+x_3) + f(y+y_3) + c = 0 $$
These 2 tangents intersect at $(x_1,y_1)$. This implies that $(x_1,y_1)$ lies on both these lines. Thus, we get:
$$\tag{1} ax_1x_2 + h(x_1y_2 + x_2y_1) + by_1y_2 + g(x_1+x_2) + f(y_1+y_2) + c = 0 $$
$$\tag{2} ax_1x_3 + h(x_1y_3 + x_3y_1) + by_1y_3 + g(x_1+x_3) + f(y_1+y_3) + c = 0 $$
Now, consider the linear equation
$$axx_1 + h(xy_1 + x_1y) + byy_1 + g(x+x_1) + f(y+y_1) + c = 0$$
From $(1)$ and $(2)$, $(x_2,y_2)$ and $(x_3,y_3)$ both lie on this line. But there exists a unique line passing through two given points. Therefore, this line must be the equation of the chord of contact, thus completing our proof.
Actually, $T=0$ represents another thing. For any point except the centre of the conic, it represents the polar of the point with respect to the conic. If you draw variable secants $PAB$ from a point $P$, then the locus of the point of intersection of the tangents to the conic at $A$ and $B$ is known as the polar of point $P$ with respect to the conic and the point $P$ is known as the pole of the polar with respect to the conic. You can prove this result by using a similar idea that I used to prove the chord of contact theorem.
There are several other notations as well for conics. These notations can be extremely useful in simplifying calculations in coordinate geometry problems like your question.
Comment: Your proof is very useful to me. Thank you for putting in the effort. I shall study it carefully.
Comment: I am just working through the submitted answers but am a little puzzled why the equation to circle C should be $$ (x-A_x)(x-P_x) + (y-A_y)(y-P_y) = 0$$
$$ (x+a)(x-a\cos2\theta) + y(y-a\sin2\theta) = 0$$ I thought circles had the general form$$(x-h)^2+(y-k)^2=a^2$$
Comment: @Steblo The equation of the circle with $A(x_1,y_1)$ and $B(x_2,y_2)$ as the ends of the diameter is given by $$(x-x_1)(x-x_2) + (y-y_1)(y-y_2) = 0$$ This is equivalent to the general form of the circle, it is just a simplified version of it. It is easy to prove too. Substitute  $h= \frac{x_1+x_2}{2}$, $k=\frac{y_1+y_2}{2}$ and $r= \frac{\sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}}{2} $ into the general form and simplify. You will end up with the same equation that I have written above.
Comment: I am puzzled by how you use $$ x^2 + y^2 + 2ax\sin^2\theta - 2ay\sin\theta\cos\theta - a^2\cos2\theta = 0 $$ to get $$ hx + ky +a\sin^2\theta (x+h) - a\sin\theta\cos\theta (y+k)- a^2\cos2\theta = 0$$  It seems you have substituted x by h and y by k in parts but then x becomes (x+h) and y becomes (y+k).
Comment: @Steblo The equation I have written is known as $T=0$ or $s_i = 0$ in [Joachimsthal's notations](http://www.cut-the-knot.org/Generalization/JoachimsthalsNotations.shtml). For a point lying on the conic, this equation represents the equation of the tangent to the conic at that point. [Proof](https://math.stackexchange.com/questions/721150/why-does-the-t-0-method-to-calculate-tangent-work) For a point lying outside the conic, it represents the equation of the chord of contact (line joining points of tangency whose tangents intersect at that point). I will include the proof for this in my answer.
Comment: Thanks very much for that.
Comment: @Steblo I have edited my answer and added the proof.
Answer: A simpler observation is to note that the coordinate of $P$ is $(a \cos 2\theta, a \sin 2\theta)$, since the central angle that $OP$ makes with the positive $x$-axis is twice the corresponding inscribed angle $\angle PAO$.
Moreover, because $\triangle AOP$ is isosceles, the midpoint $D = \frac{a}{2}(-1 + \cos 2\theta, \sin 2\theta)$ of $AP$ is the foot of the altitude $DO$, hence $\triangle AOD$ implies $AD = a \cos \theta$.
But since $BD = AD$, it follows that $$\frac{a}{2} (1 - \cos 2\theta) = a \cos \theta = a \sqrt{\frac{1 + \cos 2\theta}{2}}.$$  Letting $z = \cos 2\theta$, we obtain a quadratic in $z$ after cancelling $a$:
$$(1-z)^2 = 2 (1 + z),$$ or $$0 = z^2 - 4z - 1,$$ hence $\cos 2\theta \in \left\{ 2 \pm \sqrt{5} \right\}$.  Since only one of these roots has magnitude not exceeding $1$, we obtain $\cos 2\theta = 2 - \sqrt{5}$ as claimed.
Answer: The green circle is the given circle defined by you. Let $K$ be the center of a circle through $A$ and tangent to the $y-\text{axis}$ at $J$. This is not necessarily your circle $C$. Let these two circles meet at $A$ and $L$, and let $M$ be the midpoint of common chord $AL$.

Now, suppose point $J$ moves freely along the $y-\text{axis}$. As $J$ travels, point $K$ is equidistant from point $A$ and the $y-\text{axis}$. The locus of $K$ is the parabola having focus $A$ and the $y-\text{axis}$ as directrix. Locus of $K$:
$y^2=-2a(x+\frac{a}{2})$
Again with point $J$ traveling, point $L$ traces circle $O$, while $A$ is stationary, and $M$ is the midpoint of $AL$. The locus of $M$ is the circle having diameter $AO$. Locus of $M$:
$x(x+a) + y^2 = 0$
The center of your circle $C$ must lie on both of these loci. Solve the system of equations. That gives you the coordinates of the circle center (two solutions). The rest should fall into place from there.


How to make product views display also show up for Anonymous users in Drupal Commerce?

Question: I created a Product listing view with Add to Cart Buttons. The view displays perfectly for the Super User, but it is not displaying for Anonymous or Authenticated users.I do have a relationship "referenced product" but it is still not working for anonymous users.
What I did to solve the problem is to go to the permissions page and give everybody the "view all products" permission. This works. BUT: It might open up a security issue. Please let me know what am I doing wrong?
Comment: give view all products permission to all user but  set permission for checkout  also check https://www.drupal.org/node/1276450 there is patch for it
Comment: I already did that but on permission page there is also a Warning: Give to trusted roles only; this permission has security implications.
Comment: check drupal.org/node/1276450
Comment: it is the best solution by permission?
Answer: Inspired by what's written in some of the comments to issue nr 1276450, such as in comment nr 158 of it:

edit your View: > "Advanced" > "Query settings" : check "Disable Query Rewriting"

For sure worth trying to see if it helps in your case. If it does, it'll be way better then the permission you granted as described in your question I think.


missing data a variable is related to another variable

Question: I have a dataset with some missing data. In this dataset, there are two variables that their missing data behaviors are same. Because these variables represent hormone measures, absence of one leads to lack of another (those are measured together). What is the missing-data mechanism in this situation?
Missingness completely at random (MCAR) or Missingness at random (MAR) or another mechanisms?
Answer: Without further information about the data at your disposal, I'd say this is missing not at random (MNAR). I am saying this because the reason the 'other' value is missing, is another value missing. Basically, the missingness of the data is caused by/depended on some aspect of the missing data (see this reference).
However, if there is more data at your disposal which is known to be associated or unknowingly associated with the missing hormone levels (suggesting a partial missing at random (MAR) mechanism), you might still be able to make valid estimates of the missing values through multiple imputation techniques.


Page--front.tpl.php not working - Tao theme

Question: This should be really simple, maybe I'm just having a moment. Why is my page--front.tpl.php not rendering my home page? I'm using a tao subtheme.
Here's my tpl.php file.

(There's no other page--front.tpl.php in the tao folder.)
Here's my front page settings:

And here's theme developer telling me that the front page is using page.tpl.php to load:

I've cleared my cache with drush a couple times and restarted my local server. What else am I missing?
Comment: are the user/group ids and permissions the same as the rest of the files in the directory?  eg, can your webserver read it.
Comment: don't add .php at the last of file name, just only add the page--front.tpl
Answer: I think I see a Windows specific issue here.
Notice how block.tpl only has the extension tpl and your new file page--front.tpl.php has php as extension in the filename?
Maybe Windows hides the php extension when you list files (and instead shows it under Type)?
Try removing .php from page--front.tpl.php and see if it still under the Type column shows up as php. If so clear cache and carry on :)
Comment: Spot on :D Thank you so much for that, it actually solved another problem where I'd done the same thing as well. (Also thank you to Bala for spotting the same thing)
Answer: Following steps resolved the issue to create custom front page for Drupal 7.

Create a file - page--front.tpl.php. Notice two hyphens instead of
one.
Clear the cache - Configuration >> Development >> Performance>>
Clear all caches


Changing scan order of Gibbs Sampler on each iteration

Question: I'm implementing an algorithm that requires the use of Gibbs Sampling and, due to the nature of the way I store the values, it would be efficient to change the order of the updates on each component at every iteration.
For example, if I have three components, the first iteration will be over [1, 2, 3], but the next one could be [2, 3, 1], then [1, 3, 2], and so on.
If the answer is "it depends" then I'll edit the question with more details.
Comment: The answer to which question? Changing the order at each iteration is legitimate, whether it is done randomly or deterministically.
Answer: One can consider a Gibbs sampler as a combination of componentwise Markov kernels $G_i$ with $$G_i(\theta,\theta^\prime)=p(\theta^\prime_i|\theta_{-i})\delta_{\theta_{-i}}(\theta^\prime_{-i})$$Since each kernel is stationary wrt the joint distribution, so is the combination. The only major constraint is ensuring that the combination results in an irreducible Markov chain, meaning that all components must move infinitely often. Other than that, considering an arbitrary sequence $(i_n)_n$ over $\{1,2,\ldots,p\}$ leads to a valid Gibbs sampler
$$G_{i_m}\circ\cdots\circ G_{i_2}\circ G_{i_1}$$
Comment: Changing the order at each iteration (or $p$th) is ok as well provided the order is not induced by earlier realisations of the chain.
Comment: Yes, ergodicity would still be guaranteed in that case, so things would be ok.
Comment: I think the OP wants to change the scan order in *each iteration*. So the one-step kernel will not be time-homogeneous, right?. However, I think their three-step kernel (if they have 3 components) will be time-homogenous.


How can I do cumulative operations across columns (not rows)?

Question: I have a table of customer state (0, 1 or NA) at times t1 ... t7:
<code>##   Customer t1 t2 t3 t4 t5 t6 t7
## 1        A  0  1  1  1  0  0  0
## 2        B  0  1  1  1  0  0 NA
## 3        C  0  1  1  1  0 NA NA
## ...
</code>
How can I modify the values across columns and row-wise (per customer), so that the leftmost 1 in a row is followed by 1s only?
<code>## desired result:
##
##   Customer t1 t2 t3 t4 t5 t6 t7
## 1        A  0  1  1  1  1  1  1
## 2        B  0  1  1  1  1  1 NA
## 3        C  0  1  1  1  1 NA NA
## ...
</code>
Example data:
<code>## example input df_in
df_in <- structure(list(Customer = c("A", "B", "C", "D", "E", "F", "G"
), t1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L), t2 = c(1L, 1L, 1L, 1L,
0L, 0L, NA), t3 = c(1L, 1L, 1L, 1L, 0L, NA, NA), t4 = c(1L, 1L,
1L, 1L, NA, NA, NA), t5 = c(0L, 0L, 0L, NA, NA, NA, NA), t6 = c(0L,
0L, NA, NA, NA, NA, NA), t7 = c(0L, NA, NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA,
7L))

## desired output df_out:
df_out <- structure(list(Customer = c("A", "B", "C", "D", "E", "F", "G"
), t1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L), t2 = c(1L, 1L, 1L, 1L,
0L, 0L, NA), t3 = c(1L, 1L, 1L, 1L, 0L, NA, NA), t4 = c(1L, 1L,
1L, 1L, NA, NA, NA), t5 = c(1L, 1L, 1L, NA, NA, NA, NA), t6 = c(1L,
1L, NA, NA, NA, NA, NA), t7 = c(1L, NA, NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA,
7L))
</code>
Comment: Please enter your sample data as copy/pasteable text, not as a picture. And share a little more about your data - is this a matrix or a data frame?
Comment: Your example output shows whether at least one "1" has been observed per customer in column 2 or later. So, in a way its row-wise logically cumulative - is that indeed your intended result?
Comment: @I_O yes logically, if a customer has ever started being 1 then that customer will be counted 1 in later collumns
Answer: One possible way ...
<code>library(tidyverse)

df_in <-
  structure(
    list(
      Customer = c("A", "B", "C", "D", "E", "F", "G"),
      t1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L),
      t2 = c(1L, 1L, 1L, 1L, 0L, 0L, NA),
      t3 = c(1L, 1L, 1L, 1L, 0L, NA, NA),
      t4 = c(1L, 1L, 1L, 1L, NA, NA, NA),
      t5 = c(0L, 0L, 0L, NA, NA, NA, NA),
      t6 = c(0L, 0L, NA, NA, NA, NA, NA),
      t7 = c(0L, NA, NA, NA, NA, NA, NA)
    ),
    class = "data.frame",
    row.names = c(NA, 7L)
  )

df_in |>
  pivot_longer(starts_with("t")) |>
  group_by(Customer) |>
  mutate(new_value = if_else(cumsum(value) >= 1L, 1L, value)) |>
  select(-value) |>
  pivot_wider(names_from = name, values_from = new_value)
#> # A tibble: 7 × 8
#> # Groups:   Customer [7]
#>   Customer    t1    t2    t3    t4    t5    t6    t7
#>   <chr>    <int> <int> <int> <int> <int> <int> <int>
#> 1 A            0     1     1     1     1     1     1
#> 2 B            0     1     1     1     1     1    NA
#> 3 C            0     1     1     1     1    NA    NA
#> 4 D            0     1     1     1    NA    NA    NA
#> 5 E            0     0     0    NA    NA    NA    NA
#> 6 F            0     0    NA    NA    NA    NA    NA
#> 7 G            0    NA    NA    NA    NA    NA    NA
</code>
Created on 2022-04-21 by the reprex package (v2.0.1)


Java HashMap size limit? Some keys are disappearing in Bigram Frequency Count

Question: I am writing a simple bigram frequency count algorithm in Java and encountering a problem I don't know how to fix.
My source file is a 9MB .txt file with random words, separated by spaces.
When I run the script limiting the input to the first 100 lines, I get a value of 1 for the frequency of the bigram "hey there".
But when I remove the restriction to only scan the first 100 lines and instead scan the entire file, I get a value of null for the same bigram search. The key/value pair in the HashMap is now null.
I am storing all the bigrams in a HashMap, and using a BufferedReader to read the text file.
What is causing the bigram (key) to be removed from or overwritten in the HashMap? It shouldn't matter if I am reading the entire file or just the first part of it.
public class WordCount {

public static ArrayList<String> words = new ArrayList<String>();
public static Map<String, Integer> bi_count = new HashMap<String, Integer>();

public static void main(String[] args) {

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader(args[0]));
        System.out.println("\nProcessing file...");

        while (br.readLine() != null) {
    //  for (int i = 0; i < 53; i++ ) {
            sCurrentLine = br.readLine();
            if (sCurrentLine != null) {
                String[] input_words = sCurrentLine.split("\\s+");
                for (int j = 0; j < input_words.length; j++) {
                    words.add(input_words[j]);
                }
            }
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            if (br != null)br.close();
            countWords();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

private static void countWords() {

    for (int k = 0; k < words.size(); k++) {
        String word = words.get(k);
        String next = "";
        if (k != words.size() - 1) {
            next = words.get(k+1);
        }

        String two_word = word + " " + next;

        if (bi_count.containsKey(two_word)) {
            int current_count = bi_count.get(two_word);
            bi_count.put (two_word, current_count + 1);
        }
        else {
            bi_count.put( two_word, 1);
        }

    }

    System.out.println("File processed successfully.\n");
}

Comment: Are your keys mutable? If you mutate a key that will cause it to "disappear".
Comment: arshajii is right. Anyway, I bet for poorly written `equals()/hashCode()`
Comment: Be more specific by providing your code
Comment: Added code to the original post
Comment: @billyswifty You call `readLine()` twice in every iteration, skipping every other line.
Comment: Can you provide your .txt file?
Comment: HashMap.size() is limited to Integer.MAX_VALUE or just over 2 billion.  If there is a bug in the 99.9% of the time it will be in your code, not code which has been tested by 10 million developers over 15+ years.
Answer: I'm not totally confident this is the cause of your problem, bot you are not reading all lines of your input file.
while (br.readLine() != null) {
        sCurrentLine = br.readLine();

The line read in the if() statement is not being processed at all - you are missing alternate lines.
Instead try this:
while ((sCurrentline = nr.readLine()) != null) {
   //now use sCurrentLine...
}

Comment: Thanks, that looked promising but now I am getting an OutOfMemoryError - I don't think it's recognizing the end of input. Any clue why?
Comment: I haven't found any obvious leaks, but in the method countWords() you could remove a word from your ArrayList once you've added it to the bigram Map. Be careful though: the indexes of all remaining words in the list will reduce by one.
Comment: @billyswifty I would have thought an OutOfMemoryError means you were running out of memory. I would check how much heap you are using and how much you have given the process.
Answer: This block of code is wrong because readline is called twice:
    while (br.readLine() != null) {
//  for (int i = 0; i < 53; i++ ) {
        sCurrentLine = br.readLine();
        if (sCurrentLine != null) {
            String[] input_words = sCurrentLine.split("\\s+");
            for (int j = 0; j < input_words.length; j++) {
                words.add(input_words[j]);
            }
        }
    }

I would suggest:
    while ((sCurrentline = nr.readLine()) != null)  {
        String[] input_words = sCurrentLine.split("\\s+");
        for (int j = 0; j < input_words.length; j++) {
                words.add(input_words[j]);
        }
    }

Comment: Why not `while(sCurrentLine != null) { String[] input_words.... }` Then you don't need the if block, and gets a nicer while loop instead of a do
Comment: You are absolutely right, my code was really overcomplicated. Updated using the suggestion of NickJ.
Comment: Thanks, that looked promising but now I am getting an OutOfMemoryError - I don't think it's recognizing the end of input. Any clue why?
Comment: ArrayList throws OutOfMemoryError, if you read more elements than an Array can hold.


Restrict specific page in grails webapplication

Question: I have a small website in grails which has two pages. First is start and second page is details pages. URL's for this pages are http://somecomp.com/start and http://somecomp.com/details.
Now my first page which is start page has a  tag which takes end user to details page.
I want to basically ensure that all my end user first comes on start page and then navigates to details pages. I want to restrict user if he directly opens http://somecomp.com/details.
Can this be done in grails and grrovy in some quick way. Any pointers will help.
Thanks JK
Answer: An easy approach could be to use a filter to intercept your request before details page and then check for some sort of flag maybe in session to see if start page was visited first.
Set that flag in your index or first action of your start page.
StartController
def index(){
   session.startVisited = new Date()
}

.
class StartPageFilters {
    def filters = {
        startCheck(controller: '*', action: '*') {
            before = {
                if (!session.startVisited ) {
                    redirect(action: '....')
                    return false
                }
            }
        }
    }
}

Answer: For the required scenario the genuine way to achieve the goal is to use Grails Webflow plugin link. For working example you can refer this git repository.
Comment: That's a big hammer for such a small nail.


Badminton Racket Sleeves

Question: Buying a badminton racket is easy. Buying the right one is far more difficult. Each time when you buy a new racket however, the new racket is accompanied by a racket sleeve. I always threw them away, because they occupied space in my sports bag.
Are those sleeves for show or do they serve a purpose?
Answer: For those of us with lots of clutter (shoes, water bottles, pens, etc) knocking about in the racket bag it can protect the frame from chips and the strings from becoming snagged on anything loose.
For those without racket bags it provides the only protection from everything.
Someone once suggested that it also provides protection from extremes of hot and cold, which might cause the racket to play differently for a while.

Badminton Racket Sleeves


dual of $H^1_0$: $H^{-1}$ or $H_0^1$?

Question: I have a problem related to dual of Sobolev space $H^1_0$. By definition, the dual of $H^1_0$ is $H^{-1}$, which contains $L^2$ as a subspace. However, from Riesz representation theorem, dual of a Hilbert space is itself (in the sense of isomorphism). It seems that this implies dual of $H^1_0$ is $H^1_0$ itself.
From the result, I think the latter argument is not right. But where's the mistake?
This problem may related to the question about Hilbert space and its dual
A paradox on Hilbert spaces and their duals
However I couldn't understand the answers well after reading several times...
Thanks so much!

Thanks a lot for all the kind solutions!
The following are my conclusions:

Dual space strongly depends on action we take. For example, in our case, if we take $H^1$ inner product, the dual space is $H_0^1$ itself; if taking $L^2$ inner product, the dual space is larger than $L^2$; and taking all possible dual actions, the dual is by definition $H^{-1}$.
As dual of one space, there are certainly identifications between these spaces. Notice that identification between infinite dimensional spaces can be bijective and ISOMETRIC! Indeed there is a simple example: sequence {1,2,3...} and {2,4,6...}. Just taking metric of the latter to be half.
Another basic example is simple elliptic equation in $H_0^1$:
$$
\int_\Omega \nabla u\cdot \nabla v+\int_\Omega uv=\langle f,v\rangle , \forall v\in H_0^1(\Omega)
$$
where $f\in H^{-1}$. This gives isometric identification of $H^{-1}$ and $H_0^1$.
Brezis's book reminds that we can't take two different inner products to give both Riesz representation at the same time. The example there is very instructive.
Comment: We do not identify the dual of $H_0^1$ with itself.  Brezis gives a nice summary http://books.google.com/books?id=GAA2XqOIIGoC&pg=PA136&lpg=PA136&dq=haim+brezis+functional+analysis+p+136&source=bl&ots=srqAO7z_c_&sig=iiKwc4FvWaOE8r6mueodZ0JmiMs&hl=en&sa=X&ei=WoU_U7XtEuTLsQS2wYHwAw&ved=0CEAQ6AEwAw#v=onepage&q&f=false
Comment: related: http://math.stackexchange.com/q/314113/9464
Comment: A very similar question: https://math.stackexchange.com/q/896249/166535
Comment: I would appreciate if you could introduce to me a reference concerning example 3 (the duality pair induced by elliptic equations)
Answer: Let me restate your question as follows. Let $\Omega$ be a nonempty open subset of $\mathbb{R}^d$. On the one hand, we have the sandwich:
$$
H_0^1(\Omega)\subset L^2(\Omega)\subsetneq H^{-1} (\Omega),\tag{*}
$$
where $H^{-1}(\Omega)$ is defined as  the dual of $H_0^1(\Omega)$. On the other hand, by Riesz representation theorem, $H^{-1}(\Omega)$ can be identified as $H_0^1(\Omega)$. This suggests that we may write
$$
H^{-1}(\Omega)=H_0^1(\Omega)\tag{**}
$$
which contradicts $(*)$ since $L^2(\Omega)$ is a proper subspace of $H^{-1}(\Omega)$.
The problem is that $(**)$ is not true if one considers "$=$" in $(**)$ as equality of sets rather than an isomorphism of Hilbert space.
As Terry Tao said:

"It is better to think of isomorphic pairs as being equivalent or identifiable rather than identical, as the latter can lead to some confusion if one treats too many of the equivalences as equalities. For instance, $\ell^2(\{0,1,2,\dots\})$ and $\ell^2(\{1,2,\dots\})$ are equivalent (one can simply shift the standard orthonormal basis for the former by one unit to obtain the latter), but one can also identify the latter space as a subspace of the former. It is fairly harmless to treat one of these equivalences as an equality, but of course one cannot do so for both equivalences at the same time."
Comment: The abstract setting of these identification matters ("Gelfand triple") is discussed in remark 3 of chapter 5 in Brezis' book.
Answer: The dual space $(H_0^1)^*$ is per definition the space of all linear and continuous functionals $(H_0^1)^*\to \mathbb R$.
There are different ways in generating this dual space:
(1) Riesz representation lets you represent each functional $f\in (H_0^1)^*$ by scalar product with an element $u_f\in (H_0^1)$
$$
f(v) = \langle u_f,v\rangle \quad\forall v\in H_0^1.
$$
(2) Every function $u\in L^2$ also generates a function in $(H_0^1)^*$ via
$$
f_u(v)=\int_\Omega uv\ dx  \quad\forall v\in H_0^1.
$$
You can even take $u\in H_0^1$.
If you look at the different functionals, then you see that the functionals in (1) are defined by the $H^1$-scalar product, the functionals in (2) are defined by the $L^2$-scalar product.
Answer: Riesz representation theorem is a : "representation" theorem,
and not an identification theorem. In the example 3 above, $f = - \Delta u + u$ can be represented by $u$, but cannot be identified by $u$, since
$f$ is in $H^{-1}$ whereas $u$ is in $H^1_0$.
Answer: As you have said, the dual space of $H_0^1$ is by definition $H^{-1}$. It can be identified with $H_0^1$ via isomorphism, but whether the identification is useful or not, it depends on the problem you are studying.
If, for example, you are studying abstract problems about Hilbert spaces and it's duals then, the identification is recommended and you gain a lot of time by using it. Take a look, for example, in Brezis book chapter 5.
On the other hand, when dealing with some practical problems, like for example, Partial Differential Equations problems, it is more convenient to use just $H^{-1}$. In some further examples its even better when you know a representation for elements of $H^{-1}$ in terms of $L^2$ functions. See, for instance, page 291 of Brezis book.

dual of $H^1_0$: $H^{-1}$ or $H_0^1$?