mercredi 31 janvier 2018

how to use isin with elif statements [duplicate]

This question already has an answer here:

I have a column(INT_STATUS) in a data frame(file1) and INT_STATUS has values from A to Z and 1 to 9. If INT_STATUS columns has values in this list ['B','C','F','H','P','R','T','X','Z','8','9'] then I want to create a new column "rcut" and give a value '01' file1['rcut'] == '01'.

 file1=pd.read_csv(os.path.join("rtl_one", sep="\x01")


def risk_pass():
    if file1['INT_STATUS'].isin(['B','C','F','H','P','R','T','X','Z','8','9']):
        file1['rcut'] = '01'
    elif file1['BLOCK_CODE_1'].isin(['A','B','C','D','E','F','G','I','J','K','L','M', 'N','O','P','R','U','W','Y','Z']):
        file1['rcut'] = '02' 
    elif file1["BLOCK_CODE_2"].isin(['A','B','C','D','E','F','G','I','J','K','L','M', 'N','O','P','R','U','W','Y','Z']):
        file1['rcut'] == '03'

    else:
        file1['rcut'] = '00'

risk_pass()

But when I executing the above code I'm getting the following error. Please help

    sys:1: DtypeWarning: Columns (9,21,46,47,52,56) have mixed types. Specify dtype option on import or set low_memory=False.
Traceback (most recent call last):
  File "views.py", line 52, in <module>
    risk_pass()
  File "views.py", line 45, in risk_pass
    if file1['INT_STATUS'].isin(['B','C','F','H','P','R','T','X','Z','8','9']):
  File "/opt/anaconda3-4.4.0/lib/python3.6/site-packages/pandas/core/generic.py", line 953, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How to use pandas isin() with IF statement

I have a column(INT_STATUS) in a data frame(file1) and INT_STATUS has values from A to Z and 1 to 9. If INT_STATUS columns has values in this list ['B','C','F','H','P','R','T','X','Z','8','9'] then I want to create a new column "rcut" and give a value '01' file1['rcut'] == '01'.

 file1=pd.read_csv(os.path.join("rtl_one", sep="\x01")


def risk_pass():
    if file1[file1['INT_STATUS'].isin(['B','C','F','H','P','R','T','X','Z','8','9'])]:
        file1['rcut'] = '01'

    else:
        file1['rcut'] = '00'

risk_pass()

But when I executing the above code I'm getting the following error. Please help

    sys:1: DtypeWarning: Columns (9,21,46,47,52,56) have mixed types. Specify dtype option on import or set low_memory=False.
Traceback (most recent call last):
  File "views.py", line 52, in <module>
    risk_pass()
  File "views.py", line 45, in risk_pass
    if file1[file1['INT_STATUS'].isin(['B','C','F','H','P','R','T','X','Z','8','9'])]:
  File "/opt/anaconda3-4.4.0/lib/python3.6/site-packages/pandas/core/generic.py", line 953, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

If statement isn't being caught

I can't for the life of me figure out why C is ignoring my if statement.

I'm trying to skip all the procedures in the while statement when the input is -1000 (so that it doesn't print before exiting the program). Here is my code:

int main()
{
  int count = 1;
  int grade1;
  int grade2;
  double sum;
  double average;

  printf("Please input a number of grades: \n");

  scanf("%d", &grade1);
  printf("Sum is: %d.000000 \n", grade1);
  printf("Average is: %d.000000 \n", grade1);
  count++;

  sum = grade1;

  while(grade2 != -1000) 
  {
    if(grade2 != -1000)
    {
      scanf("%d", &grade2);

      sum = sum + grade2;
      average = sum / count;

      printf("Sum is: %lf \n", sum);
      printf("Average is: %lf \n", average);

      grade1 = sum; //Converting the sum back into an int
      count++;
    }
  }
  return 0;
}

enter image description here

Here is a link to an image of my output. As you can see, even when grade2 is given -1000, the if statement is ignored, and another 2 lines are printed to the screen before the program exits. How can I fix this? Is this some sort of oddity of how C works?

Min If with Excel VBA

I am trying to understand how I can code in VBA the equivalent of an array Min If formula.

I need to find the minimum value of a column when certain conditions in other columns are met based on parameters in each row.

I was able to do so using a bracket formula in Excel, but I can't replicate it using VBA code.

What function should I use? Thanks!

How to add multiple IF statements with conditions in Excel

Any idea how should I write query in excel for my below requirement. I have 2 columns. Column A having 5 cells and Column B having 5 cells.

1) If all cells in Column A contains text = "yes" then I would like to show status "Bronze" 2)If all cells in Column A contains text = "yes" AND all cells in column B = "yes" then I would like to show status "Gold" 3)If all cells in Column A = "yes" but any of the cell in Column B <> "yes" then I would like to show status "Silver" 4) If any of the cell in column A <> "yes" irrespective of status of cells in column B then I would like to show status "Others"

I tried simulating this with 2 cells in Column A and B with below,

=IF(AND(A18="yes",A19="yes"),"Bronze",IF(AND(A18="yes",A19="yes",B18="yes",B19="yes"),"Gold",IF(AND(A18="yes",A19="yes",B18="yes",B19="yes"),"Silver","Other")))

sorry I am not familiar with excel so can anyone help please ?

Combining Excel's AND and OR within an IF statement

I'm trying to combine 'AND' and 'OR' into an IF statement which looks at two cells, and 3 'OR' criteria, but I'm not sure if it's possible. Logic below:

IF cell M2 = "P4", AND cell AB2 = "P3" OR cell AB2 = "P2" OR cell AB2 = "P1", "Elevated", "Not Elevated"

This is as far as I got with regard to an actual formula which doesn't yet incorporate the 'OR' portion:

=IF(AND(M2="P4",(AB2="P3")),"Elevated","Not Elevated")

Any advice would be greatly appreciated. Thanks in advance.

How do if/else work intermixed with switch/case interact?

In a question about switch and goto, this answer used this code to avoid using a goto altogether:

switch(color)
case YELLOW:
    if(AlsoHasCriteriaX)
case GREEN:
case RED:
case BLUE:
        Paint();
    else
default:
        Print("Ugly color, no paint.");

How does this code work? I understand that cases automatically fall through, so I don't need it explained when color is YELLOW, but what about when color is GREEN? How does C++ handle else when it never encountered if. Would this code even compile, would it be a runtime error, or would it just ignore the else?

C++ which if/else is faster

I have seen two types of if/else, which one is faster?

if(a==b) cout<<"a";
else cout<<"b";

OR

a==b ? cout<<"a" : cout<<"b";

C++ Kaprekar test loop not printing two numbers

I'm having an issue finding out why I can't get 4879 & 5292 to print without creating another else-if to pinpoint those two to divide by a higher unit. I need to not do that.

Problem: a program to test kaprekar numbers less than 10,000

Inputs: none

Outputs: kaprekar numbers

Formulas: squared number = number * number, first half = squared number/unit, second half = remainder of squared number/unit, test = first half + second half

Here's my actual code:

#include <iostream>

using namespace std;

int main()
{
//declare variables 
int num, squaredNum, firstHalf, secondHalf, unit, test;

//initialize number
num = 1;
cout << "Here are all Kaprekar numbers less than 10,000!\n";
cout << "-----------------------------------------------\n" << endl;

//while loop
while(num < 10000){
squaredNum = num * num;
if (squaredNum < 100){
    unit = 10;
}
   else if (squaredNum < 10000){
   unit = 100;
   }
     else if (squaredNum < 1000000){
     unit = 1000;
     }
        else if (squaredNum >= 1000000){
        unit = 10000;
           }
//test if both sides add up to original number                    
firstHalf = squaredNum/unit; //right side
secondHalf = squaredNum%unit; //left side
test = firstHalf + secondHalf;  

if (test == num){
cout << num << " is a Kaprekar! " << firstHalf;
cout << " + " << secondHalf << " is = " << num << endl; //outputs kaprekar number
num++; //increment number
}
num++; //increment & continue to next number
}//end while loop
return 0;
}

If someone could help me figure out where I'm having my issue, that would be great. It has something to do with the zeros when I divide, but I'm not sure what to use for that part.

Counting values in a row that match a condition - Python

I have a dataframe that contains integers and NaNs. I am almost looking to create a countif statement, which will iterate over each value in a row and count values that are greater than 0.

Here is an example df:

d = {'col1': [1, "", 5, 0], 'col2': [3, 4, "", 7], 'col3': [2, 8, "", 3]}
df = pd.DataFrame(data=d)
df = df.convert_objects(convert_numeric = True)

df
Out[356]: 
col1  col2  col3
0   1.0   3.0   2.0
1   NaN   4.0   8.0
2   5.0   NaN   NaN
3   0.0   7.0   3.0

I have been using this function below that counts values that are not NaNs, however I want to place a condition on this (greater than 0 & not NaN).

df.apply(lambda x: x.count(), axis = 1)
Out[357]: 
0    3
1    2
2    1
3    3
dtype: int64

If anyone could offer advice on how to count values in a row based on a certain condition that would be very useful, thanks in advance.

Java, the clipboard code does not work,

The program should analyze the clipboard for the presence in it of a 5-digit number starting with one. The problem is that when copying the text I do not answer if (clipboardContent.length () == 5) the program stops working.

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;

public class drob implements FlavorListener {
    private static Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    public static void main(String[] args) throws InterruptedException {
        clipboard.addFlavorListener(new drob());

 //  fall asleep for 100 seconds, otherwise the program will immediately end

        Thread.sleep(100 * 1000);
    }

    @Override
    public void flavorsChanged(FlavorEvent event) {
        try {
            String clipboardContent = (String) clipboard.getData(DataFlavor.stringFlavor);
            handleClipboardContent(clipboardContent);
        } catch (UnsupportedFlavorException | IOException e) {
            // TODO handle the error

            e.printStackTrace();
        }
    }

    private void handleClipboardContent(String clipboardContent) {
        // check if the string satisfies condition
           

 // for example, check that the length of the string is five

        if (clipboardContent.length() == 5) {
            System.out.println(clipboardContent);

        }
    }
}

If statement in PyCharm seems to be misbehaving

I'm working on a program to draw irregular polygons based on a number of sides. I don't have much so far, and I'm fairly new to this, but I'm getting a syntax error I don't understand.

Heres the code:

    sides = input("How many sides? ")
    twosides = ("""/\""")
    """
    for sides in sides:
        if sides %2 == 1
            print(twosides)

It wants me to give a [ or a

    for

statement and i dont understand why.

Any help?

How to replace a number with missing values all over the dataset?

I have written a user defined function that should get a dataset and some number of symbol, scan the entire dataset and replace all instances of this number with missing values. The code worked just fine until I put it in a user defined function (the loop and condition worked). I can't figure out why it's not working now. There are no warnings or errors, it just doesn't work. In addition, I wanted to ask if there is a way to choose which columns to do this operation on ?

My code is:

repMissing = function(ds,x)
{
  for(i in 1:nrow(ds))
  {
    for(j in 1:ncol(ds))
    {
      if (!is.na(ds[i,j]) && ds[i,j] == x)
      {
        ds[i,j] = NA
      }
    }
  }
}

and I ran the following code:

repMissing(diet2,-99)

For some reason, the -99's are still not NA's.

Any advice will be most appreciated. Thank you !

If condition using character observations

I am trying to do a simple if/else condition to either have a 1 or a -1 when R detects the word "Green" or "RED". The variable I have is called Type and it has the observations "Green" and "RED".

Here is the code I am using:

LTDWA2 <- LTDWA %>%
  if(Type == "RED") {
    Target = 1
  } else {
  Target = -1
}

The error I get is the following:

Error in if (.) Type == "RED" else { : argument is not interpretable as logical In addition: Warning message: In if (.) Type == "RED" else { : the condition has length > 1 and only the first element will be used

Can someone please help me solve this issue. Thanks.

PHP clean up code (remove duplicate lines) in if-statement with for-loop

I have an example code, where $number is sometimes set and sometimes not:

//$number = 1;
$maxnumber = 3;
  if (isset($number)){
   echo $number;
} else {
  for ($number = 1; $number<=($maxnumber); $number++) {
   echo $number;
  }
}

As you can see I have a double echo: "echo $number;" now it's only 1 line, but in my real code I have 35 of duplicate lines. So when I change the code I need to change it in two places.

Is there a way (in this example) to get rid of the double "echo $number;", by changing the way I do the for loop or something?

False output of if-statement

I'm trying do check a char array if it's a palindrom.

This code works when my parameter consist of an even number of characters. If not it won't work.

E.g. "ana"

public boolean palindromTest(char[] test) {
    for (int i = 0; i<test.length-i-2;i++) {
        if (test[i] != test[test.length-i-1])
            return false;
    }
    return true;
}

R How to select (and do calculations with) a row and the exact row beneath it in R

thanks in advance for helping! I'm a beginner in R so apologies in advance for any inconvenience. I tried my hardest to make it a understandable question.

My dataframe looks like this:

      var1      var2    var3
1     0         5       "other"
2     25        3       "sample"
3     4         5       "other"
4     60        5       "other"
5     4         5       "other"
6     60        5       "other"
7     25        3       "sample"
8     4         8       "other"
9     60        7       "other"
10    4         3       "other"  
11    25        27      "sample"  
12    4         9       "other"   
13    30        4       "other"   

I would like to add a column that for all rows that equal var3=="sample" gives the calculation of the value in var2 column minus the value in var 2 column of the row beneath the "sample" row. That would look like this:

      var1      var2    var3      var4
1     0         5       "other"   NA
2     25        25      "sample"  20
3     4         5       "other"   NA
4     60        5       "other"   NA
5     4         5       "other"   NA
6     60        5       "other"   NA
7     25        13      "sample"  8
8     4         5       "other"   NA
9     60        5       "other"   NA
10    4         3       "other"   NA
11    25        27      "sample"  18
12    4         9       "other"   NA
13    30        4       "other"   NA

I have tried

if(df$var3=="sample") {df$var4<-(df$var2-df$var2[+1,])}

But that obviously doesn't work. How to do a calculation with a column from a specific row and the exact row beneath it?
I'm very sorry if this is a stupid question, I really searched stack overflow for a long time but couldn't find a solution.

Somewhere my if statements mess up, and my GSA's cant gelp me

So, this is supposed to go through a file of 0's, ';'s and 1;s (all in character form originally but i set to integers), however when i run it the code counts the neighboring living cells wrong, pulling 3's in 5 spots where there should be a 2 for my neighbor count.

Current output; Neighbor square for how many neighbors each cell has (counting all 8 surrounding tiles), then the updated matrix after basic game of life operations happen, lastly the original Matrix This is the original matrix below

0;0;0;0;0;0

0;0;0;1;0;0

0;1;0;1;0;0

0;0;1;1;0;0

0;0;0;0;0;0

0;0;0;0;0;0

The rest of the process happens flawlessly, but the counting of neighbors doesn't work. What do i do wrong?

#include <stdio.h>
#include <math.h>
#include <stdlib.h>  
void manage_board(FILE *input, int counter, int iterate);
int main (int argc, const char * argv[]){
    FILE *input = fopen(argv[1],"r");
    int counter = 0,temp1=0,temp2=0;
    char temp = fgetc(input);
    while (temp != EOF){
        if (temp == '1' || temp == '0'){
        counter+=1;
        }
        temp = fgetc(input) ;
    }
    counter = sqrt(counter);
    rewind(input);
    manage_board(input,counter, atoi(argv[2]));
    fclose(input);
    return 0;
}
void manage_board(FILE *input, int counter, int iterate){
    int matrix[counter][counter];
    FILE *output = fopen("output.csv","w");
    int original[counter][counter];
    int updated[counter][counter];
    int rows = 0,cols = 0, neighbors =0;
    char temp = fgetc(input);
    /*for (int i=0; i<counter; i++){
        for (int j=0; j<counter; j++){
            updated[i][j] = 0; 
        }   
        printf ("\n");
    }*/
    while (temp != EOF){
        //printf("%c",temp);
        if (temp == '1' && temp != ';'){
            matrix[cols][rows] = 1;
            rows++;
        }
        else if (temp == '0' && temp != ';'){
            matrix[cols][rows] = 0;
            rows++;
        }
        if (rows==6){
            cols++;
            rows=0;
        }       
        temp = fgetc(input);
    }   
    for (int i=0; i<counter; i++){
        for (int j=0; j<counter; j++){
            updated[i][j] = 0;          
        }   
        //printf ("\n");
    }
    for (int i=0; i<counter; i++){
        for (int j=0; j<counter; j++){
            original[i][j] =matrix[i][j]; 
        }   
        //printf ("\n");
    }   
    for (int loops = 0; loops < iterate;loops++){
        for (int i=0; i<counter; i++){
            for (int j=0; j<counter; j++){              
                if ( i !=counter-1){ //down one
                    if(matrix[i+1][j] == 1){
                        neighbors ++;
                    }
                }
                if ( i !=0){//up one
                    if(matrix[i-1][j] == 1){
                        neighbors++;
                    }
                }
                if ( j != counter-1){//right one
                    if (matrix[i][j+1] == 1){
                    neighbors++;
                    }
                }
                if (j !=0 ){//left one
                    if (matrix[i][j-1] == 1 ){
                        neighbors++;
                    }
                }
                if (i !=counter-1 && j != counter-1){//bot right
                    if(matrix[i+1][j+1] == 1)
                        neighbors++;
                }
                if (j != counter-1 && i !=0 ){//top right
                    if(matrix[i-1][j+1] == 1){
                        neighbors++;
                    }
                }
                if (j !=0 && i !=0){//top left
                    if (matrix[i-1][j-1] == 1){
                        neighbors++;
                    }
                }
                if (i !=counter-1 && j !=0 ){//bottom left
                    if (matrix[i+1][j-1] == 1){
                        neighbors++;
                    }
                }
                ///printf("%d", matrix[i][j]);
                //printf ("%d ",neighbors);
                if (neighbors < 2 ){
                    updated[i][j]=0;
                }
                else if (neighbors == 2 && matrix[i][j] == 1)
                    updated[i][j]=1;
                else if (neighbors > 3){
                    updated[i][j]=0;
                }
                else if (neighbors = 3){
                    updated[i][j]=1;
                }
                printf("%d ",neighbors);
                neighbors = 0;
            }
            printf("\n");
        }   
        for (int i=0; i<counter; i++){
            for (int j=0; j<counter; j++){
                matrix[i][j]= updated[i][j];
                printf("%d",updated[i][j]);
                updated[i][j] = 0;
            }
            printf("\n");
        }
    }
        printf("original board\n");
        for (int i=0; i<counter; i++){
            for (int j=0; j<counter; j++){
                printf("%d", original[i][j]);
            }
            printf ("\n");
        }       
        //printf(" \nnew matrix\n\n");
/*      for (int i=0; i<counter; i++){
            for (int j=0; j<counter; j++){
                    if (updated[i][j] == 1){
                        fprintf( output, "%d %d \n", i, j);
                        //printf(updated)
                    }
            }
        }
    */  
/* A live cell with fewer than two live neighbors dies. 
A live cell with more than three live neighbors also dies. 
A live cell with exactly two or three live neighbors lives. 
A dead cell with exactly three live neighbors becomes alive.*/
}

PHP: Getting rid op duplicate variables in for loop

I have a for loop which I would only like to run in a certain condition. I now have duplicate information in my script. See below:

        if ($condition == 1){

            for ($number = 1; $number<=($total); $number++) {
            echo $number; // Gives a complete list of numbers.
            // List of queries/variables I use.
            } else {
            echo $number; // Only give one number in a certain condition.
            // List of queries/variables I use which are exactly the same.
            }
        }

How can I make this more compact and get rid of the duplicates?

Issue with Prinline [duplicate]

This question already has an answer here:

I seem to have issues with my if and else if statements, I seem to be getting errors whenever I try to run my program

They're strucutured like this:

if (Spelerle < 1){
                System.out.printline("\t Your body feels too heavy as you have sustained too much damage to continue.");
                break;}

else if(invoer.equals("2")){
            if (HPdrink > 0 )
                Spelerle += HPgenezing;
                HPdrink--;
                System.out.printline("You healed yourself for 44 HP! You now have " + Spelerle + " HP" + "\nYou now have " + HPgenezing + " left");}

This goes on for another 2 if statements and whenever I try to run it, I get

java: Cannot find symbol

symbol: method printline(java.lang.String)

location: variable out of type java.io.PrintStream

Does anyone have any clues? Thanks!

How to write a line to text file when particular condition is satisfied

I have a loop and checking one condition as follows

 while (t<len(var)):
        PR=y
        ...
        if z[t]<PR :
              pass_check=1
        else:
              pass_check=0 
      t=t+1

# check z for all samples and print the result

if pass_check==1:
print ('Test is  pass')
elif pass_check==0:
print ('Test is  fail')
else:
print ('Test is  fail')

Goal

How to write Test is pass or fail in a text file depending upon the condition if all samples are 1 or 0 respectively

Excel IF Formulae , working with Number ranges

I have a formulae I am trying to work on but it seems not to be working. I am working with number ranges

3.5 - 4 None

3.4- 3 Low

2.9 - 2 Medium

1.9 - 0 High

I have IF formulae which is suppose to give me a result based on the ranges. I cant seem to make it work

=IF(D13>3.5,"None",IF(D13<3.4,"Low",IF(D13<2.9,"Med",IF(D13<1.9,"High"))))

R: create function or loop to change values based on two (or more) conditions

As you can probably see from the age of my account, i'm new here.

I'm running into problems with creating a function or loop to replace single values in a row, based on 2 or more conditions. Here is my sample dataset:

date timeslot volume lag1 1 2018-01-17 3 553 296 2 2018-01-17 4 NA 553 3 2018-01-18 1 NA NA 4 2018-01-18 2 NA NA 5 2018-01-18 3 NA NA 6 2018-01-18 4 NA NA

types are: Date, int, num, num

i want to create a function that replaces the NA from lag1 with the average of the last 5 simmulair timeslots. This value is calculated with:

w <- as.integer(mean(tail(data$volume[data$timeslot %in% c(1)],5), na.rm =TRUE ))

if i create a if or for loop, it returns "the condition has length > 1 and only the first element will be used"

So far i can only change all the lag1 values, or non.

The function should be something like this: if lag1 == NA & timeslot ==1 then change that row' value to w

i can't seem to figure this one out. Hope you guys can point me in the right direction.

Does it make a difference between using two if's in c++

Is there any difference between

if (firstCheck())
    return;

if (secondCheck())
    return;

and

if (firstCheck() || secondCheck())
    return;

?

The focus of my question is on the runtime!

Python print results of (If ... in ....)

keyinput = input()

type(keyinput) # I type "appleandgold"

B = "appleblue"

If keyinput  in B:
    # it can check that have same word in both (apple) (i tried and it work)

 print("results of A in B")

Result should be "apple" how i print results from IF .. IN ?

i want output look like this: apple

Switch statement not working properly - Javascript

Switch statement code:

var data = "manager";

 switch (data) {
  case "manager" :
  function test(){
     console.log('manager');
  }
  test();
  break; 

  case "worker" :
  function test(){
    console.log('worker');
  }
  test();
  break;

  default:
   console.log('default');
} //output showing as 'worker' but expected output  // 'manager'

but if i try this using if conditions,it will worked correctly.

If statement code:

var data = "manager";

 if (data == "manager") {
  function test(){
     console.log('manager');
  }
  test();
 } else if(data == "worker"){
   function test(){
    console.log('worker');
  }
  test();
 } else {
      console.log('default');
 } // got correct output as 'manager'

What's wrong with switch statement? is switch working as async?

mardi 30 janvier 2018

Create a computer system which mimics the functionality of lottery?

I’m a beginner in programming and started in python language. I need some help to create a computer system which mimics the functionality of lottery. Each lottery draw requires six balls, numbered between 1 and 49 to be drawn, plus one “bonus ball” making a total of seven.
The balls are not replaced after each selection, so each number may only be selected once.

The following requirements specification was created for the application: - Seven random numbers should be selected – six regular numbers plus the bonus ball. - The numbers must be displayed to the user. - No randomly selected number should be repeated.

Preventing duplicate values in several combo boxes with the same datasource in C#

I have five combo boxes all populated from a string dictionary that stores the header text from a datagridview. In my program, I want a message box to pop up either immediately a duplicate value is selected or when the OK button is pressed. The code below is an if statement that only works when other combo boxes duplicate the selectedvalue in the first combo box.

Is there a shorter way than this long if statement? and I want to be able to validate every other combo box so they won't have a duplicate. P.S I want the pop up to keep coming up till a unique value is selected. cbosort1,2,3..are the combo boxes names respectively.

if (cboSort1.SelectedValue == cboSort2.SelectedValue || cboSort1.SelectedValue == cboSort3.SelectedValue || cboSort1.SelectedValue == cboSort4.SelectedValue || cboSort1.SelectedValue == cboSort5.SelectedValue)
{
  MessageBox.Show("you cannot choose a duplicate column", "duplicate error");
return;
}

How to make objects countable to get if-statements working

Data doesn't get inserted into the database because it doesn't pass the if-statements. I am currently making a form to insert polls and corresponding answers into the database. Apparently the variables in the if-statements are non-countable objects (e.g. $answers, $rows. How do I make these countable, do I have to make them arrays? Or do I have to completely change the if-statements? These statements are going wrong:
if (count($answers) <= 1)
if (count($rows) == 0)
foreach($answers as $answer)

Here is my code:

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    // get form data and escape it properly
    $poll = strip_tags($_POST["poll"]);
    $rawAnswers = strip_tags($_POST["answers"]);

    //
    $formattedAnswers = str_replace(", ", ",", $rawAnswers);
    $answers = explode(",", $formattedAnswers);

    // add answers to database
    include("opendb.php");

    if (count($answers) <= 1) {
        echo "<p>It makes no sense to add less than or equal to one answer.</p>";
    } else {
        // add poll to database if it is not already there
        $pollNewCheck = $db->prepare('SELECT * FROM polls WHERE poll = ?');
        $pollNewCheck->bindValue(1, $poll, PDO::PARAM_STR);
        $pollNewCheck->execute();
        $rows = $pollNewCheck->fetch();
        if (count($rows) == 0) {
            $pollQuery = $db->prepare('INSERT INTO polls (poll) VALUES ( ? )');
            $pollQuery->bindValue(1, $poll, PDO::PARAM_STR);
            $pollQuery->execute();
            echo "<h2>Poll added!</h2><p id=\"addedPoll\">$poll</p>";
        } else {
            echo "<h2>Existing poll!</h2><p id=\"addedPoll\">\"$poll\" is already in the database. The answers you entered have been added to it.</p>";
        }

        // get poll_id for added poll
        $pollIDQuery = $db->prepare('SELECT * FROM polls WHERE poll = ?');
        $pollIDQuery->bindValue(1, $poll, PDO::PARAM_STR);
        $pollIDQuery->execute();
        $row = $pollIDQuery->fetch();
        $pollID = $row[0];

        echo "<h3>These are the available answers you added:</h3>";
        echo "<ul>";
        foreach($answers as $answer) {
            $answerQuery = $db->prepare('INSERT INTO answers (answer, poll_id) VALUES ( ?, ? )');
            $answerQuery->bindValue(1, $answer, PDO::PARAM_STR);
            $answerQuery->bindValue(2, $pollID, PDO::PARAM_STR);
            $answerQuery->execute();
            echo "<li>$answer</li>";
        }
        echo "</ul>";
        echo "<p id=\"returnToPanel\"><a href=\"/admin.php\">Return to admin panel</a></p>";
    }
}

Why does it not work to use multiple "if"s but it does work to use "if"s and "else if"s inside a while loop?

This was my code without using else if:

#include <stdio.h>

main()
{
    long s = 0, t = 0, n = 0;
    int c;
    while ((c = getchar()) != EOF)
        if (c == ' ')
            ++s;
        if (c == '\t')
            ++t;
        if (c == '\n')
            ++n;
    printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}

This is the code using else if:

#include <stdio.h>

main()
{
    long s = 0, t = 0, n = 0;
    int c;
    while ((c = getchar()) != EOF)
        if (c == ' ')
            ++s;
        else if (c == '\t')
            ++t;
        else if (c == '\n')
            ++n;
    printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}

For a reason, not using the else if doesn't work. What is the reason? I know that using if does it one by one while using else if stops at the first statement that is true. This has a difference in performance. Anyhow not using else if in this particular (if not other) while loop doesn't seem to work.

Thanks.

If statement using both && and || operators

I know this has been discussed plenty. I'm pretty sure I'm using proper operator precedence but am still not getting desired results.

In the code below I'm trying to to see if the body has the class "industries" AND if window.location.href is equal to any of the paths separated by || operators. If the class "industries" is present and window.location.href is not equal to any of the paths listed then I want to change the location.

What's happening though is when I enter the path as http://blahblah.com/#leisure It's still executing the code in the if statement and changing the location to https://blahblah.com/#consumer

I have a feeling my explanation is convoluted and shitty. Sorry.

var indDescObj = {
                        aec: "Connecting with <br> customers who build",
                        b2b: "Connecting <br> business to business",
                        consumer: "Connecting <br> with shoppers <br> everywhere they buy",
                        leisure: "Connecting with <br> customers when <br> they're at play"
                }
                var $indDescription = $('.industry-description');
                var $indNavLinks = $('.industry-nav__link');

                $(document).ready(function() {
                        var path = 'http://blahblah.com/'
                        if ( $('body').hasClass('industries') &&
                                                ( (window.location.href !== path + '#consumer') ||
                                                        (window.location.href !== path + '#b2b') ||
                                                        (window.location.href !== path + '#leisure') ||
                                                        (window.location.href !== path +'#aec') )
                                        ) {
                                                $(".industry-nav__link[data-filter='.consumer']").click();
                                                window.location.href = "http://blahblah.com/#consumer";
                        };
                        var hashPath = "." + window.location.hashPath.slice(1);
                        var pathObjKey = path.slice(1);
                        $(".industry-nav__link[data-filter='" + hash + "']").addClass("is-active")
                                $('.industry-description').append(indDescObj[pathObjKey])
                        })

Strange if-else condition calling

Please help me go through this :

print("%i", session.subsessions.count)    // prints 3
print("%i", self.iSessionNumber)          // prints 6
print("%i", self.sessions.count - 1)      // prints 6
if session.subsessions.count > 1 || self.iSessionNumber == self.sessions.count - 1
{
    // if called
}
else
{
    // else called
} 

Clearly, if condition should be called. But strangely, else is getting called. No idea why

Getting an error while subtracting variables

I am writing a bash script and i get an error when i try to subtracts 2 variables. I tried many ways of declaring the subtraction as a single variable, but i am constantly getting errors. What's the right way to declare the variable? Thanks in advance.

if [ ${$packets1 - $packets2} -gt 30 ]

If statement within an if statement not working

Im just learning about if statements and now im trying to create a little blackjack kinda game. But the error of "Error: unexpected '}' in "}"" keeps comming up, and I cannot solve the problem. This is my current code

#Dealer: If the sum of the cards is lower than 17, the dealer must draw another card 
n_3 = 2
A = 11
#Deck: 
deck <- c(A,A,A,A,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,9,9,9,8,8,8,8,7,7,7,7,6,6,6,6,5,5,5,5,4,4,4,4,3,3,3,3,2,2,2,2)
roll_3 <- sample(deck, n_3, replace = T)
roll_3 
sum(roll_3)

###
#Dealers game
###
if(sum(roll_3) < 17 ){
  newcard = sample(deck,1,replace = T)
  total_dealer_1 <- c(newcard + sum(roll_3))
  #print(sum(roll_3)+newcard)
    if (total_dealer_1 < 17){
      newcard_2 = sample(deck,1,replace = T)
      total_dealer_2 <- c(newcard_2 + total_dealer_1)
     else if (total_dealer_2 > 21) {
        paste("The dealers score is", total_dealer_2,",the dealer busted!")
    } else if (total_dealer_2 < 21 & total_dealer_2 >= 17) {
        paste("The dealer got",total_dealer_2,"!")
    } else if (total_dealer_2 < 17){
        newcard_3 = sample(deck,1,replace = T)
        total_dealer_3 <- total_dealer_2 + newcard_3
     
        
          if (total_dealer_3 > 21) {
            paste("The dealers score is",total_dealer_3,", the dealer busted!")
          } else (total_dealer_3 <= 21) {
            paste("The dealers score is", total_dealer_3)
          }
      }
    }

} else if ((sum(roll_3) < 21 & sum(roll_3) >= 17)) {
    paste("The dealers score is", sum(roll_3))
} else if (sum(roll_3 == 21)){
  paste("21!", "The dealer got backjack!")
}

Been trying for hours now...

why not working function javascript resize ?

My code javascript not working. I want the functions work if will be over 500px width screen.

<ul>
  <li class="da">Dawid</li>
  <li class="pi">Piotr</li>
  <li class="to">Tomek</li>
</ul>

AND JAVASCRIPT CODE- NOT WORKING

document.getElementById("dawid").addEventListener("click",displaytwo);
document.getElementById("piotrek").addEventListener("click",displayone);



function displaytwo(){

                    document.getElementById("piotrek").style.display='none';
                    document.getElementById("tomek").style.display='none';
                                }

function displayone(){
                    document.getElementById("dawid").style.display='none';
                    document.getElementById("tomek").style.display='none';
          }  

RESIZE NOT WORKING

function screen_resize(){
var w = parseInt(window.innerWidth);
   if(w > 500)
   { 

     displaytwo();
     displayone();
   }}
$(window).resize(function(e) {
screen_resize();
});

$(document).ready(function(e) {
    screen_resize();
});

Adding If-Then statement to email text

I'm trying to add an If-Then statement to my VBA in order to create two different email texts based on whether a specific field is populated in a table.

If no data is in the [VendorID/UIN] field in the t1stNoticeEmails table, I'd like this text:

"Please provide a current remit-to address as soon as possible so we can resend the check(s) to the intended recipient(s). The funds from this check will remain as a charge against the FOAPALs utilized in the transaction until this matter is resolved."

If there is data in the [VendorID/UIN] field in the t1stNoticeEmails table, I'd like this additional text:

"In addition, the Vendor ID associated with this transaction may need to be updated. Please contact Vendor Maintenance."

Here's the code:

Sub FirstEmail_IncorrectAddress_ReviewVBA()

    Dim rst As DAO.Recordset
    Dim olApp As Outlook.Application
    Dim objMail As Outlook.MailItem
    Dim rst2 As DAO.Recordset
    Dim strTableBeg As String
    Dim strTableBody As String
    Dim strTableEnd As String
    Dim strFntNormal As String
    Dim strTableHeader As String
    Dim strFntEnd As String
    Dim CheckNum As String
    Dim NameOfRecipient As String
    Dim StrSQL1 As String
    Dim NameSpaceOutlook As Outlook.Namespace

    gPARAttachment = "S:\UPAY\Z_NewStructure\SupportOperations\Projects\Returned Checks\Email Text\PaymentActionRequestForm.pdf"

'SEND FIRST NOTICE EMAILS'
'------------------'

    Set rst2 = CurrentDb.OpenRecordset("select distinct ContactEmails from t1stNoticeEmails WHERE CheckReturnReason = 'IncorrectAddress'")

    If rst2.RecordCount = 0 Then 'checks if recordset returns any records and continues if records found and exits if no records found
        Exit Sub
    End If

    rst2.MoveFirst

    'Create e-mail item
    Set olApp = Outlook.Application
    Set objMail = olApp.CreateItem(olMailItem)

    'Do Until rst2.EOF

    Set olApp = Outlook.Application
    Set objMail = olApp.CreateItem(olMailItem)

    'Define format for output
    strTableBeg = "<table border=1 cellpadding=3 cellspacing=0>"
    strTableEnd = "</table>"
    strTableHeader = "<font size=3 face='Calibri'><b>" & _
                        "<tr bgcolor=#4DB84D>" & _
                            td("CheckNumber") & _
                            td("PayeeName") & _
                            td("VendorID") & _
                            td("DocNo / ERNo / PONo") & _
                            td("Amount") & _
                            td("CheckDate") & _
                            td("OriginalCheckAddress1") & _
                            td("OriginalCheckAddress2") & _
                            td("OriginalCheckCity") & _
                            td("OriginalCheckState") & _
                            td("OriginalCheckZip") & _
                           "</tr></b></font>"
    strFntNormal = "<font color=black face='Calibri' size=3>"
    strFntEnd = "</font>"

    Set rst = CurrentDb.OpenRecordset("SELECT * FROM t1stNoticeEmails where ContactEmails='" & rst2!ContactEmails & "' AND CheckReturnReason = 'IncorrectAddress' Order by FullName asc")

    If rst.RecordCount = 0 Then
        rst2.Close
        Set rst2 = Nothing
        Exit Sub
    End If

    rst.MoveFirst

    NameOfRecipient = rst!FullName
    CheckNum = rst!CheckNumber

    'Build HTML Output for the DataSet
    strTableBody = strTableBeg & strFntNormal & strTableHeader

    Do Until rst.EOF
        strTableBody = _
        strTableBody & _
        "<tr>" & _
        "<TD nowrap>" & rst!CheckNumber & "</TD>" & _
        "<TD nowrap>" & rst!FullName & "</TD>" & _
        "<TD nowrap>" & rst![VendorID/UIN] & "</TD>" & _
        "<TD nowrap>" & rst![DocNo / ERNo / PONo] & "</TD>" & _
        "<TD align='right' nowrap>" & Format(rst!AmountDue, "currency") & "</TD>" & _
        "<TD nowrap>" & rst!OriginalCheckDate & "</TD>" & _
        "<TD align='left' nowrap>" & rst!OriginalCheckAddress1 & "</TD>" & _
        "<TD align='left' nowrap>" & rst!OriginalCheckAddress2 & "</TD>" & _
        "<TD align='left' nowrap>" & rst!OriginalCheckCity & "</TD>" & _
        "<TD align='left' nowrap>" & rst!OriginalCheckState & "</TD>" & _
        "<TD align='left' nowrap>" & rst!OriginalCheckZip & "</TD>" & _
        "</tr>"
        rst.MoveNext
    Loop
    'rst.MoveFirst

    strTableBody = strTableBody & strFntEnd & strTableEnd

    'rst.Close

    'Set rst2 = CurrentDb.OpenRecordset("select distinct ch_email from t_TCard_CH_Email")
    'rst2.MoveFirst

Call CaptureIABodyText

    With objMail
        'Set body format to HTML
        .To = rst2!ContactEmails
        .BCC = gIAEmailBCC
        .Subject = gIAEmailSubject & " - Check# " & CheckNum & " - " & NameOfRecipient
        .BodyFormat = olFormatHTML

        .HTMLBody = .HTMLBody & gIABodyText

        .HTMLBody = .HTMLBody & "<HTML><BODY>" & strFntNormal & strTableBody & " </BODY></HTML>"

        .HTMLBody = .HTMLBody & gIABodySig

        .SentOnBehalfOfName = "UP-ARS@uillinois.edu"
        .Display
        '.Send
    End With

    rst2.MoveNext

'Loop

    rst.Close
    Set rst = Nothing
    rst2.Close
    Set rst2 = Nothing

End Sub

If I have a 3D array how do I sum up the value given a boundary?

Let's say I have a 3D array such that

int[][][] array = 
{  { {1,   2,  3}, { 4,  5,  6}, { 7,  8,  9} },
   { {10, 11, 12}, {13, 14, 15}, {16, 17, 18} },
   { {19, 20, 21}, {22, 23, 24}, {25, 26, 27} } };


Now the array is as follow

First Image

1 2 3

4 5 6

7 8 9

Second Image

10 11 12

13 14 15

16 17 18

Third Image

19 20 21

22 23 24

25 26 27


I would like to sum up the value in the 3 X 3 matrix boundary and create a new array such that one example of summation of the top left corner is that

First Example

((1+2+4+5)+(10+11+13+14)+(19+20+22+23))/ 12

The second example will be to take the centre value and compute the average

Second Example

((1+2+3+4+5+6+7+8+9)+(10+11+12+13+14+15+16+17+18)+(19+20+21+22+23+24+25+26+27))/ 27

where it will compute the average of all the values that are within a 3 by 3 square centred at the pixel.

IF statement not retuning all values. Is there a limit to IF variables?

I have a nightly report that Sums up the values of our GL codes per company division from a Stored Procedure. The divisions are broken up into IP, RE and ALL. The IP and RE totals are correct but the value that returns for the ALL group seems be be getting cut off before all of the GL codes are totaled. There are 32 GL codes in the ALL group. For example IP returns $543299, RE returns $1066129 and the ALL group returns $1526900. The ALL total should be $1609428. I'm able to identify the exact number that is missing and if I remove all of the GL codes and put in just the ones that are not added to the ALL total, it will return the correct value but not when I add it to the full statement.

Below is how I have the statement written. My only idea is that it is getting cut off before all of them get processed. I'm not getting any errors when executing the statement.

If (@DIVISION = 'IP')
            Set @GLCODE = ('1.10.000.4200,2.10.000.4200,1.10.000.4210,2.10.000.4210,1.10.000.4220,2.10.000.4220,1.10.000.4301,1.10.000.4302,2.10.000.4302,1.10.000.4310,2.10.000.4310')
        Else If (@DIVISION = 'RE')
            Set @GLCODE = ('1.20.000.4100,2.20.000.4100,3.20.000.4100,1.20.000.4120,2.20.000.4120,3.20.000.4120,1.20.000.4302,2.20.000.4302,3.20.000.4302,1.20.000.4310,2.20.000.4310,3.00.000.4310,1.30.000.4304,2.30.000.4304,1.30.000.4350,2.30.000.4350,1.30.000.4351,2.30.000.4351,1.30.000.4352,2.30.000.4352,1.30.000.4353')
        Else If (@DIVISION = 'ALL')
            Set @GLCODE = ('1.10.000.4200,1.10.000.4210,1.10.000.4220,1.10.000.4301,1.10.000.4302,1.10.000.4310,1.20.000.4100,1.20.000.4120,1.20.000.4302,1.20.000.4310,1.30.000.4304,1.30.000.4350,1.30.000.4351,1.30.000.4352,1.30.000.4353,2.10.000.4200,2.10.000.4210,2.10.000.4220,2.10.000.4302,2.10.000.4310,2.20.000.4100,2.20.000.4120,2.20.000.4302,2.20.000.4310,2.30.000.4304,2.30.000.4350,2.30.000.4351,2.30.000.4352,3.00.000.4310,3.20.000.4100,3.20.000.4120,3.20.000.4302')
        Else
            Set @GLCODE = ('00.00.000.0000')

If conditions not applying to char constants. Char being ignored

I have written various programs using the if condition, and they always seem to work only when I am using integer or float constants. Whenever i use char constants, the if condition completely ignores it. Here is an example:

    #include <stdio.h>

int main(void)
{
 int age;
char status,gender;

printf("Enter age, marital status and gender");
scanf("%d%c%c",&age,&status,&gender);

  if((status=='m')||(status=='u' && gender=='m' && age>35) ||
   (status=='u' && gender=='f' && age>25)
    )
       printf("Driver is insured" );

          else
         printf("Driver is not insured");

        }

For instance, if I enter status as u, gender as m and age as 38, it yet says that driver is not insured. Here is the program from cmd:

Enter age, marital status and gender 39 u m Driver is nt insured Press any key to continue . . .

Loop with if statement in R

I did loop with if statement as you can see in the code

for (j in  2:4){
  for (i in 1:5-j){
    if (B[i,5-j]>10){   
        A[i,j] = 0
    }else{
       A[i,j] = 2
    }
  }
}

But it doesn´t work.

In if (B[i, 5 - j] > 115) { : the condition has length > 1 and only the first element will be used

I dont know how it works fine

anyone could help?

thanks

Echo message if between two hours

I am trying to echo a message depending on the time of the page. I need to show the type of service of a coach company. These services are "Semidirecte (sd)", "Pobles (p)" and "Exprés (e)". What I have written is something like: if we are between X hours or X hours, etc; echo X, elseif we are between Y hours or Y hours, etc; echo Y else if we are between Z hours or Z hours; echo Z. This is my actual code:

<?php 
$now = new DateTime();
$v0600 = new DateTime('6:00');
$v0630 = new DateTime('6:30');
$v0650 = new DateTime('6:50');
$v0705 = new DateTime('7:05');
$v0725 = new DateTime('7:25');
$v0755 = new DateTime('7:55');
$v0825 = new DateTime('8:25');
$v0840 = new DateTime('8:40');
$v0900 = new DateTime('9:00');
$v0925 = new DateTime('9:25');
$v1000 = new DateTime('10:00');
$v1020 = new DateTime('10:20');
$v1030 = new DateTime('10:30');
$v1115 = new DateTime('11:15');
$v1200 = new DateTime('12:00');
$v1210 = new DateTime('12:10');
$v1230 = new DateTime('12:30');
$v1300 = new DateTime('13:00');
$v1325 = new DateTime('13:25');
$v1400 = new DateTime('14:00');
$v1435 = new DateTime('14:35');
$v1450 = new DateTime('14:50');
$v1505 = new DateTime('15:05');
$v1525 = new DateTime('15:25');
$v1600 = new DateTime('16:00');
$v1620 = new DateTime('16:20');
$v1635 = new DateTime('16:35');
$v1700 = new DateTime('17:00');
$v1725 = new DateTime('17:25');
$v1805 = new DateTime('18:05');
$v1820 = new DateTime('18:20');
$v1835 = new DateTime('18:35');
$v1910 = new DateTime('19:10');
$v2000 = new DateTime('20:00');
$v2010 = new DateTime('20:10');
$v2035 = new DateTime('20:35');
$v2100 = new DateTime('21:00');
$v2125 = new DateTime('21:25');
$v2155 = new DateTime('21:55');
$v2210 = new DateTime('22:10');
$v2305 = new DateTime('23:05');
$v0500 = new DateTime('05:00');
$sd = Semidirecte;
$p = Pobles;
$e = Exprés;

if ($now > $v0500 && $now < $v0600 or $now > $v0630 && $now < $v0650 or $now > $v0840 && $now < $v0900 or $now > $v0925 && $now < $v1000 or $now > $v1115 && $now < $v1200 or $now > $v1325 && $now < $v1400 or $now > $v1525 && $now < $v1600 or $now > $v1635 && $now < $v1700 or $now > $v1725 && $now < $v1805 or $now > $v1910 && $now < $v2000 or $now > $v2035 && $now < $v2100 or $now > $v2125 && $now < $v2155){
echo $sd; 
} elseif ($now > $v0650 && $now < $v0705 or $now > $v0825 && $now < $v0840 or $now > $v1000 && $now < $v1020 or $now > $v1200 && $now < $v1210 or $now > $v1230 && $now < $v1300 or $now > $v1435 && $now < $v1450 or $now > $v1450 && $now < $v1505 or $now > $v1600 && $now < $v1620 or $now > $v1805 && $now < $v1820 or $now > $v2000 && $now < $v2010 or $now > $v2155 && $now < $v2210){
echo $e;    
} elseif ($now > $v0600 && $now < $v0630 or $now > $v0705 && $now < $v0725 or $now > $v0725 && $now < $v0755 or $now > $v0755 && $now < $v0825 or $now > $v0900 && $now < $v0925 or $now > $v1020 && $now < $v1030 or $now > $v1030 && $now < $v1115 or $now > $v1210 && $now < $v1230 or $now > $v1300 && $now < $v1325 or $now > $v1400 && $now < $v1435 or $now > $v1505 && $now < $v1525 or $now > $v1620 && $now < $v1635 or $now > $v1700 && $now < $v1725 or $now > $v1820 && $now < $v1835 or $now > $v1835 && $now < $v1910 or $now > $v2010 && $now < $v2035 or $now > $v2100 && $now < $v2125 or $now > $v2210 && $now < $v2305){
echo $p;
} else {
echo "No data"; 
}
?>

What am I doing wrong? Is there a simpler script to do what I want? I have a public website running my entire script: http://poldiloli.com/bus/setmanal.php, but it is showing what it wants at the time that it wants.

Excel: Combining nested IF statements with OR, without using a macro

I'm trying to basically create a mandatory field in Excel without using VBA/macros.

I am creating a spreadsheet listing employees with unused vacation hours above a maximum cap. It will go to the employees' managers who will then approve or deny the employee's request to use the additional hours. The manager will select from a drop down list of pre-populated reasons (sheet 2 A1:A13) to approve or deny the request.

enter image description here

enter image description here

There is a two part validation:

  1. If no approval reason is selected, and hours are entered in column H, validation fails:

=IF(AND((ISNA(VLOOKUP($I$2,Sheet2!$A$1:$A$7,1,FALSE))),H2<>0),"ERROR",H2)

  1. If no denial reason is selected, and the value of column H is zero, validation fails:

=IF(AND((ISNA(VLOOKUP($I$2,Sheet2!$A$9:$A$13,1,FALSE))),H2=0),"ERROR",H2)

I can get these two formulas to work independently, but can’t figure out how to combine them into a single formula using an “OR” statement. Is it possible to do this?

(I know an alternative is to add “true/false” columns for both formulas, then create another IF/AND formula to validate that both conditions are met and then hide the columns, but looking for a cleaner solution).

I specifically don't want to embed macros because this will be sent out by email as a saved document, and the recipients will be prompted whether to activate the macros.

PHP Display button if user is an admin

With this piece of code below I receive the users that are an admin from the database. A user is an admin if he has the value '1' in the 'admin' row. So I am only able to get the email addresses from all the admins, but how do I make a button that is only accessible for these admin users, so only they can go to an admin panel.

$admincheck = $db->prepare("SELECT mail From users WHERE admin = 1");          
$admincheck->execute();
$admin = $admincheck->fetchAll(PDO::FETCH_ASSOC);
foreach ($admin as $row) {
     echo $row['mail'];
}

Trying to limit input options for hangman

I was given a almost complete code (with a Library i downloaded). The code I'm making should allow a user to input letters, 1 capital letter at a time. I created a while-loop that checks if the characters that are input are ok. Problem is you can "break" the code, i guess cause the if chunks are connected? would love some help.

    import se.rosendalsgymnasiet.hangman.HangmanGameEngine;

import java.util.Scanner;

public class Thomas_Parker_hangman_1 {
public static void main(String[] args) {
    String previousLetters = "";
    HangmanGameEngine hangman = new HangmanGameEngine();
    hangman.selectWord();
    hangman.createStatusString();
    while (!hangman.evaluateStatus(previousLetters)) {
        char letter;

//Nedanstående metod saknar definition, det är din uppgift att skapa metoden
            letter = guess(previousLetters);

            previousLetters = previousLetters + String.valueOf(letter);
            hangman.updateStatusString(letter);
        }
        System.out.println("Bravo, du lyckades finna rätt ord!");
    }

/**
 * Låter användaren skriva in bokstäver
 *
 * @param previousguesses De gissningar användaren prövat
 * @return
 */

This is what i have made and where i need help:

private static char guess(String previousguesses) {
        Scanner keyboard = new Scanner(System.in);
        String userguess = keyboard.next().toUpperCase();
    char Charactercontroll;
    Charactercontroll = userguess.charAt(0);


    boolean Supercontroll = true;


    while (Supercontroll = true) {
        if (userguess.length() >= 2) {
            System.out.println("Du får bara skriva en bokstav, försök igen!");
            Supercontroll=true;
            userguess = keyboard.next().toUpperCase();
        } else if (previousguesses.contains(String.valueOf(userguess))) {
            System.out.println("Du har redan gissat på denna bokstav, försök igen!");
            Supercontroll=true;
            userguess = keyboard.next().toUpperCase();
        } else if (!Character.isLetter(Charactercontroll)) {
            System.out.println("Detta är inte en bokstav, försök igen!");
            Supercontroll=true;
            userguess = keyboard.next().toUpperCase();
        } else {
            Supercontroll = false;
        }
        while (Supercontroll=false);
        return userguess.charAt(0);
    }
    return userguess.charAt(0);


}

}

If condition not working in c.Else gets executed help ..for selecting club members

My if condition does not work. The command after else gets executed and not the if condition pls help i have tried everything

 #include <stdio.h>

main()
{
   int class;
   float grade;

   printf("Enter your class and grade");
   scanf("%d%f",&class,&grade);

   if((class==10)||(class==8 && grade>=80)||(class==9 && grade>=70))
       {
         printf("You can sign up for MUN");
       }
       else
       {

         printf("You cant sign u!");
       }


}

in the way of understanding return in python? what is the difference Here?

please explain in details as much as You can

why that is True?

def array_front9(nums):
    for i in nums[:4]:
        if i == 9:
            return True
    return False

array_front9([1, 2, 9, 3, 4])

while this is False:

def array_front9(nums):
    for i in nums[:4]:
        if i == 9:
            return True
        else:
            return False

array_front9([1, 2, 9, 3, 4])

How can I use ELSE IF inside GROUP_CONCAT?

I have an IF statement inside a mySQL query and it is working well:

 GROUP_CONCAT(DISTINCT CONCAT("animal:",if(animal.name="monkey","fred",""),",color: ",animal.color) SEPARATOR " <br>") AS animals

I want now add an ELSEIF:

  GROUP_CONCAT(DISTINCT CONCAT("animal:",if(animal.name="monkey","fred","")elseif(animal.name="cat","jane",""),",color: ",animal.color) SEPARATOR " <br>") AS animals

But I get an ERROR message:

Syntax error or access violation: 1064 You have an error in your SQL syntax

Android Only upload image if an image is selcted

I use following Code to select an image from gallery and display it with an ImageView:

@Override
    protected void onActivityResult(int RC, int RQC, Intent I) {

        super.onActivityResult(RC, RQC, I);

        if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {

            Uri uri = I.getData();

            try {

                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

                imageView.setImageBitmap(bitmap);

            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

Currently, with the method ImageUploadToServerFunction() the upload will be started, also if no image is selected. Finally the app crashes.

My question: What can I do, not to start the upload and post an Toast if there is no image selected?

if (imageView == ???) {
            ImageUploadToServerFunction();
        } else {
            Toast.makeText(MainActivity.this, "No image selected!", Toast.LENGTH_LONG).show();
        }

MSSQL Executing Procedure Using IF on Scalar

I have a query that compares values in two columns, row by row, and sums the ABS(diff) to a single scalar int. I want to use the final scalar int to determine if a procedure should be executed.

The query has two WITH and a single SELECT FROM the 2nd WITH like this:

WITH AAA AS (...),    
BBB AS (... FROM AAA)    
SELECT SUM(I)    
FROM BBB

The query works - I get the correct result when it's run as SELECT.

However, when I try to use an IF [result] = 0, I get syntax errors no matter where I put the IF condition.

Is there any way to combine WITH and IF in the way I want?

Lambda expression inside ?? (if shortcut) operator

I like short code, so recently I was trying to fit if statement and Linq query with lambda expression in one line.

Is it possible to do something like:

db.Users.First(x => x.UserId == providedId)??x.SomeUsefullField

That should return null if user not found, and value of some field if user does exists.

Is it possible to do without first getting user and than getting field value like this:

var user = db.Users.First(x => x.UserId == providedId);
var fieldValue = user.SomeUsefullField;

Thank you for possible solution and knowledge sharing.

lundi 29 janvier 2018

if else logic | pyramid error

I'm trying to build a c program that prints a right aligned pyramid ie:

   ## 
  ### 
 #### 
##### 

I thought about approaching this using an if-else logic to test the user input. However, when I run my code it keeps giving me this error and also doesn't show the error when the input is not valid.

mario.c:25:2: else error: expected '}'
}
 ^
mario.c:7:1: note: to match this '{'
{

Example code below:

#include <cs50.h>
#include <stdio.h>


int main (void)
{
    int height;
    height = get_int("Enter a number between 0 and 23: "); // keep prompting user for valid input'

    if (height > 0 || height < 23) {
        for ( int levels= 1 ; levels <= height; levels++) {
            for (int spaces = height-levels; spaces > 0; spaces--){
                printf (" ");
            }
            for (int hash = 1; hash <= levels+1; hash++){
                printf ("#");
            }
            printf("\n");
        }
        else 
        {
            height = get_int("Please try again: ");
        }

    }
}

Any help is appreciated!

Save values for each iteration of for-statement with if else in R

My problem: I have an if else-statement nested in an for-loop and want to save the values for each iteration of it.

For example with some simple data, what i've tried is:

s <- c(4, 8, 3) #a string with some values
l <- list() #the list where i want the output to be saved in
for (n in 1:length(s)) {
     if (n==1) {
         b1 <- 1:s[n]
         print(b1)
         l <- c(b1)} 
      else {
          b2 <- (s[n-1]:s[n])
          print(b2)
          l <- c(b1=b1, b2=b2)}}

The print() output is all vectors i want to save

[1] 1 2 3 4
[1] 4 5 6 7 8
[1] 8 7 6 5 4 3

but l only stores the first vector (from the if statement) and the last iteration of the else statement:

b11 b12 b13 b14 b21 b22 b23 b24 b25 b26 
  1   2   3   4   8   7   6   5   4   3 

How can i save every iteration? I've been trying this for some hours and got nowhere, so any help is greatly appreciated!

Second Scraper - If Statement

I am working on my second Python scraper and keep running into the same problem. I would like to scrape the website shown in the code below. I would like to be ability to input parcel numbers and see if their Property Use Code matches. However, I am not sure if my scraper if finding the correct row in the table. Also, not sure how to use the if statement if the use code is not the 3730.

Any help would be appreciated.

`from bs4 import BeautifulSoup

from bs4 import BeautifulSoup
import requests
parcel = input("Parcel Number: ")
web = "https://mcassessor.maricopa.gov/mcs.php?q="
web_page = web+parcel
web_header={'User-Agent':'Mozilla/5.0(Macintosh;IntelMacOSX10_13_2)AppleWebKit/537.36(KHTML,likeGecko)Chrome/63.0.3239.132Safari/537.36'}
response=requests.get(web_page,headers=web_header,timeout=100)
soup=BeautifulSoup(response.content,'html.parser')
table=soup.find("td", class_="Property Use Code" )
first_row=table.find_all("td")[1]
if first_row is '3730':
    print (parcel)
else:
   print ('N/A')

Ifelse logical statement

I'm just starting to learn ifelse statements in functions. Here's a simplified example:

librar(knitr)

Tab <- iris

my_kable <- function(x, html = TRUE) {
  if(html) {  # any expression here in parentheses is evaluated before it's passed on to the if statement
    kable(x, kable_input = "html")
  } else {
    kable(x, kable_input = "latex")
  }
}

my_kable(Tab, html = FALSE)

The issue is in R Markdown, whether I put "html = FALSE" or "html = TRUE" I get the same result (an HTML table). I know I'm missing something very simple...

'if' condition doesn't work after second cycle [python]

I have a problem with if loop. In the script I need to check if difference between i and i+1 row is exual 0.6 and if yes, then the program should calculete grad[i] value. The problem is that in third circle, even if the condition is fulfiled, calculations grad[i] aren't performed. I feel in my bones that I made a stupid mistake but totally I don't know where. I would be very grateful for a clue/enlightenment. Best regards,

This is part of my code:

data = np.loadtxt(files[p])
N=len(data)
print "N: ", N, "\n"
for i in range(0,N-1):
    print "i: ", i
    j=i+1
    Fi[i]=data[i,1]
    errFi[i]=data[i,2]
    Fj[j]=data[j,1]
    errFj[j]=data[j,2]
    t1=data[i,0]
    t2=data[j,0]
    dt=(t2-t1)
    print "dt:", dt
    print Fj[j]-Fi[i]
    if dt == 0.6:
        print " dt =", dt
        if Fi[i] < Fj[j]:
            r[i]=1
            grad[i]=(Fj[j]-Fi[i]) / dt
        else:
            r[i]=-1
            grad[i]=(Fi[i]-Fj[j]) / dt

        print " grad[",i,"]=",grad[i] 

and the result in console is:

i:  0
dt: 0.6
0.148645
dt = 0.6
grad[ 0 ]= 0.247741666667

i:  1
dt: 0.6
0.061069
dt = 0.6
grad[ 1 ]= 0.101781666667

i:  2
dt: 0.6
-0.009578

i:  3
dt: 0.6
0.078995

i:  4
dt: 0.6
0.069982

Nested For Loops w/ If-Else

I've never done a nested for loop before and my understanding of for loops is only rudimentary anyway. I am trying to get the loop to iterate over rows of a matrix and then elements of a vector to write to an empty matrix. I am also open to non-loop/vectorized solutions, though I would love to know why my loop code is so hopelessly broken.

To set up the input matrices and vector:

condition = c(0,1,2)
condition_risk = c(0,1,1,2,2,2)
condition_health = c(0,0,0,1,1,2)
ES = rnorm(n = 10)

ppt1 = matrix(sample(condition, 10, replace = T), ncol = 10, nrow = 100)
ppt2 = matrix(sample(condition_risk, 10, replace = T), ncol = 10, nrow = 25)
ppt3 = matrix(sample(condition_health, 10, replace = T), ncol = 10, nrow = 25)

key = rbind(ppt1,ppt2,ppt3)
key_recoded = matrix(NA, ncol = 10, nrow = 150)

This creates a vector of effects -1 to 1 called "ES"; a matrix w/ conditions 0,1,2 called "key"; and an empty matrix with the same dimensions called "key_recoded":

head(ES)
-0.31741374 -0.08023316 -0.57528823  0.78028852 -0.20937815  0.12266581

head(key)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    2    2    2    2    2    2    2    2    2     2
[2,]    0    0    0    0    0    0    0    0    0     0
[3,]    2    2    2    2    2    2    2    2    2     2
[4,]    0    0    0    0    0    0    0    0    0     0
[5,]    0    0    0    0    0    0    0    0    0     0
[6,]    2    2    2    2    2    2    2    2    2     2

head(key_recoded)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
[2,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
[3,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
[4,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
[5,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
[6,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA

The goal is to recode the conditions from 0,1,2 to 2,1,0 when ES values are negative.

For example, ES[1] = -.31741374 and key[1,1] = 2, so key_recoded [1,1] should be 0 instead of 2. If key[1,1] had instead been 0, then key_recoded would be 2 instead of 0. Condition values of 1 in "key" are to be ignored.

This is what key_recoded should look like; see that 0 and 2 re flipped from key w/ 0s in the 1st row instead of 2s:

head(key_recoded)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    0    0    0    0    0    0     0
[2,]    2    2    2    2    2    2    2    2    2     2
[3,]    0    0    0    0    0    0    0    0    0     0
[4,]    2    2    2    2    2    2    2    2    2     2
[5,]    0    0    0    0    0    0    0    0    0     0
[6,]    2    2    2    2    2    2    2    2    2     2

This is my sad code that does nothing to the empty matrix, "key_recoded", but returns no errors:

for (j in nrow(key)){
  for (i in nrow(ES)){
    if(ES[i] < 0 && key[j,i] == 2){
      key_recoded[j,i] = 0
    }
    else{
      key_recoded[j,i] = key[j,i]
    }
    if(ES[i] < 0 && key[j,i] == 0){
      key_recoded[j,i] = 2
    }
    else{
      key_recoded[j,i] = key[j,i]
    }
  }
}

While loop in bash script for svn

I have a bash script that Im using on my centos machine that checks out from subversion and puts everything onto my host machine.

I need to use some sort of loop, maybe a while loop, to make my script check for a new version in subversion every 5 minutes. If the version hasnt changed, sleep for another 5 minutes and check again.

If the version has changed, say from revision 15 to revision 16, I need it to run my script to export that new revision.

Can anyone help me create some sort of loop to satisfy that? Im not sure whats best; While, If-else, etc

Thank you!

Elm - Executing multiple lines per if branch

For example, in one branch, I want see how many times a number is divisible by 1000, then pass the starting number less that amount into the function recursively. This is what I have written:

if num // 1000 > 0 then
    repeat (num // 1000) (String.fromChar 'M')
    convertToRom (num - (num // 1000) * num)

However, I get the following error in the REPL when testing:

> getRomNums 3500
-- TYPE MISMATCH ----------------------------------------- .\.\RomanNumerals.elm

Function `repeat` is expecting 2 arguments, but was given 4.

34|             repeat (num // 1000) (String.fromChar 'M')
35|>            convertToRom (num - (num // 1000) * num)

Maybe you forgot some parentheses? Or a comma?

How can I write multiple lines of code for a single if branch?

ifelse inside for loop w/ 2 conditions

I'm sorry if this has been asked before. I have checked numerous questions about using if-else inside for loops to no avail. I must be misinterpreting the answers. I've edited my code multiple times to avoid different fatal errors and/or unanticipated outputs (incl. no change and/or only the else statement being evaluated). Below are my two attempts at using ifelse.

What I want the loop to do: Check if Column A has a negative value and Column B is equal to 2. If both conditions are true, put a 0 in Column C; otherwise, copy the value from Column B as is to Column C. Ultimately, I also want to do the reverse - swap 0s for 2s when Column A is negative.

Thanks!

condition = c(0,1,2)
ppt1 = sample(condition, 124, replace = T) 
ES = rnorm(n = 124)
key = as.data.frame(cbind(ES,ppt1))
key$recoded = rep(NA, 124)

for(i in nrow(key)){ 
  ifelse((key$ES[i] < 0) && (key$ppt1[i] == 2),key$recoded[i] == 0,key$recoded[i] == key$ppt1[i]) 
}

for (i in 1:nrow(key)) {
  if(key$ES[i] < 0 && key$ppt1 == 2) {
    key$recoded[i] == 0
  } else {
    key$recoded[i] == "key"
  }
}

Wondering how to compare JDateChooser with LocalNow

So I'm trying to create an if else statement where if a date from the jdatechooser is before today's date, then an error message would occur. From my knowledge, you can get today's date as LocalDate.now(), format it into a string, and then do a try-catch to parse it back into a Date. For the jdatechooser, you can grab that as a Date, format it into a string, and then do a try-catch to parse it back into a date as well. The only issue with this is when you do jdate.before(localdate) an error occurs. Is there another method of doing this? I saw that you could get today's date as an Instance, but I don't have much experience with that yet.

This is the code that I tried:

try{
    //Checks to see if New Due Date is a date set before today's date

    //Grabs today's date, converts it into string, then converts it into date
    LocalDate ld = LocalDate.now();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
    String tds = sdf.format(ld);
    Date tdd = sdf.parse(tds);

    //Grabs reactivateDateChooser1, converts it into string, then converts it into date
    Date rdc = reactivateDateChooser1.getDate();
    SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd, yyyy");
    String rdcs = sdf1.format(rdc);
    Date rdcd = sdf1.parse(rdcs);

    //If the new Due Date is before or on today's date, then error message will show
    if(rdcd.before(tdd)){
        JOptionPane.showMessageDialog(null, "Please select a date after " + tds, "Select Valid Date", JOptionPane.ERROR_MESSAGE);
    }

    //If the date chooser is empty, then error message will show
    else if (reactivateDateChooser1.getDate() == null){
        JOptionPane.showMessageDialog(null, "Please select a date", "Needs Date", JOptionPane.ERROR_MESSAGE);
    }

    //Otherwise, if the new date is after today's date, then the function will happen
    else if (rdcd.after(tdd)){
    changeStatusToActive();
    statusCheck1.setText("");
    refreshClassTable();
    closeReactivateDialog();
    }
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }

And this is the error that I'm getting:

java.lang.IllegalArgumentException: Cannot format given Object as a Date

"missing value where TRUE/FALSE needed" but no NA in data? In r

I have two dataframes.

data1:

ThirtyWestTime            Direction    Period
2017-03-20 19:19:00         W            0
2017-03-20 08:44:51         E            0
2017-03-20 12:09:22         W            0

times:

Direction      DateAct              DateDe              period
  E        2017-03-20 01:00:00   2017-03-20 08:00:00     2344
  W        2017-03-20 11:30:00   2017-03-20 19:00:00     2345

I am trying to loop through each row in data1 to see if data1$Direction matches times$Direction, if data1$ThirtyWestTime is greater or equal to times$DateAct and if data1$ThirtyWestTime is smaller or equal to times$DateDe. If all these rules are satisfied it should take the corresponding period in times, or be zero. Hence I want the following:

data1:

ThirtyWestTime            Direction     Period
2017-03-20 19:19:00         W            0
2017-03-20 08:44:51         E            0
2017-03-20 12:09:22         W            2345

I have used the following loop but it gives me the following error:

for (j in 1:nrow(data1)){
  for (i in 1:nrow(times)){
    if ((data1$ThirtyWestTime[j]<=times$DateDe[i]) && (data1$ThirtyWestTime[j]>=times[i,2]) && identical(data1$Direction[j],times[i,1])){
  data1$Period[j]<-times[i,4]
} else {data1$Period[j]<-data1$Period[j]} 
  } 
}

Error in if ((data1$ThirtyWestTime[j] <= times$DateDe[i]) && (data1$ThirtyWestTime[j] >=  : 
  missing value where TRUE/FALSE needed

I have removed all NAs from my data so I don't know why this error is coming up and the loop breaks on j=2.

Please help. Thank you

if statement with an element of my MainWindow.xaml

I have an element in my MainWindow.xaml with a name:

<Canvas x:Name="Calque1" Width="97" Height="30" Canvas.Left="0" Canvas.Top="0">

Is it possible to do a "if statement" with Calque1 in the MainWindow.xaml.cs?

Something a bit like that:

 if(theme == 0)
 {
     model.SetImageData(File.ReadAllBytes(@"D:\My_Files\Planche 4\Planche_2018-01-15 (v 4.0.0.4)\Planche\Resources\logo.png"));
 }
 else 
 {
     (Put somthing here to display Calque1);
 }

Can't find a usefull answer.

If with Weekday & DateAdd

VBA beginner here, apologies if this is a dumb question. I need to save a file as the previous day's date. On Mondays, I need to save the file as Fridays date. Here's what I have:

If FileDate = Weekday(Date, vbMonday) Then Format(DateAdd("d", -3, Date)) = "yyyymmdd" Else FileDate = Format(DateAdd("d", -1, Date), "yyyymmdd")

This is spitting out date-1 even on Mondays. Any ideas how to get this to show Friday's date if run on a Monday? I appreciate the help! Thank you!

javascript click a button with if statement to compare text variable

can you please help me with this :

I am trying to click three different buttons with different ids, but based on a string variable name in javascript like :

function my_custom_js_func(){

  jQuery( "#listViewer" ).click();

};

but this will always click the button with id listViewer

i have a variable :

 var viewTog = "List";

or : var viewTog = "Grid";

I want to do something like this :

 function my_custom_js_func(){

  if (viewTog == "List") {jQuery( "#listViewer" ).click();};
  if (viewTog == "Grid") {jQuery( "#gridViewer" ).click();};

};

but it doesn't work, I am using the variable viewTog as a memory.

thank you !

Loop with no output

d is a data.frame (71obs of 3 variables); database is a data.frame (33016 of 6 variables) d[,3] is a column with NA which should be filled by matching with database character (database[,6]) they are no troubles, but d[,3] get not filled and I know that they are some matches. Could anybody help?

for (i in nrow(d)){
for (j in nrow(database)){
if(round(d[i,1],2) %in% database[j,1]){
d[i,3]<-paste(database[j,6])}}}

**Practice to improve my Java Skills P.S I am a beginner**

***Hi, I am new to Java and want to learn more by practicing coding, It would be very helpful if you can suggest me some problems that I can solve.

  • I currently understand using For loop, if, else-if statements, and scanner classes.

Why does !is_404() not behave as expected?

In Wordpress you can use the core function is_404() to check if the current page is a 404 error page. This is a boolean function, meaning it will return TRUE if it is, and FALSE if it isn't.

However, when I place inside an IF function in my header file, and query as so, which I believe is asking IF is_404() returns FALSE...

if(!is_front_page() || !is_404()) {
    // Include something
}

When I view a 404 error page, the line is included where it shouldn't be.

I can perform a check on the value of is_404() using var_dump(), which returns as TRUE.

Why is my //include something line being parsed?

dimanche 28 janvier 2018

Using .equals in a conditional

I'm writing a rather simple BST that is taking its data from an input file. The input file contains 100+ String values. One of my jobs is to check for repeat values. In order to do this I wrote a recursion method that takes one of those words and checks it against the other words present while traversing through the BST.

This is the recursion code:

public int doubleWord(Word wordToCheck) {
    return doubleWordRec(wordToCheck, root);
}

int repeat = -1;

private int doubleWordRec(Word newWord, Word p) {

    if (p != null) {


        doubleWordRec(newWord, p.getLeftChild());
        if (newWord.getEnglishWord().equalsIgnoreCase(p.getEnglishWord())) {
            return repeat = 0;  
        }
        doubleWordRec(newWord, p.getRightChild());

    }
    return -1;
}

This is the application of the recursion:

while (input.hasNext()) {
            String englishWord = input.next();
            String italianWord = input.next();
            passedWord = new Word(englishWord, italianWord);
            if (doubleWord(passedWord) != 0)
                addWord(passedWord);
        }

As you can see, the idea is to verify that the word that is going to be added to the BST through the addWord method will only do so if the recursion method doubleWord does not return 0. The issue I am running into is that it seems as if though the recursion doesn't do anything. It still prints all of the words regardless.

Best way to check if lots of variables contain a string and if so change it? PHP

I have lots of variables that I need to check to see if it is equal to "None". If a variable is equal to "None" I would like to change it to = "-";

What's the best practice way of doing this without having a separate IF function for each variable?

//Variables
$profileEthnicity = h($result["profile_ethnicity"]);
$profileHeight = h($result["profile_height"]);
$profileBuild = h($result["profile_build"]);
$profileEyeColor = h($result["profile_eye_color"]);
$profileHairColor = h($result["profile_hair_color"]);
$profileTattoos = h($result["profile_tattoos"]);
$profilePiercings = h($result["profile_piercings"]);

//Example
if($profileEthnicity == "None") { $profileEthnicity = "-"; }

Why Is my code not outputting the string from the if statement?

Here is my code: https://plnkr.co/edit/HFyKq2JZipwAAST0iNAt?p=preview Why is it not outputting the result of the if statement to the tag with ID "WA" Here's the IF Statement separate from the code linked above:

if (demlean.WA <= 5 && demlean.WA >= -5) {
        if (demlean.WA > 0) {
          var lWA = "Tossup, Tilt D";
        } else if (demlean.WA < 0) {
          var lWA = "Tossup, Tilt R";
        } else {
          var lWA = "Absolute Tossup";
        }

      } else if (demlean.WA > 5) {
        if (demlean.WA <= 10) {
          var lWA = "Lean D";
        } else if (demlean.WA <= 17) {
          var lWA = "Likely D";
        } else {
          var lWA = "Safe D";
        }
      } else {
        if (demlean.WA >= -10) {
          var lWA = "Lean R";
        } else if (demlean.WA >= -17) {
          var lWA = "Likely R";
        } else {
          var lWA = "Safe R";
        }

how to use If and then statement to copy from ones sheet to another

I am using this if statement to compare the value on C1 on two tabs and if the value are the same copying the value on F1 on sheet1 to F1 sheet 2. But i want to add a statement that if there is a value already on Sheet2 F1, not to replace it but to add it and separate with a coma.

 =if('Original list'!C1='Second list'!C1,'Second list'!C1,0)

dynamic if statement for string

How would I do something where I have 3 string variables, string1 string2 and string3 and depending on the user input some of those variables may be empty? I want to compare those variables to another 3 variables I already have set, unless the corresponding string (string1/string2/string3) input is empty

The idea is like this:

If none of them are empty then:

if (o.s1.equals(string1) && o.s2.equals(string2) && o.s3.equals(string3))

if s1 is the only one empty then we only compare the other 2:

if (o.s2.equals(string2) && o.s3.equals(string3))

So the program will not check if that variable is equal if the inputted string is empty

Is there a way to do this that isn't a bunch of nested if statements? I have 5 variables so there would be a lot of statements

Rails Form Conditional Field Can't Submit Form

I have a problem with my code below. Essentially, I have a boolean that determines if a client already exists or not - if user says 'yes' shows a previous list of clients using collection_select - if user says 'no' they get an input field to create a new client using text_field. JQuery shows or hides the correct input field accordingly.

Problem: When submitting this form, even though JQuery is hiding the field that's not relevant, that field is affecting or preventing the form from being submitted.

For example: If user says 'yes' and chooses an existing client and form is submitted, I get an error message the client_name is blank (because the form is submitting the blank text_field instead of what user selected in collection_select)

Any ideas how I can fix this? Appreciate any help.

   <p> Is this new collection for an existing client? </p>
                <%= select_tag(:existing_client,options_for_select([['Yes', 1], ['No', 2]], 2), {id: "existing-client"}) %>                                            
    <%= f.collection_select :client_name, current_designer.client_folders, :client_name, :client_name, {prompt: true, selected: :id}, {id: "existing-list"} %>
<%= f.text_field :client_name, placeholder: "e.g. Sally Smith", id: "collect-input" %>

How to write a function to check if a list of modules are present or not, else install modules in Python

I want to write a 'If Else' function in Python to check if a list of modules are present or not, else install modules in Python (3.6).

Thanks in advance!

my if not working or I am making a mistake

when i don't select file and click on "up" , my output is "ok".. i think its wrong. please help me..i confuse. :|

     <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>

<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="image">
    <button type="submit" name="btn">up</button>
</form>
<?php  
if(isset($_POST['btn']))
{
    if(isset($_FILES['image']))
    {
    echo "ok";
    }
}
?>
</body>
</html>

Better way of writing multiple if checks in a Clojure function?

I have a Clojure function that looks something like the following.

(defn calculate-stuff [data]
  (if (some-simple-validation data)
    (create-error data)
    (let [foo (calculate-stuff-using data)]
      (if (failed? foo)
        (create-error foo)
        (let [bar (calculate-more-stuff-using foo)]
          (if (failed? bar)
            (create-error bar)
            (calculate-response bar)))))))

Which works fine but is a little hard to read, so I was wondering if there was a more idiomatic Clojure way of writing this?

I thought about making some-simple-validation, calculate-stuff-using and calculate-more-stuff-using throw exceptions and using a try/catch block but that felt like using exceptions for control flow which didn't feel correct.

I can't let the exceptions escape this function either as I'm using it to map a seq of maps and I still want to continue processing the remainder.

I guess what I'm after is something like this?

(defn calculate-stuff [data]
  (let-with-checking-function
    [valid-data (some-simple-validation data)
     foo (calculate-stuff-using valid-data)
     bar (calculate-more-stuff-using foo)]
    failed?)                    ; this function is used to check each variable
      (create-error %)          ; % is the variable that failed
      (calculate-response bar)) ; all variables are OK

Thanks!

Python IF ELSE Statement Not Working - Scrapy [on hold]

My IF ELSE statement isn't working. If the first condition isn't met, the function throws an error and doesn't continue to the next part of the IF statement. I'm new to Python, any help offered is appreciated. Code is below:

    if response.css('div.hide-for-small:nth-child(4)::text'):
        price = response.css('div.hide-for-small:nth-child(4)::text').extract()[1].split()[0]
    elif response.css('div.product-price::text'):
        price = response.css('div.product-price::text').extract()[3].split()[0]
    else:
        price = response.css('div.product-price::text').extract()[5].split()[0]

Compare variable to multi variables in PHP

I have 5 variables $a $b $c $d $e . These variables has numerical values. Im trying to compare these variables where each variable will be compared to the rest and if the condition is true it echoes something. Here is my code

if ($a > ($b && $c && $d && $e)) {
$result = '<div>Im A</div>'
} else if ($b > ($a && $c && $d && $e)) {
$result = '<div>Im B</div>'
} else if ($c > ($a && $b && $d && $e)) {
$result = '<div>Im C</div>'
} else if ($d > ($a && $b && $c && $e)) {
$result = '<div>Im D</div>'
} else if ($e > ($a && $b && $c && $d)) {
$result = '<div>Im E</div>'
}

return $result;

The result stops at first condition even though it is false and it should pass it to other conditions.

I want a RNG to repeat itself if the number is false

I'm just testing around with C# and Random Number Generators (RNGs) and I want the RNG to repeat itself if the number isn't 1 but it won't work properly.

Random random = new Random();
label1.Text = random.Next(0, 10).ToString();           

if (label1.Text == "1")
{
    label3.Text = "Positiv";
}
else
{
    label1.Text = random.Next(0, 10).ToString();
};

How to make a string match to all other in android

I want to enter into the true block of the if condition for any NAME in the following code. So how i can declare the string NAME to match it with all models.getName.

if(models.getName().equals(NAME))

I'm using this inside a loop along with other conditions like shown in below and the NAME does not contains a value all the type. So at the time when NAME is empty i need to skip that condition check. But need to check other two.

if(models.getName().equals(NAME)&&models.getType().equals(ClgType)&&models.getUniversity().equals(University))

After checking main If condition unable to reach if and while

I am new to C++. If my details are not clear, kindly modify and update. Hardware reading from scope Thread stored in beforeRightValue. Before that is coming inside void Motion::_Grid() car will stop 2 seconds. Sometimes values will not match so that time I want to calculate error value then I want to make repositioning.

  float degree_check; // calculating error value will store here.

I have created 4 conditions. All condition will check first stored value from hardware (firstdataValue) and current value(beforeRightValue). If any difference happened that will calculate the error value (degree_check), then the car need to move same first degree depends upon the error degree.

That is working fine. That is coming inside if condition. For example condition 1 if, condition 4 if printing. If that is coming inside of main if condition, this condition also true only, but that is not coming inside of this if condition, not inside of the while. I was unable to understand the mistake.

void Motion::_Grid()
{
  float beforeRightValue = ScopeThread::data; 

  if((int)beforeRightValue != (int)firstdataValue) 
    {
      float degree_check; // calculating error value will store here.

        if(firstdataValue > 0 && beforeRightValue > 0) 
        {
          degree_check = (firstdataValue)-(beforeRightValue); 

          if(degree_check > 0)
            {
              cout<<"condition 1 if : "<<degree_check<<endl;

              if(!beforeRightValue == firstYawValue) 
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,5);
                    softPwmWrite(Motr2,0);

                   while(true)
                    {
                cout<<"2nd while : "<<firstdataValue<<endl;

                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }

          else if(degree_check < 0)
            {
               cout<<"condition 1 else : "<<degree_check<<endl;

                if(int(ScopeThread::data) != (int)firstdataValue)
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,0);
                    softPwmWrite(Motr2,5);

                   while(true)
                    {
                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            cout<<"2nd while : "<<firstdataValue<<endl;

                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }
        }

        else if(firstdataValue < 0 && beforeRightValue < 0)
        {
          degree_check = (firstdataValue) - (beforeRightValue);

          if(degree_check < 0)
            {
              cout<<"condition 2 if : "<<degree_check<<endl;

                if(int(ScopeThread::data) != (int)firstdataValue)
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,5);
                    softPwmWrite(Motr2,0);

                   while(true)
                    {
                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            cout<<"3rd while : "<<firstdataValue<<endl;

                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }

          else if(degree_check > 0)
            {
                cout<<"condition 2 else : "<<degree_check<<endl;

                if(int(ScopeThread::data) != (int)firstdataValue)
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,0);
                    softPwmWrite(Motr2,5);

                   while(true)
                    {
                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            cout<<"4th while : "<<firstdataValue<<endl;

                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }
        }

        else if(firstdataValue > 0 && beforeRightValue < 0)
        {
          degree_check = (firstdataValue) - (beforeRightValue);

          if(beforeRightValue < -90)
            {
              cout<<"condition 3 if : "<<degree_check<<endl;

                if(int(ScopeThread::data) != (int)firstdataValue)
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,5);
                    softPwmWrite(Motr2,0);

                   while(true)
                    {
                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            cout<<"5th while : "<<firstdataValue<<endl;

                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }

          else if(beforeRightValue > -90 && beforeRightValue <= 0)
            {
                cout<<"condition 3 else : "<<degree_check<<endl;

                if(int(ScopeThread::data) != (int)firstdataValue)
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,0);
                    softPwmWrite(Motr2,5);

                   while(true)
                    {
                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            cout<<"6th while : "<<firstdataValue<<endl;

                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }
        }

        else if(firstdataValue < 0 && beforeRightValue > 0)
        {
          degree_check = (firstdataValue) - (beforeRightValue);

          if(beforeRightValue > 90)
            {
                cout<<"condition 4 if : "<<degree_check<<endl;

                if(int(ScopeThread::data) != (int)firstdataValue)
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,0);
                    softPwmWrite(Motr2,5);

                   while(true)
                    {
                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            cout<<"7th while : "<<firstdataValue<<endl;

                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }

          else if(beforeRightValue < 90 && beforeRightValue >= 0)
            {
              cout<<"condition 3 if : "<<degree_check<<endl;

                if(int(ScopeThread::data) != (int)firstdataValue)
                {
                    softPwmWrite(Motr2, 0);
                    softPwmWrite(Motr1, 0);
                    delay(200);

                    softPwmWrite(Motr1,5);
                    softPwmWrite(Motr2,0);

                   while(true)
                    {
                      if(int(ScopeThread::data) == firstdataValue)
                        {
                            cout<<"8th while : "<<firstdataValue<<endl;

                            softPwmWrite(Motr2, 0);
                            softPwmWrite(Motr1, 0);
                            delay(2000);
                            break;
                        }
                      break;
                    }
                }
            }
        }
    }
}