vendredi 30 avril 2021

How to check all input has value and do something

i have these inputs and i wanted to check every one of them has value then do something;

const tch_family_name = document.getElementById('tch_family_name');
const tch_lastname = document.getElementById('tch_lastname');
const tch_name = document.getElementById('tch_name');
const tch_phone = document.getElementById('tch_phone');
const first_alph = document.getElementById('first_alph');
const second_alph = document.getElementById('second_alph');
const third_alph = document.getElementById('third_alph');
const tch_bday = document.getElementById('tch_bday');
const textarea1 = document.getElementById('textarea1');

and I'm checking they have value or not like this

 function checkEmpty(check) {
        for (i = 0; i < check.length; i++) {
            if (check[i].value == "" || check[i].value == " " || check[i].value == null) {
                check[i].classList.add('inputErrorBorder')
            } else {
                check[i].classList.remove('inputErrorBorder')
            }
        }
    }

//mainInfo button id

  mainInfo.addEventListener('click', () => {
            test = [tch_family_name, tch_lastname, tch_name, tch_phone, first_alph, second_alph, third_alph, tch_bday, textarea1]
            checkEmpty(test) 
})

now how to do something when all input have value;

I tried else if() but it gave an incorrect result for example when first input don't value then it wont add inputErrorBorder class to a second or third inputs.

Please help;

Using type as an argument for an if statement [duplicate]

I am trying to write a function that checks whether or not variables a and s are of type int or float, if not it prints the print statement below. The if function does not work however how would I be able to fix it?

a = 2
s= "hello"
if ((type(a) not (float or int)) and (type(s) not (float or int))):
    print(f'Invalid a type:{type(a)} s type: {type(s)}\Make sure to use float or int as for a and s values

I don't know how to make this if statement work

this is the question on the homework: "If the person works, in hours per week, less than or equal to the number of hours in a normal work week, then the income is simply the payrate times hoursWorkedPerWeek."

this is the code i have, it says it's an unreachable statement:

public double getGrossIncome() {
    double income = 0;

    return income;

    if(hoursWorkedPerWeek <= NORMAL_WORK_WEEK){
        income = payRate * hoursWorkedPerWeek;
    }

}

How to make the if return the expected result (R)?

Any ideas on how to resolve this error?

Warning messages:
1: In if (A <0) {:
   the condition has length> 1 and only the first element will be used
2: In if (A> 0) {:
   the condition has length> 1 and only the first element will be used
A <- c (0, -2, -4,1,5)
B <- if (A <0) {A/-2} else if (A> 0) {A/2} else {A = 0}

Erro: The result of B must be (0,1,2,0,5,2.5).

I don't know how to get this if statement to work

this is the homework question: "If the person works, in hours per week, less than or equal to the number of hours in a normal work week, then the income is simply the payrate times hoursWorkedPerWeek."

this is the code i have:

public double getGrossIncome() {
    double income = 0;

    return income;

    if(hoursWorkedPerWeek <= NORMAL_WORK_WEEK){
        income = payRate * hoursWorkedPerWeek;
    }

}

c# is it possible to check if a certain line of the file is empty?

I want to check if a certain line of a file is empty, and if it is, do something.

if(File.ReadLines("MainSave.txt").Skip(1).First() == null)
{
      // do something
}

Compare two columns using pandas and update changed values and append missing values

I have two different csv dataframe files Test1.csv and Test2.csv, I would like to match the 'id' column in Test1.csv to 'id' column in Test2.csv, and append missing 'id' values into Test2.csv and update missing values.

Shortly Append False values, and update True values in Test2.csv

Test1.csv

   No    Price(Op)    Price(Cl)   id   
   1     1200         500         a01 
   2     1400         500         a02
   3     1500         600         a03
   4     1800         500         a04
   5     1000         500         a05
   6     1570         800         a06
   7     1290         500         a07
   8     1357         570         a08          

Test2.csv

   No    Price(Op)    Price(Cl)   id
   1     1200         500         a01 
   2     1500         500         a03
   3     1450         500         a02
   4     1800         500         a04
   5     1200         500         a05        

Desired Output: Test2.csv

   No    Price(Op)    Price(Cl)   id   
   1     1200         500         a01 
   2     1500         600         a03
   3     1400         500         a02
   4     1800         500         a04
   5     1000         500         a05
   6     1570         800         a06
   7     1290         500         a07
   8     1357         570         a08          

I tried To Loop Over with if statement

ds = pd.read_csv('Test1.csv')
df = pd.read_csv('Test2.csv')
for index, row in ds.iterrows():
    if row['id'] in df['id']:
        df['Price(Op)'].iloc[idx] = val['Price(Op)']
        df['Price(Cl)'].iloc[idx] = val['Price(Cl)']
        #What If index Are Different, How Program will know index of same id on other file
    else:
        df.append(ds.iloc[idx]

Why is the last condition not executing?

The first two conditions for 100<a<200 and 100<b<200 are executing perfectly but the condition for both to be between 100 and 200 is not working any idea why? My code:

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter the first integer:");
    scanf("%d",&a);
    printf("Enter the second integer:");
    scanf("%d",&b);
    if (100<=a&&a<=200)
    {printf("The integer %d lies between 100 and 200",a);}
    else if (100<=b&&b<=200)
    {printf("The integer %d lies between 100 and 200",b);}
    else if((100<=a&&a<=200)&&(100<=b&&b<=200))
    {printf("Both of the integers lie between 100 and 200");}
    else
    {printf("The integers does not lie between 100 and 200");}
    return 0;
}

Output: enter image description here

syntax-error in vhdl code in the process line

i'm trying to do a 8 states of 3-bit running LED. The LED will move forward when the input x is 1 andmove backward when x is 0. with following conditions.

i've trying this for hours now and i don't know what's wrong with it. i'm learning vhdl right now so pleaseeee go easy on me. it says it's syntax error but i don't know where

library IEEE;
use IEEE.std_logic_1164.all;


entity Quiz10 is 

 port(
        x   : in    std_logic;
        output  : out   std_logic_vector(6 downto 0)
    );

end Quiz10;


architecture arch1 of Quiz10 is
    signal digit : integer range 0 to 9 := 0;

begin

process (x,digit)
begin
    if x = '1' then
        digit <=digit+1;
    elsif x = '0' then
        digit <=digit-1;
    elsif (digit>=9)
        digit<=0;
    end if;
end process;




output <="1111110" when digit = 0 else
               "0110000" when digit = 1 else
               "1101101" when digit = 2 else
               "1111001" when digit = 3 else
               "0110011" when digit = 4 else
               "1011011" when digit = 5 else
               "1011111" when digit = 6 else
               "1110000" when digit = 7 else
               "1111111" when digit = 8 else
               "1111011" when digit = 9 else
               "0000000";
    
  -- Your VHDL code defining the model goes here

end arch1;

Trying to make a recursive function to get a y/n answer from the user, but when it recurs the check stops working

The expected output is that it will recur until the user gives a yes or no answer, and if they give yes execute code, in this case just print "yep". everything works if the user inputs "Y" right away, but when the input is illegal and the program asks for another input the user input check stops working.

Example:

(Y/N) y
yep

ends


(Y/N) illegal

Something went wrong, make sure you made the right input and try again!

(Y/N) y

ends

What am I doing wrong ?

def user_choice():
    answer = input("(Y/N) ")
    if answer.lower() == "n": return False
    elif answer.lower() == "y": return True
    else:
        print("Something went wrong, make sure you made the right input and try again!")
        user_choice()

if user_choice(): print("yep")

Testing two conditions in python. One condition is always true even when it is not supposed to be

I am having difficulties getting this code to work. I am attempting to do the following.

  1. When x is raised to a power of y, it needs to be true except with number 1.
  2. Return true when x is divisible by y.

Problems. I wrote this code but the problem is that when I input x=3 and y=3 I get and answer that x is the power of y which isn't true. Regardless of the number, if x == y it always says that x is power of y.

Question.

How would you make the corrections for this code?

def is_divisible(x, y):
    if x % y == 0:
        print("x is divisible by y")
        return True
    else:
        print("x is not divisible by y")
        print("x is not the power of y")
        return False


def is_power(x, y):
    if x == 1 or y == 1:  # code to test the base of 1
        return x == 1

    elif x % y == 0:
        print("x is the power of y")
        print("x is divisible by y")
    elif is_divisible(x, y) and is_power(x / y, y): # recursion of is_divisible. This will be true only if x/y
    # then x is the power of y.
        return 0.0
    else:
        return False
    


print(is_power(2, 2))

outputs

x is the power of y
x is divisible by y
None


print(is_power(27, 3))
x is the power of y
x is divisible by y
None
   

Change multiple values with ifelse in tidyverse

I hav a dataset with 20.000 Observations and 5 Variables. Now I want to change in some specific observations only one variable. I know that I can do this for every row like this:

test_data <- test_data%>%
  mutate(change_variable=ifelse(n=="1000","changevalue",changevariable))

My problem is now that I need to change 500 Obersvations like this. Is there any possibility to automate this process instead of writing a code of 500 lines? It is every time the same variable to get changed and I have the right value for this variable in a dataframe connected to the right "n" value.

I Hope someone of you can help me with this.

Kind Regards, Tom

Is there a nested if in lisp?

(if (> 10 5)
    (format t "First number is greater ~%"))
    
    (if (> 10 15) 
        (format t "First number is greater ~%")
        (format t "Second number is greater ~%"))
        
        (if (= 10 10)
        (format t "Both numbers are equal"))

Else block without if block in python

I found the Python Code snippet online to print the range of the prime number but the last else block is making no sense to me as it doesn't has corresponding if block

Note The Indentation of else block is intentional as it work correctly the way it is and i come up with this code after watching the tutorial on youtube at https://www.youtube.com/watch?v=KdiWcJscO_U

entry_value = int(input("Plese enter the starting value:"))
ending_value = int(input("Plese enter the ending value:"))
for i in range(entry_value, ending_value+1):
    if i>1:
        for j in range(2,i):
            if i%j == 0:
                break
        else:
            print("{} is prime number".format(i))

How to make the condition to be a Eventhandler Control.click event?

Basically what I am trying to do is, creating a new method that will have an event handler button click event condition within it.enter code here

 //when this event is active the only should then should run what inside the {}
if(buttonEvents_Click(object sender, EventArgs e))
{enter code here`
//Happening something
}

what I already tried withing(buttonEvents.click) get the error "the event control.click can only appear on the left side =+ or -+".

Display the correct input for the largest value in array [duplicate]

I already get the smallest number but for the largest it display the wrong number. How to get and display the correct number for the largest value?

public static void main(String[] args) { final int ARRAY_SIZE = 100;

    int[] array = new int[ARRAY_SIZE]; 

    int count = 0; // hold the number of elements in an array 
    int sum=0;
    int index;
    

    // everytime we add an element, the count is incremented. 
    
    Scanner uInput = new Scanner(System.in); 
    System.out.print("Enter a number or -1 to quit: "); 

    int number = uInput.nextInt(); 

    while (number != -1 && count < array.length) 

    { 

    array[count] = number; 

    count++; 

    System.out.print("Enter a number or -1 to quit: "); 

    number = uInput.nextInt(); 
    }
    
    //display all the valid elements in the array 

    for (index = 0; index < count; index++) 

    { 

    System.out.println("Element #"+ index+ ": "+ array[index]); 

    //Task #1: Tutorial 04 write your code here 

    sum += array[index];
    System.out.println(sum);
    }
    int average = sum/count;
    System.out.println("Average: " + average);
    
    int smallest = array[0], largest = array[0];
    for (int i : array) {
        if (array[i] < smallest) {
            smallest = array[i];
        }
        else if (array[i] > largest) {
            largest = array[i];
        }
            System.out.println("Smallest: " + smallest);
            System.out.println("Largest: " + largest);
            return;
    
    } 

   }
}

Output: Enter a number or -1 to quit: 2 Enter a number or -1 to quit: 4 Enter a number or -1 to quit: 6 Enter a number or -1 to quit: 8 Enter a number or -1 to quit: -1 Element #0: 2 2 Element #1: 4 6 Element #2: 6 12 Element #3: 8 20 Average: 5 Smallest: 2 Largest: 6 (The largest should be number "8")

Js how to write multiple ifs in a efficient way?

I am still a beginner to JS and I am kinda struggling on how to write multiple ifs in a correct way. For example I wrote something like this:

function calculatespot() {
  //Spot 1 to 2 transfer bandage
  if (spot1Selected == 1 && spot2Selected == 1) {
    if (spot2Free == 1) {
      localStorage.setItem('spot1Free', 1)
      localStorage.setItem('spot2Free', 0)
      localStorage.setItem('spot1Selected', 0)
      localStorage.setItem('spot2Selected', 0)
      document.getElementById('block1').style.backgroundColor = "#9eafa6"
      document.getElementById('block2').style.backgroundColor = "#9eafa6"
      if (user_item1 == "Bandage") {
        localStorage.setItem("slot1Type", "")
        localStorage.setItem("slot2Type", "Bandage")
        document.getElementById('inventoryactionbtn').style.visibility = "Hidden"
        document.getElementById('item1').src = "/static/images/transparant.png"
        document.getElementById('item2').src = "/static/images/bandage.png"
        localStorage.setItem('slot1Type', "")
        localStorage.setItem('slot2Type', "Bandage")
      }
    }
  }

This is not a very good way, but I still need all those points to match before executing the code. How could I write something like this in a better and more efficient way without having to nest all those ifs?

Re-Running the function in case "if" condition fails or else continue

I am trying to get the sum of all the messages available in my multiple SQS queues using boto3. It is executing fine but sometimes only a few of the queues are returning data instead of all of them and the program is returning empty sets. How do I solve this problem using the "IF" condition so that the function re-runs if one of the sets is empty? PS: I am a newbie to programmming import boto3 import time from datetime import datetime, timedelta

sqs = boto3.client('sqs')
cloudwatch = boto3.client('cloudwatch')
asg = boto3.client('autoscaling')

response = sqs.list_queues(QueueNamePrefix ='Queue')
queuelist = response["QueueUrls"]

soa = 0.0
noi = 0.0
ABPI = 100

def SumOfAverages(queuelist, soa, response, cloudwatch):
    for eachqueue in queuelist:
        step0 = eachqueue.split('/')
        step1 = step0[4]
        response1 = cloudwatch.get_metric_statistics(
        Namespace='AWS/SQS',
        MetricName='ApproximateNumberOfMessagesVisible',
        Dimensions=[
            {
                'Name': 'QueueName',
                'Value': step1
            },
        ],
        StartTime=datetime.utcnow() - timedelta(minutes=1),
        EndTime=datetime.utcnow(),
        Period=60,
        Statistics=[
            'Average',
        ],
        
        Unit='Count'
        )
        datapoints = response1['Datapoints']
        print(datapoints)
        #*Need If Condition*
        for values in datapoints:
            averages = values['Average']
            soa += averages
    return(soa)

result = SumOfAverages(queuelist, soa, response, cloudwatch)
print(result)

Using Java Conditional Statement

A company decided to give bonus of 5% to employee if his/her year of service is more than 5 years.Ask user for their salary and year of service and print the net bonus amount. Code

How would you print number 1,2,3,4,5,6,7,8,18,19,20,21,22,23,24 in python?

I had knowledge about java so I tried writing an if block within the for block saying,

for i in range(25):
    if i == 9:
        i = 18
    print(i)

This code logic works in java but not in python. What should I do?

How do i run rest of the code out of a loop

Look in my code how can i do that

a = int(input("enter a number"))
if a == 5:
    # from here i want to continue below code
else:
   print("a is not 5")
   exit()

#code is here

what i have already tried:

  1. putting it empty
if a == 5:
else:
   print("a is not 5")
   exit()

#code is here
  1. putting a comment
if a == 5:
    # from here i want to continue below code
else:
   print("a is not 5")
   exit()

#code is here

Why does Python print the else statement here?

The output of the below code is

Hello
Hola

Why does it print the "Hola"? Shouldn't the else statement be exempt when passing 'en' into the function?

def greet(lang):
    if lang == 'en':
        print("Hello")
    if lang == 'fr':
        print('Bonjour')
    else:
        print('Hola')

greet('en')

How to write if condition for mysql db data (condition: qty == 0 ) then email should be send to the admin

In the below code I have made a route to /editproduct in this the products can be added, edit or delete the products. I want to send an email to the admin with an alert message as the product qty is 0 . when the product is edited to zero qty then the database updated with zero. if the qty in MySQL DB is zero then an email should send. how to write that condition. please help and sorry for the bad English grammar.

@app.route('/editProduct',methods = ['POST'])
def editProduct():
   if request.method == 'POST' and 'ProductID' in request.form and 'NEWProductName' in request.form and 'NEWProductDescription' in request.form and 'NEWProductQty':
      try:
         productID = request.form['ProductID']
         productName = request.form['NEWProductName']
         productDescription=request.form['NEWProductDescription']
         ProductQty=request.form['NEWProductQty']
         cursor = mysql.connection.cursor()
         cursor.execute("UPDATE Products SET productName = % s,productDescription = % s, QTY = % s WHERE productID = % s",(productName,productDescription,ProductQty,productID) )
         #products = cursor.fetchone()
         #TEXT = "Hello "+username + ",\n\n"+ "the stock " +productName + "is empty" 
         #message  = 'Subject: {}\n\n{}'.format("Stock Alert", TEXT)
         mysql.connection.commit()
         cursor = mysql.connection.cursor()
         QTY = "SELECT * from Products where QTY == 0;"
         cursor.execute(QTY)
         if QTY == 0:
             email_alert('prakprak2002@gmail.com')
         msg = "Product Edited "
         cursor.close()
      except:
         #con.rollback()
         msg = "error in operation"
      
      finally:
         return redirect(url_for('product', msg = msg))#+"?msg="+msg)

script won't execute if statement [closed]

I'm trying to make a script where a variable can only be entered 2 times and if the variable is entered for the 3rd time the script is supposed to not let the user do that. And to do this I'm having PHP write different strings to a file such as "used1" and "used2" etc when a function is called. The file creation part works and writing until "used2" works fine but the script will never write "used3" into the file and won't display the echo message. Instead, it starts writing from "used1" again.

Here's my code:

$a = 'users/'.$playerName.'.txt';
            if (strpos(file_get_contents($a), 'used1') === false) {
                $fp = fopen('users/'.$playerName.'.txt', 'w');//opens file in append mode
                fwrite($fp, 'used1');  
                fclose($fp);  
                var_dump(strpos(file_get_contents($a), 'used1'));
                
                echo "File appended successfully";
                $wsr->sendCommand("goldencrates givekey $playerName csgo 1");
                $wsr->disconnect(); //Close connection.
                die();
            }
            if (strpos(file_get_contents($a), 'used2') === false) {
                $fp = fopen('users/'.$playerName.'.txt', 'w');//opens file in append mode
                fwrite($fp, 'used2');  
                fclose($fp);  
                var_dump(strpos(file_get_contents($a), 'used2'));
                
                echo "File appended successfully";
                $wsr->sendCommand("goldencrates givekey $playerName csgo 1");
                $wsr->disconnect(); //Close connection.
                die();
            }
            if (strpos(file_get_contents($a), 'used3') === false) {
                $fp = fopen('users/'.$playerName.'.txt', 'w');//opens file in append mode
                fwrite($fp, 'used3');  
                fclose($fp);  
                var_dump(strpos(file_get_contents($a), 'used3'));
                
                echo "You cannot get anymore rewards today!";
                $wsr->sendCommand("goldencrates givekey $playerName csgo 1");
                $wsr->disconnect(); //Close connection.
                die();
            }

jeudi 29 avril 2021

How to avoid using to much if else?

This is the concept of what I'm trying to acheive with the code. I want the user to be able to leave the login section whenever they press '0', the codes below works, but is there anyway that I can shorten these codes, cause I felt like there's too much if else being use.

def signup():
     print("Press '0' to return mainpage")
     firstname = input("Please enter your first name : ")
     if firstname == "0":
          print("Mainpage returned")
          mainpage()
     else:
          lastname  = input("Please enter your last name  : ")
          if lastname == "0":
               print("Mainpage returned")
               mainpage()
          else:
               username = firstname+lastname
               print("Welcome", username)

def mainpage():
     option = input("Press '1' to signup: ")
     if option == '1':
          print("Sign up page accessed")
          signup()
mainpage()

Not able to display the sum of for loop [closed]

I am making a code that finds the sum of all numbers from 80 to 200. The array and loop work fine, the problem I have is that it will not display the sum on Chrome. What am I missing?

rangeSum([80,200]); function rangeSum(arr) { var sum = 0; { for (i = arr[0]; i

Workaround for MS Excel If-Statement

I'm a student and I've bought Microsoft Home-Office. I was not aware that they blocked featured like If-Statements in Excel.

I've tried to write a custom functions in VBA but it seems as if the limited the functions in that programm as well...

So my question is, does someone know how to work around these limitations? I'd simply like to be able to use key features like an If-Statement...

Structure of a function altered by if statement Python

There is the function a could either be in the form of client.LinearKline.LinearKline_get() or in the form of client.Kline.Kline_get(). a and b, (first_run) however the a,(second_run) does not work. c just combines a and b and is simplifies it. My previous post: issue . How would I be able to make 'c' work with getattr.

choice= 1

if choice == 1:
    a = "LinearKline"
    b = "LinearKline_get"
    c = "LinearKline.LinearKline_get"
else:
    a = "Kline"
    b = "Kline_get"
    c = "Kline.Kline_get"

first_run =getattr(getattr(client, a), b)()
second_run= getattr(client, c)()

Java, why is toLowerCase() not working in if condition, only print? [duplicate]

I am Java beginner. I dont understand why .toLowerCase() is not working when placed in if condition.

A simple version of my code:

if ( recType.toLowerCase() == "device") {
          System.out.println("done");
      }

it works when recType= "device" ofcourse but when recType="Device", it doesnt convert it to "device" so whats inside the if condition is not implemented!!. Any ideas?

why JS function doing the wrong if statement?

I have a function with 2 if statements inside it. There is a variable set it false, and when the function is called, it is supposed to check whether or not the variable is true or false and do a function based on that when the function is false, it tells the variable to become true, and vise versa with if the variable is false. But when I call the function then it will run the opposite if statement. (ie, if the variable is false, then it will do the things that it only should do if the variable is true) I don't understand why this happening. Hope someone can help! I will include a snippet below of the code.

What should happen:
when you click the button its self should turn this color #5aa897, set the variable to true, and the text should change to "On".

What is happening:
when you click the button it turns the button this color #687980, sets the variable to false, and sets the text to "Off". It should only do this if the variable is set to "true", but it is doing it when the text is set to false.


I have no idea why this is happening. I don't know if I set up my function wrong maybe, or my if statement, but I am stuck.

Hope someone can help.

var x = false;

function arOn() {
  if (x == false) {
    document.getElementById('onOff').innerHTML = "On";
    document.getElementById('ar').style.backgroundColor = "#5aa897";
    x = true;
  }
  if (x == true) {
    document.getElementById('onOff').innerHTML = "Off";
    document.getElementById('ar').style.backgroundColor = "#687980";
    x = x - 1;
  }

}
<button id="ar" onclick="arOn()" class="ar">Auto-Run: <span id="onOff">Off</span></button>

How to get index of an outcome of if statement?

I have two dataframes 'ds' and 'df'

ds-outcome of Selenium Parser Which Constantly loops and have dynamic dataset with columns(Date, Price, id) id is static But Price and Date are Dynamic

df-SQL Database To where Values From 'ds' should be written to

  1. I need To Write Values From 'ds' to 'df'
  2. Also need update values in 'df' if those values changed in 'ds'
  3. If new values are in 'ds' append those values to 'df'

Extra

If any one knows how to perform this operation using psycopg2 or sqlalchemy

Example:

import pandas as pd
ds = pd.read_csv("Info(Parser).csv")
df = pd.read_csv("Info(SQL).csv")
for idx, val in enumerate(df['id']):
        if val in ds['id']:
            (How To Update True Values?)
        else:
            (How to append only False Values?)

how can I print a message in if statement? [closed]

#include <iostream>
#include<string>
using namespace std;
int main() {
    string username, password, option, admin, client,type;
    cout << "enter the username" << endl;
    cin >> username;
    cout << "enter the password" << endl;
    cin >> password;
    cout << "are you admin or client?" << endl;
    cin >> option;
    if (option == admin) {
        cout << "Add a New Account." << endl;
        cout << "Modify An Account." << endl;
        cout << "Close An Account." << endl;
        cout << "List All Accounts." << endl;
    }
    else if (option == client) {
        cout << "Balance Enquiry" << endl;
        cout << "Withdraw Amount." << endl;
        cout << "Deposit Amount." << endl;
        cout << "Transfer from his account to another account." << endl;
    }
    cout << "Register as admin/client?" << endl;
    cin >> type;
    cout << "log out" << endl;

    return 0;
}

These 2 messages Are you admin or client? && Register as admin/client? appear behind each other without enter in the if statment

What should be the arguments when variable prompt() is declared before the function? [duplicate]

What I am trying to now is to input data thru prompt() and when the value for each variable is accepted, it will pass to function, and if met the conditions, it will be logged to console, if not different log will be displayed. I am also not sure how should be arguments in function invocation should be packaged since I declared prompt() first before the function.

So, here's what my code looks like. Also, there's an error thrown for the length, I don't know why.

let firstName = (prompt("First Name"));
let lastName = (prompt("Last Name"));
let emailAdd = (prompt("Email Address"));
let password = (prompt("Password"));
let confirmPassword = (prompt("Confirm Password"));

function getInfo(firstName, lastName, emailAdd, password, confirmPassword){

    if (firstName.length !== 0 && lastName.length !== 0 && emailAdd.length !== 0 && password !== 0 && confirmPassword !== 0 && password.length >= 8 && password === confirmPassword){

            console.log("First Name: " + firstName);
            console.log("Last Name: " + lastName);
            console.log("Email Address: " + emailAdd);
            console.log("Password: " + password);
            console.log("confirm Password: " + confirmPassword);
            console.log("Information accepted.")

    } else {

        console.log("Please fill in your information.")
    }

}
getInfo();

Would you use an if else statement [closed]

I am looking to tackle this question but was wondering how would you go about it. I was thinking an if else statement, would this be the best way to tackle this question. Any suggestions would be great help.

A manager pays his sales staff commission according to the following rules:

1-5 clients: £15 6-10 clients: £30 11-15 clients: £45

how would you go about tackling this problem to ensure the sales staff are paid the correct amount.

Any suggestions would be much appreciated.

How To Make Blacklist And Skip blacklist String on PHP

    for ($i= 999; $i <= 99999; $i++){
        $cek = $i;
        $url = "http://rindsomxxxxxx.com/$cek";
        $headers = get_headers($url);
        $bom=explode(" ",$headers[0]);
        if ($bom[1] == 200) {
      $filess = "blacklist.txt";
      $handle = fopen($filess, 'a');
      fwrite($handle,  $cek);
      fwrite($handle, "\n");
      fclose($handle);
}}

Hello i Have PHP Code like that and i want to make some blacklist so when, $cek already found match number it will add to blacklist for next loop, how to add blacklist then? and how to make loop not from number 999 again when already meet blacklist number. ex: blacklist number 29912, and it will skip 29912 number to 29913.

Can I have a nested OR statement within my Ternary If statement?

I am wondering if it is possible to turn this statement of code into a ternary if statement.

var placeHolder = await Source.EntityOrDefaultAsync<_Item>(item => item.CompanyID == order.CompanyID && item.ItemID == od.ItemID);

                if (placeHolder.TaxedAllCountryRegions = true || placeHolder.TaxedFed == 1 && placeHolder.TaxedState == 1)
                {
                    decimal.TryParse(placeHolder.HandlingFee, out decimal trueFee);
                    od.HandlingFee = trueFee * od.Quantity;
                }

I tried formatting it like this- but don't think it quite works.

 var placeHolder = await Source.EntityOrDefaultAsync<_Item>(item => item.CompanyID == order.CompanyID && item.ItemID == od.ItemID);

                return (placeHolder.TaxedAllCountryRegions = true || placeHolder.TaxedFed == 1 && placeHolder.TaxedState == 1) ?
                                                                                                                                decimal.TryParse(placeHolder.HandlingFee, out decimal trueFee)
                                                                                                                                : false;
                od.HandlingFee = trueFee * od.Quantity;

refresh page at a specific time

hear me out. suppose a page has to be reloaded every weekday at 9:30 am. the page is opened at 9 am. so at 9:15 am the page should automatically get reloaded without any user intervention. what can be done. any help is appreciated

 function checkTime() {
        var d = new Date(); // current time
        var hours = d.getHours();
         var mins = d.getMinutes();
         if (hours >= 17 || hours <= 18) {
          setInterval(() => {
           location.reload();
             }, 5000);

                   }

                }

How to Find Missing Value index in if statement?

I Need To Compare Data From SQL And From Selemium Parser Point Is If i get new Values From Selenium insert those values into SQL update existing values They Look Like This

Outcome From Parser

ds

FIELD1 date Price id
0 Thu Apr 29 10:01 EDT $2.07 73e14f90-f482-4757-9ddb-494e2b9041b7
1 Thu Apr 29 10:01 EDT $2.06 1cf6102a-7b3c-4318-8b9e-77f3b8e32af1
2 Thu Apr 29 10:01 EDT $2.07 a72c8d39-2930-4ecd-a77b-785da6712b24
3 Thu Apr 29 10:30 EDT $2.25 b4e0e9ef-dbe1-407c-8584-b3998c915dde
4 Thu Apr 29 10:46 EDT $2.34 95c3db89-c1c7-423a-8fdb-21ecf55e0bf1
5 Thu Apr 29 09:30 PDT $2.52 8123054b-e9c9-4785-a071-67bcc20b8b96
6 Thu Apr 29 11:45 MDT $2.57 62decf1f-ebda-47ff-bedb-67e3b88c3c57
7 Thu Apr 29 11:30 PDT $2.63 a1116a78-f2b5-470c-a09d-7663b52472f5
8 Thu Apr 29 14:28 PDT $2.02 f6c7c815-c045-41a3-a0a4-0e15b1a60e57
9 Thu Apr 29 18:00 EDT $2.36 479b0f16-0688-4ceb-aedd-9bb61d8fa781
10 Thu Apr 29 18:00 PDT $2.44 f20addf7-0243-487e-9943-fe2dc8bfab2b
11 Thu May 6 18:30 PDT $2.11 40c70728-7da4-481f-bfc9-96648e10eab1
12 Fri May 7 18:30 PDT $3.00 e1b648fa-38ef-4f22-9a7b-0f79abdaa769
13 Sat May 8 17:30 PDT $2.11 fc8d61b1-692f-4c7c-9128-ba98e24564de
14 Sat May 8 18:00 PDT $2.00 b9e20c68-f72c-44e7-8c5a-fe3acee664fa

Data In SQL

df

FIELD1 date Price id
1 Thu Apr 29 19:00 PDT $2.06 e9c20a97-5cd9-4702-94a2-14865604100b
2 Thu Apr 29 19:00 PDT $2.83 001b3c03-87b6-4e2b-807d-fcb94dda1368
3 Thu Apr 29 19:00 PDT $2.44 6a97651b-7f9b-4c48-ba77-97319e34e5b1
4 Fri Apr 30 02:30 PDT $2.20 dd14367d-7282-4230-92c1-3bcde778d391
5 Fri Apr 30 04:45 PDT $2.31 3602df69-a4ff-466e-af07-5f812c32d792
6 Fri Apr 30 11:45 MDT $2.07 0e28cb3d-8b6e-4a7e-8658-0203292ee92a
7 Sun May 2 01:45 MDT $2.06 423dfd39-ba13-4742-b856-d9dab2874f6b
8 Sun May 2 01:45 MDT $2.08 bd112d74-1410-40bc-aa9e-f39773703d5d
9 Tue May 4 18:30 PDT $2.11 6be45a63-be2c-4391-ad33-ce7d95009719
10 Thu May 6 18:00 PDT $2.11 b1e6c047-793f-4e35-9854-f4df0ed975c6
11 Thu May 6 18:30 PDT $2.11 40c70728-7da4-481f-bfc9-96648e10eab1
12 Fri May 7 18:30 PDT $2.11 e1b648fa-38ef-4f22-9a7b-0f79abdaa769
13 Sat May 8 17:30 PDT $2.11 fc8d61b1-692f-4c7c-9128-ba98e24564de
14 Sat May 8 18:00 PDT $2.11 b9e20c68-f72c-44e7-8c5a-fe3acee664fa

How Can I Caompare Those Datasets And If There Is New Values In Parser Write Row With These id and if not update existing values

I thought

ds = pd.Dataframe(parser)
df = pd.Dataframe(sql)
for i in ds['id']:
    if i in df['id']
        df.append(i)
    else:
        df.insert(row index to insert specific row)

The Id unique and will remain same, but price and date can Change, how i can update SQL values if values changed in parser without overwriting it, and append or insert specific values to PostgresSQL from parser

how to make the proper if-statement for memory game

I am doing a memory game for a school project and i am having a hard time with the javascript... I need to make an if statement that compares the cards and then if they match up, then you get a score and if not then they turn around again. and i have no idea how to do it. (the console log's are just to see if the code was working)

vanilla javascript only :)

codepen:

https://codepen.io/anna100d/pen/wvgQLdW

//Function for the dropdown content
function dropdownTips() {
    document.getElementById("mydropdown").classList.toggle("show");
}


window.addEventListener("click", function(event) {
if (!event.target.matches('.dropbtn')) {

        var dropdowns = document.getElementsByClassName("dropdowncontent");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
             if (openDropdown.classList.contains('show')) {
             openDropdown.classList.remove('show');
            }
        }
    }
});

//the game
let score = 0;

const cards = document.getElementsByClassName("card");


for (let i = 0; i < cards.length; i++) {
    cards[i].addEventListener("click", function() { 
        cards[i].classList.add("open"); 
        console.log(this.id)
        
        if (document.getElementById(this.id).getAttribute('type') === document.getElementById(this.id).getAttribute('type')  ) {
            console.log("hello");
        } else {
            console.log("byebye");
        }
        });
}
* {
  margin: 0;
  padding: 0;
  font-family: 'Lato', sans-serif;
}

header {
  background-color:#00005e;
  height: 60px;
  position: relative;
}

header h1 {
  color: white;
  position: absolute;
  top: 17%;
  left: 39%;
  right: 40%;
  width: 355px;
}

/*The 'tips?' button and the drop down content*/
header button {
display: inline-flex;
position:absolute;
align-items: center;
right: 2%;
top: 15%;
bottom: 15%;
padding: 10px 20px;
font-size: 20px;
background-color:white;
color: #00005e;
border-radius: 10px;
cursor: pointer;
border-color: transparent;
}

header button:hover {
opacity: 80%;
}


.dropdowncontent {
display: none;
position: absolute;
right: 0%;
top: 100%;
background-color:#00005e;
min-width: 160px;
max-width: 400px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
border-bottom-left-radius: 20px;
z-index: 100;

}

.dropdowncontent li {
color: white;
padding: 12px 16px;
text-decoration: none;
display: block;
}

.advise{
font-size: 19px;
}

.passwordtips {
font-size: 30px;
left: 20%;
}

.show {
display:block;
}

/*The link in the dropdowncontent*/
a {
text-decoration: underline;
color: white;
}

a:hover {
cursor: pointer;
}

/*The score counter*/
.score {
  color: #01016e;
  display: flex;
  justify-content: center;
  margin: 20px;
}

/*The game section*/
section {
  max-width: 1300px;
  height: 550px;
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  border-radius: 7px;
  border-color: #00005e;
  border-style: solid;
  border-width: 5px;
  position: relative;
}

/*The sections content*/
.wrapper {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 185px;
margin-top: 7px;
}

.card{
background-color: #01016e;
color: white;
margin: 10px 10px;
height: 150px;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
font-size: 0;
border-radius: 5px;
}

.card h2{
  padding: 2px;
  transform: scale(-1,1);
}

.card:hover {
cursor: pointer;
}

.open{
animation: flip .5s;
animation-fill-mode: forwards;
transform-style: preserve-3d;
}

@keyframes flip {
from { 
  background: #00005e;
  font-size: 0;
}
to{
  background: rgb(20, 73, 185);
  font-size:17px;
  transform: rotateY( 180deg );
}
}

/* .welcome {
display: flex;
justify-content: center;
text-align: center;
color: #3c3b6e;
margin-top: 100px;
font-size: 50px;
clear: both;
position: absolute;
}

.startbutton {
display: flex;
justify-content: center;
align-self: center;
margin-top: 100px;
position: absolute;
background-color: #00005e;
color: #e8ebf1;
padding: 10px;
font-size: 30px;
border-radius: 4px;
z-index: 0;
border-color: transparent;
}

.startbutton:hover{
cursor: pointer;
background-color: #3c3b6e;
}
*/

/*The game*/


/*The 'DID YOU KNOW' over the ticker*/
.facts {
display: flex;
justify-content: space-around;
margin-top: 30px;
font-size: 20px;
color: #00005e;
}

/*The facts ticker*/
.tcontainer {
max-width: 1200px;
margin-top: 20px;
overflow: hidden;
margin-left: auto;
margin-right: auto;
border-radius: 5px;
z-index: 1000;
}

.ticker-wrap {
width: 100%;
padding-left: 100%; 
background-color: #00005e;
}

@keyframes ticker {
0% { transform: translate3d(0, 0, 0); }
100% { transform: translate3d(-100%, 0, 0); }
}
.ticker-move {
 display: inline-block;
white-space: nowrap;
padding-right: 100%;
animation-iteration-count: infinite;
animation-timing-function: linear;
animation-name: ticker;
animation-duration: 55s;
}
.ticker-move:hover{
animation-play-state: paused; 
}

.ticker-item{
display: inline-block; 
padding-top: 5px;
padding-bottom: 2px;
padding-right: 3em;
color: white;
min-height: 40px;
font-size: 25px;
}


/*The pause button for the ticker*/
.pause {
display: flex;
justify-content: center;
margin-top: 10px;
}

.pausebutton {
padding: 5px;
border-radius: 3px;
background-color: #00005e;
color: white;
border-style: none;
cursor: pointer;
}

.pausebutton:hover {
background-color: #3c3b6e;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Lato:wght@700&display=swap" rel="stylesheet">
    <link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
    <title>The Password Game</title>
</head>
<body>
    <header>
        <h1>THE PASSWORD GAME</h1>

        <div class="dropdown">
            <button onclick="dropdownTips()" class="dropbtn">TIPS?</button>
            <div class="dropdowncontent" id="mydropdown" >
                <ul>
                    <li class="passwordtips">Tips for making strong passwords: </li>
                    <li class="advise">1. Use 16 characters or more (use both uppercase and lowercase letters, number and symbols.)</li>
                    <li class="advise">2. Never use the same password twice.</li>
                    <li class="advise">3. Use a password manager.</li>
                    <li class="advise">4. Don't write your passwords down on paper.</li>
                    <li class="advise">5. Don't share your passwords with others.</li>
                    <li class="advise">6. Change your password after a breach.</li>
                    <li class="advise">7. Sign up for data breach notifications. (like <a href="https://haveibeenpwned.com/" target="_blank">haveibeenpwned.com</a>).</li>
                    <li class="advise">8. Check your accounts regularly for any suspicious activity. </li>
                </ul>
            </div>
        </div>
    </header>

    <div class="score"><h2></h2></div>

    <section>
        <div class="wrapper" id="card-deck">
            <div id="cardOne" class="card"  type="1"><h2>What information should you NEVER use in a password?</h2></div>
            <div id="answerSix" class="card"  type="6"><h2>1 log in</h2></div>
            <div id="cardThree" class="card"  type="3"><h2>When should you ALWAYS change your password?</h2></div>
            <div id="anserFive" class="card"  type="5"><h2>suspicious activity</h2></div>
            <div id="cardTwo" class="card"  type="2"><h2>Who is it okay to tell your password to?</h2></div>
            <div id="answerFour" class="card" type="4"><h2>16</h2></div>
            <div id="answerThree" class="card" type="3"><h2>After a data breach</h2></div>
            <div id="answerTwo" class="card" type="2"><h2>No one</h2></div>
            <div id="CardSix" class="card" type="6"><h2>For how many log ins is it okay to use the same password?</h2></div>
            <div id="cardFour" class="card" type="4"><h2>How many characters should you AT LEAST use in a password?</h2></div>
            <div id="answerOne" class="card" type="1"><h2>Name and Birthday</h2></div>
            <div id="cardFive" class="card" type="5"><h2>What should you regularly look for in your accounts?</h2></div>
        </div>
    </section>

    <div class="facts">
        <h2>DID YOU KNOW?</h2>
    </div>

    <div class="tcontainer"><div class="ticker-wrap"><div class="ticker-move">
        <div class="ticker-item">There is a hacker attack every 39 seconds.</div>
        <div class="ticker-item">90% of passwords can be cracked in less than 6 hours.</div>
        <div class="ticker-item">80% of hacking related breaches are linked to insufficient passwords.</div>
        <div class="ticker-item">59% use their name or birthday in their password.</div>
        <div class="ticker-item">6.850.000 passwords are getting hacked each day.</div>
      </div></div></div>

    <div class="pause">
        <p>Hold your mouse over to pause</p>
    </div>
    <script src="javascript/javascript.js" ></script>
</body>
</html>

writing a function that finds bigger numeric value [closed]

def bigger_number_return(a,b): 

    if a > b:
        return a
    else:
        return b
a= input("enter a numberic value for a:")

b= input("enter a numberic value for b:")

What should I do to make it in working condition?

Django templates if function

i want to check if there is and object in 2d list in djnago template

i have object of person and list of emails where key is person and value is email address.

I'd like to achieve something like this:


C++ ignoring else if [duplicate]

The point of this program is to get a 2 digit number input and if the number is smaller or equal to 15, return the number squared, if the number is bigger or equal than 16 and smaller or equal to 30, return the sum of it s digits and if it is bigger or equal to 31, it should return the product of its digits.

This is the code I wrote so far:

#include <iostream>
using namespace std;

int main()
{
    int a;
    cout << "dati a: ";
    cin >> a;
    if (a >= 100 || a)
    {
        cout << "a trebuie sa aiba 2 cifre" << endl
             << "mai dati incercati o data: ";
    }

    if (a <= 15)
    {
        cout << a * a;
    }
    else if (16 <= a <= 30)
    {
        cout << a / 10 + a % 10;
    }
    else if (a >= 31)
    {
        cout << (a / 10) * (a % 10);
    }
}

I compile it and run it and testing goes like this. I give it 10, it returns 100, I give it 23 it returns 5, I give it 29 it returns 11 and the i give it 31 it returns 4, i give it 38, it returns 11. I tend to believe that it goes over the last else if, but i don't know the true reason.

How to check two conditions for one variable?

Very basic issue that I do not understand:
My variable step has be 1 or 5 and I want to check it with if statement, and raise an error if the condition is not verified.

step = input("Choose a step, in nm, for the wavelength (1 or 5):")
if (
        (step != 1) or (step != 5)
):
    raise ValueError

But if I declare 1 or 5 for step I end with a ValueError.

I tried to do the thing in reverse, checking if step is equal to 1 or 5 but without success. And also with the if ... not in but no success to.

I am sure this is a very basic little thing but I don't see it.

Thanks for help

What does the PHP interpreter do at if("test")

I've a small question behind a bug I found in a customers code. There is a PHP if-statement, which is true at every time. There was something like

if("test"){
}

What does the PHP interpreter exactly do? Like if "test" can be stored in the RAM or if "test" == "test"? Thank you for you help :)

Why is my if statement just skipping past the first part?

This code is meant to output the doctor's name and specs, but it is skipping this and just outputting that it is not available

    private void listDoctors()
{
   //Zachary Thompson 23/04/2021 List all the doctors and their information 
       if(doctor1!=null)
   {
        System.out.println("Doctor 1 = ");
        System.out.println(doctor1.getName());
        System.out.println(doctor1.getSpecialisation());
    }
   else 
   {
       System.out.println("Doctor 1 is not available");
    }
   if(doctor2!=null)
   {
        System.out.println("Doctor 2 = ");
        System.out.println(doctor2.getName());
        System.out.println(doctor2.getSpecialisation());
    }
   else System.out.println("Doctor 2 is not available");
}

mercredi 28 avril 2021

Google app script IF condition not matching 0, empty and null

I have issues with Google app script IF condition. Problem i am facing its not returning value TRUE rather going to next/ Else statements. Code i am having:

const numberOfRowsToUpdate = deliveryDate.length;

// For each item making the for loop to work
for (i=0 ; i < numberOfRowsToUpdate;i++) {
    debugger;
  var dp = depositAmount[i];
  if(dp!==""|| dp!==0 || dp !==null || dp!==isblank())
   { .... <statements>
   }
}

I want to check whether particular cell of the array is empty / zero / returning null value.

thanks in advance for the help.

Multiple if condtions in a single statement

I am trying to check if a username and userId exists and either a like or a comment exists then return something. And I am using two if conditions for this :

if (username && userID) {
  if (like || comment) {
    return something
  }
}

Is there any way to fit bot the conditions into one single statement. Also, here the username is immutable.

how to use if function in classes (I'm just a beginner so take it easy with me)

so here i'm trying to make a simple library that user can add and remove books from his shopping cart, but idon't know how to use if function with oop and classes

try:
 class library:
     def __init__(self, books, costumer):
         self.books = books
         self.costumer = costumer
    # sign:
     check = input("manager account(1),costumer account(2): ")

     if check == "2":
    #age >= 18
         age = int(input("enter your age:  "))   
         if age >= 18:
            #name
             name = input("enter your firstname: ")

            # ID
             import random
             x = "ID"+str(random.randint(101,999))
             print(f"your ID is: {x}")
             print("you should memorize it")
             y = input("enter password that has at list 8 caracterse: ")

            # Password
             while len(y) < 8:
                 y = input("enter password that has at list 8 caracterse: ")
                 print(f"your password is: {y}")
             print("you should memorize it")
             data = [x,y]
             choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): \nremove books from your shopping cart(3): ")
             if choice_1 == "1":
                 def __str__(self):
                    return f"costumer {self.costumer} bought those books{self.books}"
             elif choice_1 == "2":
                 def __iadd__(self, other):
                     self.books.append(other)
                     return self

 order = library(["the golsen company"],"Mr.asad")
 print(order.books)
 order += input("enter a book: ")
 print(order.books)
except ValueError as ages:
    print(ages)

i don't know if this is the right way to use if function with classes so if you can just give me an exampl to show me how to use if function with classes

equivalent for loop in python for this loop which is written C++ [closed]

I am trying to write a for loop in python which is written in C++, while converting the loops of C++ to python I am facing diffculities.

for(int len = 1; len < n; len++){
    for(int i = 0; i + len < n; i++){
       // bla bla bla code
    }
}

How can i write the inner for loop in python ?? Any generalized approach which can work in every scenario ?? If the Question is duplicate one sorry for this I couldn't know what and how to search in google about this.

Can I please get some help in this problem from you. Thanks In Advance.

How to use ifelse inside map function in R

I am having problems with this ifelse sentence inside map function:

df<-list(mtcars,mtcars)

All I want to do is to organize each dataframe of this list this way:slice(x,c(n(),2:(n()-1),1))

map(df, ~   slice(.x,c(n(),2:(n()-1),1)))   # it works well. 

But I cant do this inside ifelse when I set the condition x$cyl == 4:

map(df, ~   ifelse(sum(.x$cyl == 4) > 0, slice(.x,c(n(),2:(n()-1),1)), .x)) # The output is weird

I tried to do the same using lapply but its not working:

lapply(df, function(x) ifelse(sum(x$cyl == 4) > 0, slice(x,c(n(),2:(n()-1),1)),x))

Any help?

How would I make it so if any number bigger than 10 or less than 10 it would say "wrong answer"?

I am trying to make a code so if the answer is less than 10 or more than 10 it says "wrong answer" I just testing somethings right now I'm very new to coding. right now I have:

#include <iostream>
#include "log.h"

int main()
{
    MultiplyAndLog2(5, 2); // this is what is going to be multiplied
    
    int x = 11;

    if (x == 10) // I have it so I if it equal to 10 it says right answer
        Log("right answer");
    
    if (x == )  // Heres where im stuck I dont know what to add if any number other than 10 is the answer
        Log("wrong answer");    
    
    std::cin.get();
}

Heres my log.h its a bit messy...

#pragma once

int Multiply(int a, int b, int c) // this is so I can multiply 3 integers at a time just for testing.
        {
            return a * b * c;
        }

int Multiply(int a, int b) // this is the same thing but for 2 integers at a time
{
    return a * b;
}

void MultiplyAndLog(int a, int b, int c) // this is so that whatever 3 integers are multiplied it would say answer: and then the answer to the question
{
    int result = Multiply(a, b, c);
    std::cout << "answer:" << result << std::endl;
}

void MultiplyAndLog2(int a, int b) // this is so that is 2 integers are multiplied it would say answer: and then the answer to the question
{
    int result = Multiply(a, b);
    std::cout << "answer:" << result << std::endl;
}

void Log(const char* message)  // This is so if I type Log I can write whatever I want for example "right answer"
{
    std::cout << message << std::endl;
}

Thank you, Mario

if/else logic using NULL

I'm not sure if I understand the conditionals using = NULL and != NULL.

Is this

if (somethin->example == NULL) 
{
   do task A 
   return;       
}
    
else
{
   do task B
}

the same as this?

if (somethin->example != NULL) 
{        
   do task B  
}
    
else
{  
   do task A
   return;
}

measuring matrix distances within a python loop

i have the below code which draws circles on a matrix by changing points from 0s to 1s:

def renderCircle(Nx,Ny,radius): #function for drawing circles at x,y with radius r
  x = np.round(radius*x_circ+Nx).astype(int)
  y = np.round(radius*y_circ+Ny).astype(int)
  for i in range(len(x)):
   if x[i]>0 and x[i]<1024 and y[i]>0 and y[i]<1024: #ensuring plotted points are within the grid
    S[x[i], y[i]] = 1

i then loop this function over different start points (Nx and Ny) and over a list of radii (multiple circles are plotted from each start point. i need to add a section which will not plot the points from circle A if they are within any of the other circles - effectively an if statement which would say

if x[i] and y[i] are outside r[all other circles]: 
   S[x[i], y[i]] = 1

appreciate this may be a bit confusing but any help is hugely appreciated

Java program "entering" if statement despite not meeting condition [duplicate]

I have what would be a simple if statement to check if two strings are null.

 if (airlineID == "null" && airportID == "null"){
        JOptionPane.showMessageDialog(null, "Airline and airport do not exist or are incorrect");
}
else if (airlineID == "null") {
        JOptionPane.showMessageDialog(null, "Airline incorrect or does not exist");
}
else if (airportID == "null") {
        JOptionPane.showMessageDialog(null, "Airport code incorrect or does not exist" );
}
else if (airlineID != "null" && airportID != "null"){ // 4.1 If they both exist, then proceed
        // Do stuff
}

However, no matter the actual contents of airportID or airlineID, it always enters the last statement.

Here is a picture from the debugger showing the statement enter image description here

The blue line is where the program is currently at, as you can see it's entered the last if statement despite not meeting the requirements.

Here's a picture from the variables' values to confirm

enter image description here

Note: I have "null" as a string because the server sends the reply back as a string.

C++ Add secondary integer for couting values

I’m Alexander, I’m an Arduino UNO and C++ beginner.

I’m stuck trying to add a secondary integer for counting values. I suspect that the issue is within the first if statement in the loop.

I have two integers, one for Home and one for Away. Would anyone happen to pinpoint how I can add my secondary integer (Away) within or at least as a member of this if statement?

 if (currentHomeState != previousHomeState) {
previousHomeState = currentHomeState;

if (currentHomeState == On) {
  if ( (msec - msecLst) > Interval)  {
    msecLst = msec;
    numberOfGoals++; 
}

The complete program:

/*
Program for the 1960s Panco Mini-Match table top soccer game.
*/

#include <SSD1320_OLED.h>

// Initialize the display with the follow pin connections.
SSD1320 flexibleOLED(10, 9); //10 = CS, 9 = RES

// Define constants for home and away team.
const int Home = A1;
const int Away = A2;

// Define constants for LED pins.
const int LED_1 = 7;    // Pin 7 connected to a LED, turns HIGH when away team score.
const int LED_2 = 8;  // Pin 8 connected to a LED, turns HIGH when home team score.

enum { Off = HIGH, On = LOW };

#define Interval  1000

// Initalize and define states for the goal sensors.
int currentHomeState = 0, previousHomeState = 0;
int currentAwayState = 0, previousAwayState = 0;

int numberOfGoals = 0;

unsigned long msecLst = 0;

void setup() {
  //Run once

  //Initilize the display
  flexibleOLED.begin(160, 32);  //Display is 160 wide, 32 high
  flexibleOLED.clearDisplay();  //Clear display and buffer

  //Display Home score
  flexibleOLED.setContrast(255);
  flexibleOLED.setFontType(2); //7-segment display style characters, 10x16-pixels each.
  flexibleOLED.setCursor(45, 7);
  flexibleOLED.print(numberOfGoals);

  //Display Away score
  flexibleOLED.setContrast(255);
  flexibleOLED.setFontType(2); //7-segment display style characters, 10x16-pixels each.
  flexibleOLED.setCursor(95, 7);
  flexibleOLED.print(numberOfGoals);
  flexibleOLED.display();
  pinMode(Home, INPUT_PULLUP);
  pinMode(LED_1, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  unsigned long msec = millis ();
  //Run repeatedly
  currentHomeState = digitalRead(Home);
  currentAwayState = digitalRead(Away);

  if (currentHomeState != previousHomeState) {
    previousHomeState = currentHomeState;

    if (currentHomeState == On) {
      if ( (msec - msecLst) > Interval)  {
        msecLst = msec;
        numberOfGoals++;
        Serial.println (numberOfGoals);

        flexibleOLED.setContrast(255);
        flexibleOLED.setFontType(2); //7-segment display style characters, 10x16-pixels each.
        flexibleOLED.setCursor(45, 6);
        flexibleOLED.print(numberOfGoals);
        flexibleOLED.display();

        digitalWrite(LED_1, HIGH);
        delay(250);
        digitalWrite(LED_1, LOW);
      }

      if (numberOfGoals == 5) {
        digitalWrite(LED_1, HIGH);
        delay(250);
        digitalWrite(LED_1, LOW);
        delay(250);
        digitalWrite(LED_1, HIGH);
        delay(250);
        digitalWrite(LED_1, LOW);
        delay(250);
        digitalWrite(LED_1, HIGH);
        delay(250);
        digitalWrite(LED_1, LOW);
        delay(250);
        digitalWrite(LED_1, HIGH);
        delay(250);
        digitalWrite(LED_1, LOW);
        delay(250);
        digitalWrite(LED_1, HIGH);

      }

      if (numberOfGoals == 5) {
        numberOfGoals = 0;
        delay(250);
        digitalWrite(LED_1, LOW);

      }

      if (numberOfGoals == 0) {

        flexibleOLED.clearDisplay(); // Clear display and buffer
        flexibleOLED.setContrast(255);
        flexibleOLED.setFontType(2); //7-segment display style characters, 10x16-pixels each.
        flexibleOLED.setCursor(45, 6);
        flexibleOLED.print(numberOfGoals);
        flexibleOLED.display();
        Serial.println (0);

      }

    }
  }
}

In another forum a user wrote to me that I needed to make a sub-function with arrays, although this is fairly new to me I came up with something like

int main(int argc, char** argv) {
string teams[2] = {"Home", "Away"};
int numbers[1];
for(int i = 0;i<1;i++) 
{
// not yet sure what to add here.
} 
for(int i = 1;i<1;i++)
{
// not yet sure what to add here.
}
return 0;
}

Would anyone happen to share their thoughts on whether or not I am close to figuring this one out?

Your time and help are very much appreciated.

If else loop is skipping if clause [if(2 > 1) ] and moving straight to dead code in the else clause. gRPC instantiation

I'm in the midst of the crunchier end of a gRPC project and I have no idea what is going wrong in this rpc. I am testing the RPC with Bloom and it is continually just executing the final clause and skipping the first one. Had thought it was a gRPC issue but after a lot of editing I tried changing the loop to a guaranteed true just to ensure it was executable and it continued to skip over it.

I am relatively new so I am sure I made some terrible design choices but I can't see anything catastrophically bad. Project was created with Maven for what it is worth

@SuppressWarnings("static-access")
@Override
    public void mWClock(targetRoom request, StreamObserver<lockStatus> responseObserver) {
    int key = request.getTarget();
    int trigger = 0;
    //lockStatus response;//null added due to promp to initialize
    //lockStatus response2;
    if (key == 0) {
        //success
        do {
            CapacityService.MaleWC().newBuilder()//These are throwing up warnings. Unsure how to address
            .setPopulation(randomInt(5));//randomly simulate the movement of people into the room
            try {
                Thread.sleep(30000);//5 minute intervals, reduce for quick demo
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (OutOfMemoryError e) {//Using thread indefinitely could eventually cause memory issues
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            //THIS WAS THE ORIGINAL COMPARISON BEFORE CHANGING TO 2 > 1
            //if(CapacityService.MaleWC().getPopulation() >= CapacityService.MaleWC().getCapacity()) {
            if(2 > 1) {
                CapacityService.MaleWC().newBuilder()
                .setLock(true);
                trigger++;
                //
                String result1 = "Male Bathroom is currently at or over capacity, please wait";
                lockStatus response = lockStatus.newBuilder()
                        .setStatus(result1)
                        .setSpaces(0)
                        .build();
                responseObserver.onNext(response);
                
                
                try {
                    Thread.sleep(30000);Just to delay returns and simulate movement. 
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }catch (OutOfMemoryError e) {//Using thread indefinitely will eventually cause memory issues
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                CapacityService.MaleWC().newBuilder()
                .setPopulation(randomInt(3));//To reduce it below capacity so the loop continues at while loop
                
            }else {
                int space = CapacityService.MaleWC().getCapacity() - CapacityService.MaleWC().getPopulation();
                if(space < 0) {
                    space = 0;//Ensure no negative value for return
                }
                trigger++;
                String result2 = "Male Bathroom is currently available for use";
                lockStatus response = lockStatus.newBuilder()
                        //response.newBuilder()
                        .setStatus(result2)
                        .setSpaces(0)
                        .build();
                responseObserver.onNext(response);
                
                
            }
            //end of do loop
        }while(trigger < 3000);
        responseObserver.onCompleted();
        
        

        
    }else {
        //failure, wrong number entered. TO DO
        responseObserver.onCompleted();
    }

}

The MaleWC object is a message from a different services proto being imported here and instantiated at the top. What may possibly be of note is that I was unable to import the proto file where the Room message was created into the proto file with the MWClock service but I don't know if that affects anything. I'm also not overly sure if the static access warning could be causing the issue

@SuppressWarnings("static-access")
@Override
    public static Room MaleWC() {
    return Room.newBuilder()
            .setCapacity(3)
            .setPopulation(0)
            .setLock(false)
            .build();
}

The server is definitely working from what I can tell. It just keeps jumping to the else clause. Can anyone shed some light? Can share the proto file for the service if it's needed but I'm guessing the proto is fine as it's returning the correct stuff from the else statement, unless the issue was caused by the importing snaffoo mentioned earlier.

Using IF and conditional formatting

I'm trying to have a cell becoming highlighted if it satisfies two criteria.

I would like the cells below each Staff column to be purple if its both the same as the version# and contains . I've managed to highlight cells containing the * by using "highlight if cells contain" ~ but I can't get it to do both.

Image of excel table in question highlighting cells containing *

I've tried

=AND(L2=$J2,"~*")

=AND($J2,"~*")

=IF(AND(L2=$J2,"~*"))

(Version# is column J, Staff 1 is column J)

Using if-condition in pandas to fill na values in pandas

I have some columns in df where one of the columns has a missing value. I need to fill them but only when the ColumnY has a False value.

Here is how df looks

A                 B                    C
Value             4                    True
v3                9                    True
v9                                     False
v0                4                    False

I have a dictionary which I am using to map the values in column B ... di_map

df['B'].map(di_map)

Here is how output should look

A                 B                    C
Value             4                    True
v3                9                    True
v9                New_Val              False
v0                New_Val              False

Python: Make program react to keywords in a string without endless if-else nightmare

So, the real world context for this is a chatbot I'm working on, but here is a condensed version of what I'm trying to accomplish.

The function is supposed to take a message, look if it contains certain keywords (some are case sensitive and some aren't) and print one response. Currently my code looks something like this:

def func(msg):
    msg_low = msg.lower()
    
    if "keyword_1" in msg_low:
        print("Reaction 1")
    elif "KeYwOrD_2" in msg:
        print("Reaction 2")
    elif "keywords_3" in msg_low:
        print("Reaction 3")

and so on, it feels very wrong.

This feels like it should have a very trivial solution, but I just can't figure it out. The two biggest issues are that I want to preserve the priority of keywords and that to deal with case sensitivity I essentially deal with two different messages (msg and msg_low) in a single if-else block.

Counting multiple used if statments in one loop

Currently learning C and I could use a bit of a nudge in the right direction. I'd like to know what options I have for stage I'm at. Not know much of anything you all will know what terms to search for.

I need to provide a print out of the number of correct / incorrect guesses and times the game was played.

In essence tally how many times each of the 3 if statements have been used within a while loop.

I'm thinking I'd like to have 3 variables for each if statement that can be a used as a tally and added up each time it's accessed. I'd think I'd like to use an array as I've not yet practiced with that and would be a neat way to tally and recall values.

It's for an assignment so I've only provided a general skeleton of the code to avoid any issues with that.

Any thoughts on how to approach this would be appreciated.

          /* While loop to continue game */
        while (code) {
            
            /* Code to prompt for and read the user’s guess. */
            printf("txt")
            scanf();
            

            /* If guess is correct. */
            if (test code) {
                printf("txt");
                *code to count correct guess here*

            }
            /* If guess is incorrect but an odd number. */
            if (test code) {
                printf("txt");
                *code to count incorrect guess here*
            }
            /* If guess is incorrect but an even number. */
            if (test code) {
                printf("txt");
                *code to count incorrect even guess here, maybe do a double tally with above?*
            }
            /* Ask to play again. */
                printf("txt"); 
                scanf();
                *code to count games played here*
    
                if (code) {
                    printf("txt")
                    exit(EXIT_SUCCESS);

how to set up a search with an "if" statement for arrays, very basic app (swift)

I'm working on a basic app which has a listArray with ~1400 items, each with 3 properties (icao, callsign, image). It has 2 outlets: a "textField" and a "label". With my custom keyboard(buttons) i can write 3 characters into my "textField". And if these 3 characters are matching with the icao item of my listArray, then I would like the callsign item to be shown in my "label". Is there a way to do it with an "if" statement? I would like to see "AMERICAN" in the "label". Here is what I have: my xcode and simulator screens

  @IBOutlet var ICAOtextField: UITextField!
@IBOutlet var callsignTextLabel: UILabel!

var updatedICAOtextField = ""
var listArray = [list]()

override func viewDidLoad() {
    super.viewDidLoad()
    setUpList()
}

private func setUpList() {

listArray.append(list(icao: "AAB", callsign: "A-B-G", image: "BELGIUM"))
listArray.append(list(icao: "AAC", callsign: "ARMYAIR", image: "UK"))
listArray.append(list(icao: "AAF", callsign: "AZUR", image: "FRANCE"))
listArray.append(list(icao: "AAL", callsign: "AMERICAN", image: "USA"))
}

@IBAction func abcButton(_ sender: UIButton) {
    
    updatedICAOtextField = ICAOtextField.text! + sender.currentTitle!
    ICAOtextField.text = updatedICAOtextField
    
    if updatedICAOtextField.count > 3 {
        ICAOtextField.text = ""
    }
    
    if ICAOtextField.text ==                           {
        
        callsignTextLabel.text = "            "
    }
    
}

elif not working on dictionary key-value pairs

I am writing a function to clean data of dictionary which contains a key-value pairs showing a date and the rainfall on that date. The conditions for the cleaning of data requires the removal of and key-value pairs where the values meet the following conditions:

  • the type is not an integer or a float. Even if the value is a string that could be converted to an integer (e.g. "5") it should be deleted.
  • the value is less than 0: it's impossible to have a negative rainfall number, so this must be bad data.
  • the value is greater than 100: the world record for rainfall in a day was 71.8 inches
def clean_data (adic):
    newDic = {}
    for (date,inches) in adic.items():  
        print (date,inches)
        if not type(inches) == float:
            if not type(inches) == int:
                print ("type")
                continue
        elif inches < 0:
            print ("below 0")
            continue
        elif inches > 100:
            print ("above 100")
            continue
        else:
            print ("added")
            newDic[date]=inches
    return newDic



rainfall = {"20190101": 5, "20190102": "6", "20190103": 7.5, 
           "20190104": 0, "20190105": -7, "20190106": 102,
           "20190107": 1}
print(clean_data(rainfall))

For some reason my code is outputting:

20190101 5
20190102 6
type
20190103 7.5
added
20190104 0
20190105 -7
20190106 102
20190107 1
{'20190103': 7.5}

So many of the key-value pairs are not behaving with the elif statements as I would expect. I can't figure out for example why the first key-value pair of 20190101 5 passes through all the if/elif statements put is not added to the new dictionary or why the 20190105 -7 key-value pair passes through the elif statement with value less than 0. When I change all these statements to if statements not elif statements the code works but as fair I can tell the statements are mutually exclusive so the elifs should work. I want the code to only run the one if or elif statement that is true, I don't need it to run all of them if one condition is met. I don't understand elifs are not working?

How to pass value from xaml to class?

I´m creating WPF Application. In this application I would like to achieve that on the introductory screen the user chooses one option from mathematical operations (addition, subtraction, multiplication and division)this chooses are constructed by radiobutton.In the same window, the user would choose from two levels (low, high) also formed by radibutton,then I would check if-statement which option was selected. The values ​​to be selected would be sent to the class, from which they would then proceed to the next xaml.cs window.The game would run in this window.

MainWindow.xaml:

<Window x:Class="GameofMath.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       xmlns:local="clr-namespace:GameofMath"
       mc:Ignorable="d"
       Title="Menu" Height="321" Width="583">
   <Grid>
       <TextBlock Text="Vyber jednu z možností" TextWrapping="Wrap" Margin="10,10,59,250" FontSize="20"/>
       <Button Content="Start" Margin="281,240,10,10" FontSize="16" Click="Button_Click" IsDefault="True"/>

       <RadioButton   x:Name="scitani" x:FieldModifier="public" Content="Sčítání"  Margin="10,60,214,200" GroupName="level" />
       <RadioButton x:Name="odcitani" x:FieldModifier="public" Content="Odčítání" Margin="10,110,214,153" IsThreeState="False" GroupName="level" />
       <RadioButton x:Name="nasobeni" x:FieldModifier="public" Content="Násobení" Margin="10,157,214,109" IsThreeState="False" GroupName="level" />
       <RadioButton x:Name="deleni" x:FieldModifier="public" Content="Dělení" Margin="10,201,227,67" IsThreeState="False" GroupName="level" />
       <GroupBox x:Name="uroven" Header="Vyber jednu z úrovní" Margin="281,30,10,73"/>
       <RadioButton x:Name="nizsi" Content="Nízká" Margin="292,83,-291,180" GroupName="uroven"/>
       <RadioButton x:Name="vyssi" Content="Vyšší" Margin="292,153,-291,104" GroupName="uroven"/>

   </Grid>
</Window>

MainWidow.xaml.cs:

using System;

using System.Windows;


namespace GameofMath
{
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
       public MainWindow()
       {
           InitializeComponent();
       }


       private void Button_Click(object sender, RoutedEventArgs e)
       {
           
           if ( scitani.IsChecked.Value == true && nizsi.IsChecked.Value == true)
           {
               hra lvl = new hra();
               
               Vlastnosti vlastnosti = new Vlastnosti();
               lvl.Show();
               this.Close();
           }
           if ( scitani.IsChecked.Value == true &&  vyssi.IsChecked.Value == true)
           {
               hra lvl = new hra();
               Vlastnosti vlastnosti = new Vlastnosti();
               
               lvl.Show();
               this.Close();
           }
           else if ( odcitani.IsChecked.Value == true &&  nizsi.IsChecked.Value == true)
           {
               hra lvl = new hra();
               Vlastnosti vlastnosti = new Vlastnosti();
               lvl.Show();
               this.Close();
           }
           else if ( odcitani.IsChecked.Value == true &&  vyssi.IsChecked.Value == true)
           {

               hra lvl = new hra();
               Vlastnosti vlastnosti = new Vlastnosti();
               
               lvl.Show();
               this.Close();
           }
           else if ( nasobeni.IsChecked.Value == true && nizsi.IsChecked.Value == true)
           {
               hra lvl = new hra();
               Vlastnosti vlastnosti = new Vlastnosti();
               lvl.Show();
               this.Close();
           }
           else if ( nasobeni.IsChecked.Value == true&& vyssi.IsChecked.Value == true)
           {
               hra lvl = new hra();
               Vlastnosti vlastnosti = new Vlastnosti();
               lvl.Show();
               this.Close();
           }
           else if (deleni.IsChecked.Value == true && nizsi.IsChecked.Value == true)
           {
               hra lvl = new hra();
               Vlastnosti vlastnosti = new Vlastnosti();
               lvl.Show();
               this.Close();
           }
           else if ( deleni.IsChecked.Value == true &&  vyssi.IsChecked.Value == true)
           {
               hra lvl = new hra();
              
               Vlastnosti vlastnosti = new Vlastnosti();
               lvl.Show();
               this.Close();
           }
           else if (scitani.IsChecked.Value == false &&  odcitani.IsChecked.Value == false &&  nasobeni.IsChecked.Value == false &&  deleni.IsChecked.Value == false)
           {
               MessageBox.Show("Musíš zvolit, jednu z početních operací!");

           }
           else if ( nizsi.IsChecked.Value == false && vyssi.IsChecked.Value == false)
           {
               MessageBox.Show("Musíš zvolit, jednu z úrovní!");
           }
           else 
           {
               MessageBox.Show("Musíš zvolit, jednu z početních operací a úrovní!");
           }

       }
       

   }
}

class:

namespace GameofMath
{
    class Vlastnosti
    {
        public enum Operace
        {
            scitaniNiz= MainWindow.
            scitaniVys,
            odcitaniNiz,
            odcitaniVys,
            nasobeniNiz,
            nasobeniVys,
            deleniNiz,
            deleniVys,

        }
        public static class Class1
        {
           

            static Class1()
            {
                
            }

        }
    }
}

hra.xaml:

<Window x:Class="GameofMath.hra"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:GameofMath"
        mc:Ignorable="d"
       Title="GameOfMath" Height="450" Width="800" Loaded="Window_Loaded">
    <Grid>
        <TextBlock x:Name="prvnit" Text="TextBlock" TextWrapping="Wrap" Margin="66,115,641,199" FontSize="48" Height="120" Width="90"/>
        <TextBlock x:Name="znamenko" Text="TextBlock" TextWrapping="Wrap" Margin="209,144,533,220" FontSize="48" Width="58" Height="70"/>
        <TextBlock x:Name="druhyt" Text="TextBlock" TextWrapping="Wrap" Margin="310,119,400,195" FontSize="48" Width="90" Height="120"/>
        <TextBlock Text=" = " TextWrapping="Wrap" Margin="453,0,0,217" FontSize="48" Width="58" Height="70" HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
        <TextBlock x:Name="vysledek" Text="TextBlock" TextWrapping="Wrap" Margin="243,248,480,129" Visibility="Hidden" />
        <TextBlock x:Name="hlaska" TextWrapping="Wrap" Margin="0,0,480,379" FontSize="24"/>
        <Button x:Name="kontrola" Content="Kontrola" Margin="508,369,10,10" FontSize="16" Click="kontrola_Click" IsDefault="True"/>
        <TextBox x:Name="vysledekHrac" TextWrapping="Wrap" Margin="576,122,83,202" FontSize="48" BorderThickness="2,2,2,2"/>
        <TextBlock x:Name="pch" Text="Počet chyb:" TextWrapping="Wrap" Margin="10,317,579,74"/>
        <TextBlock x:Name="pocetchyb" TextWrapping="Wrap" Margin="8,349,688,8" FontSize="24"/>
        <ProgressBar x:Name="timer" Margin="121,369,335,41" Maximum="10"/>
        <Button x:Name="konec" Content="Ukončit" Margin="612,10,10,379" Click="konec_Click"/>
        <TextBlock x:Name="pocetPrikladu" Text="TextBlock" TextWrapping="Wrap" Margin="381,15,247,364"/>
        <Label x:Name="pocetpr" Content="Počet příkladů:" HorizontalAlignment="Left" Margin="293,10,0,0" VerticalAlignment="Top"/>

    </Grid>
</Window>

hra.xaml.cs:


using System.Diagnostics;
using System.IO;

using System.Windows;

using System.Windows.Threading;

namespace GameofMath
{
    /// <summary>
    /// Interakční logika pro hra.xaml
    /// </summary>
    public partial class hra : Window
    {
        Stopwatch mt = new Stopwatch();
        DispatcherTimer posunTimer = new DispatcherTimer();
        decimal trvani = new decimal();
        int suma = new int();
        public hra()
        {
            InitializeComponent();
            posunTimer.Tick += posunTimer_Tick;
            posunTimer.Interval = TimeSpan.FromSeconds(1);

        }
        public void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
            vysledekHrac.Focus();
            suma++;
            pocetPrikladu.Text = suma.ToString();
            mt.Start();
            timer.Value = 0;
            posunTimer.Start();
            Random prvni = new Random();
            Random druhy = new Random();
            int maxprvni = 10;
            int maxdruhy = 10;
            int prvnic = prvni.Next(1, maxprvni);
            int druhyc = druhy.Next(2, maxdruhy);

            if (Vlastnosti.Class1.scitani.IsChecked.Value == true)
            {
                znamenko.Text = "-";

            }
            if (odcitani.IsChecked.Value == true)
            {
                znamenko.Text = "-";

            }
            if (nasobeni.IsChecked.Value == true)
            {
                znamenko.Text = "*";
            }
            if (znamenko.Text == "+")
            {
                int total = (prvnic + druhyc);
                prvnit.Text = prvnic.ToString();
                druhyt.Text = druhyc.ToString();
                vysledek.Text = total.ToString();

            }
            if (znamenko.Text == "-")
            {
                int total = (prvnic - druhyc);
                prvnit.Text = prvnic.ToString();
                druhyt.Text = druhyc.ToString();
                vysledek.Text = total.ToString();

            }
            if (znamenko.Text == "*")
            {
                int total = (prvnic * druhyc);
                prvnit.Text = prvnic.ToString();
                druhyt.Text = druhyc.ToString();
                vysledek.Text = total.ToString();

            }


        }
        private void posunTimer_Tick(object sender, object e)
        {
            timer.Value += 1;
            if (timer.Value >= timer.Maximum)

            {
                posunTimer.Stop();
                hlaska.Text = "Špatně";
                poch++;
                suma++;
                pocetchyb.Text = poch.ToString();
                pocetPrikladu.Text = suma.ToString();
                timer.Value = 0;
                posunTimer.Start();
                Random prvni = new Random();
                Random druhy = new Random();
                int maxprvni = 10;
                int maxdruhy = 10;
                int prvnic = prvni.Next(1, maxprvni);
                int druhyc = druhy.Next(2, maxdruhy);
                if (znamenko.Text == "+")
                {
                    int total = (prvnic + druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }
                if (znamenko.Text == "-")
                {
                    int total = (prvnic - druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }
                if (znamenko.Text == "*")
                {
                    int total = (prvnic * druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }


                vysledekHrac.Text = String.Empty;

                if (poch == 4)
                {
                    mt.Stop();
                    timer.Value = 0;
                    posunTimer.Stop();
                    MessageBox.Show("Konec hry! Čas vypršel. ");
                    TimeSpan trvani = TimeSpan.FromMilliseconds(mt.ElapsedMilliseconds);
                    MessageBox.Show("Tvůj čas je " + trvani.ToString("mm\\:ss\\.ff") + "\n" + "Počet příkladů:" + pocetPrikladu.Text + "\n" + "Průměrný čas:" + trvani / suma);
                    if (!File.Exists(path))
                    {
                        StreamWriter str = File.CreateText(path);
                        str.WriteLine(trvani);
                    }
                    else if (File.Exists(path))
                    {
                        var str = new StreamWriter(path);
                        str.WriteLine(trvani);
                    }
                    this.Close();
                }
            }
        }
        private int poch;

        private void kontrola_Click(object sender, RoutedEventArgs e)
        {

            timer.Value += 1;
            posunTimer.Start();
            if (vysledekHrac.Text == vysledek.Text)
            {
                posunTimer.Stop();
                hlaska.Text = "Správně";
                suma++;
                pocetPrikladu.Text = suma.ToString();
                Random prvni = new Random();
                Random druhy = new Random();
                int maxprvni = 10;
                int maxdruhy = 10;
                int prvnic = prvni.Next(1, maxprvni);
                int druhyc = druhy.Next(2, maxdruhy);
                if (znamenko.Text == "+")
                {
                    int total = (prvnic + druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }
                if (znamenko.Text == "-")
                {
                    int total = (prvnic - druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }
                if (znamenko.Text == "*")
                {
                    int total = (prvnic * druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }

                vysledekHrac.Text = String.Empty;
                timer.Value = 0;
                posunTimer.Start();
            }

            else
            {
                posunTimer.Stop();
                hlaska.Text = "Špatně";
                poch++;
                suma++;
                pocetchyb.Text = poch.ToString();
                pocetPrikladu.Text = suma.ToString();
                Random prvni = new Random();
                Random druhy = new Random();
                int maxprvni = 10;
                int maxdruhy = 10;
                int prvnic = prvni.Next(1, maxprvni);
                int druhyc = druhy.Next(2, maxdruhy);
                if (znamenko.Text == "+")
                {
                    int total = (prvnic + druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }
                if (znamenko.Text == "-")
                {
                    int total = (prvnic - druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }
                if (znamenko.Text == "*")
                {
                    int total = (prvnic * druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();

                }

                vysledekHrac.Text = String.Empty;
                timer.Value = 0;
                posunTimer.Start();
                if (poch == 4)
                {
                    mt.Stop();
                    timer.Value = 0;
                    posunTimer.Stop();
                    MessageBox.Show("Konec hry!");
                    konec_Click(sender, e);

                }
            }







        }
        string path = @"C:\\Žebříček.txt";
        private void konec_Click(object sender, RoutedEventArgs e)
        {
            timer.Value = 0;
            posunTimer.Stop();
            if (mt.IsRunning == true)
            {
                mt.Stop();
            }
            TimeSpan trvani = TimeSpan.FromMilliseconds(mt.ElapsedMilliseconds);
            MessageBox.Show("Tvůj čas je " + trvani.ToString("mm\\:ss\\.ff") + "\n" + "Počet příkladů: " + pocetPrikladu.Text + "\n" + "Průměrný čas: " + Math.Round(trvani.TotalSeconds / suma, 4) + " sekund");
            if (!File.Exists(path))
            {
                StreamWriter str = File.CreateText(path);
                str.WriteLine(trvani);
            }
            else if (File.Exists(path))
            {
                var str = new StreamWriter(path);
                str.WriteLine(trvani);
            }

            this.Close();
        }
    }
}


Probably there are a lot of things that would be easier to do but I'm a beginner so please be patient. In the last phase, I want to design a table in which it will be stored.

But my problem now is in sending the value from the if-statement to the class.I tried to invent an enumeration somehow, but I also failed.

Will be happy for any idea.

Thank you

mardi 27 avril 2021

Why does this code say x not intialized but when we execute print statement inside if statement it works fine?

public class Main{
    public static void main(String[] args) {
        int x;
        int y=10;
        if(y==10){
            x=y;
            //System.out.println("x is "+x);
        }
        System.out.println("x is "+ x);
    }
}

When executed this says x not initialized?Cannot understand why? But the commented print statement is executed and the later one is removed then it works fine?

How to use CONCATENATE inside an IF ELSE Statement in Excel Macro [duplicate]

I am attempting to create a new column ("AF") to bring in an existing Internal Part Number from another column ("Z") if the part number is already listed. But if that field is set to #N/A, I want to concatenate the word "CST" with another column ("J") Which includes the Customer Part Number to create the value in my new column. Here is what I tried that does not work:

Lastrow = Worksheets("Current").UsedRange.Rows.Count
Range("AF2").Select
For counter = 2 To Lastrow
Dim PartLine As String
Dim PartNum As String
Dim CustPart As String
    PartLine = "AF" & counter
    PartNum = Cells(counter, "Z").Value
    CustPart = Cells(counter, "J").Value
If (Cells(counter, "Z")) <> "#N/A" Then
Range(PartLine).Value = PartNum
ElseIf (Cells(counter, "Z")) = "#N/A" Then
Range(PartLine).Select
ActiveCell.Formula = "=TEXT(CONCATENATE(""WOOD"",CustPart),0)"
End If
Next counter

Thanks for any help you can offer!

How can I even use the'else' syntax in Python?

I am reading data from a JSON file to check the existence of some values.

In the JSON structure below, I try to find adomain from the data in bid and check if there is a cat value, which is not always present.

How do I fix it in the syntax below?

import pandas as pd
import json
    
path = 'C:/MyWorks/Python/Anal/data_sample.json'
    
records = [json.loads(line) for line in open(path, encoding='utf-8')]
    
adomain = [
    rec['win_res']['seatbid'][0]['bid'][0]['adomain']
    for rec in records
    if 'adomain' in rec
]

Here is a data sample:

      "win_res": {
        "id": "12345",
        "seatbid": [
          {
            "bid": [
              {
                "id": "12345",
                "impid": "1",
                "price": 0.1,
                "adm": "",
                "adomain": [
                  "adomain.com"
                ],
                "iurl": "url.com",
                "cid": "11",
                "crid": "11",
                "cat": [
                  "IAB12345"
                ],
                "w": 1,
                "h": 1
              }
            ],
            "seat": "1"
          }
        ],
      },

As a result, the adomain value exists unconditionally, but the cat value may not be present sometimes.

So, if cat exists in adomain, I want to express adomain and cat in this way, but if there is no adomain, the cat value, how can I do it?