javax.imageio.IIOException: Can't read input file! is being thrown, but I don't know why it is?

Question: I wanted to learn how to make 3d graphics in java and found this code and study it and looked on how it worked and I searched how each command works. I ran the code and it gives me an error I don't really understand how its not working. Its suppose to place the textures on the walls in the map but won't place them. I am using eclipse to run the code.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Texture {
    public int[] pixels;
    private String loc;
    public final int SIZE;
        public Texture(String location, int size) {
        loc = location;
        SIZE = size;
        pixels = new int[SIZE * SIZE];
        load();
    }

    private void load() {
        try {
            BufferedImage image = ImageIO.read(new File(loc));
            int w = image.getWidth();
            int h = image.getHeight();
            image.getRGB(0, 0, w, h, pixels, 0, w);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Texture wood = new Texture("res/wood.png", 64);
    public static Texture brick = new Texture("res/redbrick.png", 64);
    public static Texture bluestone = new Texture("res/bluestone.png", 64);
    public static Texture stone = new Texture("res/greystone.png", 64);
}

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.util.ArrayList;

import javax.swing.JFrame;

public class Game extends JFrame implements Runnable{

    private static final long serialVersionUID = 1L;
    public int mapWidth = 15;
    public int mapHeight = 15;
    private Thread thread;
    private boolean running;
    private BufferedImage image;
    public int[] pixels;
    public ArrayList<Texture> textures;
    public Camera camera;
    public Screen screen;
    public static int[][] map =
        {
            {1,1,1,1,1,1,1,1,2,2,2,2,2,2,2},
            {1,0,0,0,0,0,0,0,2,0,0,0,0,0,2},
            {1,0,3,3,3,3,3,0,0,0,0,0,0,0,2},
            {1,0,3,0,0,0,3,0,2,0,0,0,0,0,2},
            {1,0,3,0,0,0,3,0,2,2,2,0,2,2,2},
            {1,0,3,0,0,0,3,0,2,0,0,0,0,0,2},
            {1,0,3,3,0,3,3,0,2,0,0,0,0,0,2},
            {1,0,0,0,0,0,0,0,2,0,0,0,0,0,2},
            {1,1,1,1,1,1,1,1,4,4,4,0,4,4,4},
            {1,0,0,0,0,0,1,4,0,0,0,0,0,0,4},
            {1,0,0,0,0,0,1,4,0,0,0,0,0,0,4},
            {1,0,0,0,0,0,1,4,0,3,3,3,3,0,4},
            {1,0,0,0,0,0,1,4,0,3,3,3,3,0,4},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,4},
            {1,1,1,1,1,1,1,4,4,4,4,4,4,4,4}
        };

    public Game() {
        thread = new Thread(this);
        image = new BufferedImage(1920, 1080, BufferedImage.TYPE_INT_RGB);
        pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
        textures = new ArrayList<Texture>();
        textures.add(Texture.wood);
        textures.add(Texture.brick);
        textures.add(Texture.bluestone);
        textures.add(Texture.stone);
        camera = new Camera(4.5, 4.5, 1, 0, 0, -.66);
        screen = new Screen(map, mapWidth, mapHeight, textures, 1920, 1080);
        addKeyListener(camera);
        setSize(1920, 1080);
        setResizable(true);
        setTitle("3D Engine");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBackground(Color.black);
        setLocationRelativeTo(null);
        setVisible(true);
        start();
    }
    private synchronized void start() {
        running = true;
        thread.start();
    }
    public synchronized void stop() {
        running = false;
        try {
            thread.join();
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void render() {
        BufferStrategy bs = getBufferStrategy();
        if(bs == null) {
            createBufferStrategy(3);
            return;
        }
        Graphics g = bs.getDrawGraphics();
        g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
        bs.show();
    }
    public void run() {
        long lastTime = System.nanoTime();
        final double ns = 1000000000.0 / 60.0;//60 times per second
        double delta = 0;
        requestFocus();
        while(running) {
            long now = System.nanoTime();
            delta = delta + ((now-lastTime) / ns);
            lastTime = now;
            while (delta >= 1)//Make sure update is only happening 60 times a second
            {
                //handles all of the logic restricted time
                screen.update(camera, pixels);
                camera.update(map);
                delta--;
            }
            render();//displays to the screen unrestricted time
        }
    }
    public static void main(String [] args) {
        new Game();
    }
}

This is the error message I been getting every time I run the code. I have tried using different locations for the textures but keep getting the same error message.
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    at Texture.load(Texture.java:20)
    at Texture.<init>(Texture.java:15)
    at Texture.<clinit>(Texture.java:29)
    at Game.<init>(Game.java:46)
    at Game.main(Game.java:104)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    at Texture.load(Texture.java:20)
    at Texture.<init>(Texture.java:15)
    at Texture.<clinit>(Texture.java:30)
    at Game.<init>(Game.java:46)
    at Game.main(Game.java:104)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    at Texture.load(Texture.java:20)
    at Texture.<init>(Texture.java:15)
    at Texture.<clinit>(Texture.java:31)
    at Game.<init>(Game.java:46)
    at Game.main(Game.java:104)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    at Texture.load(Texture.java:20)
    at Texture.<init>(Texture.java:15)
    at Texture.<clinit>(Texture.java:32)
    at Game.<init>(Game.java:46)
    at Game.main(Game.java:104)

Answer: The exception message is self-explanatory: res/* files cannot be read.
Assuming you already have a res folder including these files, that folder should be in classpath. If not put it in classpath or change res/* into absolute path, e.g. C:\res\wood.png
The exception is thrown on javax.imageio.ImageIO:
public static BufferedImage read(File input) throws IOException {
        if (input == null) {
            throw new IllegalArgumentException("input == null!");
        }
        if (!input.canRead()) {
            throw new IIOException("Can't read input file!");
        }

The File.canRead() is (on openJdk 1.8.0_192)
 public boolean canRead() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        if (isInvalid()) {
            return false;
        }
        return fs.checkAccess(this, FileSystem.ACCESS_READ);
    }

The input.canRead() returns false only if the path is invalid or the path or file does not have read access. If you use an absolute path in Linux, check that the user has read access in the path recursively
Comment: @3dog It would appear your image files are _resources_. Never try to access resources via the `File` class. You should be using `Class#getResource` or `Class#getResourceAsStream` instead. Make sure you use the correct path as well—see the [documentation](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Class.html#getResourceAsStream(java.lang.String)).


Interaction term with several levels in multi linear regression in R

Question: first of all thank you very much for admitting me!
I am currently stuck with a problem regarding interaction terms:
I would like to interact a categorical variable with several levels with a continuous variable in a multi-linear regression.
However, all of the ways I know how to do it in R failed so far.
Can anybody help me?
Is it even possible to create such an interaction term?
To illustrate, here is my example:
categorical variable: acquired_years (indicates how many years before a certain event a firm was acquired) --> categories: not_acquired, acquired_one_year_before, acquired_two_years_before, acquired_three_years_before, acquired_four_years_and_more_before
continuous variable: firm_age (age of the firm of interest)
regression model:
y = firm_age + firm_age * acquired_one_year_before+ firm_age * acquired_two_years_before + firm age * acquired_three_years_before + firm_age * acquired_four_years_and_more_before + control_variables; omitted category: not_acquired
Comment: You can achieve this in two ways. The first one is to convert `acquired_years` into a factor by calling `factor(acquired_years)`. The second one is to create the regressors by hand, which is a good excercise to learn how R is dealing with factors and interactions.
Comment: Hey Michael, so you mean manually dummy coding the variables? In this case I would need k-1 dummy variables, correct? So in my case with 5 categories, I would need 4 binary dummy variables, right?
Comment: Not 100% sure I got your question, but I'd say yes. 4 binary dummies and for each of them its product with `firm_age`.
Comment: That is exactly what I mean! Thank you very much! So non_acquired would be my base category and the coefficient on firm_age would be the effect of age on y if the firm has not been acquired.
Comment: Yes. And the interaction effects will show the change in slope for the corresponding other categories. But remember, that instead of writing a lot of code, you will end up with this by writing `firm_age * factor(acquired_year)`
Answer: Yes, it is definitely possible, and in fact I do it all the time. The result is an ANCOVA model where the regression lines are not parallel (i.e. you're basically fitting a new regression line of your response variable against firm_age for each level of acquired_years).
Here's an example (please excuse my silly example):

favourite.fruit = as.factor(c("apple","apple","orange","apple","orange"))
age = c(6,8,7,9,7)
height = c(70,80,75,90,87)
my.df = cbind.data.frame(favourite.fruit,age,height)
colnames(my.df) = c("favourite.fruit","age","height")
my.lm = lm(age ~ favourite.fruit + height + favourite.fruit * height, my.df)
my.lm
And the returned result:

Call:
lm(formula = age ~ favourite.fruit + height + favourite.fruit *
    height, data = my.df)

Coefficients:
                 (Intercept)         favourite.fruitorange                        height
                      -4.333                        11.333                         0.150
favourite.fruitorange:height
                      -0.150

To force the omitted category to be 'orange':

favourite.fruit = as.factor(c("apple","apple","orange","apple","orange"))
age = c(6,8,7,9,7)
height = c(70,80,75,90,87)
my.df = cbind.data.frame(favourite.fruit,age,height)
colnames(my.df) = c("favourite.fruit","age","height")
my.df$favourite.fruit = relevel(my.df$favourite.fruit, ref = "orange")
my.lm = lm(age ~ favourite.fruit + height + favourite.fruit * height, my.df)
my.lm

Results:

Call:
lm(formula = age ~ favourite.fruit + height + favourite.fruit *
    height, data = my.df)

Coefficients:
                (Intercept)         favourite.fruitapple                       height  favourite.fruitapple:height
                  7.000e+00                   -1.133e+01                    4.039e-17                    1.500e-01
Comment: Thank you for your response! However, in your model you only interact the dummy for apple with height (favourite.fruitapple:height), correct? Would it also be possible to have all interactions per category in one model? (omitting one category of course)
Comment: @Cgal Yeah, as you can see I only have two levels in my example. Since you have multiple levels in yours, the same code should give you the four terms you need.
Comment: I just had to take a little detour, now it works perfectly!
Comment: @CGal For the square of firm_age, try  poly(height,degree=2,raw=TRUE). Next time if you need to dummy code manually, consider the model.matrix function as well :)


Why have some MLB managers stopped wearing uniforms?

Question: I believe that for many years, MLB managers would always wear the same uniform as their players during games.  However, I've been watching more games on TV this year, and it seems that many managers now wear other clothing.
For example, in this photo from May 9, 2015 (credit David Richard of USA Today), we see Cleveland manager Terry Francona making a visit to the mound.  The shirt he's wearing is completely different from his player's uniforms, and it doesn't look like he has a uniform jersey underneath.

Why the break with tradition?  Was there a rule change, or simply managers deciding to dress differently for some reason?
Answer: Major league players, managers and coaches are required to abide by strict uniform guidelines. They are required to be in uniform, but can also wear other team apparel on top to stay warm.
However, some managers have elected not to comply and wear just a team pullover for various reasons. MLB can and does check and fine repeat offenders.
Terry Francona's case is a bit different though. During the 2005 season he had some circulatory and clotting issues that led to him thinking he was having a heart attack. Because of this he has to wear several layers of clothing in order for his body to behave properly.

During the 2005 season, Francona was hospitalized after complaining of severe chest pains. Tests revealed significantly clogged arteries, but it was concluded that Francona had not suffered a heart attack. This incident, as well as a life-threatening pulmonary embolism suffered in 2002, painful knees, and ongoing treatment for blood clots, has led to circulation issues which necessitate wearing extra clothes, including two pairs of tights. This is also why his regular uniform top is usually hidden by a pullover
Comment: This will sound pedantic, but nowhere in the rules does it mention that managers have to be in uniform, as this answer suggests.  The rules do state that coaches have to be in uniform, specifically base coaches.  They are required to wear uniforms while performing their responsibilities on the field, but the current rules say nothing about requiring managers to wear a uniform.
Comment: Buck Showalter wears a pullover like Fancona.  It is well known that he doesn't wear a jersey.  He did with the "Baltimore" home uniforms last month. [Picture 2](http://www.baltimoresun.com/sports/orioles/blog/bal-orioles-wear-baltimore-on-home-jerseys-20150512-photogallery.html)


What does KSP mean?

Question: I have a Yamaha PSR-540. There are a few voices on it with another voice's name and KSP in their names:

GrndPianoKSP
BritePnoKSP
ElecGrPnoKSP
HonkytonkKSP
El.Piano1KSP
El.Piano2KSP
Harpsi.KSP
Clavi.KSP
Vibes KSP
Marimba KSP

To me, they sound like they are duplicates of the other voices. What does KSP mean?
Comment: *Kerbal Space Program*
Comment: Took about a minute to google KSP. Did you have a try? This only just comes within the MP&T remit, in my opinion.
Comment: @Tim `"KSP" yamaha` doesn't get anything clear and just `"KSP"` gets *Kerbal Space Program*.
Comment: I stand corrected -- Yamaha manuals talk a lot about stereo panning functions but never mention the difference between $VOICE  and $VOICE.KSP  .  Stupid on their part.
Comment: @Carl Hi, may I ask what your search terms are? I really can't find this by googling (tried the above ones and `"ksp" yamaha keyboard` and couldn't find anything)
Answer:
"KSP" means "Keyboard Stereo Panning", that means for these voices, the placement of the instrument changes in the stereo panorama, depending on the position on the keyboard. So, "low notes" come from "left", "middle notes" "from the middle" and "high notes" "from right" (viewed from the player). For the versions of the Voices WITHOUT "KSP", the position in the stereo panorama is FIXED.

–Translated from Yamaha Europe forum post by t4chris

What does KSP mean?


Comparing reduced, intermediate and complex model in logistic regression?

Question: How should I compare my logistic regression models?
My study is about the association between diabetes (dia), and a genetic variation (GV) I'm adjusting for confounders such as gestational age (GA) and gender (GE).
I have these models:
the simpel, reduced model
dia ~ GV

half complex, intermediate model
dia ~GV + GA

The full complex model
dia ~GV + GA + GE

All three models are testet from the same dataset. But I don't know how to present my models in my project. Can I compare the reduced model and the full model? Or should the "half" model be included in the project as well? I'm only interested in the coefficient for GV. So is it important to include all models?
I'm asking because that would be a lot of forest plots to show, and I hope that it is okay to compare only the reduced and the full model.
But if that does not make sense, then I will include all three. Hope you can help and clarify things for me
Thanks in advance!
Answer: No presentation that you are considering would violate any statistical rules that I know of. It's a question of how much they would show about your results and what you found. You also might not need to show forest plots for all three.
You could

present just the complex model
present the simple and the complex one
present all three

And the presentation could be done in a table.
But, if this is a project for a journal or a school, then they may have their own requirements.


$T_2$ spaces and isolated points

Question: Is there a topological Hausdorff space with an infinite number of isolated points such that any infinite set of isolated points have an infinite number of limit points !? (Of course it would be impossible if a limit point is a limit of a sequence.)
Answer: Yes: $\beta\Bbb N$, the Čech-Stone compactification of $\Bbb N$, which is a compact Hausdorff space, has that property. In fact, every infinite subset of $\Bbb N$ has $2^{\mathfrak{c}}$ limit points. (Every point of $\Bbb N$ is isolated.)
Comment: @julien: Thanks!
Comment: Would you give me some references to study the properties of $\beta\Bbb{N}$?
Comment: @user41304: Three possibilities: Russell C. Walker, [*The Stone-Čech Compactification*](http://www.amazon.com/Stone--Compactification-Ergebnisse-Mathematik-Grenzgebiete/dp/3540066993); Neil Hindman & Dona Strauss, [*Algebra in the Stone-Čech Compactification*](http://www.amazon.com/Stone--Compactification-Ergebnisse-Mathematik-Grenzgebiete/dp/3540066993); Leonard Gillman & Meyer Jerison, [*Rings of Continuous Functions*](http://www.amazon.com/Rings-Continuous-Functions-University-Mathematics/dp/1258637391). I'm personally familiar only with the last; I've picked up most of what I know in bits.

$T_2$ spaces and isolated points


Proof that Gauss-Jordan elimination works

Question: Gauss-Jordan elimination is a technique that can be used to calculate the inverse of matrices (if they are invertible).  It can also be used to solve simultaneous linear equations.
However, after a few google searches, I have failed to find a proof that this algorithm works for all $n \times n$, invertible matrices.  How would you prove that the technique of using Gauss-Jordan elimination to calculate matrices will work for all invertible matrices of finite dimensions (we allow swapping of two rows)?
Induction on $n$ is a possible idea: the base case is very clear, but how would you prove the inductive step?
We are not trying to show that an answer generated using Gauss-Jordan will be correct.  We are trying to show that Gauss-Jordan can apply to all invertible matrices.
Note: I realize that there is a similar question here, but this question is distinct in that it asks for a proof for invertible matrices.
Comment: You should prove that each of the operations involved in the algorithm (swapping rows, adding a multiple of one row to another row, multiplying a row by a nonzero constant) do not change the rank of the matrix; then show that, under a suitable definition of "simplify", after a suitable number of steps of the algorithm any matrix that is not in row-echelon form can be turned into a "simpler" matrix by the algorithmic step.
Answer: This is one of the typical cases where the most obvious reason something is true is because the associated algorithm cannot possibly fail.
Roughly speaking, the only way Gauss-Jordan can ever get stuck is if (at any intermediate point) there is a column containing too many zeroes, so there is no row that can be swapped in to produce a non-zero entry in the expected location.  However, if this does happen, it is easy to see that the matrix is non-invertible, and   since the row operations did not cause this, it must have been the original matrix that is to blame.
Comment: @AndrewSalmon Think of all the operations that are needed: the only one that can fail is division by zero.  It's not particularly quantitative, but I don't see how it isn't rigorous.
Comment: OK. But how do you show that "the only way it can get stuck is if there is a column containing too many zeroes?"  I was looking for something a little more rigorous.
Answer: Assumption: Square Invertible matrix.
Gauss-Jordan method is typically taught after Gaussian Elimination method for solving System of linear equations. So, I'm assuming you know about Gaussian Elimination.
Consider system of linear equations $Ax=b$.
$Ax=b$.....................................(1)
$Ux = c$.....................................(2)
$Ix = A^{-1}b$...............................(3)
We can go from step (2) to step (3) in Gauss-Jordan method only if we assume that U has full set of n pivots.
If some pivot is zero, we cannot use it to eliminate elements above it for reaching Identity matrix.
If A is invertible => A has full set of n pivots => We can go from U to I.
$\therefore$ For all invertible matrix A, Gauss-Jordan method works.
If $b = I$
then $x=A^{-1}$.


Maximum and Minimum Values of the function

Question: What will be the maximum and minimum value of the following function,
$f(x,y)=3x+4y$ in the region $0\le x \le1$, $-1\le y \le1 $
Comment: Your thoughts on the problem?
Answer: $\max_{x,y} f(x,y) = \max_x \max_y f(x,y)$, where $x \in [0,1], y \in [-1,1]$, and similarly for $\min$.
For example, $\max_y f(x,y) = f(x,1) = 3x+4$, and $\max_x (3x+4) = 3+4 = 7$.
Answer: Here's another way to consider this (and it doesn't even use calculus), which touches on what cooper.hat describes.
Consider that the equation $ \ 3x + 4y \ = C \ $ represents a "family" of parallel lines, shifting "upward and to the right" as $ \ C \ $ increases.  (This is a bit clearer if we write the equation in "slope-intercept" form as  $ \ y = \frac{C}{4} - \frac{3}{4}x \ . $ ) The region you are interested in is a rectangle with sides parallel to the coordinate axes.  So as we follow these lines in the "direction of increasing C", there is a line which just makes contact with the "lower left" vertex of the rectangle, $ \ ( 0, -1 ) \ $ .  The value of $ \ C \ $ for that line is $ \ 3 \cdot 0 \ + \ 4 \cdot (-1) \ = \ -4 \ , $ so this is the minimum value of our function for this region.
As we continue, successive lines pass through the perimeter and interior of the rectangle, until we reach a line which makes "final contact" with the rectangle at its "upper right" vertex, $ \ ( 1 , 1 ) \ . $  There, the value of $ \ C \ $ is $ \ 3 \cdot 1 \ + \ 4 \cdot 1 \ = \ 7 \ , $ the maximum value of our function for the region.
More sophisticated methods would show more directly that we should not expect the extremes for the function to occur in the interior of the rectangle, leaving us to check the sides and then the vertices.  For a (bi)linear function such as the one in this problem and regions like rectangles, we can jump immediately to testing the values at the vertices.


How to continuously read from stdin (not just once input file is done)?

Question: I have these two scripts:
clock.py
#!/usr/bin/env python3
import time

while True:
    print("True", flush=True)
    time.sleep(1)

continuous_wc.py
#!/usr/bin/env python3
import sys

def main():
    count = 0
    for line in sys.stdin:
        sys.stdout.write(str(count))
        count += 1

if __name__=='__main__':
    main()

And I run them like so:
./clock.py | ./continuous_wc.py

I'm hoping that it prints:
1
2
3
4
5
...

Every second is like a clock, because it's counting the lines in the file basically. But it doesn't output anything. Why not?
Comment: `print("True", flush=True)`
Comment: The problem isn't with reading, it's with writing to a pipe.
Comment: You should write a newline after the count in `continuous_wc.py`, since you want each number on a different line. That will also solve the problem, since output is line-buffered.
Comment: Why are you using `sys.stdin` and `sys.stdout`, instead of `input()` and `print()`?
Comment: You need to flush the stdout buffer in `clock.py`.
Comment: @Barmar thank you. I have updated the question with that suggestion. It still seems not to have any output.
Comment: I think what Barmar is suggesting is that you also need to flush the output from `continuous_wc.py`.
Comment: You could try `export PYTHONUNBUFFERED=1 ; ./clock.py | ./continuous_wc.py`
Comment: If your Python is 3.6 or newer, you can write more elegantly (and with the desired newline): `sys.stdout.write(f"{count}\n")`.
Answer: In addition to print(x, flush=True) you must also flush after sys.stdout.write.
Note that the programs would technically work without flush, but they would print values very infrequently, in very large chunks, as the Python IO buffer is many kilobytes. Flushing is there to make it work more real-time.
sys.stdout.write(str(count))
sys.stdout.flush()

Answer: Using everyone's advice, this is what I have now (which works):
clock.py
#!/usr/bin/env python3
import time

while True:
    print("True", flush=True)
    time.sleep(1)

continuous_wc.py
#!/usr/bin/env python3
import sys

def main():
    count = 0
    for line in sys.stdin:
        print(count, flush=True, end='\r')
        count += 1

if __name__=='__main__':
    main()

I had to use flush=True in both the write and the read scripts. However when using PYTHONUNBUFFERED=1, I was able to skip this and it worked. Thanks @Mark Setchell. Additionally, I am using print and stdin but it seems fileinput.input works as well.


Can contrasts and interaction contrasts be identical in linear mixed model?

Question: I have a doubt with respect to the estimated marginal means of a linear mixed model.
I performed a mixed model like the one in the example below:
library("lme4")
library("emmeans")

model <- lmer(dep_variable ~ covariate * condition + (condition | subject), dataset)
summary(model)
anova(model)

After this, I checked the contrasts:
emmeans(model, pairwise ~ condition)
emmeans(model, pairwise ~ condition | covariate)

I wanted to check which factors (i.e., covariate and condition) affected my dependent variable (i.e., dep_variable). The dependent variable and the covariate were numeric variables, while condition was a factor variable with 3 levels.
After performing the model and checking the estimated marginal means, I realized that the estimated marginal means were the same both when I looked at the main effect condition and when I checked the interaction between covariate and condition.
Moreover, I realized that the contrasts of the interaction were centered at the mean value of the covariate (numeric variable).
I have two questions:
Did I make a mistake? If not, can I change the value of my covariate in order to explore the contrasts by "holding" the covariate to another value (not the mean)?
Comment: By default, only one covariate value is used -- its mean. So the two `emmeans` calls you show are guaranteed to yield the same results. That is, it doesn't matter whether you explicitly condition on it or not because the same value is used either way. If you use an `at` specification to specify several covariate values, then you will see an assortment of results in that second call.
Answer: When you have interactions, things indeed get more complicated. But what you describe seems valid. That is, you select a specific value for the covariate, and make the pairwise comparisons for the different conditions using this particular value. Also, because you have fitted an interaction model, note that the main effect of condition is interpreted for a specific value of covariate, namely for covariate = 0.
With that in mind, I feel that your question mainly relates to the use of the emmeans package, and therefore, I would suggest having a look at the online documentation. More specifically, in the Interaction Analysis vignette. I would speculate that emmeans(model, pairwise ~ condition) produces results for covariate = mean(covariate) because this is often more relevant than covariate = 0. For example, say that the covariate is age. It makes more sense to produce pairwise comparisons for condition for the average age in your data, than for age = 0 (assuming you have a study on subjects with ages far away from zero).
Comment: It does not use `covariate = 0` by default in any situation. i don't know why you say that.
Comment: @RussLenth I think I said that is uses `covariate = mean(covariate)` because this is more relevant than `covariate = 0`. Nonetheless, as always, there are exceptions to the rule. In longitudinal data where I work, `covariate` is time, and there it makes sense to see what happens at baseline, i.e., at time = 0.
Comment: I know you said that, but earlier you said that covariate = 0 is the custom when it is an interaction model. And I don't know anywhere where that is recommended as a routine analysis.
Comment: @RussLenth what I mean is that the coefficients for the main effect of condition are interpreted for `covariate = 0`. That is, in the model $\beta_0 + \beta_1 cond + \beta_2 cov + \beta_3 \{cond \times cov\}$, the coefficient $\beta_1$, what I called the main effect of cond is interpreted for cov = 0.
Comment: Well, it all depends on the parameterization, but under the default contr.treatment coding, ,(beta_0, bata_2)  together give the intercept and slope for the reference level of cond, and (beta0 + beta_1, beta_2 + beta_3) give the intercept and slope for the other level of cond. So really it is beta_0 and beta_2 that have a context with the covariate being zero.


Como fazer o p:wizard voltar para determinada aba?

Question: Tenho um p:wizard no qual, caso uma determinada condição seja true, ele avança para a ultima aba ao clicar em próximo. Mas não estou conseguindo fazer ele retornar para a primeira aba, caso eu clique em voltar. Existe uma maneira de fazer isso com o wizard?
Método onFlowProcess
public String onFlowProcess(FlowEvent event) {
   boolean skip = !tipoProtocoloSelecionado.equals(TipoProtocoloConstante.REGISTRO_ONLINE_EMPRESA);

   if(skip) {
       skip = false;

       return "tabAnexoArquivos";
   }

   else {
      return event.getNewStep();
   }
 }

View
<h:form>

                    <h:outputLabel value="Os campos marcados com * são de preenchimento obrigatório" style="font-weight: bold; color: #f00;" />

                    <h:outputLabel value="Tipo*: " style="font-weight: bold"/>

                    <h:selectOneRadio value="#{registroOnlineEmpresaController.empresa.tipoPessoaJuridica}"
                                      style="display: inline;" required="true"
                                      requiredMessage="Tipo: Preenchimento Obrigatório">

                        <f:selectItems value="#{registroOnlineEmpresaController.obterTiposPessoaJuridica()}"/>

                    </h:selectOneRadio>

                        <h:outputLabel value="Subtipo*: " style="font-weight: bold"
                                       rendered="#{registroOnlineEmpresaController.renderizaSubTiposPessoaJuridica}"/>

                        <h:selectOneMenu value="#{registroOnlineEmpresaController.empresa.subtipoPessoaJuridica}"
                                         style="display: inline; background-color: #fff;"
                                         rendered="#{registroOnlineEmpresaController.renderizaSubTiposPessoaJuridica}"
                                         required="true" requiredMessage="Subtipo: Preenchimento Obrigatório">

                            <f:selectItem noSelectionOption="true" itemLabel="Selecione..." />

                            <f:selectItems value="#{registroOnlineEmpresaController.obterSubtiposPessoaJuridica()}"/>

                        </h:selectOneMenu>

                    <h:outputLabel value="Tipo de Registro*: " style="font-weight: bold"/>

                    <h:selectOneMenu value="#{registroOnlineEmpresaController.tipoProtocoloSelecionado}"
                                     style="display: inline; background-color: #fff;" required="true"
                                     requiredMessage="Tipo de Registro: Preenchimento Obrigatório"
                                     converter="tipoProtocoloConverter">

                            <f:selectItem noSelectionOption="true" itemLabel="Selecione..." />

                            <f:selectItems value="#{registroOnlineEmpresaController.obterTiposProtocolos()}"
                                           var="tipoProtocolo" itemValue="#{tipoProtocolo}" itemLabel="#{tipoProtocolo.descricao}"/>

                        </h:selectOneMenu>

                    <h:outputLabel value="Razão Social*: " style="font-weight: bold"/>

                        <h:outputLabel value="Nome Fantasia*: " style="font-weight: bold"
                                       rendered="#{registroOnlineEmpresaController.renderizarCamposRegistro()}"/>

                    <h:outputLabel value="CNPJ*: " style="font-weight: bold"/>

                    <h:outputLabel value="Email*: " style="font-weight: bold"/>

                            <h:outputLabel value="Categoria*: " style="font-weight: bold"/>

                            <h:selectOneMenu value="#{registroOnlineEmpresaController.empresa.categoria}" style="background-color: #fff;"
                                             required="true" requiredMessage="Categoria: Selecione uma Opção...">
                                <f:selectItems value="#{registroOnlineEmpresaController.obterCategorias()}" />

                            </h:selectOneMenu>

                            <h:outputLabel value="Objeto Social*: " style="font-weight: bold"/>

                            <h:inputTextarea value="#{registroOnlineEmpresaController.empresa.objeto}" cols="53" rows="7"
                                             required="true" requiredMessage="Objeto Social: Preenchimento Obrigatório"/>

                            <h:outputLabel value="Restrição de Objeto Social*: " style="font-weight: bold"/>

                                <h:selectBooleanCheckbox value="#{registroOnlineEmpresaController.capitalDestacado}" title="Tem Capital Destacado"
                                                     rendered="#{registroOnlineEmpresaController.empresa.categoria == 'F'}">

                                </h:selectBooleanCheckbox>

                                <h:outputLabel value="Possui capital destacado" style="font-weight: bold"
                                               rendered="#{registroOnlineEmpresaController.empresa.categoria == 'F'}"/>

                                <h:outputLabel value="Capital Social*: " style="font-weight: bold"
                                               rendered="#{registroOnlineEmpresaController.capitalDestacado or registroOnlineEmpresaController.empresa.categoria == 'M'}"/>

                                    <f:convertNumber currencySymbol="R$" locale="pt_BR" pattern="#,##0.00" />

                                <h:outputLabel value="Capital Social da Matriz*: " style="font-weight: bold"
                                               rendered="#{registroOnlineEmpresaController.empresa.categoria == 'F'}"/>

                                    <f:convertNumber currencySymbol="R$" locale="pt_BR" pattern="#,##0.00" />

                    <h:outputLabel value="Os campos marcados com * são de preenchimento obrigatório" style="font-weight: bold; color: #f00;" />

                    <h:outputLabel value="CEP*: " style="font-weight: bold"/>

                    <h:outputLabel value="Tipo de Logradouro *: " style="font-weight: bold"/>

                    <h:outputLabel value="Logradouro *: " style="font-weight: bold"/>

                    <h:outputLabel value="Número *: " style="font-weight: bold"/>

                    <h:outputLabel value="Complemento: " style="font-weight: bold"/>

                    <h:outputLabel value="Bairro *: " style="font-weight: bold"/>

                    <h:outputLabel value="Cidade *: " style="font-weight: bold"/>

                    <h:outputLabel value="UF *:" style="font-weight: bold" />

                    <h:outputLabel value="Telefone 1 *: " style="font-weight: bold"/>

                    <h:outputLabel value="Telefone 2: " style="font-weight: bold"/>

                    <h:outputText value="AVISO: Será enviada uma mensagem no email cadastrado
                                  com data de agendamento para apresentação dos documentos originais"
                                  style="color: #f00; font-weight: bold;"/>

                    <fieldset>
                        <legend>
                            <h:outputLabel value="Anexar Arquivos" style="font-weight: bold"/>
                        </legend>

                                <ui:repeat value="#{registroOnlineEmpresaController.obterTiposDocumentosObrigatorios()}" var="itemTipoDocumento">

                                            <h:outputText value="#{itemTipoDocumento.descricao}" style="margin-right: 5px;"/>

                                    <ui:repeat value="#{registroOnlineEmpresaController.recuperarArquivosAnexados(itemTipoDocumento)}"
                                               var="itemArquivoAnexado">

                                            <h:outputText value="#{itemArquivoAnexado.nomeArquivo}" style="margin-right: 1px;"/>

                                    </ui:repeat>
                                </ui:repeat>

                    </fieldset>

                    <h:selectBooleanCheckbox value="#{registroOnlineEmpresaController.aceitacaoTermos}"
                                             title="Aceito o Termo de Responsabilidade"
                                             validator="#{registroOnlineEmpresaController.validarAceitacaoTermos}"/>

                    <h:outputLabel value="Aceito o " style="font-weight: bold"/>

                    <h:link target="blank" outcome="termoResponsabilidadeEmpresa" value="Termo de Responsabilidade"
                            style="font-size: 11px; font-weight: bold;"/>

                             <h:outputLabel value="Tipo de Documento *: " style="font-weight: bold" />
                             <h:selectOneMenu id="tiposDocumentos" style="height: 20px; width: 200px; background-color: #fff;"
                                             value="#{registroOnlineEmpresaController.tipoDocumentoSelecionado}"
                                             converter="tipoDocumentoRegistroOnlineEmpresaConverter">
                                <f:selectItem noSelectionOption="true" itemLabel="Selecione..." />
                                <f:selectItems value="#{registroOnlineEmpresaController.obterTodosTiposDocumentos()}"
                                    var="tipoDocumento" itemValue="#{itemTipoDocumento}" itemLabel="#{tipoDocumento.descricao}" />
                             </h:selectOneMenu>

                        <h:outputLabel value="Anexo de Arquivos *:" style="font-weight: bold" />

                        <p:fileUpload id="uploadAnexo"
                              fileUploadListener="#{registroOnlineEmpresaController.handleFileUpload}"
                              allowTypes="/(\.|\/)(gif|png|jpe?g|pdf)$/"
                              sizeLimit="10000000"
                              label="Escolher..."
                              multiple="true"
                              auto="true"
                              showButtons="false"
                              mode="advanced"
                              uploadLabel="Enviar Arquivos"
                              process="@this"
                              dragDropSupport="true"
                              required="true"
                              invalidFileMessage="Arquivo Inválido! Anexe apenas imagem e/ou PDFs"
                              invalidSizeMessage="Tamanho inválido! Tamanho máximo 10MB"
                              requiredMessage="Anexe pelo menos um arquivo"/>

    </h:form>

Comment: Tem certeza que a versão do primefaces é 3.5 ? O método onFlowProcess é de uma versão mais nova, na 3.5 o método se chama handleFlow.
Comment: @wryel, tenho certeza sim, a versão do Primefaces que tá rodando aqui é a 3.5
Answer: Se vc quiser fazer via JS:
onclick="PF('widget_j_idt701_j_idt702').loadStep('tabDadosEmpresa','back');"

Não deixe de especificar um id para o componente.
Se não estou confundindo as versões, no PF 7.0 vc pode utilizar PrimeFaces.execute p/ executar javascript dentro do bean.
Comment: o Wizard não tem o onclick, tentei colocar o código no onBack, mas sem sucesso
Answer: Consegui resolver fazendo binding componente e usando p:commandButtons para os botões voltar e próximo, em vez de usar os botões do p:wizard e criei métodos para serem executados ao clicar nos dois botões.
onNext
public void onNext() {
   if(wizardForm.getStep().equals("tabEnderecoContatoEmpresa") && !tipoProtocoloSelecionado.equals(TipoProtocoloConstante.REGISTRO_ONLINE_EMPRESA)) {
       RequestContext.getCurrentInstance().execute("wizardForm.loadStep(wizardForm.cfg.steps[4], true)");
   }

   else {
       RequestContext.getCurrentInstance().execute("wizardForm.next()");
   }

   if((wizardForm.getStep().equals("tabEnderecoContatoEmpresa") && !tipoProtocoloSelecionado.equals(TipoProtocoloConstante.REGISTRO_ONLINE_EMPRESA))
           || (wizardForm.getStep().equals("tabResponsaveisTecnicos"))) {
       renderizaBotaoProximo = false;
   }

   if(wizardForm.getStep().equals("tabDadosEmpresa")) {
       renderizaBotaoVoltar = true;
   }

   }

onBack
public void onBack() {
   if(wizardForm.getStep().equals("tabAnexoArquivos") && !tipoProtocoloSelecionado.equals(TipoProtocoloConstante.REGISTRO_ONLINE_EMPRESA)) {
       renderizaBotaoProximo = true;
       RequestContext.getCurrentInstance().execute("wizardForm.loadStep(wizardForm.cfg.steps[1], true)");
   }

   else if(wizardForm.getStep().equals("tabEnderecoContatoEmpresa") && !tipoProtocoloSelecionado.equals(TipoProtocoloConstante.REGISTRO_ONLINE_EMPRESA)) {
       renderizaBotaoProximo = true;
       renderizaBotaoVoltar = false;
       RequestContext.getCurrentInstance().execute("wizardForm.loadStep(wizardForm.cfg.steps[0], true)");
   }

   else {
       if(wizardForm.getStep().equals("tabEnderecoContatoEmpresa")) {
           renderizaBotaoVoltar = false;
       }

       RequestContext.getCurrentInstance().execute("wizardForm.back()");
   }
   }


Initialize a static final field in the constructor

Question: public class A
{
    private static final int x;

    public A()
    {
        x = 5;
    }
}

final means the variable can only be assigned once (in the constructor).
static means it's a class instance.

I can't see why this is prohibited. Where do those keywords interfere with each other?
Answer: A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this
class A {
    private static final int x;

    static {
        x = 5;
    }
}

But, if you remove static, you are allowed to do this:
class A {
    private final int x;

    public A() {
        x = 5;
    }
}

OR this:
class A {
    private final int x;

    {
        x = 5;
    }
}

Comment: Apparently nobody bothered to explain that static variables are variables that exist in all instances of a class. As such, they can only be instantiated once, when the class is loaded - not when potentially many instances of the class are constructed.
Comment: Also, I would recommend just assigning in the declaration rather than in a static block. It's just cleaner and probably is what the OP wanted to do: `private static final int x = 5;`
Comment: What if you want to pass the value "5" from another component/class, instead of having it hardcoded?
Answer: static final variables are initialized when the class is loaded. The constructor may be called much later, or not at all. Also, the constructor will be called multiple times (with each new object ), so the field could no longer be final.
If you need custom logic to initialize your static final field, put that in a static block
Comment: @YaronLevi he just said it... the static field is a member of the class itself. In your constructor you are assigning a value to the variable. The word final means you can only assign a value to the variable ONE time, in your code you are assigning a value to the variable every time the class is instantiated - because the variable is static (a member of the class). If you get rid of static, then you can assign it a value in the constructor since its a new variable each time. If you get rid of final then it is just a static variable, which you can assign a new value to at any time.
Comment: @user12345613 put up a pretty good explanation. Alone, either final or static work; but once put together, "static final" forces there is only one such field for that class across all instances and can only be initialized once regardless how many instances.
Comment: Ok, but you just explained what is happening. I am asking why ? I mean, without the final it works, without the static it works. so combining the both creates some new logic ?
Answer: Think about what happens the second time you instantiate an object. It tries to set it AGAIN, which is expressly prohibited by being a static final. It can only be set one time for the entire class, not instance.
You should set the value when you declare it
private static final x=5;

If you need additional logic, or more complex instantiation, this can be done in a static initializer block.
Answer: static means that the variable is unique on the application.
final means that it should be set only once.
If you set it in your constructor, you allow to set the variable more than once.
Hence you should intialize it directly or propose a static method to initialize it.
Answer: Think about it. You could do this with your code:
A a = new A();
A b = new A(); // Wrong... x is already initialised

The correct ways to initialise x are:
public class A
{
    private static final int x = 5;
}

or
public class A
{
    private static final int x;

    static
    {
        x = 5;
    }
}

Answer: Final doesn't mean that is has to be initialized in the constructor.
Generally this is what is done :
 private static final int x = 5;

static instead means that the variable will be shared through multiple instances of the class. For example :
public class Car {
   static String name;
   public Car(String name) {
      this.name = name;
   }
}

...

Car a = new Car("Volkswagen");
System.out.println(a.name); // Produces Volkswagen

Car b = new Car("Mercedes");
System.out.println(b.name); // Produces Mercedes
System.out.println(a.name); // Produces Mercedes

Answer: Static
The keyword static means that a member of an object, in this case a field, is not tied to an instance of a class, but is a member of the class in general instead. If the static member is a field, it is initialised during loading of a class.
It is accessible through the class rather than through an instance (though the latter is not impossible, it is considered bad form), so it is accessible without the constructor having ran at all — ever.
Final
The keyword final, when applied to a field of an object, means that it can be assigned to only once, and that it has to be assigned to during initialisation.
Static Final
Taken together, these two keywords effectively define a constant: it can be assigned to only once, has to be assigned to, and is the same for all instances of that class.
Since the static field is initialised during class loading, it has to be initialised then, either at declaration, or in a static initialiser block.
This means that if and when you reach the constructor, it will already have been initialised, because it needed to already have been initialised.
Singleton
If you're looking for a class member that you only assign to once, but read many times, you're dealing with a singleton. The singleton pattern is commonly used for access to a shared resource.
The field is made static but not final; instead when accessing the field, the code checks whether it has been initialised already, if not, it is done then and there. Note that in environments with multiple threads, you need to synchronise access to the field, to avoid accessing it while it is initialising.
Answer:     public class StaticFinalExample {
  /*
   * Static final fields should be initialized either in
   * static blocks or at the time of declaration only
   * Reason : They variables are like the utility fields which should be accessible
   * before object creation only once.
   */
  static final int x;

  /*
   * Final variables shuould be initialized either at the time of declaration or
   * in initialization block or constructor only as they are not accessible in static block
   */
  final int y;

  /*
   * Static variables can be initialized either at the time of declaration or
   * in initialization or constructor or static block. Since the default value is given to the
   * static variables by compiler, so it depends on when you need the value
   * depending on that you can initialize the variable appropriately
   * An example of this is shown below in the main method
   */
  static int z;

  static {
    x = 20; // Correct
  }
  {
    y = 40; // Correct
  }
  StaticFinalExample() {
    z = 50; // Correct
  }
  public static void main (String args[]) {
    System.out.println("Before Initialization in Constructor" + z);   // It will print 0
    System.out.println("After Initializtion in Constructor" + new StaticFinalExample().z); // It will print 50
  }
}


Mixing Distributions with Certain Probability?

Question: Suppose I have two distributions $X \sim N(a, \sigma ^2)$ and $Y \sim N(b,\sigma^2)$. From these distributions, I create a third distribution $Z$ so that there is a $\frac 12$ chance that $Z$ comes from $X$ and a $\frac 12$ chance that $Z$ comes from $Y$. Question: What is the distribution of $Z$ (i.e. expectation, variance).
It seems intuitive that $Z=\frac 12 X + \frac 12 Y$ Here's my reasoning, which I think is faulty (as I will explain later). The PDF for $Z$ is
$P(Z\le z)= P(Z \le z | Z \text{ chosen from } X) * P(Z \text{ chosen from } X) +P(Z \le z | Z \text{ chosen from } Y) * P(Z \text{ chosen from } Y)$
$=\frac 12 \text{PDF for } X + \frac 12 \text {PDF for } Y$.
So $Z\sim \frac 12 X + \frac 12 Y$.
Which is normal, and one can calculate the mean and the variance easily to find that $Z \sim N(\frac 12 a + \frac 12 b, \frac 12 \sigma ^2)$
But what- what happened here? Specifically, what if I let $a=b$. Then $Z \sim N(a,\frac 12 \sigma ^2)$, but $Z$ should clearly be just $N(a,\sigma ^2)$. Where did I go wrong, and what should be the correct answer?
Comment: Averaging densities is NOT the same as averaging random variables.
Answer: I think there are a couple issues here.  One you introduce the density functions for $X$ and $Y$ incorrectly when calculating the distribution function of $Z$.  You should have gotten
$$
P(Z \leq z) = \frac{1}{2} \Phi_{a, \sigma^2}(z) + \frac{1}{2} \Phi_{b, \sigma^2}(z)
$$
where $\Phi_{\mu, \sigma^2}(z)$ is the distribution function for a normal$(\mu, \sigma^2)$.  This does not mean that $Z$ is a sum of $X$ and $Y$.  Notice that even if somehow $Z$ were a linear combination of $X$ and $Y$ you would still need to know their joint distribution to determine the distribution of $Z$, something which you never specify.  This tells you that there's a gap in your reasoning.
$Z$ instead follows a mixture normal distribution which is most certainly not normal (in general it has more than one mode, for instance).  If you want to calculate the mean and variance, say, then you can try conditioning on the distribution from which we're drawing (that of $X$ or $Y$) and take an expectation as you do when finding $P(Z \leq z)$.
Edit based on comments
To calculate the expectation and variance of $Z$ let's call the mixing indicator $I$ and have $I = 1$ if we sample from the distribution of $X$ and $I = 0$ if we sample from the distribution of $Y$.  This means that $Z = IX + (1 - I)Y$.  To get both the mean and variance we condition on $I$ (we'll denote the mixing probability with $p$ just to make this more general):
\begin{align}
\text{E}(Z) &= \text{E}[\text{E}(Z \mid I)] \\
&= \text{E}[I a + (1 - I) b] \\
&= p a + (1 - p) b .
\end{align}
The variance however is a little bit more complicated due to the formula
\begin{align}
\text{Var}(Z) &= \text{Var}[ \text{E}(Z \mid I)] + \text{E}[ \text{Var}(Z \mid I)].
\end{align}
Note that we cannot simply average variances as we do with expectations.  One quick counterexample to prove this would be the Bernoulli distribution itself, viewed as a mixture of a point mass at one and a point mass at zero.  Each of these random variables is just a constant and so has zero variance, but their mixture has positive variance in general.  In any event, for the first term in the above formula we have
\begin{align}
\text{Var}[ \text{E}(Z \mid I)] &= \text{Var}(I a + (1 - I) b) \\
&= a^2 \text{Var}(I) + b^2 \text{Var}(1 - I) + 2 a b \text{Cov}(I, 1 - I) \\
&= a^2 p (1 - p) + b^2 p (1 - p) - 2abp (1 - p) \\
&= p(1 -p) (a - b)^2.
\end{align}
And for the second
\begin{align}
\text{E}[ \text{Var}(Z \mid I)] &= \text{E} [ \text{Var}(IX + (1 - I) Y \mid I) ] \\
&= \text{E} [ I^2 \sigma_x^2 + (1 - I)^2 \sigma_y^2 + 2 I(1 - I) \sigma_{xy} ] \\
&= \text{E} [ I \sigma_x^2 + (1 - I) \sigma_y^2] \\
&= p \sigma_x^2 + (1 - p) \sigma_y^2 .
\end{align}
Putting everything together we get
\begin{align}
\text{Var}(Z) &= p(1 - p) (a - b)^2 + p \sigma_x^2 + (1 - p) \sigma_y^2 .
\end{align}
Comment: I see. So expectation is easily calculated using $E[Z]=\frac 12 E[Z|X] + \frac 12 E[Z|Y]$. And for the variance, is it just simply that there is a $\frac 12$ chance the variance is $\sigma ^2$ (from $X$) and a $\frac 12$ chance the variance is $\sigma ^2$ (from $Y$), so the total variance is just $\sigma ^2$? And if, say, we chose $X$ w.p. $p$ and $Y$ w.p. $(1-p)$ then it would come out to be $Var(Z)=p(\sigma^2)+(1-p)\sigma^2 = \sigma ^2$ too?
Comment: I added to my answer with some of these calculations.


How to connect RabbitMQ Queue into Socket IO server and send messages from Socket IO server to client concurrently

Question: Im trying to get work Rabbit MQ queues through AioPika to send messages to Socket Io server and server would send those messages to client based on there SID, UID, etc. Documentation for using rabbitmq on socket is almost non existent. I am able to send messages to exchange with rabbit mq producer but socket io server don't receive anything. But even if i would receive some message from rabbitmq i don't  now how to send message to the client. Because if i put sio.emit(...) into def main() sio.emit is never reached because web.run_app(app) run constantly in loop.
Im using local rabbit mq. How to make the running app and sending messages so they can run independent. Thank you for every hint and help. Really appreciated.
Socket IO code:
from aiohttp import web
import socketio
import redis

mgr = socketio.AsyncAioPikaManager(channel="Socket io test")
sio = socketio.AsyncServer(client_manager=mgr)
app = web.Application()
sio.attach(app)

async def redis_sio_uid_write(sid):
    client = redis.Redis(db=0)
    client.set(sid, "uid")

async def redis_sio_uid_delete(sid):
    client = redis.Redis(db=0)
    client.srem(sid, "uid")

@sio.event
async def connect(sid, environ):
    """Connect and print "connection established" message."""
    await redis_sio_uid_write(sid)
    print('Connection Established', sid)

@sio.event
async def disconnect(sid):
    """Disconnect and print "disconnected from server" message."""
    print('disconnected from server', sid)

def main():
    web.run_app(app)

if __name__ == '__main__':
    main()
'''

Rabbit MQ Producer:
import sys
import asyncio
from aio_pika import connect, Message, DeliveryMode, ExchangeType

async def main(loop):
    # Perform connection
    connection = await connect(loop=loop)

    # Creating a channel
    channel = await connection.channel()

    socketio_exchange = await channel.declare_exchange(
        "Socket io test", ExchangeType.FANOUT
    )

    message_body = b"Hello World!"

    message = Message(
        message_body,
        delivery_mode=DeliveryMode.PERSISTENT
    )

    # Sending the message
    await socketio_exchange.publish(message, routing_key="")

    print(" [x] Sent %r" % message)

    await connection.close()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))

ok so i solve the concurrent part with threading but still dont know ho to connect the rabbit mq onto socket io server.
socketio server:
from aiohttp import web
import socketio
import redis
import time
import random
import asyncio
from threading import Thread, Event, Lock

mgr = socketio.AsyncAioPikaManager(channel="Socket io test")
sio = socketio.AsyncServer(client_manager=mgr)
app = web.Application()
sio.attach(app)
loop = asyncio.new_event_loop()

def side_thread(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

thread = Thread(target=side_thread, args=(loop,), daemon=True)
thread.start()

async def redis_sio_uid_write(sid):
    client = redis.Redis(db=0)
    client.sadd(sid, "".join([str(random.randint(1, 10)) for _ in range(10)]))

async def redis_sio_uid_delete(sid):
    client = redis.Redis(db=0)
    client.spop(sid)

@sio.event
async def connect(sid, environ):
    """Connect and print "connection established" message."""
    await redis_sio_uid_write(sid)
    print('Connection Established', sid)

@sio.event
async def disconnect(sid):
    """Disconnect and print "disconnected from server" message."""
    await redis_sio_uid_delete(sid)
    print('disconnected from server', sid)

async def _data():
    while 1:
        await sio.emit(event="message_rabbit_mq", data=time.time())
        await asyncio.sleep(5)

def main():
    future = asyncio.run_coroutine_threadsafe(_data(), loop)
    future.add_done_callback(web.run_app(app))

if __name__ == '__main__':
    main()

Answer: The documentation for your use case is here: Emitting from external processes.
From the documentation, the example for a Redis queue is as follows:
# connect to the redis queue as an external process
external_sio = socketio.RedisManager('redis://', write_only=True)

# emit an event
external_sio.emit('my event', data={'foo': 'bar'}, room='my room')

You would need to replace RedisManager with the aiopika manager, but other than that everything works the same. In case it isn't clear, you do not need to manage anything on the RabbitMQ side, you should use the client manager class both on the server and the external process scripts.


Name for map associated with simplicial complex

Question: Given a simplicial complex $\Delta$, implied by the construction process there are associated maps sending euclidean standard simplices into the simplicial complex $\imath: \Delta^n \to \Delta$. What is the name of those maps? Associated maps, canonical maps, characteristic maps,...?
Answer: In Hatcher's Algebraic Topology, these are called characteristic maps, and the restriction $\varphi\colon \partial\Delta^n\to \Delta$ to the boundary is referred to as the attaching map.  In my experience, this usage is fairly standard.


Bayesian: Sampling from Truncated Distributions

Question: When would the rejection sampling method be preferred to the inverse CDF method for sampling truncated random variables?
And when would the inverse CDF method be preferred to the rejection sampling method for sampling truncated random variables?
Answer: The latter half of this answer gives a justification for why the inverse CDF method would be undesirable to use: the CDF is expensive or impossible to evaluate. The downside to the rejection sampling method is that you can potentially draw a lot of unwanted samples if the area you are truncating to is sufficiently small relative to the whole support. See here.
Thus, to answer your questions..

When would the rejection sampling method be preferred to the inverse CDF method for sampling truncated random variables?

When the CDF is either (A) impossible or (B) more expensive to evaluate than just doing rejeciton sampling

And when would the inverse CDF method be preferred to the rejection sampling method for sampling truncated random variables?

When rejection sampling would require you to waste too much computational effort in generating unwanted samples.
How do you know precisely when one is more efficient? That will depend on the specifics of the distributions, algorithms used to sample them, the specifics of your hardware and programming setup, etc.
There are other sampling methods which get around some of these problems. See the same wikipedia article.


Print array element syntax

Question: I am using devel and <?php dpm($items); ?> in my field template file so the node looks like the following.

I can print the #theme element (which is a string) with the following code.
<?php print $items[0]['#theme']; ?>

What is the syntax to print elements in an array such as URLs, labels, titles?
Answer: You'll have to follow the trail in the DPM structure. The url field is under the #element element. The #element element is under the 0 element. This means you can access the value of url with:
$items[0]['#element']['url'];

You can reach the title element in a similar way.
The value of #theme is directly under the 0 element, that is why you could access it with:
$items[0]['#theme']

Comment: @ Jesse thanks but I don't want to use dpm I want to use print ie corresponding to my #theme example. By url I meant the url element of the #element array ie the one highlighted in red in the screenshot ie what is the syntax to print this string?
Comment: Your question is not clear. The elements URL and label are in your $items array, what do you mean with printing them in an array?
Comment: Ok let me try again - I can print the #theme string with  '' Now I want to do the same thing for the url string (the one highlighted in red) ie to print just the url string on its own. I think the answer I am looking for will be something like ''
Comment: Ah, it should be `` I'll update my answer to explain
Answer: where did you output the dpm? double click on any of the attributes then it shows you the trail array which displays that content. like this

then use this array key at the beginning of the variable passed in your hook preprocess function. for example:
function hook_preprocess_node(&$variables){
    $variables['value'] = $variables['revision_timestamp']
}

Print array element syntax


Probability of event occurring multiple times

Question: I'm trying to calculate the probability of exactly $8$ identical independent events occurring if each has a $25\%$ chance of occurring.
To simplify, if I were rolling a four-sided die $8$ times, what would be the probability be of rolling a $1$ only once through the probability of rolling a $1$ on the die $8$ times? I'd like to create a data table with $x$ being $1$ through $8$ and $f(x)$ being the probability. It seems like a normal distribution.
Comment: This is a job for the Binomial Distribution https://en.wikipedia.org/wiki/Binomial_distribution . Your intuition is in the right place: In a sense that can be made precise, this distribution is approximately normal.
Comment: If you are familiar with the language R, then you can look up some functions related to the binomial distribution like `dbinom`. Also, formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: It follows a binomial distribution.
If $X$ is distributed according to the binomial distribution with number of trials $n$ ($8$, in your case) and probability $p$ ($0.25$ for you), then $X\sim\mathcal {Bin}(n,p)$ means:
$$\mathsf P(X=r) \,=\, \binom{n}{r}\,p^r\,(1-p)^{n-r} \qquad \text{where }r\in\{0,..,n\}, 0\text{ otherwise}$$
Where $\dbinom{n}{r} = \dfrac{n}{r!\,(n-r)!}$, which is also often represented as: ${^n{\rm C}_r}$
Comment: Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).


How can i check for null property in object inline with ES 6 syntax?

Question: I have one object with five properties and i need to take just three of them.For one of the properties i need to check if it is null value then it should be 'Unknown'.
The code will look like this
let obj = {
    name:"john",
    lastName:"doe",
    age:24,
    city:null

}

function getSomeProperties(obj) {
    let newObj = {
        name: obj.name,
        age:obj.age,
        city:obj.city == null ? 'unknown' : obj.city
    }
    console.log(newObj);
}

getSomeProperties(obj);

if i try to take only three properties inline then this works

function getSomeProperties(obj) {
    const newObj = (({name, age, city}) => ({name, age, city }))(obj);
    console.log(newObj);
}

but the problem is when i try inline to check if city is null like in the first case then i get error.
function getSomeProperties(obj) {
    const newObj = (({name, age, city}) => ({name, age, city == null ? 'unknown' : city }))(obj);
    console.log(newObj);
}

Can be this thing maked inline?
Comment: newObj = (({name, age, city}) => ({name, age, city : city == null ? 'unknown' : city }))(obj);
Answer: You need to check it like this:
({name, age, city: city == null ? 'unknown' : city })

Or you use nullish coalescing operator:
({name, age, city: city ?? 'unknown' })

The same you can do above:
city: obj.city ?? 'unknown'

It checks if the left side is either null or undefined. If its the case it returns the value thats on the right side.
Remember 0 or false is not considered as nullish value.
In JavaScript, a nullish value is the value which is either null or undefined. Nullish values are always falsy.


How to check if my theory has already been made

Question: I'm in high school so I don't know a whole lot about mathematic theories but I've started working on my own and have got a good proof written up but I'm not sure if this theory is already something that exists or not. Are there any websites I could check or any other ways I could check? My math teacher didn't know of anything like it (he teaches algebra and calculus).
Ok since this question has gotten really clustered I'm going to post a second question with my theorem to simply as if it has already been stated and proven.
Here is a link
Is this division theorem already a proven idea?
Comment: You could share the result here (without proof, if you like) and people will certainly give their opinions on the originality of it.  Cheers!
Comment: what are the implication of your theory ? don't write the proof, but at least give the implication or what the improvement to math your theory will bring.
Comment: Even in research mathematics it can be quite difficult to verify if somebody has done something before, often because of notational or terminological differences. And people on the internet may not be very receptive either. You might consider trying to find a local scientist or mathematician who can mentor you and take a look at your work.
Comment: If you have proved something, it is a theorem.  Sharing that theorem here would greatly improve this conversation.
Comment: I'm not sure how exactly it will improve mathematics per se but it has to do with finding the factors that two numbers contain by dividing the two
Comment: Alright, I'll try heading over to a local college and see if there's a math teacher I can talk to, maybe they'll know
Comment: Would a result be an example of what my theory shows?
Comment: Relevant questions: https://math.stackexchange.com/questions/1643785 , https://math.stackexchange.com/questions/2169686 , https://math.stackexchange.com/questions/275194 , https://math.stackexchange.com/questions/898042
Answer: Here is an algorithm that might work:

Define a computable integer sequence based on your theory/theorem.
Compute several terms of that sequence.
Look up these terms in OEIS
Repeat steps 1-3 several times. If most/all of the sequences are new, then it is likely that you have indeed found some new theory/theorem. If the sequences are already recorded in OEIS, read the relevant comments and references to figure out what exactly you have rediscovered.
Comment: Ok, I'll give that a shot. Thanks :)
Comment: This is a good way to look for a reference that can be described by an integer sequence, but it should be taken with a caveat: coming across your finding in the literature means it's already known, but *not* coming across your finding only means you haven't found it yet. Failing to come across your finding leaves you no more certain that it is truly original, only slightly more confident.
Answer: You could publish on Arxiv, then share to ask for feedback.
I would have suggested making a blog post such that the date of the post is verifiable, but Blogger does not work as the post can be edited without showing the edit date, meaning that people could claim you made the post before they published and edited in their results after.
Comment: Are there any real-life examples of high-school students publishing on arxiv??
Comment: https://arxiv.org/help/registerhelp does not indicate that high-school students are not allowed. Also, I found an example: https://www.universetoday.com/44259/high-school-students-get-published-in-astrophysics-journal/ . In the comments, there is a link to the arxiv paper.
Comment: In your example, three of the co-authors are actually established scientists; that changes a lot! A new author on arxiv, without co-authors, would need an endorsement - and it is not easy to get endorsed.
Comment: If I post my theorem on here is the date unchangeable even if edited and such?
Comment: I'm not going to get my hopes up that this is something revolutionary and important, I know that's likely not the case and it's probably something that is already known but just in case you know?
Comment: I just publish my math on Blogger. I don't worry about credit. If someone insists that they came up with it first, like Newton did against Leibniz, I wouldn't be able to prove them wrong even if they are wrong. I invented some number theory involving nonpowers and the Riemann Zeta function, and 1+ years later, my advisor found some guy on the internet who had done 80%+ of it before me. I even Google searched and didn't find it until after my advisor showed me it.
You seem to want credit, which is why I suggested Arxiv. There are other options, but I don't know them.


Can my app load only the games installed on users device?

Question: I wan that my app should show a list of games installed on user device. Is it possible to that?
One way I think is that I will tell the user to create a folder on desktop suppose named "gamesforXYZapp". Now is it possible that my app will search for this folder and show the games put in that folder in my app?
Is there any other way?
Comment: If you have a list of the common game package names, you can easily get a list of all the installed apps then add only the apps that match your package names to your list.
Comment: If you mean a folder in the launcher, it would depend on if the launcher exports folder contents somehow to other interested apps.  I can't really see why a launcher would, but then don't immediately see major security reasons why it would be improper for one to do so.
Answer: In Android, you cannot set your app as <code>"Game Type"</code>  so you cannot filter applications by this category.
I think, a solution to this would be to find all games packages from Google Play and put that list in your app and frequently update it. It needs uninterrupted internet connection so that you could send found apps list to server and server will return back games from that list. So, you need to write server code for that.
Answer: If you have a list of 'All Games' on the Platform (like A--C does), you could use the PackageManager to determine which apps are installed on the users device, and then match that list to the 'All Games' list.
This might look something like this:
<code>        List<String> allGames = //list of all games on device - not sure where you get this
        PackageManager packageManager = getPackageManager();
        List<ApplicationInfo> appsList;
        appsList = new ArrayList<ApplicationInfo>();
        appsList = packageManager.getInstalledApplications(0);

        Iterator<ApplicationInfo> it = appsList.iterator();

        while (it.hasNext()) {
                if (appName != null) {
                        ApplicationInfo value = (ApplicationInfo) it.next();
                        if (value != null) {
                                String appName2 = value.packageName;
                                if (appName2 != null) {
                                        // Check if this app is in the 'All Games' list
                                        if (allGames.contains(appName2) {
                                                // This is a game
                                        }

                                }
                        }
        }
</code>


Will there be a performance gain by using Apache's mod_proxy to proxy off static file requests to Lighttpd/nginx?

Question: I know there are lot of tutorials out there which suggest the use either nginx or lighttpd on port 80 and proxy dynamic requests to apache running on a different port. I am not ready to take that leap yet for my VPS. However I could definitely try the reverse scenario.
i.e. use apache's mod_proxy to proxy requests to nginx/lighttpd running on a different port.
But does that even make sense? will there be a performance gain if I use the reverse setup?
Answer: No.  The performance on that is pretty much guaranteed to be significantly worse than just serving the static content out of Apache.
Furthermore, I don't think the performance gains to be had (if any) from serving static content from nginx outweigh the downsides of proxying dynamic requests back to Apache -- that is to say, the "conventional wisdom" embodied in the "lot of tutorials" is just plain wrong, stupid, and generally unnecessary (who would have thought it -- bad information on the Internet?).  I'd be willing to wear the idea of using nginx to serve static assets from a separate assets domain, on a separate IP (even if it's on the same box), but I don't think proxying webserver to webserver makes sense.
Comment: Substitute "subjective" for "busted".  Preference given to demonstrations where something gets blown up.
Comment: Eek, I might have had the right initial impulse, to call this one subjective.  For what it's worth, I completely agree that using a "lighter" web server as a reverse proxy at all times as standard practice should be burned from our collective "conventional wisdom", and that there's very rarely an excuse for it from a performance perspective.  I just felt the need to give my answer a qualifier in the form of "but, in this insane edge-case, it could make sense."
Comment: I can get behind that.
Comment: I agree, putting nginx on the front proxying back to Apache makes no sense. I will however point out that nginx performs quite better on the same hardware and it scales higher COMPARED to Apache :-)
Comment: Well, someone put a down-vote on both answers, so I guess we've got some proponents of the single-node reverse proxy architecture around here somewhere.  @pauska There's that subjectivity again ;).
Comment: No, that is not subjectivity at all. Do your homework :-) nginx (stripped down to the bare necessary modules) scales higher on the same hardware.
Answer: This is a very uncommon setup, I've never heard about anyone using nginx/lighttpd as a backend. It doesn't make sense, as you want the front-end to be the absolutely fastest point for serving static files (nginx, lighttpd) or caching both static and dynamic (varnish etc).
If you're really bound to use Apache as a front-end then just keep it.
Comment: Its not that uncommon, if you search for it on google, various blog posts claiming its performance benifits, but didn't make sense to me, thats why the query
Comment: Yes, you'll get results from google, same as you would if you search for "how to eat poop".. I think you get my point :)


Are matrices with determinant zero a manifold?

Question: Consider the set of matrices with determinant zero in $M_n(\mathbb R)$, where $n > 1$. Is it a manifold? In fact, is it even a topological manifold?
I would suspect not; but I do not have a proof.
If it is indeed not a manifold, is it perhaps a union of finitely many manifolds? Is there a way to determine them? Does the problem become easier if $\mathbb R$ is replaced by $\mathbb C$?
Comment: [Any scaling-invariant smooth submanifold $M\subset \mathbb R^m$ that contains $0$ is a linear subspace](http://math.stackexchange.com/a/180861/53153). So much for differentiable structure.
Comment: The set of matrices with a fixed rank $k$ in $M_{m\times n}(\mathbb{R})$ is an embedded sub-manifold of $M_{m\times n}(\mathbb{R})$ with co-dimension $(m-k)(n-k)$. (For a proof, see example 8.14 of John M.Lee's *Introduction to Smooth Manifolds*). So the zero set of determinant of $M_{n}(\mathbb{R})$ is a disjoint union of $n$ embedded sub-manifold, one for each $0 \le k < n$.
Comment: @Potato I can't imagine that the question was about producing differentiable structures on a non-smooth subset of a Euclidean space.
Comment: see: http://math.stackexchange.com/questions/144488/is-the-set-of-singular-matrices-ever-a-differentiable-manifold
Comment: @AsafShachar In first edition (2002), it is located at Chapter 8 submanifolds, near the end of section about Level Sets with title "Matrices of Fixed Rank". In second edition, that chapter/section has been moved to Chapter 5. It might be in page 106-107 ( I can't see those two pages in a google book search).
Comment: Do you want a differentiable structure, or is a topological manifold good enough?
Comment: Differentiable structure. It it is difficult to obtain, a topological manifold would be good enough, too. My feeling is that it is not even a topological manifold; but I don't have a proof.
Comment: @5pm That just shows we can't embed it in the obvious way to Euclidean space. I fail to see how this rules out other clever differentiable structures. What am I missing?
Comment: My first reaction is to try to produce a matrix of determinant zero with $d\det$ not onto. At such a point, the inverse function theorem fails, so it's a candidate singularity.
Comment: @5pm Good point.
Comment: @achillehui Are you sure about the location of the reference? (I have looked  at the second edition and didn't find it there)
Comment: @achillehui $S=\{(x,y)\in\mathbb{R}^2:\ y^2-x^3=0\}$ is a disjoint union of the submanifold $\{(0,0)\}$ of co-dimension $2$, and the submanifold $S\setminus\{(0,0)\}$ of codimension $1$, and is itself a topological submanifold.
Answer: Let $S$ be the set of matrices with determinant $0$. Let $M_{ij}$ be the matrix whose $(i,j)^{\rm th}$ entry is $1$ and all of whose other entries are $0$. Then $\gamma_{ij}(t)=tM_{ij}$ is a curve in $S$ for all $(i,j)$.
Suppose for the sake of contradiction that $S$ is a manifold. Then $T_0S$ (exists and) contains $\gamma_{ij}'(0)=M_{ij}$ for all $(i,j)$. But the $M_{ij}$ span $T_0M_n(\Bbb{R})$. It follows that $T_0M_n(\Bbb{R})=T_0S$. So $S$ has dimension $n^2$, and thus is open in $M_n(\Bbb{R})$. But this is absurd (e.g., the matrices $\varepsilon \cdot\mathrm{id}$ do not lie in $S$, and come arbitrarily close to $0$). So $S$ is not a manifold.
(Note that this proof is morally very similar to that given in @5PM's link in the comments.)
Answer: Okay, here's what I have so far: Pick $n-1$ linearly independent vectors in $\mathbb{R}^n$: $v_1,v_2,\ldots,v_{n-1}$. Then consider a small $U$ neighborhood of:
$$M_0 = \left(\begin{array}{ccccc}  & & & & \\ v_1 & v_2 & \cdots & v_{n-1} & 0 \\ & & & & \end{array}\right)$$
And consider $U \cap X$, where $X$ is our set of matrices that have determinant zero. If $U$ is small enough, for every matrix in $U \cap X$ the first $n-1$ vectors will be linearly independent. That means for $M \in U \cap X$ there exist unique real numbers $a_1(M),a_2(M),\ldots,a_{k-1}(M)$ such that the nth column of $M \in U \cap X$ (let's write it as $v_n(M)$) can be written:
$$v_n(M) = a_1(M)v_1(M) + a_2(M)v_2(M) + \cdots + a_{n-1}(M)v_{n-1}(M)$$
And furthermore it is clear that the $a_i(M)$ depend continuously on $M$ (In fact, the $a_i$ should just be rational functions of the elements of $M$, so they should be smooth as well). Adding in variations of the first $n-1$ vectors, each of which looks like an open subset of $\mathbb{R}^n$, we get that $U \cap X$ is homeomorphic to an open subset of $\mathbb{R}^{n^2 - 1}$
Now, by looking at a neighborhood of another point (the origin?) we should be able to determine that $X$ is not a manifold... though I cannot figure out a proof.


Is a ♭ 3 a minor 3rd, a ♭♭3 a diminished 3rd, and ♭5 a diminished 5th?

Question: I just need some clarification. Am I getting chords notated this way - 1-5-♭7-9-11, 1-3-5-♭7-♯11, 1-3-5-♭7-9-13, 1-4-5-♭7-9-13 - right?

    3   == M3
    5   == P5
    ♭7  == m7
    ♭♭7 == d7 (?)
    ♭5  == d5 (?)
    ♯5  == A5
    ♯9  == A9
Answer: Every one of your intervals looks right, but I'll explain a little more. When people use numbers to represent notes like above, they always do it in reference to the major scale. So the interval they correlate to is:

1 - P1
2 - M2
3 - M3
4 - P4
5 - P5
6 - M6
7 - M7
8 - P8
9 - M9
10 - M10
11 - P11
12 - P12
13 - M13
14 - M14
15 - P15
...

The sharps and flats obviously alter the intervals in there respected ways with sharps raising the interval and flats lowering them.
For perfect intervals, the intervals go as followed when raised or lowered:

♭♭ - ♭ - natural -  ♯  - ♯♯
dd - d -    P    -  A  - AA

For major intervals, the intervals go as followed when raised or lowered:

♭♭♭ - ♭♭ - ♭ - natural -  ♯  - ♯♯
dd - d  - m -   M    -   A  - AA
Comment: Note, you can doubly diminish a major interval also, in case that's not clear to future readers.


GCC generates wrong structure offset why?

Question: I have this code:
mbr.h:
struct mbr_partition {
                char flags;
                char start_head;
                char start_sector;
                char start_cyl;
                char type;
                char last_head;
                char last_sector;
                char last_cyl;
                uint32_t start;
                uint32_t size;
        };

        struct mbr {
                char bootloader[446];
                struct mbr_partition partition1;
                struct mbr_partition partition2;
                struct mbr_partition partition3;
                struct mbr_partition partition4;
                char magic[2];
        };

And: main.c:
int main()
{
        printf("%d\n", sizeof(struct mbr));
        printf("%d\n", sizeof(struct mbr_partition));
        printf("%d\n", sizeof(long));
        struct mbr mbr;
        printf("%d, %d\n", ((char *) &mbr.magic) - ((char *) &mbr), sizeof(mbr)$
        printf("1: %d\n", ((char *) &mbr.partition1) - ((char *) &mbr));
        printf("2: %d\n", ((char *) &mbr.partition2) - ((char *) &mbr));
        printf("3: %d\n", ((char *) &mbr.partition3) - ((char *) &mbr));
        printf("4: %d\n", ((char *) &mbr.partition4) - ((char *) &mbr));
        return 0;
}

And output:
516
16
8
512, 516
1: 448
2: 464
3: 480
4: 496

Why size is 516 bytes (It should be 512) ?
Why partition1 offset is 448 not 446?
How can I fix it?
Comment: I think you might have to add attribute called **packed** to the struct to remove extra padding.
Comment: Padding.  See http://stackoverflow.com/a/18654110/12711
Comment: Does `-Wpadded` help?
Answer: Because there might be some padding bytes or padding bits.
Quoted from N1570 220.127.116.11 Structure and union specifiers:(emphasis mine)

15 Within a structure object, the non-bit-field members and the units
  in which bit-fields reside have addresses that increase in the order
  in which they are declared. A pointer to a structure object, suitably
  converted, points to its initial member (or if that member is a
  bit-field, then to the unit in which it resides), and vice versa.
  There may be unnamed padding within a structure object, but not at its beginning.


SageMaker and TensorFlow 2.0

Question: What is the best way to run TensorFlow 2.0 with AWS Sagemeker?
As of today (Aug 7th, 2019) AWS does not provide TensorFlow 2.0 SageMaker containers, so my understanding is that I need to build my own.
What is the best Base image to use? Example Dockerfile?
Comment: https://github.com/aws/sagemaker-tensorflow-container/blob/master/docker/1.12.0/final/py2/Dockerfile.cpu

Above is the Dockerfile used by Sagemaker to build Tensorflow images. You can refer this and update the base image as per your use case
Answer: EDIT: Amazon SageMaker does now support TF 2.0 and higher.

SageMaker + TensorFlow docs: https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html
Supported Tensorflow versions (and Docker URIs): https://aws.amazon.com/releasenotes/available-deep-learning-containers-images

Original answer
Here is an example Dockerfile that uses the underlying SageMaker Containers library (this is what is used in the official pre-built Docker images):
FROM tensorflow/tensorflow:2.0.0b1

RUN pip install sagemaker-containers

# Copies the training code inside the container
COPY train.py /opt/ml/code/train.py

# Defines train.py as script entrypoint
ENV SAGEMAKER_PROGRAM train.py

For more information on this approach, see https://docs.aws.amazon.com/sagemaker/latest/dg/build-container-to-train-script-get-started.html
Comment: Hi, in this approach is it easy to scale training horizontally, i.e. is it enough to set `train_instance_count ` to something large than 1?
Comment: your `train.py` will need to be able to handle distributed training in that case, including setting up parameter servers, etc. if appropriate.
Comment: I get the below warning while building the docker image.  'Step 3/10 : RUN pip install sagemaker-containers
 ---> Running in b75277212fd9
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting sagemaker-containers'
Comment: @Biranchi you no longer need to build your own image for TF 2.x support. (I've also edited my answer to hopefully make this clearer.)
Answer: Update on 10 nov 2019:
There is now a way to use Tensorflow 2 in SageMaker, event though there is no shortcut to start TF 2 directly from SageMaker console.

Start a conda Python3 Kernel
Make some updates (one in each code cell):

!pip install --upgrade pip         # pip 19.0 or higher is required for TF 2
!pip install --upgrade setuptools  # Otherwise you'll get annoying warnings about bad installs

Install Tensorflow 2

!pip install --user --upgrade tensorflow

Given the doc, this will install in $HOME.

Nota:
If you are using a GPU based instance of SageMaker, replace tensorflow by tensorflow-gpu.

You now can use TF 2 in your instance. This only needs to be done once, as long as the instance remains up.
To test, just run in the next cell:
import tensorflow as tf
print(tf.__version__)

You should see 2.0.0 or higher.
Comment: This lets you use TensorFlow 2.0 in Jupyter (in a SageMaker Notebook Instance), but does not allow for training/hosting via a Docker container run by SageMaker.
Answer: As of now, the best image that you can use to build Tensorflow 2.0 is 2.0.0b1, which is the latest version of Tensorflow 2.0(image) that is available now.Please find the link here. You also have an image 2.0.0b1-py3, which comes with Python3 (3.5 for Ubuntu 16-based images; 3.6 for Ubuntu 18-based images).
If you feel this answer is useful, kindly accept this answer and/or up vote it. Thanks.
Answer: Here from the SageMaker team. To use SageMaker seamlessly, it's recommended that you try out Amazon SageMaker Studio. It's similar to a Jupyter Notebook instance but has a variety of SageMaker services already integrated within it. A huge plus point is that you can select from a variety of kernels and for TensorFlow 2.0 you can select any of these that already have all the required packages installed:
Python 3 (TensorFlow 2.1 Python 3.6 CPU Optimized)
Python 3 (TensorFlow 2.1 Python 3.6 GPU Optimized)
Python 3 (TensorFlow 2.3 Python 3.7 CPU Optimized)
Python 3 (TensorFlow 2.3 Python 3.7 GPU Optimized)

In Studio, you can select the Kernel drop-down located in top-right corner of your SageMaker Studio instance:

Shown below is a screenshot of the UI interface in SageMaker Studio of the available kernels that are compatible with TensorFlow 2.0. Note that all kernels within SageMaker Studio are continuously tested and work seamlessly with all SageMaker Services.

SageMaker and TensorFlow 2.0


Prove that there exist divisors for a and b with certain conditions

Question:
Show that if $a$ and $b$ belong to $\mathbb{Z}_+$ then there are divisors $c$ of $a$ and $d$ of $b$ with $(c,d)=1$ and $cd=\text{lcm}(a,b)$.

My try:
We know that $$\text{gcd}(a,b)\cdot \text{lcm}(a,b)=ab$$
then, $$\text{lcm}(a,b)=\dfrac{ab}{\text{gcd}(a,b)}$$
Let $d=b$ and $c=\frac{a}{\text{gcd}(a,b)}.$
Now $d|b$ and $c|a$
with $\text{lcm}(a,b)=cd$.
Now I am not sure about the following step: $$\text{gcd}(c,d)=\text{gcd}\left(\dfrac{a}{\text{gcd}(a,b)},b\right)
=\text{gcd}\left(\dfrac{\text{lcm}(a,b)}{b},b\right)=1$$
Tell me is this correct?
Comment: Dear @Cookiemaster, welcome to MSE. I have used TeX and edited your post so that it improves readability. From my experience, if you do this then you will get a better response from this website. So please use TeX to type your equations in further posts.
Comment: Can i use TeX on mobile?
Comment: @Cookiemaster Yes. It's tedious, but it's possible. Just type the commands like you normally would here.
Comment: Follows from the gcd dual [here](https://math.stackexchange.com/q/3083157/242), which includes an efficient algorithm using gcds.
Answer: It is not correct.
If $ a = 4, b = 2$, then you have $ d = b = 2, c = a/ \gcd(a,b) = 4/2 = 2$.
This doesn't satisfy $ \gcd(c,d) = 1$.
Now, figure out where your reasoning breaks down, and how to fix it.
Comment: Check my answer i tried my best
Answer: Using prime factorization formula for a and b we have:
a= $p_1$$^{a1}$ $p_2$$^{a2}$ ... $p_n$$^{an}$
b=$p_1$$^{b1}$ $p_2$$^{b2}$ ... $p_n$$^{bn}$
We know that gcd($p_i$$^s$,$p_k$$^t$)=1 for any i,k $\in$ [1,n] with    i $\ne$ k
and s,t $\in$ {a1,a2,...,an,b1,b2,...,bn}
Now we know that lcm(a,b)= $p_1$$^{max(a1,b1)}$ $p_2$$^{max(a2,b2)}$ ... $p_n$$^{max(an,bn)}$
Let c be the multiplication of factors of lcm(a,b) that are factors of a and let d be the multiplication of factors of lcm(a,b) that are factors of b this implies that c divides a and d divides b
Hence cd = lcm(a,b) and since factors of c and factors of d are  both of the form $p_i$$^{s}$
Thus gcd(c,d)=1
Comment: For the symbols \in, include them between dollar signs `$` like `$\in$` to get $\in$.
Comment: Thank you very much and now finally commands work :)
Comment: Replace pi with p_i
Comment: You have the right ideas of dividing up the prime powers, but I don't think it is complete. E.g. what happens with prime factors that appear in both, like in my example? The writeup could be much simplified, think about what happens if $ a_1 > b_1 , a_1 \leq b_1 $.
Answer: List the prime factors of $a$ and/or $b$ as $p_1, p_2, .....,p_n$.
Let $a= \prod_{i=1}^n p_i^{k_i}$ for some non-negative integer values of $k_i$ (which may be equal to $0$). And let $b=\prod_{i=1}^n p_i^{j_i}$ for some non-negative integer values of $j_i$.
Then $\text{lcm}(a,b)= \prod_{i=1}^n p_i^{\max(k_i, j_i)}$.  We can note that although $k_i$ may be $0$ and $j_i$ may be $0$, they can't be both be. And we can not that if $\max(k_i, j_i)=k_i$ then $p_i^{k_i}|a$.  And if $\max(k_i, j_i)=j_i$ then $p_i^{j_i}|b$.
Now if we let $c = \prod_{i=1;k_i\ge j_i} p_i^{k_i} = \prod_{i=1;k_i\ge j_i} p_i^{\max(k_i,j_i)}$ and $d=\prod_{i=1;k_i< j_i} p_i^{j_i} = \prod_{i=1;k_i< j_i} p_i^{\max(k_i,j_i)}$ then:
$c|a$ and $d|b$.
$\gcd(c,d) =\prod_{i=1; k_i\ge j_i\text{ and }k_i < j_i} p_i^{\min(k_i, j_i} = \prod_{i=1; i\in \emptyset}^n p_i^{\min(k_i, j_i} = 1$.
$cd = \prod_{i=1;k_i\ge j_i} p_i^{\max(k_i,j_i)}\prod_{i=1;k_i< j_i} p_i^{\max(k_i,j_i)}=\prod_{i=1}^n p_i^{\max(k_i, j_i)}=\text{lcm}(a,b)$.
....
If that seems too abstract consider $a= 3^{17}5^47^{3}$ and $b=2^{6}3^{8}5^{9}$.
Then $a = 2^03^{17}5^47^3$ and $b=2^{6}3^85^87^0$.
And $\text{lcm}(a,b) = 2^{6}3^{17}5^97^3$.
$k_1=0< j_1=6$ so $2^6$ is a factor of $d$.  $k_2=17>j_2=8$ so $3^{17}$ is a factor of $d$. And $k_3=4< j_3=9$ so $5^9$ is a factor of $d$. and $k_4=3>j_4 = 0$ so $7^3$ is a factor of $c$
So $c = 3^{17}7^3$ and $c|a$.  And $d=2^65^9$ and $d|b$.
ANd $\gcd(c,d)= 1$ and $cd = 2^63^{17}5^97^3 = \text{lcm}(a,b)$.


Acessar o site via HTTPS - AWS

Question: Estou com dúvidas para acessar o site usando o protocolo HTTPS para os domínios em minha hospedagem.
Subi uma instância Linux T2.micro zona São Paulo (Amazon ECS). Já fiz o procedimento para adquirir o certificado (ACM) e o status dele é 'Emitido'.
Também configurei o CloudFront e o status dele é 'Implantado' e habilitei o SSL do Apache2 (sudo a2ensite default-ssl). Porém, ao acessar o site utilizando o HTTPS, diz que o site não é seguro, fica com o HTTPS riscado em vermelho.
Nessa mesma instância possuo outros sites (domínios diferentes) e gostaria de habilitar o HTTPS para eles também.
O que está faltando ou o que estou fazendo de errado?
A maioria dos tutorias que encontrei são superficiais e não tem detalhes do passo-a-passo...
Abraços a todos!
Answer: Recomendaria que você utilizasse o Letsencrypt ou CertBot para gerar certificados HTTPS. Para que você coloque em funcionamento o certificado, você deve usar dependendo do seu site, Apache ou Nginx para poder configurar adequadamente os certificados. Lembrando, que todas as configurações, visto que você está utilizando uma instância micro, devem ser realizada no terminal com comando sudo preferencialmente.
Comment: Olá Matheus, aprecio sua resposta! Gostaria de entender o motivo ou o que estou fazendo de errado, pois o certificado da AWS o site já possui, porém continua aparecendo como "não seguro".
Comment: mas esse seu certificado é direito da aws? Você não implantou no server? Pode dar mais detalhes?
Comment: É direto da AWS. Nao implementei no server.
Meus passos foram: Criar e habilitar/verificar um certificado no AWS Certificate Manager, habilitar o acesso SSL no servidor pelo comando 'a2ensite default-ssl', criar uma 'distribuição' no CloudFront e por último habilitar o LoadBalancer na instancia do meu servidor.
Feito esses passos, atualmente o site entra com o HTTPS, porém o símbolo fica vermelho (do HTTPS no browser).
Answer: Depois de várias tentativas e reconfigurações, o professor Francisco Edilton (Cloud Architect) descobriu o erro! Faltou fazer o apontamento do domínio para o Load Balancer. Substitui o apontamento do IP da instancia para o Load Balancer e sucesso!
Agradeço a todos!

Acessar o site via HTTPS - AWS


how to join two field together

Question: i have a content type named product. i need to add product like this:
title: product1
description: this is a product
company:a
price:100
company:b
price:200
company is a node reference field with numbered of values set to unlimited and price is a text field but i don't know how relate price field with company.
if i can't do something like this in drupal 6, drupal 7 help me?
Answer: If you use CCK ver 3.x you get the multigroup submοdule. This allows you to create a group of fields like in you case company and price and then create multiple instances of this group.
UPDATE
CCK ver 3.x is alpha. However I have used it in production without problems. You could look into the issue queue for bugs in the 3.x version before you use it.
If you are creating a new site I would suggest going with drupal 7. CCK has moved to core in drupal 7 but the functionality of multigroup does not exist.
However you can achieve a similar result using the Field Collection module. Looking at this http://oliverdavies.co.uk/blog/2011/08/create-multigroups-drupal-7-using-field-collections or this http://mostrey.be/creating-multigroup-widgets-drupal-7 will find out how.
Comment: It is alpha version but I have used it in production without problems. Perhaps you could look into the issue queue for bugs in the 3.x version before you use it. If you are creating a new site I would suggest drupal 7. CCK has moved to core in drupal 7 but the functionality of multigroup does not exist. However you can achieve a similar result using the Field Collection module. Look at this http://mostrey.be/creating-multigroup-widgets-drupal-7 and this http://oliverdavies.co.uk/blog/2011/08/create-multigroups-drupal-7-using-field-collections
Comment: thank you. it is a alpha version. what about drupal 7?

how to join two field together