lundi 30 septembre 2019

If-else Refactor

I am trying to refactor this block of if else statements. What can be the best optimized version of this code?

`const handlePhoneNumberFormat = (rules, value, callback) => {
    if (value && value.match(phoneNumberRegex)) {
      if (value.includes('-')) {
        if (value.indexOf('-') === 2) {
          if (value.length !== 10) {
            callback('Please enter 7 digits after "-".');
          } else {
            callback();
          }
        } else if (value.indexOf('-') === 3) {
          if (value.length !== 14) {
            callback('Please enter 10 digits after "-".');
          } else {
            callback();
          }
        } else {
          callback();
        }
      } else {
        callback();
      }
    } else {
      callback('');
    }
  };`

Is this pseudocode solution correct? (Update)

Can someone check my code? (pseudocode problem)?

Here's the problem I have to solve: The CIS Department is looking to get audit reports printed for its employees that detail enrollment in each of the programs monitored by the department. The reports (which will be run only once to produce all that is required) will detail on a single page the name of the program, number of students enrolled in the program, and the names of the students in the program. The CIS department monitors Cisco Networking, Computers and Information Systems, Data Assurance and IT Security and Web Design.

I'm still new to programming, hoping someone can confirm if I put all of the values in the right place. For instance, after ENDIF, should I put "produce" or something else? Feedback would be greatly appreciated!

Here's my defining diagram and solution...

DEFINING DIAGRAM:

input
Program name

output
program name
number of students
student  names

processing
Prompt for program name
Read program name
Print report

SOLUTION:

Produce audit_report

Print 'Program name'

    Read program name

   IF program name = 'Cisco Networking' 

  OR 'Data Assurance' 

  OR 'Web Design'

  OR 'CIS'

  THEN

    Print program_name, number_students, student_names

ELSE

    Print  'program not found'

ENDIF

END

Print Not Executing after If Else Statement

Vending Machine Python 3 Exercise - Program ending after last if else statement. I cannot get the program to read "insufficient funds" at the end if the price paid was less than the cost. If the funds are sufficient I cannot get it to print "thank you".

price_multiplier=1.25
option=int(input("Welcome to the vending machine! What would you like to drink today?\n1 - Dr. 
Pepper\n2 - Code Red Mountain Dew\n3 - Cherry Coke\t\n4 - Mountain Dew\n(Small - $1.25; Medium 
$2.50; Large $3.75)\nPlease Make your selection: "))
if (option==1):
    print("You have ordered a Dr. Pepper.")
elif (option==2):
    print("You have ordred a Code Red Mountain Dew.")
elif (option==3):
    print("You have ordered a Cherry Coke.")
elif (option==4):
    print("You have ordered a Mountain Dew.")
else:
    print("Invalid selection. Please choose from the menu above.")
option=input("Please select 'S' for small, 'M' for medium, or 'L' for large: ")
if (option=='S'):
    price=price_multiplier
    print("You have ordered a small. Your total is: $", price)
elif (option=='M'):
    price=price_multiplier*2
    print("You have ordered a medium. Your total is: $", price)
elif (option=='L'):
    price=price_multiplier*3
    print("You have ordered a large. Your total is: $", price)
else:
    print("Error: Invalid selection.")
print("Please insert amount.")
paid=float(input("Amount inserted: $"))
if paid<price:
    print("Insufficient funds, no sale!")
else:
    print("Your change is: $", paid-price)
    print("Thank you - enjoy your drink!")

What is the best way to refactor multiple conditions in an if statement?

I have an if statement with lots of conditions inside, but the conditions are fairly different. It looks really bulky. I'm not sure if there is a way to do it.

// rqstCriteria is a List
// anotherCriteria is a List
// key# are the different values that I want to see if it has
if (
rqstCriteria.contains(key1) || 
rqstCriteria.contains(key2) || 
rqstCriteria.contains(key3) || 
rqstCriteria.contains(key4) || 
rqstCriteria.contains(key5) && 
(anotherCriteria != null && 
  (anotherCriteria.contains(key1) || 
   anotherCriteria.contains(key2) || 
   anotherCriteria.contains(key3) || 
   anotherCriteria.contains(key4) || 
   anotherCriteria.contains(key5))
{...} 

Excel: Count how many times a value appears in a row

Below in the pic on the right side you have got the values. On the left the excel formula "count(And(A4=A5);1;0)" is included which counts how many times each value appears in a row. You see the value "2" and "8" appears twice in a row. The formule is however cumbersome. A more practical way would be to have a formula over the column which counts all values that are constant once in a row then twice in a row etc. Would be the "index" command a solution?

enter image description here

How does "showpage()" work in this piece of code?

I have been learning Lua from http://www.lua.org/pil/4.3.1.html and they had this piece of code:

if line > MAXLINES then
  showpage()
  line = 0
end

I don't understand what "showpage()" does here. I don't know whether this is just an example of a function that had to be previously defined (and I don't know if you can actually do this with a function) or is it a library I don't know of.

Loop statement inside if else statement

i want to show all rows using loop in a table, but if there is no data available i want to echo some text there. i am using codeigniter. i want to use loop inside if statement and in else i will echo any text when there will be no data.

here is the code

<?php 
$nextdate = date('Y-m-d',strtotime("+3 day"));
$this->db->order_by('tourdateID', 'ASC');
$this->db->where('tourid', $blogres[0]['tourid']);
$this->db->where('start >=', $nextdate); 
$subs = $this->db->get('tour_date')->result_array();

$i = 1;

foreach($subs as $sub){?>
    <div class="row priceRow priceRowReg  filter_12  guaranteedFlag">
        <div class="eq-pr2 small-4 medium-4 large-4 columns pad-lft-20">
            <div class="tcircle amber"></div><a class="date drk" rel="nofollow" href="#"><?php echo date('d M, Y', strtotime($sub['start'])); ?> - <?php echo date('d M, Y', strtotime($sub['end'])); ?></a>

        </div>

        <div class="eq-pr2 small-3 medium-3 large-3 columns cnt bld"><?php 

        $this->db->where('tourdateID',$sub['tourdateID']);
        $booking = $this->db->count_all_results('book_tour');                    
        $availibility = $sub['total_capacity'] - $booking;


        ?><?= $availibility; ?> Seats left</div>
        <div class="eq-pr2 small-3 medium-3 large-3 columns cnt pad-rgt-20"><a class="inl bld f19 wht wrBCol3 colLinkPad showinfo" rel="nofollow" href="<?=base_url();?>bookings/step1/<?= $blogres[0]['tourid'];?>/<?= $sub['tourdateID']?>">Book Now</a> </div>

    </div>

<? } ?>

Excel Formula substitute similar values into a single formula

I have set up this formula, For each cell it should subtract the contents from what i have stored in data!$B$1, in this case this is 300, so if the contents of "Time 1" is 100, this will display 200, this will then add up all of these values from Time 1 up to Time 15, this will also ignore anything that is not a number. Currently I have:

=SUM(IF(ISNUMBER([@[Time 1]]),data!$B$1-[@[Time 1]], 0),IF(ISNUMBER([@[Time 2]]),data!$B$1-[@[Time 2]], 0),IF(ISNUMBER([@[Time 3]]),data!$B$1-[@[Time 3]], 0),IF(ISNUMBER([@[Time 4]]),data!$B$1-[@[Time 4]], 0),IF(ISNUMBER([@[Time 5]]),data!$B$1-[@[Time 5]], 0),IF(ISNUMBER([@[Time 6]]),data!$B$1-[@[Time 6]], 0),IF(ISNUMBER([@[Time 7]]),data!$B$1-[@[Time 7]], 0),IF(ISNUMBER([@[Time 8]]),data!$B$1-[@[Time 8]], 0),IF(ISNUMBER([@[Time 9]]),data!$B$1-[@[Time 9]], 0),IF(ISNUMBER([@[Time 10]]),data!$B$1-[@[Time 10]], 0),IF(ISNUMBER([@[Time 11]]),data!$B$1-[@[Time 11]], 0), IF(ISNUMBER([@[Time 12]]),data!$B$1-[@[Time 12]], 0),IF(ISNUMBER([@[Time 13]]),data!$B$1-[@[Time 13]], 0), IF(ISNUMBER([@[Time 14]]),data!$B$1-[@[Time 14]], 0), IF(ISNUMBER([@[Time 15]]),data!$B$1-[@[Time 15]], 0))

This is essentially just

=SUM(IF(ISNUMBER([@[Time 1]]),data!$B$1-[@[Time 1]], 0))

but repeated for each Time. It seems extremely verbose for something that is practically using the same formula, could the same result be achieved through substituting "Time 1" with a list?

Here is a sample of the calculation currently:

enter image description here enter image description here

Thanks in advance.

If and Nested If

PURPOSE: To code a program using a while-loop with a nested(embedded) if-else structure within an if-else structure

INSTRUCTIONS: Code a program that prints messages based on the validity of a password and a person’s age.

1.In a sentinel-controlled while-loop, where the first iteration of this repetition structure is automatically entered,

a.ask for a password. The password is “MonthyPython”.

i.When the password is wrong print, “Invalid Password!” and the while-loop can either continue or stop.

ii.Otherwise, the password is correct, so ask for an age.

1)If the age is greater than 17 print “Shangri-La welcomes you to your earthly paradise!”

2)Otherwise, age is less than or equal to 17, so print, “Sorry, NO under-age patrons allowed!”

b.There are 2 double-selection ifs. One is nested within the other. Is the nested if-else within the body of the if that tests for an invalid password or its else?

2.Use printf() and format specifiers.

  1. Exit the main()

****SAMPLE OUTPUT**** What is the password? MontyPithy

Invalid password!

Do you want to try again? Enter ‘Y’ or ‘N’: y

What is the password? MonthyPython

Enter your age: 16

Sorry, NO under-aged patrons allowed!

Do you want to try again? Enter ‘Y’ or ‘N’: y

What is the password? MonthyPython

Enter your age: 25

Shangri-La welcomes you to your earthly paradise!

Do you want to try again? Enter ‘Y’ or ‘N’: n

Thank you! Have a nice day!

****HERE IS MY CODE BELOW****CAN'T SEEM TO GET IT RIGHT**** /** * Auto Generated Java Class. */ import java.util.Scanner;

public class testLU {

 public static void main(String[] args) { 

 //create scanner to capture input from keyboard
 Scanner input = new Scanner(System.in);

 String pass;
 int age = 0;
 char keepGoing = 'Y';
 char stop = 'N';
 boolean valid = true;    

 while(Character.toUpperCase(keepGoing) == 'Y')
 {          
 System.out.printf("What is the password%n");
 pass = input.nextLine();

 if (pass.equals("MonthyPython"))
 {
 System.out.printf("Enter your age: %n");
 age = input.nextInt();
 if (age > 17)
 {
 System.out.printf("Shangri-La welcomes you to your "+
                   "earthly paradise!%n");
 }   
 else

 if (age <= 17)
 {
 System.out.printf("Sorry, NO underaged patrons allowed!%n");
 }
 }
 else
 { 
 System.out.printf("Invalid password!%n");
 }
 {
 System.out.printf("%nDo you want to keep going? Enter \'Y\'"+
                         "or \'N\': ");     
 keepGoing = input.nextLine().charAt(0);

 {

System.out.printf("Thanks you!%n"); }

 }
 }
 }
 }

Formula that would check a column of cells and say if he found an exact word

Alright, so I want a formula that would search in a column of words a specific word, I was helped at making one but it only logs the first one and stops there (even though it's not the one I want it to find)

=ARRAYFORMULA(IFERROR(VLOOKUP(A1:A50, IMPORTRANGE("(sheetid)", "Project Automation Checker!B1:D50"), {2,3}, 0))).

I want it to find the word "CT" in column D of the Project Automation Checker. https://docs.google.com/spreadsheets/d/1n8DF771658l-7lIMu2Jx7YF9ZoHGb3H8UA0eOVd8iaE/edit?usp=sharing

How to display anything in between particular duration in php?

I have a code as shown below in which the values inside $start_day, $data->{"start_time"} and $end_day, $data->{"end_time"} is entered by user.

enter image description here

1. Start Day: $start_day
2. Start Time: $data->{"start_time"}

3. End Day: $end_day
4. End Time: $data->{"end_time"}

What I want to achieve through php is I want to display something in between particular duration.

I want to display something in between Start Day/Time and End Day/Time.

Let say suppose $start_day is mon, $data->{"start_time"} is 111300, $end_day is sat and $data->{"end_time"} is 114500

date_default_timezone_set('America/Toronto');

$nowtime = (int)date('His');

$arradate = strtolower(date('D')); //extracting day of the week on the basis of timezone

$start_day=$data->{select_start_day}; // it can be `mon` or `tue` or `wed` or `thu` or `fri` or `sat` or `sun` depending on what is in the JSON

$end_day=$data->{select_end_day}; // it can be `mon` or `tue` or `wed` or `thu` or `fri` or `sat` or `sun` depending on what is in the JSON

The values inside all these variables is entered by user so in short user control all these times.

This is what I have tried and its not wroking for me.

if(($arradate >= $start_day && $nowtime>=$data->{"start_time"}) && ($arradate <= $end_day && $nowtime <= $data->{"end_time"})) {
    echo "Hello World";  // I want Hello World to be displayed in between Friday 6pm and Tuesday 6pm
}

New to programming in general (JAVA). How should I fix these errors? Is the nested if-else structure correctly ordered?

I am working on a program using Java and I am getting errors. The purpose of the program is to code a while-loop with a nested if-else structure within an if-else structure. (1) There is an error on line 33 that says "variable age might not have been initialized" even though it is declared in the main()? (2) Am I correctly nesting the if-else structures inside the while? (3)Are the curly brackets correctly placed? Please let me know if I am doing anything wrong or could be doing anything better! Updated question

/**
* @author Sean Ramos
* @version1.0 9/30/2019 1:30PM 
* PURPOSE: To use a while-loop with a nested if-else structure within an if-else structure.
*/
import java.util.Scanner;
public class RamosSLE32 { //Begin class

public static void main(String[] args) { //Begin main()

Scanner input=new Scanner(System.in);
int age;
String correctPassword="MonthyPython";
char tryAgain='Y';
char tryAgain2='Y';
String q1="%nWhat is the password?";
String q2="%nEnter your age: ";

while(Character.toUpperCase(tryAgain)=='Y') {
 System.out.printf(q1);
 String password=input.nextLine();
 if(!password.equals(correctPassword))
 { 
   System.out.printf("%nInvalid password!%nDo you want to try again? Y or N.");
   tryAgain=input.nextLine().charAt(0);
 }
 else
 { if(password.equals(correctPassword))
 { System.out.printf(q2);
   age=input.nextInt();
 }
 { if(age > 17)
 {
    System.out.printf("%nShangri-La welcomes you to your earthly paradise!%nThank you! Have a nice day!");
 }
 else 
 { if (age <= 17)
 { System.out.printf("%nSorry, NO underaged patrons allowed!%nDo you want to try again? Y or N.");
   tryAgain2=input.nextLine().charAt(0);
      }
     }
    }
   }
  }
  } //End main()

  } //End class

Run ffmpeg command based on data on a file

I have a text file that gets generated from running a command.

The text file has name of a file followed by all the matching audio tracks in one line then next line has the next video followed by matching tracks.

Because some of the videos have less tracks and some have more.is there a way i can do if and else command for ffmpeg to do the mergeing based on number of tracks matched to the name.

This is the command i use to merge. Merge (Copy Video and Audio)

ffmpeg -i video.mxf_V1.MXF.m2v -i video.mxf_A1.MXF -i video.mxf_A2.MXF -c copy out.mxf

followed by:

ffmpeg -i out.mxf -map 0:0 -map 0:1 -map 0:1 -c copy finished.mxf

Below is the example of how the file names are and how its written in the text file "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_V1.MXF.m2v" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A1.MXF" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A2.MXF" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A3.MXF" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A4.MXF" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A5.MXF" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A6.MXF" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A7.MXF" "5f367f72-9e2f-4f89-b3d6-2cdafed17d94_IRR_DOCUI_SONG_SomeMusic_KomKom.mxf_A8.MXF"

There's about 25,000 lines of these.

another thing i wanted is to be able to name the final file the same as the video file. Please.

Using IF statement in vb with database material

So I'm trying to use an If statement based on criteria in my database and I'm not sure how I'm new to vb. The viewaccess, editaccess, and approveaccess are bits in my database.

 If (Session("ViewAccess") = 1) And Session("EditAccess") = 0 And (Session("ApproveAccess") = 0) Then
            btnSaveTop.Visible = False
            btnSaveBottom.Visible = False
            btnApproveTop.Visible = False
            btnApproveBottom.Visible = False
            btnRequestUnapproveTop.Visible = False
            btnRequestUnapproveBottom.Visible = False
            RequiredData.FreightWBS.ReadOnly = True
            RequiredData.GemFeeWBS.ReadOnly = True
            RequiredData.Approver.ReadOnly = True
        End If

Bash script if not processing as I would expect

I am in the very early stages of learning Unix scripting. I've written a Bash script which does not generate any errors, but clearly has a logic error, as the IF test always gives the same response.

I have tried various variations on the theme of my IF, but still end up with the same result.

#!/bin/bash

declare -i number1
declare -i number2
declare -i total

declare operation

echo "Enter a, s, m or d for add, subtract, multiply or divide"
read operation

echo "Enter number 1"
read number1
echo "Enter number 2"
read number2

echo "operation="$operation

if [ $operation=='m' ]
then 
    total=$number1*$number2
elif  [ $operation=='a' ]
then 
    total=$number1+$number2
elif [ $operation=='d' ]
then 
    total=$number1/$number2
elif [ $operation=='s' ]
then 
    total=$number1-$number2
fi

echo $number1 " multiplied by " $number2 " equals " $total
exit 0

It doesn't matter whether I enter a, s or d (or indeed m) in response to the first prompt, my script always does a really nice multiplication... The line

echo "operation="$operation

correctly shows the operator I've requested.

Any ideas what I've done wrong?

Many thanks

MySQL/PHP else if statement with affected rows

I am trying to let to check the a table if there exists a value and if there exists a value it should output as JSON "one" and if it doesn't exist it should output "two". My thought is that With my SELECT EXIST Statement it should only return a row if there exists the value in the table but for some reason it always outputs a row.

Here is the code:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
if ($result = mysqli_query($conn, $query)) {

    $newArr = array();
    $value = mysqli_fetch_object($result);
    $newArr[] = (bool) $value->item_exists;

    echo json_encode($newArr); // get all products in json format.    
}
*/


/* part where output is just 1 or 0*/
$query = "SELECT EXISTS(SELECT * FROM wp_woocommerce_order_items WHERE order_id = $sdata)";
$myArray = array();
if ($result = mysqli_query($conn, $query)) {

        while($row = $result->fetch_row()) {
            $myArray[] = $row;
    }
 // 2nd operation checkif order available
 if ($conn->affected_rows == 1) {
        echo json_encode($one);
    } else {

//Success and return new id
        echo json_encode($two);
    }    
//end 2nd operation


    echo json_encode($myArray);
}$result->close();


echo json_encode($newArr); // get all products in json format.    
}


$conn->close();
?>

How to set a variable if set /a fails?

I would like to check if my set /a statement failed with a Missing operator. error or not. My current batch file, only sets the variable.

@echo off & @setlocal
set "rndtest=%random% %%2+1"
if "%rndtest%" == "1" set test=1()1
) else (
set test=1+1+1+1+1
)
set "test=1+1+1+1+1+1+1+1+1"
set /a "test_123_abc=%test%"
echo %test_123_abc%

I have tried the following solution, but to no avail :

@echo off & @setlocal
set "rndtest=%random% %%2+1"
if "%rndtest%" == "1" set test=1()1
) else (
set test=1+1+1+1+1
)
set /a "test_123_abc=%test%" | find "Missing operator."
if %errorlevel% equ 0 echo Test failed!
) else (
echo Test didn't fail!
)
exit /b 0

This always evaluates to Test didn't fail.

How to fix 'Wrong syntax near the IF statment'?

When I'm trying to create such stored procedure with CTE:

CREATE PROCEDURE bng_normalize_ps 
    @ps_id uniqueidentifier, 
    @u_name VARCHAR(50), 
    @u_type VARCHAR(50) 
    AS
 BEGIN

WITH My_Recursive (link, n_type, n_name, F_Parent )
    AS
    (
        SELECT
            i.link
            , t.C_Name n_type
            , i.C_Name as n_name
            , s.F_Parent
        FROM ED_Network_Items i
        JOIN ES_Network_Items_Types t on i.F_Network_Items_Types = t.LINK
        JOIN ED_Network_Struct s on s.F_Child = i.LINK
        WHERE
            i.link = @ps_id
        UNION ALL
        SELECT
            i.link
            , t.C_Name n_type
            , i.C_Name as n_name
            , s.F_Parent
        FROM ED_Network_Items i
        JOIN ES_Network_Items_Types t on i.F_Network_Items_Types = t.LINK
        JOIN ED_Network_Struct s on s.F_Child = i.LINK
        JOIN My_Recursive r ON s.F_Parent = r.link
    )

    IF EXISTS(SELECT n_name FROM My_Recursive r WHERE n_name LIKE '%' + @u_name + '%' AND n_type = @u_type GROUP BY n_name HAVING COUNT(*) > 1)
    BEGIN
        SELECT CONCAT('DELETE DOUBLES for ', @u_type, ' ', @u_name)
        RETURN
    END

    SELECT link, n_type, n_name, F_Parent
    FROM My_Recursive r
    WHERE
        n_name LIKE '%' + @u_name + '%'
        AND n_type = @u_type
    END

SQL Server returns:

Wrong syntax near the If statement.

I was investigating the manual and didn't find what's up. What's wrong with this code?

New to Java. What am I doing wrong? (while-loop with nested if-else) [duplicate]

This question already has an answer here:

I am working on a program using Java and I am having some problems compiling my program. The purpose of the program is to code a while-loop with a nested if-else structure within an if-else structure. (1) There is an error on line 13 that says ".class expected", "illegal start of expression", and "; expected". (2) Am I correctly nesting the if-else structure so far? (3)Are the curly brackets correctly placed?

/**
* @author Sean Ramos
* @version1.0 9/30/2019 1:30PM 
* PURPOSE: To use a while-loop with a nested if-else structure within an if-else structure.
*/
import java.util.Scanner;
public class RamosSLE32 { //Begin class

public static void main(String[] args) { //Begin main()

Scanner input=new Scanner(System.in);
int age=
char tryAgain='Y';
char tryAgain2='Y';
String q1="%nWhat is the password?";
String q2="%nEnter your age: ";

while(Character.toUpperCase(tryAgain1)=='Y'){

 System.out.printf(q1);
 String password=input.nextLine();
 if(password!="MonthyPython")
 { 
   System.out.printf("%nInvalid password!%nDo you want to try again? Y or N.");
   tryAgain=input.nextLine().charAt(0);
 }
 else
 { if(password=="MonthyPython")
 { System.out.printf(q2);
   age=input.nextInt();
 }
 { if(age > 17)
 {
    System.out.printf("%nShangri-La welcomes you to your earthly paradise!%nThank you! Have a nice day!");
 }
 else 
 { if (age <= 17)
 { System.out.printf("%nSorry, NO underaged patrons allowed!%nDo you want to try again? Y or N.");
   tryAgain2=input.nextLine().charAt(0);
 }}}}}
  System.exit(0); 
 } //End main()

 } //End class

dimanche 29 septembre 2019

What do I need to change in the second "if" statement?

I cannot get the second number to be correct. There is something wrong in the "if" statement. Can anyone spot it? It works when I input 2 3 4 or 4 3 2 but not scrambled like 6 -5 4. If I do 6 -5 & 4 then my output is -5 -5 6

import java.util.*; // imported scanner
public class ThreeNumbers{

   public static void main(String[] args){

      Scanner input = new Scanner(System.in);

        // Prompt the user to enter three floating-point numbers
        System.out.print("Enter 3 numbers separated by a space: ");
        int num1 = input.nextInt();
        int num2 = input.nextInt();
        int num3 = input.nextInt();


        // Display inputs in sorted order
        System.out.print("Sorted numbers: ");

        // Find the minimum number input by the user
        if ((num1 < num2) && (num1 < num3)) {
            System.out.print(num1 + " ");
        } else if ((num2 < num1) && (num2 < num3)) {
            System.out.print(num2 + " ");
        } else if ((num3 < num1) && (num3 < num2)) {
            System.out.print(num3 + " ");

        }
        // Find the middle number input by the user
        if ((num1 != num2) && (num1 != num3) && (num1 >= num2) && (num1 <= num2)) {
            System.out.print(num1 + " ");
        } else if ((num2 != num1) && (num2 != num3)) {
            System.out.print(num2 + " ");
        } else if ((num3 != num1) && (num3 <= num2)) {
            System.out.print(num3 + " ");

        }
        // find the maximum number input by the user
        if ((num1 > num2) && (num1 > num3)) {
            System.out.print(num1 + " ");
        } else if ((num2 > num1) && (num2 > num3)) {
            System.out.print(num2 + " ");
        } else if ((num3 > num1) && (num3 > num2)) {
            System.out.print(num3 + " "); 

my if and elif is not working properly how to fix? its only printing the first statement no matter what choice you pick

peso_value = int(input("Enter PESO value:\n"))
print("""
Menu:
[A]Dollar
[B]Yen
[C]Rial
""")
choice = input("choice: ")
if choice == 'A' or 'a':
    print('\nDollar Value:%.2f' % (peso_value / 52.04))
elif choice == "B" or "b":
    print('\nYen Value:%.2f' % (peso_value / .048))
elif choice == "C" or "c":
    print('\nRiyal Value:%.2f' % (peso_value / 0.072))
else:
    print("Invalid Choice")

'''it only prints the dollar value no mattter what choice you pick'''

How to can I set specific image in if condition?

I am non-native English speaker and I am beginner of programming language. I understand that my explanation is not best but I am trying to explain better to people to understand what I am trying to do. So, please be patient with me and please not try to down vote instead of tell me why my explanation is bad. I appreciate your time to read this. Thank you.

I am working on canvas game called coin sorting game which is drag the coins to the correct piggy bank images. I am stuck with if condition right now. In the current state, alert will trigger when any images touch, but I want to trigger alert when specific images touched. For example, when 1yen coin image touched with 1yen piggy bank image then trigger alert otherwise no event occur.

I am wondering if I can set specific images in if condition below...

  if (haveIntersection(obj.getClientRect(), targetRect)) {
  alert("Intersection");
    }

Can I add more conditions to existed if conditions above? If so, how can I add if conditions? I want to add condition is if ichiYenimage === ichiYenpiggyImg than alert ("Intersection"); else { no event}

Please let me know if my explanation is not readable.

Thank you!

Here is full code below...

var stage = new Konva.Stage({
  width: 400,
  height: 200,
  container: 'container'
});
var layer = new Konva.Layer();
stage.add(layer);

layer.on('dragmove', function(e) {
  var target = e.target;
  var targetRect = e.target.getClientRect();
  layer.children.each(function(obj) {
    if (obj === target) {
      return;
    }
    if (haveIntersection(obj.getClientRect(), targetRect)) {
      alert("Intersection");
        }
  });
});

function haveIntersection(r1, r2) {
  return !(
    r2.x > r1.x + r1.width/2 ||
    r2.x + r2.width/2 < r1.x ||
    r2.y > r1.y + r1.height/2 ||
    r2.y + r2.height/2 < r1.y
  );
}

// This will draw the image on the canvas.
function drawImage(source, konvaImage) {
  layer.add(konvaImage);
  var image = new Image();
  image.src = source;
  image.onload = function() {
    konvaImage.image(image);
    layer.draw();
  }
}


//1yen
var ichiYenImg = new Konva.Image({
  x: 20,
  y: 20,
  width: 100,
  height: 100,
  draggable: true
});
var sourceImg1 = "https://illustrain.com/img/work/2016/illustrain09-okane5.png";
drawImage(sourceImg1, ichiYenImg);


var goYenImg = new Konva.Image({
  x: 120,
  y: 20,
  width: 100,
  height: 100,
  draggable: true
});
var sourceImg2 = "https://illustrain.com/img/work/2016/illustrain09-okane7.png";
drawImage(sourceImg2, goYenImg);

//piggy bank 1yen
var ichiYenpiggyImg = new Konva.Image({
  x: 300,
  y: 100,
  width: 100,
  height: 100,
  draggable: false
});
var sourceImg7 = "https://user-images.githubusercontent.com/31402838/63416628-a322b080-c3b4-11e9-96e8-e709ace70ec1.png";
drawImage(sourceImg7, ichiYenpiggyImg);
<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://unpkg.com/konva@4.0.5/konva.min.js"></script>
</head>

<body>
  <div id="stage-parent">
    <div id="container"></div>
  </div>
</body>

</html>

Python, Difference between if and elif

What is the difference beetwen if and elif?

Example code

If statement with elif statement

if x == y:
 print(x)
elif x == "a":
 print(x)

If statement without elif statement

if x ==y:
 print(x)
if x =="a" and x != y:
 print(x)

What's the difference? Because the second if statement used "and" key

Only For Loop, If/Else Statement and Array ONLY. This is the closest that I've gotten. The for loop didn't work, so I took it out for now [on hold]

import java.util.Scanner;
import java.util.ArrayList;

public class Part5 {
    public static void main (String[] args) {

        // Name Array List
        ArrayList <String> name = new ArrayList <String>();
        name.add("Mason");
        name.add("Bubba");
        name.add("Jill");
        name.add("Pat");
        name.add("Jenny");
        name.add("Howard");
        name.add("Buster");

        // Age Array List
        ArrayList <Integer> age = new ArrayList <Integer>();
        age.add(25);
        age.add(44);
        age.add(16);
        age.add(18);
        age.add(21);
        age.add(44);
        age.add(8);

        Scanner user = new Scanner(System.in);

// if I place a loop here, all I get is an empty console. I don't know how to fix it

        System.out.println("Enter a letter to exit the program. Enter an integer to find a list of names " + 
        "(1) equal to, (2) older than, or (3)younger than a certain age: ");
        int i = user.nextInt();

// Originally I used an if-else statement, but again, the program wouldn't work.

        switch (i) {
        case 1: {
            System.out.println("You have chosen number 1. Enter in age for comparison: ");
            int e = user.nextInt();

            if (e == age.get(e)) {
                System.out.println(name.get(e) + ":" + age.get(e));
            }
            else {
                System.out.println("There are no names associated with that age.");
            }

        }
            break;

        case 2 : {
            System.out.println("You have chosen number 2. Enter in age for comarison: ");
            int e = user.nextInt();

            if (e <= age.get(e)) {
                System.out.println(name.get(e) + ":" + age.get(e));
            }

        }
            break;

        case 3: {
            System.out.println("You have chosen number 1. Enter in age for comarison: ");
            int e = user.nextInt();

            if (e >= age.get(e)) {
                System.out.println(name.get(e) + ":" + age.get(e));
            }

        }
            break;

        default: {
            System.out.println("Invalid Entry.");
        }
            break;
        }

        user.close();

    }
}

// Given the following people’s names and their ages, you are asked to write a Java program to finish the following tasks. Write a program to display names and ages based on user questions according to the following requirements. First, you must build the arrays - one for names and one for ages. The data below will be hard coded into the program.

Mason: 25
Bubba: 44
Jill: 16
Pat: 18
Jenny: 21
Howard: 44
Buster: 8

The program will then repeatedly ask questions of the user and provide answers. First find out if the user is interested in a list of names of those who are exactly equal to a certain age (integer values only), older than a certain age, or younger than a certain age. This should be accomplished by asking the user to enter a single character response to a single question. If the user enters an invalid response, output an error message and retreat to the question again. If the user enters the single character “X,” then end the program. Use Scanner rather than JOptionPane for all input and output.

If a valid character is entered for the question, then ask for an age for comparison. Bonus points for error checking in this step (not required) - if you do, indicate via Java code comments. Display on the console all the names and ages that satisfy the question. Display each on a separate line using the format “name : age.” If no name satisfy the question, indicate in a message to the console. After this step, always retreat to asking a new question – do not terminate the program.

using list values in an if statement to compare with a string

I have this list and string

list_var=(['4 3/4','6','6 3/4'])
string_var='there are 6 inches of cement inside'

i want to check through and find if any of the elements of the list is in the string

if list_var in strin_var (wont work of course due to the fact its a list but this is what i want to achieve is to compare all of the values and if any match return true)

i tried using any function but this not seem to work i would also like to achieve this without using loops as the code i will be using this in contains extracting data from a lot of files so execution speed is an issue

Why does DELETE command doesn't work after INSERT is done?

I fetched this data from table1 into form input value and tried to INSERT to table2. Then I want it to be deleted from table1. But the DELETE doesn't work after INSERT is done. Is there any way to do same without IF? How? See I tried this:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lock_access";

$conn = mysqli_connect($servername, $username, $password);

if(!$conn)
{ echo 'Not connected'; 
}
if(!mysqli_select_db($conn,$dbname))
{
    echo 'DB Not selected'; }

$fn = $_POST['full_name'];
$fln = $_POST['flatno'];
$gn = $_POST['gender'];
$pcn = $_POST['pcardno'];

$sql = "INSERT INTO approved (full_name, flat_number, gender, new_card) VALUES('$fn', '$fln', '$gn', '$pcn')";


if(mysqli_query($conn, $sql))
{

     DELETE FROM lock_access WHERE full_name='$fn';
}

else {
     echo "Application not received. ";
}

?>

reproducing an Excel IF statement in Postgresql

I have a table that has the following column headers: customer id, Stage1, Stage2, Stage3 xxxxxx, 21-01-2019, 22-01-2019, 23-01-2019 yyyyyy, 22-02-2019, , 24-02-2019

I want to create a forth column, Stage 2 New, that if the relevant cell in Stage 2 is blank, assigns the date in Stage 1, in excel it will be: IF(C3=" ", B3, C3).

What is the SQL code I can use to achieve this?

Many thanks in dvance!

How to save an element from a list as a whole after an if-statement

Hello stackoverflow community :-)

I want to save elements of a list as a whole in a new list.

My new task is to transform nested lists into a flat one. My plan was to take out the elements of each list and save them into a variable. And in the end to put the variables together, so that there is just a flat list at the end.

I have two problems:

1) The index-3 element ('99999') isn't saved as a whole in the list of the new variable. This problem is the topic of this question.

2) I can not separate the nested list [66, 77, 88] from the higher list ['4', '5',[]], but this is not the topic of this question

So here is the code of the nested list and of my if-statement:

nested_list = ['1', '2', '3', '99999',['4', '5',[66, 77, 88]]]
y = []
for i in nested_list:
    if type(i) != (list or tuple):
        y += i
print(y)

I want the index=3 element (the string '99999') be saved in the variable y as a whole string and not splitted into the single parts '9', '9', '9', '9', '9'

I want:

print(y)
['1', '2', '3', '99999']

I get:

print(y)
['1', '2', '3', '9', '9', '9', '9', '9']

I can't solve the problem with saving into a string (y = ' '), because than I get the result:

print(y)
12399999

and if I would transform the string to a list

y = list(y)

I get the same unwanted result

['1', '2', '3', '9', '9', '9', '9', '9']

I think the solution lies in the action code after the if-statement

y += i

Is there a command, which takes the whole element into y? I tried y += sum(i) but of course this didn't work, because

1) it adds up all numbers like int, floats, etc.., not strings

2) I don't need to add 9+9+9+9+9=45, but I need just the whole string in my new list y.

I've searched a lot on Google for such a command, but didn't found something that would help me.

I have to say, that I am a code Newbee and learning Python for just 2 weeks.

Best regards Matthias

Order posts from the smallest to the largest within an if loop

I am making an event booking, obviously the events can be different and so I created taxonomies to associate the events with the latter.

Being events as properties of the post they have enclosed within a meta_value that corresponds to the meta key:metakey_AMC_data the date of the event.

It made me a little mad to order the events from the smallest to the largest on the taxonomy page but in the end I did it.

$v_args = array(
    'post_type'     =>  array('eventi-suite'), // your CPT
    'posts_per_page'    => -1,
    'orderby' => 'metakey_AMC_data',
    'meta_query' => array(
        array
        (
            'key'     => 'metakey_AMC_data',
            'compare'   => '>=',
        ),
    ),
    'tax_query' => array(
        array(
            'taxonomy' => 'categoria',
            'field' => 'slug',
            'terms' => 'aperitivi'
        )
    )

);
$vehicleSearchQuery = new WP_Query( $v_args );

// Open this line to Debug what's query WP has just run
//print_r($vehicleSearchQuery->request);

// Show the results
if( $vehicleSearchQuery->have_posts() ) :
    while( $vehicleSearchQuery->have_posts() ) : $vehicleSearchQuery->the_post();
        ?>
        <?php
        /*CONVERTIRE LA DATA DEGLI EVENTI SALVATA NEL DB DA DD-MM-YY A Y-M-D*/
        $var = get_post_meta(get_the_ID(),'metakey_AMC_data',true);
        $date = str_replace('/', '-', $var);
        $data_eventi = date('Y-m-d', strtotime($date));

        /*PRENDERE LA DATA CORRENTE IN FORMATO Y-m-d DIRETTAMENTE DA MYSQL*/
        $data_mysql = date( 'Y-m-d', current_time( 'timestamp', 0 ) );

        if ($data_eventi <= $data_mysql): ?>
        <!-- NON MOSTRARE NULLA -->
        <?php else: ?>
            <div style="padding-top: 25px;" class="col-md-4"><!-- Card -->
                <?php include('content/home_page/card.php');  ?>
            </div>
        <?php endif; ?>

        <?php
    endwhile;
else :
    ?><div style="text-align: center;padding-top: 25px;" class="col-md-12"><?php
    _e( 'Ci dispiace, non abbiamo nessun evento da proporti nella data che hai immesso. <br> Prova con un altra data.', 'textdomain' );
    ?></div><?php
endif;
wp_reset_postdata();
?>

after performing the conversion of the date in the form of a string inside the db, and taking the current date mysql, I implemented an if loop, where I tell it that if the event is less than the current date it should not be shown if it is greater it must to be shown.

Where's my problem?

The fact is that I have 4 events with different dates:

  • 09/30/2019
  • 09/30/2019
  • 10/08/2019
  • 10/10/2019

that should come out in this order, instead they come out in this other

  • 09/30/2019
  • 09/30/2019
  • 10/10/2019
  • 10/08/2019

how do I place a sort from the smallest to the largest within my if loop, to solve this?

What formula or method could I go to subtract amounts from values in a range using a table

I have a master sheet with values of what I would sell for. I want to create a formula or rules where I can subtract commission based on the value of the cell. I want to be able to edit from the table only so I don't have to mess around with hundreds of cells formulas when things change. I also don't want to just take commission by percentage. I know how to link the cells. I want a formula that will look in the table and say hey its between the two values so ill extract this amount of commission. I have attached a picture of an example of the rules table.

I've tried doing IF statements and ran into too many arguments issues.

I expect the formula to look in my table and take out the proper commission beside it.

Sample Table

Googlescript 'if' question - do only one of two tasks

I have 'else if' statements and I need it to be called only if the previous 'if' does not execute. First 'if' (check status) work perfect, second work to, but the 'else if' is done every time because there are different types in the table (A, B, C e.t.c) Here is my code:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetName');
  var data = sheet.getRange(2,1,sheet.getLastRow(),2).getValues();
  var nextRow = SpreadsheetApp.getActiveSheet().getDataRange().getLastRow()+1;

  for (var i=0; i<data.length; i++){
    var row = data[i];
    var type = row[0];
    var status = row[1];

//check it always     
    if (status != 'close'){

//check first and if it's true don't do 'else if'      
       if (type == 'A') {
         sheet.getRange(i+2,2).setValue('close')
       }

//this should only be called if the previous 'if' is not true      
      else if (type != 'A' && type != ''){
        var values = [['A','open']];
        sheet.getRange("A"+nextRow+":B"+nextRow).setValues(values); 
      }
    }
  }
}

Consolidating multiple if statements in Java

I have the following code which relies on multiple different if-statements. I am making a Cribbage score counting app for android. The code shown is just for team Blue but whatever I end up with for team Blue will be used for teams red and green as well. What I have right now works, but it's bulky. I'm new to java and was hoping for some pointers on best practices about consolidating the code to it is easier to read and maintain.

    if(blueTeamScore >= ENDGAMESCORE) {
        String baseVictoryText = "Blue Team has won!";
        TextView winningTeamTextView = (TextView) findViewById(R.id.winningTeam);

        if(hasThreePlayer == false) {
            winningTeamTextView.setText(baseVictoryText);
            if (hasSkunk == true) {
                if (redTeamScore <= 90) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red Team got Skunked");
                }
            }
        }
        if(hasThreePlayer == true) {
            winningTeamTextView.setText(baseVictoryText);
            if (hasSkunk == true) {
                if ((redTeamScore <= 90) && (greenTeamScore <= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red and Green Teams got Skunked");
                }
                if ((redTeamScore <= 90) && (greenTeamScore >= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Red Team got Skunked");
                }
                if ((redTeamScore >= 90) && (greenTeamScore <= 90)) {
                    winningTeamTextView.setText(baseVictoryText + "\nAnd Green Team got Skunked");
                }
            }
        }
    }

I know Boolean variables can't be used in switch statements (too bad) but is there something else similar that would help concentrate my code?

samedi 28 septembre 2019

I was trying to check if an input is equal to a character in a string

I tried to find out if an input is a part of the string

if my_input==astring[i]:

However, python returns me with an error:

Traceback (most recent call last):
  File "/home/user/Desktop/Programs/test.py", line 7, in <module>
    if my_input==astring[i]:
builtins.TypeError: string indices must be integers

How should I fix this?

How to make my if statements run again as if-else statement runs?

Currently if someone inputs a date that is out of bounds it will result in the else statement running which is all fine and dandy, but I would like it so if-else statement were to run, it would rerun the if statements. I don't really have a solid idea on what I should do so any help would be appreciated!

import java.util.Scanner;

public class Horoscope {
    public Horoscope() {
        Scanner sc = new Scanner(System.in);
        String output = "Please enter a valid date";
        int month;
        int day;

        System.out.println("What is your month of birth?");
        month = sc.nextInt();
        System.out.println("What is your day of birth?");
        day = sc.nextInt();

        if((month == 3 && day >= 20 && day <= 31) || (month == 4 && day >= 1 && day <= 19)) {
            System.out.println("You are an Aries");
        }
        else if((month == 4 && day >= 20 && day <= 30) || (month == 5 && day >= 1 && day <= 20)) {
            System.out.println("You are a Taurus");
        }
        else if((month == 5 && day >= 21 && day <= 31) || (month == 6 && day >= 1 && day <= 20)) {
            System.out.println("You are a Gemini");
        }
        else if((month == 6 && day >= 21 && day <= 30) || (month == 7 && day >= 1 && day <= 22)) {
            System.out.println("You are a Cancer");
        }
        else if((month == 7 && day >= 23 && day <= 31) || (month == 8 && day >= 1 && day <= 22)) {
            System.out.println("You are a Leo");
        }
        else if((month == 8 && day >= 23 && day <= 31) || (month == 9 && day >= 1 && day <= 22)) {
            System.out.println("You are a Virgo");
        }
        else if((month == 9 && day >= 23 && day <= 30) || (month == 10 && day >= 1 && day <= 22)) {
            System.out.println("You are a Libra");
        }
        else if((month == 10 && day >= 23 && day <= 30) || (month == 11 && day >= 1 && day <= 21)) {
            System.out.println("You are a Scorpio");
        }
        else if((month == 11 && day >= 22 && day <= 31) || (month == 12 && day >= 1 && day <= 21)) {
            System.out.println("You are a Sagittarius");
        }
        else if((month == 12 && day >= 22 && day <= 31) || (month == 1 && day >= 1 && day <= 19)) {
            System.out.println("You are a Capricorn");
        }
        else if((month == 1 && day >= 20 && day <= 31) || (month == 2 && day >= 1 && day <= 18)) {
            System.out.println("You are an Aquarius");
        }
        else if((month == 2 && day >= 19 && day <= 29) || (month == 3 && day >= 1 && day <= 20)) {
            System.out.println("You are a Pisces");
        }
        else {
        System.out.println(output);
        }
    }
}

Unreachable code from if-statement about String checks

For some reason I get an error that the line currentUser = gar.getAccount(userN); is unreachable and yet it shouldn't be. Garage.getAccount() is just a retrieval from a Hashmap. Both if statements don't counter each other and I've tried adding else statements but no matter what it says the line is unreachable.

package main;

import java.util.Scanner;

public class Main {

    private static Scanner input;
    private static Garage gar;
    private static Attendant currentUser;
    private static boolean isManager;

    public static void main(String[] args) {
        input = new Scanner(System.in);
        gar = new Garage(10, 80, 10);
        currentUser = null;
        while (currentUser == null)
            logIn();
    }

    public static void logIn() {
        System.out.println("Enter username: ");
        String userN = input.nextLine();
        System.out.println("Enter password:");
        String userP = input.nextLine();
        //if no username, go back
        if(gar.getAccount(userN) == null) { 
            error("Incorrect username");
            return;
        } 
        if(gar.getAccount(userN).getPassword().equals(userP) == false); { //if entered password doesn't match
            error("Incorrect password");
            return;
        } 
        currentUser = gar.getAccount(userN);
        return;
    }

    //update to throw error pop-up later
    public static void error(String er) { System.out.println(er); }
}

Haskell trying to implement null function on if

So basically i have a question for ym homework that says: "Create a function that checks if a list is not empty using prelude functions" I saw the null function and i wanted to use it and print the message. So i tried the following:

notEmpty :: [Int] -> [Char]
notEmpty [x] = if (null[x]) then "False" else "True"

If i call notEmpty [ ], it gives me this error: Non.Exhaustive patterns in function notEmpty after several learning i came up with this:

notEmpty :: [Int] -> [Char]
notEmpty [] = "False"
notEmpty [x] = if (null[x])then "False" else "True"

but after this, i tried the following input: notEmpty[1,2] and it gave me the same error.

My question is, when i run null [1,2] it gives me False, so what am i doing wrong?

Turn this into an if / else statement

When an item is chosen on my site, it opens a details page. This is the top of the details page above the html tags:

<?php require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$recordID = $_GET['recordID'];
$query_Master_details = "SELECT * FROM Master_List WHERE Master_List.Master_Id = $recordID";
$Master_details = mysqli_query($conn, $query_Master_details) or die(mysqli_error());
$row_Master_details = mysqli_fetch_assoc($Master_details);
$totalRows_Master_details = mysqli_num_rows($Master_details);
?>

This is the code that makes the body of the page:

<div class="container2">
    <div class="category"><h2><?php echo $row_Master_details['Name']; ?></h2></div>
    <p><?php echo $row_Master_details['Name']; ?></p>
    <p><img src="img/<?php echo $row_Master_details['Img']; ?>" /></p>
    <p><?php echo $row_Master_details['Code']; ?></p>
    <p><?php echo $row_Master_details['Length']; ?> Characters</p>
    <?php
    mysqli_free_result($Master_details);
    ?>
<!-- end .container2 --></div>

What I would like to do is create an if/else statement that will look at the Style_ID of the selected item and determine if the number is > 3. If it is, I want it to choose an item that has a Style_Id of 1, 2, or 3 and the same Length as the item chosen and return a random row in the layout above, skip a few lines and then display the information for the selected item in the layout above. Else if it is < or = 3, then I need it to just display as above.

I have tried using:

    <?php
    If (Style_ID > 3) {
        echo 'Test';
    }Else {
    <div class="category"><h2><?php echo $row_Master_details['Name']; ?></h2></div>
    <p><?php echo $row_Master_details['Name']; ?></p>
    <p><img src="img/<?php echo $row_Master_details['Img']; ?>" /></p>
    <p><?php echo $row_Master_details['Code']; ?></p>
    <p><?php echo $row_Master_details['Length']; ?> Characters</p>
    }
    ?>
    <?php
    mysqli_free_result($Master_details);
    ?>

But it doesn't work and has syntax errors. How can I create this if/else statement?

Note: I would appreciate being able to get one setup for all of it, but if not just fixing this part would be a big help right now.

Why does my program think that two completely different if statements are the same?

I am trying to create a program that calculates the difference between two dates (this includes dates with different years). As such, I have to account for leap years. If both dates are leap years or if the first date is a leap year, the program works fine. However, the two if statements below don't seem to work. The first if statement is meant to figure out the difference if the starting date is a non-leap year and the end date is a leap year. The second if statement is meant to determine the difference if both dates are non-leap years. Despite the clear difference, my program seems to think that these statements are logically equivalent.

To solve this problem, I have tried many things. First, in my code, I have placed printf statements to tell me which option is running for each input. For instance, the first statement prints out "the commanding officer" and the second prints out "regular year 2" if it is the correct one. Also, I have attempted to change the bracket notation in the affected if statements. Here are my lines of code:

else if ((yyyy1 % 4 != 0) || ( yyyy1 % 100 == 0 ) && ( yyyy1 % 400 != 0 ) && (yyyy2 % 4 == 0) && ( yyyy2 % 100 != 0 ) && ( yyyy2 % 400 == 0 ) && (argc == 3)) 
startingDate = dd1 + startdayofYear[mm1-1];
endDate = dd2 + leapenddayofYear[mm2-1];
dateDifference = endDate - startingDate;
yearDifference = yyyy2 - yyyy1;
leapBetween = (yyyy2-yyyy1) / 4;
difference = 365 * yearDifference + dateDifference + leapBetween;
printf("%d", difference);
printf("the commanding officer");
}`


`else if ((yyyy1 % 4 != 0) || ( yyyy1 % 100 == 0 ) && ( yyyy1 % 400 != 0 ) && (yyyy2 % 4 != 0) && ( yyyy2 % 100 == 0 ) && ( yyyy2 % 400 == 0 ) && (argc == 3)) {
startingDate = dd1 + startdayofYear[mm1-1];
endDate = dd2 + enddayofYear[mm2-1];
dateDifference = endDate - startingDate;
yearDifference = yyyy2 - yyyy1;
difference = 365 * yearDifference + dateDifference;
printf("%d", difference);
printf("regular year 2");
}`

Currently using C# and having trouble looping

I am currently having trouble looping the following code so that the else part asks the question again.

        String name, wtd, act, trav;

        Console.WriteLine("What is your name?");
        name = Console.ReadLine();

        Console.WriteLine("Hello {0}, What do you want to do today?", name);
        Console.WriteLine("1) Action\n2) Chilling\n3) Danger\n4) Good Food\n");

        int result, ppl;


        result = Convert.ToInt32(Console.ReadLine());


        if (result == 1)
        {
            wtd = "action";
            act = "Stock Car Racing";
        }
        else if (result == 2)
        {
            wtd = "chilling";
            act = "Hiking";
        }
        else if (result == 3)
        {
            wtd = "danger";
            act = "Skydiving";
        }
        else if (result == 4)
        {
            wtd = "good food";
            act = "to Taco Bell";
        }
        else
        {
            wtd = "";
            act = "";
            Console.WriteLine("I do not understand. Please select again");

        }

Console.WriteLine("Okay. If you are in the mood for " + wtd + ", then you should go " + act + "and travel in " + trav +".");

*The rest of the code works fine. trav variable works fine

I have tried using while loop, but it always comes back with errors, or does not run how i want it to. One of the most common errors when using the while loop are "use of unassigned local variable wtd" and "use of unassigned local variable act". These errors happen at the last Console.WriteLine part of the code.

I also need the variables to be defined based on used input and would like it to loop if there is any invalid input, like any other value besides the ones listed (1,2,3,4).

Picture appears after a choice from prompt has been made w/ JS

After the user has entered in an appropriate choice, I need to use a conditional statement that compares the input to my choices, and then render an image on the web page. I know somehow I have to use the CSS display, and possibly a if/then statement but I'm not entirely sure how or where. So far, I have this in my javascript. I'm not sure what I should use so that if the user inputs 'red' that a picture would appear (it's going to be Hogwarts related). Any tips in the right direction?

function myFunction() {
    var text;
  var favColor = prompt("What color appeals most to you out of red, green, blue, or yellow?", "Let the game begin");
  switch(favColor.toLowerCase()) {
    case "blue":
      text = "Sounds like you like to think";
      break;
    case "red":
      text = "Feeling bold?";
      break;
    case "green":
      text = "Really? Interesting choice";
      break;
      case "yellow":
        text = "How very clever of you!"
          break;
    default:
      text = "C'mon! Pick one!";
  }
  document.getElementById("demo").innerHTML = text;
}

How to compare text from external .txt file to a string

I have achieved returning the text from external text file by using this method here

FileReader reader = new FileReader("C:\\Users\\boung\\Desktop\\usernames.txt");

int character;

while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();

This method prints

username1

But now what I want to do is, I want to take the text that was returned from the text file and compare it to a String that was already set in the program. Like this:

        String S = "username1";

        FileReader reader = new FileReader("C:\\Users\\boung\\Desktop\\usernames.txt");
        int character;

        while ((character = reader.read()) != -1) {
            System.out.print((char) character);
        }
        reader.close();

        if (character.contains(S)) {
        System.out.println("username1 found");


    }

But I cant compare character and S.

I need to be able to stringify all of the text returned from the .txt file and check if the file contains a certain string im looking for. Can anyone help?

How can I combine these && if conditions in bash?

I want to write a bash script that takes in marks of 5 subjects and the marks cannot be greater than 100. How can I avoid typing -le 100 each time.

 while true
do
echo "enter marks of 5 subjects"
read m1 m2 m3 m4 m5
if [ $m1 -le 100 ] && [ $m2 -le 100 ] && [ $m3 -le 100 ] && [ $m4 -le 100 ] && [ $m5 -le 100 ]
then
        break
else
 echo "marks cannot be more than 100"
fi
done

Conditionally Text in SwiftUI depending on Array value

I want make placeholder custom style so i try to use the method of Mojtaba Hosseini in SwiftUI. How to change the placeholder color of the TextField?

if text.isEmpty {
            Text("Placeholder")
                .foregroundColor(.red)
        }

but in my case, I use a foreach with a Array for make a list of Textfield and Display or not the Text for simulate the custom placeholder.

          ForEach(self.ListeEquip.indices, id: \.self) { item in
     ForEach(self.ListeJoueurs[item].indices, id: \.self){idx in
// if self.ListeJoueurs[O][O] work
        if self.ListeJoueurs[item][index].isEmpty {
                                    Text("Placeholder")
                                        .foregroundColor(.red)
                                }
    }
    }

How I can use dynamic conditional with a foreach ?

Show a Messagebox if program is ran for the first time in C#

When a user runs the program for the first time I want a message box to show up.

I was thinking of something like this:

        private void Form1_Load(object sender, EventArgs e)
    {
        if(firstTime)
        {
            MessageBox.Show("Welcome");
        }

How could I get my program to display a message box when a user launches the program for the first time in c#?

IF function in Google Sheets

I need a function in a cell to say: Blank if Tab 1 A2 cell is blank and Tab 2 A2 is blank. If Tab 1 A2 isn't blank and Tab 2 is blank the cell says "Pending" and if Tab 1 A2 isn't blank and Tab 2 A2 isn't blank then the cell = Tab 2 A2.

I'm working on a Google Sheets that need to reference other cells across 2 tabs.

Here's the function I have at the moment:

=IF(A13<>""&'Import Processing'!A13<>"",'Import Processing'!A13,IF(A13<>"","Pending"))"))

At the moment it's just showing whatever is in Tab 2 A2, and not regarding if Tab 1 A2 is blank or not.

How To Limit Column Values Retrieved From Another Column

I am trying to get a column in Google Sheets to display the values produced by another column but if they are greater than 10, I want it to just display 10 for that cell but if the cell would contain a number less than 10 that cell within the column still contains the original value.

I tried a query with an IF statement but I'll admit I'm too sure how this works

=query(D:D,"select D label D 'Your total points'" & IF("D">10,10,"D"),1)

I expected a new column to list all the values in column D unless they were greater than 10. If they were greater than 10, I expected the cell to contain the value 10 instead of the original value of the corresponding cell in column D.

Instead I get the following error:

Unable to parse query string for Function QUERY parameter 2: PARSE_ERROR: Encountered " "10 "" at line 1, column 37. Was expecting one of: "format" ... "options" ... "," ...

My Python IF Statement is not working and it should be, I have no idea why not

I'm making a project on python and this IF statement is not executing the required response even tho the two values are exactly the same. songs[random_number] and user_guess have the same values Please help, I have tried everything and made sure the two variables are IDENTICAL but it is still not working. It should be printing out 'WELL DONE' but is not. Thanks Jack

if songs[random_number] == user_guess:
        print("Well Done, you have guessed correctly!")
        guess_counter = guess_counter + 1
else:
     guess_counter = guess_counter + 1

truth tables in php with more then 3 variable

Hi StackOverflow people.

if i have 3 variable out side of the loop called :

 $atr
 $ber
 $cdr

Another system will provide 2 option value for this 3 variable: Empty or not empty.

and other 3 variables inside the loop: the value for each variable come from Another system and depend on $i every loop will get different value

$aa 
$bb 
$cc

now my code:

function SelectAll2()
{

$arrArraySize = 283;

$atr =  Empty or not empty.;
$ber =  Empty or not empty.; 
$cdr =  Empty or not empty.; 


if($atr=="" && $ber=="" && $cdr==""){ represent 0 0 0
  return 1;
}
elseif($atr=="" && $ber=="" && $cdr!=""){
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if( $cdr==$cc){ 
    return 1;
    }
  }
}elseif($atr=="" && $ber!="" && $cdr==""){  represent 0 1 0
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $bb = value come from Another system and depend on $i every loop will get diffrent value
    if($ber==$bb){ 
    return 1;
    }
  }  
}elseif($atr!="" && $ber=="" && $cdr==""){  represent 1 0 0
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $aa = value come from Another system and depend on $i every loop will get diffrent value
    if($atr==$aa){ 
    return 1;
    }
  } 
}elseif($atr=="" && $ber!="" && $cdr!=""){   represent 0 1 1
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $bb = value come from Another system and depend on $i every loop will get diffrent value
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if($ber==$bb && $cdr==$cc){ 
    return 1;
    }
  } 
}elseif($atr!="" && $ber=="" && $cdr!=""){   represent 1 0 1
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $aa = value come from Another system and depend on $i every loop will get diffrent value
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if($atr==$aa && $cdr==$cc){ 
    return 1;
    }
  } 
}elseif($atr!="" && $ber!="" && $cdr==""){  represent 1 1 0
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $aa = value come from Another system and depend on $i every loop will get diffrent value
  $bb = value come from Another system and depend on $i every loop will get diffrent value
    if($atr==$aa && $ber==$bb){ 
    return 1;
    }
  } 
}else{     represent 1 1 1
  for ($i=1; $i<$arrArraySize; $i++)
  { 
  $aa = value come from Another system and depend on $i every loop will get diffrent value
  $bb = value come from Another system and depend on $i every loop will get diffrent value
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if($cdr==$cc && $atr==$aa && $ber==$bb){
      return 1;
    } 
  }
}
}

there is a way to write this code more effectively?

because it's messy and it's for only 3 outside loop variable ($atr,$ber,$cdr) and 3 inside loop variable ($aa,$bb,$cc)

and i need this for 4 variable and even 6. if its 6, for example, I can add other 3 outside variable ($atr,$ber,$cdr,$fdsf,$tre,$dsds) and other 3 inside variable ($aa,$bb,$cc,$dd,&ee,$ff)

thanks!

How can I filter out a value above 100 so that it doesn't puts it in the sum

The program asks for input of the speed, when the speed is above 100 it should not include that value in the calculation of the average speed. How can I do that?

I have put a i--; in the else if where it says else if(speed > 100). It repeats the question, but doesn't remove the value that is bigger than 100.

#include <stdio.h>




int main(){




int i;

double speed, sum = 0.0;

float average; 




for( i = 0; i < 10; i ++ ){ // asks 10 times the printf




printf("%d Enter speed: ", i);

scanf("%lf",&speed); // saves the input speed

    sum += speed; // sum = sum + speed; 




// decides which gear to use



 if (speed == 0){
    printf("gear N\n");

}else if (speed < 0 ){
    printf("gear R\n");

}else if(speed <= 10.0){
    printf("gear 1\n");

}else if (speed <= 30.0){
    printf("gear 2\n");

}else if (speed <= 60.0){
    printf("gear 3\n");

}else if (speed <= 80.0){
    printf("gear 4\n");

}else if (speed <= 100.0){
    printf("gear 5\n");

}elseif (speed > 100 ){ // when input higher than 100 dont save the input and ask again
    printf("max speed 100 km/h\n");

     i--;  
}else 
    printf("Error!\n");


}


average = sum/i; // average calculation

  printf("average speed = %.2lf km/h", average); // prints out the average


return(0);

}

When I put 200 it should remove the value and ask again. What I'm getting when I put 200 it asks again but uses the 200 to calculate the average.

Avoid a lot of conditions inside an If Statement

I have an if statement like this

if(check1 && check2 && check3 && check4 && check5 && check7 && check8 && check9 && check10 && check11 && check12 && check13)

This if statement includes lots of conditions and it is not readable.How can i avoid this situation? Is there any pipeline pattern for if conditions?

at first if method works, after quite some weeks it does not work and show errors

Im very much a beginner on programming, i have been using netbeans11.1 for some quite a while now have the latest java sdk, the first time i make programs it just look like the same as taught at school (btw im practicing at home with my laptop) but after like 1 month and going to make another activity, the if method always show "incompatible type: int cannot be converted to boolean. im doing just the same syntax taught in school, so im confused why this is happening. and on making new project the java folder is not on the main list instead it has now java with maven, i dont know the difference but im really confused especially being a beginner` Scanner input = new Scanner(System.in);

    int in1, in2, out;

       System.out.print("Enter first number: ");
       in1 = input.nextInt();

       System.out.print("Enter second number: ");
       in2 = input.nextInt();

       out = in1 +in2;

       System.out.println("The anwer is:" + out);

       if (out % 2) {
           System.out.println("The answer is an even number");
       }
       else
           System.out.println("The answer is an odd number");

error in if method`

generating truth tables in php with position

i need to write code that generate truth table position. (php code)

for example:

result      a b c
  -         0 0 0 
c -         0 0 1 
b -         0 1 0 
cb -        0 1 1 
a -         1 0 0 
ca -        1 0 1 
ba -        1 1 0 
cba -       1 1 1 

i found this code (in java)

public class TruthTable {
    private static void printTruthTable(int n) {
        int rows = (int) Math.pow(2,n);

        for (int i=0; i<rows; i++) {
            for (int j=n-1; j>=0; j--) {
                System.out.print((i/(int) Math.pow(2, j))%2 + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        printTruthTable(3); //enter any natural int
    }
}

but i need the postion of the 1 and be able to generating TruthTable of 1,2,3...etc.

Java, creating a conditional statement that sends a message if none of the element's name dont match with input?

I apologize in advance if the information is lacking, this is new to me!

So the assignments says; there is a Hotel for pets (dogs, cats and snakes) and the program is supposed to print out how much food and what type of food they are supposed to eat. User writes the name of a pet and it should print which it does.

What I don't understand is how to write a conditional statement that says if NONE of the element's name match input, write "We have no pets with the name (input) at our hotel".

Reason why I got this problem is because I can't reach any elements unless I create a foreach-loop and I don't want a message to pop up for every element just after loop ends.

import javax.swing.*;

public class Main {

public static void main(String[] args) {

    Dog d1 = null;
    Dog d2 = null;
    Cat c1 = null;
    Cat c2 = null;
    Snake s1 = null;

    try {
        d1 = new Dog("Sixten", 5);
        d2 = new Dog("Dogge", 10);
        c1 = new Cat("Venus", 5);
        c2 = new Cat("Ove", 3);
        s1 = new Snake("Hypno", 1);
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
        System.exit(0);
    }

    Hotel h1 = new Hotel();
    h1.addPet(d1);
    h1.addPet(d2);
    h1.addPet(c1);
    h1.addPet(c2);
    h1.addPet(s1);

    h1.getPets(); // gets the list with all the pets

    while (true) {
        String input = JOptionPane.showInputDialog("What pet(name of pet) needs feeding?");
        if (input == null){
            System.exit(0);
            break;
        }
        else if(input.equals("")){
            JOptionPane.showMessageDialog(null, "Invalid input!");

        }// HERE IS WHERE I WANT THE STATEMENT
        else if(**Statement that says if input isn't equal to any of the animal's name**){

        }
        else{
            input = input.toLowerCase();

            for(Pet pet: h1.getPets()){

                String text1 = String.format("%s%10s%10s\n", "Namn:", "Mått:", "Sort:");
                String text2 = String.format("%s%10.2f%16s", pet.getName(), pet.measureFood(), pet.getFoodName());
                String text3 = "---------------------------------------\n";
                text1 = text1 + text3 + text2;


                if (pet.getName().toLowerCase().equals(input)) {
                    JOptionPane.showMessageDialog(null,text1);
                    break;
                }
            }


        }
    }

}

}

How to get keys and values from dictionary python

I have my dictionary as per below my_dict = {4: 8, 3: 11, 4: 10, 5: 10, 8: 5, 9: 5, 10: 10, 5: 2}

I am trying to figure out how to get a sorted list when key == value and also when itinerating the value becomes the key. The result then is

[[2,5,4,8],[10]]

Any ideas?

my if else function is not working correctly, how do i fix it? python

i'm just wondering why this doesn't work, when i say "n" or "no" for the input if works fine but when i say "y" or "yes" for the input it just does the same thing as for "no". everything else in the program runs perfectly apart from this. i have absolutely no clue as to why this is happening.

def restart():
    replay = input("Do you want to restart? (Y/N): ")
    if replay.lower() == "n" or "no":
        print("exiting")
        sys.exit()
    if replay.lower() == "y" or "yes":
        calc()
    else:
        print("Unknown Command")
        restart()
restart()

Putting multiple variables into a IF statement and loop

I just started my IT studies in France, and they're moving really fast. From the first lesson, I already had to write some codes for homework and I can't seem to get it right.

The task: To print out a table (made of characters, so basically _ and |) on IDLE Python (Python Shell 3.7.4). The user must be asked for the number of rows and columns at the start of the program. The user must be asked if they wish to restart the program or not.

The problem: I have successfully done the first part of the task (printing the table). However I have failed to put in "fail proofs".

Basically I would like to do it that if the user types in something OTHER than a integer at the start of the program, he will be asked to enter only numbers and asked to enter the rows and columns again.

Similarly, at the end of the program, I would like to ask if they would like to restart or not.

  • If they type in Yes, yes, Y, y, I would like it to ask the question about the rows and columns again.

  • If they type in No, no, N, n, I would like it to end the program.

  • If they type something else, be asked to enter Yes/No and have the previous input prompt again

Any help is greatly appreciated!

if __name__ == "__main__":

    o = "Yes"
    while o == "Yes":
        i=0
        x= int(input("Number of columns: "))
        m = x*" _"
        l= "|"+(x*"_|")
        y= int(input("Number of rows : "))
        y=y-1
        print(m)
        for i in range(y+1):
            print(l)
        o=str(input("Would you like to restart? (Yes/No) :"))
        if o == "Yes":
                print("\n" * 49)

        elif o == "":
            print("Please enter Yes or No.")

        else:
            print("See you soon!")

plz help me with this

x = input('enter any character :')
if x >= 'A' and x <= 'Z':
    print('you entered a uppercase letter')
elif x >= 'a' and x <= 'z':
    print('you entered a lowercase letter')
elif x >= '1' and x <= '8':
    print('you entered an integer')
else:
    print('you entered a special character')

when i give input 21,77,11 or any such number it gives the output "you entered an integer" but when i enter any number like 80, 81, 87 (number starting with 8) it displays "you entered a special character".

why i get such output?

vendredi 27 septembre 2019

How do I set up an if statement to use an array of conditionals as input in python

First I check a given condition, as per a normal IF statement. If it is True, I need to scan all files for a single keyword. If it is not True, I need to scan all files for a set of keywords, which will have been supplied.

For my simple working example, rather than scanning file names in a directory, I simply search a string for the keywords.

test1 = "NotKeyWord"
password = "password"
password1 = "password1"
password2 = "password2"
password3 = "password3"

if test1.lower() == "keyword":
    condition = password
else:
    condition = [password1, password2, password3]

f = "password1_password2_password3_jibberish_E=mc2"
if condition in f:
    print("Problem solved")

If the keyword = "keyword" i.e., is singular, then this code works. Fine. However, I would like to make it so that if it is the other case, which requires knowing several keywords to grab the right file, I don't need to resort to explicitly writing out all the words.

For my purposes I could write

if password1 in f and password2 in f and password3 in f:
    print("problem solved")

But I am after a pythonic method, that will hopefully be generic enough to be able to handle an array of keywords that is of unknown length, and thus can't be hard coded.

What is meaning of ['create'] in php when complete line is this if(isset($_POST['create']))

Php programming problem in if-statement when start the php code with if.

Missing element of an array after loop and conditions. Result in an array with 3 elements instead of 4. 4 instead of 5, so on

You could call it a homework problem. I am doing a CodeWar challenge, basically, I get a string of numbers and I am supposed to return maximum and minimum values. I got this close of completing this problem but there is an issue. For example, "1 2 3 4 555" should return "555 1". I know about max and min functions but I don't need this yet.

I created a for loop for every x in a list of given string I made. For example "1 2 3 4 555" changed to list ["1", " ", "2", " ", "3", " ", "4", " ", "5", "5", "5"]. I have nested some if statements to add x or a number in string to new array with a few conditions. ["1", " ", "2", " ", "3", " ", "4", " ", "5", "5", "5"] --> [1, 2, 3, 555]. Instead I get [1, 2, 3]. I have gotten [1, 2, 3, 555] or any array without missing an element, now this.

This is my code. I want [1, 2, 3, 555] instead of [1, 2, 3]. Then I will use max and min functions to get min and max values.

def high_and_low(numbers):

  numbers = numbers

  toList = list(numbers)
  print(toList)

  newList = []
  string = ''

  for x in toList:
    if x != ' ': #number
      string += x
      print(string)
    else: #elif x == ' ': #anything that's not a number.  Space for example
      newList.append(int(string)) #we 'add' number to new list before space.  Converted number string to integar.

      #then

      string = '' #reset to empty so we can add next number to empty without worrying about adding number we do not need.
    print(newList) #[1,2,3] instead of [1, 2, 3, 555] is what I wanted.  If I called high_and_low("1 2 3 555 3"), I can get [1, 2, 3, 555]

high_and_low("1 2 3 555")  # return "555 1"

Same code without comments:

def high_and_low(numbers):

  numbers = numbers

  toList = list(numbers)
  print(toList)

  newList = []
  string = ''

  for x in toList:
    if x != ' ':
      string += x
      print(string)
    else: #elif x == ' ':
      newList.append(int(string))
      string = ''

    print(newList)

high_and_low("1 2 3 555")  # return "555 1"

I expect the output of [1, 2, 3, 555], but the actual output is [1, 2, 3]. If I called high_and_low("1 2 3 555 3"), I can get [1, 2, 3, 555].

how can i identify policy renewals by different fields

enter image description hereWhat I am trying to do is count the number of renewals with the different sales trees.

In the case of NumberPlate "015ABN", the customer always renews with the same "company" twice renews with "boss 2", but renews with different "sellers" (seller1, seller2)

this is what i tried

data ['renewal'] = (np.where (data.NumberPlate == data.NumberPlate.shift (), 1, np.nan)) This information tells me that there was a renovation that works for me when I only compare two years but I don't know how to take into account the fields of sales trees.

The other problem I have has complicated me a bit is the difference in the dates on which they are renewed. In subtraction, I use it with a data ['difference'] = (np.where (data.NumberPlate == data.NumberPlate.shift (), data.Expedition_Date.diff (), np.nan))

This creates a field with the difference of days but returns the value of "366 days 04: 01: 19.177000000" but I have to subtract a year to be displayed in days. I must subtract 365 days.

I present three different cases each registration. Some customers are loyal to renew with the company, other customers renew with the boss and other customers renew with the seller.

I appreciate if you can help me with this

seller seller's boss Company NumberPlate Expedition_Date effective_date year difference renewal Company "Renewal seller's boss" "Renewal seller" Seller 1 Boss 1 Global Company 015ABN 2015-05-14 08:37:48.000 2015-05-15 08:37:48.000 2015 0 el mismo dia 1 1 1 Seller 1 Boss 2 Global Company 015ABN 2016-05-13 12:39:07.177 2016-05-15 08:37:48.000 2016 2 dias antes 2 1 1 Seller 2 Boss 2 Global Company 015ABN 2017-05-12 17:01:39.900 2017-05-15 08:37:48.000 2017 3 dias antes 3 2 1 Seller 1 Boss 1 Global Company 016ZYX 2015-05-15 08:37:48.000 2015-05-15 08:37:48.000 2014 0 1 1 1 Seller 1 Boss 1 Global Company 016ZYX 2016-05-12 12:39:07.177 2016-05-15 12:39:07.177 2015 3 2 2 2 Seller 1 Boss 1 Global Company 016ZYX 2017-05-11 17:01:39.900 2017-05-15 17:01:39.900 2016 4 3 3 3 Seller 1 Boss 1 Global Company 016ZYX 2018-05-14 17:01:39.900 2018-05-15 17:01:39.900 2017 1 4 4 4 Seller 1 Boss 1 Global Company 016ZYX 2019-05-15 17:01:39.900 2019-05-15 17:01:39.900 2018 0 5 5 5 Seller 1 Boss 1 Global Company 025ABC 2015-05-15 08:37:48.000 2015-05-15 08:37:48.000 2014 0 1 1 1 Seller 1 Boss 1 Global Company 025ABC 2016-05-13 12:39:07.177 2016-05-15 12:39:07.177 2015 2 2 2 2 Seller 2 Boss 1 Global Company 025ABC 2017-05-10 17:01:39.900 2017-05-15 17:01:39.900 2016 5 3 3 1 Seller 1 Boss 1 Global Company 2 025ABC 2018-05-14 17:01:39.900 2018-05-15 17:01:39.900 2017 4 1 1 1 Seller 1 Boss 1 Global Company 2 025ABC 2019-05-15 17:01:39.900 2019-05-15 17:01:39.900 2018 0 2 2 2

Why does my game ignore my true false statement?

I made a game on pygame. I want the player speed to change once the health reaches a certain point. I have tried a combination of if/else statements and true/false statements - the speed still won't change. Here is the relevent code:

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.health = PLAYER_HEALTH
        self.speed = True
        if PLAYER_HEALTH <= 20:
            self.speed == False
        if PLAYER_HEALTH >= 20:
            self.speed == True

    def get_keys(self):
        PLAYER_RUN = 55
        PLAYER_RUNS = 300
        self.rot_speed = 0
        self.vel = vec(0, 0)
        keys = pg.key.get_pressed()
        if keys[pg.K_UP] or keys[pg.K_w]:
            if self.speed == True:
                self.vel = vec(PLAYER_RUNS, 0).rotate(-self.rot)
            else:
                self.vel = vec(PLAYER_RUN, 0).rotate(-self.rot)
        if keys[pg.K_DOWN] or keys[pg.K_s]:
            if self.speed == True:
                self.vel = vec(-PLAYER_RUNS / 2, 0).rotate(-self.rot)
            else:
                self.vel = vec(-PLAYER_RUN / 2, 0).rotate(-self.rot)

This is the code from the file I use to define my sprites. I thought that importing this file with its changes would be enough to make the speed change, but it doesn't work. I even added code to the main loop that dealt with player damage:

if self.player.health <= 20:
    print(CONSTANT[hit_count])
    self.player.speed == False
    self.player.health += CONSTANT.popleft()
    hit_count += 1
    hit.vel = vec(0, 0)
elif self.player.health >= 20
    print(CONSTANT[hit_count])
    self.player.speed == True
    self.player.health += CONSTANT.popleft()

Do you see anything that can explain why the player speed won't switch after the player health hits a certain point?

Strange behavior of PHP value comparison [duplicate]

This question already has an answer here:

I see there are similar questions but they are normally related to integer numbers being compared.

In this case I stumbled upon the following situation.

I have a category id that's taken from a Firebase database and it's a generated ID that looks like this:

-Kk9O6BWamcuUWzkemIr1

Now my thoughts were, well it's obvious it's a string, but as PHP is not very strict with formats I decided to do the following.

if($category_id != 0) { ... }

To explain a little, my default value for when there's no category is 0, so this would be the exception when category_id is not equal to 0.

Then what happened is that when the condition became if('-Kk9O6BWamcuUWzkemIr1' != 0) the script interpreted it as false and never did what was inside of it.

What I did was change the if to if($category_id) but I fear that's a little too broad.

My theory is that if I don't specifically cast -Kk9O6BWamcuUWzkemIr1 as a string, PHP interprets it as a negative number because of the starting - sign. I am not sure if that's what's happening or it's some other thing.

What would be the correct comparison in this case?

Why does C program give wrong output for positive integer?

The below program gives correct result for negative and zero integer, but for positive integer, it gives wrong output:

Enter the value of a : 6
The no is positive
The no is zero

Why?

int main()
{   int a;
    printf("Enter the value of a : ");
    scanf("%d",&a);
    if(a>0)
        printf("The no is positive\n");
    if(a<0)
        printf("The no is negative\n");
    else
       printf("The no is zero\n");
}

Create variable inside/after if statement

In JSON with key "string" and "value":

'Something xxx something' = 10
'Something yyy something' = 20
'Something xxx something' = 30
'Something zzz something' = 40

The flow I want is:

find partial string inside string
if true
get sum of all its matched string's value
if false
return 0

What I tried is

if (strpos($string, 'xxx') == false){
        $value = array_sum(array_column($arrayjson['string'],'value'));
        continue;
    }
echo $value

But, what I am getting is

100
100

Expected result is 40

Check if a Cell Contains any Date using VBA

The run down: Coworkers have been using excel an template to fill out some in-house paperwork. There is a Cell that should have a date. But sometimes there are multiple dates and then they will go in other cells, while the original cell will either be left blank or state to see the other section of the worksheet.

Now: They want to have these dates and subject matter compiled on a weekly basis.

What I'd like to do: Is there a way to use Excel's VBA to create an If Then statement to check if there is a date in the original cell? I can't find the Command or function that only checks for a date (Not a Specific Date).

Thanks in Advanced.

How do i check if the input of the user is empty? And if it is, how will ask for another input?

I've been trying this code but i think the move == " " doesnt work because i've tried to use the move > grid_width or move <0 part only and it works fine. I want to ask the user for another input if he/she didn't type any input but still pressed enter on the input getter.

 while True:
        try:
            move= int(input('Enter your move: '))
        except ValueError:
            print('Please enter a valid input.')
        if move > grid_width or move < 0 or move == " ":
            print('Please enter a valid input.'))
            continue
        break

Batch File with two conditions and a loop

Let us assume my only method of scripting is via a batch file.

I have a batch file with a long list of commands, however, I need to include two contingencies:

  • Needs to be on the domain (we'll use .com for this example)
  • Must have a non typical IP (meaning 192 is not used on the domain, but is used prior to joining and not 169 due to delay in DHCP assignment).

I'd prefer to keep this in the same batch file as the rest of the code. I've tried sewing together some commands, but usually get a syntax error. I am able to make the IP portion work, using %ERRORLEVEL% however, I can only figure out searching for a single IP mask.

PHP - use declared var from foreach in next iteration

I would ask for help with foreach and using vars. There are several conditions in the loop. If value from array is equal to something then happened something and so on. I need to save something to variable and then use it in second iteration of foreach. Then I use array $totals in frontend. I would like to keep order - so first in $totals should be sub_total, then tax and then total.

I tried also define $difference and $tax before foreach but It is getting resetted at every iteration. Now I have done it by using session but I am not sure if it's correct and I would like to do it without session. I hope you uderstand.

Could you help me please? Thank you.

EXAMPLE:

Array ( [0] => Array(
              [code] => sub_total 
              [value] => 3140.5000) 
        [1] => Array ( 
              [code] => tax 
              [value] => 680.2950) 
        [2] => Array ( 
              [code] => total 
              [value] => 3919.7950) 
       ) 
  $totals = array();
foreach($array as $key => $value) {
  if (!in_array($value['code'], array('sub_total', 'tax', 'total')){
       //do something, not important, just showing structure of my code
  } else {
    if($value['code'] == 'total') {
        $text = $value['total'];
      if(round($value['value']) > $value['value']) {
        $difference = round($value['value']) - $value['value'];
        $tax = ($difference*($tax_rate/(100+$tax_rate)));
      }
    }
    if($value['code' == 'tax') {
     $text= $value['value'] + $tax;
     echo $tax; //shows nothing
     echo $text; //shows only 680.2950 ($value['value'] without $tax)
    }
   echo $tax; // Shows $tax correctly
 }
    $totals[] = array(

         'code'  => $value['code'],

         'text'  => $text,

    ); }

how to skip executing several lines with if clause in R

how to skip executing several lines of codes if a condition in IF statement is met. Condition happens occasionally so whenever it happens we need to skip executing several lines of codes, for example:

 if ( op=='A) {

     #skip doing everything here }
{

  #some line of codes which will be run in any condition

or is it possible to do it using while or for loops ?

jeudi 26 septembre 2019

Use nested IF statements to change sparkline colors

Im trying to colorcode my sparklines based on percentage cutoffs.

I am able to do two colors but can't wrap my head around multiple ifs.

B1 has points possible of 3

B2 has points scored first time

B3 has points scored second time

B4 has a two column sparkline.

•B1 can vary from 2 to 8.

•Would like to color code the sparklines where each column has its own colors based on the following percentage conditions of Cell B1

-•>0% but <50% to be (RED)

-•>=50% but <75% to be (ORANGE)

-•>=75% but <100% to be (GREEN)

-•>100% to be (BLUE) I used the following formula to create two possible ones where the high color is blue or green.

=if(B3>B1, SPARKLINE(B2:B3,{"charttype","column";"color","red";"highcolor","blue";"ymin",0}), SPARKLINE(B2:B3,{"charttype","column";"color","red";"highcolor","green";"ymin",0}))

https://docs.google.com/spreadsheets/d/1cvzznbrsR0GdqEr6J52_aWOSFDAf0zYn9MxglzKRyfA/edit?usp=sharing

If-statement using Same as operand coming back false

I am in the process of making a match game. I have two variables with a string of integers that I am using in an if-statement with the == operand. It shows a number then when I type back the same number it should print out a String. I type back the same number and even use 'System.out.println' to make sure my variables are correct but it always prints back the 'Else' String. Here is the script I am using.

package StackOverflow;
import java.util.Scanner;
import java.util.Random;
public class test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    {
        Random r = new Random();
        Scanner s = new Scanner(System.in);
        int b = r.nextInt(9) + 1;
        int c = r.nextInt(9) + 1;
        String d ="" + b + c;
        System.out.println(d);
        String guess = "" + s.nextLine();
        System.out.println(guess);
        if(d == guess)
        {
            System.out.println(":)" );
        }
        else
        {
            System.out.println("almost");
        }
    }
}
}

Any comments are ideas are much appreciated.

Why does "str[index] = 90 + str[index] - 122" it have an error as bus error?

The code is supposed to transform every letter of every word to uppercase. But running the code results in a bus error. What causes the bus error?

#include <stdio.h>

char *ft_strupcase(char *str)
{
    int index;

    index = 0;
    while (str[index] != '\0')
    {
        if (str[index] >= 97 && str[index] <= 122)
            str[index] = 65 + str[index] - 97;
        index++;
    }
    return (str);
}
int main()
{   
    char *name = "sEbas";
    printf("%s\n", ft_strupcase(name));
    return (0);
}

Input: sEbas

Output: SEBAS

How do I use if-statements in regards to inverses of matrices?

Everything works how I want it to apart from the final if statement. I want "Singular product" to be returned if the product of X and Y does not have an inverse.

The following is the code I have thus far, and it doesn't work for the final matrices.

question.five <- function(X,Y) {
if(is.matrix(X)==F) stop("X not matrix")
else { if(is.matrix(Y)==F) stop("Y not matrix")
else { if(ncol(X)!=nrow(Y)) stop("X and Y are not conformable")
else { if(solve(X%*%Y)==ERROR) stop("Singular product")
else on.exit(print(solve(X%*%Y)))
}}}}
X <- matrix(c(1,2,3,4),2,2)
Y <- c(1,2,3,4)
question.five(X,Y)
X <- matrix(c(1,3,4,5),2,2)
Y <- matrix(c(3,2,4,2,4,5,1,2,3),3,3)
question.five(X,Y)
X <- matrix(c(1,-1,-3,4),2,2)
Y <- matrix(c(4,1,3,1),2,2)
question.five(X,Y)

So again, this part of the code is what I need help with:

if(solve(X%*%Y)==ERROR) stop("Singular product")

How to simplify a repetitive function

Is there a way anyone can think of to simplify this function? I find much of this quite repetitive but having a hard time thinking of a way to make it more pythonic or cleaner. Relatively new to python, so I'd appreciate any recommendations.

def colorize(n):
    if n in range(0, 10):
        return selection[-1]
    elif n in range(10, 20):
        return selection[-2]
    elif n in range(20, 30):
        return selection[-3]
    elif n in range(30, 40):
        return selection[-4]
    elif n in range(40, 50):
        return selection[-5]
    elif n in range(50, 60):
        return selection[-6]
    elif n in range(60, 70):
        return selection[-7]
    elif n in range(70, 80):
        return selection[-8]
    elif n in range(80, 90):
        return selection[-9]
    elif n in range(90, 100):
        return selection[-10]
    else:
        return None

Multiple outputs based on each if statement being true. Java

I am trying to make both of these if statements output if true.

Like if I am enter:

cat
car

I want it to output:

Cat and Car are both the same length. 
Cat and Car both start with C.

Right now I am only getting the First output

Here is the code:

import java.util.Scanner;  // Import the Scanner class


public class Main
{
    public static void main(String[] args) {
        System.out.println("input words");

        String myObj, myObj1;

         Scanner sc = new Scanner(System.in);  // Create a Scanner object
         myObj = sc.nextLine();  // String Input
         myObj1 = sc.nextLine(); // String Input


         if(myObj.length() == myObj1.length()){  // System check for String Length
             System.out.println( myObj + " and " + myObj1 + " are the 
            same length.");

         }
         if ((myObj1.charAt(0) == 'C') && (myObj.charAt(0) == 'C')){

            System.out.println(myObj + " and " + myObj1 + " start with C." );
            } // Output if both start with C