lundi 31 mai 2021

Evaluate multiple conditional statements with possible undefined variables

In Javascript, what would be the best way to evaluate several conditions when taking into consideration variables that could be undefined? For instance, I want to evaluate if x > y only if x is NOT undefined (has a value), and if it is undefined, continue to proceed to the next condition.

Something like:

if(x && x > y && a && a > b && c < d && e > f) ....

Here I want to see if x is defined, and then evaluate if x is greater than y, then go to evaluate if a is defined and evaluate if a is greater than b, then evaluate if c is less than d and etc. So here I want it so that if x or a is undefined CONTINUE to proceed to evaluate c < d and e > f

Here if the variables are are undefined then the whole statement is all false... what are some solutions for this that's clean?

Palindrome program , i don't understand a few parts

String word;

int z;

int y = 0;

int i = 0;

char letter;

Scanner input = new Scanner(System.in);

System.out.print("Enter a word: ");

word = input.nextLine();

word = word.replaceAll("\s+", ""); // ik the use of replace all and its syntax clearly but i can't understand "\s+" , "" part

word = word.toLowerCase();

z = word.length()-1; // why do word.length()-1? what's the reason of doing so

//after this basically i dont understand the whole loop so can you please explain

while (i <= z) {

if ((letter = word.charAt(i)) == (letter = word.charAt(z-i))){
    y += 1;
}
i += 1;

}

//and also this if else statement , please elaborate

if (y == (z+1)) {

System.out.println("The word IS a palindrome");

} else {

System.out.println("The word is NOT a palindrome");

}

} }

usage of if statement - Java 11

Recently I've seen many times the if statement being written like this (with simple tests) on Java 11:

int x = 10, y = 0;
if( x > y) System.out.print("x is > y"); // one line

Instead of:

int x = 10, y = 0;
if(x > y){ 
   System.out.print("x is > than y"); // multiple lines
}

Could this "one line" method cause any incompatibility on old versions of Java or it works for older versions normally?

R test if value is lowest from group, add 'yes'/'no' in new column if value is lowest from group

I'm relatively new to R and running into a problem I can't seem to solve. My apologies if this question has been asked before, but answers related to 'finding lowest' I'm running into here seem to focus on extracting the lowest value, I haven't found much about using it as a condition to add new values to a column.

A simplified example of what I'm trying to achieve is below. I have a list of building names and the years they have been in use, and I want to add to the column first_year "yes" and "no" depending on if the year the building is in use is the first year or not.

building_name   year_inuse    first_year
office          2020          yes 
office          2021          no 
office          2022          no
office          2023          no 
house           2020          yes
house           2021          no
house           2022          no
house           2023          no
retail          2020          yes
retail          2021          no
retail          2022          no
retail          2023          no

I grouped the data by the building names, and now I'm thinking about doing something like:

data_new <- data %>% mutate(first_year = if_else(...., "yes", "no"))

so add a condition in the if_else that tests if the year is the lowest from the group, and if so add a yes, otherwise add a no. However, I can't seem to figure out how to do this and if this is even the best approach.

Help is much appreciated.

(Python) Why does this if statement not affect the first value placed within it? [closed]

I am an amatuer coding student, self-studying python, and, at the moment, I have completed a problem but I do not understand why this solution works. I had to create code that would print this grid and I was successfully able to do it, with this code. However, despite me having gotten this correct, I fail to understand it. How come the if statement does not trigger on the first number? The first value on the grid (going horizontally) is less than ten, but there is no space before it. Shouldn't there be one, causing the grid to be offset by one? Thank you very much for the responses in advance!

Why is else triggering in this if else statement?

So I have this method in vue which changes the darkMode variable onclick,

What I don't understand is why it always triggers the if part and then also triggers the else part

data(){
    return{
      darkMode:false,
    }
  },
methods:{
darkModeToggle(){
  if(this.darkMode == false)
  {
    console.log("should be dark")
    this.darkMode = true
  }
  else(this.darkMode == true)
  {
    console.log("should be light")
    this.darkMode = false
  }
}
}

expected output is first click = "should be dark" then second click = "should be light" However it is triggering twice on each click and outputting = "should be dark" and "should be light"

I know it works correctly with "else if" I just don't understand why it doesn't work this way.

Problem with a variable and IF statements [closed]

So, I am working on editing a program in which the user has to guess a scrambled word.

I'm trying to edit in a part where the computer asks the user if they would like a hint, and then the program prints the hint, but I also would like to incentivise the player for not taking the hint.

So, I've got 2 variables I am trying to edit in, hint, and hintinput.

This is the code I've got so far:

while guess != correct and guess != "":
    print("Sorry, that's not it.")
    if hint == False:
        hintinput = print("Would you like a hint? Y/N.")
        if hintinput == "Y":
            print("Your hint is: ")
            print(word[0])
            print(word[1])
            print(word[2])
            hint = True
            guess = input("Your guess: ") 
        elif hintinput == "N":
            guess = input("Your guess: ")
    else:
        guess = input("Your guess: ")

The code is designed to ask so that if the player fails to correctly answer the question correctly and the player hasn't taken a hint, the computer will ask the player if they want a hint.

If the player wants the hint, the computer prints out the hint and then switches the hint to True, so the player won't be asked again for the hint if they get it wrong.

I tried to do this with the following code:

# create a jumbled version of the word, along with setting the hint variables to False. 
jumble =""
hintinput =""
hint =""

The last 2 lines of code I've added so that the game starts with the assumption that the player has not taken the hint.

However, when I run the code and get the question wrong, the computer doesn't ask me about the hint.

What should I do to fix this?

!all(is.na(df)) returns FALSE in console but passes the if

here is the code: if(sapply(pcol,class)!= sapply(dfcol,class) & !all(is.na(dfcol))){, which is intended to harmonise var types between two dataframes. The !all(is.na(dfcol))) is supposed to rule out empty dataframes .If I test one that it empty, my console returns [1] FALSE but it get through the if in the code above. Any thoughts ? Highly appreciated !!

A for loop using a double conditional

I'm currently trying to create a dual conditional, where, if the Cancer type (Indication) and Gene (Genes) of my data frame "mockup" both appear in another data frame called "cpg", then a new column in the mockup table has either a "yes" if both conditions are met, and a "no" if not. To illustrate this:

The mockup table has:

Indication Genes
Acute Myeloid Leukemia TP53
Acute Myeloid Leukemia GNAQ

And the cpg dataframe has:

Cancer Type Gene
Acute Myeloid Leukemia TP53
Acute Myeloid Leukemia ATM

I would like to produce a mockup table that looks like this (based on the cpg data):

Indication Genes Hotspot?
Acute Myeloid Leukemia TP53 Yes
Acute Myeloid Leukemia GNAQ No

So far I've tried (and failed) to make a for loop with a conditional to create a vector, with the hopes of then appending this vector as a new column:

hotspot <- c()
for (i in 1:nrow(mockup)){
  if ((mockup$Genes[i] == cpg$Gene && mockup$Indication[i] == cpg$`Cancer Type`)){
    hotspot[i] <- print("yes")
    } else {
      hotspot[i] <- print("no")
    }
}

unique(hotspot)

As always, any help would really be appreciated!

how to write nested if statement in more readable way [closed]

problem domain: I am creating an animal shelter for animals using queues, I have the reusable class Queue that I have built. in the dequeue method, I should return null if the pref is not cat either dog. and I don't want to tell the user that if the shelter (i.e cats) is empty so I have no cats in my shelter.

this is my animal class:

class AnimalShelter {
  constructor() {
    this.cats = new Queue();
    this.dogs = new Queue();
  }
  enqueue(animal) {
    if (animal.type === "cat") {
      this.cats.enqueue(animal);
    }

    if (animal.type === "dog") {
      this.dogs.enqueue(animal);
    } else {
      console.log("animal type should be either dog or cat");
      return "animal type should be either dog or cat";
    }
  }
  dequeue(pref) {
    if (pref === "cat") {
      if (!this.cats.isEmpty()) {
        return this.cats.dequeue(pref);
      } else {
        return "sorry the cats shelter is empty";
      }
    }
    if (pref === "dog") {
      if (!this.dogs.isEmpty()) {
        return this.dogs.dequeue(pref);
      } else {
        return "sorry the dogs shelter is empty";
      }
    } else {
      return null;
    }
  }
}

and this is the Queue class :

const Node = require("./Node");

/**
 * creates a queue with a storage and pointers to the elements in the storage
 */
class Queue {
  constructor() {
    this.top = 0;
    this.bottom = 0;
    this.storage = {};
  }
  /**
   *
   * @param {any} value method for pushing elements to the queue.
   */
  enqueue(value) {
    let node = new Node(value);
    this.storage[this.top] = node;
    this.top++;
  }
  /**
   * method for removing the first element entered the queue.
   * @returns {Object} removedElement: the removed element
   */
  dequeue() {
    try {
      this.emptyException();
      let removedElement = this.storage[this.bottom];
      delete this.storage[this.bottom];
      this.bottom++;
      return removedElement;
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * method returning the first element enqueued without removing it.
   * @returns the first element entered the queue.
   */
  peek() {
    try {
      this.emptyException();
      return this.storage[this.bottom];
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * method for calculating the size the queue.
   * @returns {Number} returns the number of elements in the queue.
   */
  size() {
    return this.top - this.bottom;
  }
  /**
   * method for checking if the queue is empty or not.
   * @returns {boolean}
   */
  isEmpty() {
    return this.size() === 0;
  }
  /**
   * method throwing an exception if the peek() or dequeue called on an empty queue
   */
  emptyException() {
    if (this.isEmpty()) {
      throw new Error("queue is empty !!");
    }
  }
}

and this is my Node class:

/**
 * creates a node object with a value and a empty pointer to the next node.
 */
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

Excel Multiple conditions IF OR AND

I need to create an Excel one formula that will pick up the following conditions:

  1. 1. If have only Sweden =IF(C12:C27="Sweden";"SE05")

    2. If Sweden and Norway, then the code is CH51 =IF(OR(C12:C27="Norway";C12:C27="Finland");"CH51"

    3. Multiple courtiers, any of countries like Sweden, Norway, Finland =IF(C12:C27="Sweden";C12:C27="Norway"; C12:C27="Finland");"GB80";"")

When I used the formulas separated they work, however I need to combine them together, so it make sense. I tried to use OR /AND together with IF formulas, but it did not return the correct values. I use this =IF(AND(C12:C27="Norway";C12:C27="Finland");"CH51") but then it returns CH51, even if I have all the countries in the list (Sweden, Norway, Denmark)

Can you please advice what formula to use to return all the conditions in the right way?

enter image description here

I get an unexpected NoneType error in my if-statement

I am trying to debug some code that for some reason returns TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

The if statement should trigger on the else condition (not first month of quarter), and should return the output of the calculation.

import pandas as pd
from datetime import date

    def getInterest(self):
        today = date.today()
        current_month = today.month 
        if current_month == [1,4,7,10]:
            print("First month of quarter")
            return 50
        else:
            print("Not first month of quarter")
            return (30000*-1*((0.03/365)*30))*0.9
  File "C:\Git\xxx\xxx.py", line 49, in getInterest
    return 30000*-1*((0.03/365)*30))*0.9
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

What am I missing here? I don't see why I get the NoneType error.

perl if not executing

I have modified perl script. It reads status from external file and executes subroutine based on that status.

##!/usr/bin/perl

use strict;
use warnings;

my $filename1="/usr/local/tmp/status.txt";



my $StepInfo;
open Input, $filename1;
undef $/;
$StepInfo= <Input>;
close Input;
$/ = "\n";
print "value $StepInfo";


if ($StepInfo eq  "Fresh" ){
        print "step1";
}

if ($StepInfo eq  "stp_fail"){
        print "step2";
}

I set status stp_fail in status file and run the script, i get this output. it not executing the IF statement.

-bash-4.2$ ./test2.pl
value stp_fail

kindly help on what am I missing.

I have got a problem checking a condition and write the answer into a new column

I have a column called "score_differential". I want to write a "1" into the new column "home_win" if the number is positive and a "0" if the number is negative. Result is the name of my new DataFrame.

This is my try

result.loc[i,"home_win"]=if result["score_differential"] > 0:
                                print("1")
                                else:
                                    print("0")

But this gives me the error "invalid_syntax". I am new to python so thanks for any help.

an Issue in count statement of PHP

During the implementation of multichain-web-demo, I got an error as following

   Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable|array, null given line 96

code around 96th line is as follows

        foreach ($addressmine as $address => $ismine) {
            if (count(@$addresspermissions[$address]))                      // 96th line
                $permissions=implode(', ', @array_keys($addresspermissions[$address]));
            else
                $permissions='none';
                
            $label=@$labels[$address];
            $cansetlabel=$ismine && @$addresspermissions[$address]['send'];

I am new to PHP world, forgive me for any mistakes. Thank you.

Why is my Python code ignoring my if-statement and quitting? [closed]

I am trying to write a python word puzzle game which may have multiple players and points are given based on the length of the words found.

Here is my function which 'plays' the game, however, it always results in "Game over!" no matter if my answer is right or wrong. So it quits the game every time.

def play_game(players, board , words, answers):
found_words = []
num_remaining = num_words_on_puzzle - len(found_words)
player_num = 0
while num_remaining > 0:
    print_headers(players, board, found_words, num_remaining)

    guess_input = input("{player}, make a guess: ".format(
        player=players[player_num % len(players)][0]))
    
    # Allow player to quit
    if guess_input.lower() == 'q' or 'quit':
        break 

    # Determine if the guess is valid
    guess = convert_guess(guess_input)
    
    if is_valid_answer(answers, guess):
        # Update a players score since answer is valid
        update_score(players[player_num % len(players)], matching_answer(answers, guess))
        # Add this word to found_words list
        found_words.append(matching_answer(answers, guess))
        
        print("Congratulations, you found '%s'." % matching_answer(answers, guess))
        print("That's %d points(s)." % word_score(matching_answer(answers, guess)))

    else:
        print("Sorry, that is incorrect.")

    num_remaining = num_words_on_puzzle - len(found_words)
    player_num += 1

print("\nGame over!\n")
print("The final scores are: \n")
print_score(players)
print(answers)

I hope someone can help me see where my issue is.

How to check for available places with if statement?

I’m working on a reservation system for a camping website. There are several places where you can sit, but it shouldn't be possible to have 2 different family’s on one place.

That’s why I want to make an if statement to check if the given date is already booked at the places, or is available at any of the places.

If one place is booked, I want it to check for another available spot with the same time, if no spots around the same time are available it should say "There's no available spots around this time", if there does turn out to be 1 spot available, it should automatically reserve at that spot and tell the user.

What kind of if statement do I need to use?

Few notes:

Begintijd = starting time

Eindtijd = endtime

reserveringen = reservations

reserveringstijden = reservationtimes

<?php
if (!isset($_SESSION['id'])){
    header('Location: login.php');
}

$errors = [];
if(isset($_POST['submit'])) {
    if ($_POST['begintijd'] == '') {
        $errors['begintijd'] = "Wat is de eerste dag dat je op de camping wilt staan? ontbreekt";
    }
    if ($_POST['eindtijd'] == '') {
        $errors['eindtijd'] = "Wat is de laatste dag dat je op de camping wilt staan? ontbreekt";
    }
    if (count($errors) == 0) {
      
        //Hier haal je de plaatsen op 
        $sql = "SELECT * FROM reservering WHERE type = ? ";
        $stmt = $conn->prepare($sql);
        $stmt->execute([$_POST['type']]);
        $result = $stmt->fetchAll();
       
       
        //Hier haal je de reserveringstijden op
        $sql1 = "SELECT * FROM reserveringstijden";
        $stmt1 = $conn->prepare($sql1);
        $stmt1->execute();
        $result1 = $stmt1->fetchAll();
        
        $begintijd = strtotime($_POST['begintijd']);
        $eindtijd = strtotime($_POST['eindtijd']);
        
        var_dump($_POST['begintijd']);
        if (($begintijd <= $result1[0]['begintijd'])&&($begintijd < $result1[0]['eindtijd']))
        {
            echo "hallo?";
            exit;
            if (($eindtijd = $result1[0]['begintijd'])&&($begintijd < $result1[0]['eindtijd']))
            {
                echo "stap verder";
                exit;
            }
            
        }
        else
        {
            echo "mag niet hier komen";
            exit;
            /*$sql2 = "INSERT INTO `reserveringstijden`(`id_plaats`, `begintijd`, `eindtijd`, `id_kampeerder`) VALUES (?,?,?,?) ";
            $stmt2 = $conn->prepare($sql2);
            $stmt2->execute([$result[0]['id'], $_POST['begintijd'], $_POST['eindtijd'], $_SESSION['id']]); */
        }
        
        
                            
                    
       
    }
}
?>
    <p>U wilt reserveren: </p>
    <div class="blockform">
        <form method="post">
            <label for="Plaats">Waar slaap je in?</label><br>
            <select id="type" name="type"><br>
            <option value="tent">tent</option>
            <option value="camper">camper</option>
            </select>
            <label>Eerste dag</label><br>
            <input type="date" id="begintijd" name="begintijd" value=" <?php echo (isset ($_POST['begintijd']) ? $_POST['begtintijd'] : ''); ?> "><br>
            <label>Laatste dag</label><br>
            <input type="date" id="eindtijd" name="eindtijd" value=" <?php echo (isset ($_POST['eindtijd']) ? $_POST['eindtijd'] : ''); ?> "> <br>
            <button type="submit" name="submit">reserveren</button>
        </form>
    </div>

C++ "else" statement when the preceding line has multiple "if" statements

The following C++ program

#include <iostream>

int main() {
    for(int i=0; i<5; i++) for(int j=0; j<5; j++){
        if(i==1) if(j==2) std::cout << "A " << i << ' ' << j << std::endl;
        else std::cout << "B " << i << ' ' << j << std::endl;
    }
    return 0;
}

outputs

B 1 0
B 1 1
A 1 2
B 1 3
B 1 4

From this I infer that the "else" statement is referring to the second "if".

Is this behavior described in the C++ standard? Is there a reason for implementing it this way? I intuitively expected "else" to refer to the first "if".

R loop doesn't give an error but no output either, what could be the issue with the code?

I am new with R and got stuck with this loop code. I want to see in which rows column 3 values and column 2 values are unequal.

I have created a data frame list, by extracting columns from a dataset PFC_DATA.

list <- as.data.frame(PFC_Data[ ,c(1,6,10)])

And then created the loop with two conditions. Since the column 3 has a bunch of NAs, if it is an NA, then skip, otherwise, if column 3 has a value that is unequal to column 2 value, print the row numbers. That's the code:

`

for (i in 1:1840) {

if (list[[3]][[i]] == is.na())

  next

else {

  if (list[[3]][[i]] != list[[2]][[i]]) {

    print(i)

  }
  }
  }

`

I also tried =="NA". However, in either case nothing happens. I do not get any error, but no output either. Any ideas?

perl IF executing both conditions

I am new to perl scripting (i am data analyst trying to work on some scripts)

I am trying to modify a perl script. The logic of what I am trying to achieve is I have created a text file with some status in it. I want to read the file and decide which subroutine will run based on it. I have manually created file with status. The if else command is not working. Next I want to change the status in same text file depending on what subroutine was executed.

unfortunately as on now nothing works :P

here is the script (not the original as for security reasons)

-------XXX--------------

#!/usr/bin/perl

my $filename1="/usr/local/tmp/status.txt";



open Input, $filename1;
undef $/;
$StepInfo= <Input>;
close Input;
$/ = "\n";
print "value $StepInfo";

#Step 1 -
if ($StepInfo =  "Fresh" ){
        step1();
#       exit();
}

if ($StepInfo =  "stp_fail"){
        step2();
#       exit();
}


sub stepcheck {
        my ($argument1) = @_;
        my $filename1= shift;
        open(FH, '>', $filename1);
        print FH "$argument1\n";
        close FH;
}

sub step1 {
        my $StepInfo= shift;
        print "Step1 completed\n";
        print $StepInfo;
        stepcheck ('dh_fail');
}

sub step2 {
        my $StepInfo= shift;
        print "Step2 completed\n";
        print $StepInfo;
        stepcheck ('Test');
}

#open($FH, '>', $filename1);
#print $FH "Fresh\n";
#close ($FH);

#perl -i -pe 'y|\r||d' script.pl

-----XXX----------

I set status to "stp_fail". when i execute the script I am expecting step2 to be executed. I see the its reading the right status but not executing the correct step rather both of them

-bash-4.2$ ./test_script.pl

value stp_fail

Step1 completed

Step2 completed

additionally the script is not changing the status in the text file. rather it creates 2 new files named Test and dh_fail.

kindly assist in what part i am doing wrong. thanks a lot in advance.

Perform an action from a condition for a Python Dataframe

I have the following dataframe:

import pandas as pd
import re
df = pd.DataFrame ({'example': ['ACETATO MOLOCUATO']})

The condition is that if the string ends in "ATO" I will choose only the first three words. The way I planted it is as follows:

#If the example ends in "ATO"

df ['example']. str.contains ('ATO $')

#Then Extract the first 3 words

df ['example']. str.extract ('(\ w +) \ s (\ w +) \ s (\ w +)')

#Otherwise, print the dataframe without changes

I would like to know the best way to relate this last action based on the first condition.

Connect and disable an HTML option tag to a PHP file on certain conditions

I have two files:

web_directory_body.html (only important snippets)

<form name="web_directory_form" id="web_directory_form" method="POST" action="web_directory.php">

<tr>
   <td width="35%"><b>Status</b></td>
   <td width="65%">
     <select name="status_id" id="status_id">
     <option value="-1">All</option>
     <option value="0">Active</option>
     <option value="1">Inactive</option>
     </select>
    </td>
  </tr>

1

web_directory.php (only important snippets)

$dir_search = array();

$action = 'search';
$params = array(
       'profile'        => 'profile',
       'employee_no'    => 'employee_no',
       'mcr_no'         => 'mcr_no',
       'name'           => 'name',
       'dept'           => 'dept',
       'section'        => 'section',
       'designation'    => 'designation',
       'mobile_no'      => 'mobile_no',
       'no_mobile'      => 'no_mobile',
       'username'       => 'username',
       'user_role'      => 'user_role',
       'login_access'   => 'login_access',
       'status_id'        => 'status_id',
       'user_type'      => 'user_type'
);

my goal for this is to only have "status active" whenever there is no user and for the option tag to be disabled/greyed out if this is the case. If someone logs in, they have the additional options "All" and "Inactive". here is my code for that (working, tested on other parts of my system)

if($_SESSION['user_name'] == "")
  
else

My problem is that the html file and the backend are separated (not my system originally) I need to somehow do a disable of the option tag of the html file inside my php file. Would like some advice on how to do that.

What I have tried:

  • It somehow works if I change "'status_id' => 'status_id'," to an appropriate value like "'status_id => 0," but the issue is the dropdown options can still be seen and clicked, I would like to have them disabled (if no user is logged in, only shows Active).

  • I also cannot simply add the whole of the Status to my if else statement, since the original option tag is still back at the html file.

any help would be appreciated thank you for reading.

EDIT: please do not vote to close, if it is still not clear I will gladly elaborate more

dimanche 30 mai 2021

my code give an error if a enter a letter or a charcter different to a float or integer

my purpose is to return a message if the user enter a letter or character different to an integer or float but if a enter a letter like "jhdsjfhdhjd" it give me an error

 my_number = int(input("Please ,enter your number here !"))
if my_number is not int:
    print("It is not a number a number !")
else:
    my_num = int(my_number)
    if my_num == 0:
        while my_num < 11 :
            print("Not there Yet , your number is " + str(my_num) + ".We continue increase your number to 10 !")
            my_num +=1
        print("Good, increasing is Done , the number is 10")
    elif my_num > 0:
        while my_num > -1:
            if my_num == 0:
                print("Correct ,the decreasing is finished.The number is 0")
        print("Not there Yet , your number is " + str(my_num)+ ".We continue decrease your number to 0 !")
        my_num -=1
    else:
        print("It isn't a number ,Please enter an integer")


   

converting phone number into phone 'word' - python

I want to convert given phone number into respective letters

0 -> 'a'
1 -> 'b'
2 -> 'c' etc.

E.g. the number 210344222 should get converted to the string 'cbadeeccc'. I understand my return is wrong at the end which is where I am stuck, so can you please explain how I would instead return the letter conversions.

def phone(x):
    """
    >>> phone(22)
    'cc'
    >>> phone(1403)
    'bead'
    """
    result = "" 
    x = str(x)
    for ch in x: 
        if x == 0:
            print('a')
        elif x == 1:
            print('b')
        elif x == 3:
            print('c')
    return result

Javascript DOM best practice

 if (index === 0) {
      const image = document.createElement('img');
      image.alt = 'image';
      image.src = 'https://media.s-bom.com';
      image.width = '100';
      li.appendChild(image);
    }
    if (index === 1) {
      const image = document.createElement('img');
      image.alt = 'image';
      image.src =
        'https://images-na.ssl-images-amazon.com';
      image.width = '100';
      li.appendChild(image);
    }
    if (index === 2) {
      const image = document.createElement('img');
      image.alt = 'image';
      image.src =
        'https://upload.wikimedia.orgmmer.jpg/220px-The_pragmatic_programmer.jpg';
      image.width = '100';
      li.appendChild(image);
    }

Hey, I have this code above in if condition and I want it to be more clear and not repeated, so anyone have idea how to be more clean.

What does the "player = (player == 1) ? 2 : 1? [duplicate]

I am beginner programmer and trying to understand the various ways to represent a code written like the one below. I was reading a line of code that was under a while-loop but did not explain what the code below means. I only understand the equality sign but not the "? 2 : 1"

player = (player == 1) ? 2 : 1;

I was browsing the internet but wanted to make sure since its slightly different, but is this the same as to an if statement? Is there another way to present the code above beside the if statement?

if(player % 2) {
   player = 1;
   }
   else {
   player = 2;

how to make program for finding greatest number out of n given number using if else in c [closed]

I want to know that how can we make a program for finding greatest number out of n given numbers using if else statement

How to use one loop if input is invalid for an if statement?

I am pretty new at coding in Java. I'm in classes now to study it and I'm having an issue with loops.

My assignment for this class is to write only ONE while loop for a program which calculates the weighted total of 3 grades. I'm using if else statements and a variable to declare what user input it should be on, however, if the input is not in a certain range, I need it to ask the same question again to the user. So far this only works with the first question, not the other two. How would I ask the same question again if the input is not valid?

Here is my code so far:

import java.util.Scanner;
public class Lab3 
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);

double homework; 
double midterm;
double finalGrade;
int i = 0;

while (i == 0)  {   
    if (i == 0) {
    System.out.print("Enter your HOMEWORK grade: ");
        homework = scan.nextInt();
    
    if (homework < 0 || homework > 100){
        System.out.println("[ERR] Invalid input. A homework grade should be in [0, 100].");
    }
        else {
           i++;
        }
    
        if (i==1) {
            System.out.print("Enter your MIDTERM EXAM grade: ");
            midterm = scan.nextInt();
        
                if (midterm < 0 || midterm > 100) {
                    System.out.println("[ERR] Invalid input. A midterm grade should be in [0, 100].");
                
                    } else {
                        i++;
                    
            }

if (i==2) {     
    System.out.print("Enter your FINAL EXAM grade: ");
        finalGrade = scan.nextInt();
        
        if (finalGrade < 0 || finalGrade > 200) {
            System.out.println("[ERR] Invalid input. A FINAL EXAM grade should be in [0, 200].");
            
        }   else {
                i++;
                
                
double totalWeighted = (finalGrade / 200 * 50) + (midterm * .25) + (homework * .25);

    System.out.println("[INFO] Student's Weighted Total is " + totalWeighted);
    if (totalWeighted >= 50) {
        System.out.println ("[INFO] Student PASSED the class.");
        }
        else { 
            System.out.println ("[INFO] Student FAILED the class.");
        }
        

                
        }}}}}}}

The values of both the variables are same but still the True block doesn't get executed?

for row in range(1, 100):
        #print(ws["C"+ str(row)].value)
        if ws["C"+ str(row)].value == entered_username:
            if ws["D"+ str(row)] == entered_password:
                dashboard()
            else:
                Label(l_screen,text="Incorrect password!!").pack(pady = 10) 
        else:
            Label(l_screen,text="Username not found.").pack(pady = 10)

When checking the ws["C"+ str(row)].value and entered_username separately, both are same(checked the type function as well). but the code block always returns "Username not found"

Something is wrong with my if and else statement

Here is my code:

var points = 10

if(points == 10) {

points + 200;

}

else if (points === 100) {

points + 10;


}

console.log(points)

What happens is that it logs 10, when what i would like to happen is that it logs 210. Any idea on what i have done wrong? I got some feedback on it on an earlier question, but it still does not seem to work.

if statement doesn't works with socket.io and mongodb

i want to check if some values on my mongodb database exist, but if not exist, give me an error, instead of a event.
This is my code:

   socket.on("bot_req_id", async function(data) {
       let db = mongoose.db("wumpusCave")
       let bots = db.collection("bots")
       let find = bots.find({data})
       if(find) {
           console.log(data)
           let bot = await bots.findOne({"id":data})
           console.log(bot)
           socket.emit('bot_res_id', {"name": bot.name, "description": bot.description, "avatar": bot.avatar, "id": bot.id, "invite": bot.invite})
       } else {
           socket.emit('notfound', "bot non trovato")
       }
   })

The error:

           socket.emit('bot_res_id', {"name": bot.name, "description": bot.description, "avatar": bot.avatar, "id": bot.id, "invite": bot.invite})
                                                  ^

TypeError: Cannot read property 'name' of null

I use node.js
How i can fix that?
Thanks in advice and sorry for bad english!

Swal.fire when click text in Javascript (Sweetalert)

I want to make appear a window promp with sweetalert (swal.fire) when i click a text. How do if statements and window prompt work on this library? After this point, you can appreciate that i'm new in this programming world.

After that, i would like to asign a value to that input and verify if the answer is correct or not.

<td class="gases" title="Hidrógeno" id="H">H</td> This is the element i want to click

Swal.fire({
title:'¿Cuál es el elemento?',
text: 'Introduce el nombre aquí',
input: 'text',
inputPlaceholder: 'Nombre', })

This is the prompt i want to appear when i cliked that element. When the button 'OK' is clicked, want to verify if the name introduced is correct or not...:

if (name === hidrógeno) {
     Swal.fire ('Correct!', 'You got the answer right!', 'success') }

else {
     Swal.fire ('Incorrect...', 'You failed!', 'error') }

Audio.play() doesn't work ONLY in if statement

So I am making a small game to practice javascript. I wanted to add the getting point sound when the car is not crashing with the obstacle. If car is not crashing with obstacle I am adding points and making that the obstacle disappears and appearing once again in the top of the road so everything is working just fine. Under those lines I added the audio.play(); function and it is not working. I added the alert to check if it should work and alert is appearing so what is going on?

else if(document.getElementById("B7").innerHTML == '<div id="obstacle">X</div>' || document.getElementById("A7").innerHTML == '<div id="obstacle">X</div>')
        {
            document.getElementById("A7").innerHTML = "";
            document.getElementById("B7").innerHTML = "";
            points = points + addPoints;
            audio.play();
            alert("sound here");
            nextObstacle();
        }

Link for GitHub repository for this project:

https://github.com/AdamMaichrzik/Spliterio/blob/master/car.html

Lines 270 - 280.

Oracle - Subquery in IF Clause

I have the following code:

if USER IN (SELECT user_id from user_maint where roll = 12) THEN
        p_status := 'W';

ELSE 
        p_status := 'A';
END IF;

It gives the error: Error(332,16): PLS-00405: subquery not allowed in this context

How to make subquery in the IF clause?

Learning PHP basic if statement comparer struggles

I'm attempting to learn PHP and am currently struggling with a basic comparer I made with if statements.

I can't reliably get $teststype to display "mix" if the $test1 and $test2 are both a and b. However if I make one of them something random like "ball" then it works but in that case $teststype should execute the 0 case and display " ", but it doesn't. Echoing $test1_type and $test2_type and the gettype were just part of my trouble shooting.

Any help in explaining my errors and this behavior would be greatly appreciated.

Thanks

my code: http://sandbox.onlinephpfunctions.com/code/723d64346a12816e0db66b4af64a87253a31abe1

<?php
 
 
 $test1 = "a";
 $test2 = "b";

 
 
 if         ( $test1 === "a" ) {
                $test1_type = 1;
            } elseif ($test1 === "b") {
                $test1_type = 2;
            } else {
                $test1_type = 0;
            }

            if ($test2 === "a") {
                $test2_type = 1;
            } elseif ($test2 === "b") {
                $test2_type = 2;
            } else {
                $test2_type = 0;
            }
            
        
            if ($test2_type && $test1_type === 1) {
                $teststype = "a";
            } elseif ($test2_type && $test1_type === 2) {
                $teststype = "b";
            } elseif ($test2_type !== $test1_type) {
                $teststype = "mix";
            } elseif ($test2_type || $test1_type === 0) {
                $teststype = " ";
            }
            
             $type = gettype($test2_type);
            
            
            echo "type = $type  |||  test1 = $test1_type  ||  test 2= $test2_type  |||  evaluated = $teststype";
            
?>

Python Elif statement not executing fourth condition

I'm building a Desktop Assistant in python.

The if Condition and first two Elif conditions are working just file but when I try to call the fourth Elif contion, it automatically calls the third Elif condition no matter how I change my conditions.

I have tried replacing third Elif by fourth Elif, but still its executing the Elif at third position.

Here is my code ...... Problem exists in run() function

# region                                                                            Importing Modules
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import webbrowser
# endregion

gender=0
rate = 190
listener = sr.Recognizer()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[gender].id)

def speak(text):
    engine.setProperty('rate', rate)   
    engine.setProperty('voice', voices[gender].id)
    engine.say(text)
    engine.runAndWait()

def tk_command():
    with sr.Microphone() as source:
        print("listening...")
        listener.adjust_for_ambient_noise(source)
        voice = listener.listen(source)
        try:
            command = listener.recognize_google(voice, language="en-in")
            command=str(command)
            return command
        except Exception as e:
            speak("Didn't hear anything, try again.")
            tk_command()

def hotword():
    global gender
    command = tk_command()
    if 'jarvis' in command.lower():
        gender=1
        speak("Jarves, hey buddy. You're up.")
        gender=0
        speak('Well, I am here to assist')
        print (command)
        run()
    elif 'friday' in command.lower():
        gender=0
        speak("Hey Friday, it's your call")
        gender=1
        speak('Ok, how can I assist')
        print (command)
        run()

def anything_else():                                                #### Check if this works ####
    speak("Any other service I can do ?")
    command=tk_command()
    command.lower()
    if 'no' or 'nope' or 'nah' or 'na' in command:
        speak("Ok. Happy to help.")
        print(command)
        hotword()
    elif command == 'yes' or command == 'yeah' or command == 'yup':
            speak("Ok. Just ask me.")
            run()
    else:
        speak("Sure...")
        run(command, True)


def run(command=None, check=False):
    global rate
    # region                                                                        Taking command input
    if check == False:
        command = tk_command()
    command = command.lower()
    command = command.replace('friday', '')
    command = command.replace('Jarvis', '')
    # endregion

''' Functioning of various commands are describes below
     as multiple elif statements '''

if ('play' or 'search') and 'youtube' in command and 'google' not in command:   # Play or search on youtube
    song = command.replace('play', '')
    song = song.replace('youtube', '')
    song = song.replace('on', '')
    song = song.replace('for', '')
    speak('Playing.'+ song)
    pywhatkit.playonyt(song)

elif ('send' or 'message') and 'whatsapp' in command:                           # Sending a Whatsapp message
    if 'to' not in command:                 # Check if phone number is input
        speak('''Please say the command with a phone number or a contact name.
             To save a new contact say, Save... your phone number... 
                as... name of the recepient.''')
    else:                                   # Else Send the message
        command = command.replace('send', '')
        command = command.replace('whatsapp', '')
        command = command.replace('message', '')
        command = command.replace('to', '')
        command = command.replace('on', '')
        try:
            number = int(command.replace(' ',''))
            speak("Sure, what's the message.")
            message = tk_command()
            pywhatkit.sendwhatmsg_instantly(f"+91{number}", message)
        except Exception as e:
            speak('Invalid number or contact, please try again.')
            print (command)
            run()

elif 'time' in command:                                                         # Asking what time is it
    time = datetime.datetime.now().strftime('%I:%M:%S %p')
    speak('Right now, its, '+ time)

elif 'search google for' or ('search' and 'on google') in command:              # Searches anything on google
    print('Google Search')
    command=command.replace('search google for', '')
    command=command.replace('search', '')
    command=command.replace('on google', '')
    command=command.replace(' ', '+')
    pywhatkit.search(command)
    
elif (('who' or 'what') and 'is') or 'wikipedia' in command:                    # Searches wikipedia for anything or anyone
    print(command)
    print('Wikipedia Search')
    lines = 1
    if 'explain' in command:
        lines = 3
        command = command.replace('explain', '')
    command = command.replace('who', '')
    command = command.replace('what', '')
    command = command.replace('is', '')
    info = pywhatkit.info(command, lines)
    rate -= 20
    speak(info)
    rate += 20

else:                                                                           # Exits the program
    speak('Exiting the program.')
    sys.exit()

anything_else()


hotword()

Adding all integers together in a file input, line by line in Python

I am trying to make a program that get the sum of all numbers in a input and print it. For example, if the file had:

3   } 3 * 5 = 15
Five
2   } 2 * 10 = 20
tEn
2   } 2 * 20 = 40
Twenty
6   } 6 * 1 = 6
onE

15 + 20 + 40 + 6 = 81

I essentially am trying to convert the words into numbers and multiply them by the integer above them and then add them up together. The problem is that I don't know how to grab all the products and add them together. Here is what I have so far:

def main():
    print(counting_money("python.txt"))


def counting_money(fileName):
    total = 0
    fin = open(fileName, "r")
    file = fin.readline()
    while file != '':
        num = int(file)
        file = fin.readline()
        face_num = file.lower()
        if face_num == "one":
            total = num * 1
        elif face_num == "five":
            total = num * 5
        elif face_num == "ten":
            total = num * 10
        elif face_num == "twenty":
            total = num * 20
        elif face_num == "fifty":
            total = num * 50
        elif face_num == "hundred":
            total = num * 100
    fin.close()
    return total

main()
        

samedi 29 mai 2021

How do I make this code cleaner using functions? [closed]

I am working on a python program that evaluates a user's input to out put their astrological sign, constellation, and traits. Part of the code I used from pre-exisiting code online and I adapted a list of traits to be randomly generated using the choice function.

I also used a CONSTANT to print out what the user's constellation is.

HELP! I would love input on how to clean up the code. Also how to keep the program running once the code generates the user's output.

import random
ZODIAC ="Your constellation is"
#Constant to create print statement which Zodiac Sign is found

#Generated list for random trait according to zodiac sign
aries = ['Adventuerous and energetic', 'Pioneering and courageous', 
'Enthusiastic and confident','Dynamic and quick-witted', 'Selfish 
and quick-tempered', 'Impulsive and impatient', 'Foolhardy and 
daredevil']

taurus =['Patient and reliable', 'Warmhearted and loving', 
'Persistent and determined', 'Placid and security loving',
'Jealous and possessive', 'Resentful and inflexible', 'Self- 
Indulgent and greedy']

gemini = ['Adaptable and versatile', 'Communicative and witty', 
'Intellectual and eloquent', 'Youthful and lively','Nervous and 
tense', 'Superficial and inconsistent', 'Cunning and inquisitive']
cancer = ['Emotional and loving', 'Intuitive and imaginative', 
'Shrewd and cautious', 'Protective and sympathetic',
'Changeable and moody', 'Overemotional and touchy', 'Clinging and 
unable to let go']

leo = ['Generous and warmhearted', 'Creative and enthusisatic', 
'Broad-minded and expansive', 'Faithful and loving',
'Pompous and patronizing', 'FABULOUS and AMAZING!', 'Bossy and 
 interfering', 'Dogmatic and intolerant','LIFE OF THE PARTY!', 'BEST 
DRESSED AND DRESSED TO IMPRESS!']

 virgo = ['Modest and shy', 'Meticulous and reliable', 'Practical 
 and diligent', 'Intelligent and analytical',
'Fussy and a worried', 'Overcritical and harsh', 'Perfectionist and 
conservative']

 libra = ['Diplomatic and urbane', 'Romantic and charming', 
 'Easygoing and sociable', 'Idealistic and peaceable',
 'Indecisive and changeable', 'Gullible and easily influenced', 
 'Flirtatious and self-indulgent']

 scorpio = ['Determined and forceful', 'Emotional and intuitive', 
 'Powerful and passionate', 'Exciting and magnetic',
       'Jealous and resentful', 'Compulsive and obsessive', 
 'Secretive and obstinate']

 sagittarius = ['Optimistic and freedom-loving', 'Jovial and good- 
 humored', 'Honest and straightforward',
 'Intellectual and philosophical', 'Blindly optimistic and 
 careless', 'Irresponsible and superficial','Tactless and restless']
 
 capricorn = ['Practical and prudent', 'Ambitious and disciplined', 
 'Patient and careful', 'Humorous and reserved',
 'Pessimistic and fatalistic', 'Miserly and grudging']

 aquarius = ['Friendly and humanitarian', 'Honest and loyal', 
 'Original and inventive', 'Independent and intellectual',
 'Intractable and contrary', 'Perverse and unpredictable', 
 'Unemotional and detached']

 pisces = ['Imaginative and sensitive', 'Compassionate and kind', 
 'Selfless and unworldly', 'Intuitive and sympathetic',
 'Escapist and idealistic', 'Secretive and vague', 'Weak-willed and 
 easily led']

def main():
    zodiac()
    print("Astrology is the study of patterns and relationships - planets in motion and our birth chart. \nLet's find your astrological sign, constellation, and traits!")
    while True:
        try:
            day = int(input("Input birthday (e.g. 1 - 31): "))
            month = input("Input month of birth (e.g. march, july etc): ")
            #.lower() lets the user write the zodiac sign in multiple ways
        except ValueError:
            #when a user doesn't enter a valid entry it will return this statment
            print("Sorry, that is an invalid entry. \nEnter a numeric value for day. \nSpell out the your birth month.")
            #try again and return to start of the loop
            continue
        else:
            #we'e ready to exit the loop.
            break

    if month.lower() == 'december':
        astro_sign = 'Sagittarius' if (day < 22) else 'Capricorn'
    elif month.lower() == 'january':
        astro_sign = 'Capricorn' if (day < 20) else 'Aquarius'
    elif month.lower() == 'february':
        astro_sign = 'Aquarius' if (day < 19) else 'Pisces'
    elif month.lower() == 'march':
        astro_sign = 'Pisces' if (day < 21) else 'Aries'
    elif month.lower() == 'april':
        astro_sign = 'Aries' if (day < 20) else 'Taurus'
    elif month.lower() == 'may':
        astro_sign = 'Taurus' if (day < 21) else 'Gemini'
    elif month.lower() == 'june':
        astro_sign = 'Gemini' if (day < 21) else 'Cancer'
    elif month.lower() == 'july':
        astro_sign = 'Cancer' if (day < 23) else 'Leo'
    elif month.lower() == 'august':
        astro_sign = 'Leo' if (day < 23) else 'Virgo'
    elif month.lower() == 'september':
        astro_sign = 'Virgo' if (day < 23) else 'Libra'
    elif month.lower() == 'october':
        astro_sign = 'Libra' if (day < 23) else 'Scorpio'
    elif month.lower() == 'november':
        astro_sign = 'scorpio' if (day < 22) else 'Sagittarius'
    print("Your Astrological sign is :", astro_sign)

#choice function allows to random generate for a list
    if astro_sign == "Sagittarius":
        print(ZODIAC + ' the Archer')
        print('Traits:', random.choice(sagittarius))
    elif astro_sign == 'Capricorn':
        print(ZODIAC + ' the Goat')
        print('Traits:', random.choice(capricorn))
    elif astro_sign == 'Aquarius':
        print(ZODIAC + ' the Water Carrier')
        print('Traits:', random.choice(aquarius))
    elif astro_sign == 'Pisces':
        print(ZODIAC + ' the Fish')
        print('Traits:', random.choice(pisces))
    elif astro_sign == 'Aries':
        print(ZODIAC + ' the Ram')
        print('Traits:', random.choice(aries))
    elif astro_sign == 'Taurus':
        print(ZODIAC + ' the Bull')
        print('Traits:', random.choice(taurus))
    elif astro_sign == 'Gemini':
        print(ZODIAC + ' the Twins')
        print('Traits:', random.choice(gemini))
    elif astro_sign == 'Cancer':
        print(ZODIAC + ' The Crab')
        print('Traits:', random.choice(cancer))
    elif astro_sign == 'Leo':
        print(ZODIAC + ' the Lion')
        print('Traits:', random.choice(leo))
    elif astro_sign == 'Virgo':
        print(ZODIAC + ' the Maiden')
        print('Traits:', random.choice(virgo))
    elif astro_sign == 'Libra':
        print(ZODIAC + ' the Scales')
        print('Traits:', random.choice(libra))
    elif astro_sign == 'Scorpio':
        print(ZODIAC + ' the Scorpion')
        print('Traits:', random.choice(scorpio))






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

Next calendar day invalid range [duplicate]

I am a beginner and this is an exercise I am expanding on. Basically given 3 input day, month, year it needs to return the following day. It works almost perfectly but I can't manage to print the correct date (ex: 31/5/2020 to 1/6/2020) because it print "invalid range" given I set 31 for days, given that this months (4,6,9,11) have only 30 days. I else want to print "invalid range" in the case I give 31 to a month that have only 30 days. This is my code so far:

`def next_day():

day = int(input("Input a day: "))
month = int(input("Input a month: "))
year = int(input("Input a year: "))
print(f'Current date is : {day}/{month}/{year}')

# for months with 30 days
if month == (4 or 6 or 9 or 11) and day == 30: 
    month += 1
    day = 1
# for months with 31 days ###ISSUE HERE
elif month == (1 or 3 or 5 or 7 or 8 or 10) and day == 31: 
    month += 1
    day = 1
else:
    day += 1

# for out of range values
if  day > 31 or month > 12:
    print("Invalid range")
    return False

# for leap years
if month == 2 and year % 4 == 0 and day == 28:
    day += 1
elif year % 4 != 0:
    month += 1
    day = 1

# for new year 
if month == 12 and day == 31:
    day = 1
    month = 1
    year += 1

print(f'Next date is : {day}/{month}/{year}')

Else is there a way to reformat the if statement in a simpler way without using so many or? Any suggestions?

Array: if all 4 Elements included count up

My code isn't working right. Could someone help me out? Everytime there is one of those items: (socken,schuhe, hose, pullover) in the array (doesn‘t matter where) then it should count 1 up. It shouldn‘t count how many times each of them is included in total, just if all of them are included once and then again if all 4 are in the array etc. and then the total number of them. If I use && I get 0 and if I use || in the if statement I get 16. I should get 3 instead of 16 though. I would be really happy if someone could help me out.

    int HOSE = 1;
    int PULLOVER = 2;
    int SOCKEN = 3;
    int MÜTZE = 4;
    int SCHUHE = 5;
    int TANKTOP = 6;
    int LONGSLEEVE = 7;
    int KLEID = 8;
    int BLUEJEANS = 9;
    int BOOTIES = 10;
    int WEDGES = 11;
    int HIGHHEELS = 12;
    int KAROHEMD = 13;
    int BLAZER = 14;
    int HALSTUCH = 15;

    int[] lager = { HOSE, SCHUHE, SOCKEN, PULLOVER, PULLOVER, HOSE, HALSTUCH, MÜTZE, SCHUHE, TANKTOP, LONGSLEEVE,
            PULLOVER, PULLOVER, KLEID, KLEID, BLUEJEANS, HOSE, SOCKEN, SCHUHE, BOOTIES, WEDGES, HIGHHEELS, KAROHEMD,
            BLAZER, SCHUHE, HALSTUCH, SOCKEN, HOSE, PULLOVER };

    int counter = 0;
    for (int i = 0; i < lager.length; i++) {
        if (lager[i] == SCHUHE || lager[i] == SOCKEN || lager[i] == HOSE || lager[i] == PULLOVER) {
            counter++;
            break;
        
        }
    }

    System.out.println(counter);

If-else condition returns always false when checking an object attribute

I'm trying to use the function 'set_disp_time' to change the disp_time value of every 'workshop' object from undefined to a certain number, depending on a formula. The formula can take 2 forms depending from an if statement, but the condition for entering the statement returns false even when it should return true!

This is the code: Class that calls the fuction:

from loader import Loader

loader_ = Loader(r'C:\Users\damia\OneDrive\Desktop\logistic management tool\cycles_sample.xlsx',
                 r'C:\Users\damia\OneDrive\Desktop\logistic management tool\demand_sample.xlsx',
                 r'C:\Users\damia\OneDrive\Desktop\logistic management tool\bom_sample.xlsx',
                 r'C:\Users\damia\OneDrive\Desktop\logistic management tool\workshops_sample.xlsx')


class Plant:

    def __init__(self, loader):

        self.loader = loader
        self.workshops = self.loader.get_workshops()

        for ws in self.workshops:
            print('workshop automation level: ', ws.automation)
            print('checks if the workshop automation is table: ', str(ws.automation) == 'table')

        # computes disposable times
        for workshop in self.workshops:
            workshop.set_disp_time()


plant = Plant(loader_)
class Workshop:

    def __init__(self, name, shifts, shift_dur, pauses, pause_dur, placing, type_, uptime):

        self.name = name
        self.shifts = shifts
        self. shift_dur = shift_dur
        self.pauses = pauses
        self.pause_dur = pause_dur
        self.placing = placing
        self.type_ = type_
        self.uptime = uptime

        self.parts = []
        self.automation = set()
        self.disp_time = 'undefined'

    def set_part(self, part):

        for phase in part.phases:
            if phase.placings > 0:
                self.automation.add('auto')
            elif phase.placings == 0 and phase.machining != phase.operator:
                self.automation.add('machine')
            elif phase.placings == 0 and phase.machining == phase.operator:
                self.automation.add('table')
            else:
                raise Exception('Undefined type for workshop, part, phase: ', self.name, part.name, phase.seq)

        if len(self.automation) != 1:
            raise Exception('more that 1 kind of automation')

        self.parts.append(part)

    # computes workshop disposable time
    def set_disp_time(self):

        print('inside set function')
        print(self.automation)
        print(self.automation == set('auto'))

        if self.automation == set('table'):
            self.disp_time = self.shifts * self.shift_dur * 60 * self.uptime - self.pauses * self.pause_dur
        elif self.automation == set('machine') or self.automation == set('auto'):
            self.disp_time = self.shifts * self.shift_dur * 60 * self.uptime
        else:
            raise Exception('Undefined disposable time for: ', self.name)

There's also a class that loads data from excel, but it shouldn't give any problem, since the workshop objects are created correctly:

import pandas as pd
from iteration_utilities import duplicates, unique_everseen
from workshop import Workshop


class Phase:

    def __init__(self, seq, workshop, machining, operator, placings, setup):

        self.seq = seq
        self.workshop = workshop
        self.machining = machining
        self.operator = operator
        self.placings = placings
        self.setup = setup


class Part:

    def __init__(self, name, phases, workshop):

        self.name = name
        self.phases = phases
        self.workshop = workshop
        self.demand = 'undefined'
        self.downstream_bom = 'undefined'

        # check if all seq are unique and in sequence
        if not all(x.seq < y.seq for x, y in zip(self.phases, self.phases[1:])):
            raise Exception('Unsorted phases in part: ', self.name)

    def set_demand(self, demand):
        self.demand = demand

    def set_downstream_bom(self, bom):
        self.downstream_bom = bom


class Loader:

    def __init__(self, cycles_file, demand_file, bom_file, workshops_file):

        self.cycles_file = cycles_file
        self.demand_file = demand_file
        self.bom_file = bom_file
        self.workshops_file = workshops_file
        self.workshops = []

        cycles = pd.read_excel(self.cycles_file, sheet_name=None)
        # checks if all part names are unique
        cycles_names = []
        for sheet in cycles:
            cycles_names.append(sheet)
        if list(duplicates(cycles_names)):
            raise Exception('Multiple parts names in cycles file: ', list(duplicates(cycles_names)))
        # list of parts sheets
        sheets = []
        for sheet in cycles:
            sheets.append(cycles[sheet])
        # fillna
        sheets = [sheets[i].fillna(0) for i in range(len(sheets))]
        # drops useless 2nd row
        sheets = [sheets[i].drop([0]) for i in range(len(sheets))]
        # drops useless columns
        sheets = [sheets[i].drop(['Unnamed: 1', 'T mac (min/pz)', 'Unnamed: 4', 'Unnamed: 5'], axis=1) for i in range(len(sheets))]
        # list of parts names
        parts = []
        for sheet in sheets:
            part_name = sheet.columns[0]
            workshops_set = set()
            phases_list = []
            for i in range(len(sheet.index)):
                seq = sheet.iloc[i][0]
                workshop = sheet.iloc[i][1]
                workshops_set.add(workshop)
                machining = sheet.iloc[i][2]
                operator = sheet.iloc[i][3]
                placings = sheet.iloc[i][4]
                setup = sheet.iloc[i][5]
                # checks placings coherence
                if (placings > 0 and setup > 0) or (placings > 0 and operator > 0):
                    raise Exception('Placing coherence error in part, phase: ', self.name, seq)
                phase = Phase(seq, workshop, machining, operator, placings, setup)
                phases_list.append(phase)
            for workshop in workshops_set:
                same_workshop_phases = []
                for phase in phases_list:
                    if workshop == phase.workshop:
                        same_workshop_phases.append(phase)
                part = Part(part_name, same_workshop_phases, workshop)
                parts.append(part)

        demand_data = pd.read_excel(self.demand_file)
        # checks for multiple products
        if list(duplicates(demand_data)):
            raise Exception('Multiple parts in demand file: ', list(duplicates(demand_data)))
        # demand assignment
        for part in parts:
            for col in demand_data.columns:
                if part.name == col:
                    part.set_demand(demand_data[col])

        bom_data = pd.read_excel(self.bom_file)
        bom_data = bom_data.fillna(0)
        # changes index name from numbers to parts
        new_indexes = []
        for item in bom_data['Unnamed: 0']:
            new_indexes.append(item)
        bom_data.index = new_indexes
        # deletes parts names column
        bom_data = bom_data.drop(['Unnamed: 0'], axis=1)
        # checks for multiple parts in rows and columns
        if list(duplicates(bom_data.columns)):
            raise Exception('Multiple parts in BoM columns: ', list(duplicates(bom_data.columns)))
        if list(duplicates(bom_data.index)):
            raise Exception('Multiple parts in BoM rows: ', list(duplicates(bom_data.index)))
        # checks if there are reciprocal dependencies
        coordinates = []
        for column in bom_data.columns:
            for row in bom_data.index:
                if row != column and bom_data.at[row, column] > 0:
                    coordinates.append({row, column})
        duplicates_list = list(duplicates(coordinates))
        if duplicates_list:
            raise Exception('Reciprocal dependencies in the BoM: ', duplicates_list)
        # sets downstream BoM
        for part in parts:
            part.set_downstream_bom(bom_data.loc[part.name])
        # checks coherence of parts data
        if len(list(unique_everseen(list(bom_data.columns) + list(bom_data.index)))) != len(sheets):
            raise Exception('Incoherent data about parts names in the BoM')

        workshops_data = pd.read_excel(self.workshops_file, sheet_name=None)
        # checks if there are turns and turn durations
        for workshop in workshops_data:
            if int(workshops_data[workshop]['Shifts']) == 0:
                raise Exception('Missing shifts in workshop: ', workshop)
            if float(workshops_data[workshop]['Shift duration (h)']) == 0:
                raise Exception('Missing Shift duration in workshop: ', workshop)
        # checks for multiple names
        if list(duplicates(workshops_data)):
            raise Exception('Duplicate names in workshops data: ', list(duplicates(workshops_data)))
        # checks if all the workshops in the parts are present in the workshop file
        for part in parts:
            for phase in part.phases:
                if phase.workshop not in workshops_data:
                    raise Exception('workshop in cycles not found in workshops file: ', phase.workshop)
        # creates workshop obj
        for workshop in workshops_data:
            name = workshop
            shifts = int(workshops_data[workshop]['Shifts'])
            shift_dur = float(workshops_data[workshop]['Shift duration (h)'])
            pauses = int(workshops_data[workshop]['Pauses/shift'])
            pause_dur = float(workshops_data[workshop]['Pause duration (min)'])
            placing = float(workshops_data[workshop]['Placing duration (min)'])
            type_ = str(workshops_data[workshop]['Type'])
            uptime = float(workshops_data[workshop]['uptime'])
            workshop = Workshop(name, shifts, shift_dur, pauses, pause_dur, placing, type_, uptime)
            self.workshops.append(workshop)

        # setting parts for workshops
        for part in parts:
            for workshop in self.workshops:
                if workshop.name == part.workshop:
                    workshop.set_part(part)

    def get_workshops(self):
        return self.workshops

This is the result I get:

workshop automation level: {'auto'}

checks if the workshop automation is table: False

workshop automation level: {'machine'}

checks if the workshop automation is table: False

workshop automation level: {'machine'}

checks if the workshop automation is table: False

workshop automation level: {'table'}

checks if the workshop automation is table: False

workshop automation level: {'table'}

checks if the workshop automation is table: False

workshop automation level: {'table'}

checks if the workshop automation is table: False

workshop automation level: {'table'}

checks if the workshop automation is table: False

workshop automation level: {'table'}

checks if the workshop automation is table: False

inside set function {'auto'} False

Traceback (most recent call last): File "C:\Users\damia\PycharmProjects\logistic_management_tool\plant.py", line 25, in plant = Plant(loader_)

File "C:\Users\damia\PycharmProjects\logistic_management_tool\plant.py", line 22, in init workshop.set_disp_time()

File "C:\Users\damia\PycharmProjects\logistic_management_tool\workshop.py", line 48, in set_disp_time raise Exception('Undefined disposable time for: ', self.name)

Exception: ('Undefined disposable time for: ', 'clav acciaio')

"Switch" and "If" conditional is not checking my variable values on PHP

Neither "if" nor "switch" are working for me. Could you please help me?

switch ($subject2) {
       case '-':
              $input = $subject1;
              break;
       default:
              $input = $subject1.' and '.$subject2;
}


echo $input;

I need to check if "subject2" has a dash or not.

If it has a dash, then my variable "input" needs to store the value of "subject1".

If it doesn't have a dash, then my variable "input" needs to store the values of "subject1" and also "subject2".

If I try using a 0 instead (without quotes), it works. If I try the word "none" instead of a dash, it doesn't work.


Here's a sample of the code I'm running:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>

<h1>Form</h1>

<form action="" method="get">

<!--First field of the form-->

<label for="name">Choose an option(mandatory):</label>

<input list="opcionLista1" id="sujeto1" name="sujeto1" value="<?php echo isset($_GET["sujeto1"]) ? $_GET["sujeto1"] : ''; ?>" onfocus="this.value=''">

<datalist id="opcionLista1">
   <option value="-">
   <option value="Juan">
   <option value="Pedro">
   <option value="Oliver">
</datalist> <br><br>


<!--Second field of the form-->

<label for="name">Choose an option (Optional):</label>

       <input list="opcionLista2" id="sujeto2" name="sujeto2" value="<?php echo isset($_GET["sujeto2"]) ? $_GET["sujeto2"] : ''; ?>" onfocus="this.value=''">

<datalist id="opcionLista2">
   <option value="-">
   <option value="Mariana">
   <option value="Estefa">
   <option value="Lucía">
</datalist>

<!--"Send" button-->

<input type="submit" name="enviar" value="buscar">

</form><br><br><br>

<!--Saving the field values on JavaScript to send them to PHP afterwards-->

<script type="text/javascript">
var sujeto1 =  document.getElementById("sujeto1").value;
var sujeto2 = document.getElementById("sujeto2").value;

<?php 
       $sujeto1 = "<script>document.write(sujeto1)</script>";
       $sujeto2 = "<script>document.write(sujeto2)</script>";

?> 
</script><br><br><br>

<!--Finally, the "Switch" code meant to check the value of the second field, that would define the value of $input according to the option selected-->

<?php 

switch ($sujeto2) {
       case '-':
       $input = $sujeto1;
              break;
       default:
              $input = $sujeto1.' and '.$sujeto2;
}

<!--This echo should show the value stored on my variable.-->

echo $input;

?>

</body>
</html>

The website should make you choose two options. The first one should be (will be) mandatory, the second one should be optional.

When you click on "search", it should display the result. But if you choose a dash on the second field, it will say something like "juan and -" instead of just "Juan".

Why the if statement continuing while the first condition is true

I have this program where a user will give 3 inputs. Comparing the inputs the program will return the biggest number. When a user give an input where the third number greater than the second number but the first number is the biggest number it gives a result that the third number is the biggest. But it should give the result that the first number is the biggest.

def max_num(x,y,z):
    x = input("num_1")
    y = input("num_2")
    z = input("num_3")
    
    if x > y and x > z:
        return(x + "is the biggest number")
    elif y > x and y > z:
        return(y + " is the biggest number")
    else:
        return(z + " is the biggest number")
        
        
print(max_num("num_1", "num_2", "num_3"))   

enter image description here

The program doesn't compare two number properly

The comparision operator doesn't work properly

class Solution:
    def romanToInt(self, s: str) -> int:
        dic = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        result = 0
        s = list(s)
        while True:
            if len(s) == 1:
                x = s.pop(0)
                result+=dic[x]
                break
            elif len(s) == 0:
                break
            else:

The comparision operator doesn't work properly

                if (dic[s[0]] < dic[s[1]]) == True: #gives true for 1000<10
                    result += dic[s[1]] - dic[s[0]]
                    s.pop(0)
                    s.pop(0)

It directly jumps here

                elif (dic[s[0]] >= dic[s[1]] )== True:
                    result += dic[s[1]] + dic[s[0]]
                    s.pop(0)
                    s.pop(0)

        return result


o = Solution()
print(o.romanToInt("MCMXCIV"))

How to improve this code to make it time efficient? For-loops, prime numbers

The task was taken from www.codewars.com

The prime numbers are not regularly spaced. For example from 2 to 3 the step is 1. From 3 to 5 the step is 2. From 7 to 11 it is 4. Between 2 and 50 we have the following pairs of 2-steps primes:

3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43

We will write a function step with parameters:

g (integer >= 2) which indicates the step we are looking for,

m (integer >= 2) which gives the start of the search (m inclusive),

n (integer >= m) which gives the end of the search (n inclusive)

In the example above step(2, 2, 50) will return [3, 5] which is the first pair between 2 and 50 with a 2-steps.

So this function should return the first pair of the two prime numbers spaced with a step of g between the limits m, n if these g-steps prime numbers exist otherwise nil or null or None or Nothing or [] or "0, 0" or {0, 0} or 0 0(depending on the language).

Examples: step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7"

step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++

step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}

See more examples for your language in "TESTS"

Remarks: ([193, 197] is also such a 4-steps primes between 130 and 200 but it's not the first pair).

step(6, 100, 110) --> [101, 107] though there is a prime between 101 and 107 which is 103; the pair 101-103 is a 2-step.

Here is my solution, which works perfectly and takes more than it requires to test out, however, I'm trying to optimize this code in order to make it more time-efficient.

def step(g,m,n):

    count = 0
    list= []
    list2 = []
    for num in range(m,n+1):
        if all(num%i!=0 for i in range(2,num)):
            count += 1
            list.append(num)
    

        
    for k in list:
        for q in list:
            if (q-k) > 0:
                if (q-k) == g:
                    list2.append(k)
                    list2.append(q)
            

                
    if not list2:
         return 
    else:
         return  [list2[0],list2[1]]

If you have any suggestions or even sample code, I would appreciate this.

why does not if command in while loop is not executing?

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
for(int i = 0 ; i<n ; i++) {
    
    int a =sc.nextInt();
    while (a < 0) {
        int lastDigit = a%10 ;
        a =  a/10;  

// this step is not executing if ( lastDigit == 4) {

            System.out.println("why this is not printing");
        }
    }
}

How do I get back to the top of a while loop?

so I am trying to make a guessing game on my own and when the game ends I hope it will prompt the player if he wants to play again by typing yes or no like this:

Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) y
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) n
Thank you for playing!

I managed to get the game working but I can't play the game again. I am stuck here:

guess = int(input("Guess a number between 1 and 10: "))
while True:
    if guess > num:
        print("Too high, try again!")
        guess = int(input("Guess a number between 1 and 10: "))
    elif guess < num:
        print("Too low, try again!")
        guess = int(input("Guess a number between 1 and 10: "))
    else:
        print("You guessed it! You won!")
        replay = input("Do you want to continue playing? (y/n) ")
        if replay == "y":
            **what to insert here???**
        else:
            break

I don't know what to type inside the if statement that will return my code to the top of the loop if the user press "y" and allows me to restart the game.

Any help will be appreciated! Please do not give me the entire solution but try to give me hints so I can solve this by myself! Thank you!

Add quiz to student in object oriented programming (Java)

Before you read, this is for my homework. The questions will be very specific.

I am writing some code that has an object class of the course and it allows the user to enter the quiz marks of the student. The quiz also has a scale for each mark. How this works is that there is an ArrayList that stores all the quiz marks of each student according to their studentId. The problem that I am having is that I can not include all the parameters that the method has. Since it was a boolean, what I have tried is to but the if-else function to the method. However, I cannot think of a way to incorporate the scale or have the if the statement has an error that the studentGrade cannot equal to "null". What I believe that should be in the block of code is that there would be something like studentGrade * scale for the adding for the total of the quiz marks but I am unsure how to implement that into my method.

This is my code:

import java.util.ArrayList;

public class Course{
    private ArrayList<Student> students;
    ArrayList<Student> quiz;

    public Course() {
        students = new ArrayList<Student>();
        quiz = new ArrayList<Student>();
    }

    Student addStudent (String name, String familyName){
        students.add(new Student(name,familyName));
        return null;
    }

    Student findStudent(long studentId) {
        for (Student e : students) {
            if (e.getStudentNumber() == studentId)
                return e;
        }
        return null;
    }

    Student deleteStudent(long studentId){
        students.remove(studentId);
        return null;
    }

    boolean addQuiz(long StudentId, double scale, double studentGrade){
        if (studentGrade == null || students.contains(StudentId)) {
            return false;
        }
        studentList.add(student);
        return true;
    }

    Student findTopStudent(){
        if (students.size() == 0)
            return null;
        Student largestYet = students.get(0);

        for(int i = 1; i < students.size(); i++){
            Student e = students.get(i);
            if(e.getQuizAverage() > largestYet.getQuizAverage())
                largestYet = e;
        }
        return largestYet;
    }

    double getAverage(){
//ignore this for now
    }

}

vendredi 28 mai 2021

HTML Javascript check if submit clicked before timer expired

I am trying to add a validation for promotion timer that allows users to get discount while timer is running (countdown).

Pseudo code

  1. Timer still running
  2. User fills out form and clicks submit button
  3. If condition : a) if timer still running -> send form and Add discount to this form submission b) if timer expired -> send form without discount code

(index.html) here is my script for timer inside html page

'''

    <script>
      // Set the date we're counting down to
      var countDownDate = new Date("May 30, 2021 09:17:25").getTime();
      
      // Update the count down every 1 second
      var x = setInterval(function() {
      
        // Get today's date and time
        var now = new Date().getTime();
          
        // Find the distance between now and the count down date
        var distance = countDownDate - now;
          
        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
          
        // Output the result in an element with id="timer"
        document.getElementById("timer").innerHTML = days + "d " + hours + "h "
        + minutes + "m " + seconds + "s ";
          
        // If the count down is over, write some text 
        if (distance < 0) {
          clearInterval(x);
          document.getElementById("timer").innerHTML = "EXPIRED";
        }
      }, 1000);
      </script>

'''

and when you click submit button it takes you to submission form on the other page (booknow.html)

(booknow.html) here is my script for submission form inside different html page

'''

<script>$(document).ready(function() {
            var $sendEmailEl = $('#send-email');
            var $subjectEl = $('#subject');
            var $bodyEl = $('#body');
            var $addressEl = $('#address');
            var $fnameEl = $('#fname');
            var $lnameEl = $('#lname');
            var $phoneEl = $('#phone');
            var $applianceEl = $('#appliance')
            var $dayEl = $('#day');
            var $myEmailEl = 'gmail.com';
            var $myEmailEncode = ('acbdefg' +  '@' + $myEmailEl );
            // adding coupon function if timer still running Start
            var $coupon = "";

            function addCoupon() {

            }
            // adding coupon function if timer still running End
            function updateEmailLink() {          
                $sendEmailEl.attr('href', 'mailto:'+ encodeURIComponent($myEmailEncode) +'?' + 
                'subject=' + encodeURIComponent($subjectEl.val()) + 
                '&body=' + 'Hi there' + '%0D%0A' + encodeURIComponent($bodyEl.val()) + '%0D%0A' + ' Address: ' 
                + encodeURIComponent($addressEl.val()) + '%0D%0A' + ' First Name: ' 
                + encodeURIComponent($fnameEl.val()) + '%0D%0A' + ' Last Name: ' 
                + encodeURIComponent($lnameEl.val()) + '%0D%0A' + ' Phone: ' 
                + encodeURIComponent($phoneEl.val()) + '%0D%0A' + ' Appliance: ' 
                + encodeURIComponent($applianceEl.val()) + '%0D%0A' + ' Prefered date: '
                + encodeURIComponent($dayEl.val())
                );
                // console.log($sendEmailEl.attr('href'));
            }
            $('#subject,#body').on('input', updateEmailLink);
            updateEmailLink();
        });
    </script>

'''

I should probably add var with random code "Discount777" somewhere inside timer script and then check with if statement inside submission script whether timer is running, and if so then grab that var = "Discount777" from a different page and send it along with the form. Or maybe there is an easier way?

python printing vectors in different forms

Write a program called ‘vectormath.py’ to do basic vector calculations in 3 dimensions: addition, dot product and normalization.

hi there's an error on my mapping function

sample input:

Enter vector A:

1 3 2

Enter vector B:

2 3 0

sample output

A+B = [3, 6, 2]

A.B = 11

|A| = 3.74

|B| = 3.61

import math
def addition(a,b):
    return[a[0]+b[0] , a[1] + b[1] , a[2] + b[2]]

def  Dotproduct(a , b):
    return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]

def norm(a):
    square = a[0]**2 + a[1]**2 + a[2]**2
    return math.sqrt(square)

def main():
    vector_A = input("Enter vector A:\n").split(" ")
    vector_A = map(int,vector_A)
    vector_B = input("Enter vector B:\n").split(" ")
    vector_B = map(int, vector_B)
    
    print(addition(vector_A,vector_B))
    print(addition(vector_A,vector_B))
    print(norm(vector_A))
    print(norm(vector_B))
    
if __name__ == "__main__":
    main()

Why does my Eclipse formatter move the condition and parenthesis to separate lines for my if statements and for loops?

When I reformat my java code in Eclipse (CTRL-SHIFT-F), it does weird things to my if statements. It puts the open parenthesis, the condition, and the closing parenthesis each on their own line.

Here is an example:

        if (
            x != null
        )
        {
          ...
        }

I want it to look like this:

        if (x != null)
        {
          ...
        }

Reformatting does the same thing to my for loops:

    for (
            int i = startIndex; i <= endIndex; i++
    )
    {
       ...
    }

I've tried going to Window -> Preferences -> Code Style -> Formatter. I can't find the option I need in order to fix this. Please help!

PHP Array get value within if value is found

As the title says im trying to get addresses with a certain search query. Im trying to get the addresses if n = a specific number, in this example 0

I decoded the json to an php array using json_decode($json, true)

{
    "result": {
        "txid": "40ca93b1c36355cf53817c233e1dcad8658ae7640754666c6618f7fcc46d78fe",
        "hash": "7bf98122b6fc6270e025eb7a54a0002160ea0a70234c5ddbf83829fa6194502b",
        "vout": [
            {
                "value": 6.73707231,
                "n": 0,
                "scriptPubKey": {
                    "asm": "OP_DUP OP_HASH160 536ffa992491508dca0354e52f32a3a7a679a53a OP_EQUALVERIFY OP_CHECKSIG",
                    "hex": "76a914536ffa992491508dca0354e52f32a3a7a679a53a88ac",
                    "reqSigs": 1,
                    "type": "pubkeyhash",
                    "addresses": [
                        "18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX"
                    ]
                }
            },
            {
                "value": 0.00000000,
                "n": 1,
                "scriptPubKey": {
                    "asm": "OP_RETURN 52534b424c4f434b3a2fa0aeae5b032973f7e4646182b15e99e85e6be4c6b0c830a207f21c0032ca3c",
                    "hex": "6a2952534b424c4f434b3a2fa0aeae5b032973f7e4646182b15e99e85e6be4c6b0c830a207f21c0032ca3c",
                    "type": "pubkeyhash"
            "addresses": [
                        "545545553454354"
                    ]
                }
            },
            {
                "value": 0.00000000,
                "n": 2,
                "scriptPubKey": {
                    "asm": "OP_RETURN b9e11b6d3600c5e9411b60ef0150a4eb5a9e18c6e9fc43390ef6eb3357a58f992a82c0a7",
                    "hex": "6a24b9e11b6d3600c5e9411b60ef0150a4eb5a9e18c6e9fc43390ef6eb3357a58f992a82c0a7",
                    "type": "pubkeyhash"
            "addresses": [
                        "asdas5d6as1dsa1sd15asd156"
                    ]
                }
            }
            }
        ],
        "blockhash": "000000000000000000038e4342bab438ad277824e17d39cf39a44fc5aa419ff4",
        "confirmations": 3029
    },
    "error": null,
    "id": "curltest"
}

R - Copy negative sign from one to another column

I have a dataframe (df_ann) as shown here:

Cha Seg_value Seg_value2
AXL2 -0.654 2.965
PTT1 1.957 1.84
AXL2 2.654 0.989
PTT1 -1.038 0.85

I want to add the negative sign in the Seg_value2 column if it is present in the Seg_value column.

Output should be:

Cha Seg_value Seg_value2
AXL2 -0.654 -2.965
PTT1 1.957 1.84
AXL2 2.654 0.989
PTT1 -1.038 -0.85

I have searched for the solution to the problem but did not find the answer. Anything would be helpful.

Thanks in advance!

Use "Else If" program that takes 3 integers x, y, z (3 kinds of goods) from the employee [closed]

You are a supermarket manager, aiming to place goods to the right place which are coded by number (odd and even number).

Write a program that takes 3 integers x, y, z (3 kinds of goods) from the employee and checks If x is even or odd.

  • If x is an even number, check whether y is greater than or equal to 20. If y >= 20, print "y to the A place", print "y to B place" otherwise.

  • If x is an odd number, check whether z is greater than or equal to 30. If z >= 30, print "z to the C place ", print "z to D place" otherwise

Example:

For x = 20, y = 33, z = 15, the output should be " y to the A place ".

Because x % 2 = 0 and y > 20

For x = 15, y =23, z = 20, the output should be " z to the D place ".

Because x % 2 != 0 and z < 30

Flutter: Running Navigation only if one thing is selected

Im trying to only allow the navigation to happen if _gender != ''. Meaning the user needs to select at least a gender. Currently, _gender is error underlined here.

How should the ternary operator run here as I know the error is probably caused by the genderwidget being in another dart file?

Lmk if there's any better way to run this? Open to any answers thanks!

etc

    return MaterialApp(
        home:
            Gender()); // This trailing comma makes auto-formatting nicer for build methods
  }
}

class Gender extends StatelessWidget {

etc

    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color(0xff3a327f),
        elevation: 9,
        child: Icon(Icons.chevron_right, size: 27, color: Colors.white),
        onPressed: () {
          if (_gender != '')
          Navigator.push(context, _createRoute());
        },
     
      ),
      body: SafeArea(
        child: Column(children: <Widget>[
         
        Container(
              
                child: Text(
                  'What\'s your gender?',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30),

              ),
            ),
 
        
          SizedBox(
            height: 60.0,
          ),
          child: genderWidget(),
        ]),
      ),
    );
  }
}

On another dart file

class genderWidget extends StatefulWidget {


etc

  String _gender = '';

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(9.0),
      child: Column(
        children: <Widget>[
          Card(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15.0)),
            child: RadioListTile(
              title: CardTextStyle(gender: 'Female'),
              value: 'isFemale',
              activeColor: Colors.green,
              groupValue: _gender,
              onChanged: (value) {
                setState(() {
                  _gender = value;
                  print(_gender);
                });
              },
              controlAffinity: ListTileControlAffinity.trailing,
            ),
          ),
          Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15.0),
            ),
            child: RadioListTile(
              title: CardTextStyle(gender: 'Male'),
              value: 'isMale',
              activeColor: Colors.green,
              groupValue: _gender,
              onChanged: (value) {
                setState(() {
                  _gender = value;
                  print(_gender);
                });
              },
              controlAffinity: ListTileControlAffinity.trailing,
            ),
          ),
          Card(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15.0)),
            child: RadioListTile(
              title: CardTextStyle(gender: 'Non-Binary'),
              value: 'isNonBinary',
              activeColor: Colors.green,
              groupValue: _gender,
              onChanged: (value) {
                setState(() {
                  _gender = value;
                  print(_gender);
                });
              },
              controlAffinity: ListTileControlAffinity.trailing,
            ),
          )
        ],
      ),
    );
  }
}

class CardTextStyle extends StatelessWidget {
  CardTextStyle({this.gender});

  String gender;

  @override
  Widget build(BuildContext context) {
    return Text(
      gender,
      style: TextStyle(
          color: Colors.black, fontWeight: FontWeight.w600, fontSize: 15),
    );
  }
}



PHP Parse error: syntax error, unexpected 'else' (T_ELSE) in ... on line 179 [duplicate]

My first question in this forum. If I haven't supplied enough info, please let me know.

I am receiving an error in a PHP if/else statement and the page does not load - page error is HTTP error 500. I'm not very experienced in PHP, but what I have written looks ok to me. Apparently it is not. Seeing if anyone can point me to my error.

enter image description here

Why am I always getting 1 as answer irrespective of the value assigned to the variable a

Why am I getting 1 as output instead of 7 ( if a is initially assigned with 12 , then a-5 should give 7) or 3 as ( if a is assigned with 8 then a-5 should give 3 ). The output remains 1 always irrespective of the value assigned to a.

int main()
{
    int a = 12;
    if (a = 8  && (a = a - 5))
        cout << a;
    else
    {
        //do nothing !!
    }
}

To refactor multiple If statements in java

How can I avoid multiple if statements for the below code?

for (Student students : studentList) {

    if ((Constants.CODE1.equals(students.getactivities().getCode())
            && ValidationRepository.validateStudentId1(department.getId()))
            || ((Constants.CODE2).equals(students.getactivities().getCode())
                    && ValidationRepository.validateStudentId2(department.getId())
                    && ValidationRepository.validateStudentId3(department.getId()))
            || ((Constants.CODE3
                    .equals(students.getactivities().getCode())
                    || Constants.CODE4
                            .equals(students.getactivities().getCode()))
                    && (ValidationRepository.validateStudentId4(
                            department.getId(),
                            students.getactivities().getCode())))
            || ((Constants.CODE5.equals(students.getactivities().getCode())
                    || Constants.CODE6
                            .equals(students.getactivities().getCode())

                    || Constants.CODE7
                            .equals(students.getactivities().getCode())
                    || Constants.CODE15
                            .equals(students.getactivities().getCode())

                    || Constants.CODE8
                            .equals(students.getactivities().getCode())
                    || Constants.CODE9
                            .equals(students.getactivities().getCode())

                    || Constants.CODE10
                            .equals(students.getactivities().getCode())
                    || Constants.CODE11
                            .equals(students.getactivities().getCode()))

                    && (ValidationRepository.validateStudentId4(
                            department.getId(),
                            students.getactivities().getCode())))

    )
    { 
        some statements
    }

jeudi 27 mai 2021

How to average data with an exclusion criterion?

this is the expected input and output:enter image description here and this is what I got with the following code: enter image description here

c = float(input())
cant = 1
suma = 0
i = 0

while c > 0.053:
    suma += c
    cant += 1
    c = float(input())

if c > 2.049:
    a = c
    prom = (suma-a)/cant 
else:
    prom = suma/cant

print(cant)

print('{0:.2f} '.format(prom))

Python - How to write only 'if' in one line?

When I write the following it gives me an error, but I need to write it like this (in one line) how to solve it.

this works

if c:
    for y in r: img += '   '

this doesn't

if c: for y in r: img += '   '

syntax error

File "<string>", line 12
if c: for y in r: img += '   '
^
SyntaxError: invalid syntax

Wordpress / Elementor / Ninjaforms - Challenge: If else / sales calculation

i’m looking for a soloution for the following problem. It’s a small form to calulate the cost of a product.

The form has only one field to enter: “Quantity” The Price of the product ist always $50. But the shipping costs are: For 1 piece: $10 From: 2-10 pieces: $20 from 11-30 pieces: $40

One way i thought: classic excel style with if/else statements the other way: a precalculated amount for every possible ordered amount. But both are not possible with ninja forms, or are they?

Or are ther any other possible ways?

Thanks!

Condition in array results

i'm new into python, so, my question is kind simple.

I have a linear Regression, my ypred returns to me a array like this

  yPre2_pred = regressaoPre2.predict(XPre2_test)

  ddf2 = pd.DataFrame({'Realizado': yPre2_test, 'Resultado do modelo': yPre2_pred, 'Variação': 
  yPre2_pred / yPre2_test  -1 })
  r_sq = regressaoPre2.score(xPre2, yPre2)
  r_sqmodelo = regressaoPre2.score(XPre2_test, yPre2_test)

  print(ddf2)

  Realizado  Resultado do modelo  Variação
  43     211.33           279.505979  0.322604
  49     125.84            88.377950 -0.297696
  62      55.57            44.049949 -0.207307
  51      39.68            11.281662 -0.715684
  32     473.58           408.446098 -0.137535
  34     123.92           211.493634  0.706695
  29     441.96           311.487298 -0.295214
  46     317.28           309.504595 -0.024506
  11     122.19           162.888449  0.333075
  2       37.73          -103.208499 -3.735449
  26      40.16            73.811614  0.837939
  60     240.40           184.092869 -0.234223
  4       88.98           -24.397806 -1.274194

I need to " if "resultado modelo" (yPre2_pred) below 40, then add 40 to the results.

How can i get it?