I can't figure out whats wrong with my java tictactoe

Question: It keeps spitting out "you can pick that space its already been taken and it seems like it's ignoring all the other if statements. I've been tinkering at this for a couple hours and I don't know how to fix it.
public class tictactoegame {

    public static void main(String[] args) {
        int j = 0;

        System.out.println("");
        char a = ('a');
        char b = ('b');
        char c = ('c');
        char d = ('d');
        char e = ('e');
        char f = ('f');
        char g = ('g');
        char h = ('h');
        char i = ('i');

        String gameboard = ("    1  2  3\n1   "+a+"| "+b+ " | "+c+"\n   - - - - -"+"\n2   "+d+"| "+e+ " | "+f+"\n   - - - - -"+"\n3   "+g+"| "+h+ " | "+i+"\n   - - - - -");
        System.out.println(gameboard);
        a = (' ');
        b = (' ');
        c = (' ');
        d = (' ');
        e = (' ');
        f = (' ');
        g = (' ');
        h = (' ');
        i = (' ');

        System.out.println();

        while (j < 9){
            int x = IO.inputInt("What is your x value");
            int y = IO.inputInt("What is your y value");

            //For X

            if (j%2 == 0){
                System.out.println("\n Invalid attempt, try again");
            }
            else if (x == 1 && y == 1 && a != 'X' && a != 'O' ){
                a = ('X');
                j++;
            }
            else if (x == 1 && y == 2 && b != 'X' && b != 'O' ){
                b = ('X');
                j++;
            }
            else if (x == 1 && y == 3 && c != 'X' && c != 'O' ){
                c = ('X');
                j++;
            }
            else if (x == 2 && y == 1  && d != 'X' && d != 'O' ){
                d = ('X');
                j++;
            }
            else if (x == 2 && y == 2  && e != 'X' && e != 'O' ){
                e = ('X');
                j++;
            }
            else if (x == 2 && y == 3  && f != 'X' && f != 'O' ){
                f = ('X');
                j++;
            }
            else if (x == 3 && y == 1 && g != 'X' && g != 'O' ){
                g = ('X');
                j++;
            }
            else if (x == 3 && y == 2  && h != 'X' && h != 'O' ){
                h = ('X');
                j++;
            }
            else if (x == 3 && y == 3  && i != 'X' && i != 'O' ){
                i = ('X');
                j++;
            }
            else {
                System.out.println("you cant pick that space its already been taken");}

            //For O

            if (j%2 != 0){
                System.out.println("\n Invalid attempt, try again");
            }
            else if (x == 1 && y == 1  && a != 'X' && a != 'O' ){
                a = ('O');
                j++;
            }
            else if (x == 1 && y == 2  && b != 'X' && b != 'O' ){
                b = ('O');
                j++;
            }
            else if (x == 1 && y == 3  && c != 'X' && c != 'O' ){
                c = ('O');
                j++;
            }
            else if (x == 2 && y == 1 && d != 'X' && d != 'O' ){
                d = ('O');
                j++;
            }
            else if (x == 2 && y == 2 && e != 'X' && e != 'O' ){
                e = ('O');
                j++;
            }
            else if (x == 2 && y == 3 && f != 'X' && f != 'O' ){
                f = ('O');
                j++;
            }
            else if (x == 3 && y == 1 && g != 'X' && g != 'O' ){
                g = ('O');
                j++;
            }
            else if (x == 3 && y == 2 && h != 'X' && h != 'O' ){
                h = ('O');
                j++;
            }
            else if (x == 3 && y == 3 && i != 'X' && i != 'O' ){
                i = ('O');
                j++;

            }
            else {
                System.out.println("you cant pick that space its already been taken");}

            if (a == 'X') {
                if (b == 'X') {
                    if (c == 'X') {
                        System.out.println("X wins!!!");
                        System.exit(1);
                    }
                }
            }
             if (d == 'X') {
                if (e == 'X') {
                    if (f == 'X') {
                        System.out.println("X wins!!!");
                        System.exit(1);
                    }
                }
            }
              if (g == 'X') {
                if (h == 'X') {
                    if (i == 'X') {
                        System.out.println("X wins!!!");
                        System.exit(1);
                    }
                }
            }
               if (a == 'X') {
                if (e == 'X') {
                    if (f == 'X') {
                        System.out.println("X wins!!!");
                        System.exit(1);
                    }
                }
            }
                if (a == 'X') {
                    if (d == 'X') {
                        if (g == 'X') {
                            System.out.println("X wins!!!");
                            System.exit(1);
                    }
                }
            }
                if (b == 'X') {
                    if (e == 'X') {
                        if (h == 'X') {
                            System.out.println("X wins!!!");
                            System.exit(1);
                    }
                }
            }
                if (c == 'X') {
                    if (f == 'X') {
                        if (i == 'X') {
                            System.out.println("X wins!!!");
                            System.exit(1);
                    }
                }
            }
                if (c == 'X') {
                    if (e == 'X') {
                        if (g == 'X') {
                            System.out.println("X wins!!!");
                            System.exit(1);
                    }
                }
            }

            //O

            if (a == 'O') {
                if (b == 'O') {
                    if (c == 'O') {
                        System.out.println("O wins!!!");
                        System.exit(1);
                    }
                }
            }
             if (d == 'O') {
                if (e == 'O') {
                    if (f == 'O') {
                        System.out.println("O wins!!!");
                        System.exit(1);
                    }
                }
            }
              if (g == 'O') {
                if (h == 'O') {
                    if (i == 'O') {
                        System.out.println("O wins!!!");
                        System.exit(1);
                    }
                }
            }
               if (a == 'O') {
                if (e == 'O') {
                    if (f == 'O') {
                        System.out.println("O wins!!!");
                        System.exit(1);
                    }
                }
            }
                if (a == 'O') {
                    if (d == 'O') {
                        if (g == 'O') {
                            System.out.println("O wins!!!");
                            System.exit(1);
                    }
                }
            }
                if (b == 'O') {
                    if (e == 'O') {
                        if (h == 'O') {
                            System.out.println("O wins!!!");
                            System.exit(1);
                    }
                }
            }
                if (c == 'O') {
                    if (f == 'O') {
                        if (i == 'O') {
                            System.out.println("O wins!!!");
                            System.exit(1);
                    }
                }
            }
                if (c == 'O') {
                    if (e == 'O') {
                        if (g == 'O') {
                            System.out.println("O wins!!!");
                            System.exit(1);
                    }
                }
            }
            if (j == 9 && a != ' '&& b != ' '&& c != ' '&& d != ' '&& e != ' ' && f != ' '&& g != ' '&& h != ' '&& i != ' '){
                System.out.println("Tie Game");
                System.exit(1);

            }

            System.out.println(gameboard);

        }}

    }

The program should let me change the values of a-i and display it on the game board instead it just spits out the else statement.
Comment: So have you tried [debugging](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your code? Stack Overflow requires that you identify the source of your problem, otherwise, there's no way to ask any sort of meaningful and specific question, which is kind of important for a Q&A site.
Comment: Incidentally, one problem that should be easy to fix is that you're never changing the value of the `gameboard` variable inside the loop, so no matter what happens with `a, b, c ...`, the board will always be printed the same.
Comment: To be honest, besides the code, you'd better give the specific rules for dealing with the problem or the "playstyle" of this "game", otherwise few people will have the patience to read this kind of code, at least I won't read it
Comment: Is there any possibility that the problem is in the `IO.inputInt` method, which you haven't shown?
Comment: When `if (j%2 == 0){` is `true`,  you should contain the actions within this block, same for `if (j%2 != 0){`
Comment: Also, `j` doesn't need to be incremented in each if statement, it should increment AFTER all the if statements have run
Comment: You're trying to deal with both X's turn and O's turn in the same iteration of the loop.  Within each iteration, you're prompting X for the co-ordinates of their turn; but you're never prompting O.  Then O's turn ends up being the same as X's turn, which fails; but then the code can never get back on track, because next time through the loop, you still don't ask O for their co-ordinates.  So the same error happens again and again.
Answer: You really need to learn how to desk check your code (sit down if a piece of paper and a pen and walk through you code writing down the state)
For example, let's look at...
if (j % 2 == 0) {
    System.out.println("\n Invalid attempt, try again");
} else if (x == 1 && y == 1 && a != 'X' && a != 'O') {
    a = ('X');
    j++;
} else if (x == 1 && y == 2 && b != 'X' && b != 'O') {
    b = ('X');
    j++;
} else if (x == 1 && y == 3 && c != 'X' && c != 'O') {
    c = ('X');
    j++;
} else if (x == 2 && y == 1 && d != 'X' && d != 'O') {
    d = ('X');
    j++;
} else if (x == 2 && y == 2 && e != 'X' && e != 'O') {
    e = ('X');
    j++;
} else if (x == 2 && y == 3 && f != 'X' && f != 'O') {
    f = ('X');
    j++;
} else if (x == 3 && y == 1 && g != 'X' && g != 'O') {
    g = ('X');
    j++;
} else if (x == 3 && y == 2 && h != 'X' && h != 'O') {
    h = ('X');
    j++;
} else if (x == 3 && y == 3 && i != 'X' && i != 'O') {
    i = ('X');
    j++;
} else {
    System.out.println("you cant pick that space its already been taken");
}

//For O
if (j % 2 != 0) {
    System.out.println("\n Invalid attempt, try again");
} else if (x == 1 && y == 1 && a != 'X' && a != 'O') {
    a = ('O');
    j++;
} else if (x == 1 && y == 2 && b != 'X' && b != 'O') {
    b = ('O');
    j++;
} else if (x == 1 && y == 3 && c != 'X' && c != 'O') {
    c = ('O');
    j++;
} else if (x == 2 && y == 1 && d != 'X' && d != 'O') {
    d = ('O');
    j++;
} else if (x == 2 && y == 2 && e != 'X' && e != 'O') {
    e = ('O');
    j++;
} else if (x == 2 && y == 3 && f != 'X' && f != 'O') {
    f = ('O');
    j++;
} else if (x == 3 && y == 1 && g != 'X' && g != 'O') {
    g = ('O');
    j++;
} else if (x == 3 && y == 2 && h != 'X' && h != 'O') {
    h = ('O');
    j++;
} else if (x == 3 && y == 3 && i != 'X' && i != 'O') {
    i = ('O');
    j++;

} else {
    System.out.println("you cant pick that space its already been taken");
}

This looks okay, but, let's step through it, first loop...

j == 0
x and y are 1
(j % 2 == 0) is true, print "Invalid attempt, try again"
(j % 2 != 0) is false
(x == 1 && y == 1 && a != 'X' && a != 'O') is true, set a to 'O', increment j by one (j == 1)

Next loop...

j == 1
x is 1, y is 2
(j % 2 == 0) is false
(x == 1 && y == 2 && b != 'X' && b != 'O') is true, set b to 'X', increment j by one (j == 2!!)
(j % 2 != 0) is false
(x == 1 && y == 2 && b != 'X' && b != 'O') is false!!
Print "you cant pick that space its already been taken"

And this is now your core issue.  Incrementing j inside each if statement will cause the next block to think it is it's turn.
What you could do is use a single if-elseif-else block, but, based on the value of j, set a player character, for example...
char player = 'X';
while (j < 9) {
    if (j % 2 == 0) {
        player = 'X';
    } else {
        player = 'O';
    }

    System.out.println("Current player: " + player);
    System.out.println("What is your x value");
    int x = scanner.nextInt();
    scanner.nextLine();
    System.out.println("What is your y value");
    int y = scanner.nextInt();
    scanner.nextLine();

    if (x == 1 && y == 1 && a != 'X' && a != 'O') {
        a = player;
        j++;
    } else if (x == 1 && y == 2 && b != 'X' && b != 'O') {
        b = player;
        j++;
    } else if (x == 1 && y == 3 && c != 'X' && c != 'O') {
        c = player;
        j++;
    } else if (x == 2 && y == 1 && d != 'X' && d != 'O') {
        d = player;
        j++;
    } else if (x == 2 && y == 2 && e != 'X' && e != 'O') {
        e = player;
        j++;
    } else if (x == 2 && y == 3 && f != 'X' && f != 'O') {
        f = player;
        j++;
    } else if (x == 3 && y == 1 && g != 'X' && g != 'O') {
        g = player;
        j++;
    } else if (x == 3 && y == 2 && h != 'X' && h != 'O') {
        h = player;
        j++;
    } else if (x == 3 && y == 3 && i != 'X' && i != 'O') {
        i = player;
        j++;
    } else {
        System.out.println("A you cant pick that space its already been taken");
    }

(please note, I replaced your IO class for Scanner as IO is not a standard Java library class)
Oh and at the end of that, you need to update the gameboard
gameboard = ("    1  2  3\n1   " + a + "| " + b + " | " + c + "\n   - - - - -" + "\n2   " + d + "| " + e + " | " + f + "\n   - - - - -" + "\n3   " + g + "| " + h + " | " + i + "\n   - - - - -");

otherwise it will never change


Probability of at least x Hamiltonian paths in a random tournament

Question: Let $X$ be a random variable denoting the number of Hamiltonian paths in a random tournament with $n$ vertices. I'm trying to compute the probability that there are at least $x$ such paths in the random tournament. My thinking is that there are $n!$ permutations of the vertices and therefore $n!$ total Hamiltonian paths in the random tournament. The probability that a given permutation contains a Hamiltonian path is $(\frac{1}{2})^{n - 1}.$ Then $$Pr[X >= x] = 1 - \Pr[X < x] = 1 - \sum_{k = 0}^{x - 1} C(n!, k) \cdot (1/2)^{n - 1}.$$ Am I on the right track? If so, how can this expression be simplified?
Answer: Even if the Hamiltonian paths were independent, the probability of seeing exactly $k$ Hamiltonian paths would not be $\binom{n!}{k} \frac1{2^{n-1}}$ as it is in your answer: it would be $$\binom{n!}{k} \left(\frac1{2^{n-1}}\right)^k \left(1 - \frac1{2^{n-1}}\right)^{n!-k}.$$
So this is what a term in your summation should look like.
However, the summation will still not give the correct answer, because Hamiltonian paths are not independent. If one particular path is present, then paths that share many edges with it are more likely to appear, and paths that contain any edges going the other way are guaranteed not to appear. This is pretty much impossible to take into account systematically. In particular, we have $\Pr[X=0] = 0$, since any tournament contains a Hamiltonian path.
We can compute the expected value $\mathbb E[X]$ more easily: it is $\frac{n!}{2^{n-1}}$ by linearity of expectation, since there are $n!$ possible Hamiltonian paths and each of them appears with probability $\frac1{2^{n-1}}$.
This can give us some upper and lower bounds on $\Pr[X \ge x]$. For example:

We have $\Pr[X \ge x] \le \frac{\mathbb E[X]}{x} = \frac{n!}{x \cdot 2^{n-1}}$, by Markov's inequality.
We have $\Pr[X \ge x] \ge \frac{\mathbb E[X]-x}{n!-x}$ by making use of the fact that $X$ can never be larger than $n!$.

These are not very good bounds; more can be learned from understanding, for example, higher moments of $X$ such as $\mathbb E[X^2]$.


Electron: process.platform undefined

Question: My global variable process is not set when my electron app is packaged. It only contains these info: {"title":"browser","browser":true,"env":{},"argv":[],"version":"","versions":{}}.
process is not manipulated in my code and info like process.platform are only available in development mode. I'm using electron-builder (v23.6.0) and electron (v23.1.3).
I found this problem when using electron-updater. This package uses variables like process.platform or process.resourcesPath so I guess it's not normal that mine is that empty.
Comment: you're accessing `process` in the main process, or where?
Comment: Yes, that's what I'm trying to do.
Answer: I found a solution by explicitly importing the 'process' package like so
import prcs from 'process'

I assumed it would be accessible in the main process without doing that since it's possible in other nodeJS applications. Apparently not.
Comment: This fix issue for me too. Thanks! The strange thing is that in previous electron-react-boilerlate project structure process.platform works as expected.
Answer: The reason for this issue is that you use node-polyfill-webpack-plugin
it polyfill node.js process global with this short version for the web browser only.
You can try in webpack config to exclude process from polyfilled globals
new NodePolyfillPlugin({
            excludeAliases: ['process']
})

Electron: process.platform undefined


Classification of Bieberbach groups

Question: Does anybody know if there exists a list of the four dimensional Bieberbach groups presented by generators and relations on the web?. I know there exists the book Crystallographic Groups of Four-Dimensional Space by Brown, Bulow and Neubuser, but I do not have it at the moment.
Answer: You may want to look into GAP, a system for computational discrete algebra, which contains the CrystCat package. This package contains all information contained in the book you mention.
To check if a group is Bieberbach, you can use DisplaySpaceGroupType, which will mention "fp-free" if the group is torsion-free.
gap> DisplaySpaceGroupType(3,6,1,1,1);
#I     Space-group type (3,6,1,1,1); IT(168) = P6; orbit size 1
gap> DisplaySpaceGroupType(3,6,1,1,4);
#I    *Space-group type (3,6,1,1,4); IT(169) = P61, IT(170) = P65;
#I      orbit size 2; fp-free

If you want a simple list of generators and relations, see the following example:
gap> S := SpaceGroupOnRightBBNWZ(3,6,1,1,4);
SpaceGroupOnRightBBNWZ( 3, 6, 1, 1, 4 )
gap> F := Image(IsomorphismFpGroup(S));
<fp group on the generators [ f1, f2, f3, f4, f5 ]>
gap> RelatorsOfFpGroup(F);
[ f1^3*f5^2, f2^-1*f1^-1*f2*f1, f2^2*f5, f3^-1*f1^-1*f3*f1*f3*f4^-1,
  f4^-1*f1^-1*f4*f1*f3*f4^2, f5^-1*f1^-1*f5*f1, f3^-1*f2^-1*f3*f2*f3^2,
  f4^-1*f2^-1*f4*f2*f4^2, f5^-1*f2^-1*f5*f2, f4^-1*f3^-1*f4*f3,
  f5^-1*f3^-1*f5*f3, f5^-1*f4^-1*f5*f4 ]

You can then simplify this presentation as follows:
gap> G := SimplifiedFpGroup(F);
<fp group on the generators [ f1, f2, f4 ]>
gap> RelatorsOfFpGroup(G);
[ f2^-1*f1^-1*f2*f1, f2^-1*f4*f2*f4, f2^-4*f1^3, (f4^-1*f1)^2*f4^-1*f1^-2,
  f1^-1*(f4*f1)^2*f4*f1^-1, f2*f4^-1*f1^-1*f2^-2*f1*f4*f2 ]

You may also be interested in the Carat package, which allows you to calculate a database of higher-dimensional crystallographic groups and the AcLib package, which contains a database of almost-crystallographic groups.
Comment: The link is broken
Comment: @YCor Thank you for notifying me of this!
Answer: See Sections 3 and 4 of Chapter 8 of my book
``Four-Manifolds, Geometries and Knots",
Geometry and Topology Monographs 5 (2002)
(revised in 2007 and 2014).
Presentations are given for the groups which are not {\it uniquely}
semidirect products $G\rtimes_\theta\mathbb{Z}$.
In the remaining cases, $G$ is a flat
3-manifold group, and the possible automorphisms $\theta$ are given.
Presentations and automorphisms of flat 3-manifold groups
are considered in Section 2 of the same chapter,
and it is straightforward to write down a presentation
for each such semidirect product.
The list of 4-dimensional Bieberbach groups is also rederived in
the arXiv paper 1303.6613 [math.GT] by Lambert, Ratcliffe and Tschantz.
(They noticed an oversight in my treatment of the four examples
with finite abelianization, but the presentations are correct.)
Comment: Please include the essence of the answer

Classification of Bieberbach groups


Propensity score matching in cross-sectional survey data and different size of subgroups

Question: Let's say that I have a mutation in 1% of a population in a cross-sectional survey:
library(NHANES)
library(survey)
library(MatchIt)

# Generate survey dataset including sample weights and strata
myvars <- c("ID","Gender", "Age", "BMI", "Race1", "Diabetes","SDMVPSU", "SDMVSTRA", "WTMEC2YR")
nhanes <- as.data.frame(subset(NHANESraw, SurveyYr == "2009_10"))
nhanes <- na.omit(nhanes[myvars])

# Including presence of "mutation" in 1% of the entire population. Yes = 1; No = 0
set.seed(999)
nhanes$mutation <- sample(c(0, 1), replace = T, size = nrow(nhanes), prob = c(0.99, 0.01))

Now I would like to examine whether there is a difference in BMI mean according to the presence of the mutation.
As expected, there is a huge between-group difference in size according to the presence or absence of the mutation:
mutation0 = 9300; mutation1 = 109.
In order to achieve my task I attempted different approaches:
1. Crude unweighted GLM
# crude unweighted GLM, which showed a difference in mean BMI of 1.47236 between groups (P = 0.0482)

summary(glm(BMI ~ mutation, data = nhanes))

2. Crude weighted GLM
# crude weighted GLM, which showed a difference in mean BMI of 2.4454 between groups (P = 0.0579)
# Using sarvey procedure accounting for sample weight
nhanesDesign <- svydesign(id      = ~SDMVPSU,
                          strata  = ~SDMVSTRA,
                          weights = ~WTMEC2YR,
                          nest    = TRUE,
                          data    = nhanes)
summary(svyglm(BMI ~ mutation,
              data   = nhanes,
              design = nhanesDesign))

3. ADJ unweighted GLM
# ADJ unweighted GLM, which showed a difference in mean BMI of 0.97542 between groups (P =  0.126)
summary(glm(BMI ~ mutation + Age + Gender + Race1 + Diabetes, data = nhanes))

4. ADJ weighted GLM
# ADJ weighted GLM, which showed a difference in mean BMI of 1.831912 between groups (P =  0.0620)
# Using sarvey procedure accounting for sample weight
    summary(svyglm(BMI ~ mutation + Age + Gender + Race1 + Diabetes,
                   data   = nhanes,
                   design = nhanesDesign))

I feel that there is something that I miss. I guess that this huge difference in size between groups can lead to misleading results.
For this reason I have approched Propensity Score Matching (excluding BMI variable) in order to provide more reliable results:
5. Propensity Score Matching
# Choose subjects according to propensity score
match_model <- matchit(mutation ~ Age + Gender + Race1 + Diabetes,
                       data = nhanes,
                       method = "nearest")
match_data <- match.data(match_model)
colnames(match_data)[12] <- "propensity_weights"

# ADJ unweighted GLM from Propensity
summary(glm(BMI ~ mutation + Age + Gender + Race1 + Diabetes, data = match_data))

# Survey Design from Propensity matching
nhanesPropensity <- svydesign(id      = ~SDMVPSU,
                              strata  = ~SDMVSTRA,
                              weights = ~WTMEC2YR,
                              nest    = TRUE,
                              data    = match_data)
summary(svyglm(BMI ~ mutation + Age + Gender + Race1 + Diabetes,
               data   = match_data,
               design = nhanesPropensity))

I have some questions:

Which one of the above listed methods is the most reliable? In
other words, what is the right approach to data analyses
(specifically, for the calculation of mean BMI) when there is a
large difference in size between groups, like in this case?
is propensity score matching an appropriate approach to overcome
between-groups differences in this kind of population
(cross-sectional survey)?
is the use of sample weights appropriate in propensity matching, as proposed above?
Answer: First, you would expect that the mutation and no mutation groups would have the same BMI since the presence of the mutation is completely independent from BMI and all other variables in the data. The fact that you got a significant difference using the first comparison is a fluke; if you use a different seed, (e.g., 9999), you get a nonsignificant difference. No matter what method you use, your estimate of the effect of mutation should be unbiased for 0. That is, whether you consider the unweighted population, the survey-weighted population, or a propensity score-matched population, the difference in group means for BMI is equal to zero, and no amount of conditioning or adjusting will make any of the estimators fail to converge to zero in expectation. The estimator with the lowest variance (i.e., the most precision) will be the covariate-adjusted unweighted comparison because adding covariates predictive of the outcome increases precision and including survey weights decreases precision.
If your question is more broadly about estimating an exposure effect in complex survey data, then we can discuss the differences among the approaches. First, it doesn't matter that your groups are of unequal size. That affects the precision of any estimator, but not the choice of which estimator you should use.
Second, you only need to incorporate the survey design into the analysis if the quantity of interest varies across sampling units or across the variables used to compute the survey weights. If not (i.e., if the exposure effect was equal for all members of the population), you don't need to incorporate the sampling design. Failing to incorporate the survey design means that your estimates generalize to the wrong population, but if the quantity estimated doesn't vary across populations, it doesn't matter whether you attempt to generalize to the unweighted or correctly weighted population.
Third, propensity score analysis with complex survey designs is not well understood, but there has been some literature on it. See DuGoff, Schuler, and Stuart (2014) for a review and current best practices. The choices of how to proceed depend on the goals of the analysis.
Finally, to answer an implied question, it's rarely the case that propensity score methods outperform well-specified regression models. Propensity score methods severely decrease the precision of your estimate, thereby increasing the typical error of an estimate even if the bias is reduced. Unless you have a good reason to prefer propensity score-based approaches (and the one you provided, to generally improved robustness, is not one), you should probably stick with regression approaches to estimate exposure effects, though you should use more sophisticated regression methods like the parametric g-formula over just throwing covariates in a regression.

DuGoff, E. H., Schuler, M., & Stuart, E. A. (2014). Generalizing Observational Study Results: Applying Propensity Score Methods to Complex Surveys. Health Services Research, 49(1), 284–303. https://doi.org/10.1111/1475-6773.12090
Comment: Thank you for your kind words. 1:1 PS matching is one of the most egregious wastes of precision, but standard IPW causes a similar loss because the effective sample size is inversely related to the variance of the weights. There are some more sophisticated versions of weighting that attempt to retain precision, but none will outperform regression assuming the functional form is correctly specified.
Comment: A much better answer than the one I was thinking about writing (+1). I understand your skepticism in the last paragraph with respect to propensity score matching, which can throw out lots of useful data, but do the same considerations hold with respect to methods like inverse propensity score weighting when all cases are included (even if differentially weighted)?


in laravel how to search student data by ( "registor no" and "joing date" )and display student name, fname, mname, lname in view

Question: any one guide me how to do this
this is input view,

output come in view like this with student data

my model
Student.php
<?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $table = 'student_lists';
    // protected $dates = ['certificate_issue_date','date_of_join','date_of_completion','dob'];

    protected $fillable = ['student_name', 'student_registration_id', 'date_of_join', 'student_phone_no', 'student_photo' ];

}

my route
Route::any ( '/search', function () {
    $q = Input::get ( 'q' );
    $user = Student::where ( 'student_registration_id', 'LIKE', '%' . $q . '%' )->orWhere ( 'email', 'LIKE', '%' . $q . '%' )->get ();
    if (count ( $user ) > 0)
        return view ( 'my-search' )->withDetails ( $user )->withQuery ( $q );
       else
         return view ( 'my-search' )->withMessage ( 'No Details found.  Try to search again !' );
} );

my view

 {{ csrf_field() }}

               @if(isset($details))  The Search results for
  your query   are : Sample User details    Name Email
  Photo    @foreach($details as $user)
  {{$user->name}} {{$user->email}}  student_photo }}"    class="img-circle" width="90" />
   @endforeach   @elseif(isset($message))
  {{$message}} @endif
Comment: we would need to see your code of your models, your controller and what you tried so far
Comment: can you post your tabke migration so that we can suggest you a query to do that
Comment: @Khalid Khan i added my controller view and route
Comment: @Paladin i added
Comment: @user12380208 Everything looks fine to me. Then what problem you are facing with  this above code ?
Comment: @Khalid Khan look my model and give me solution in your way i was tried many way but i get error so guide me
Comment: @KhalidKhan in this code showing all student data wen i refresh the page and i what to passing "date of join " and "register no"  that time only display data in view
Comment: @user12380208 Check my answer
Answer: Put this is your model Students.php
public static function search(string $search) {
    $columns = ["student_registration_id", "date_of_join"];

    // If the search is empty, return everything
    if (empty(trim($search))) {
      return static::select($columns)->get();
    }
    // If the search contains something, we perform the fuzzy search
    else {
      $fuzzySearch = implode("%", str_split($search)); // e.g. test -> t%e%s%t
      $fuzzySearch = "%$fuzzySearch%"; // test -> %t%e%s%t%s%

      return static::select($columns)->where("name", "like", $fuzzySearch)->get();
    }
}

Create one controller and paste this code there:
class SearchController extends Controller {
    public function type(Request $request, $search = "") {
      $search = Input::get('q');
      $user =  Student::search($search);

      return view ('my-search',compact($user));
    }
  }

And your route for this should be:
Route::get( '/search', 'SearchController@type');

Hopefully it'll help you
Comment: showing error "Argument 1 passed to App\Student::search() must be of the type string, null given, called in"
Comment: is input::get('q') getting anything ?
Comment: just i typed url in browser it showing error it not showing view page except error
Comment: Have you created that controller ?
Comment: @user12380208 I've updated the code above. I've just renamed the function and route. Please check if it is working
Comment: Same error ,, if possible  to you make working example code


Troubleshooting issue forks to make core version compatibility fixes

Question: During the Drupal 8->9 upgrade, we noticed an issue where module maintainers had abandoned a project or were not responding to merge requests in a timely manner. As you know, composer doesn't care about patches when it comes to compatibility with major versions of Drupal, so you need an actual release which is compatible with the next major version before you can update drupal core in composer. This problem was easily solved by using issue forks to make core version compatibility fixes as per the article on Drupal.org.
Now, for the 9->10 upgrade, I have yet to get this to work for some reason. I am wondering if anything has changed for the syntax we need to use, perhaps with gitlab or something.
For example, I have set my drupal repositories to ignore drupal/views_ef_fieldset and use the issue branch:
<code>"repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8",
            "exclude": [
                "drupal/views_ef_fieldset"
            ]
        },
        "drupal/views_ef_fieldset": {
            "type": "git",
            "url": "https://git.drupalcode.org/issue/views_ef_fieldset-3290466.git"
        },
</code>
Require line:
<code>"drupal/views_ef_fieldset": "dev-3290466-automated-drupal-10",
</code>
I am fairly certail all of this is correct. Here is the issue branch:
https://git.drupalcode.org/issue/views_ef_fieldset-3290466/-/tree/3290466-automated-drupal-10?ref_type=heads
But I get this:

Your requirements could not be resolved to an installable set of packages.
Problem 1

Root composer.json requires drupal/views_ef_fieldset dev-3290466-automated-drupal-10, found drupal/views_ef_fieldset[dev-1.x, 1.x-dev (alias of dev-1.x)] but it does not match the constraint.

Has the methodology for doing this changed since 9th?
Comment: FYI: For the Drupal 8 -> 9 upgrade there is a lenient composer [endpoint](https://www.drupal.org/docs/develop/using-composer/using-drupals-lenient-composer-endpoint). For 9 -> 10 there is a lenient composer [plugin](https://github.com/mglaman/composer-drupal-lenient) to ignore the major version constraint.
Comment: Thank you @Hurdi. I think this is the best solution to the problem.
Answer: As @Hudri mentioned, the lenient composer package is the right answer here. It is, actually, the new suggested method for dealing with these situations rather than pinning to a feature branch.
Documentation:

https://github.com/cweagans/composer-patches
https://www.drupal.org/docs/upgrading-drupal/upgrading-from-drupal-8-or-later/upgrading-a-composer-based-site


How can I connect to MySQL remotely and still keep it safe?

Question: As you know, keeping the MySQL port 3306 open is unsafe. However, I would like to use a good MySQL administration program instead of phpMyAdmin, which requires 3306 port to be open.
Of course I can allow only my IP address to connect to port 3306 using ipfw. The problem is that my IP address changes every 24 hours, so I would have to add a new rule for every IP address.
Isn't there a better way to keep MySQL safe and still use the remote connection?
Answer: Yes, with SSH port forwarding.
On your local machine, issue the command
ssh -L 3306:127.0.0.1:3306 firstname.lastname@example.com

and then you can connect your local MySQL admin tool to port 3306 on your local machine. You have to consider though that for the MySQL the connection appears to be coming from 127.0.0.1 as well, so the access rights for your MySQL user most be set accordingly.
If you happen to use a MySQL server on the local machine, port 3306 will be already taken, but you can just use a different port for the forwarding (13306:127.0.0.1:3306) and then point your admin tool to that different port.
(More info with man ssh).

Edit Some more explanations as an answer to your comments:

You will use this command on your local machine where you usually work, just before you want to do some administrative work on your database. What is does is to create a tunnel via SSH that forwards all traffic going to a port on your local machine to another port on another machine.
In this case, the tunnel ends on the MySQL server, which you contact directly via SSH. The part email@example.com is just a placeholder, replace it with the username of your shell account and the IP address or host name of MysQL server. From your local machine, that will definitively not be localhost though. This part is not at all about your MySQL username, because SSH doesn't know about MySQL.
If you work as root on your database, you will connect your MySQL admin tool to port 3306 on the host 127.0.0.1 and use the username root. Although you work from a remote host, for the MysQL server the connection appears to coming from localhost, so the access permissions must be set accordingly.
SSH port forwarding / tunneling is an extremely powerful tool. You should definitely read more about it.
Comment: So, when I will use the command you gave, I'll be able to connect remotely to my mysql server, but then, local connection like website and other services wont be available until I forward the port? Sounds like a tunnel for me.
Comment: And what exactly does this mean: `email@example.com` it should be `root@localhost` for a mysql `root` user?
Comment: @Cyclone: See my edit.
Comment: Look what I've added: http://pastebin.com/VHkyhTir
And I still can not connect remotely.
Comment: This unfortunately not work...
Comment: Have you managed to get the SSH connection working? If not, search on Serverfault or Google for the error message and you will get loads of hints what to do. And what *does not work* mean?
Comment: I'm trying to connect via Navicat to my mysql server, and it does not work.


Taxonomy Terms node count of different content type along with zero count in a hierarchy

Question: After much headache I was able to maintain a kind of hierarchy for the taxonomy terms, of the already continuing issue here, please click the below link
Taxonomy Terms node count of different content type
I did It like this, but still needs to do more.
In second step select the parent relation and check the exclude display.

Under format option select the parent taxonomy under group 1

I am getting the parent category under  tag and the child terms as list-terms. using jquery I can display it in an accordion style somehow.

Now the problem i am facing is that empty taxonomy terms with counter zero are not getting displayed, please help if anyone knows the solution.
Answer: Check what you have set for the "no results" behaviour on that field. You will not want it set to "hide".
Also check if it displays in the views preview. If it displays there but not on your page then it may be that your template is checking if a field is blank and before deciding whether to show it - you could solve this by setting a default/no results value of "0"
Comment: I unchecked the check box "Hide if empty" for this particular field but unfortunately empty terms are not shown, even not in view preview.
Comment: Try entering "0" (zero) in the "no results behaviour text" box. This should put the number zero when there are no results rather than just not displaying the item. Not sure if this will not cause the number 1 to appear as there is now a value so test and see.
Comment: I tried with number "0" but nothing happens, may be some other way..
Comment: Actually by adding reverse relation in relationships the empty terms gets hidden...
Comment: Does anyone founds any solution for this....


How to get Display Mode of a product variation in hook_commerce_form_add_to_cart_form_alter?

Question: I want to alter a product display using hook_form_alter as below:
<code>/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function HOOK_form_commerce_order_item_add_to_cart_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $product = $form_state->getFormObject()->getEntity()->getPurchasedEntity();

// THIS WHERE I want something like
  if($product->viewMode() == 'compact') {
     // do something...
  }
}
</code>
Any help would be appriciated.
Answer: Never mind figured out myself,
I found the answer to get the view_mode you need to access storage of form stage using following code.
<code>$form_state->getStorage()['view_mode'];
</code>
This will return string based on which view mode the form is attached to.
i.e, "defualt" or "compact" etc...


Concluding three statements regarding $3$ real numbers.

Question:
$\{a,b,c\}\in \mathbb{R},\ a<b<c,\ a+b+c=6 ,\ ab+bc+ac=9$
Conclusion $I.)\ 1<b<3$
Conclusion $II.)\ 2<a<3$
Conclusion $III.)\ 0<c<1$
Options
By the given statements
$\color{green}{a.)\  \text{Only conclusion $I$ can be derived}}$.
$b.)\ $ Only conclusion $II$ can be derived.
$c.)\ $ Only conclusion $III$ can be derived.
$d.)\ $  Conclusions $I,\ II,\ III$ can be derived.
$e.)\ $  None of the three conclusions can be derived.

$\quad\\~\\$
I tried $(a+b+c)^2=36 \implies a^2+b^2+c^2=18$
and found that $(a,b,c)\rightarrow \{(-1,1,4),(-3,0,3)\}$ satisfies the two conditions
$a^2+b^2+c^2,\ a<b<c $  but not this one $a+b+c=6$
I thought a lot but can't find any suitable pairs.
I look for a simple and short way.
I have studied maths upto $12$th grade.
Comment: But if to solve a system of Diophantine equations?  $$ \left\{\begin{aligned}&a+b+c=6x\\&ab+ac+bc=9x^2\end{aligned}\right. $$  But there is one number always turns negative.
Comment: I'm in the sign was wrong. There is a solution. This.  $$a=3p^2$$ $$b=3s^2$$ $$c=3(p+s)^2$$ $$x=p^2+ps+s^2$$  Or so.  $$a=4s^2$$ $$b=9p^2+6ps+s^2$$  $$c=9p^2-6ps+s^2$$  $$x=3p^2+s^2$$
Answer: I shall show that only Conclusion I is correct. For a fixed $b$, we have
$a+c=6-b$ and $ac=9-(a+c)b=9-(6-b)b=(b-3)^2$.  Hence, the quadratic polynomial
$x^2-(6-b)x+(b-3)^2$ has two distinct real roots $x=a$ and $x=c$.  Therefore,
the discriminant $(6-b)^2-4(b-3)^2=3b(4-b)$ of this quadratic is strictly
positive (hence, $0<b<4$).  Furthermore, the roots of the quadratic are
$a=\dfrac{(6-b)-\sqrt{3b(4-b)}}{2}$ and $c=\dfrac{(6-b)+\sqrt{3b(4-b)}}{2}$.  As
$a<b<c$, we must have $\dfrac{(6-b)-\sqrt{3b(4-b)}}{2}<b<\dfrac{(6-b)+\sqrt{3b(4-b)}}{2} $, or equivalently,
$-\sqrt{3b(4-b)}<3b-6<+\sqrt{3b(4-b)}$.  Hence,
$\sqrt{3}|b-2|<\sqrt{b(4-b)}$, or $3(b-2)^2<b(4-b)$.  Ergo, $4(b-1)(b-3)<0$.
That means $1<b<3$.
Note that $b=2$ gives a solution $(a,b,c)=(2-\sqrt{3},2,2+\sqrt{3})$.
Consequently, Conclusions II and III are false.  In fact, we can prove that
$0<a<1<b<3<c<4$.  It might be a good exercise for you to show that $0<abc<4$.
Answer:
$\{a,b,c\}\in \mathbb{R},\ a<b<c,\ a+b+c=6 ,\ ab+bc+ac=9$
Conclusion I.) $1<b<3$
Conclusion II.) $2<a<3$
Conclusion III.) $0<c<1$

Let $\{p,q,r\}\in \mathbb{R}: a=\min(p,q,r),\ c=\max(p,q,r),
b=\max(\min(p,q),\min(q,r),\min(r,p))$.
Let's solve a system
\begin{align}
p+q+r&=6 ,\\
pq+qr+rp&=9
\end{align}
for $q$ and $r$ in terms of $p$:
\begin{align}
q(p)&=3-\frac{1}{2} p-\frac{1}{2} \sqrt{3p (4-p)},
\\
r(p)&=3-\frac{1}{2} p+\frac{1}{2} \sqrt{3p (4-p)}.
\end{align}
The solution suggests that
$0\le p\le 4$ (to ensure real values).
This diagram illustrates relationship between $p,q$ and $r$:

Analysis of $q(p)$ and $r(p)$
(boundary end extreme points)
shows that
\begin{align}
a&=\begin{cases}
p,& 0<p<1\\
q(p),& 1<p<4
\end{cases}
\\
b&=\begin{cases}
q(p),& 0<p<1\\
p,& 1<p<3\\
r(p),& 3<p<4
\end{cases}
\\
c&=\begin{cases}
r(p),& 0<p<3\\
p,& 3<p<4\\
\end{cases}
\end{align}
And
$0<a<1$
$1<b<3$
$3<c<4$:

so the answer is

a.) Only conclusion I can be derived.


how to create csv using 2 csv info?

Question: I have two  csv tables with schema of
table A as (Name,X,Y,date,time,millisecond,type1)
and
table B as (Name ,X,Y,date,time,millisecond,type2)
I want table C with schema (X,Y,type1,type2) where X,Y,time of table must be same millisecond may not be same.How can I do this?
Table A:
    Edp,1116,313,23/6/2020,7:25:48,637,ToBolled
    Edp,1155,313,23/6/2020,7:25:50,899,ToItaled
    Edp,1155,313,23/6/2020,7:25:51,14,ToItaled
    Edp,1198,308,23/6/2020,7:25:53,217,ToUndled
    Edp,1198,308,23/6/2020,7:25:53,323,ToUndled
    Edp,1198,308,23/6/2020,7:25:53,431,ToUndled

Table B:
    Edp,1155,313,23/6/2020,7:25:50,891,dou
    Edp,1198,308,23/6/2020,7:25:53,211,tri

Result table:
 Edp,1155,313,23/6/2020,7:25:50,899,ToItaled,dou
 Edp,1198,308,23/6/2020,7:25:53,431,ToUndled,tri

Comment: What is *a csv table*?
Comment: ' must be same millisecond may not be same' - come again?
Comment: may not be same
Comment: Not with you , can you add sample data and expected outcome as text please.
Comment: now can you pls see question again
Comment: comma seperated values
Comment: There is no logic I can see for arriving at the result.
Comment: @gmb https://dev.mysql.com/doc/refman/8.0/en/csv-storage-engine.html
Comment: so we cant make  result table from 2 tables?
Comment: @P.Salmon: thank you! I learnt something here.
Answer: I think that you are looking for a join:
select a.*, b.type2
from tablea a
inner join tableb b
    on  b.name = a.name
    and b.x    = a.x
    and b.y    = a.y
    and b.date = a.date
    and b.time = a.time

This brings records from both tables that have the same (name, x, y, date, time). You might want to adjust the conditions for your exact use case.
Comment: How to do this for csv?
Comment: In MySQL CSV is just a storage engine (as explained in the link given by P.Salmon in a comment to your question), so you can query the tables like you would with other storage engines.

how to create csv using 2 csv info?


Ajuda para Comparar ID com String

Question: Bom pessoal, estou desenvolvendo uma aplicação simples que quando iniciada fica exibindo Imagens e texto aleatórios na tela só para aprendizado e o que tenho até agora é isso:
package br.com.appteste;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class RunActivity extends ActionBarActivity {

    Timer timer = new Timer();

    int delay = 1000;
    int interval = 1000;

    ImageButton imBt_Post;
    TextView tv_Post, tv_setScore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running);

        imBt_Post = (ImageButton) findViewById(R.id.ImageSelectGame);

        tv_Post = (TextView) findViewById(R.id.TextSelectGame);
        tv_setScore = (TextView) findViewById(R.id.TextScoreGame);

        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                int[] varButtonImages = {R.drawable.circle_blue,
                                         R.drawable.circle_green,
                                         R.drawable.circle_pink,
                                         R.drawable.circle_red,
                                         R.drawable.circle_yellow};

                final int buttonSelect = varButtonImages[new Random().nextInt(varButtonImages.length)];

                imBt_Post.setTag(buttonSelect);

                imBt_Post.post(new Runnable() {
                    @Override
                    public void run() {
                        imBt_Post.setBackgroundResource(buttonSelect);
                    }
                });

                String[] varTextColor = {"Azul","Verde","Rosa","Vermelho","Amarelo"};

                final String textSelect = varTextColor[new Random().nextInt(varTextColor.length)];

                tv_Post.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_Post.setText(textSelect);
                    }
                });
            }
        }, delay, interval);

        imBt_Post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Estou tentando a partir deste código achar um jeito que quando o usuário clique no ImageButton "imBt_Post" aconteça a comparação para ver se o texto que foi sorteado e setado no TextView "tv_Post" corresponde a cor do circulo (Imagem) setada no ImageButton, alguem poderia me ajudar em como fazer isso porque no momento não tenho a minima ideia de como fazer isso.
Comment: Não é mais fácil você trabalhar com índices? Porque não guarda o índice do item sorteado como variável de instância e fazer a comparação entre os dois índices?
Comment: desculpe... sou iniciante.. poderia me ajudar a fazer isso?
Comment: Ok, estou montando uma explicacao do que estou falando.
Comment: estou no aguardo :)
Answer: Minha sugestão é guardar o estado das cores e do texto selecionado na Activity, assim como os vetores de valores possíveis como constantes:
public class RunActivity extends ActionBarActivity {

    // Valores possiveis de Drawables para o ImageButton
    private static final int[] cores =
    {
        R.drawable.circle_blue,
        R.drawable.circle_green,
        R.drawable.circle_pink,
        R.drawable.circle_red,
        R.drawable.circle_yellow
    };

    // Constante com os valores possiveis de cores em formato textual
    private static final String[] coresTexto =
    {
        "Azul",
        "Verde",
        "Rosa",
        "Vermelho",
        "Amarelo"
    };

    // Valores atuais dos vetores
    int mIndiceTexto, mIndiceCor;
    Random mRandom = new Random();

    // Restante das suas variaveis de instancia

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Restante do seu codigo...

        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                mIndiceTexto = mRandom.nextInt(coresTexto.length);
                mIndiceCor = mRandom.nextInt(cores.length);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imBt_Post.setBackgroundResource(cores[mIndiceCor]);
                        tv_Post.setText(coresTexto[mIndiceTexto]);
                    }
                });
            }
        }, delay, interval);
    }

    // Restante do seu codigo
}

Para fazer a comparação:
imBt_Post.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(mIndiceCor == mIndiceTexto) {
            // A cor e o texto sao iguais
        }
    }
});

Comment: perfeito :) vlw cara... muito obrigado!

Ajuda para Comparar ID com String


How to use require.js for managing JavaScript dependencies in a Django project?

Question: I use RequireJS for managing dependencies between my JavaScript libraries and modules. The backend is written in Django. Django has many apps for managing static assets, but none of them talk about incorporating the r.js compiler.
What's the best way to manage and compile my JS files using r.js in Django?
My requirements are:

Versioned output file to get around caching when the file is updated.
Automatically use uncompiled JS file when DEBUG = True in settings.py for Django, and the compiled file when Debug = False.
Some of the libraries will be loaded from CDN (such jquery) with a local fallback.

Any suggestions will be much appreciated.
Comment: Interesting timing. I just finished writing a `r.js` module for `django-assets`. Needs some polish and I should be able to open source it.
Comment: @WyattAnderson Any progress?
Comment: Awesome! If you need a beta tester, count me in!
Comment: For the caching part, I copy the JQuery Ajax NoCache method (somewhat), by adding a version number to the request src='/path/to/file.js?VERSION={{ settings.VERSION }}'
Comment: @Pykler Do you update `settings.VERSION` manually every time you edit one of the JS files, or do you have that automated somehow?
Answer: Seems as though django-require covers at least some of what you need,  https://github.com/etianen/django-require .


Passar valores SQL para outra pagina Ionic 3

Question: Tenho um input em uma pagina que e armazenado no banco de dados e gostaria de mostrar o que foi armazenado em uma nova pagina.

<ion-list>
  <ion-item>
      <ion-input type="text" placeholder="Nome" [(ngModel)]="entry.name" clearInput ></ion-input>
    </ion-item>
  <ion-item>
    <ion-input type="tel" name="phone" placeholder="Celular" [brmasker]="{phone: true}" [(ngModel)]="entry.celular" clearInput ></ion-input>
  </ion-item>
</ion-list>
<ion-item>
  <ion-textarea rows="3" cols="10" placeholder="Deixe aqui comentários e sugestões..." [(ngModel)]="entry.description"></ion-textarea>
</ion-item>

  Enviar
segue arquivo ts.
    export class HomePage {
  entry = {};

  constructor(
    public navCtrl: NavController,
    public brMaskerIonic3: BrMaskerIonic3,
    public database: DatabaseProvider,
    public account: AccountProvider,
    public entrydao: EntryDaoProvider
    ) { }

  entryReport() {
    console.log('Enviando dados...');
    console.log(JSON.stringify(this.entry));
    this.insertDB();
    this.navCtrl.push(ReportPage, { nome: this.entry['name'] });
  }

  insertDB() {
    const name = this.entry['name'];

    this.account
      .addEntry(name)
        .then(() => console.log('registro inserido'));
  }

}

segue BD.
import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';

@Injectable()
export class DatabaseProvider {
  private dbConection: SQLiteObject;

  constructor(public sqlite: SQLite) {
    this.initDB();
  }

  get db(): SQLiteObject{
    return this.dbConection;
  }

  private initDB() {
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    })
    .then((db:SQLiteObject) => {
      this.dbConection = db;

      //this.dropTables();
      this.createTables();
      this.insertBD(db);
    })
    .catch(e => console.error('error on load db', JSON.stringify(e)));
  }

  private createTables() {
    console.log('creatins tables...');

    this.dbConection.sqlBatch([
      "CREATE TABLE IF NOT EXISTS pesquisa( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);"
    ])
    .then(() => console.log('tables created successfully'))
    .catch(e => console.error('error on creating tables', JSON.stringify(e)));
  }

  insertBD(db: SQLiteObject) {
    db.executeSql('SELECT COUNT(id) as qtd from pesquisa', [])
      .then((data: any) => {

        if (data.rows.item(0).qtd == 0) {
          db.sqlBatch([
            ['INSERT INTO pesquisa (name) VALUES (?)']
          ])
            .then(() => console.log('Dados pesquisa incluídos com sucesso!'))
            .catch(e => console.error('Erro ao incluir os dados default', e));
        }
      })
      .catch(e => console.error('Erro ao consultar a qtd em pesquisa', JSON.stringify(e)));
  }

  private dropTables() {
    console.log('dropinng tables...');

    this.dbConection.sqlBatch([
      ["DROP TABLE pesquisa"]
    ])
    .then(() => console.log('tables droped successfully'))
    .catch(e => console.error('error on drop tables', JSON.stringify(e)));
  }

}

segue a nova pagina .ts.
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { EntryDaoProvider } from '../../providers/entry-dao/entry-dao';
import { DatabaseProvider } from '../../providers/database/database';

@IonicPage()
@Component({
  selector: 'page-report',
  templateUrl: 'report.html',
})
export class ReportPage {

  nome;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public entrydao: EntryDaoProvider,
    public database: DatabaseProvider) {

      this.nome = navParams.get('name');
  }

}

Quero exibir na pagina html oinput que foi salvo no banco de dados na coluna name.
Answer: coloca no seu HTML tipo assim:
    <ion-content>
       {{nome}}
    </ion-content>

o uso do bind do angular com a interpolação faz com que sua variavel nome esteja ligada a this.nome


Carrinho com opcionais dinamicos com Angularjs

Question: Pessoal estou com o seguinte problema: como subtrair 2 arrays com angularjs.
Já tentei de varias maneiras e não consegui fazer essa subtração.
Estou criando um carrinho de produtos com opcional dinâmico em angularjs
nesse caso o cliente fez a seguinte modificação:
incremento o id 1004, 1000 decremento o id 1001 adicionou o id 1002
receita original:
<code>[{"id":1004,"idproduto":3,"forma":"Alface","preco":1,"quantidade":1},{"id":1000,"idproduto":3,"forma":"Bacon","preco":2,"quantidade":1},{"id":1001,"idproduto":3,"forma":"Queijo Cheedar","preco":2,"quantidade":3}]
</code>
receita modificada:
<code>[{"id":1004,"idproduto":3,"forma":"Alface","preco":1,"quantidade":2},{"id":1000,"idproduto":3,"forma":"Bacon","preco":2,"quantidade":2},{"id":1001,"idproduto":3,"forma":"Queijo Cheedar","preco":2,"quantidade":1},{"id":1002,"idproduto":2,"forma":"Bacon","preco":2,"quantidade":1}]
</code>
Estou precisando que reformule esse array pois preciso mostrar as alterações no carrinho de compras para o cliente.
Produto 500
+1 1004 (R$1,00)
+1 1000 (R$2,00)
+1 1002 (R$2,00)
-2 1001 (R$4,00)
Receita final para o carrinho
<code>[{"id":1004,"idproduto":3,"forma":"Alface","preco":1,"quantidade":1},{"id":1000,"idproduto":3,"forma":"Bacon","preco":2,"quantidade":1},{"id":1001,"idproduto":3,"forma":"Queijo Cheedar","preco":2,"quantidade":-2},{"id":1002,"idproduto":2,"forma":"Bacon","preco":2,"quantidade":1}]
</code>
E no final teria que somar o array original com o final para dar baixa no estoque.
Estou correto nessa logica?
Answer: O nome desta operação é diff, e você quer obter o delta (diferença) entre as duas coleções.
Existe uma library chamada jsondiffpatch (link) que pode ser útil pra você. A saída é o delta (diferença) entre duas fontes.
O exemplo acima resulta no seguinte delta de acordo com esta library:
<code>{
  "2": {
    "quantidade": [
      3,
      -2
    ]
  },
  "3": [
    {
      "id": 1002,
      "idproduto": 2,
      "forma": "Bacon",
      "preco": 2,
      "quantidade": 1
    }
  ],
  "_t": "a"
}
</code>
Comment: blz vou testar, mas de qualquer forma brigado!
Comment: pow meio que nao funcionou do jeito que imaginava... teste com o demo e foi o mesmo exemplo seu... fico faltando muitos dados... o jeito certo nao seria o array da receita final nao?
Comment: @Willian o objetivo da operação é expor a diferença; você pode combinar o resultado com seu array original da maneira como desejar.
Comment: então consegui implementar agora me da uma dica ai como fazer virar um array = o da receita final
Comment: pow @OnoSendai tava pensando sobre esse assunto axo que nos array[2] precisava de uma referencia pra saber de qual item se trata a modificação... o como puxaria o resto dos itens que são adicional igual o bacon?


geometric description of subsets that form bases in $\mathbb R^2$ and $\mathbb R^3$

Question: How do you give a geometric description of the subsets of $B$ in $\mathbb R^2$ and $\mathbb R^3$ that form bases?  would the bases of the space have the same number of points.  I'm having difficulty understanding bases and forming them.
Comment: Do you know what a basis is?
Comment: @crf - I know that if the subset is linearly independent and it spans the linear space then its a basis.  But I'm still shaky on determining if it spans.
Answer: Hint for part 1. A basis of a $k$-dimensional vector space $V$ is a set of vectors $B=\{\mathbf{v}_1,\dots,\mathbf{v}_k\}$ such that you can write any $\mathbf{v}\in V$ as a linear combination of vectors in $B$. Can you think of a simple, obvious example of such a set of vectors for $\mathbb{R}^2$? What would be a geometric description of that set? Can you generalize from that?
As for the second part, I'm not sure what you mean... Are you asking if the bases contain the same number of vectors?
Comment: The problem literally asks " Do all bases for one of these spaces have the same number of points?
Comment: @CassandraFairWilliams Ah okay, it means the same number of elements. So the question is: if $B_1=\{\mathbf{u}_1,\dots\mathbf{u}_j\}$ and $B_2=\{\mathbf{v}_1,\dots\mathbf{v}_k\}$ are both bases for the same space, then is it necessarily true $j=k$? Do you have any intuition about what the answer might be?
Answer: Let $V$ be a linear space (aka vector space).  Then a basis for $V$ is a subset of points $\{v_i\}_{i \in I}$, such that each vector in $V$ can be written in one and only one way as a finite linear combination of vectors from $\{v_i\}$.
As for a geometric description in $\mathbb{R}^3$ all bases have $3$ elements, so basically think of a set of $3$ vectors.  To form a basis for $\mathbb{R}^3$, the vectors need to form edges of a parallelopiped (geometric shape) with one corner at the origin, that has nonzero volume.
Now prove all the above.
Answer: A subset $B$ of ${\mathbb R}^2$ is a basis if it consists of exactly 2 (non-zero) vectors that are not colinear, i.e., that are not both on the same line.
A subset $B$ of ${\mathbb R}^3$ is a basis if it consists of exactly 3 (non-zero) vectors that are not coplanar, i.e., that are not all three on the same plane.


Should an entity access the Service Layer and execute Update/Save methods?

Question: My application requirements: if any property is changed by the user - like entering data into a textbox and then leaving the textbox - it must be updated immediately to the database.
I using WPF with MVVM design pattern. All my entities implement INotifyPropertyChanged.
If any property of a CUSTOMER changes I do
Customer.cs

customerService.UpdateCustomer(this);

Should an entity really update itself? Or induce its own update into the database?
I mean how else could I do an immediate upate of a property if not within the entity ?
Answer: An entity should not update itself; another service (repository) should do that.
You can induce the repository that the entity should be updated, by subscribing to the PropertyChanged event of the entity.
In the eventhandler, you can make sure that your entity is updated:
Customer c = new Customer();

c.PropertyChanged += (s, e) => customerService.UpdateCustomer(c);

But, on a sidenote, I think it is a strange requirement that your entity should be changed whenever a property changes.
This means that transactions are quite useless.  I mean, you have no real 'unit of work', where all changes should be committed, or should not be persisted at all ?
Next to that, it also results in lots of roundtrips to the database.
Comment: Yes I know your concern Frederik. But they do not count for my requirements. In my application I do not want to remind/force the user to press a save button to have its changes saved. Therefore on every LostFocus of a Textbox a PropChange is fired and so the service is called. Btw. you said an entity should ot update itself... another service... thats exactly what I wrote. I just did not write c.PropertyChanged += etc... so we both came to the same conclusion.
Comment: In a former code I did this:  this.PropertyChanged += (o, e) =>
            {
                switch (e.PropertyName)
                {
                    case "Homework": _lpRepo.UpdateHomeWork(PeriodNumber, LessonDayDate, Homework); break;
                    case "Content": _lpRepo.UpdateContent(PeriodNumber, LessonDayDate, Content); break;
                }
            }; Homework or Content property can be long RTF-String which needs its time so save therefore I have 2 extra Update methods on the period...
Comment: Just imagine this scenario: my app has 8 modules in each the user can add/del objects or change properties. Now there is a save button the user should press: Now I must find out which objects got removed/added/change. The same when he wants to close the app so I can popup a last messagebox:"You have change data , do you want to save?" just like in word. But Word has just a document. I have 8 "documents" much more complicated. So my requriement is fine do you agree? ;-) btw. I use sqlite with STApplication. I do not care for roundtrips.


vb.net get the *values* of the first and last lines of an array

Question: I have an array of numbers like this:
{10 20 30 40 50 60 70 80 90}

The start and end numbers will not always be the same (in fact none of them will).
I want to get the value (not the index) of the first and last entries.
So in the above example, all I'm interested in getting are the values "10" and "90".
This array is being constructed from a comma delimited text file which looks like this:
10,3.456
20,3.588
30,3.640
40,3.790
50,3.850
60,3.680
70,3.480
80,3.280
90,3.765

This is my code:
    Dim arrName, arrValue As New List(Of String)()
    Dim sdata() As String
    Dim column1, column2 As Decimal

For Each line As String In IO.File.ReadAllLines("c:\file.txt")
    If line <> "" And Not line.StartsWith("#") Then
        sdata = line.Split(","c)
        arrName.Add(sdata(0).Trim())
        arrValue.Add(sdata(1).Trim())
        ' get data from array
        column1 = sdata(0)
        column2 = sdata(1)
End If
Next

So what I want is to be able to create two variables where:
column1Lowest=<the lowest value> (in this case 10)
column1Highest=<the highest value> (in this case 90)

I have tried several method, but all I seem to be getting back is the entire array each time, or "-1" (no match found in array I know).
Things I have tried: IndexOf(), FirstIndexOf(),LastIndexOf()
I am only interested in the lowest an highest values in column1 (but I still use the rest elsewhere).
I am now out of ideas.
Please help - with answers in the form that a novice can understand.
Thanks.
EDIT:
To add to Steve's answer below, I tried the Inumerable strings option but I believe I was running into issues with my file format - some files were fine - some were not (usually files without a line feed after the last line of data!).
This is my code:
Dim Lines As Collections.Generic.IEnumerable(Of String) = File.ReadLines("c:\file.txt").Where(Function(q) q.StartsWith("#") = False)
        Line0 = Lines.FirstOrDefault
        LineN = Lines.LastOrDefault
       lowestNum = Line0.Split(New Char() {","c})
        highestNum = LineN.Split(New Char() {","c})
        lowNum = lowestNum(0)
        highNum = highestNum(0)

etc..
So if I wanted to use this chunk of code on my already parsed file - how would I use the existing array with it?
I have just tried:
Dim Lines As Collections.Generic.IEnumerable(Of String) = {column1}
                FirstValue = Lines.FirstOrDefault
                LastValue = Lines.LastOrDefault

But this still prints the entire array?
To display the output I'm using:
    ListBox2.Items.Add(FirstValue)
    ListBox1.Items.Add(LastValue)

I've tried inserting the listbox code both in and outside of the "For Each" loop. Putting them outside gives me variable issues - so I tried to declare the variables outside of the loop to no avail.
I did say I was a novice!
Answer: There are these pretty IEnumerable extensions that you can use
Dim first = numbers.First()
Dim last = numbers.Last()

However from your question is not clear if you want just the first and last element of the array or the highest and lowest value in the array.
For the second case you have
Dim high = numbers.Max()
Dim low = numbers.Min()

I have also noticed that you use strings to manage these values, but if they are numbers and you want to retrieve the highest and lowest numbers then you should absolutely convert these values to integers otherwise you will have a difficult time to explain to your computer that a string "100" is higher than a string "20".
EDIT
Loop over your lines and convert every line to a decimal then get the min and max
(Note, no check on the correctness of the input)
Dim names = new List(Of Decimal)()
Dim values = new List(Of Decimal)()
For Each line As String In IO.File.ReadAllLines("c:\file.txt")
    If line <> "" And Not line.StartsWith("#") Then
        sdata = line.Split(","c)
        names.Add(Convert.ToDecimal(sdata(0).Trim()))
        values.Add(Convert.ToDecimal(sdata(1).Trim()))
    End If
Next
Dim lowValue = names.Min()
Dim highValue = names.Max()

Comment: Steve, that's perfect thank you. I had to switch values <> names and correct a typo or two!! But I guess you were just testing me :-)
Comment: I was using this already, but I ran into issues when reading files. So I tried to incorporate it into my loop above without success. I have edit my original question to illustrate this.
Answer: The first element in a list or array always has index 0 and the last element always List.Count - 1 or Array.Length - 1 depending on whether you use an array or a list. So you get the first and the last value from your array using:
arrayLowest = arrayVariable(0)
arrayHighest = arrayVariable(arrayVariable.Length - 1)
listLowest = listVariable(0)
listHighest = listVariable(listVariable.Count - 1)

The other methods you mention (IndexOf(), FirstIndexOf(), LastIndexOf()) are used to find the index of a given element. For example if you wanted to know at which position the element 90 is in the list/array, you'd use these.
Please note that an array or list are not sorted by default, so if you want to get the minimum and maximum values from your array or list you need to either use the extensions Steve mentioned, or sort the list/array and then get the first and last value, or loop over the list/array and perform comparisons.
Answer: Try this to get the first and last values:
Dim FirstValue As String = sdata(0)
Dim LastValue As String = sdata(sdata.Length - 1)

Comment: @OSKM : However `UBound()` is an outdated function which only exists for backwards compability. navigator's solution is the current .NET solution.
Comment: You can also use `Dim LastValue As String = sdata(Ubound(sdata))`
Answer: First make sure that you only try to access the elements if the array has a size > 0, then access the first and last element like this:
Dim lowest, highest As String;
If arrValues.Length > 0 Then
  lowest = arrValues(0);
  highest = arrValues(arrValues.Length - 1);
End If

Array.Length returns the number of elements, as elements are indexed starting from 0, the last element will be Length - 1.


Tensor product equivalent definitions

Question: I'm studying tensor products right now and I've came across multiple definitions. The one I'm confused with is when we have vector spaces $V$ and $W$ and we define the tensor product as the quotient of the free module $F$ of $V \times W$ and $E$, where $E$ can either be:
Definition 1:
$E$ is the subspace of $F$ spanned by all elements:
$$(v_1+v_2,w)-(v_1,w)-(v_2,w)$$
$$(v,w_1+w_2)-(v,w_1)-(v,w_2)$$
$$a(v,w)-(av,w)$$
$$a(v,w)-(v,aw)$$
or
definition 2:
$E$ is the subspace of $F$ spanned by all elements:
$$(v_1+v_2,w)-(v_1,w)-(v_2,w)$$
$$(v,w_1+w_2)-(v,w_1)-(v,w_2)$$
$$(av,w)-(v,aw)$$
Are these definitions equivalent?
(namely, what I'm asking is, does:
$(al_1 \otimes l_2) = (l_1 \otimes al_2), = a(l_1 \otimes l_2)$ hold in definition 2)?
Thanks very much
Answer: None of these is a definition. The correct definition of the tensor product is the universal property: the tensor product classifies bilinear maps. Your "definitions" are actually constructions (but there are also other constructions of the tensor product; of course isomorphic). Now to answer your question: The first construction is the correct one, the second is not correct. If $\beta : V \times W \to U$ is a map which is additive in each variable and balanced in the sense that $\beta(av,w)=\beta(v,aw)$ for $a \in K$, $v \in V$ and $w \in W$, then there is no reason why we can conclude $a \beta(v,w) = \beta(a v,w)$. Try to find an example for $V=W=U=K=\mathbb{C}$.
Comment: Actually the second construction is the correct one in the context of noncommutative rings and bimodules. If someone is interested, the Wikipedia article on tensor products explains this.
Comment: I just read the wiki article. Would you care elaborating?

The problem I'm having is that, this the 2nd definition, nothing ever "goes outside" the tensor product. So is the basis the tensors of all the basis of V and W? What if you have the 2nd definition but the underlying ring is commutative anyway? etc
Comment: I don't understand the question. You can find everything in the Wikipedia article, and my answer also gives a hint how to find the difference between the two constructions.
Comment: Thanks for your help with this. The issue I am having is that some notions of the two constructions seem too different. For example the proof (at least the one I've seen) that if $v_1,v_2...$ is a basis for V and $w_1,w_2,...$ is a basis for $W$ then the tensors $v_iw_j$ are a basis for the tensor product seem to not work (namely we can't express any tensor in terms of linear combinations of the $(v_i \otimes w_j)$ because nothing "goes outside" the tensors as in definition 1)? If not, can you direct me to a proof?

Tensor product equivalent definitions


How to prevent performance issues when checking a large list of nodes using Rules?

Question: Please, advice me on such a question about the Rules module.
Background: I have two types of users and 2 types on content. Each user can create one type of content. User of type2 can create a content of content_type_2 which has an entity reference field to a node of content_type_1. But this user should have a limit - such user may reference a node of content_type_1 only once.
How I implemented it:

rule is triggered when user_type2 is visiting content_type_2 node-add form. A NID of reference to content_type_1 is present as URL parameter.
rule fetches nodes by property (where author is current user)
for each item of the list of fetched entities is triggered another
one rules component
component checks is current list item is of "content_type_2"
component checks current list item's entity reference field (nid of
the referenced node) is equal to the nid value from URL parameter.
if both conditions are true - prevent node saving and display and
error message.

It works fine and does it's job. But I worry about the following: what will happened if a user of user_type2 already has let say 10000+ of nodes of content_type_2? Does it mean that "fetch entity by property" will query for all that number of nodes at once? Can it highly slow down my site performance?
If it is true, maybe there is a better way of organizing this checking process?
Will be thankful for any comment and advice!
UPD 1 (to make the question more clear):

User type "Client" can create nodes of type "Request" .
User type "Provider" can create nodes of type "Proposal".
"Proposal" type has entity reference field to "Request" node (only 1 value allowed, it is required).
Provider can create multiple number of "Proposal" nodes.
But he has to be restricted to create only 1 "Proposal" per a certain "Request" node. So he should not be allowed to reference a "Request" node if he has already referenced it in any of his previous Proposals.
Reference field is filled automatically ("Provider" can't do it by hands). "Provider" also can't edit any of published Proposals, but can delete any of them.

UPD 2 (Rules export)
Reaction Rule which is triggered at "node/add/proposal"
{ "rules_check_unique" : {
    "LABEL" : "Check Proposal is unique per Request",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "business_custom" ],
    "REQUIRES" : [ "rules", "rules_url_argument" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node\/add\/proposal" } },
      { "rules_url_argument_argument_exists" : { "argument" : "field_request_reference" } }
    ],
    "DO" : [
      { "rules_url_argument_rules_action_get_argument_from_url" : {
          "USING" : { "type" : "integer", "argument_name" : "field_request_reference" },
          "PROVIDE" : { "argument_from_url" : { "argument_from_url" : "Argument from URL" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "author",
            "value" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_if_proposal_is_already_posted_for_a_request" : { "cnid" : [ "argument-from-url" ], "proposal" : [ "list-item" ] } }
          ]
        }
      }
    ]
  }
}

Component Rules which check if Proposal for the referenced Request already exists
{ "rules_if_proposal_is_already_posted_for_a_request" : {
    "LABEL" : "If proposal is already posted for a request",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "cnid" : { "label" : "Current NID", "type" : "integer" },
      "proposal" : { "label" : "Proposal", "type" : "node" }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "proposal" ],
          "type" : { "value" : { "proposal" : "proposal" } }
        }
      },
      { "data_is" : { "data" : [ "proposal:field-request-reference:nid" ], "value" : [ "cnid" ] } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "You have already made a proposal for this request.",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "node\/[cnid:value]" } }
    ]
  }
}

Answer: Preface
Even though I didn't test it, I trust your rule (+ Rules Component) works. But, you really made it complicated. Moreover, it seems that your rule is using Rules Event "Drupal is initializing". You're right, you must use this event if you want to have Rules intercept something like "a node is going to be added". Because if you'd use something like "before saving content of type ABC", you wouldn't be able to STOP such saving (you would be too late).
But using that Rules Event also implies that this rule gets triggered for every (repeat every) page load on your site, and each time at least the Rules Condition to check for that node/add/proposal path has to be performed. So only because of using that Rules Event, I think you should try to go for an alternative implementation to achieve the same goal. That goal is, if I correctly interpreted your question, like so: A Provider can only reference a "Request" node in a single "Proposal".
Read on for a blueprint with some more details about how I would implement this ... (BTW: in D7).
Step 1: Flag a Request after a Proposal was submitted
Use the Flag module to create a (non-global) flag to be used for flagging a node of type "Request", so that whenever a Provider submits a proposal, the referenced Request gets flagged by that Provider. So the flag is to indicated that such provider did submit a Proposal to the specific Request.
To actually do so, simply use the Rules module to do so (this is a kind of getting started with Rules, not further explained in this answer).
Step 2: Create a view with an Entity Reference display
Create a view (with the Views module) to create a list of all the Requests that are allowed to be selected by a specific user. Some more details (specs) about the view to be created:

The display type of such view must be an Entity Reference display.
It should list all nodes of content type "Request".
It should have a filter like "Not flagged (with the flag from Step 1) by the current user".

Step 3: Adapt your Entity Reference field
Your entity reference field (to select from a filtered list of Requests) should be field that looks like so:

Field Name = Anything you want, eg field_requests_list.
Field Type = Entity Reference, using these additional settings for it:

Target type = node.
Number of values = 1.
"Mode" (within "entity selection") = Views: Filter by an entity reference view. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an Entity Reference display, or add such a display to an existing view. In your case, you should select the view created in "Step 2".
Pick any of the other options to define this field as you see fit.

Step 4: Disable your custom rule
After you completed the previous steps, there is no more need for your custom rule "Check Proposal is unique per Request", so at least disable that rule (and optionally just delete it). If this was the only Rule using your Rules Component, you might also want to delete that Rules Component (not needed anymore either).
Step 5: Reduce the risk to run in a new (Views) performance issue
You have a valid point in the extra comment you posted below this answer, ie:

If I have over 10000 nodes of type "Request" on the website which are not flagged by the current Provider, the view will query for all that number of stuff as I understand. Doesn't it influence the performance as well?

I don't expect such performance issue for as long as you have only like a few hundreds of nodes of type "Request". But for 10.000 nodes I'm not sure. However, if you also want to take away that risk, you could improve the above solution a bit further like so:

Introduce an additional (non-global) flag, which a "Provider" must use to indicated something like "I am interested in preparing a proposal for this request".
Improve the view in Step 2, by adding this additional flag as an additional filter of that view.

Obviously, the downside of introducing this extra flag is that the Provider must first "flag" relevant Requests. But the benefit of doing (enforcing?) so is that the number of results in your view will probably be limited to only a few (or a few dozens at max).
Bottomline
After you completed the previous steps, you will:

No longer use that Rule (+ related component) for which you wondered about its performance.
You will have relevant business logic in place so that a Provider can only reference a "Request" node in a single "Proposal" (which IMO is what you're trying to implement).

Homework
The above is just a blueprint, you may want to further refine it. E.g. what if some smart Provider tries to "unflag" a Request that the Provider (automatically) flagged before (via Step 1)? If that happens, such Provider could submit another proposal to the same Request (which is not what you'd want). Hint: intercept that event also, and don't allow that to happen ... also using ... euh ... Rules!
Comment: Many thanks for your solution! Actually I have a question Step 2 - if I have over 10000 nodes of type "Request" on the website which are not flagged by the current Provider, the view will query for all that number of stuff as I understand. Doesn't it infuelce the performance as well?
Comment: @john ... Solution to the problem, changes the problem, right? Check my expanded answer (= my addition in "Step 5").
Comment: @john : merci for the accept!
Answer:
let say 10000+ of nodes of content_type_2? Does it mean that "fetch
  enitity by property" will query for all that number of nodes at once?
  Can it highly slow down my site perfomance?

I think you answered your own question,

rule fetches nodes by property (where author is current user)
for each item of the list of fetched entities is triggered another one rules component

Haha yea, not a good approach. A better approach:
Use the flag module and create flag for the Request nodes.
Use Rules Conditional
Then in rules, when Proposal is created >> component of request node (loaded using the Reference NID), if flagged is unflaged, flag. Else prevent node from saving and show error message.
When Proposal node is deleted >> component of request node (loaded using the Reference NID), unflag if it's flagged.
Comment: How about using the Flag module to flag such node for which you suggest storing its nid? Do you think that might be a valid alternative also? As you must know, checking if a node is yes/no flagged in Rules is a piece of cake, no?
Comment: @Pierre.Vriens interesting idea, but the flag would have to be universal. So how would you deal with removing the 1 reference on node x?
Comment: not sure if it would make sense to you, but wouldn't "unflag" that node be the equivalent of that? disclaimer: I'm still confused about the actual question here, so sorry if this makes no sense.
Comment: @Pierre.Vriens yes "unflag" would do, but what would be the check before that? If entity reference field is empty? but what about all the other nodes that will be created with an empty reference, since only 1 node is allowed to have it? They would trigger the unflag, causing a false positive.
Comment: Good (extra) question ... not sure about how to answer that. Except: if entity ref field is empty, that's because the user deleted the reference (= your words in your own answer). But "user deletes the reference" appears to me like something you should be able to capture as a rules event, via which maybe you could make other rules logic happen? Sorry, I'm only a kind of guessing here (need more time to digest the original question here, after OPer addresses my original comment also). Au revoir!
Comment: @Pierre.Vriens, I was approaching it as if, user can keep adding more nodes (with empty references) if he/she already used up their 1 reference.  hmm, your comment made me re-read the question `Each user can create one type of content.` which makes me think now that user is allowed to create only 1 node of type x? hmm or is my original thought correct, they can create any amount of nodes of type x, but only 1 of them can have a reference.
Comment: @Pierre.Vriens, No Sssweat thanks a lot for your comments. Please see the updated question - hope it will make it more clear. Thanks!
Comment: @Pierre.Vriens, about "Drupal is initializing" - my initial idea was to prevent user from posting at once he reaches "node/add/proposal" path (just not to make him fill the form which can't be published). As well as the rule actions should be stopped by "IF" conditions, I thought it should not make a big impact to performance. But I'd like to switch to anything different from "Drupal is initializing" if it can fire once visiting "node/add/proposal".
Comment: Voilà, I'm done ... curious about your feedback now (also from @john of course) ...


Area of plane $2x+y+2z=2$ in the cylinder $x^2+y^2=16$

Question: Area of plane $2x+y+2z=16$ in the cylinder $x^2+y^2=16$ I'm having trouble making sure I'm getting the correct answer so I'll walk through it and hopefully someone can point out if it is correct.
$$2x+y+2z=16 \rightarrow z=8-x-{y\over2}$$
$$A(s)={\int \int}_D \sqrt{1+({\partial z\over \partial x})^2+({\partial z\over \partial y})^2}={\int \int}_D \sqrt{9\over4}dA={3\over2}{\int \int}_DdA$$
Then I transform into cylindrical:
$${3\over2} { {\int_0^{2\pi}} {\int_0^4} rdrd\theta}=24\pi$$
I think the biggest problem I'm having justifying this is that I'm not sure I can go to cylindrical cordanites where I did, is that valid? Is the answer correct?
Thanks for any help!
Comment: Why even go to polar? It's just the area of a circle.
Comment: @ZacharySelk $A={\pi}r^2=16{\pi}$ Is the answer? I don't quite understand how it's just the area of a circle. When the plane cuts the cylinder flat, but then at a steeper angle won't there be more area in the steeper angle cut?
Comment: You're not integrating over the circle floating above, but the shadow in the XY plane which is just a plane (get it?) ol circle.
Comment: @ZacharySelk How would you do this using calculus though? is there a way?
Comment: Just like you did.
Comment: @ZacharySelk ? I have two different answers then: $16{\pi}$ and $24{\pi}$
Comment: Well $16\pi \times 3/2$ is your answer.
Answer: Your $dS$ is a constant so your integral is simply the area of the circle time $dS$
$$A= \int \int _D dS = \int \int _D 3/2 dA = 3/2(16\pi ) = 24\pi $$


Number of integral coordinates in a given region.

Question: The number of points, having both coordinates as integers, that lie in the interior of the triangle with
vertices $(0,0) ,(0, 41$) and $(41,0)$ , is:
(1) 901   (2) 861   (3) 820   (4) 780.
I tried to find out the number of points manually, but it didn't look like the optimal method.
Thanks in advance.
Answer: Manually seems fine to me. First draw the triangle.
Consider the integral points on the line $x=1$. The point on the hypotenuse is $(1,40)$. The number of points inside the triangle are $39$, that is, $\{1,2\dots,39\}$.
Similarly number of integral points on $x=2$ are $38$, that is $\{1,2,\dots,38\}$.
So basically you have to sum up $39+38+\dots+1 = \frac{40.39}{2}=780.$
Answer: The problem can be approached by finding the area of the triangle in two ways:
First, as $\displaystyle A = \frac{1}{2}(41^2) = \frac{1681}{2}$
Second, by an application of Pick's theorem $\displaystyle A = i + \frac{b}{2} - 1$
Now boundary points $b$ can be calculated by considering that there is a single origin point $(0,0)$ common to both cathetuses, $40$ points unique to each of the two cathetuses, and $42$ points along the hypotenuse (inclusive of the end points where it intersects with the cathetuses).
So $\displaystyle b = 1+ 2(40)+42 = 123$, giving $\displaystyle A = i + \frac{121}{2}$
Equating the two expressions for $A$, we get the number of interior points $i = 780$.