JavaFX TreeView java.lang.RuntimeException

Question: I get the following exception when running a simple program demonstrating the use of the TreeView control:
java.lang.RuntimeException: Error while creating node:class javafx.scene.layout.StackPane id:null
The error occurs when expanding or closing TreeItems with children.
Here is the SSCCE:
import static javafx.application.Application.launch;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;
public class TreeViewTest extends Application {
    Tab treeTab;
    @Override
    public void start(Stage primaryStage) throws Exception {
        TabPane pane = new TabPane();
        Scene scene = new Scene(pane,800,600);
        treeTab = new Tab("Tree");
        pane.getTabs().addAll(treeTab);
        primaryStage.setTitle("F(X)yz - Collision Test");
        primaryStage.setScene(scene);
        primaryStage.show();
        makeTree();
    }
    private void makeTree(){
        TreeItem<String> treeItemRoot = new TreeItem<> ("Root");
        TreeItem<String> nodeItemA = new TreeItem<>("Item A");
        TreeItem<String> nodeItemB = new TreeItem<>("Item B");
        TreeItem<String> nodeItemC = new TreeItem<>("Item C");
        treeItemRoot.getChildren().addAll(nodeItemA, nodeItemB, nodeItemC);
        TreeItem<String> nodeItemCA = new TreeItem<>("Item CA");
        TreeItem<String> nodeItemCB = new TreeItem<>("Item CB");
        nodeItemC.getChildren().addAll(nodeItemCA, nodeItemCB);
        TreeItem<String> nodeItemA1 = new TreeItem<>("Item A1");
        TreeItem<String> nodeItemA2 = new TreeItem<>("Item A2");
        TreeItem<String> nodeItemA3 = new TreeItem<>("Item A3");
        nodeItemA.getChildren().addAll(nodeItemA1, nodeItemA2, nodeItemA3);
        TreeView<String> treeView = new TreeView<>(treeItemRoot);
        treeTab.setContent(treeView);
    }
     public static void main(String[] args) {
        launch(args);
    }
}

This is running on jdk1.8.0_162 in Netbeans 8.2 on WIndows 7.
Please can anyone suggest an improvement to get rid of the error.
Thanks.
PS StackTrace:
java.lang.RuntimeException: Error while creating node:class javafx.scene.layout.StackPane id:null
NODE INFORMATION
Node:StackPane@5bb0a705[styleClass=tree-disclosure-node] Class:class javafx.scene.layout.StackPane Id:null
Children:[StackPane@401249ef[styleClass=arrow]]
PARENT INFORMATION
Node:TreeViewSkin$1@72fac9c9[styleClass=cell indexed-cell tree-cell]'Root' Class:class com.sun.javafx.scene.control.skin.TreeViewSkin$1 Id:null
Children:[Text[text="Root", x=0.0, y=0.0, alignment=LEFT, origin=BASELINE, boundsType=LOGICAL_VERTICAL_CENTER, font=Font[name=System Regular, family=System, style=Regular, size=15.0], fontSmoothingType=LCD, fill=0x333333ff]]

    at org.fxconnector.node.SVNodeFactory.createNode(SVNodeFactory.java:56)
    at org.fxconnector.StageControllerImpl.createNode(StageControllerImpl.java:775)
    at org.fxconnector.StageControllerImpl.lambda$new$10(StageControllerImpl.java:231)
    at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.FXCollections$UnmodifiableObservableListImpl.lambda$new$62(FXCollections.java:929)
    at javafx.collections.WeakListChangeListener.onChanged(WeakListChangeListener.java:88)
    at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:164)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at com.sun.javafx.collections.VetoableListDecorator.lambda$new$31(VetoableListDecorator.java:76)
    at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
    at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
    at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
    at javafx.collections.ModifiableObservableListBase.remove(ModifiableObservableListBase.java:183)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:332)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:221)
    at javafx.scene.Parent.impl_toBack(Parent.java:644)
    at javafx.scene.Node.toBack(Node.java:1756)
    at com.sun.javafx.scene.control.skin.TreeCellSkin.updateDisclosureNode(TreeCellSkin.java:186)
    at com.sun.javafx.scene.control.skin.TreeCellSkin.layoutChildren(TreeCellSkin.java:211)
    at javafx.scene.control.Control.layoutChildren(Control.java:578)
    at javafx.scene.Parent.layout(Parent.java:1087)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Scene.doLayoutPass(Scene.java:552)
    at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2397)
    at com.sun.javafx.tk.Toolkit.lambda$runPulse$29(Toolkit.java:398)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:397)
    at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:424)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:518)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:498)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:491)
    at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$403(QuantumToolkit.java:319)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: Error while creating node:class javafx.scene.layout.StackPane id:null
NODE INFORMATION
Node:StackPane@3fb4f2e2[styleClass=tree-disclosure-node] Class:class javafx.scene.layout.StackPane Id:null
Children:[StackPane@b52262b[styleClass=arrow]]
PARENT INFORMATION
Node:TreeViewSkin$1@330b4596[styleClass=cell indexed-cell tree-cell]'Item A' Class:class com.sun.javafx.scene.control.skin.TreeViewSkin$1 Id:null
Children:[Text[text="", x=0.0, y=0.0, alignment=LEFT, origin=BASELINE, boundsType=LOGICAL_VERTICAL_CENTER, font=Font[name=System Regular, family=System, style=Regular, size=15.0], fontSmoothingType=LCD, fill=0x333333ff]]

    at org.fxconnector.node.SVNodeFactory.createNode(SVNodeFactory.java:56)
    at org.fxconnector.StageControllerImpl.createNode(StageControllerImpl.java:775)
    at org.fxconnector.StageControllerImpl.lambda$new$10(StageControllerImpl.java:231)
    at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.FXCollections$UnmodifiableObservableListImpl.lambda$new$62(FXCollections.java:929)
    at javafx.collections.WeakListChangeListener.onChanged(WeakListChangeListener.java:88)
    at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:164)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at com.sun.javafx.collections.VetoableListDecorator.lambda$new$31(VetoableListDecorator.java:76)
    at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
    at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
    at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
    at javafx.collections.ModifiableObservableListBase.remove(ModifiableObservableListBase.java:183)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:332)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:221)
    at javafx.scene.Parent.impl_toBack(Parent.java:644)
    at javafx.scene.Node.toBack(Node.java:1756)
    at com.sun.javafx.scene.control.skin.TreeCellSkin.updateDisclosureNode(TreeCellSkin.java:186)
    at com.sun.javafx.scene.control.skin.TreeCellSkin.layoutChildren(TreeCellSkin.java:211)
    at javafx.scene.control.Control.layoutChildren(Control.java:578)
    at javafx.scene.Parent.layout(Parent.java:1087)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Scene.doLayoutPass(Scene.java:552)
    at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2397)
    at com.sun.javafx.tk.Toolkit.lambda$runPulse$29(Toolkit.java:398)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:397)
    at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:424)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:518)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:498)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:491)
    at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$403(QuantumToolkit.java:319)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: Error while creating node:class javafx.scene.layout.StackPane id:null
NODE INFORMATION
Node:StackPane@4a2a9995[styleClass=tree-disclosure-node] Class:class javafx.scene.layout.StackPane Id:null
Children:[StackPane@5483de69[styleClass=arrow]]
PARENT INFORMATION
Node:TreeViewSkin$1@269becf3[styleClass=cell indexed-cell tree-cell]'Item C' Class:class com.sun.javafx.scene.control.skin.TreeViewSkin$1 Id:null
Children:[Text[text="", x=0.0, y=0.0, alignment=LEFT, origin=BASELINE, boundsType=LOGICAL_VERTICAL_CENTER, font=Font[name=System Regular, family=System, style=Regular, size=15.0], fontSmoothingType=LCD, fill=0x333333ff]]

    at org.fxconnector.node.SVNodeFactory.createNode(SVNodeFactory.java:56)
    at org.fxconnector.StageControllerImpl.createNode(StageControllerImpl.java:775)
    at org.fxconnector.StageControllerImpl.lambda$new$10(StageControllerImpl.java:231)
    at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.FXCollections$UnmodifiableObservableListImpl.lambda$new$62(FXCollections.java:929)
    at javafx.collections.WeakListChangeListener.onChanged(WeakListChangeListener.java:88)
    at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:164)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at com.sun.javafx.collections.VetoableListDecorator.lambda$new$31(VetoableListDecorator.java:76)
    at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
    at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
    at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
    at javafx.collections.ModifiableObservableListBase.remove(ModifiableObservableListBase.java:183)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:332)
    at com.sun.javafx.collections.VetoableListDecorator.remove(VetoableListDecorator.java:221)
    at javafx.scene.Parent.impl_toBack(Parent.java:644)
    at javafx.scene.Node.toBack(Node.java:1756)
    at com.sun.javafx.scene.control.skin.TreeCellSkin.updateDisclosureNode(TreeCellSkin.java:186)
    at com.sun.javafx.scene.control.skin.TreeCellSkin.layoutChildren(TreeCellSkin.java:211)
    at javafx.scene.control.Control.layoutChildren(Control.java:578)
    at javafx.scene.Parent.layout(Parent.java:1087)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Scene.doLayoutPass(Scene.java:552)
    at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2397)
    at com.sun.javafx.tk.Toolkit.lambda$runPulse$29(Toolkit.java:398)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:397)
    at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:424)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:518)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:498)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:491)
    at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$403(QuantumToolkit.java:319)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)

Comment: That got me worried so I copied the file to a 'clean project - I still get the error when I run it. However, googling org.fxconnector.node.SVNodeFactory has led me to the ScenicView source code. I then remembered I had ScenicView running!!!
Comment: After the closing ScenicView the test program now works as expected. Thanks for your comment. I still think it is probably a bug as I don't think that ScenicView should cause a RuntimeException.
Comment: glad you found the reason :) Most probably a bug, I would suspect ScenicView to be the culprit ...
Comment: Just to confirm, had the exact same problem here. Running Javafx 11.0.2 under linux and also saw the stacktraces. I also had ScenicView running in the background. Closed it and the stacktrace is gone! :) thanks @jimbo8 for leading me to it :)
Comment: hmm ... worksform in 8_151 and 9_01 - would not expect an "intermediate" misbehaviour in 8_161. On the other hand: faintly remember having seen a weird bug around treeView recently, but can't find it ... could you please add the stacktrace?
Comment: hmm ... org.fxconnector is not a core fx package, or is it? Where does it come from?
Answer: I encountered this as well so I'll put the @jimbo8's comment as the answer:
This is caused by ScenicView.
Close ScenicView and you won't get this error anymore.


How to save TimeStamp in single column using hibernate

Question: How do I save timestamps in mysql DB using a hibernate entity in specific format.
Hibernate Entity Class:
@CreationTimestamp
@Column(name="created_on", nullable = false, updatable = false)
private LocalDateTime createdOn;

@UpdateTimestamp
@Column(name="updated_on", nullable = false)
private LocalDateTime updatedOn; // = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

I have also used DateTimeFormatter and SimpleDateFormat but they all gave the same error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unsupported property type [java.time.format.DateTimeFormatter] for @CreationTimestamp or @UpdateTimestamp generator annotation

application.properties:
spring.jpa.hibernate.ddl-auto=update

Comment: Which (exact) version of Hibernate do you use?
Answer: The error suggests that one of the non-static fields is of type DateTimeFormatter and is annotated with @CreationTimestamp or @UpdateTimestamp which is illegal. These annotation can only be applied to fields of type java.util.Date, java.util.Calendar, java.time.LocalDateTime etc.


Spin in Ice Hockey Shots?

Question: Spin is highly important in professional ball games such as tennis, football (soccer) and basketball. In order to shoot with spin in tennis, you need to have enough flexible hands/arms and learn the proper technique. Spin also helps to score in basketball because side-spinned balls turn more easily to the goal. In football (soccer), spinned shots are highly unpredictable for the goalkeeper and defence, making scoring more probable with the surprise element. Golf balls can travel father away due to spin. Spins are everywhere and its understanding can be a real advantage!
The importance of spin in ball games make me wonder whether spin is also used in ice hockey or could it be used? I feel topspin and backspin are very rare in hockey. So

How is spin done in ice hockey?

What kind of spins are they?

Side-spins? And when are they used? Do they deflect the puck in the air?
Answer: First, in hockey the blade is curved.  This will lead to the puck spinning clock wise or counter clock wise depending on if the player is right or left handed, and if the shot was taken with the front or back of the stick.
Here is a link about the spin and sticks
There are often times where the puck will have top spin or back spin.  These are not always intentional, as hockey is a fast paced game played in a relatively small area.  Players will mishit the puck or it may get deflected by a defender.  Also with the goalie wearing pads and taking up a significant portion of the net, the top spin or back spin may just hit the goalie.  The tight side spin will allow for more control and velocity of the shot into the open areas of the net.
You can often see defensemen flip the puck out of the defensive zone with some top spin to avoid icing the puck, but in order to clear the defensive zone.
The deception that you refer to in other sports is created in hockey mostly by screening the goalie and deflecting pucks.  The player in front of the net will try and get in between the goalies line of sight with the puck.  He may also try and tip the puck in mid air with his body or stick.  These deflections make the shot unpredictable to the goalie.
Here is a link of a tip in
Here is a link of a goalie screen
Comment: @hhh Spin shouldn't add or decrease effectiveness of a deflection.  Usually it is just good hand eye coordination by the deflector to get a piece of the puck and change its direction.  Without being to scienftific... the puck is pretty low friction, but something rotating in a direction would cause it to move in that direction due to changes in air pressure created.  This can be seen by a curveball in baseball or a top spin or slice shot in tennis.
Comment: @edmastermind29 I think of it more in relation to baseball.  The puck is flat on the top and bottom which changes things slightly.  [This talks about how a curveball works](http://ffden-2.phys.uaf.edu/211_fall2002.web.dir/jon_drobnis/curveball.html).  Also the gear effect has to do with the way the clubs work in golf.  The golf ball rolls into the center from an edge to create spin.  I believe if you had a completely flat stick with a "softer" center than edges then the gear effect could come into play.
Comment: @edmastermind29 However sticks are curved and a wrist shot will spin off the blade as in the link in the answer.  A slap shot may spin off or "knuckle" depending on how it is struck.  The aerodynamic properties then take over in flight and the puck will move according to the angular velocity and air density.  Realize that it is a short distance a shot travels, as well as with pretty good velocity so the air displacement may not move the puck too much.  I cant see a scenario where it would spin the opposite direction.
Comment: +1 excellent points from the first reference: `"Spinning gives the puck more stability"`, `"A blade that tips backward is said to be more "open faced", very much like a 9 iron is compared to a 3 iron in golf."` -- golf/tennis really helps to understand elements in other sports! I personally use more curved blade precisely because it makes control far easier and a surprise element with fast upshot. Yes and does the spin add deflection to the shot? Does the spin make the puck deflect in the air or is the flight path totally straight?
Comment: @hhh players usually want stability on their shots because they are shooting at a certain area.  If they didn't want stability and want to incorporate some randomness or instability, then they would turn to a more flat stick blade.  This is seen more with defensemen who shoot from a distance with slap shots more than with precise wrist shots.
Comment: @diggers3 More so out of curiosity, how would you interpret the "[gear effect](http://sports.stackexchange.com/a/4072)" in regards to your statement, "something rotating in a direction would cause it to move in that direction"? The "gear effect" and your statement seem to contradict...but am looking for more of a practical than scientific response.
Comment: @diggers3  So, I assume that there is some truth to the [knucklepuck](http://www.youtube.com/watch?v=oqq-glymrRs).  Great explanation. Thanks for the responses.
Comment: @edmastermind29 without a doubt the knucklepuck is real.  I've never seen someone flip it on the edge (I can't see how you would have time), but it happens where a puck will roll on its edge and be hit off center and knuckle.
Answer: A hockey puck is a very flat cylinder. We may compute very easily the Moment of Inertia of a hockey puck in both the axis of symmetry (going through the center of the puck from top to bottom) and the central axis (going through the sides of the puck) quite easily.
The moment of inertia around the axis of symmetry is 27 square inch square ounces, while moment of inertia around the central axis is 28.5 inch square ounces. These quantities are not vastly different, and if you grab a hockey puck, it's about as easy to flip as it is to spin.
The difference, however, is that a hockey puck's stable attitude is going to be laying flat. As such, most of the time when you play with the puck, it's going to tend to lay flat on the ice.
It's not hard to flip a puck end-over-end, but unlike the aerodynamics of a ball, a hockey puck has relatively large flat surfaces. This makes controlling the puck in such a way very difficult, and it's quite hard to shoot a puck if it's not laying flat. Due to the motion of a shot and the geometry of a stick blade, shooting a puck on-edge makes it much more prone to go high, and it's hard to control the accuracy. In addition, it's much harder to shoot the puck with any high velocity, as the puck doesn't sit well in the blade of the stick.
Like a football, a puck flipping end-over-end will bounce unpredictably. Occasionally, players will attempt to surprise a goalie by flipping the puck to try to get a lucky bounce, and even in the pros, it happens a few times a year that a goalie lets one by.
However, flipping the puck at the goalie like this is a low-probability play, and it is one that is nearly guaranteed to result in a change of possession. Consequently, it's rarely done.
It's much better to try to shoot the puck hard and accurate in order to beat the goalie in a spot where they're not expected to make a save.
In this case, the spin of the puck actually does very little in terms of its dynamics. The puck is too heavy and the flight times are too short for the Magnus Effect to have much of an impact on the puck's trajectory, and the moments of inertia being so close in value mean that the rotational effect does very little to stabilize the puck. The spin is a consequence of the shot mechanics -- stick blades are curved to give the player control over the puck while handling it and shooting it, not to induce spin.
The pace of hockey is extremely fast. Any deception is better suited by using your other players (e.g. fake a shot and pass to an open player with a better view of the net) than attempting to play trickery with a shot. Even a 65 mph shot, which is fairly slow, especially for the pros, will travel 25 feet in about a quarter of a second. Speed and accuracy, not deception, are the shooter's best friend.

Spin in Ice Hockey Shots?


What values of $p$ make this a transient chain?

Question: Suppose we have a Markov chain with state space $S = \{0, 1, 2, \dots \}$  and probabilities
$p(x, x + 2) = p$, $p(x, x - 1) = 1-p$ for $x > 0$ and $p(0, 2) = p$ and $p(0, 0) = 1 - p$
I would like to find the values of $p$ that make this a transient chain.  So I need to find $\alpha(x)$ such that $\inf \alpha(x) = 0$ and
$\alpha(x) = p\alpha(x + 2) + (1-p)\alpha(x - 1)$
I'm having a bit of trouble solving this difference equation.  Trying $\alpha(x) = a^x$ doesn't seem to work.
Comment: Your transitions probabilities don't add up to 1.
Comment: Actually $\alpha(x)=a^x$ *does* work.
Comment: @ByronSchmuland Typo, just corrected.
Answer: For reference, this is Exercise 2.4 from Gregory Lawler's Introduction to Stochastic Processes.
Following Lawler, we define $\alpha(x)$ to be the probability that the process ever
 visits state 0, starting at $x$. As for any left-continuous random walk, this function
is of the form $\alpha(x)=a^x$ where $a$ is the smallest positive root of the
equation $z=\sum_{n=0}^\infty p(1,n) z^n$. Here $p(1,n)$ is the transition probability from
state $1$ to $n$.
In our case, this equation reads $z=(1-p)+pz^3$ and the solution $a$ will be strictly less
than one if and only if $p>1/3$. This is when the chain is transient.


Forecasting with lower frequency independent

Question: I'm trying to forecast a time series variable that was sampled on a weekly frequency. All of the potential independent variables I'm considering are also available on a weekly frequency.
The catch is that the independent variable forecasts are only available on a monthly basis. This is also the frequency that the model forecast will be reported.
Is there an approach that would let me take advantage of my higher frequency dataset while also capable of generate forecasts at a lower frequency?
Answer: There are two approaches. Let's say $y_t,x_{it}$ are dependent and independent variables available historically.
One way is to develop a model which forecasts at weekly frequency, then down sample (aggregate) the forecast to monthly. You'll need to up sample (interpolate) $x_{i,t+h}$ independent variables between month ends to weekly forecasts.
The other way is to build the model at monthly frequency. Instead of having one series as above, you'll have four series $y_{k+t},x_{i,k+t}$, where $k=0,1,2,3$. You'll use all four series to get the estimate of model parameters. This way you have a monthly forecasting model.
Comment: Could you expand on the second approach? I don't quite understand the reasoning behind making four series. Does $k$ represent the week within the month?
Comment: If you estimate a model at monthly frequency, then your series could be t=Jan 1, Feb 1, Mar 1, Apr 1 etc. The problem is that you'll be using only 25% of your data. That's why you have three other series such as Jan 8, Feb 8, Mar 8... , and Jan 15, Feb 15, Mar 15...
Comment: Sorry, I'm still having trouble understanding how this approach works. Do you estimate 4 models, or 1? If there is only one time series model, what are the dependent and independent variables?
Comment: You estimate one model, of course, but using 4 series. If it's OLS, then you can simply merge the series, with ARIMA it's a bit trickier


Sequence sub sequences!

Question: There is a sequence: $a_0, a_1, a_2, a_3, a_4, \ldots$
If $a_n=a_{a_{n−1}}, a_2=5$ and $a_{2014}=2015$,  what are all possible values of $a_{2015}$?
I've tried to set $a_2=5$ and therefore $a_3=a_5$. From that I got that all even numbers greater than $2$ have to be equal, and that all odd numbers greater than $3$ had to be equal. Please help!
Comment: Your question is very unclear, and you should probably format your math. Do you think you can take care of these problems?
Answer: We know $a_{2} = 5$, and since $a_{n} = a_{a_{n - 1}}$, we have: $$a_{3} = a_{a_{2}} = a_{5}.$$  Similarly, $$a_{4} = a_{a_{3}} = a_{a_{5}} = a_{6}.$$  And further $$a_{5} = a_{a_{4}} = a_{a_{6}} = a_{7}.$$
So it is not hard to see that we have $a_{3} = a_{5} = a_{7} = \dots$, and also $a_{4} = a_{6} = a_{8} = \dots$
For the rest, please see Brian M. Scott's comment to this answer.
Comment: @mfl: You can't. In fact it appears to be consistent that the terms with odd index all be $5$ or all be the same positive even integer.
Comment: A proof that the terms with odd index can be any positive even integer can be found [here](http://math.stackexchange.com/a/1002040/12042).
Comment: How can you infer from $a_{2015}=a_3$ that $a_{2015}=5?$
Comment: @mfl My mistake, I wrote up this solution thinking $a_{3} = 5$ at the end...

Sequence sub sequences!


Conectar um lineEdit a um método de uma classe

Question: estou tendo uma problema que dá a seguinte mensagem

TypeError: consultaCodigo() missing 1 required positional argument:
'self'

Eu tenho um projeto que até o momento funciona bem em paradigma estruturado, mas estou tentando reescrever o código em POO.
Tenho o seguinte arquivo py " conexao" com o seguinte código:
import mysql.connector

# Classe responsável pela conexão ao banco de dados

class Conexao():
    def __init__(self):
        try:
            self.conectar = mysql.connector.connect(host="localhost", user="root", database="db_farmacia", password="")
        except mysql.connector.Error as e:
            print(e)
        return self.conectar

    def ConsultarTabela(self, consulta):
        try:
            self.cursor = self.conexao_db()
            lista = self.cursor.execute("SELECT nome_produto, preço FROM tb_produtos WHERE codigo=?;", [consulta])
            return lista.fetchall()

        except mysql.connector.Error as e:
            print(e)
        return self.conectar

E o seguinte arquivo py com o seguinte código:
from PyQt5 import uic, QtWidgets, QtCore, QtGui
from conexao import Conexao

#Função que insere código

# OBS: inserir_codigo = é um linedEdit

class frenteCaixa:

    def consultaCodigo(self):

        codigo = pdv.inserir_codigo.text()
        pdv.inserir_codigo.setText("")
        consultados = Conexao()
        busca = consultados.ConsultarTabela(codigo)
        print(busca)

app = QtWidgets.QApplication([])
pdv = uic.loadUi("interface_2.ui")
tela_total = uic.loadUi("interface_total.ui")
dial_forma_pgto = uic.loadUi("dialogo_forma_pgto.ui")

pdv.inserir_codigo.returnPressed.connect(frenteCaixa.consultaCodigo) # Utiliza o enter para enviar o código sem necessidade do pushButtom
pdv.showFullScreen()
pdv.show()
app.exec()

O meu erro está no código : pdv.inserir_codigo.returnPressed.connect(frenteCaixa.consultaCodigo). No código estruturado está : pdv.inserir_codigo.returnPressed.connect(funcao_1) e funciona perfeitamente. No que eu estaria errando?
Answer: como sua classe esta com  o atributo self ela precisa ser instanciada antes de usar
você pode instanciar e chamar o metodo consultaCodigo() ou transformar o seu metodo em um class method
# 1 solução
pdv.inserir_codigo.returnPressed.connect(frenteCaixa().consultaCodigo)

# 2 solução
@classmethod
def consultaCodigo(cls):
     #seu codigo

pdv.inserir_codigo.returnPressed.connect(frenteCaixa.consultaCodigo)

Comment: Olá JooJ, obrigado pela resposta e pela ajuda, a solução 1 não faz mais travar, mas não consigo enviar também, ao pressionar enter no lineEdit, ele deveria enviar o código, isso não está funcionando.

Consegui funcionamento na solução 2, mas sem importar o módulo conexão, incluí a consulta no banco de dados e fetchall no código mesmo e com o class method funcionou!

Muito obrigado, depois preciso refazer com calma o módulo "Conexao".
Comment: Em todo caso seu comentário já ensinou muito sobre POO!


SQL: Start Date > 1 October Previous Year

Question: I'm building a query which only triggers if the start date is greater than 1 October Previous Year.
I imagine its something similar to using DATEADD below, but i'm not sure what to use instead of GETDATE. Thanks
WHERE Start_Date > DATEADD(year,-1,GETDATE())
Comment: Tag only the database that you use.
Answer: If you're using SQL Server, you could use DATEFROMPARTS:
WHERE Start_Date > DATEFROMPARTS(YEAR(GETDATE())-1,10,1)

Note that this will return the prior year regardless of when in the year is it. So, for example, even on 2021-12-31 the date 2020-10-01 would be returned from the expression.


O Visual Studio 2013 é compatível com SQL Server 2014?

Question: Conectei a tabela do SQL com o Visual Studio, mas na hora de mexer na tabela aparecia uma mensagem dizendo que o SQL Server não era compatível.
Se não for mesmo, terei que baixar outro Visual Studio ou banco?
Answer: Se está dizendo é porque existe alguma incompatibilidade, mas em maiores informações fica difícil ajudar.
Em tese é possível usar ambos juntos mas pode precisar fazer algumas coisas. Há uma resposta no SO mostrando que é necessário instalar uma atualização específica. Provavelmente resolverá seu problema.
Se isto não resolver pode precisar de algo mais, mas tem desenvolvedores usando ambos. ou poste mais detalhes.
De qualquer forma considere atualizar o Visual Studio para o 2015. Ele tem muitas vantagens. Ou para oi mais novo, não faz mais sentido manter versão antiga com o Community que é gratuito e praticamente completo.
Comment: Cara, muito obrigado!
Consegui resolver aqui, era só atualizar mesmo kkkkk... Obrigado novamente!
Comment: @MárcioCristian a melhor forma de dizer obrigado aqui é aceitando a resposta, como você fez, e votando na resposta, que espero, em breve, você poderá fazer. Veja o [tour]. Você poderá votar em qualquer post no site assim que ganhar mais 2 pontos.


Does Always On in Sql Server 2016 work better with Windows Server 2016?

Question: I am interested in using Sql Server 2016's upgraded Always On features.
But my DBA has said that these features work better with Windows Server 2016.  He suggested waiting for Windows Server 2016 to release before we start using those features.
The only feature that I am seeing that needs Windows Server 2016 is if you are running across domains.  But I would be running on a single domain, so I am not worried about that.
Is there anything else in Sql Server 2016 that wants Windows Server 2016 to work well?  Or would I be fine with a Windows Server 2012 R2?
Answer:
Is there anything else in Sql Server 2016 that wants Windows Server
  2016 to work well? Or would I be fine with a Windows Server 2012 R2?

There are a slew of new and updated features in Windows Server 2016. Unless any of them are specifically important to you, for example enhancements to storage spaces and CSV storage, I wouldn't specifically call out a need to wait for it.
This will depend, though, on how nice of a system administrator you are. Once Windows Server 2016 comes out, will you build a new system to allow the DBA to migrate?
Maybe you'll want to wait for supportability reasons (granted 2012R2 is still mainstream support)?
There is nothing inside of SQL Server that is really dependent upon Windows 2016 with AlwaysOn. Yes, you have greater flexibility with things like gMSAs, AD-less clusters, etc., but nothing specific inside of Windows that SQL Server hooks into.
Having said all of this, I'd either wait for Windows 2016 to come out or build a 2012R2 cluster for the AlwaysOn Availability Groups and know that we can do a rolling OS upgrade after Windows 2016 comes out. It's double work but you get your cluster now (vs waiting) and can upgrade the same cluster with rolling OS upgrades (so double work).


How to remotely edit a line containing double quotes and variables using sed across ssh?

Question: I have a sed command that works perfectly if I run it locally on Ubuntu or our embedded client Arago:
sed -i 's/export PART="$1"/export PART="A"/' flash.sh

This results in exactly what I need on both versions of sed, a line that changes:
export PART="$1"

to
export PART="A"

My problem is, I need to run that same command across a network to the embedded client so I tried this on an Ubuntu server using bash, to an Arago client using sh:
ssh -n -o stricthostkeychecking=no firstname.lastname@example.com sed -i 's/PART="$1"/PART="A"/' flash.sh

Which results in a line that contains:
export PART=A"$1"

The substitution command needs to stay inside the single quotes so the double quotes are passed as literals, or maybe there's a better way to keep the double quotes in the two strings?  This looks to me like the $1 is simply being ignored like it's empty and the "A" is being passed as A and replacing the end of PART=.  I've tried encapsulating the command in single and double quotes, which both result in the same thing.  I've also tried escaping the quotes with backslashes, same result.  I think this is something with quote expansion with sh that I simply don't understand.  Or possibly something I don't understand with ssh.
I've read through a number of other threads that are similar, but none of them dealt with using ssh to run the command remotely.  I'm no longer a novice at sed, but this one has become quite the puzzle for me.
Answer: ssh -n -o stricthostkeychecking=no firstname.lastname@example.com 'sed -i "s/export PART=\"\\\$1\"/export PART=\"A\"/" flash.sh'

Comment: This method works perfectly!  Thanks Dimitre!  I was close to this solution at one point, but didn't know about using triple backslashes to escape the $ character.  Thanks again.
Answer: You can switch back and forth to get the quoting you need. try this
ssh -n -o stricthostkeychecking=no firstname.lastname@example.com sed -i 's/PART='"$1"'/PART="A"/' flash.sh
# -------------------------------------------------------------------^^^^^^

OR if you really need the value of $1 surrounded by dbl-quotes,
ssh -n -o stricthostkeychecking=no firstname.lastname@example.com sed -i 's/PART='\"$1\"'/PART="A"/' flash.sh
# -------------------------------------------------------------------^^^^^^^^

You do want $1 to come from your local machine (not the ssh'd to machine), right?
I hope this helps.
P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.
Comment: Hi @shellter, I believe he don't want to expand $1 at all.
Comment: Hi @DimitreRadoulov : yes,  you're probably right. I took the sentence (fragment) "This looks to me like the $1 is simply being ignored like it's empty" to mean that he *did* want to pass in a value for $1, but now I can see it is probably meant to be a string literal. Oh well. Good luck to all! :-)
Comment: Thanks for the help, I tried both methods above, and both result in the same problem I was having before:

   export PART=A"$1"

And you're correct, I need the files to have a quoted variable:  "$1".  I'm going to try the next solution below, and I'll report back.  Thanks again.


Cakephp sitemap for google

Question: I am trying to make my first sitemap to use with google for the site that I am making. The thing is that all the displayed content is static, all the solutions i found are related with the usage of models. How can I make a sitemap for a Cake site like this? Also, is it possible to do it using the Routes, on routes.php file or does it need to be made in a more complex way?
I am using CakePHP 2.4.4.
Comment: what have you tried so far? please show some code. Also: You should always mention the exact cakephp version you are using.
Comment: it can - in what way is writing a static xml file and putting it in your webroot _not_ a solution? Don't do things the hard way just for the sake of it.
Comment: @mark I don't have anything yet, as I don't know what kind of approach I should have.
Comment: @SunT sounds like you're over complicating things - if you don't have models your site is static. Write a static sitemap, and "that's it".
Comment: possible duplicate of [How to create sitemap for cakephp](http://stackoverflow.com/questions/3789841/how-to-create-sitemap-for-cakephp)
Comment: @AD7six And can that be done using something like ` 'home', 'action' => 'index'));?>`, or should I use it with the plain URL?
Answer: In case you don't need any dynamic content (from the way you asked your question there is no way of knowing if you do), just create a static
sitemap.xml

in your /webroot directly
That's it.
Nothing else necessary.
Always keep things as simple as possible.

Cakephp sitemap for google


geometric intuition behind rationalizing denominator in order to find limits

Question: Given a question such as: compute the limit
$\lim_{t\to0}\frac{\sqrt{t^2+9}-3}{t^2}$
the answer becomes apparent only once we rationalize the denominator.
My question is: why? (i.e. how does this work)? what are we really doing here, and what is the geometric/algebraic significance of this. To clarify, I obviously see its usefulness, i just have no intuition as to how it works.
Comment: Rationalizing the rational function is merely a technique that works well in these scenarios.  It is merely an algebraic manipulation that clears up the mess.
Comment: I don't see what is to be rationalized in the denominator of your own example. Maybe you meant to ask about $\lim \limits _{t \to 0} \dfrac {t^2} {\sqrt {t^2 + 9} - 3}$?
Comment: @JoeGaige: In that case, what you rationalize in your example is the *numerator*.
Comment: the limit only becomes apparent after multiplying by $\frac{\sqrt{t^2+9}+3}{\sqrt{t^2+9}+3}$
Answer: When an expression goes to $0/0$ in a limit, it's because there's some factor in the top and bottom going to zero.  Fun limit problems hide that factor.  In your example the factor is $t^2$.  To hide it, write $t^2 +9 -9$ and factor by
difference of squares: $(\sqrt{t^2+9}-3)(\sqrt{t^2+9}+3)$ and discard the bit which doesn't go to zero.


Mann-Kendall test in R using 'Kendall' package: exact test or approximation?

Question: Problem: I am trying to perform a test for trend using the MannKendall() function available in the Kendall R package. My number of data points is n=11. For this reason, I would prefer an exact test, however I am unable to find in the documentation if the MannKendall() function performs an exact test or if it uses a normal approximation.
In the literature I find that for n <=10 an exact test is done, and for n>10 an approximation is used. I'm wondering if this is what the function does?
Answer: MannKendall calls Kendall which calls the FORTRAN routine TAUK2.
You can find out the details by reading the FORTRAN source of TAUK2 at this link on Github. Based on the comments in the code, I think it performs the exact test if the data x has no ties and uses the normal approximation otherwise, but you should probably check this as I don't know anything about these methods. (It also gives a reference to a book by Kendall.)
This comment appears on line 29:
c sw is true if at least one of X or Y has no ties

(but here, one of the vectors is just 1:N and the other is the data) and then later:
C USE EXACT METHOD IF THERE ARE NO TIES
C
If (sw) Then
C
C CALCULATE P-VALUE USING EXACT METHOD
C
IS = IFIX(S)
PROB = 1.0 - PRTAUS(IS,N,IER1)
If (IER1.EQ.0) Then
SLTAU = 2.0 * PROB
If (PROB.GE.0.5) SLTAU = 2.0 * (1.0-PROB)
Return
Endif
C
C IF THERE ARE TIES, NEED ATLEAST SAMPLE SIZE OF ATLEAST 3
C
Elseif (N.GT.3) Then
C
C USE CONTINUITY CORRECTION FOR S
SCOR = 0.0
If (S.GT.0) SCOR = S - 1.0
If (S.LT.0) SCOR = S + 1.0
C CALCULATE P-VALUE USING NORMAL APPROXIMATION
ZSCORE = SCOR / SDS
PROB = ALNORM(ZSCORE,.FALSE.)
SLTAU = 2.0 * PROB
If (PROB.GE.0.5) SLTAU = 2.0 * (1.0-PROB)
Return
Endif
Endif

Comment: The ManKendall function is just `function (x){Kendall(1:length(x), x)}`
Comment: This seems to be the code for the Kendall function in the package not the MannKendall function?
Answer: Using the information provided by Flounderer, I think I finally understand.
By typing  MannKendall into R, I indeed get that the function is really calling the Kendall function as Kendall(1:length(x), x).
The Kendall function requires various considerations.  In my case, the values of X have no ties.
Case 1: No Ties:
Subcase 1: length(x)<9: In this case the probabilities are computed using a recurrence relation described in kaarsemaker and van wijngaarden 1953.
Subcase 2: length(x)>=9: In this case the probabilities are calculated using a modified edgeworth series. What is important to note here is that I don't think any asymptotics are being called, but rather you are approximating the cumulative probability density by truncating an infinite series. This method is presented in Best and Gipps (1974). In the paper, they mention that the maximum error for any probability is 0.0004.
Case2 : There are ties:
        This is the case in which asymptotics are called in order to use a normal approximation. The details are explained in the R CRAN package documentation.


Ansible double loop in hostvars

Question: I want to loop over the variables of all the hosts of a specific group.
With the following data in hostvars (simplified):
{
    "server1": {
        "group_names": ["web"],
        "sites": {
            "website1": { "id": "site1", "domain": "..." }
            "website2": { "id": "site2", "domain": "..." }
         },
     }
     "server2": {
        "group_names": ["web"],
        "sites": {
            "website3": { "id": "site3", "domain": "..." }
        }
     }
}

I want on an third server (the database server) create all the db:
- name: create databases
- mysql_db:
      name: "{{ item.1.id }}"
- with_subelements:
      - "{{ groups["web"] }}"
      - "{{ hostvars[item.0]['sites']

This doesn't work, I have the error: {"failed": true, "msg": "'item' is undefined"}
How should I write the role ?
Answer: Here are some jinja magic for you:
inventory:
localhost ansible_ssh_host=127.0.0.1 ansible_connection=local

[web]
host1 sites="{'web1':{'id':'z1'},'web2':{'id':'z2'}}"
host2 sites="{'web3':{'id':'z3'}}"

demo:
---
- hosts: localhost
  gather_facts: no
  tasks:
    - debug:
        msg: "Site name – {{ item.key }}, id - {{ item.value.id }}"
      with_dict: "{{ dict(groups['web'] | map('extract',hostvars,'sites') | map('dictsort') | sum(start=[]) | list) }}"

I do dictsort->sum->dict trick, because your sites object is a dictionary (not list) and it's not that easy to iterate over nested dicts.

Ansible double loop in hostvars


MOTD debian - is this ever changed by an update?

Question: Is this ever changed automatically by a system update?
I'm just wondering as I set a 'hilarious' one for a personal server off rackspace cloud, and it seems to have been deleted.
Answer: See /etc/init.d/bootlogs
Specifically this line
# Update motd
uname -snrvm > /var/run/motd
[ -f /etc/motd.tail ] && cat /etc/motd.tail >> /var/run/motd

Meaning you should put your changes to motd in /etc/motd.tail otherwise its going to get overwritten on boot.
Answer: It might be interesting to add that editing /etc/motd.tail is not enough, the above snippet must be executed to update /etc/motd, the system only updates it on reboot (well, how often do you reboot your servers?)
Just out of lazyness, and because my server has no load anyways, I update /etc/motd every minute by using cron to execute exactly the code mentioned above.


Lines return "NaNs" when within a switch; some of these same lines operate flawlessly when the switch is commented out

Question: When I run my program (using gcc -std=c99 -lm) with a switch statement, all of the "factors" calculated in this Case 1:
factors[rows][0]=cbrtf((3+(float)scores[rows][1])/(3+(float)scores[rows][3]));

are reported as "NaN".  If I comment out Cases 2 and 3, the same line runs flawlessly.  Can anyone explain this?
As a separate issue, Cases 2:
factors[rows][0]=((float)scores[rows][1])/(((float)scores[rows][1])+((float)scores[rows][3]));

and 3:
factors[rows][0]=log((((float)scores[rows][1])/(((float)scores[rows][1])+((float)scores[rows][3])))+1);

result in NaNs whether within or outside of the switch.  I've checked my parentheses a dozen times.  There's no possibility of division by zero (since the sum of the scores in the denominators must be positive), and to prevent taking the natural logarithm of zero, which is undefined, I have added 1 to a quotient which always falls between 0 and 1 inclusive. Why do these lines produce NaNs?
This is the first program I've written since Intro to Fortran IV in 1973, so it may be something obvious . . .
Here's part of the data file (data.csv):
home_id,home_team,home_points,away_id,away_team,away_points
98,Western Kentucky,38,2046,Austin Peay,27
77,Northwestern,31,158,Nebraska,28
2439,UNLV,52,304,Idaho State,21
356,Illinois,38,2751,Wyoming,6
328,Utah State,31,41,Connecticut,20
52,Florida State,47,2184,Duquesne,7
2226,Florida Atlantic,43,2429,Charlotte,13
153,North Carolina,56,50,Florida A&M,24
2638,UTEP,13,249,North Texas,31
166,New Mexico State,12,2440,Nevada,23
62,Hawai'i,10,238,Vanderbilt,63
2006,Akron,30,2598,St Francis (PA),23
2116,UCF,56,2569,South Carolina State,10
2633,Tennessee,59,2050,Ball State,10
221,Pittsburgh,38,277,West Virginia,31
197,Oklahoma State,58,2117,Central Michigan,44
2649,Toledo,37,112358,Long Island University,0
2229,Florida International,38,2803,Bryant,37
154,Wake Forest,44,2678,VMI,10
2509,Purdue,31,213,Penn State,35
2459,Northern Illinois,34,2197,Eastern Illinois,27
142,Missouri,52,2348,Louisiana Tech,24
5,UAB,59,2010,Alabama A&M,0
135,Minnesota,38,166,New Mexico State,0
9,Arizona State,40,2464,Northern Arizona,3
23,San José State,21,2502,Portland State,17
278,Fresno State,35,13,Cal Poly,7
2429,Charlotte,24,2729,William & Mary,41
2199,Eastern Michigan,42,2198,Eastern Kentucky,34
127,Michigan State,35,2711,Western Michigan,13
295,Old Dominion,20,259,Virginia Tech,17
150,Duke,30,218,Temple,0
84,Indiana,23,356,Illinois,20
2305,Kansas,56,2635,Tennessee Tech,10
38,Colorado,13,2628,TCU,38
151,East Carolina,20,152,NC State,21
2426,Navy,7,48,Delaware,14
103,Boston College,21,164,Rutgers,22
41,Connecticut,28,2115,Central Connecticut,3
120,Maryland,31,2084,Buffalo,10
2026,Appalachian State,61,153,North Carolina,63
245,Texas A&M,31,2534,Sam Houston State,0
130,Michigan,51,36,Colorado State,7
2294,Iowa,7,2571,South Dakota State,3
258,Virginia,34,257,Richmond,17
2005,Air Force,48,2460,Northern Iowa,17
66,Iowa State,42,2546,Southeast Missouri State,10
26,UCLA,45,189,Bowling Green,17
21,San Diego State,20,12,Arizona,38
2751,Wyoming,40,202,Tulsa,37
201,Oklahoma,45,2638,UTEP,13
276,Marshall,55,2450,Norfolk State,3
2390,Miami,70,2065,Bethune-Cookman,13
2636,UT San Antonio,35,248,Houston,37
61,Georgia,49,2483,Oregon,3
158,Nebraska,38,155,North Dakota,17
8,Arkansas,31,2132,Cincinnati,24
58,South Florida,21,252,BYU,50
25,California,34,302,UC Davis,13
145,Ole Miss,28,2653,Troy,10
6,South Alabama,48,2447,Nicholls,7
2440,Nevada,38,326,Texas State,14
256,James Madison,44,2393,Middle Tennessee,7
290,Georgia Southern,59,2415,Morgan State,7
30,USC,66,242,Rice,14
195,Ohio,41,2226,Florida Atlantic,38
57,Florida,29,254,Utah,26
275,Wisconsin,38,2287,Illinois State,0
309,Louisiana,24,2545,Southeastern Louisiana,7
2572,Southern Mississippi,27,2335,Liberty,29
238,Vanderbilt,42,2210,Elon,31
2,Auburn,42,2382,Mercer,16
2655,Tulane,42,113,UMass,10
324,Coastal Carolina,38,349,Army,28
96,Kentucky,37,193,Miami (OH),13
239,Baylor,69,399,Albany,10
2032,Arkansas State,58,2755,Grambling,3
2306,Kansas State,34,233,South Dakota,0
344,Mississippi State,49,235,Memphis,23
333,Alabama,55,328,Utah State,0
2579,South Carolina,35,2247,Georgia State,14
194,Ohio State,21,87,Notre Dame,10
249,North Texas,10,2567,SMU,48
24,Stanford,41,2142,Colgate,10
251,Texas,52,2433,Louisiana Monroe,10
2641,Texas Tech,63,93,Murray State,10
183,Syracuse,31,97,Louisville,7
167,New Mexico,41,311,Maine,0
265,Washington State,24,70,Idaho,17
204,Oregon State,34,68,Boise State,17
264,Washington,45,2309,Kent State,20
62,Hawai'i,17,98,Western Kentucky,49
52,Florida State,24,99,LSU,23
59,Georgia Tech,10,228,Clemson,41
5,UAB,24,193,Miami (OH),20
2653,Troy,18,2636,UT San Antonio,12
97,Louisville,24,2132,Cincinnati,7
204,Oregon State,30,57,Florida,3
278,Fresno State,29,265,Washington State,6
2572,Southern Mississippi,38,242,Rice,24
252,BYU,24,2567,SMU,23
68,Boise State,35,249,North Texas,32
41,Connecticut,14,276,Marshall,28
23,San José State,27,2199,Eastern Michigan,41
2649,Toledo,21,2335,Liberty,19
6,South Alabama,23,98,Western Kentucky,44
2005,Air Force,30,239,Baylor,15
248,Houston,23,309,Louisiana,16
142,Missouri,17,154,Wake Forest,27
21,San Diego State,23,2393,Middle Tennessee,25
189,Bowling Green,19,166,New Mexico State,24
2084,Buffalo,23,290,Georgia Southern,21
328,Utah State,10,235,Memphis,38
151,East Carolina,53,324,Coastal Carolina,29
197,Oklahoma State,17,275,Wisconsin,24
150,Duke,30,2116,UCF,13
8,Arkansas,55,2305,Kansas,53
153,North Carolina,27,2483,Oregon,28
145,Ole Miss,25,2641,Texas Tech,42
135,Minnesota,28,183,Syracuse,20
52,Florida State,35,201,Oklahoma,32
264,Washington,27,251,Texas,20
152,NC State,12,120,Maryland,16
26,UCLA,35,221,Pittsburgh,37
2579,South Carolina,38,87,Notre Dame,45
2751,Wyoming,27,195,Ohio,30
228,Clemson,14,2633,Tennessee,31
2306,Kansas State,20,333,Alabama,45
96,Kentucky,0,2294,Iowa,21
130,Michigan,45,2628,TCU,51
61,Georgia,42,194,Ohio State,41
356,Illinois,10,344,Mississippi State,19
30,USC,45,2655,Tulane,46
2509,Purdue,7,99,LSU,63
254,Utah,21,213,Penn State,35
61,Georgia,65,2628,TCU,7
2116,UCF,14,97,Louisville,20
167,New Mexico,14,68,Boise State,31
8,Arkansas,44,2579,South Carolina,30
194,Ohio State,45,2032,Arkansas State,12
251,Texas,19,333,Alabama,20
349,Army,38,2636,UT San Antonio,41
213,Penn State,46,195,Ohio,10
2306,Kansas State,40,142,Missouri,12
2247,Georgia State,28,153,North Carolina,35
77,Northwestern,23,150,Duke,31
135,Minnesota,62,2710,Western Illinois,10
2390,Miami,30,2572,Southern Mississippi,7
238,Vanderbilt,25,154,Wake Forest,45
152,NC State,55,2127,Charleston Southern,3
2117,Central Michigan,24,6,South Alabama,38
254,Utah,73,253,Southern Utah,7
218,Temple,30,322,Lafayette,14
2050,Ball State,30,2711,Western Michigan,37
87,Notre Dame,21,276,Marshall,26
221,Pittsburgh,27,2633,Tennessee,34
2429,Charlotte,21,120,Maryland,56
2132,Cincinnati,63,338,Kennesaw State,10
228,Clemson,35,231,Furman,12
2005,Air Force,41,38,Colorado,10
2426,Navy,13,235,Memphis,37
275,Wisconsin,14,265,Washington State,17
245,Texas A&M,14,2026,Appalachian State,17
127,Michigan State,52,2006,Akron,0
256,James Madison,63,2450,Norfolk State,7
2641,Texas Tech,33,248,Houston,30
189,Bowling Green,57,2198,Eastern Kentucky,59
25,California,20,2439,UNLV,14
2294,Iowa,7,66,Iowa State,10
356,Illinois,24,258,Virginia,3
164,Rutgers,66,2681,Wagner,7
2509,Purdue,56,282,Indiana State,0
2751,Wyoming,33,2458,Northern Colorado,10
264,Washington,52,2502,Portland State,6
61,Georgia,33,2535,Samford,0
36,Colorado State,19,2393,Middle Tennessee,34
26,UCLA,45,2011,Alabama State,7
2440,Nevada,41,2916,Incarnate Word,55
324,Coastal Carolina,31,2241,Gardner-Webb,27
2335,Liberty,21,5,UAB,14
2084,Buffalo,31,107,Holy Cross,37
151,East Carolina,39,295,Old Dominion,21
2226,Florida Atlantic,42,2545,Southeastern Louisiana,9
277,West Virginia,42,2305,Kansas,55
193,Miami (OH),31,2523,Robert Morris,14
2655,Tulane,52,2016,Alcorn State,0
201,Oklahoma,33,2309,Kent State,3
309,Louisiana,49,2199,Eastern Michigan,21
326,Texas State,41,2229,Florida International,12
58,South Florida,42,47,Howard,20
2567,SMU,45,2320,Lamar,16
328,Utah State,7,2692,Weber State,35
2649,Toledo,55,113,UMass,10
59,Georgia Tech,35,2717,Western Carolina,17
41,Connecticut,14,183,Syracuse,48
57,Florida,16,96,Kentucky,26
145,Ole Miss,59,2110,Central Arkansas,3
2653,Troy,38,2010,Alabama A&M,17
202,Tulsa,38,2459,Northern Illinois,35
2348,Louisiana Tech,52,2617,Stephen F. Austin,17
197,Oklahoma State,34,9,Arizona State,17
249,North Texas,59,2640,Texas Southern,27
242,Rice,52,2377,McNeese,10
2,Auburn,24,23,San José State,16
24,Stanford,28,30,USC,41
99,LSU,65,2582,Southern,17
158,Nebraska,42,290,Georgia Southern,45
21,San Diego State,38,304,Idaho State,7
2628,TCU,59,2627,Tarleton State,17
259,Virginia Tech,27,103,Boston College,10
130,Michigan,56,62,Hawai'i,10
84,Indiana,35,70,Idaho,22
2433,Louisiana Monroe,35,2447,Nicholls,7
2483,Oregon,70,331,Eastern Washington,14
2638,UTEP,20,166,New Mexico State,13
252,BYU,26,239,Baylor,20
278,Fresno State,32,204,Oregon State,35
12,Arizona,17,344,Mississippi State,39
97,Louisville,31,52,Florida State,35
2751,Wyoming,17,2005,Air Force,14
259,Virginia Tech,27,2747,Wofford,7
96,Kentucky,31,2754,Youngstown State,0
77,Northwestern,24,79,Southern Illinois,31
183,Syracuse,32,2509,Purdue,29
142,Missouri,34,2000,Abilene Christian,17
2579,South Carolina,7,61,Georgia,48
84,Indiana,33,98,Western Kentucky,30
158,Nebraska,14,201,Oklahoma,49
2309,Kent State,63,112358,Long Island University,10
193,Miami (OH),17,2132,Cincinnati,38
239,Baylor,42,326,Texas State,7
349,Army,49,222,Villanova,10
130,Michigan,59,41,Connecticut,0
324,Coastal Carolina,38,2084,Buffalo,26
277,West Virginia,65,119,Towson,7
2117,Central Michigan,41,2083,Bucknell,0
218,Temple,14,164,Rutgers,16
258,Virginia,16,295,Old Dominion,14
2050,Ball State,31,93,Murray State,0
26,UCLA,32,6,South Alabama,31
66,Iowa State,43,195,Ohio,10
87,Notre Dame,24,25,California,17
2439,UNLV,58,249,North Texas,27
2306,Kansas State,10,2655,Tulane,17
5,UAB,35,290,Georgia Southern,21
59,Georgia Tech,0,145,Ole Miss,42
2483,Oregon,41,252,BYU,20
275,Wisconsin,66,166,New Mexico State,7
2459,Northern Illinois,28,238,Vanderbilt,38
135,Minnesota,49,38,Colorado,7
2026,Appalachian State,32,2653,Troy,28
2,Auburn,12,213,Penn State,41
113,UMass,20,2619,Stony Brook,3
68,Boise State,30,2630,UT Martin,7
248,Houston,30,2305,Kansas,48
333,Alabama,63,2433,Louisiana Monroe,7
189,Bowling Green,34,276,Marshall,31
265,Washington State,38,36,Colorado State,7
154,Wake Forest,37,2335,Liberty,36
99,LSU,31,344,Mississippi State,16
150,Duke,49,2448,North Carolina A&T,20
151,East Carolina,49,2097,Campbell,10
197,Oklahoma State,63,2029,Arkansas-Pine Bluff,7
152,NC State,27,2641,Texas Tech,14
2633,Tennessee,63,2006,Akron,6
235,Memphis,44,2032,Arkansas State,32
2572,Southern Mississippi,64,2466,Northwestern State,10
8,Arkansas,38,2623,Missouri State,27
194,Ohio State,77,2649,Toledo,21
2393,Middle Tennessee,49,2634,Tennessee State,6
202,Tulsa,54,55,Jacksonville State,17
2247,Georgia State,41,2429,Charlotte,42
2711,Western Michigan,13,221,Pittsburgh,34
264,Washington,39,127,Michigan State,28
2226,Florida Atlantic,14,2116,UCF,40
242,Rice,33,309,Louisiana,21
120,Maryland,34,2567,SMU,27
57,Florida,31,58,South Florida,28
103,Boston College,38,311,Maine,17
2294,Iowa,27,2440,Nevada,0
167,New Mexico,27,2638,UTEP,10
251,Texas,41,2636,UT San Antonio,20
228,Clemson,48,2348,Louisiana Tech,20
204,Oregon State,68,147,Montana State,28
245,Texas A&M,17,2390,Miami,9
254,Utah,35,21,San Diego State,7
30,USC,45,278,Fresno State,17
12,Arizona,31,2449,North Dakota State,28
9,Arizona State,21,2199,Eastern Michigan,30
62,Hawai'i,24,2184,Duquesne,14
2247,Georgia State,24,324,Coastal Carolina,41
259,Virginia Tech,10,277,West Virginia,33
356,Illinois,31,236,Chattanooga,0
183,Syracuse,22,258,Virginia,20
2005,Air Force,48,2440,Nevada,20
2638,UTEP,27,68,Boise State,10
344,Mississippi State,45,189,Bowling Green,14
2,Auburn,17,142,Missouri,14
2199,Eastern Michigan,31,2084,Buffalo,50
130,Michigan,34,120,Maryland,27
2567,SMU,34,2628,TCU,42
61,Georgia,39,2309,Kent State,22
97,Louisville,41,58,South Florida,3
2305,Kansas,35,150,Duke,27
213,Penn State,33,2117,Central Michigan,14
66,Iowa State,24,239,Baylor,31
154,Wake Forest,45,228,Clemson,51
221,Pittsburgh,45,227,Rhode Island,24
38,Colorado,17,26,UCLA,45
218,Temple,28,113,UMass,0
195,Ohio,59,2230,Fordham,52
2633,Tennessee,38,57,Florida,33
98,Western Kentucky,73,2229,Florida International,0
21,San Diego State,17,2649,Toledo,14
235,Memphis,44,249,North Texas,34
153,North Carolina,32,87,Notre Dame,45
2641,Texas Tech,37,251,Texas,34
2636,UT San Antonio,52,2640,Texas Southern,24
2390,Miami,31,2393,Middle Tennessee,45
2026,Appalachian State,28,256,James Madison,32
2132,Cincinnati,45,84,Indiana,24
127,Michigan State,7,135,Minnesota,34
2116,UCF,27,59,Georgia Tech,10
36,Colorado State,10,16,Sacramento State,41
145,Ole Miss,35,202,Tulsa,27
265,Washington State,41,2483,Oregon,44
25,California,49,12,Arizona,31
290,Georgia Southern,34,2050,Ball State,23
248,Houston,34,242,Rice,27
151,East Carolina,20,2426,Navy,23
2335,Liberty,21,2006,Akron,12
295,Old Dominion,29,2032,Arkansas State,26
328,Utah State,24,2439,UNLV,34
6,South Alabama,38,2348,Louisiana Tech,14
2655,Tulane,24,2572,Southern Mississippi,27
326,Texas State,34,2277,Houston Christian,0
245,Texas A&M,23,8,Arkansas,21
164,Rutgers,10,2294,Iowa,27
96,Kentucky,31,2459,Northern Illinois,23
2653,Troy,16,276,Marshall,7
333,Alabama,55,238,Vanderbilt,3
99,LSU,38,167,New Mexico,0
152,NC State,41,41,Connecticut,10
194,Ohio State,52,275,Wisconsin,21
2579,South Carolina,56,2429,Charlotte,20
2509,Purdue,28,2226,Florida Atlantic,26
77,Northwestern,14,193,Miami (OH),17
201,Oklahoma,34,2306,Kansas State,41
52,Florida State,44,103,Boston College,14
166,New Mexico State,45,62,Hawai'i,26
2433,Louisiana Monroe,21,309,Louisiana,17
204,Oregon State,14,30,USC,17
252,BYU,38,2751,Wyoming,24
9,Arizona State,13,254,Utah,34
264,Washington,40,24,Stanford,22
23,San José State,34,2711,Western Michigan,6
2579,South Carolina,50,2569,South Carolina State,10
252,BYU,38,328,Utah State,26
248,Houston,24,2655,Tulane,27
2393,Middle Tennessee,30,2636,UT San Antonio,45
68,Boise State,35,21,San Diego State,13
26,UCLA,40,264,Washington,32
2439,UNLV,31,167,New Mexico,20
145,Ole Miss,22,96,Kentucky,19
103,Boston College,34,97,Louisville,33
2306,Kansas State,37,2641,Texas Tech,28
2005,Air Force,13,2426,Navy,10
235,Memphis,24,218,Temple,3
2628,TCU,55,201,Oklahoma,24
275,Wisconsin,10,356,Illinois,34
2294,Iowa,14,130,Michigan,27
135,Minnesota,10,2509,Purdue,20
349,Army,14,2247,Georgia State,31
256,James Madison,40,326,Texas State,13
2050,Ball State,44,2459,Northern Illinois,38
2199,Eastern Michigan,20,113,UMass,13
254,Utah,42,204,Oregon State,16
58,South Florida,28,151,East Carolina,48
213,Penn State,17,77,Northwestern,7
239,Baylor,25,197,Oklahoma State,36
2026,Appalachian State,49,2643,The Citadel,0
2305,Kansas,14,66,Iowa State,11
2084,Buffalo,24,193,Miami (OH),20
194,Ohio State,49,164,Rutgers,10
276,Marshall,28,2241,Gardner-Webb,7
153,North Carolina,41,259,Virginia Tech,10
52,Florida State,21,154,Wake Forest,31
120,Maryland,27,127,Michigan State,13
8,Arkansas,26,333,Alabama,49
41,Connecticut,19,278,Fresno State,14
2006,Akron,28,189,Bowling Green,31
2649,Toledo,38,2117,Central Michigan,17
2309,Kent State,31,195,Ohio,24
249,North Texas,45,2226,Florida Atlantic,28
344,Mississippi State,42,245,Texas A&M,24
309,Louisiana,17,6,South Alabama,20
183,Syracuse,59,2681,Wagner,0
265,Washington State,28,25,California,9
2711,Western Michigan,44,160,New Hampshire,7
2429,Charlotte,35,2638,UTEP,41
295,Old Dominion,24,2335,Liberty,38
202,Tulsa,21,2132,Cincinnati,31
2,Auburn,17,99,LSU,21
2032,Arkansas State,45,2433,Louisiana Monroe,28
324,Coastal Carolina,34,290,Georgia Southern,30
98,Western Kentucky,27,2653,Troy,34
242,Rice,28,5,UAB,24
150,Duke,38,258,Virginia,17
2751,Wyoming,16,23,San José State,33
142,Missouri,22,61,Georgia,26
251,Texas,38,277,West Virginia,20
228,Clemson,30,152,NC State,20
158,Nebraska,35,84,Indiana,21
166,New Mexico State,7,2229,Florida International,21
221,Pittsburgh,21,59,Georgia Tech,26
12,Arizona,43,38,Colorado,20
30,USC,42,9,Arizona State,25
2483,Oregon,45,24,Stanford,27
57,Florida,52,331,Eastern Washington,17
2116,UCF,41,2567,SMU,19
164,Rutgers,13,158,Nebraska,14
235,Memphis,32,248,Houston,33
2440,Nevada,14,36,Colorado State,17
23,San José State,40,2439,UNLV,7
57,Florida,24,142,Missouri,17
120,Maryland,29,2509,Purdue,31
2711,Western Michigan,23,2199,Eastern Michigan,45
99,LSU,13,2633,Tennessee,40
344,Mississippi State,40,8,Arkansas,17
201,Oklahoma,0,251,Texas,49
258,Virginia,17,97,Louisville,34
84,Indiana,10,130,Michigan,31
2305,Kansas,31,2628,TCU,38
189,Bowling Green,7,2084,Buffalo,38
2247,Georgia State,41,290,Georgia Southern,33
195,Ohio,55,2006,Akron,34
2132,Cincinnati,28,58,South Florida,24
197,Oklahoma State,41,2641,Texas Tech,31
113,UMass,24,2335,Liberty,42
221,Pittsburgh,45,259,Virginia Tech,29
61,Georgia,42,2,Auburn,10
2426,Navy,53,202,Tulsa,21
26,UCLA,42,254,Utah,32
193,Miami (OH),27,2309,Kent State,24
5,UAB,41,2393,Middle Tennessee,14
77,Northwestern,7,275,Wisconsin,42
2655,Tulane,24,151,East Carolina,9
2459,Northern Illinois,32,2649,Toledo,52
2117,Central Michigan,16,2050,Ball State,17
127,Michigan State,20,194,Ohio State,49
59,Georgia Tech,23,150,Duke,20
9,Arizona State,45,264,Washington,38
238,Vanderbilt,28,145,Ole Miss,52
2390,Miami,24,153,North Carolina,27
2636,UT San Antonio,31,98,Western Kentucky,28
326,Texas State,36,2026,Appalachian State,24
2653,Troy,27,2572,Southern Mississippi,10
2229,Florida International,12,41,Connecticut,33
2032,Arkansas State,20,256,James Madison,42
167,New Mexico,14,2751,Wyoming,27
328,Utah State,34,2005,Air Force,27
2348,Louisiana Tech,41,2638,UTEP,31
30,USC,30,265,Washington State,14
87,Notre Dame,28,252,BYU,20
154,Wake Forest,45,349,Army,10
66,Iowa State,9,2306,Kansas State,10
356,Illinois,9,2294,Iowa,6
96,Kentucky,14,2579,South Carolina,24
103,Boston College,3,228,Clemson,31
2433,Louisiana Monroe,21,324,Coastal Carolina,28

. . . and here's the code:
// A program to rank teams based strictly on current season performance and quality of opponents
// use "gcc Rankings.c -std=c99 -lm"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#define _CRT_SECURE_NO_WARNINGS

// Parse the data csv file and store into array of structs

typedef struct Data
{
int iA_ID;
char cA_Name [30];
int iA_Points;
int iB_ID;
char cB_Name [30];
int iB_Points;
char placeholder [];
}data; // Make 'data' the alias for struct Data

int main(void)
{
// Obtain a count of games played
FILE *ptr;
char c;
int games=-1;
// Open the file for reading and count the number of games played
ptr = fopen("data.csv", "r");
if (ptr == NULL)
{
    printf("Can't open file!");
    return 0;
}
// Read from the file until end-of-file is reached
for (c = getc(ptr); c != EOF; c = getc(ptr))
{
    if (c == '\n') // Increment games count if this character is newline
    games++;
}
system("clear");
printf("The number of games played is %d\n",games);
// Close the file
fclose(ptr);
ptr = NULL;

// Initialize the file pointer
FILE *pF=fopen("data.csv", "r");  // Open in read mode
if(!pF)
{
    printf("Can't open file!");
    return 0;
}
char buff[4096];  // Stores the scores into buff
int rows = 0;
int fields = 0;
data values[games+1];  // Array of structs to store values

int i = 0;
while(fgets(buff, 80, pF))
{
    fields = 0;
    rows++;
    if(rows == 1) continue;  // Do not take the labels

    char *field = strtok(buff, ",");
    while(field)
    {
        if(fields == 0)
        values[i].iA_ID=atoi(field);
        if(fields == 1)
        strcpy(values[i].cA_Name, field);
        if(fields == 2)
        values[i].iA_Points=atoi(field);
        if(fields == 3)
        values[i].iB_ID=atoi(field);
        if(fields == 4)
        strcpy(values[i].cB_Name, field);
        if(fields == 5)
        values[i].iB_Points=atoi(field);
        field = strtok(NULL, ",");  // update
        fields++;
    }
    i++;
}
fclose(pF);
pF=NULL;

// Create a function to print all the values of the array of structs
//void printValues (data values[])
//{
    //for(int i=0; i<games; i++)
    //{
    //  printf("%d\t %s\t %d\t %d\t %s\t %d\n", values[i].iA_ID, values[i].cA_Name, values[i].iA_Points, values[i].iB_ID, values[i].cB_Name, values[i].iB_Points);
    //}
//}
//printValues(values); // Call the function

int scores[2*games][6]; // Column 4 is top-level Evaluated checklist; 5 is #games team B played
float factors[2*games][3]; // Column 0 is score factors; column 1 is team factors; column 2 is holding place for team factors during preliminary run
int ATeam=0, BTeam, CTeam, AGames=0, BGames=0, CGames=0, ARows=0, BRows=0, CRows=0, n=0;
float AFactor=0.0, BFactor=0.0, CFactor=0.0;
float cbrtf(float arg), factormin=10;

int iPreference=0;
printf("\n1\tCube root of (Points scored by Team A + 3)/(Points scored by Team B + 3)\n");
printf("2\tFraction of game points scored by Team A\n");
printf("3\tln of [(percentage of game points scored by Team A) + 1]\n");
printf("\nPlease select your preference (1-3): ");
scanf("%d", &iPreference);

for (rows=0; rows<games; rows++)
{
    scores[rows][0]=values[rows].iA_ID;
    scores[rows+games][0]=values[rows].iB_ID;
    scores[rows][1]=values[rows].iA_Points;
    scores[rows+games][1]=values[rows].iB_Points;
    scores[rows][2]=values[rows].iB_ID;
    scores[rows+games][2]=values[rows].iA_ID;
    scores[rows][3]=values[rows].iB_Points;
    scores[rows+games][3]=values[rows].iA_Points;
    scores[rows][4]=0;  // Column 4 will be checked off with a '1' once a game has been evaluated
    scores[rows+games][4]=0;
    factors[rows][1]=1;  // Seed every team with a starting value of 1
    factors[rows+games][1]=1;
    switch (iPreference)
    {
    case 1:
        factors[rows][0]=cbrtf((3+(float)scores[rows][1])/(3+(float)scores[rows][3]));
        factors[rows+games][0]=cbrtf((3+(float)scores[rows+games][1])/(3+(float)scores[rows+games][3]));
    //case 2:
    //  factors[rows][0]=((float)scores[rows][1])/(((float)scores[rows][1])+((float)scores[rows][3]));
    //  factors[rows+games][0]=((float)scores[rows+games][1])/(((float)scores[rows+games][1])+((float)scores[rows+games][3]));
    //case 3:
    //  factors[rows][0]=log((((float)scores[rows][1])/(((float)scores[rows][1])+((float)scores[rows][3])))+1);
    //  factors[rows+games][0]=log((((float)scores[rows+games][1])/(((float)scores[rows+games][1])+((float)scores[rows+games][3])))+1);
    }
}

if (isnan(factors[rows][0]))
{
// print the numerator and denominator
printf("\tNumerator:(%E) / Denominator(%E) = %E\n", (float)scores[rows][1], ((float)scores[rows][1]+(float)scores[rows][3]), (float)scores[rows][0]);
// end the program and review
exit(0);
}

for (rows=0; rows<2*games; rows++)
    printf("%d\t %d\t %d\t %d\t %f\n", scores[rows][0], scores[rows][1], scores[rows][2], scores[rows][3], factors[rows][0]);
printf("\n\n\n");

for (rows=0; rows<2*games; rows++)
{
    if(factors[rows][0]>=factormin) continue;
    factormin=factors[rows][0];
}
printf("Lowest factor calculated is %f\n\n", factormin);

for (rows=0; rows<2*games; rows++) // Work down the scores array until you get to . . .
{
    if(scores[rows][4]==1) continue;  // . . . a team that has not already been evaluated
    ATeam=scores[rows][0]; // Team A (not yet evaluated) becomes ATeam (team under evaluation this run at level A)
    AFactor=0;
    AGames=0;
    //printf("ATeam = %d\n", ATeam);
    for (ARows=rows; ARows<2*games; ARows++)  // Look through the the remaining games in the scores array for ATeam's games
    {
        if(scores[ARows][0]!=ATeam) continue;  // Skip games in which ATeam didn't play
        BTeam=scores[ARows][2]; // The opposing team becomes the team under evaluation at level B
        AGames=AGames+1;
        BGames=0;
        BFactor=0;
        for (BRows=0; BRows<2*games; BRows++) // Now evaluate strength of opponent BTeam
        {
            if(scores[BRows][0]!=BTeam) continue;  // Skip games in which BTeam didn't play
            CTeam=scores[BRows][2]; // The opposing team becomes the team under evaluation at level C
            BGames=BGames+1;
            CGames=0;
            CFactor=0;
            for (CRows=0; CRows<2*games; CRows++) // Now evaluate strength of each of BTeam's opponents CTeam
            {
                if(scores[CRows][0]!=CTeam) continue;  // Skip games in which CTeam didn't play
                CGames=CGames+1;
                CFactor=CFactor+(factors[CRows][1]*factors[CRows][0]);
            }
            CFactor=CFactor/CGames;  // Cumulative performance of CTeam against its opponents
            BFactor=BFactor+(CFactor*factors[BRows][0]); // Increment BFactor by CTeam's strength x BTeam's performance against it
        }
        BFactor=BFactor/BGames;  // Cumulative performance of BTeam against its opponents
        AFactor=AFactor+(BFactor*factors[ARows][0]); // Increment AFactor by BTeam's strength x ATeam's performance against it
        //printf("AFactor = %f\t AGames = %d\n", AFactor, AGames);
        scores[ARows][4]=1; // Mark this game for ATeam vs BTeam as Evaluated
        //printf("rows = %d\t ARows = %d\n", rows, ARows);
    }
    AFactor=AFactor/AGames;

    for (n=0; n<2*games; n++)
        {
        if(scores[n][2]!=ATeam) continue;  // Wherever ATeam is the opponent . . .
        factors[n][2]=AFactor;  // Store AFactor in factors column 2 until preliminary round has been completed
        }
}
for (i=0; i<2*games; i++)
{
factors[i][1]=factors[i][2]; // Replace starting team value of 1 in column 1 with factor from column 2 to prepare for final evaluation round
//printf("%d\t %f\n", scores[i][2], factors[i][1]);
scores[i][4]=0;  // Remove "evaluated" tag from every game to prepare for round 2
}

// Begin round 2, now with factors[][1] seeded with AFactor from round 1

for (rows=0; rows<2*games; rows++) // Work down the scores arrahy until you get to . . .
{
    if(scores[rows][4]==1) continue;  // . . . a team that has not already been evaluated
    ATeam=scores[rows][0]; // Team A (not yet evaluated) becomes ATeam (team under evaluation this run at level A)
    AFactor=0;
    AGames=0;
    //printf("ATeam = %d\n", ATeam);
    for (ARows=rows; ARows<2*games; ARows++)  // Look through the the remaining games in the scores array for ATeam's games
    {
        if(scores[ARows][0]!=ATeam) continue;  // Skip games in which ATeam didn't play
        BTeam=scores[ARows][2]; // The opposing team becomes the team under evaluation at level B
        AGames=AGames+1;
        BGames=0;
        BFactor=0;
        for (BRows=0; BRows<2*games; BRows++) // Now evaluate strength of opponent BTeam
        {
            if(scores[BRows][0]!=BTeam) continue;  // Skip games in which BTeam didn't play
            CTeam=scores[BRows][2]; // The opposing team becomes the team under evaluation at level C
            BGames=BGames+1;
            CGames=0;
            CFactor=0;
            for (CRows=0; CRows<2*games; CRows++) // Now evaluate strength of each of BTeam's opponents CTeam
            {
                if(scores[CRows][0]!=CTeam) continue;  // Skip games in which CTeam didn't play
                CGames=CGames+1;
                CFactor=CFactor+(factors[CRows][1]*factors[CRows][0]);
            }
            CFactor=CFactor/CGames;  // Cumulative performance of CTeam against its opponents
            BFactor=BFactor+(CFactor*factors[BRows][0]); // Increment BFactor by CTeam's strength x BTeam's performance against it
        }
        BFactor=BFactor/BGames;  // Cumulative performance of BTeam against its opponents
        AFactor=AFactor+(BFactor*factors[ARows][0]); // Increment AFactor by BTeam's strength x ATeam's performance against it
        //printf("AFactor = %f\t AGames = %d\n", AFactor, AGames);
        scores[ARows][4]=1; // Mark this game for ATeam vs BTeam as Evaluated
        //printf("rows = %d\t ARows = %d\n", rows, ARows);
    }
    AFactor=AFactor/AGames;

    for (n=0; n<2*games; n++)
        {
        if(scores[n][2]!=ATeam) continue;  // Wherever ATeam is the opponent . . .
        scores[n][5]=AGames; // . . . store # games ATeam played in column 5 and . . .
        factors[n][2]=AFactor;  // . . . store AFactor in factors column 2 until round 2 has been completed
        }
}
printf("\n\n\n");

for (i=0; i<games; i++)  // Sort the data by factors
{
if(factors[i][2]>=factors[i+1][2])continue;
else
    {
    factors[games+1][2]=factors[i+1][2];  // Temporarily "move" the larger factor (w/ id # and school name) to a row beyond the games data
    scores[games+1][2]=scores[i+1][2];
    scores[games+1][5]=scores[i+1][5];
    strcpy(values[games+1].cB_Name, values[i+1].cB_Name);

    factors[i+1][2]=factors[i][2];  // "Move" the smaller factor (w/ id # and school name) into the "vacated" cells
    scores[i+1][2]=scores[i][2];
    scores[i+1][5]=scores[i][5];
    strcpy(values[i+1].cB_Name, values[i].cB_Name);

    factors[i][2]=factors[games+1][2];  // "Move" the larger factor (w/ id # and school name) to where the smaller had been
    scores[i][2]=scores[games+1][2];
    scores[i][5]=scores[games+1][5];
    strcpy(values[i].cB_Name, values[games+1].cB_Name);

    i=0;
    }
}

n=-1;
for (i=0; i<games; i++)
{
if(scores[i+1][2]==scores[i][2]) continue;  // Skip duplicates
    {
    if(scores[i][5]<4) continue;  // Skip teams that played fewer than 4 games
        {
        n=n+1;
        printf("%d.\t %d\t %.3f\t (%d)\t %s\n", n, scores[i][2], factors[i][2], scores[i][5], values[i].cB_Name);
        }
    }
}

return 0;
}

Comment: I think you have forgotten to include a listing of your code in your post.
Comment: You also haven't said which programming language you are using. There are many languages that have switch statements, and they do not all behave the same.
Comment: @StevenPatterson Please post a [mcve].
Comment: I just added the lines, thanks.  I thought that would be the next box in the posting process.  I'm using C.
Comment: @Steven Patterson –
What is `iPreference` set to if you _run_ _with a switch statement_?
Comment: It is set to '1' when I'm trying to get case 1 (the formula that works when the switch is commented out) to work WITH the switch, Armali.  Thanks.
Comment: I'm new to coding. I don't know what I can trim and still have functional code, so I've added the entire program and some of the data file it accesses.  Hopefully you can see that it runs without the switch, and balks with NaNs with the switch.  Thanks!
Comment: I tried commenting out different lines.  The block that scans in iPreference (the switch index) can be uncommented, and Case 1 works fine, but ONLY if Cases 2 and 3 remain commented out.  So the problem apparently resides there.
Comment: Please note that if you don't add a `break;` at the end of each `case`, the execution continues in the next one, so that the values are overwritten.
Comment: Also note the warnings produced by this: https://godbolt.org/z/GcT6911nT I added a couple of comments, removed the data file and used stdin instead (due to online compiler limitations). The rest of the program is the same, but there are no NaNs.
Answer: As your cube roots get smaller they may hit the limit for a float which has a range of [3.4*10-38, 3.4*1038], in which case you'd want to use double and cbrt() which will increase the range and avoid dividing by zero.
It may be good to add in a print statement to understand why/when the NaN is occurring:
// add this at the top if you don't already have it
#include <stdio.h>
#include <math.h>

/* place this somewhere after you set factors[rows][0]
   to stop the program when you hit a NaN.  Remove
   exit(0) if you want this to continue after computing a NaN
*/
if ( isnan(factors[rows][0]) ) {
     // print the numerator and denominator
     printf("\tNumerator:(%E) / Denominator(%E) = %E\n", (float)scores[rows][1], ((float)scores[rows][1]+(float)scores[rows][3]), (float)scores[rows][0]);
     // end the program and review
     exit(0);
}

Update: replaced NaN comparison with isnan from math.h
Comment: NaNs can't be compared for equality. [isnan](https://en.cppreference.com/w/c/numeric/math/isnan) is the right function to use.
Comment: Thanks, I should've used isnan() from the beginning.
Comment: Note: Typical non-zero `float` range begins with 1.4E-45f.
Comment: @StevenPatterson Are those the values that are in the data file or the values *actually* used in the calculations?
Comment: Thanks, Michael, Retired Ninja, chux, and phuclv.  I've added the isnan code. I checked, and the smallest factor calculated for the 897 games played was 0.340489. Since Case 1 is ((TeamA score +3)/(TeamB score +3))^-3, even a score of 80 to 0 only gets Case 1 to 3.024 for the winner, and 0.331 for the loser. Case 2 will always be between 0 and 1, and Case 3 between 0 and 0.69.  So going out of the range of floats won't be an issue here, but it's something I'll think about in future coding!
Comment: Thanks, Bob!  I somehow missed that breaks are part of switches!  Adding them allowed me to uncomment the switch, and Case 1 runs without NaNs, as you said!  I was also able to remove the "placeholder" from struct Data without any ill effects.
Comment: Bob, the values in the data file are the ones used in the program, but the file was truncated due to the 50K-character limit, so it didn't include the 0 to 0 score that resulted in the division by zero error I saw.
Answer: My switch was missing break statements.  Once I added them, Case 1 ran perfectly.  A single NaN continued to cause Cases 2 and 3 to hang, and I traced it to an acquired error in the data file.  (A 23 to 22 score had changed to a 0 to 0 score, resulting in division by zero.)  When that error was corrected, Cases 2 and 3 ran smoothly as well.


How to supply console input ( yes / no ) as part of batch file on Windows.

Question: I am writing a simple batch file (remove.bat) to remove a directory and all its subdirectories. The file contains the following command-
rmdir /S modules

where modules is the name of the non-empty directory.
I get the following message -
C:\...\bin>rmdir /S modules
modules, Are you sure (Y/N)?

How can I supply through the batch file the console input "Y" to the Y/N question above? Is there a command that can do this?
Answer: As others have pointed out, you should use the /Q option. But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.
echo y|rmdir /s modules

I recommend using the /Q option instead, but the pipe technique might be important if you ever run into a command that does not provide an option to suppress confirmation messages.
Note - This technique only works if the command reads the input from stdin, as is always the case with cmd.exe internal commands. But this may not be true for some external commands.
Comment: useful to close a command window after a pesky PAUSE presents the "Press any key to continue..." prompt!
Comment: thanks, this was a very good out-of-the-box answer, works also for other commands then rmdir
Comment: I am trying to generate the ssh keys silently on windows. This approach does not seem to work.
 echo ''| ssh-keygen.exe -t rsa -f ./id_rsa  -q.
I don't want any password for the key. so I am keeping it empty. But the prompt is not picking up the echo text
Comment: @rbansal , your best bet is to post a new question. Refer to this post, then ask your specific question. Good luck!
Comment: This doesn't work. `echo Y | net user j: /delete` gives "No valid response was provided."
Comment: @PhilipRego - Did you read the note at the bottom of the answer? I suspect the external `net` command is not reading from stdin.
Answer: Do rmdir /S for deleting a non-empty directory and do rmdir /Q for not prompting. Combine to rmdir /S /Q for quietly delete non-empty directories.
Answer: Use rmdir /S /Q modules
/Q suppresses the confirmation prompt.
Answer: You can do
rmdir /Q

Q is for quiet
Answer: I just want to add that, although not applicable to Rmdir, a force switch may also be the solution in some cases. So in a general sense you should look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f).
The echo pipe is a neat trick and very useful to keep around since you wont always find an appropriate switch. For instance, I think it's the only way to bypass this Y/N prompt...
Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp

Link to nearly identical StackOverflow post
Comment: Two years later, and you decide to post an answer that does not provide any new information!? Why? And your first sentence is wrong - the `/Q` option is the "force" option, as was already stated in the three prior answers.
Comment: @dbenham I see your point, but... 1.) Why is two years later a problem when this is still a result on Google? 2.) Example of "new information" is that you may have to hunt for a similar switch for another command, it won't always be /q or /f, but those are good first guesses. 3.) I guess you could nit pick over the first sentence, but it brings up a good point that other posts here don't mention. The word "force" makes me expect "Y" behavior, while the word "quiet" makes me think "Y" or "N". If /S isn't provided, RmDir /Q actually provides the "N" behavior for a non-empty folder.
Comment: @dbenham I agree this answer doesn't add a lot though... I really posted it as an answer to my own question concerning Netdom. I wanted to share what I found worked in different cases for that, but thought it was too similar to be a separate question, and I always hesitate to post and answer my own questions... so I kind of appended it here... maybe it should be seperate
Comment: @dbenham Also, this answer included a link to a similar post, where it can be seen that quiet <> force. They are obviously different when considering the case "del /f /q".
Answer: If you are not dealing with a windows with a english/us locale you might need to retrieve the answers needed for your machine:
@echo off

setlocal

set "ans_yes="
set "ans_no="
set "ans_all="

copy /y nul # >nul

for /f "tokens=2-7 delims=[(/)]" %%a in ( '
    copy /-y nul # ^<nul
' ) do if not defined ans_yes if "%%~e" == "" (
    set "ans_yes=%%~a"
    set "ans_no=%%~b"
    set "ans_all=%%~c"
) else (
    set "ans_yes=%%~a"
    set "ans_no=%%~c"
    set "ans_all=%%~e"
)

del /q #

set "ans_yes=%ans_yes: =%"
set "ans_no=%ans_no: =%"
set "ans_all=%ans_all: =%"

set "ans_y=%ans_yes:~0,1%"
set "ans_n=%ans_no:~0,1%"
set "ans_a=%ans_all:~0,1%"

endlocal & (
    set "ans_y=%ans_y%"
    set "ans_n=%ans_n%"
    set "ans_a=%ans_a%"
)

echo %ans_y%|rmdir /s modules

Comment: This is extremely useful when one works in a multilingual and/or multinational coding environment/organization/life. +1 for that.
Answer: YES.EXE
Yes is a fantastic tool that will continually answer Yes, No or whatever to any process that is asking for input.
If you run it by itself, it just outputs y + enter over and over. But that's not really what it's meant for. It's meant for piping into another program that is looking for a response to a prompt.
The simplest use case:
yes|rd temp /s
You can use yes.exe to output any argument or string: (stupid example warning):
yes hello world for a simple basic 10 PRINT "Hello World": GOTO 10
What it's really for:
It's meant for command line tools that can have a repetitive prompt but don't have a built-in /y or /n.
For example, you're copying files and keep getting the Overwrite? (Yes/No/All) prompt, you get stuck having to hammer to "N" key for No. Here's the fix:
yes n|copy * c:\stuff
How to get it?
This is just a small part of the GNU Core Utils for Windows, which provides the basic Linux commands to Windows people. VERY, VERY useful stuff if you write a lot of batch files.
If you have Git for Windows, you already have it, along with the rest of the GNU Core Utils. Check your PATH for it. It's probably in C:\Users\USERNAME\AppData\Local\Programs\Git\usr\bin
If you need to download the Windows binaries, they're available from a lot of different places, but the most popular is probably at https://cygwin.com/packages/summary/coreutils.html


How to split a string and record each split as a distinct variable C++

Question: I was looking at a popular StackOverflow post about how to split strings.  I have found this very useful, but I'd like to take each split and store it in array or a distinct string variable.  Such that I can access: scott, tiger, mushroom, or fail.  Below is my attempt to do this, but I cannot complile this due to an error:

cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'char' in assignment

Does anyone know an efficient way of doing this?
#include <bits/stdc++.h>
using namespace std;

#include <stdio.h>
#include <string.h>

char str[10];
void setup(){
    std::string s = "scott>=tiger>=mushroom>=fail";
    std::string delimiter = ">=";
    int arrayIndex = 0;

    size_t pos = 0;
    std::string token;
    while ((pos = s.find(delimiter)) != std::string::npos) {
        token = s.substr(0, pos);
        std::cout << token << std::endl;
        s.erase(0, pos + delimiter.length());
        str[arrayIndex++] = token;

    }
    std::cout << s << std::endl;
}

void loop(){
}

Comment: Why not just use an exiting strsplit?
Answer: str[] is an array of individual chars, but you are trying to store std::string objects in it, hence the error. Change the array to hold std::string instead of char. And then consider using std::vector instead of a fixed array.
#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> str;

void setup(){
    std::string s = "scott>=tiger>=mushroom>=fail";
    std::string delimiter = ">=";

    size_t start = 0, pos;
    std::string token;

    while ((pos = s.find(delimiter, start)) != std::string::npos) {
        token = s.substr(start, pos-start);
        str.push_back(token);
        start = pos + delimiter.size();
    }
    if (start < s.size())
        str.push_back(s.substr(start));

    for(auto &elem : str)
        std::cout << elem << std::endl;
}

Online Demo
Comment: @Feynman137 add `#include `
Comment: @Feynman137 like arrays, vector indexes start at 0, not 1. Make sure the vector is not `empty()` before accessing it
Comment: I see the method you are proposing and it seems to align with the question well, but the compiling is giving me the error `'cout' is not a member of 'std'`
Comment: How would one access say the first entry in the vector?  I am trying `String elem = str.at(1);` and `String & elem = str[1]`;  not sure why this is failing.
Comment: Looks like I needed to say `std::string zzz = str.at(0);` instead of `String zzz = str.at(0);`
Answer: TRY this:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Suites
#include <boost/test/unit_test.hpp>
#include <stdio.h>
#include <string>
#include <unordered_map>

class StringLabelAdapter
{
std::unordered_map<std::string, int> firstLabelFound;
public:

StringLabelAdapter(std::string& stringPassedIn, std::string& delimiter):firstLabelFound()
{
    int arrayIndex = 0;

    size_t delimiterPosition = 0, prevDelimiterPosition = 0;

    while ((delimiterPosition = stringPassedIn.find( delimiter, prevDelimiterPosition)) != std::string::npos)
    {
        std::string token = stringPassedIn.substr(prevDelimiterPosition, delimiterPosition);
        if (!Exists(token))
        {
            firstLabelFound[token] = prevDelimiterPosition + 1;
        }
        prevDelimiterPosition += token.size() + delimiter.size();
    }
    };

    bool Exists(std::string& labelToCompare) { return firstLabelFound.find(labelToCompare) != firstLabelFound.end(); };
    };
    BOOST_AUTO_TEST_SUITE(TestStringLabelAdapterSuite)
    BOOST_AUTO_TEST_CASE(TestStringLabelAdapter)
    {
    std::string stringPassedIn = "scott>=tiger>=mushroom>=fail";
    std::string delimiter = ">=";
    StringLabelAdapter test(stringPassedIn,delimiter);
    std::string s("scott");
    BOOST_CHECK(test.Exists(s));
    }
    BOOST_AUTO_TEST_SUITE_END()

if you don't want boost unit test remove the boost header and the boost suite and put it in main.


Do Random Effects Regressions drop respondents with only 1 wave of data?

Question: In a random effects regression across 2 waves of panel data in Stata (or really any statistical program) like below:
xtreg health_y age_y income_y, cluster(current_county_y1) re robust
When respondents are in 1 but not both waves are these respondents included in the random effects regression? Or are they dropped?
Do only individuals with 2 waves of data get included in a random effects regression or is any wave for which they have data included?
Also is there any way to include individuals who only have one wave and would this even make sense?
Very best,
John
Answer: xtreg reports the minimum number of observations per group in the output. You shouldn't see any ones there if Stata was dropping them.
You can verify this with a simple simulation where you delete the first of two observations for unit 1 and the check the e(sample), which marks estimation sample:
. use if id != 407 & !missing(fte) using http://fmwww.bc.edu/repec/bocode/c/CardKrueger1994.dta, clear
(Dataset from Card&Krueger (1994))

. bys id: drop if _N!=2
(19 observations deleted)

. drop if id == 1 & t==0
(1 observation deleted)

. xtset id t
       panel variable:  id (unbalanced)
        time variable:  t, 0 to 1
                delta:  1 unit

. xtdes

      id:  1, 2, ..., 522                                    n =        389
       t:  0, 1, ..., 1                                      T =          2
           Delta(t) = 1 unit
           Span(t)  = 2 periods
           (id*t uniquely identifies each observation)

Distribution of T_i:   min      5%     25%       50%       75%     95%     max
                         1       2       2         2         2       2       2

     Freq.  Percent    Cum. |  Pattern
 ---------------------------+---------
      388     99.74   99.74 |  11
        1      0.26  100.00 |  .1
 ---------------------------+---------
      389    100.00         |  XX

. xtreg fte i.(treated bk kfc roys wendys t), re cluster(id)
note: 1.wendys omitted because of collinearity

Random-effects GLS regression                   Number of obs     =        777
Group variable: id                              Number of groups  =        389

R-sq:                                           Obs per group:
     within  = 0.0003                                         min =          1
     between = 0.2412                                         avg =        2.0
     overall = 0.1842                                         max =          2

                                                Wald chi2(5)      =     256.45
corr(u_i, X)   = 0 (assumed)                    Prob > chi2       =     0.0000

                                   (Std. Err. adjusted for 389 clusters in id)
------------------------------------------------------------------------------
             |               Robust
         fte |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
     treated |
         NJ  |  -.9138251   .9044213    -1.01   0.312    -2.686458    .8588081
        1.bk |   .8437428   1.116946     0.76   0.450    -1.345431    3.032916
       1.kfc |  -9.291282   1.074727    -8.65   0.000    -11.39771   -7.184855
      1.roys |  -1.050834   1.306531    -0.80   0.421    -3.611588    1.509919
    1.wendys |          0  (omitted)
         1.t |  -.1174794   .4526165    -0.26   0.795    -1.004592    .7696327
       _cons |   20.18882   1.178418    17.13   0.000     17.87916    22.49848
-------------+----------------------------------------------------------------
     sigma_u |  5.3011202
     sigma_e |  6.2737008
         rho |  .41656354   (fraction of variance due to u_i)
------------------------------------------------------------------------------

. count if e(sample)==0
  0

As you can see the singleton observation was included in the model.
Comment: In the GLS transformation, you alter the data by subtracting the weighted mean for each panel: $y_{it}-\lambda \bar y_i.$ In the case of the singleton panel, $y_{it}=\bar y_i$, but because you are multiplying by $\lambda$, which is a function error variances and the number of time periods, you don't get a zero. There's also a corresponding transformation for the covariates that has the same intuition. Then you perform pooled OLS on this transformed data. So the singleton observation remains and contributes to the estimation of the slope and intercept.
Comment: Dimitriy,

Thank you for your response, could I ask you to explain further how respondents in panel data are contributing to the analysis when they only appear in the first of two waves for example? In simple terms, how is their presence in this first wave adding information to the relationship examined?

For example, in a random effects regression across 2 waves like below:
xtreg health_y age_y income_y, re
When respondents are in 1 but not both waves, how does their presence in 1 wave contribute to an overall analysis of employment change and health across 2 waves?