mercredi 30 septembre 2020

How to take values initiated in an if else statement to be used outside the statement?

hello I'm a newbie and I am having a hard time doing this program. I was wondering if there is any work around to get the value in the else statement be used outside the statement itself or any other way for this to work. The program is suppose to stop when there are 10 odd numbers in the array which i tried to do by putting it in a do while loop and assigning variable k to add 1 value if the the else statement detects an odd number but the value of k is only usable in the else statement.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num[] = new int[100];

        System.out.println("This program stops when 10 odd numbers are entered.");
        do {
            int j = 0;
            int k = 0;
            for (int i = 0; i <= num.length; i++) {
                System.out.println("Please enter element " + i);
                num[j] = sc.nextInt();

                if (j % 2 == 0)
                    System.out.println("Entered number is even");
                else
                    k = k + 1;
            }
        } while (k != 11);
    }
    
}

How to use switch statement to assign a string value to a variable

I hope that I put a title that properly relates to my problem.

The purpose of my program is to calculate the expenses for a trip between various cities. The program will give a list of source cities, followed by a list of destination cities. The user will be allowed to choose their cities by inputting the first letter of each city.

I want the program to be able to take the input from the user and assign it to one of the given cities.

//Declarations
    char src_city[15];
    char dest_city[15];
system("cls");
    puts("\n");
    printf("ENTER THE SOURCE CITY: \n\n");
    printf("B for Baltimore\n\n");
    printf("C for Chattanooga\n\n");
    printf("N for Nashville\n\n");
    printf("P for Pasadena\n\n");
    puts("");
    scanf("%c", &src_city);
    switch(src_city)
    {
    case 'B': case 'b': ("Baltimore");
    break;
    case 'C': case 'c': ("Chattanooga");
    break;
    case 'N': case 'n': ("Nashville");
    break;
    case 'P': case 'p': ("Pasadena");
    break;
    }
    getchar();

The 'B', 'C', 'N', and 'P' are the letters I want the user to input, and when they do to assign it to the corresponding city.

However, when I use this method I get the error: "assignment to expression with array type". I looked up this error and I was then told to use if/else if statements which in turn failed similarly. The switch statement method makes the most sense to me.

I need to assign the string value to the corresponding variable (src_city/dest_city) because I will need to call those variables later in a printf(); statement.

Any help would be very much appreciated!

expected primary-expression before 'switch'

#include <IRremote.h>
#include <AFMotor.h>
#include <Servo.h>
int receiver = A5;

IRrecv irrecv(receiver);
decode_results results;

void translateIR(){
  switch(results.value){
    case 0xFFA25D: Serial.println("POWER");break;
    case 0xFFE21D: Serial.println("FUNCTION/STOP");break;
    case 0xFF629D: Serial.println("VOL+");break;
    case 0xFF22DD: Serial.println("FAST BACK");break;
    case 0xFF02FD: Serial.println("PAUSE");break;
    case 0xFFC23D: Serial.println("FAST FORWARD");break;
    case 0xFFE01F: Serial.println("DOWN");break;
    case 0xFFA857: Serial.println("VOL-");break;
    case 0xFF906F: Serial.println("UP");break;
    case 0xFF9867: Serial.println("EQ");break;
    case 0xFFB04F: Serial.println("ST/REPT");break;
    case 0xFF6897: Serial.println("0");break;
    case 0xFF30CF: Serial.println("1");break;
    case 0xFF18E7: Serial.println("2");break;
    case 0xFF7A85: Serial.println("3");break;
    case 0xFF10EF: Serial.println("4");break;
    case 0xFF38C7: Serial.println("5");break;
    case 0xFF5AA5: Serial.println("6");break;
    case 0xFF42BD: Serial.println("7");break;
    case 0xFF4AB5: Serial.println("8");break;
    case 0xFF52AD: Serial.println("9");break;
    case 0xFFFFFFF: Serial.println(" REPEAT");break;

    default:
      Serial.println(" other button");
  }
      delay(500);
  
}

AF_DCMotor Motor(1);
Servo servo1;
Servo servo2;

void setup(){
  if (irrecv.decode(&results)){
    translateIR();
    irrecv.resume();
  }

  
  Serial.begin(9600);
  servo1.attach(9);
  Motor.setSpeed(200);
  Motor.run(RELEASE);

}
void loop(){
  if (switch(results.value)) = (case 0xFF906F:){     // THE OTHER PROBLEM <-------------
    Motor.run(FORWARD);
  }
  else switch(results.value) != (case 0xFF906F:){    // THE PROBLEM <-------------
    Motor.run(RELEASE);
  } 
  
  
}

The problem is the if and else switch lines, The else switch line was, "else if switch(results.value) != (case 0xFF906F:){" but I changed it to "else". I need help I'm relatively new. What I am trying to do in the code is making it so if the receiver revives the information "case 0xFF906F:" then it performs and action with a motor, if the button is not being pressed anymore on the remote then the motor stops.

Simple startswith statment

new to powershell-

Trying get this stupid simple statement working, and I cant understand why it won't output the correct result..

        $asset = "get-wmiobject -class win32_computersystem | select Name"
        if ($asset.StartsWith("ME")) {
        echo "Asset tag is ok" }
        Else 
        { echo "Asset tag needs updating" }

For some reason, despite the result from the WMI query being "ME12345" for example, the startswith code outputs "asset tag needs updating"

Do I need to use a damn /F or something to make the IF statement work with the result from the WMI statement?

Thanks

boolean code is outputting 2 answers and dividing inputs

enter image description here

Im not sure what else to add

How to determine if a char is upper or lower case - Java [closed]

I'm trying to write a program that will, for each character in a user-inputted string, count if it is uppercase and display the amount of each afterwards. This code is very messy and weird because I'm still trying to figure out what to do. Here is the code right now:

public static void main(String[] args) {
       
        Scanner sc = new Scanner(System.in);
        String sentence = sc.nextLine();
        int a = sentence.length();
        int ind = 0;
        char letter = sentence.charAt(ind);
        int k, l;
        k = 0;
        l = 0;
        
        boolean up_or_low = Character.isUpperCase(letter);
        
        while (ind < a) {
            if (up_or_low == false) {
                k += 1;
                ind += 1;
                
            } else if (up_or_low == true) {
                l += 1;
                ind += 1;
            }
        }
        
        System.out.println(k + ", " + l);
    }
}

Also, if the code looks weird it might be because it is part of a larger program but I'm writing and testing each section independently. When I run this with a scanner in the if else statement. I can see that the program returns true or false correctly, but after the first character it displays the same thing every time (the same as the first one). Please help? Btw I'm new to this language.

Thanks in advance.

R Script Error: comparison (6) is possible only for atomic and list types Traceback:

I am trying to create a new variable called exp_error in the same dataset that takes the value “FALSE” whenever experience is negative, and “TRUE” otherwise. In the line that does this, I keep getting an error Message.

mutate(india04_new, exp = age - 18)
mutate(india04_new, exp_error = ifelse(exp > 0, "TRUE", "FALSE"))

Error message:

Error in exp > 0: comparison (6) is possible only for atomic and list types
Traceback:

1. mutate(india04_new, exp_error = ifelse(exp > 0, "TRUE", "FALSE"))
2. mutate.tbl_df(india04_new, exp_error = ifelse(exp > 0, "TRUE", 
 .     "FALSE"))
3. mutate_impl(.data, dots, caller_env())
4. ifelse(exp > 0, "TRUE", "FALSE")

array element duplicate count using convert array element to string matching the value and also get string value its possible?

function count5numbers1(arr){
 const m1 = arr.toString().match(/[5]/g);
 if (typeof m1 === 'string' || m1 instanceof String){
      return "it's not a number";
    }else if(m1 === null){
      return  0;
    }else{
      return m1.length;
    }
}
console.log(count5numbers1([1,2,5,43]));
console.log(count5numbers1([1,2,3,5]));
console.log(count5numbers1([1,2,4,2]));
console.log(count5numbers1([2,4,54,15]));
console.log(count5numbers1([1,5,55,555]));
console.log(count5numbers1([6,3,2,1]));
console.log(count5numbers1(['notnumber,its a string']));

I'm getting an answer is: [1,1,0,2,6,0,0]

But an expected answer is: [1,1,0,2,6,0, it's not a number]

how to handle error not enough values to unpack in for loop

In the following code user will enter single integer N as number of pairs that he should enter next as b. Assume the entered list is b=[('r', 1),('a', 1),('a', 2),('a', 1),('r', 1),('r', 2)] and the output should be B=[1].User will input data like below:

6
r 1
a 1
a 2
a 1
r 1
r 2

The code raised with error: 'not enough values to unpack (expected 2, got 1)'

N = int(input())
B=[]
for i in range(N):
    b = (input().split())
for (action, value) in b:
  if action == 'a':
    B.append(value)
  elif action == 'r':
    try:
      B.remove(value)
    except ValueError:
      pass

How do you make a while true loop continuedly check for a condition

def main():
    from playsound import playsound as play
    import datetime
    time=datetime.datetime.now()
    hour=int(input("Hour of alarm: "))
    minute=int(input("Minute of alarm: "))
    #sound chooser
    alarm=str(input("Alarm, PI, AC, AV, BE, ZE, IO: "))
    noise=""
    #sound files
    if alarm== "PI":
        noise="8D_Pure_Imagination.mp3"
    elif alarm=="AC":
        noise="8D_chill2_noise.mp3"
    elif alarm=="AV":
        noise="8D_avatar_clip.mp3"
    elif alarm=="BE":
        noise="8D_Beach.mp3"
    elif alarm=="ZE":
        noise="8D_zelda_clip.mp3"
    elif alarm=="IO":
        noise="8D_iroh.mp3"
    #sound player

    while 1==1:
        if time.hour == hour and time.minute == minute:
           play(noise)
        else:
            if time.hour==hour and time.minute== minute:
                play(noise)
        
main()

The problem is it checks for the statement once and so it works if you play it at the exact same time, i want it to be opened, and set an alarm, then play a sound at that time, but after checking the if statement once, it stops.

how can I minimize code function that find repeated values in Array of Objects in JavaScript

I need to fix this function, which must find two similar names in an array of object. I tried to do this, and it's work, but the test tells me that should be just only one loop and one if

function searchByName() {
    const values = [
        { name: 'Johny Walker', birthDate: '1995-12-17' },
        { name: 'Andrew', birthDate: '2001-10-29' },
        { name: 'Viktor', birthDate: '1998-11-09' },
        { name: 'Andrew', birthDate: '2011-05-09' }
    ];

    for (let obj of values) {
        for (let elem of values) {
            if (obj == elem)
                continue;
            if (elem.name === obj.name && elem.age === obj.age) {
                console.log(obj);
                break;
            }
        }
    }

};

here is the example that must come out

[
  { name: 'Andrew', birthDate: '2001-10-29' },
  { name: 'Andrew', birthDate: '2011-05-09' }
]

issue while using a !== with || operator in javascript [duplicate]

const value = 'shopper'
if (value != 'shopper' || value != 'admin' ){
throw new Error('Invalid selection')}

Some how in the code above, I always enter into the if block even as value= shopper. I suspect value != 'admin' always convert it to true and hence the if block runs. But i'm not quite sure.

How can I make one of the fields in admin.TabularInline conditional?

Is there a way how can I make one of the fields in admin.TabularInline conditional?

for example

class ParameterInline(admin.TabularInline):
    form = ParameterForm
    fields = ["ParameterA", "ParameterB"]

What if I wanted to display the ParameterB only if something else was set to, for example, True?

Thanks in advance.

while loop defaults to else statement. Java

I was assigned a bike shop assignment, where you would be able to rent or return a bike through this program. You to take into counter stock and such. It was very open ended so you could do what ever you felt would work, I don't have crazy great coding skills so I'm probably making it more complicated than it would be for someone else. My solution was to make do-while loop that would replay the same questions until we ran out of bikes and then display a different question when we had none. not everything is all planned out yet but I've run into a problem, every time the loop starts it defaults to the else statement without allowing user input and then loops again and lets you answer. I don't really know if that's a good explanation but ill leave my code and maybe you can help me.

import java.awt.Choice;
import java.util.Scanner;
public class bikeShop {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Scanner scan = new Scanner(System.in);
        int amount = 13;


        do 
        {
        System.out.println("Welcome to the bike shop. Are you here to rent a bike or return a bike? Please enter rent or return.");
        String choice = scan.nextLine();
        
        if (choice.equals("rent"))
        {
            System.out.println("Would you like to rent as a family (3-5 bike) or as an individual? Please enter family or individual.");
            String plan = scan.nextLine();
            
            if (plan.equals("individual"))
            {
            System.out.println("How long would you like to rent? you can rent by hours, days, and weeks. If none put 0. How any hours?");
            int hours = scan.nextInt();
            System.out.println("How any days?");
            int days = scan.nextInt();
            System.out.println("How any weeks?");
            int weeks = scan.nextInt();
            
            amount --;
            
            int total = (((hours * 5) + (days * 20) + (weeks * 60)));
            System.out.println("The total cost is: $" + total );
            }
            
            else if (plan.equals("family"))
            {
                System.out.println("How many people will you be renting for?");
                int people = scan.nextInt();
                if (people > 2 & people < 6 & people > amount)
                {
                    System.out.println("I'm sorry we don't have that many bikes in stock");
                }
                else if (people > 2 & people < 6)
                {
                System.out.println("How long would you like to rent? you can rent by hours, days, and weeks. If none put 0. How many hours?");
                int hours = scan.nextInt();
                System.out.println("How many days?");
                int days = scan.nextInt();
                System.out.println("How many weeks?");
                int weeks = scan.nextInt();
                
                amount = (amount - people);
                
                int time = ((hours * 5) + (days * 20) + (weeks * 60));
                int total = ( (((time * people)  * 70) / 100 ));
                System.out.println("The total cost is: $" + total);
                }
                else 
                {
                    System.out.println("Error, that is not a valid answer.");
                }
            }
            else
            {
                System.out.println("Error, that is not a valid answer.");
            }
        }
        
        else if (choice.equals("return"))
        {
            System.out.println("Which bike are you returning?");
        }
        else 
        {
            System.out.println("Error, that is not a valid answer.");
        }
        
        }
        while(amount > 0);
        
        
        if (amount == 0)
        {
            System.out.println("We are all out of bikes for now, are you returning a bike?");
            String returnBike = scan.nextLine();
            
            if (returnBike.equals("yes"))
            {
                System.out.println("Which bike are you returning?");
            }
            else if (returnBike.equals("no"))
            {
                System.out.println("We are all out of bikes for now.");
            }
            else
            {
                System.out.println("Error, that is not a valid answer.");
            }
        }
    }
}

NullPointerException in the IF statement with two negative conditions in Java + Selenium

I'm just starting to work with Java and Selenium and stuck with getting a NullPointerException in the following if statement when trying to switch to a third window opened. My test has two windows opened already. Each window has its handle saved into a variable.

Then this method LessonHeader.clickLessonPreview(); opens a third window that I need to switch to.

String windowLMS = ApplicationManager.driver.getWindowHandle();
String windowLD = ApplicationManager.driver.getWindowHandle();

 private void previewLesson() {
    WebDriverWait wait = new WebDriverWait(ApplicationManager.driver, 5);
    assert ApplicationManager.driver.getWindowHandles().size() == 2;
    LessonHeader.clickLessonPreview();
    wait.until(numberOfWindowsToBe(3));

    for (String windowHandle : ApplicationManager.driver.getWindowHandles()) {
      if (!windowLMS.contentEquals(windowHandle) && !windowLD.contentEquals(windowHandle)) {
        ApplicationManager.driver.switchTo().window(windowHandle);
        break;
      }
      wait.until(elementToBeSelected(By.id("titlestartbutton")));
    }
  }

The exception happens in this line: if (!windowLMS.contentEquals(windowHandle) && !windowLD.contentEquals(windowHandle)) {

How to specify the length of output lines in phyton

Im wondering how to make all the lines in a text to be like this

Hi im new
hey i sol

So the the output lines is the same length. Below is the the text not edited

In stead of like this:
Hi im new hey
i sol

Tried diffrent if solutions but could not manage to make it work

Time Limit exceeded ,how to write efficient code?

I had previously used array and then sorted but giving the same result. This is the link to problem https://www.spoj.com/problems/ARMY/

import java.util.Scanner;

public class main {

    public static void main(String args[])
    {
        
            Scanner s=new Scanner(System.in);
            int t=s.nextInt();      
            
            while(t-->0) {
                int temp1=-1;
                int temp2=-1;
                
                int temp=0;

                int ng =s.nextInt();
                int nm =s.nextInt();
                
                for(int i=0;i<ng;i++) {
                    temp=s.nextInt();
                    if(temp>=temp1) {
                        temp1=temp;
                    }
                }
                
                for(int i=0;i<nm;i++) {
                    temp=s.nextInt();
                    if(temp>=temp2) {
                        temp2=temp;
                    }
                }
                
                
                if(temp1>=temp2) {
                    System.out.println("Godzilla");
                }
                else {
                    System.out.println("MechaGodzilla");
                }
                

            }

   
    }

}

How to use goto without getting this error?

#include <stdio.h>

int main()
{
    repeat:
    printf("choose an option: \n1:Draw\n2:Even or Odd:\n3:Text type\n4:How to Dec\n5:Base to Dec:\n6:Count to Bits\n0:Exit\n"); 
    int x;
    scanf("%d", &x); 
    if (x > 6)
       printf("Wrong option!\n");
       goto repeat;
    if (x == 1) 
       printf("Drawing");
    if (x == 0)
       printf("we are out!\n");
    return 0;
}

I am using an online complier.

The end result I want to see is a simple menu that asks the user for input number and executes a code according to the number and then goes to the starting point and prints the menu again. (That's why I chose goto. If you have other solution that restarts the main program after an execution please tell me.)

The problem I encountered is that no matter the number I input, it outputs the menu again without the messages or without exiting (when I input 0).

I need to run the same line again in a for loop

So basically, I need to make a sort of sorting hat for a school project to see which study would best suit you. But whenever you give an invalid answer e.g. uncapitalized. It won't give you the points and goes to the next question. But I want it to give the same question again until a correct answer is given. Is this possible? It's pretty sad but I am forced to use the for loop to keep giving the question, otherwise I would have done it differently. Code:

import time
def vragen_ophalen():
    with open("C:\\Users\digit\PycharmProjects\pythonProject2\TXT\meerkeuzevragen.txt", "r") as fh:
        all_lines = fh.read()

    return all_lines;


def vraag_en_antwoord(q_a):
    se = 0  # Points for Software Engineer
    bdam = 0  # Points for Business DataManagement
    interactie = 0  # Points for Interaction Technology
    fict = 0  # Points for CSI ICT
    antwoorden = " "  # All Answers together for writing data
    vraagenantwoorden = ""  # All answers including Question No.
    vraagnummer = 1  # Question No.

    for line in q_a.split('#'):
        print(line)
        antwoord = input("Kies uit A, B, C of D: \n")
        if antwoord == "A":  # If the input given == "A" 1 point will be added to SE
            se = se + 1
        elif antwoord == "B":  # If the input given == "B" 1 point will be added to BDAM
            bdam = bdam + 1
        elif antwoord == "C":  # If the input given == "C" 1 point wil be added to Interaction Technology
            interactie = interactie + 1
        elif antwoord == "D":   # If the input given == "D" 1 point will be added to CSI ICT
            fict = fict + 1
        else:
            print("Antwoord niet mogelijk. Let op Hoofdletters!")  # Answer Not possible

        vraagenantwoord = f"{vraagnummer}. {antwoord}"  # Combining Question No. With answer
        vraagnummer = vraagnummer + 1  # Adding 1 to Question No. For next question
        vraagenantwoorden = f"{vraagenantwoorden} \n {vraagenantwoord}"  # Adds alls question and their Quesiton No. together
        with open("TXT\\antwoorden_gebruiker.txt", "w") as fd:
            fd.write(vraagenantwoorden)  # Writes all Answer and Question No. to TXT file
    main()

def main():
    run = input("Kies 1 voor Vragenlijst \n Kies 2 voor resultaten \n Kies q voor afsluiten \n")
    if run == "1":
        vraag = vragen_ophalen()
        vraag_en_antwoord(vraag)
    elif run == "2":
        with open("TXT\\antwoorden_gebruiker.txt", "r") as fr:
            print(fr.read())
    elif run == "q":
        exit()
    else:
        print("Onbekend Commando.")
        print("Herstarten in 5 seconden")
        time.sleep(5)
        main()



if __name__ == '__main__':
    main()

How comparison operator utilizes CPU cycle in programming

If I have following conditions then which comparison condition executes fast(in terms of CPU cycles and time):

if(1 < 2)

if(1 < 100)

Break out of two loops and two if statements - Python [duplicate]

I have a section of code used to find a key value within a dictionary. The current method i'm using works, however i'm attempting to speed up the execution of the script.

To do this i want to move the if ticker in tick: to immediately after for tick in trades_dic["Ticker"].items():. The intention of which is to speed up this element by removing the need to check all combinations.

Full section of code below, any help would be much appreciated. :)

    for tick in trades_dic["Ticker"].items():
        for stat in trades_dic["Status"].items():
            if ticker in tick and "Open" in stat:
                (tick_k, tick_val) = tick
                (stat_k, stat_val) = stat
                if tick_k == stat_k:
                    (active_k, v) = tick
                    break
        else:
            continue
        break

Expression must have arithmetic or unscoped emun type/ Objectname

      (10 == Battery0.BatteryLife());  //if battery is fully charged
      {
          cout << " Battery is full" << "\n" << endl;
          break;
      }
      if (0 == Battery0.BatteryLife()) //if battery is empty
      {
      {
          cout << " Battery is empty" << "\n" << endl;
          break;
      }
      if (1 < Battery0.BatteryLife() || Battery0.BatteryLife() < 9) //neither
        

I'm creating bluetooth product. I made the ObjectName equal to 10 but still get an error in the first if statement. May I ask what needs to change.

"Name Doesn't Match" print but here it printing 5 times

When I type something which isn't there in array list, "Name Doesn't Match" is printing for 5 times. I want to make this print for only one time.

  1. Which line of code is making "Name Doesn't Match" print 5 times?
  2. how to print "Name Doesn't Match" only 1 time?
public class Arrays {
    public static void main(String[] args) {

String[] names = {"Meisam", "Raju", "Sasi", "Aju", "Ram"};
        int[] numbers = {123456, 654321, 345678, 953456, 123445};
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }

        System.out.println("Please Enter a Name:  ");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.next();

        for(int i = 0; i < names.length; i++){
            if(name.equals(names[i])) {
                System.out.println(numbers[i]);
            } else {
                System.out.println("Names Doesn't Match!");
            }
            }
        }
    }
               

Output is:

Meisam
Raju
Sasi
Aju
Ram
Please Enter a Name:  
raj //input a keyword called 'raj' 
Names Doesn't Match!
Names Doesn't Match!
Names Doesn't Match!
Names Doesn't Match!
Names Doesn't Match!

mardi 29 septembre 2020

I'm trying to create a loop that will close down a form when a progressbar hits 100

I'm trying to make it so that if a checkbox is checked, and a progressbar hits 100, the application will close. The problem is that i need the progressbar1.value to be in a loop until the value hits one hundred.

after that it should close the application, but only if both the checkbox has been checked and the progressbar at 100

           timer1.Start();
            if (CheckBox1.Checked)
            if (progressBar1.Value == progressBar1.maximum)
                    Application.Exit();```

Javascript - If condition is met, return True for specific amount of time, then false

I'm trying to code a function that, if some conditions are met, it returns "true" for some time, then return false again, even if the condition is still true.

The idea of the code is something like this:

if(condition is met)
    {return 'True' for 3000ms then 'false'} //even if the condition it's still 'true'
        else {False}

I can easily program the result of the condition (returning true or false if met), but i'm having a lot trouble trying to (if true) returning it for a specific amount of time.

NOTE: a function with setTimeout() is not an option in this case.

Thanks!

VBA: nested With with If statement

Is nested With allowed in VBA? If it is, how to use it with IF statement?

I have the following nested With combined with If statement and compiler gave me an error message saying "End With without With".

With
If
    With
    End With
Else
    End With   <- End With without With
End If

I put the first With outside the IF statement because the IF statement can use it. Since the above code didn't work, I tried a different way. Another error message was obtained if I moved the first With inside the IF statement. This time, the error message says "Else without If". That leads me to wonder if nested With is allowed in VBA.

A google search turned up one hit, which is not exactly the same as my problem.

How to check elements of a list of variable length in an if statement python

I am new to python

I have a list of flags. and that list has a variable length. I want to check if all the variables in that list are true

I have tried

    if (all  in flags[x]==True):
    finalFlags[x-1]=True

But that turned the final flag true when only one flag is true

CSS manipulation in jQuery with if statement

$(document).ready(function(){
  var width = $(window).width();
  $(function(){
    if ( width < 800 ) {
          $(".navbar-brand").css({'margin-left':'0'});
      }else{
          $(".navbar-brand").css({'margin-left':'100px'});
      }
  });
});

Hello, I know it's basic and I should not to ask about something so simple, but I have struggled by myself long enough. What I am trying to do is to remove margin-left in navbar when the viewport width is smaller than 800px, I can do it simply by adding a class, but I really want to learn how to manipulate css, with the jquery.

I appreciate all your advice, thank you.

Is there a way to check for whether a substring is in a string in a Linux/Bash script with a short line usable in a conditional if statement?

I'm using

if[ "$wordCount" -gt 10 ]

To check if there are more than 10 words in the line, but how can I also check if a specific string, say "Brown Cow" is also within the line?

So the conditional should only work if the line has a wordCount of over 10 and contains the string "Brown Cow" within the $line string. Is there a way to do that within Linux/Bash? Or will I need a multi-line or different conditional like case to do it?

Ifelse for matrix in R

I have the following code below:

cenarios = 100 #

tamanho = 10000
prob_sin = 0.02
sev_med = 10000

replicacoes_ind = matrix(NA, tamanho, cenarios)

replicacoes_sev = matrix(NA, tamanho, cenarios)

SAg = array(NA, cenarios)

quant_sin = array(NA, cenarios)

u = matrix(data=runif(tamanho*cenarios, 0, 1), nrow=tamanho, ncol=cenarios)
ifelse(u <= prob_sin, {replicacoes_ind = 1; replicacoes_sev = rexp(1,rate = 1/sev_med)}, {replicacoes_ind = 0; replicacoes_sev = 0})

However in my last line (ifelse) what I intended to do is: if each element of the matrix u is <= than prob_sin, then the respective element of the replicacoes_ind matrix is ​​equal to 1 and the respective element of the replicacoes_sev matrix follows a number random. Otherwise, 0 in the respective elements. However, it assigns 1 or 0 to the matrices and transforms them into numbers.

Does anyone know how I can make this condition for each element of the matrices involved?

Thanks in advanced!

Different output when running a line inside vs. outside an ifelse() statement

I am trying to run a simple command but no idea why the output is different when running it inside vs outside an ifelse() function. The function condition evaluates to FALSE, so the output should be the exact same.

However, when running it alone, the output is 0 0 1 1 0 1 0 1 NA (as desired) but from the ifelse() function, the output is 0 (not desired).

library(dplyr)
library(zoo)

x <- c(0, 1, 1, 0, 0, 1, 0, 1, 0)
del <- 2

dplyr::lead(zoo::rollsum(x, del - 1, fill = NA, align = "left")) == 0
[1] FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE    NA

ifelse(del == 1, -1, dplyr::lead(zoo::rollsum(x, del - 1, fill = NA, align = "left")) == 0)
[1] FALSE

I would appreciate any help on why this is happening! Never seen something like this before. The outcomes of the ifelse() have different lengths depending on whether the condition is evaluated as true or false, but I don't see why this would cause a truncation of the longer output.

Print how many times appears a specific digit in a number

The return type is void and there is one input parameter and I am trying to use a while loop to print out how many of a certain number there is an the input integer.

So as an example int i = 32001; then I want too know how many 0's there are in the int and the output would be 2 cause there's only two 0's in that int.

My code below for some reason only outputs 0 and I don't know why. Could someone pls fix or help.

And please don't use any power tools or certain methods that do the work for you and you can use for loop or while loop.

public class loopPrr
{

public void howMany0(int i){
        
        
        int n = 0;
        int howmany = 0;
        char z = '0';
         while(i <= 0){
             ++i;
            if(i == z){
                howmany++;  
            }
        }
       
         System.out.println(howmany);
    }


public static void main(String args[]){
        
        loopPrr n = new loopPrr();
    
        
        n.howMany0(32001);
        
        
    
    
    }





}



JavaScript DOM: How do I tell JS to createElement('p') that says something according to the value in a json array?

how do I tell JS to createElement('p') that says survived if a boolean array value in a JSON says "1" and if it says "0" to say deceased? **I need it to create that p element that says "survived" if it the value "survived" in the JSON says 1 or "deceased" if it says 0. This is one of the many people in the JSON:

'use strict';
let passengers = [{
        "PassengerId": 1,
        "Survived": 0,
        "Pclass": 3,
        "Name": "Braund, Mr. Owen Harris",
        "Sex": "male",
        "Age": 22,
        "SibSp": 1,
        "Parch": 0,
        "Ticket": "A/5 21171",
        "Fare": 7.25,
        "Cabin": "",
        "Embarked": "S"
    },
//this is my DOM js:

 'use strict';
const seccCards = document.querySelector('#sctCards');
const inputFiltro = document.querySelector('#txtFiltro');
const imprimirCards = () => {
    seccCards.innerHTML = '';
    let filtro = inputFiltro.value.toLowerCase();
    passengers.forEach(obj_passenger => {
        if (obj_passenger.Name.toLowerCase().includes(filtro) || obj_passenger.PassengerId.toLowerCase().includes(filtro)) {
            let card = document.createElement('div');
            card.classList.add('card');
            let passengerbeen = document.createElement('h2');
            passengerbeen.innerText = obj_passenger.Name;
            let passengerF = document.createElement('p');
            if (obj_passenger.Survived == 1) {
                passengerF = sobrevivio;
            } else {
                passengerF = fallecido;
            }
            passengerF.innerHTML = obj_passenger.Survived;

            card.appendChild(passengerbeen);
            card.appendChild(passengerF);
            seccCards.appendChild(card);
        }

    });
};
inputFiltro.addEventListener('keyup', imprimirCards);
imprimirCards();


How do I add up all the numbers in the list box?

I want to add up all the numbers in the list box(while still keeping the numbers in it) after the while loop is completed.

    void Task3()
    {
        limit = Convert.ToInt32(tBNumber.Text);
        int finalN = limit + 100;
        int n = limit;
        int sum = 0;
        while (n < finalN )
        {
            if (n % 9 == 0)
            {
                lbAnswer.Items.Add(n);
                n++;
            }
            else
            {
                n++;
            }
        }
    }

Java Coding Help! Can't get if statement to confirm string

Write a program that prompts the user to provide a single character from the alphabet. Print Vowel or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.

I have been trying to solve this problem, and basically have it all figured out but have ran into two issues. How do I get the scanner to recognize an error if the user inputs a number rather than a letter. Also how would one not have to repeat their input. Is there a way to have the first if statement evaluate if the user entered a string?

import java.util.*;

public class MessAround {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Please Provide single character from the alphabet: ");
        String letter = scan.next();
        
        if (scan.hasNext())
        {
            letter = letter.toLowerCase();
            if (letter.equals("a") || letter.equals("e") || letter.equals("i") || letter.equals("o") || letter.equals("u"))
            {
                System.out.println("Vowel");
            }
            else if (letter.length() > 1)
            {
                System.out.println("Error");
            }
            else
            {
                System.out.println("Consonant");
            }
        }
        else
        {
            System.out.println("Error");
        }
    }

}

EXCEL VBA: Class Module Variables value location depending on if function

I have created a dictionary to combine several bits of data for one event. For example, NameA can have four entries depending on the value in column 5. It can be A, B, C, D. However i would like to display all this information from A, B, C, D on one row in a table for NameA as the end product.

So i have created a dictionary with a class module to show this, with the class listing all possible variables to display in final output. Depending on the entries (A, B, C, D) the value in column 1 can be equal to different variables in the class.

SO the dictionary will add one NameA but then if NameA is exists already, it will add the exisiting info for A, B, C, D to said values.

E.g. If entry A, the value is column 1 is equal to PQL, if entry B, the value is 1IW, if C, 2IW and D is PPL.

I have used an if function however when writing the data it will not write anything for the variables within the IF statements e.g. PQL, 1IW, 2IW and PPL, it just remains blanks for each NameA. As the varibales are not filled.

Whole module

Sub Dictionary()

Dim dict As Dictionary

Set dict = ReadData()

Call WriteDict(dict)

End Sub

Function ReadData()


Dim dict As New Dictionary

Dim DataWs As Worksheet: Set DataWs = ThisWorkbook.Sheets("DATA")
Dim PoolOfWeekWs As Worksheet: Set PoolOfWeekWs = ThisWorkbook.Sheets("Pool of the week")

Dim LastrowData As Long: LastrowData = DataWs.range("A" & Rows.Count).End(xlUp).row
Dim LastColData As Long: LastColData = DataWs.Cells(1 & DataWs.Columns.Count).End(xlToLeft).Column


Dim LastColDataString As String: LastColDataString = Split(Cells(1, LastColData).Address, "$")(1)

Dim DataRange As range: Set DataRange = DataWs.range("A1:" & LastColDataString & LastrowData)
Dim DataArr As Variant: DataArr = DataWs.range("A1:AO" & LastrowData)

Dim range As range: Set range = DataWs.range("A1").CurrentRegion

Dim i As Long
Dim CandidateProcessID As String, CandidateName As String, FirstName As String, ProcessStatus As String, FirstITWDate As String, PQLDate As String, XP As String, oCandidate As ClsCandidate

For i = 2 To range.Rows.Count
    If range.Cells(i, 35).Value <> "NOK" Then

        CandidateProcessID = range.Cells(i, 10).Value
        FirstName = range.Cells(i, 17).Value
        ProcessStatus = range.Cells(i, 9).Value
        CandidateName = range.Cells(i, 16).Value
        Nationality = range.Cells(i, 39).Value
        XP = range.Cells(i, 24).Value
        SalaryExpectation = range.Cells(i, 48).Value
        Email = range.Cells(i, 18).Value
        PhoneNum = range.Cells(i, 19).Value
        ROName = range.Cells(i, 46).Value
        YearsExp = range.Cells(i, 24).Value
        Sector = range.Cells(i, 48).Value
        ProcessType = range.Cells(i, 35).Value
        InterviewScore = range.Cells(i, 37).Value
        DetailedSkills = range.Cells(i, 28).Value
        SkillsSummary = range.Cells(i, 29).Value
        NameofCM = range.Cells(i, 44).Value
        ROName = range.Cells(i, 46).Value
         
        If range.Cells(i, 13) = "Prequalification" Then PQLDate = range.Cells(i, 11).Value

        If range.Cells(i, 13) = "Candidate Interview 1" Then
                FirstITWDate = range.Cells(i, 11).Value
                BM1ITW = range.Cells(i, 44).Value
                ProposedSalary = range.Cells(i, 48).Value
        End If
        If range.Cells(i, 13) = "Candidate Interview 2+" Then
                SecondITWDate = range.Cells(i, 11).Value
                ProposedSalary = range.Cells(i, 48).Value
        End If
        If range.Cells(i, 13) = "Candidate Interview 2*" Then
                PPLDate = range.Cells(i, 11).Value
                ProposedSalary = range.Cells(i, 48).Value
        End If

        If range.Cells(i, 13) = "Signature Interview" Then
                SignatureInterview = range.Cells(i, 11).Value
        End If
    
    If dict.Exists(CandidateProcessID) = True Then
        Set oCandidate = dict(CandidateProcessID)
            oCandidate.YearsExp = oCandidate.YearsExp
            oCandidate.NameofCM = oCandidate.NameofCM
            oCandidate.ROName = oCandidate.ROName
            oCandidate.DetailedSkills = oCandidate.DetailedSkills
            oCandidate.Nationality = oCandidate.Nationality
            oCandidate.CandidateName = oCandidate.CandidateName
            oCandidate.FirstName = oCandidate.FirstName
            oCandidate.PQLDate = oCandidate.PQLDate
    Else
        Set oCandidate = New ClsCandidate
        dict.Add CandidateProcessID, oCandidate
            oCandidate.YearsExp = oCandidate.YearsExp + YearsExp
            oCandidate.NameofCM = oCandidate.NameofCM + NameofCM
            oCandidate.ROName = oCandidate.ROName + ROName
            oCandidate.DetailedSkills = oCandidate.DetailedSkills + DetailedSkills
            oCandidate.Nationality = oCandidate.Nationality + Nationality
            oCandidate.CandidateName = oCandidate.CandidateName + CandidateName
            oCandidate.FirstName = oCandidate.FirstName + FirstName
            oCandidate.PQLDate = oCandidate.PQLDate + oCandidate.PQLDate
    End If
    
   
    
    End If

Next i

Set ReadData = dict


End Function

Sub WriteDict(dict As Dictionary)

    Dim key As Variant, oCandidate As ClsCandidate, row As Long
    Set rangeoutput = Sheets("Sheet1").range("A2").CurrentRegion
    row = 2
    
    For Each key In dict
        Set oCandidate = dict(key)
        'Debug.Print key, oCandidate.CandidateName, oCandidate.PQLDate, oCandidate.YearsExp, oCandidate.NameofCM, oCandidate.ROName, oCandidate.DetailedSkills, oCandidate.Nationality
        rangeoutput.Cells(row, 1).Value = oCandidate.Nationality
        rangeoutput.Cells(row, 2).Value = oCandidate.DetailedSkills
        rangeoutput.Cells(row, 3).Value = oCandidate.ROName
        rangeoutput.Cells(row, 4).Value = oCandidate.NameofCM
        rangeoutput.Cells(row, 5).Value = oCandidate.YearsExp
        rangeoutput.Cells(row, 6).Value = oCandidate.PQLDate
        rangeoutput.Cells(row, 7).Value = oCandidate.CandidateName
        rangeoutput.Cells(row, 8).Value = oCandidate.FirstName
        row = row + 1
    Next key

End Sub
```

Class moudle 

```
Option Explicit

Public CandidateProcessID As String
Public Status As String
Public PQLDate As Date
Public ProcessType As String
Public InterviewScore As String
Public CandidateName As String
Public FirstName As String
Public NameofCM As String
Public BM1ITW As String
Public FirstITWDate As Date
Public DetailedSkills As String
Public SkillsSummary As String
Public XP As Long
Public NP As String
Public Nationality As String
Public SalaryExpectation As Long
Public ProposedSalary As Long
Public SecondITWDate As Date
Public PPLDate As Date
Public Email As String
Public PhoneNum As Long
Public ROName As String
Public BusinessUnit As String
Public RecruiterTregram As String
Public Country As String
Public YearsExp As Long
Public Sector As String
Public SignatureInterview As Date
```

Cleanest possible if statements (but still understandable to any)?

I want to learn to write better if statements.

Let´s say I have this code:

if someBool == true {

let someStatement = String("This is not cool")
let textCell = someTableViewCell

textCell.textlabel?.text = (" \(dateFormatter.string) \(someStatement)")

}

else {

if someBool == true {

let someStatement = String("This is cool")
let textCell = someTableViewCell

textCell.textlabel?.text = (someStatement)

}

I can imagine myself doing exactly this even with multiple lets and textcell etc. The code would be so long.

What are other, better ways to do it?

Why does this Google Sheets IF statement return "#Value" instead of "0"

I have a pretty simple IF statement in my google sheet:

=IF(SEARCH("PM",K2)>0,1,0)

Basically, I'm asking if cell K2 has "PM" in it. K2 is a time in the format of "H:MM:SS AM/PM". When this returns true, it gives me a value of "1", otherwise it gives me "#VALUE" with an error of

In SEARCH evaluation, cannot find 'PM' within '8:02:48 AM'.

Why the heck won't this return as "0"?

Can you check where I went wrong? Sharing my syntax [closed]

for nuc in DNA:
  if nuc == "A": 
    A_count = A_count+1
  print(A_count)
  elif nuc == "T": 
    T_count = T_count+1
  print(T_count)
  elif nuc == "G": 
    G_count = G_count+1
  print(G_count)
  elif nuc == "C": 
    C_count = C_count+1
  print(C_count)
  else:
    print("na")

Can someone explain why my luhn's algo fails?

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

short unsigned int numlen(unsigned long long n);
bool isValidCC(unsigned long long int n);
unsigned short int first_n_nums(unsigned short int n, unsigned short int x);


int main(void) 
{
    unsigned long long num = 0;
    num = get_long("Enter your card number ");
    
    if(numlen(num) == 15 && (first_n_nums(num, 2) == 34 || first_n_nums(num, 2) == 37) && isValidCC(num) == true)
    {
        printf("AMEX\n");
    }
    else if((numlen(num) == 13 || numlen(num) == 16)  && first_n_nums(num, 1) == 4 && isValidCC(num) == true)
    {
        printf("VISA\n");
    }
    else if(numlen(num) == 16 && (first_n_nums(num, 2) == 51 || first_n_nums(num, 2) == 52 || first_n_nums(num, 2) == 53 || first_n_nums(num, 2) == 54 || first_n_nums(num, 2) == 55)  && isValidCC(num) == true)
    {
        printf("MASTERCARD\n");
    }
    else
    {
        printf("INVALID\n");
    }

    
}

unsigned short int first_n_nums(unsigned short int n, unsigned short int x)
{
    while(n > pow(10,x))
    {
        n /= 10;
    }
    return n;
}    
    
   

short unsigned int numlen(unsigned long long n)
{
    short unsigned int count = 0;
    while (n !=0)
    {
        n /= 10;  //removes last digit
        count++; //counts the num of digits removed
    }
    return count;
}

bool isValidCC(unsigned long long int n)
{

    // take user input and add elements to array in reverse
     int arr1[(numlen(n))]; // declares but can't Initialize an array of n ;
     
     for (int i = 0; i < (int)sizeof(arr1)/sizeof(int) ; i++)
    {
        arr1[i] = 0;
    }
    
    for (int i = 0 ; i <(int) (sizeof(arr1)/sizeof(int)) ; i++)
    {
        arr1[i] = n % 10; //Appends last digit to an array
        n /= 10; // removes that last digit
    }
    
    
    // since arr1 = x digits long, arr2 is every second digit so its x/2 long 
     int arr2[((sizeof(arr1)/sizeof(int))*2)];
    
    //initializing garbage data to 0
    for (int i = 0; i < sizeof(arr2)/sizeof(int) ; i++)
    {
        arr2[i] = 0;
    }
    
    // multiplies, seperates, and sums arr2 elements
    int sum_of_arr2 = 0;
    for (int i = 1,  a = 0,  b = 0 ; i < (sizeof(arr1)/sizeof(int)) ; i += 2) // sizeof(array) = n of elements * sizeof(type of n)
    {
        a = arr1[i] * 2;
        if( a > 9)
        {
            b = a % 10;
            a /= 10;
            arr2[i] = b;
            sum_of_arr2 += b;
        }
        arr2[i-1] = a; // cz i currenrly is one idex ahead
        sum_of_arr2 += a;
    }
    
    // adds other elements of arr1 to sum_of_arr2
    for (int i = 0 ; i < (sizeof(arr1)/4) ; i += 2) // sizeof(array) = n of elements * sizeof(type of n)
    {
        sum_of_arr2 += arr1[i];
    }
    
    // returns true or false
    if (sum_of_arr2 % 10 != 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

Can someone pls explain why this fails for values like:

371449635398431 - expected "AMEX\n", not "INVALID\n"

5555555555554444 - expected "MASTERCARD\n", not "INVALID\n"

5105105105105100- expected "MASTERCARD\n", not "VISA\n"

4111111111111111 - expected "VISA\n", not "INVALID\n"

4222222222222 - expected "VISA\n", not "INVALID\n"

IFELSE does not recognize negative numbers

I have a dataframe with latitude and longitude. I have an other dataframe with the code of each 5x5 grid, and a column with the lat max and min and lon max and min for each grid. I want to create a new column in my first dataframe, called "cuad55", using the limits for each grid from the dataframe B, that is, I want to assing the grid code from my B dataframe, to my A dataframe, using lat y lon of A and limits from B:

sample of dataframe A (CALLED "plantados_totales"):

POINT || LATITUDE || LONGITUDE
1        0.933333     49.3667
2        4.250000     52.1500
3       -49.83333     49.8333
4       -34.35000     53.3667

sample of dataframe B (CALLED "cuadrícula"):

CUADRÍCULA || LAT MIN || LAT MAX || LON MIN || LON MAX
100045           0           5         45         50
100050           0           5         50         55
245045          -50         -45        45         50
230050          -35         -30        50         55 

I executed this code:

plantados_totales$cuad55 <- ifelse((plantados_totales$latitude > cuadricula$latmin & plantados_totales$latitude < cuadricula$latmax & plantados_totales$longitude > cuadricula$lonmin & plantados_totales$longitude < cuadricula$lonmax ), cuadricula$cuadricula, "NA")

But when I check the result, R only assign the correct grid code when the latitude is positive. When it's negative, R assign "NA":

POINT || LATITUDE || LONGITUDE || cuad55
1        0.933333     49.3667     100045
2        4.250000     52.1500     100050
3       -49.83333     49.8333       NA
4       -34.35000     53.3667       NA

All my data are in numeric format... does anyone have any idea what may be going on?

Thank you in advance!! Regards!

How i print only one number between 1 and 1000

I want the program print one number only between 1 and 1000, not many numbers.

String RollingDice = input.next();
if (RollingDice.eqauls("Yes") || RollingDice.eqauls("yes")){
    Random rn = new Random();
    for (int i=1 ; i<= 1000; i++){
        int answer = rn.nextInt(10)+1;
        System.out.println(answer);

How would I write this using if-else statements in java?

Problem:

You have a group of friends coming to visit for your high school reunion, and you want to take them out to eat at a local restaurant. You aren’t sure if any of them have dietary restrictions, but your restaurant choices are as follows:

Joe’s Gourmet Burgers—Vegetarian: No, Vegan: No, Gluten-Free: No

Main Street Pizza Company—Vegetarian: Yes, Vegan: No, Gluten-Free: Yes

Corner Cafe—Vegetarian: Yes, Vegan:Yes, Gluten-Free: Yes

Mama’s Fine Italian—Vegetarian: Yes, Vegan: No, Gluten-Free: No

The Chef’s Kitchen—Vegetarian: Yes, Vegan: Yes, Gluten-Free: Yes

Write a program that asks whether any members of your party are vegetarian, vegan, or gluten-free, then display only the restaurants that you may take the group to.

looping through outlook emails to update excel spreadsheet by finding specific string in email body

i am trying to loop through the sent folder in outlook and update my spreadsheet with the 'received time" of an email..my spreadsheet has a column that contain record number, each emails contain one or more record numbers, if the email body has a matching record then i want to extract the received date and put it in a column, i believe the issue is with my If statement :


 
Option Explicit

 

Private Sub CommandButton1_Click()

    On Error GoTo ErrHandler

   

    ' Set Outlook application object.

    Dim objOutlook As Object

    Set objOutlook = CreateObject("Outlook.Application")

   

    Dim objNSpace As Object     ' Create and Set a NameSpace OBJECT.

    ' The GetNameSpace() method will represent a specified Namespace.

    Set objNSpace = objOutlook.GetNamespace("MAPI")

    

    Dim myFolder As Object  ' Create a folder object.

    Set myFolder = objNSpace.GetDefaultFolder(olFolderSentMail)

   

    Dim objItem As Object

    Dim iRows, iCols As Integer

    Dim sFilter As String

    iRows = 2

    Dim MyRange As Range

    Dim cell As Range

    Dim Wb As Workbook

    Dim FiltRange As Range

   

     Workbooks("RIRQ and RRTNs with LOB Sept 28 2020").Activate

    'Set MyRange = Workbooks("RIRQ and RRTNs with LOB Sept 28 2020").Worksheets("Data").Range(Cells(1, 1).Offset(1, 0), Range("A1").End(xlDown))
    
    
    ' select the records in column A
    Set MyRange = Workbooks("RIRQ and RRTNs with LOB Sept 28 2020").Worksheets("Data").Range(Cells(2, 1), Range("A1").End(xlDown))

        'Debug.Print MyRange.Address
    'only select the filtered records
    Set FiltRange = MyRange.SpecialCells(xlCellTypeVisible)

    'Debug.Print FiltRange.Address

   

    
    'create a filter for emails marked as not completed
    sFilter = "[Categories] = 'Not Completed'"

    'Debug.Print sFilter

    ThisWorkbook.Sheets("Sent_Email").Activate

    ' Loop through each item in the folder.

    'Debug.Print myFolder.Items.Restrict(sFilter).Count
    
    'loop through the emails in the sent folder restricted to specific category
    For Each objItem In myFolder.Items.Restrict(sFilter)

        If objItem.Class = olMail Then

       

            Dim objMail As Outlook.MailItem

            Set objMail = objItem

 
            'extract data from email
            Cells(iRows, 1) = objMail.Recipients(1)

            Cells(iRows, 2) = objMail.To

            Cells(iRows, 3) = objMail.Subject

            Cells(iRows, 4) = objMail.ReceivedTime

            Cells(iRows, 5) = objMail.Body

            'If MyRange <> "" Then
                
                'loop throug the records on the spreadsheet to find matches
                For Each cell In FiltRange

                    'Debug.Print MyRange.Find(cell.Value)

                'Debug.Print cell.Value

                'Debug.Print Cells(iRows, 5)

                    'if the email body contain the matching record or specific string then copy the received time to the row for the matching record

                    If InStr(LCase(Cells(iRows, 5)), cell.Value > 0) And InStr(LCase(Cells(iRows, 5)), LCase("GTPRM")) > 0 Then

                        

                        Debug.Print cell.Value

                        cell(, 35).Value = Cells(iRows, 4).Value

                    End If

                Next cell

               

            'End If

           

        End If

        iRows = iRows + 1

    Next

    Set objMail = Nothing

  

    ' Release.

    Set objOutlook = Nothing

    Set objNSpace = Nothing

   Set myFolder = Nothing

ErrHandler:

    Debug.Print Err.Description

End Sub

Katalon Recorder : If variable contains some text - True/False

In Katalon Chrome addon or Selenium Chrome addon, I'm trying to set up a simple check to verify if an element contains a specific text.

Here is what I've done so far :

Katalon Recorder:

Command | Target | Value

click | id=subscribed |

StoreText | id=subscribed | i

echo | ${i}

verifyText | id=subscribed | alyx

Log result :

[info] Executing: | click | id=subscribed | |

[info] Executing: | storeText | id=subscribed | i |

[info] Store 'alyx.vance' into 'i'

[info] Executing: | echo | ${i} | |

[info] Expand variable '${i}' into 'alyx.vance'

[info] echo: alyx.vance

[info] Executing: | verifyText | id=subscribed | alyx |

From here, how can I set up this? :

If VerifyText = alyx (Contains) => Goto Label X (True)

If VerifyText != alyx (Not Contains) => Goto Label Y (False)

Thank you for your help.

if flag = 0, then which will be the most preferable statement to execute the true or false block? if(!flag) or if(flag == 0)

In the code given here:

void search(int a)
{
    int i = 0, flag = 1;
    for(; i < MAX; i++)
    {
        if(a == stack[i])
        {
            flag = 0;
            break;
        }
    }

    if(!flag)
        printf("%d found at location %d.\n", a, i);
    else
        printf("%d not found in the stack.\n", a);
    return;
}

which statement if(!flag) or if(flag == 0) will be more efficient and generalized? Is using if(!flag) considered as a wrong approach?

find the duplicate element count using array element and array string

I'm passing an array element and array string in a single function and convert into a string and find duplicate element count.

function count5numbers1(arr, arr1) {
  let m1 = arr.toString().match(/[5]/gi);
  let m2 = arr1.toString().match(/[5]/gi);
  if (m1 === null && m2 != null) {
    return m1 = 0;
  } else if (m1 != null) {
    return m1.length;
  } else if (m2 === null) {
    return m2 = "it's not a number";
  } else {
    return m2.length;
  }
}
console.log(count5numbers1([1, 2, 5, 43], [5]));
console.log(count5numbers1([1, 2, 3, 5], [5]));
console.log(count5numbers1([1, 2, 4, 2], [5]));
console.log(count5numbers1([2, 4, 54, 15], [5]));
console.log(count5numbers1([1, 5, 55, 555], [5]));
console.log(count5numbers1([6, 3, 2, 1], [5]));
console.log(count5numbers1(['notnumber,its a string'], []));

But I need to use a single parameter only m1 getting the same result.

The result will be: 1 1 0 2 6 0 it's not a number

Pine Script - If statement with a plot

I am new to Pine Script but hoping to get some assistance with two IF statements and based on the outcome I need to plot a flat line for the week (Monday to Friday), the following week the Marker (see below) should re-calculate.

pLevel = (prevHighHTF + prevLowHTF + prevCloseHTF) / 3
r1Level = (pLevel - prevLowHTF) + pLevel
s1Level = pLevel - (prevHighHTF - pLevel)


//Marker Calculations
// Close above Pro_High on Friday
if prevCloseHTF[1] > r1Level[1]
    Marker = r1Level - ((r1Level - prevCloseHTF) * 0.55)

//Close Below Pro_Low on Friday
if prevCloseHTF[1] < s1Level
    Marker = ((prevCloseHTF - s1Level) * .55) + s1Level

Using this code, How can I plot the Marker on Monday as a single line and recalculated the following week?

lundi 28 septembre 2020

Create a column in MySQL that automatically fills 0 or 1 based on presence of substring on previous column

I have this database at MySQL that has, among others, the following columns: Country, Level and Branch. I would like three new columns to this database indicating wether there's a comma (1) or not (0) on each of this three columns. Like this: example

I want these columns to be automatic, so new observations can be added to the table without the need of running the same script again and again to update the values shown there. I know how to do this in excel with IF functions, but I got stuck on MySQL. I have tried this:

alter table countries
add bol_coutnry int GENERATED ALWAYS AS (if(`COUNTRY` LIKE '%{$,}%',1));

among other variations of the same code but didn't even run. Any ideas? Thanks

(JAVA) Is there a more efficient way to do this?

This part of my program asks the user to enter the number of drinks they want and it must return "Invalid amount" if the number of drinks is negative.

System.out.print("Please enter the number of each drink that you like to purchase:");
System.out.println();
        
System.out.print("Small Coffee: ");
int smallCoffee = scnr.nextInt();
if (smallCoffee < 0) {
    System.out.println("Invalid amount")
    System.exit(1);
}
System.out.print("Medium Coffee: ");
int mediumCoffee = scnr.nextInt();
        
System.out.print("Large Coffee: ");
int largeCoffee = scnr.nextInt();
        
System.out.print("Banana Berry Smoothie: ");
int berrySmoothie = scnr.nextInt();
        
System.out.print("Mocha Shake: ");
int mochaShake = scnr.nextInt();
        
System.out.print("Raspberry Green Tea: ");
int greenTea = scnr.nextInt();

Instead of putting an if-statement under each option, is there any other way I can output "invalid amount" under each option?

Why won't my IF-ELSE-IF statement work correctly?

I am trying to create a simple Blackjack game in Java. I have a menu with possible integer options from 1-4. If the user inputs an integer greater than 4, my IF statement needs to print "invalid integer" and then restart the game. If the user inputs a negative value, my ELSE-IF statement needs to do the same thing.

However, the statements will only work once, so I can't get "invalid integer" to print if I input values below 0 and values greater than 4 multiple times/back-to-back.

Code:

System.out.print("1. Get another card\n" +
        "2. Hold hand\n" +
        "3. Print statistics\n" +
        "4. Exit\n" + "Choose an option: ");
userOpt = scnr.nextInt();

if (userOpt > 0) {
    switch (userOpt) {
        case 1:
            if (playerHand == 21) {
                System.out.println("BLACKJACK! You win!");
                playerWins++;
                gameCounter++;
                System.out.println("START GAME #" + gameCounter);
                playerHand = 0;
            } else if (playerHand > 21) {
                System.out.println("You exceeded 21! You lose!");
                dealerWins++;
                gameCounter++;
                System.out.println("START GAME #" + gameCounter);
                playerHand = 0;
            }
            break;
        case 2:
            dealer = generatedNumber.nextInt(11) + 16;
            if (dealer > 21) {
                System.out.println("You win!");
                playerWins++;
                gameCounter++;
                System.out.println("START GAME #" + gameCounter);
                playerHand = 0;
            } else if (dealer == playerHand) {
                System.out.println("It's a tie! No one wins!");
                tieGames++;
                gameCounter++;
                System.out.println("START GAME #" + gameCounter);
                playerHand = 0;
            } else {
                System.out.println("Dealer wins!");
                dealerWins++;
                gameCounter++;
                System.out.println("START GAME #" + gameCounter);
                playerHand = 0;
            }
            break;
        case 3:
            System.out.println("Number of Player wins: " + playerWins);
            System.out.println("Number of Dealer wins: " + dealerWins);
            System.out.println("Number of tie games: " + tieGames);
            System.out.println("Total # of games played is: " + gameCounter);

            double playerwinsNew = playerWins;
            percentage = (((playerwinsNew * 100)) / (gameCounter));
            System.out.println("Percentage of Player wins: " + percentage + "%");
        case 4:
            break;
        default:
            System.out.println("Invalid input!\n" + "Please enter an integer value between 1 and 4.");
            System.out.print("1. Get another card\n" +
                    "2. Hold hand\n" +
                    "3. Print statistics\n" +
                    "4. Exit\n" + "Choose an option: ");
            userOpt = scnr.nextInt();
            continue;
    }
} else if (userOpt < 0) {
    System.out.println("Invalid input!\n" + "Please enter an integer value between 1 and 4.");
    System.out.print("1. Get another card\n" +
            "2. Hold hand\n" +
            "3. Print statistics\n" +
            "4. Exit\n" + "Choose an option: ");
    userOpt = scnr.nextInt();
    continue;
}

Any help is appreciated.

How do I get my code to calculate a value from javascript and display the answer in html?

I am trying to create a code that calculates the ddf (daily water flow) from a household based on the type of household, number of bedrooms, number of occupants, and floor area. Right now I have completed code for a single family with any number of bedrooms and occupants (no code for floor area yet and other types of homes). But it is not showing the answer or calculating it. P.S. the if statements are based on guidelines for calculating water flow based on the info. Any help would be greatly appreciated.

<input type="number" id="bedrooms" placeholder="Number of Bedrooms" />
<input type="number" id="occupants" placeholder="Number of Occupants" />
<input type="number" id="area" placeholder="Floor Area (m&sup2)"/>


<select name="type of residence" id="residence">
  <option value=""disabled selected>Select the Type of Residence</option>
  <option value="single">Single Family Dwelling</option>
  <option value="multi">Multi Family</option>
  <option value="luxury">Luxury Home</option>
  <option value="cottage">Seasonal Cottage</option>
  <option value="mobile">Mobile Home</option>
</select>

<button onclick="calcDDF()">Calculate DDF</button>

<script>
function calcDDF() {
var ddf=0;
let bedrooms=document.getElementsById("bedrooms").innerHTML;
let occupants=document.getElementsById("occupants").innerHTML;
let residence=document.getElementsById("residence").innerHTML;

if (residence = single) {

  if (bedrooms == 1 && occupants == 2 || occupants == null) {
    ddf=700;
  }
  if (bedrooms == 1 && occupants > 2) {
    ddf=occupants*350;
  }
  if (bedrooms == 2 && occupants == 3 || occupants == null) {
    ddf=1000;
  }
  if (bedrooms == 2 && occupants > 3) {
    ddf=occupants*350;
  }
  if (bedrooms == 3 && occupants == 3.75 || occupants == null) {
    ddf=1300;
  }
  if (bedrooms == 3 && occupants > 3.75) {
    ddf=occupants*350;
  }
  if (bedrooms == 4 && occupantss == bedrooms + 0.5 || occupants == null) {
    ddf=1600+((bedrooms-4)*300);
  }
  if (bedrooms => 4 && occupants > bedrooms + 0.5) {
    ddf=occupants*350;
  }
}
  document.getElementById("ddf").innerHTML = ddf;
}
</script>

How would I fix this 'if' statement error?

I'm trying to make a BMI calculator for health class. I don't have any of the calculations yet, as I'm just testing the menu in the beginning. for some reason, every time I try to run the code, it shows me an error (shown below the code I have so far). I'm new to python, so this seems like a rookie mistake. if you could please help, that would be great.

*my code below

    ans = input('''
***The Body Mass Index***
    1. I use Kilograms and Metres
    2. I'M AMERICAN!!!
    ''')
if ans==1
    m = input("Your height in Metres")
    kg = input("Your weight in Kilograms")
if ans==2
    print("Stawp yelling at me!!")
    inc = input("Your height in Inches")
    lbs = input("Your weight in Pounds")
else
    print("please try again with a valid input")

the error appears after the first if statement:

 if ans==1

could not convert string to float: ' ' [closed]

ive looked at other questions and they seem to have to do with text more than a space (''). my error im getting is

could not convert string to float

I'm confused on how to make the previous answer equal to num1 when num2 doesnt get an answer. so lets say you do addition, 5+5, now prevAnswer is 10, when doing lets say subtraction next and make num1 = 5, it will calculate 5-10 instead of 10-5. i have no idea what to try and play around with values and position of code because when i do that it just creates more errors.

def isExitCommand(userInput):
return (userInput == 'exit' or userInput == 'stop' or userInput == 'Exit' or userInput == 'EXIT' or userInput ==
        'Stop' or userInput == 'STOP')


def calc_exponent(num, pow):
result = 1
for i in range(pow):
    result = result * num
return result


while True:
operator = str(input("Would you like to add(+), subtract(-), multiply(*), divide(/) or use exponents(**)? "))

if isExitCommand(operator):
    break

num1 = input("Enter number 1: ")
if isExitCommand(num1):
    break
else:
    num1 = float(num1)

num2 = input("Enter number 2: ")
if num2 == '':
    num1 = num2
    num1 = prevAnswer

if isExitCommand(num2):
    break

else:
    num2 = float(num2)

    if operator == 'add' or operator == '+':
        answer = num1 + num2
        print(num1, '+', num2, '=', answer)

    elif operator == 'subtract' or operator == '-':
        answer = num1 - num2
        print(num1, '-', num2, '=', answer)

    elif operator == 'multiply' or operator == '*':
        answer = num1 * num2
        print(num1, '*', num2, '=', answer)

    elif operator == 'divide' or operator == '/':
        answer = num1 / num2
        print(num1, '/', num2, '=', answer)

    elif operator == 'exponents' or operator == '**':
        num1 = int(num1)
        num2 = int(num2)
        answer = calc_exponent(num1, num2)
        print(num1, '**', num2, '=', answer)
    else:
        print('Please type a valid operator...')

    prevAnswer = answer

print('Program has exited due to user input.')

JSON script enhancement

How can I enhance this, I would like this action to only happen if CurrentField is equal to 'Registrat'

{ "$schema": "https://ift.tt/2SbrTHr", "elmType": "a", "txtContent": "@currentField", "attributes": { "target": "_blank", "href": "='https://ift.tt/348yKGC', + @currentField"

} }

random numbers from 1 to 100 and print the first input parameter number

The return type is void and the input parameter is int. I had to generate random numbers from 1 to 100 using Math.random() and using a while loop only and continually print out the first input parameter number with how many even numbers there were.

Ex: prtEven(5) will print out the following even integers: 56 8 12 76 44

My code prints out numbers put it isnt random, it doesnt print out the input parameter number first, and for some reason it does not output the correct number of even numbers. Could someone pls help me. While Loop only

public class MeLoop
{
    
    public int a, b;
    public String str;

public void prtEven(int d){
        
        int count = 0;
        int number = d;
        int sumEven = random % 2;
        while(count <= 100){

            int random = (int)(Math.random()*100);
            
            count++;
            System.out.print(count + " ");

        }
        if(sumEven == 0){
             
             System.out.println("\tThere are: " + sumEven + " even numbers");
            }
        
        
    }

}



 

Confused by use of If-else

I'm running this piece of code in a compiler:

def main():
  print("This program will produce a letter grade equal to the numerical exam score given")

  int(input("Input numerical grade score:"))

  grade=["A","B","C","D","F"]
  
  if grade>=90:
    return 'A'
  if grade>=80:
    return 'B'
  if grade>=70:
    return 'C'
  if grade>=60:
    return 'D'
  else:
    return 'F'
 
  print("The letter grade for this score is:",grade)

main()

Whenever I try and put a numerical score in, I get this error:

This program will produce a letter grade equal to the numerical exam score given
Input numerical grade score:55
Traceback (most recent call last):
  File "main.py", line 21, in <module>
    main()
  File "main.py", line 8, in main
    if grade>=90:
TypeError: '>=' not supported between instances of 'list' and 'int'

I have no idea what it's trying to say to me or how to fix it

How to change a style of an element in React.js in onClick function

I am trying to change the color of list elements in my conditional rendering in react.js.

onClick={exist ? () => {this.handleClick(); this.props.updateSummary(store_id)} : null }

I want to have style="color :#E8E8E8" and not :null. It seems like I can not use inline styling in onClick function while doing conditional rendering. Any ideas how to do it? Thank you

<ul>
   {this.props.stores.map(({exist, store_id}) => (
      <li className ="storeIdList" onClick={exist ? () => {this.handleClick(); this.props.updateSummary(store_id)} : null }>Store Id: {store_id}</li>
   ))}
</ul>

Simple Calculator problem Runtime Error (java)

I'm pretty new to Java coding and I code this Simple Calculator and it works perfectly in my IDE but it shows Runtime Error when I put in the online judge system. Very appreciated If you can provide any helps on this!

import java.util.Scanner;
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        Scanner calc = new Scanner(System.in);
        String operator1, operator2;
        int firstNum, secondNum;

        ArrayList<String> equation = new ArrayList<>();

        while(true) {

            String temp = calc.nextLine();
            if(temp.equals("0"))
                break;
            equation.add(temp);

        }
        for(String temp:equation) {
            if(temp.contains(" + ")) {
                operator1 = temp.substring(0,temp.indexOf('+'));
                operator2 = temp.substring(temp.indexOf('+')+1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum + secondNum);
            }
            if(temp.contains(" * ")) {
                operator1 = temp.substring(0, temp.indexOf('*'));
                operator2 = temp.substring(temp.indexOf('*') + 1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum * secondNum);
            }
            if(temp.contains(" - ")) {
                operator1 = temp.substring(0,temp.indexOf('-'));
                operator2 = temp.substring(temp.indexOf('-')+1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum - secondNum);
            }
            if(temp.contains(" / ")) {
                operator1 = temp.substring(0,temp.indexOf('/'));
                operator2 = temp.substring(temp.indexOf('/')+1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum / secondNum);
            }
        }
        System.out.println("Bye");
    }

}

What alternative can I use for onClick in my JavaScript quiz?

After working very hard on a JavaScript quiz, I found out (cause of my own stupidity) that I cannot use JavaScript in HTML (in this case that would mean not using the onclick function). We would have to use id's and classes, but onClick is not allowed. Since I am a beginner in JavaScript, I would not know how I could code this without using onClick. I could use a addEventListener pressing the right button, but how would I let it know what question the user is on and which answer is right if let the questions and anwsers be read out of arrays.

Please take a look at my code down below, I made some comments what functions do. Please notice that I suffer from PDD/NOS, so I might not be able to word what I mean properly or understand what some of you guys are saying. Thank you for understanding.

var buttonA = document.getElementById('buttonA'); //This is a variable to the buttons
var buttonB = document.getElementById('buttonB');
var buttonC = document.getElementById('buttonC');
var buttonD = document.getElementById('buttonD');
var quizQuestionDesign = document.getElementsByClassName('btn-quizquestiondesign'); //Class for all buttons for the design
var answerOutput = document.getElementById('checkedAnwser');
var questions = ["What does CSS stand for?", "Which from these options cannot be used in a variable name"];
var currentQuestion = document.getElementById('question');
var scoreDisplay = document.getElementById('scoreDisplay');
var nextButtonDisplay = document.getElementById('nextButton');
var questionCount = 1; //the question count begins here
var scoreCounter = 0; //We count the score beginning from the value 0
var questionImage = document.getElementById('questionImage'); //Images or gifs to make the quiz entertaining
var choice1 = ["<button class=btn-quizquestiondesign style=cursor:pointer onclick=question1Incorrect()>Central Styling Systematic</button>",
    "<button class=btn-quizquestiondesign style=cursor:pointer onclick=question2Correct()>Hashtags</button>"
];
var choice2 = ["<button class=btn-quizquestiondesign style=cursor:pointer onclick=question1Correct()>Cascading Style Sheet</button>",
    "<button class=btn-quizquestiondesign style=cursor:pointer onclick=question2Incorrect()>Underscores</button>"
];
var choice3 = ["<button class=btn-quizquestiondesign style=cursor:pointer onclick=question1Incorrect()>Central Structured System</button>",
    "<button class=btn-quizquestiondesign style=cursor:pointer onclick=question2Incorrect()>Letters</button>"
];
var choice4 = ["<button class=btn-quizquestiondesign style=cursor:pointer onclick=question1Incorrect()>Caring Style Sheet</button>",
    "<button class=btn-quizquestiondesign style=cursor:pointer onclick=question2Incorrect>Numbers</button>"
];
var correctFeedback = ["Wow you're smart", "Right!"];
var negativeFeedback = ["Too bad", "Nope"];

function addButtonActions() {
    var startButton = document.getElementById('button-start');
    var questionsButton = document.getElementById('button-questions');

    startButton.addEventListener("click", function() {
        showStartPage();
    });
    questionsButton.addEventListener("click", function() {
        showQuestionsPage();
        firstQuestionDisplay(); 
        startButton.style.display = 'none';
        questionsButton.style.display = 'none'; //If the start and GENERAL question for info and stuff will disappear, so people cannot cheat.
    });

}

function firstQuestionDisplay() {
    currentQuestion.innerHTML = "Question " + (questionCount) + ": " + questions[0]; //With this I show what the current question is
    questionImage .innerHTML = "<img src=\"https://lenadesign.org/wp-content/uploads/2019/12/untitled7-1.gif?w=580\" width=\"300px\" height=\"150px\">";
    // I use a GIF to keep it entertaining
    buttonA.innerHTML = "A. " + choice1[0]; //I let the questions take the choices based on the arrays
    buttonB.innerHTML = "B. " + choice2[0];
    buttonC.innerHTML = "C. " + choice3[0];
    buttonD.innerHTML = "D. " + choice4[0];
    scoreDisplay.innerHTML = "Current score: " + (scoreCounter) + " of 10 points";
}

function question1Correct() {
    scoreCounter++; //If you clicked on the correct button, increment it/Higher the score with 1 point
    gecheckteAntwoord.innerHTML = "<h2 id=colorCorrect>" + correctFeedback[0] + "Current score: " + scoreCounter + " of 10 points" + "</h2>";
    currentQuestion.innerHTML = ""; //With this I say, do not display the button anymore
    questionImage.innerHTML = "<img src=\"https://thumbs.gfycat.com/ElatedGlamorousAmericanindianhorse-size_restricted.gif\" width=\"300px\" height=\"150px\">";
    buttonA.innerHTML = "";
    buttonB.innerHTML = "<h4> You chose for: </h4>" + "<button class=checkBtnDesign>Cascading Style Sheet</button>"; //display of the right question
    buttonB.style.backgroundColor = "green";
    buttonC.innerHTML = "";
    buttonD.innerHTML = "";
    nextButtonDisplay.innerHTML = "<button class=btn-quizquestiondesign style=cursor:pointer onclick=secondQuestionDisplay()>Go to the next question</button>";
    scoreDisplay.innerHTML = "Current score: " + (scoreCounter) + " of 10 points";
}

function question1Incorrect() { //Function if the first question gets anwsered wrong
    answerOutput.innerHTML = "<h2 id=colorIncorrect>" + negativeFeedback[0] + " Current score: " + scoreCounter + " of 10 points" + "</h2>";
    currentQuestion.innerHTML = "";
    questionImage.innerHTML = "<img src=\"https://thumbs.gfycat.com/BruisedElementaryBedlingtonterrier-size_restricted.gif\" width=\"300px\" height=\"150px\">";
    buttonA.innerHTML = "";
    buttonB.innerHTML = "<h4> Het juiste antwoord is: </h4>" + "<button class=checkBtnDesign>Cascading Style Sheet</button>";
    buttonB.style.backgroundColor = "green";
    buttonC.innerHTML = "";
    buttonD.innerHTML = "";
    scoreDisplay.innerHTML = "Current score: " + (scoreCounter) + " of 10 points";
    nextButtonDisplay.innerHTML = "<button class=btn-quizquestiondesign style=cursor:pointer onclick=secondQuestionDisplay()>Go to the next question</button>";
}

function secondQuestionDisplay() {
    questionCount++;
    answerOutput.innerHTML = "";
    currentQuestion.innerHTML = "Question " + (questionCount) + ": " + questions[1];
    questionImage.innerHTML = "<img src=\"https://thehustle.co/wp-content/uploads/2019/10/header-1.gif\" width=\"300px\" height=\"150px\">";
    buttonA.innerHTML = "A. " + choice1[1];
    buttonB.style.backgroundColor = "";
    buttonB.innerHTML = "B. " + choice2[1];
    buttonC.innerHTML = "C. " + choice3[1];
    buttonD.innerHTML = "D. " + choice4[1];
    nextButtonDisplay.innerHTML = "";
    scoreDisplay.innerHTML = "Current score: " + (scoreCounter) + " of 10 points";
}

function question2Correct() {
    scoreCounter++;
    answerOutput.innerHTML = "<h2 id=colorCorrect>" + correctFeedback[1] + "Current score: " + scoreCounter + " of 10 points" + "</h2>";
    currentQuestion.innerHTML = "";
    questionImage.innerHTML = "<img src=\"https://media0.giphy.com/media/Y42vmMOOa5CiTGkOto/giphy.gif\" width=\"300px\" height=\"150px\">";
    buttonA.innerHTML = "<button class=checkBtnDesign ()>Hashtags</button>";
    buttonB.innerHTML = "";
    buttonA.style.backgroundColor = "green";
    buttonC.innerHTML = "";
    buttonD.innerHTML = "";
    scoreDisplay.innerHTML = "Current score: " + (scoreCounter) + " of 10 points";
    nextButtonDisplay.innerHTML = "<button class=btn-quizquestiondesign style=cursor:pointer onclick=thirdQuestionDisplay()>Go to the next question</button>";
}

function question2Incorrect() {
    answerOutput.innerHTML = "<h2 id=colorIncorrect>" + negativeFeedback[1] + "Current score: " + scoreCounter + " of 10 points" + "</h2>";
    currentQuestion.innerHTML = "";
    questionImage.innerHTML = "<img src=\"https://media0.giphy.com/media/26BGATx4qFzThYJnG/giphy.gif\" width=\"300px\" height=\"150px\">";
    buttonA.innerHTML = "";
    buttonB.innerHTML = "<h4> The right answer is: </h4>" + "<button class=checkBtnDesign ()>Hashtags</button>";
    buttonB.style.backgroundColor = "green";
    buttonC.innerHTML = "";
    buttonD.innerHTML = "";
    scoreDisplay.innerHTML = "Current score: " + (scoreCounter) + " of 10 points";
    nextButtonDisplay.innerHTML = "<button class=btn-quizquestiondesign style=cursor:pointer onclick=thirdQuestionDisplay()>Go to the next question</button>";
}
/**
 * Hide all pages
 */
function hideAllPages() {
    var startPage = document.getElementById('page-start');
    var questionsPage = document.getElementById('page-questions');

    startPage.style.display = 'none';
    questionsPage.style.display = 'none';
}

/**
 * Show start page
 */
function showStartPage() {
    var page = document.getElementById('page-start');

    hideAllPages();

    page.style.display = 'block';

    console.info('Je bent nu op de startpagina');
}

/**
 * Show questions page
 */
function showQuestionsPage() {
    var page = document.getElementById('page-questions');

    hideAllPages();

    page.style.display = 'block';

    console.info('Je bent nu op de vragenpagina');
}


// Initialize
addButtonActions();
showStartPage();

Get Value out of specific Column if first Value match

I need to get a specific value out of f.e. column 4 of my imported Excel if the Value in column 1 matched with the earlier imported number (lets assume the value is defined as V). So that means if Value Column A = V than get me the value of column 4. All the Values in Column 1 are numbers and the value in column 4 is a mix betweend letters and numbers.

I tried different things but none worked until I realized that even if I search for the value with 0000 in pd the result is False. I imported the Excel with pd.read_excel.

Can you please provide some help - thank you.

Change value of a cell if a condition is fulfilled with R

I am new in R-world and now I am trying to set a certain text if a condition is fulfilled. I have a dataframe of different restaurants (df_Restaurant) and there is column with the Name of the restaurant (Name) and other with the Risk of being infected (Risk). All the restaurants with the same name, have the same risk. The original dataframe does not have the Risk values in every case, so I want to fulfill this condition. Apart of that, the value cannot be 0.

I got some errors, but first I want to know if the way I wrote this condition is correct. Is there any other way to replace the value of a cell in case of being text? The df Restaurant has over 200.000 rows and I do not know other way.

Errors shown are: 1- Object 'j' not found 2- Unexpected error in }

if (Restaurant$Name[i]==locales$Name[j] & Restaurant[i]!=0) { Restaurant$Risk[i]= Restaurant$Risk[j]}

Thank you in advance

How to use IF statement inside a built in function

im trying to create a VBA built in function where if depending on the requirement, one type of calculation is done. this is what i tried to do but it is not working. anyone has an example of how do this type of function?

Public Function FRPV(ratey As Double, ratet0 As Double, maturity As Date, asof As Date, amount As Double, testif As Double)

If testif = 123 Then
    FRPV = ((1 + (ratey / 100) * (maturity - asof) / 360) * amount) / (1 + (ratet0 / 100) * (maturity - asof) / 360)
    
Else
    FRNPV = (((1 + ratey / 200) ^ ((maturity - asof) / 180)) * amount) / (1 + (ratet0 / 100) * (maturity - asof) / 360)
    
End If

End Function

Why am I getting the error: cond: expected a clause with a question and an answer

Why am I getting the error: cond: expected a clause with a question and an answer, but found a clause with only one part? What am I doing wrong?

Basically, I have to find out if the discriminant is a positive / negative number.

(define (has-real-roots? a b c)
  (cond
    [(positive? (- (square b) (* 4 a c)))]
    [else false]))

Use interior in cells to click and unclick e-mail adresses in a specific range. Then store this e-mail adres in a string and use it as recipiant vba

I'm a beginner in vba and i got a question about it. In range a10 till a14 there are names. These names all have a specific e-mail adres like in my code below. A10 = a A11 = b A12 = c and so on. Names and e-mail adresses are fakes ofcourse.

I want to loop through the cells a10 till a14 and then if the interior color of the cells are code 43 then it need to store the string of the e-mail adres in the string "namen" .So if i click A10 and A12 string a and c should be in the string "namen"

Now it only shows string A in my e-mail recipiants.


Sub mailen()
Dim a As String
Dim b As String
Dim c As String
Dim namen As String
Dim inhoud As String


a = "brrr@hotmail.com;"
b = "grrr@hotmail.com;"
c = "crrr@hotmail.com.com;"


If Range("A10").Cells.Interior.ColorIndex = 43 Then
namen = a
ElseIf Range("A10").Cells.Interior.ColorIndex = 43 And Range("A11").Cells.Interior.ColorIndex = 43 Then
namen = a & b
Else: MsgBox "Geen namen geselecteerd"
   End If
    With CreateObject("Outlook.Application").createitem(0)
    inhoud = "Hoi Vincent"
    .to = namen
    .Subject = "Test"
    .body = inhoud
    .attachments.Add ThisWorkbook.FullName
    .display
    End With
End Sub

dimanche 27 septembre 2020

Pandas if column X is not a null value, take the value of column X, else take column Y value

df['raw_score']
df['indicator']
df['final_score']

Hi everyone, i have 3 columns in a pandas df. I want the column 'final_score' to be a condition using both 'raw_score' and 'indicator'.

this is the condition i am trying to achieve:
df['final_score'] = if df['indicator'] is not a null value, take the value of df['indicator'], else take df['raw_score'].

I cant figure out how to do this and need your help!

python function Namerror: name 'dictionary' is not defined

I would like to load a file and convert it to a dictionary. then, would like to use the loaded file to display the data. user input for choice is between 1 and 2, in order to decide which function to run. The catch is if I press 2 before 1 then it will display the message "dictionary is empty". Again, when I load the file and try to run display data, it is showing "Nameerror: name 'dictionary' is not defined" The code is as below: (Thanks in advance)

def load_data():
  import csv
  open_data = open('file.csv', 'r')
  datasets = csv.reader(open_data)
  mydict = {row[0]:row[1:] for row in datasets}
  return mydict

def display_data(my_dict):
  ds = my_dict
  if ds == {}:
    print("dictionary is empty")
  else:
    for key, value in ds.items():
      print(key)
      print(value)
       
def main():
    while True:
    choice = int(input("select 1 or 2"))    
    if choice == 1:
      my_dict = load_data()
      print(my_dict)    
    elif choice == 2:
      display_data(my_dict)
main()

How to use 'Exit For Loop IF' keyword with multiple condition in Selenium Robot framework

I need to exit FOR LOOP in Selenium Robot framework when multiple conditions are met

I am trying something like this where it should exit FOR LOOP , if the below conditions are met:

Exit For Loop IF '${Name}'=='Adam' and '${Age}'=='27'

Error:

Keyword 'BuiltIn.Exit For Loop If' expected 1 argument, got 2.

IF statement acting weird in twilio texting project

I am trying to create a texting project where I can text a twilio number, and based off what the message is I can reply with a custom message. I am using a string of if statements to check the body of the text and reply with certain things

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])

def sms_reply():
  reply_pointer = 0
  body = request.values.get('Body', None)
  resp = MessagingResponse()

  print(body)

  if(body == "Test1"): reply_pointer = 0
  elif(body == "Test2"): reply_pointer = 1
  elif(body == "Test3"): reply_pointer = 2
  elif(body == "Test4"): reply_pointer = 3


  print(reply_pointer)

I am texting these messages from my phone and if I send Test1 through Test3 I get normal results, but when I text Test4, reply_pointer gets set to 0 and it stays 0 if I text Test1, Test2, etc. I've been trying to fix this for so long and I have no idea whats going on.

if statement to create new column pandas for string variable

With this dataframe, I would like to create another column that is based on the values of the first column.

data = {'item_name':  ['apple', 'banana', 'cherries', 'duck','chicken','pork']}
df = pd.DataFrame (data, columns = ['item_name'])
Expected df:
item_name  item_type
apple      fruit
banana     fruit
cherries   fruit
duck       meat
beef       meat
pork       meat

Code that I tried:

def item_type(item_name):
   if df['item_name'] is in ['apple','banana','cherries']:
       df['item_type']=='fruit'
   else:
       df['item_type']=='meat'

df = df.apply(item_type)

How can I compare the values of different columns for each row?

So say I have a dataframe with a column for "play" and two columns with values:

df <- data.frame(Play = c("Comedy", "Midsummer", "Hamlet"),
                he = c(105, 20, 210),
                she = c(100, 23, 212)) 

I would like to get two vectors, one containing each Play with a higher value for "he" than "she", and one for the opposite, so each Play that has a higher value for "she" than "he".

I've looked at a few ways I thought going about it but none really seems to work, I tried building a 'if (x > y) {print z}' function then apply() that over my dataframe but I'm really far to inexperienced and run into so many problems, there ought to be simpler way than that …

Exercise in C with if and switch statements: Write code to convert 2 digit numbers into words

There's this exercise I'm trying to figure out. The assignment asks to convert a two-digit number in words, the output should be something like this :

Enter a two-digit number:45
You entered the number forty-five.

I'm still a total beginner to programming. I'm at this chapter in this C programming book, in the exercise section about the switch and if statements. The exercise suggests to use two switch statements, One for the tens and the other one for units, but numbers within 11 and 19 require special treatment.

The problem is that I'm trying to figure out what should I do for numbers between 11 and 19, I was thinking to use the if statement but then the second switch function would include in the output and it would turn into something like You've entered the number eleven one.

This is the program I've been writing so far (incomplete):

    int digits;

    printf("Enter a two-digit number:");

    scanf("%d", &digits);

    printf("You entered the number ");

    switch (digits / 10) {
    case 20:
        printf("twenty-");break;
    case 30:
        printf("thirty-");break;
    case 40:
        printf("forty-");break;
    case 50:
        printf("fifty-");break;
    case 60:
        printf("sixty-");break;
    case 70:
        printf("seventy-");break;
    case 80:
        printf("eighty-");break;
    case 90:
        printf("ninety-");break;
    }

    switch (digits % 10) {
    case 1:
        printf("one.");break;
    case 2:
        printf("two.");break;
    case 3:
        printf("three.");break;
    case 4:
        printf("four.");break;
    case 5:
        printf("five."); break;
    case 6:
        printf("six.");break;
    case 7:
        printf("seven.");break;
    case 8:
        printf("eight.");break;
    case 9:
        printf("nine.");break;
    }
    return 0;

Creating a funciton that prints the result of if-statements

I want to create a function that will compare some values that I calculated (and placed in a list called abv_list_round) and compare them to some values that other people have calculated. I set up a for loop with an if statement nested inside of it, and it doesn't return any errors, but it also doesn't print any of the statements I asked it to. Do I need the function to return each of those statements? Or should I try saving them all to a list and returning that instead?

Here's what I have so far:

def resolve(x = grad1, y = grad2):
    find_abv(SG = SG_val, FG = FG_val)
    for i in abv_list_round:
        if abv_list_round == x:
            print("Grad student 1 is correct")
        elif abv_list_round == y:
            print("Grad student 1 is correct")
        else: 
            print("you were both wrong")

Why is "if [ -z "ls -l /non_existing_file 2> /dev/null" ] not true [duplicate]

I want to check if an external drive is still plugged in by checking /dev/disk/by-uuid/1234-5678.

However, I know that this could be done much easier with:

if ! [ -e "/non_existing_file" ]
   echo "File dont exists anymore"
fi

But I still want to know why the script in the Title dont work. Is it because of the exit code of ls?

Thanks in advance.

Compiler not recognizing that class string value is equal to another String value [duplicate]

public class Station {
    String name;
    boolean pass;
    int distance;

    // method to create a new Station taking the arguments of the name,pass and distance in the parameter
    public static Station createStation(String name, boolean pass, int distance) {  
    }

    // Array list containing all the Stations in London we will use
    static Station[] StationList = {createStation("Stepney Green", false, 100), createStation("Kings Cross", true, 700), createStation(
            "Oxford Circus", true, 200)};

    public static String infoAboutStation(Station station) {
        String message;
        if (station.pass)
            message = //string message
        else
            message = //string message
        return message;
    }

    public static String checkInfo(String stationName){
        String info = null;

        for(Station station : StationList){     
            if(stationName == station.name) { //it does not recognise it to be the same for some reason
                info = stationName + infoAboutStation(station);
            }
            else
                info = stationName + " message ";
        }
        return info;
    }

    public static void printInfo(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("How many... ");
        int totalResponses = Integer.parseInt(scanner.nextLine());

        String choice;
        for(int i = 0; i < totalResponses; ++i){
            System.out.println("Enter a station: ");
            choice = scanner.nextLine();
            System.out.println(checkInfo(choice));
        }
    }
    // psvm(String[] args)
}

So the program runs fine but when we use "Stepney Green", "Kings Cross", "Oxford Circus" as the input for choice at checkinfo(choice), it does not recognise it to be the same for stationName == station.name in the method checkInfo(stationName //choice)

Intellij debugger reads this at stationName == station.name

-StationList = {Station[3]@980} -> 0 = {Station@994} 1 = {Station@997} 2 = {Station@998}

-static -> StationList = {Station[3]@980}

-stationName = "Stepney Green" value = {byte[13]@996} coder = 0 hash = 0 hashisZero = 0

-info = null

-station = {Station@994} -> name = "Stepney Green", pass = false, distance = 100

-station.name = "Stepney Green" -> value = {byte[13]@999] rest is zero

Beside the statement it says stationName: "Stepney Green" station: Station@994. Instead of printing out stationName + infoAboutStation it goes to the else station and prints "Stepney Green is not a London Underground Station". I am so puzzled as to why. Also if you don't mind helping me as to making this code a little more efficient and better.

Ghost Data in supposedly empty cells in Excel (COUNTA may be culprit)

I'm encountering a math error in Excel where supposedly empty cells are being counted as data. I believe the culprit is COUNTA but I could be wrong. I've attached some photos to demonstrate the error. Essentially I have an IF statement in many cells that are dynamic and changing. When the IF statement is incorrect I want the cell to be blank NOT display a 0. I obviously accomplish this with IF(A1>A2,1,""). Another math formula references all of those IF statement cells, chops off 31% of the lowest numbers then shows me the current lowest number. This formula is counting the empty cells when it shouldn't be. The reason I am encountering this error now is that I'm moving the data from Google Sheets to Excel.

Here's a more in depth analysis of the formulas. Formula A is =IF(E20=1,D20/C20,"") and Formula B is =IF(C20>0.1,IF(E19=1,IF(E20=0,D20/C20,""),""),"") These are both dragged down. Result % Formula is =(SMALL(F20:G28,ROUNDUP(COUNTA(F20:G28)*0.31,0))). Photo A is the normal result % but if I go to the empty spaces in Formula A & B and click 'delete' you get the Result % in Photo B. I am also open to changing these formulas if they are the problem as long as they accomplish the same thing.

Independent is an additional formula but I don't see how it could be effecting anything so it's not worth noting. Photo A Photo B