jeudi 31 octobre 2019

How to include a string being equal to itself shifted as a coniditon in a function definition?

I'm defining a simple if xxxx return y - else return NaN function that I want the if condition to be true when the input string is equal to input offset by 8 records

I've tried calling the record and setting it equal to itself offset by 8 using == and .shift(8)

def Growth (X):
    if X['Product'] == X['Product'].shift(8):
        return (1+ X['Sales'].shift(4)) / (1+ X['Sales'].shift(8) - 1)
    else:
        return 'NaN'

I expect the output to be NaN for the first 8 records, and then to have numbers at record 9, but I receive the error instead.

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Is there an efficient way to let a variable equal multiple values in an if-statement in Stata?

I am doing data clean-up in Stata and I need to recode a variable to equal 1 if a whole set of other variables are equal to 1, 6, or 7.

I can do this by writing out:

replace anyadl=1 if diffdress==1 | diffdress==6 | diffdress==7 | ///
    diffwalk==1 | diffwalk==6 | diffwalk==7 | ///
    diffbath==1 | diffbath==6 | diffbath==7 | ///
    diffeat==1 | diffeat==6 | diffeat==7 | ///
    diffbed==1 | diffbed==6 | diffbed==7 | /// 
    difftoi==1 | difftoi==6 | difftoi==7

However, this is very inefficient to type out and it's easy to make errors. Is there a simpler way to do this -- say, something like:

replace anyadl=1 if diff*==(1 | 6 | 7)

?

Thank you for any help you can provide!

Comparing ComboBox with an If [duplicate]

I'm trying to compare two ComboBox with a If Statement, and then get the result in a TextBox, tried several thing but can't get it

Here is the code i tried :

private void conver()
    {
        if((comboBox1.SelectedText == "Krw - Wons") && (comboBox2.SelectedText == "Euro"))
        {
            txtBox2.Text = (float.Parse(txtBox1.Text) * 0,00077).ToString();
        }
    }

Also tried that one :

 private void conver()
    {
        if((comboBox1.SelectedItem.ToString() == "Krw - Wons") && (comboBox2.SelectedItem.ToString() == "Euro"))
        {
            txtBox2.Text = (float.Parse(txtBox1.Text) * 0,00077).ToString();
        }
    }

I got 2 differents TextBox, the first one to get the amount to convert in another currency and the second TextBox to get the conversion.I don't have any error but can't get the conversion shown in the Second TextBox.

Thank you for your time.

If, else with multiple constraints and dialog message function

I'm working on a code in eclipse with swing and I have a long-ish if, else function that I'm having trouble with. So, I kind of forgot about nested if, else functions and made all the if's separate, which of course only brings back the last if as true. I want the else function to take into consider multiple constraints, but how do I do this when each "if" has its own dialog message that pops up?

I tried to just make it one long if function with &&'s and a single dialog message, which would work fine for what I need, but I don't know how to do the confirm password and make sure that's not null with that still having its own dialog message and still being in the same if, else function.

btnSubmit = new JButton("Submit");  
            btnSubmit.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    JFrame frmregistration_test = new JFrame("Submit");
                    if (p1.getText().isEmpty())
                    {
                        JOptionPane.showMessageDialog(null, "Password Field field must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
                    }

                    if (p2.getText().isEmpty())
                    {
                        JOptionPane.showMessageDialog(null, "Confirm password Field field must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
                    }


                    if (p1 != null && p2 != null) {
                    if (!Arrays.equals(p1.getPassword(), p2.getPassword())) 
                    {   
                           JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);


                    }
                    if (txtname.getText().isEmpty())
                    {
                        JOptionPane.showMessageDialog(null, "Name field must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
                    }
                    if (txtDOB.getText().isEmpty())
                    {
                        JOptionPane.showMessageDialog(null, "DOB field must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
                    }
                    if (txtNum.getText().isEmpty())
                    {
                        JOptionPane.showMessageDialog(null, "Phone Number field must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
                    }
                    if (txtState.getText().isEmpty())
                    {
                        JOptionPane.showMessageDialog(null, "State field must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
                    }
                    if (txtid.getText().isEmpty())
                    {
                        JOptionPane.showMessageDialog(null, "Email Field field must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);

                    }


                    else 

                        JOptionPane.showMessageDialog(null, "Registered Successfully", "Login Warning", JOptionPane.WARNING_MESSAGE);
                    }



                }});

What's the most pythonic range to check to what particular range (out of many) a number belongs?

I know I can check if a number X belongs to a particular range (out of Y consecutive ranges) by using concatenated if ... elif ... else ... but is there a more concise, pythonic way to do so?

I'm new to Power BI, How can I write an IF statement using two differet tables and return N/A in the second table if conditions are met?

= IF VW-tdsls401100 (Qty B/O) = 0, else, ttdsls903100 (Est. Ship Date),N/A or blank

Tried creating a relationship between both tables. Both tables tdsls401100 & tdsls903100 are related by a primary key column. Looked on line to research how to set up the IF statement across two tables.

Function returns correct value when i use conditional operator or if statement without return statement

#include<stdio.h>
int fact(int);
int main()
{
    int a, b;
    printf("enter a number : ");
    scanf("%d",&a);
    b=fact(a);
    printf("\n%d",b);
}
int fact(int y )
{
    int d=1;
    for(int i = 1;i<=y;i++)
            d*=i;
    d= d>0 ? d : 0;
}

If I remove the last statement , O/P is a+1. I have checked this with other functions and the function returns correct values if I use if statement or conditional operator. I want to know why this happens. Thank You.

How to calculate multiple returns of assets

I have tried to set up a R-code to calculate returns of each column. My problem is that the code should consider multiple investments of different time periods in each asset (column).

I have managed to extract the relevant prices of each day in which each investment was owned (rows) as an xts-object. Therefore, I have a table as shown below (as a xts object). Also, please note that the weekend is not included in the index column:

 Stock 1 Stock 2 Stock 3 Stock 4 Stock 4

2019-10-18 100 NA NA 750 NA

2019-10-21 105 NA NA 1000 6

2019-10-22 110 NA NA NA 7

2019-10-23 NA NA NA 750 8

2019-10-24 10 NA NA 500 8

2019-10-25 7.5 NA NA NA 8

2019-10-28 5 NA NA 500 8

2019-10-29 NA NA 200 250 9

The output I search to obtain is a vector summarizing each independent investment - which is not based upon the investment size:

 Stock 1 Stock 2 Stock 3 Stock 4 Stock 5

Cumulative Return -40% NA 0% -50% 50%

Notice that each investment make use of the first and last row of each investment period to calculate the cumulative return. As an example -40% is calculated as: 110/100-1 + 5/10-1

If multiple investments are made in an asset (column), it will always be of non-overlapping periods as in the example above.

Thanks in advance!

Reasons why Condition shortening for same attributes is not enabled?

I have seen this Post, and want to know if there are any known reasons why this is not implemented. Does someone know why something like this is not available? I can't find anything on the web.

i only want to know if there are known downsides or disadvantages or things i did not consider on this idea.

i wish there would be something like this:

if (objectOneWithLongName.getNumber() == [12 || 13]) {
  someCode();
}

I think this would be a huge advantage for coders, to have something like that.
what do you think?
is it a bad idea and if so, why?
Where there already any thoughts on this subject by the creator of java and they dismissed it?

Otherwise, if someone has seen this, or it's on the timeboard at Oracle, can someone link the JEP?

Return value from row if multiple conditions are true

I have the following dummy Df:

structure(list(lat = c(15.04166667, 15.125, 15.29166667, 15.375, 15.04166667, 15.125, 15.20833333, 15.29166667, 15.375, 15.45833333, 15.54166667, 14.95833333, 15.04166667, 15.125, 15.20833333, 15.29166667, 15.375, 15.45833333, 15.54166667, 15.625, 15.70833333, 15.79166667, 15.875, 16.54166667, 13.875, 14.875, 14.95833333), lon = c(48.95833333, 48.95833333, 48.95833333, 48.95833333, 48.875, 48.875, 48.875, 48.875, 48.875, 48.875, 48.875, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.79166667, 48.70833333, 48.70833333, 48.70833333), Var1 = c(40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L), Var2 = c(29.76510459, 6.480850609, 223.0983795, 203.8934788, 11.27195619, 65.76071468, 194.8171225, 262.4171485, 171.163622, 240.1846431, 239.8467942, 53.94738807, 49.07189175, 118.194278, 218.744134, 313.4466307, 185.409121, 252.8829675, 219.123076, 211.2351477, 279.0554084, 260.621935, 169.9482421, 337.1199379, 9.932910029, 96.11876075, 69.54847552), Var3 = c(6.24087876, 1.358846252, 46.77725586, 42.75054481, 2.363402045, 13.78811339, 40.84749728, 55.02126264, 35.88804325, 50.35974897, 50.28891223, 12.29369073, 10.28895202, 24.78191063, 45.86429711, 65.72066044, 38.87491352, 53.02222021, 45.94375161, 44.28987901, 58.50982373, 54.64485812, 35.63321409, 70.68427011, 1.731396537, 20.15331521, 14.58229774), Var4 = c(173.4664468, 173.4706729, 173.4790964, 173.4833057, 173.4077614, 173.4117034, 173.4156335, 173.4195758, 173.4235096, 173.4266725, 164.1875386, 239.5356333, 173.3490717, 173.3527418, 173.3563883, 173.3600476, 173.3637073, 173.3667678, 164.1276972, 164.1295668, 164.1308363, 164.1321065, 164.1333879, 167.3271206, 150.2922712, 224.8818893, 224.8852899), Var5 = c(19.62146524, 19.62146505, 19.62146589, 19.62146616, 19.62146629, 19.62146473, 19.62146495, 19.62146552, 19.62146614, 19.62146513, 16.76539618, 38.78913858, 19.62146615, 19.62146541, 19.62146505, 19.62146575, 19.62146599, 19.62146573, 16.76539594, 16.76539677, 16.7653963, 16.76539632, 16.76539658, 17.25115902, 11.78819987, 34.82506079, 34.82506128), var6 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "High", class = "factor"), var7 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "HIGH RISK", class = "factor")), class = "data.frame", row.names = c(NA, -27L))

What I want to do is create a new variable called var8 which return Var2 only if Var6 is "High" and Var7 is "HIGH RISK" otherwise return nothing. Note that var6 and var7 have other factor( e.g. Low, Medium, SAFE.. )which are not provided in the example.

I tried this, but it return TRUE o FALSE value, whereas I want the value from VAr 2 only in case it being TRUE and 0 in case it is FALSE.

  df<- df %>% 

mutate( Area.HRH=Var6 =="High" & (Var7== "HIGH RISK"))

Thank you!

I have to make a "guess next card is higher" game. but can't find the problem

3 classes. Card, Game & Deck. I don't know why it is giving me an error. Wish someone can help me out, I would like to know what the problem is.

What the title say's, I have to guess if the next card that I would get is higher or lower.


package CardGame;

import java.util.Scanner; import java.util.*;

public class Game {

private static int score;

// currentCard : Card
private static Card currentCard;
// Next Card
private Card nextCard;
// Scanner
private static Deck deck;

private static Scanner sc = new Scanner(System.in);

// Main

public static void main(String[] args) {

    deck = new Deck();

    currentCard = deck.getNextCard();

    Game.gameTurn();
}

// get turn method
public static void gameTurn() {
    // System.out.println(Deck.getCards().size());
    System.out.print("is your next card higher or lower than the next card?");
    System.out.print(sc);
    String answer = sc.nextLine();

    Card nextCard = deck.getNextCard();


    if (answer.equals("higher") && nextCard.isHigherOrEqual(currentCard)) {

        correct();
    } else if (answer.equals("lower") && !nextCard.isHigherOrEqual(currentCard)) {
        correct();
        // answer.equals("lower")&& !nextCard.isHigherOrEqual(currentCard)
    } else {
        gameOver();
    }
}

// correct method

public static void correct() {
    Game.gameTurn();
    score = 0;
    score++;
}

// Game over Method

public static void gameOver() {
    System.out.println("total score is " + score + "!");
}

}

package CardGame;

import java.util.ArrayList; import java.util.Collections;

public class Deck {

// cards = Card = new ArrayList<>()
private static ArrayList<Card> cards = new ArrayList<>();

// Deck Method
public void Deck() {

    for (int i = 1; i < 4; i++) {
        String suits;

        switch (i) {

        case 1:
            suits = "Hearts";
            break;

        case 2:
            suits = "Diamonds";
            break;

        case 3:
            suits = "Spades";
            break;

        case 4:
            suits = "Clubs";
            break;
        default:
            suits = "";
            break;
        }
        for (int j = 1; j <= 10; j++) {
            int value = j;
            String name = j + " of " + suits;
            Card c = new Card(suits, name, value);

            cards.add(c);

        }
        // add 1.3 tot 1.11

        Card jack = new Card(suits, "jack of " + suits, 11);

        cards.add(jack); // JACK

        Card queen = new Card(suits, "queen of " + suits, 12);

        cards.add(queen); // QUEEN

        Card king = new Card(suits, "king of " + suits, 13);

        cards.add(king); // KING

        Card ace = new Card(suits, "ace of " + suits, 14);

    }
    // 1.11 shuffle cards
    Collections.shuffle(cards);
}

// getNextCard() : Card

public Card getNextCard() {

    Card nextCard = cards.remove(0);

    return nextCard;

}

// getCards() : ArrayList <card>
public static ArrayList<Card> getCards() {

    return cards;
}

}

package CardGame;

public class Card {

// Suit String
private String suit;

// Name String
private String name;
// Value int
private int value;

// Card constructor
public Card(String suit, String name, int value) {
    this.value = value;
    this.name = name;
    this.suit = suit;

}

public int getValue() {
    return value;
}

// toString Method
public String toString() {
    if (value == 15);
    return "";
}
// isHigherorEqual Method

public boolean isHigherOrEqual(Card c) {
    if (this.value >= c.getValue()) {
        return true;
    } else {
        return false;
    }
}

}

Any alternative to redundant var in OR conditions? [duplicate]

Is there any smarter and shorter way in Java, to avoid repeating long varnames in OR conditions?

if (objectOneWithLongName.getNumber() == 12 || objectOneWithLongName.getNumber() == 13) {
  someCode();
}

Of cause we could locally shorten the var, but i think this reduces the readability in meaning in most cases.

int x = objectOneWithLongName.getNumber();
if (x == 12 || x == 13) {
  someCode();
}

i wish there would be anything like this:

if (objectOneWithLongName.getNumber() == [12 || 13]) {
  someCode();
}

I think this would be a huge advantage for coders, to have something like that.
what do you think?
is it a bad idea and if so, why?
Where there already any thoughts on this subject by the creator of java and they dismissed it?

if statement in react JS function

I have a function that calculates a price based off of a set base_price and user input (property square footage).

I want to change the initial base_price based off of which package is selected.

for example, say the current let base_price= 159.998 is for cleaning services.

If the customer chooses photography services, the initial let base_price = 159.998 changes to a new number: let base_price = 259.998.

???what would be the best way to go about this??? using if/else?

Current code:

checkPrice = () => { 
   let base_price = 159.998;
     if(this.state.propertySqft > 2000){
   let overage = this.state.propertySqft - 2000;
   let percentage = Math.floor(overage / 500) * 10;
   base_price += base_price * (percentage / 100);


  }
     this.setState({ totalPrice: Math.round(base_price * 100) / 100 }); 
  }

stripping punctuation and finding unique words in Python

So my task is as such:

Write a program that displays a list of all the unique words found in the file uniq_words.txt. Print your results in alphabetic order and lowercase. Hint: Store words as the elements of a set; remove punctuations by using the string.punctuation from the string module.

Currently, the code that I have is:

def main():
    import string

    with open('uniq_words.txt') as content:
        new = sorted(set(content.read().split()))
        for i in new:
            while i in string.punctuation:
                new.discard(i)
                print(new)

main()

If I run the code as such, it goes into an infinite loop printing the unique words over and over again. There sre still words in my set that appear as i.e "value." or "never/have". How do I remove the punctuation with the string.punctuation module? Or am I approaching this from a wrong direction? Would appreciate any advice!

Edit: The link does not help me, in that the method given does not work in a list.

Vlookup then return a different row in Google Sheets

I'm struggling to figure out how to get sheets to first look up the location of a key value and then look up which of the sub values it should take. Best would be to include an example, which:

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

What I'm hoping to achieve is that the values for item 1, when selected, auto fill in the correct gear builder fields.

Any advice on this is hugely appreciated.

How to return a value based on whether two columns contains values present in other columns

I have four columns to compare against and a fifth one which contains the target value. I need to compare the four columns (2 each) and if they match then return the corresponding value in the fifth column. One of the columns requires comparing using the typical = sign while the other column requires checking if the other column contains part of the text. I tried using regexmatch but I couldn't get the formula to return the values as I'd wanted.

Here is the link to the google sheets file: https://docs.google.com/spreadsheets/d/13RotkFBSOTylN6YOxPjzYDNWwYtCXo6Ewh6UtCi0i1E/edit?usp=sharing

if statement not valid?

This sounds so stupid, and i know for sure im being stupid, but i cant figure out why its not working.

the if in question, is

if (currentRoom = outside || pub);
    {
        System.out.println("A friendly traveller is here!"); 

    }
}

below is the rest of the relevant code

private Room currentRoom;

private void createRooms() 
{
    Room outside, theatre, pub, lab, office, up, down;

    // create the rooms
    outside = new Room("outside the main entrance of the university");
    theatre = new Room("in a lecture theatre");
    pub = new Room("in the campus pub");
    lab = new Room("in a computing lab");
    office = new Room("in the computing admin office");
    up = new Room("creepy upstairs");
    down = new Room("spooky downstairs");

    // initialise room exits
    outside.setExit("north", lab);
  //  outside.item.addItem("Gun", 10);
    outside.setExit("down", down);
    outside.setExit("up", up);
    outside.setExit("west", pub);
    outside.setExit("east", office);

    down.setExit("north", outside);
   // down.item.addItem("book", 1);
    up.setExit("south", outside);
    // up.item.addItem("knife", 5);

    lab.setExit("east", office);
    lab.setExit("south", outside);
    lab.setExit("north", theatre);
    // lab.item.addItem("bomb", 10);

    office.setExit("south", lab);
    // office.item.addItem("key", 0);

    pub.setExit("east", theatre);
    pub.setExit("south", outside);
    // pub.item.addItem("beer", 2);

    theatre.setExit("south", outside);
    currentRoom = outside;  // start game outside
}

    private void printWelcome() 
{
    System.out.println();
    System.out.println("Welcome to the World of Zuul!");
    System.out.println("World of Zuul is a new, incredibly boring adventure game.");
    System.out.println("Type 'help' if you need help.");
    System.out.println();
    System.out.println(currentRoom.getLongDescription());

    if (currentRoom = outside || pub);
    {
        System.out.println("A friendly traveller is here!"); 

    }
}

im literally just trying to make it so that if the players room is either outside, or the pub, then to print a message. However it's not working, any guidance is really appreciated. Im sure this is a really dumb question to ask but im new and i dont understand why its not working

Compare hours and minutes using only if

I got two variables, hour and minute. I need compare it with another h/m and depending results, show it or not. Example: 13:30 needs to print "AHORA TOCA". But only if this time is previous to 20:30. Is earlier by the hour but not by the minute.

int hours = 13;
int minutes = 30;
if(hours <= 20){
            if(minutes < 30){
                System.out.println("AHORA TOCA");     
            } 
        }

This don't print cause minutes. So, what can i do?

Nested if else-if function "unexpected error" in R getting

I am trying to select the column "sn_r" from the data set "va" where "va$VACHART==1". If this condition is satisfied then I want to store the value in a new column while calculating it using the formula "85+50*log10(va$sn_r)". If the condition does not satisfy it, then search in a different range value of "sn_r" and store it.

In R. I have tried using the if, else if function but there is an unexpected '}' error in "}"

if(va$VACHART=="1" & va$sn_r>"0.025"){
va$ETDRS_R = 85+50*log10(va$sn_r)
}else if(va$VACHART=="1" & "0.020"< vd$sn_r <="0.025"){
va$ETDRS_R = 5
}else if(va$VACHART=="1" & "0.015"< vd$sn_r <="0.020"){
va$ETDRS_R = 3
}else if(va$VACHART=="1" & "0.005"< vd$sn_r <="0.015"){
va$ETDRS_R = 1
}else {#if(va$VACHART=="1" & "0"< vd$sn_r <="0.005"){
va$ETDRS_R = 0
}

How to code a shortest path problem with for cycle in Java

I created an actions array and each one of this action has a cost. After this, I implement a for cycle to find the action with the lowest cost. Secondly, I have to check the preconditions to see which action is possible.

//Actions
static Action loadPlaneP1 = new Action("loadPlaneP1",pkg1Location[1], pkg2Location[0], truckLocation[0], planeLocation[0], cityLocation[0], 30);
    static Action loadPlaneP2 = new Action("loadPlaneP2", pkg1Location[0], pkg2Location[1], truckLocation[0], planeLocation[0], cityLocation[0], 40);
    static Action fly = new Action("fly",pkg1Location[1], pkg2Location[1], truckLocation[0], planeLocation[1], cityLocation[0], 100);
    static Action unloadPlaneP1 = new Action("unloadPlaneP1",pkg1Location[2], pkg2Location[1], truckLocation[0], planeLocation[2], cityLocation[1], 50);
    static Action unloadPlaneP2 = new Action("unloadPlaneP2",pkg1Location[1], pkg2Location[2], truckLocation[0], planeLocation[2], cityLocation[1], 55);
    static Action loadTruckP1 = new Action("loadTruckP1",pkg1Location[3], pkg2Location[2], truckLocation[0], planeLocation[2], cityLocation[1], 60);
    static Action loadTruckP2 = new Action("loadTruckP2",pkg1Location[2], pkg2Location[3], truckLocation[0], planeLocation[2], cityLocation[1], 10);
    static Action drive = new Action("drive",pkg1Location[3], pkg2Location[3], truckLocation[1], planeLocation[2], cityLocation[1], 70);
    static Action unloadTruckP1 = new Action("unloadTruckP1", pkg1Location[5], pkg2Location[5], truckLocation[2], planeLocation[2], cityLocation[1], 40);
    static Action unloadTruckP2 = new Action("unloadTruckP2",pkg1Location[4], pkg2Location[4], truckLocation[3], planeLocation[2], cityLocation[1], 43);

//Array
static Action[] acts = { loadPlaneP1, loadPlaneP2, fly, unloadPlaneP1, unloadPlaneP2, loadTruckP1, loadTruckP2, drive, unloadTruckP1, unloadTruckP2 };

The problem is in the main logic, because when I print the action name and the cost obtained, is showing "loadPlaneP1"(the one with lower cost) but the parameter that I get through getActParameter1() is the parameter of "unloadTruckP2"(the last one in the array). Moreover, if I change the cost to set another action cost to the lowest, the logic doesn't work.

//Main logic
System.out.println("Old state parameters are " + "pkg1Location: " + state.getStateParameter1() + " pkg2Location: " + state.getStateParameter2() + " truckLocation: "+ state.getStateParameter3() + " planeLocation: " + state.getStateParameter4() + " cityLocation:"+ state.getStateParameter5());



                 for(int i = 0; acts[i].getActionCost() == getMinValue(costs); i++) {

                     System.out.println("PRE The first parameter is : " + acts[i].getActParameter1() + acts[i].name);



                     if(acts[i].getActParameter1() == "plane") {

                     System.out.println("POST The first parameter is : " + acts[i].getActParameter1());
                     System.out.println("Precondition satysfied" + " with action name: " + acts[i].name);

                     if(acts[i].getActParameter1() != state.getStateParameter1()) {

                         state.setStateParameter1(acts[i].getActParameter1());
                     }

                     if(acts[i].getActParameter2() != state.getStateParameter2()) {

                         state.setStateParameter2(acts[i].getActParameter2());
                     }

                     if(acts[i].getActParameter3() != state.getStateParameter3()) {

                         state.setStateParameter3(acts[i].getActParameter3());
                     }

                     if(acts[i].getActParameter4() != state.getStateParameter4()) {

                         state.setStateParameter4(acts[i].getActParameter4());
                     }

                     if(acts[i].getActParameter5() != state.getStateParameter5()) {

                         state.setStateParameter5(acts[i].getActParameter5());
                     }
                 }

                         Node child = new Node(state, startNode, acts[i].getActionCost());


                        /*    List<Action> removeList = new ArrayList<Action>(Arrays.asList(acts));
                            removeList.remove(Arrays.asList(i));
                            acts = removeList.toArray(acts);*/


                         //nextAction = acts[i];

                         System.out.println("Costs array: "+  Arrays.toString(costs));
                         System.out.println("ActionID" +" " +  i);
                         System.out.println("The action choosen is " + acts[i].name + acts[i].actionCost + acts[i].getActParameter1());
                         System.out.println("State parameters updated are " + "pkg1Location: " + state.getStateParameter1() + " pkg2Location: " + state.getStateParameter2() + " truckLocation: "+ state.getStateParameter3() + " planeLocation: " + state.getStateParameter4() + " cityLocation:"+ state.getStateParameter5());

                     };




                     }  

The output that I receive is

Old state parameters are pkg1Location: lhr pkg2Location: lhr truckLocation: cdg planeLocation: lhr cityLocation:london
PRE The first parameter is : southloadPlaneP1
POST The first parameter is : south
Precondition satysfied with action name: loadPlaneP1
Costs array: [30, 40, 100, 50, 55, 60, 70, 70, 40]
ActionID 0
The action choosen is loadPlaneP130south
State parameters updated are pkg1Location: south pkg2Location: south truckLocation: south planeLocation: cdg cityLocation:paris

So the condition is not satysfied, because the parameter that I get from getActParameter1() is different from the one that loadPlaneP1 has. Why is this happening?

Writing sum of sinc functions in ampl

I have to implement a Mathematica output as a variable in ampl which is a sum and product of sinc functions. I have defined a sinc function as

var SincA {i in N}=   if abs(x1[i]) > 1e-8 then sin(x1[i])/x1[i] else 1;
var SincB {i in N}=   if abs(x2[i]) > 1e-8 then sin(x2[i])/x2[i] else 1;

However, the Mathematica output takes the shape

    -19.99590492248535*Sinc[0.12566370614359174*(0. + t)]*
  Sinc[0.26927937030769655*(-65. + u)] - 
 4.360287189483643*Sinc[0.12566370614359174*(25. + t)]*
     Sinc[0.26927937030769655*(-65. + u)] + 
 12.314101219177246*Sinc[0.12566370614359174*(50. + t)]*
  Sinc[0.26927937030769655*(-65. + u)] 

and this is just a small part of the total output.

I can reproduce this in ampl as

var Sinc1x1A{i in N}= if abs(0.12566370614359174*(0. + x1[i])) > 1e-8 then sin(0.12566370614359174*(0. + x1[i]))/(0.12566370614359174*(0. + x1[i])) else 1;

var Sinc1x1B{i in N} = if abs(0.26927937030769655*(-65. + x2[i])) > 1e-8 then sin(0.26927937030769655*(-65. + x2[i]))/(0.26927937030769655*(-65. + x2[i])) else 1

var Resultx1{i in N} = -19.99590492248535*Sinc1x1A[i]*Sinc1x1B[i]-...;

However, this method is extremely inefficient since I have to define too many variables.

I want to construct a sinc function without a defined argument and then call it as many times as needed instead of having to define tens of variables.

I have found these slides, https://ampl.com/MEETINGS/TALKS/2018_07_Valencia_WA-57.pdf, but I cannot find any way to do what I want.

Can someone point me to some documentation where this is solved?

How to fix the -like which searches for charakters

first of all i'am very new to Powershell Programming and iam really sorry if this is a trivial question.

I'am trying to write a Password generator in Powershell everything works fine expect the if Statement. Iam askign if the Password containes any special charakters or numbers. If it doesnt contain any of them it should output an error if it contains numbers or charakter it should wirte the Password.

Iam trying to do this with an Array and ASCII. Iam writing the charakters into an array with a for loop and later on iam converting them to the specific character i want.

This is for a School Project iam working on. I've tried to remove the brackets in the IF statement but then it shows the password even without the special charakters and numbers.

$RandomePassword = "abC!231"
for($ASCII = 33  ; $ASCII -le 64 ; $ASCII++)
{
    $char += @($ASCII)
} 

if ($RandomePassword -like ([char[]]$char -join "|"))
{
    write (($RandomePassword -split '' | Sort-Object {Get-Random}) -join '')
}
else{
    write "ERROR"
}

The Expected result would be:

$RandomePassword = "Abc!12" -> writes Password on Comand line

$RandomePassword = "Abc" -> wirtes error

Thank you for your time and help

IF/ELSE Control flow in Python to work out price of courier service from 4 choices

I cannot seem to understand how to use if/else in the following question:

● You need to design a program for a courier company to calculate the cost                         of sending a parcel. ● Ask the user to enter the price of the package they would like to purchase. ● Ask the user to enter the total distance of the delivery in kilometers. ● Now, add on the delivery costs to get the final cost of the product. There are                               four categories to factor in when determining a parcel’s final cost, each with                        two options based on the customer’s delivery preferences. (Use an if else                      statement based on the choice they make) ○ Delivery via air ($0.36 per km) or via freight ($0.25 per km) ○ Full insurance ($50.00) or limited insurance ($25.00) ○ Gift option ($15.00) or not ($0.00) ○ Priority delivery ($100.00) or standard delivery ($20.00) ● Write code to work out the total cost of the package based on the options                             selected in each category.

Can anyone help? Thank you.

mercredi 30 octobre 2019

Using if statements with an else to validate form and redirect to a new page if form is valid

hi i've got this code to validate the form which works but it doesn't carry out the else statement and direct to the page if the form is valid

function printpage() {
  if (!mandatoryText(document.getElementById('FIRSTNAME_FIELD'), 'First name')) return false;
  if (!mandatoryText(document.getElementById('LASTNAME_FIELD'), 'Last name')) return false;
  if (!mandatoryText(document.getElementById('ZIP_CODE_FIELD'), 'Post code')) return false;
  if (!mandatoryText(document.getElementById('EMAIL_FIELD'), 'Email')) return false;
  if (!isEmail(document.getElementById('EMAIL_FIELD'))) return false;
  if (!isDateOK(document.getElementById('LAST_SHOWROOM_VISIT_FIELD').value)) return false;
  if (document.getElementById('LAST_SHOWROOM_VISIT_FIELD').value != '') modifyDateFormat(document.getElementById('LAST_SHOWROOM_VISIT_FIELD'));
  document.getElementById('emvForm').submit();
  if (document.getElementById('LAST_SHOWROOM_VISIT_FIELD').value != '') modifyDateFormat(document.getElementById('LAST_SHOWROOM_VISIT_FIELD'));
  else {
    return true;
    var p1 = document.getElementById('SELECTED_PRODUCT_1_FIELD').value;
    window.location.href = "summary.html?" + "p1" + "=" + p1;
  }
}

If statement resulting in NotImplementedError: couldn't find matching opcode for 'and_bdd' followed by a VaueError

Good day, Folks.

I am trying to add a new column to a DataFrame after performing checks on the value of two other columns. The conditional statement that I have is resulting in an error that I am unable to understand and resolve.

if (DF.loc[DF['column_1']==0.0] & DF.loc[DF['column_2']==0.0]):
    DF['new_column']=1
else:
    DF['new_column']=0

The execution of code resulted in the following errors:

KeyError: ('a_value & b_value', (('optimization', 'aggressive'), ('truediv', True)), (('a_value', ), ('b_value', )))

NotImplementedError: couldn't find matching opcode for 'and_bdd'

Because I couldn't understand and resolve the above error, I decided to split the if condition as given below which resulted in a different error.

if (DF.loc[DF['column_1']==0.0]):
   if(DF.loc[DF['column_2']==0.0]):
      DF['new_column']=1
else:
    DF['new_column']=0

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I would really appreciate if you could please help me understand what I am doing wrong here in these two scenarios.

Thanks

i have a range slider in which i want to control the value change. if slider value is greater than 0.. say good day

<div class="container"><div id="number">0</div>
        <input type="range" min="0" max="10" value="0" id="slider"></div>
<script>
        var slider=document.
            getElementById("slider");
        var number=document.
            getElementById("number");
        slider.oninput=function(){
            number.innerHTML=slider.
                value;}
</script>
<p id="demo">good evening</p>

for some reason its not working when i have number or slider or slider.value in the if statement.

<script>

    if (number> '0' ){document.getElementById("demo").innerHTML = "Good day!";}
    </script>

How to pull information from a cell based on two or more cells content?

I have a main Spreadsheet, where I'm pulling information from other various spreadsheets, as of now I have this formula:

=IF(ISBLANK(F2), "", SUMIF('Redirects Sheets'!A$2:A$19499, "*" & F2 & "*", 'Redirects Sheets'!B$2:B$19499))

if the content in the cell F2 matches what's in the redirect sheet, it would pull the information.

What I want to add to this is in case that the information in F2 does not match the content from the redirect sheet, to look into another spreadsheet for the information matching what I have in A2 which is a simple name, and then fill the cell with that information.

I tried different ifs or sum if but I get limited in the way google sheets handles conditionals, or maybe and super new to this and I just don't get the proper way of doing this.

when testing or nesting other IFs, or sumifs, I get parse errors, or #N/A .

If/elif wrong display of "random" output

## After input amount of chips and amount of bet and choose number, the number is always red, this worked few days ago but i changed something and there is impossible to get "black" ## If elif statement is considering only when IF is not True, then i dont get why spin= number from second pool of numbers but there is "red" from first statement

import random
#program
while True:
    print("Enter 'rules' to show rules")
    print("Enter 'play' to play the game")
    print("Enter 'author' to show info about creator")
    print("Enter 'quit' to end the program")
    user_input=input()
    if user_input.lower()=="quit":
        break
    elif user_input.lower()=="rules":
        print(cont)
    elif user_input=="play":
        while True:       #LOOOP IN DA LOOOP
            start=int(input("How much chips you want for start?\n"))
            amount=int(input("How much you want bet\n"))
            bet=int(input("Place your bet\n"))
            spin=random.randint(0,36)
            #Continue/break?
            if bet>36:
                print("There is only 36 numbers!")
            elif bet<0:
                print("You need bet number beetwen 0 and 36")
            elif spin==bet:
                print("You won",amount*35)
                print("Now you have",start-amount+amount*35)
            else:
                print("You lose")
                print("Now you have",start-amount) #Aktualizacja stacka
                if spin==1 or 3 or 5 or 7 or 9 or 12 or 14 or 16 or 18 or 19 or 21 or 23 or 25 or 27 or 30 or 32 or 34 or 36:
                    print(spin,"red")
                elif spin==2 or 4 or 6 or 8 or 10 or 11 or 13 or 15 or 17 or 20 or 22 or 24 or 26 or 28 or 29 or 31 or 33 or 35:
                    print(spin,"black")
                else:
                    print(spin,"green")
    elif user_input=="author":
         print("Jacob X")
    else:
         print("Unknown command")

Movie length from minutes to hours

How would i go about writing a program that would get the length of a movie in minutes and show me how long the movie would be in hours+ minutes (for instance 88 minutes would show 1 hour and 28 minutes) using the "if" statement.

Adding if user is guest/customer statement to PHP

I am trying to edit some PHP code so that the cart appears on the checkout page for certain users only. I need it to appear for guests, customers, and admins. I know very little about PHP, but the code is throwing an error.

This is the original code I started with, and wanted to add an if statement so it shows up for certain users only:

add_action( 'woocommerce_before_checkout_form', 'bbloomer_cart_on_checkout_page_only', 5 );

function bbloomer_cart_on_checkout_page_only() {

if ( is_wc_endpoint_url( 'order-received' ) ) return;

echo do_shortcode('[woocommerce_cart]');

}

This is the code I am trying that is not working:

add_action( 'woocommerce_before_checkout_form', 'bbloomer_cart_on_checkout_page_only', 5 );

function bbloomer_cart_on_checkout_page_only() {

if ( Auth::guest() && current_user_can('customer') || current_user_can('Administrator' ) && is_wc_endpoint_url( 'order-received' ) ) return; 

echo do_shortcode('[woocommerce_cart]');

}

R - Split String with conditions

I have a string splitting related problem. I have a huge amount of files, which names are structures like this:

filenames = c("NO2_Place1_123_456789.dat", "NO2_Nice_Place_123_456789.dat", "NO2_Pretty_Place_123_456789.dat", "NO2_Place2_123_456789.dat")

I need to extract the Stationnames, e.g. Place1, Nice_Place1 and so on. Its either "Place" and a number or "Nice_Place" and a number.

I tried this to get the stationnames for "Place" and a number and it works geat, but this doesnt give me the correct name in case of "Nice_Place"...because it handles it as 2 words.

Station = strsplit(filenames[1], "_")[[1]][2] #Works
Station = strsplit(filenames[2], "_")[[1]][2] #Doesnt work

My idea is now to use if...else. So If the Stationname in the example above is "Nice", add the 3rd part of the stringsplit with an underscore. Unfortunatley I am totally new to this if else condition.

Can somebody please help?

How to define a shortest path problem with preconditions in Java

I'm trying to develop a program like a planner. This means that for each node has to decide which action is better and go on with that path. However, for now I'm stucked at the first decision node after the start. This decision has to depend on the minimum action cost and on if the action precondition are respected. With my code I had success in the minimum action cost, but the precondition are not working good yet.

I have defined an array of all the actions, and with a for cycle I check which is the one with lower cost. After, I have implemented an if statement to verify the precondition. This precondition is based on the previous state parameter and on a check to choose the right action to do.

This is my code, with a main class, an action class and a state class(and a node one but is not relevant for this).

public class Action {

         int actionCost;    
        static String actParameter1;
        static String actParameter2;
        static String actParameter3;
        static String actParameter4;
        static String actParameter5;
        public String name;


    public Action(String name1, String pkg1Loc, String pkg2Loc, String truckLoc, String planeLoc, String city1, int cost) {

        actParameter1 = pkg1Loc;
        actParameter2 = pkg2Loc;
        actParameter3 = truckLoc;
        actParameter4 = planeLoc;
        actParameter5 = city1;

        actionCost = cost;
        name = name1;

    }

/*  public boolean loadPlaneP1Precondition() {

        if(State.stateParameter1 == State.pkg1Location[0]) {
            if(State.stateParameter4 == State.planeLocation[0]) {
                if(State.stateParameter5 == State.cityLocation[0]) {
                    if(Action.actParameter1 == State.pkg1Location[1]) {
                        if(Action.actParameter2 == State.pkg2Location[0]) {
                            if(Action.actParameter4 == State.planeLocation[0]) {
                                return true;
                            }else {
                                return false;
                                  }
                        }else {
                            return false;
                              }
                    }else {
                        return false;
                          }
                }else {
                    return false;
                      }
            }else {
                return false;
                  }     
        }else {
            return false;
             }
    }
    */

public boolean loadPlaneP1Precondition() {

        if(Action.actParameter1 == State.pkg1Location[1]) {
            return true;
        }else {
            return false;
        }
}



    public String getActParameter1() {
        return actParameter1;
    }

    public String getActParameter2() {
        return actParameter2;
    }

    public String getActParameter3() {
        return actParameter3;
    }

    public String getActParameter4() {
        return actParameter4;
    }

    public String getActParameter5() {
        return actParameter5;
    }

    public int getActionCost() {
        return actionCost;
    }
}

The loadPlaneP1 commented precondition is the completed one, but is not working. So I defined just a small version of that with just one action check and is still not working(with only the state checks works).

public class State {

            static String[] pkg1Location = {"lhr","plane", "cdg", "truck", "south","north"};
            static String[] pkg2Location = {"lhr","plane", "cdg", "truck", "south","north"};
            static String[] truckLocation = {"cdg","driving", "south", "north"};
            static String[] planeLocation = {"lhr","flying","cdg"};
            static String[] parisLocation = {"north", "south"};
            static String[] cityLocation = {"london", "paris"};
            static String parisAirport = "cdg";
            static String londonAirport = "lhr";


            int stateValue; 
            static String stateParameter1;
            static String stateParameter2;
            static String stateParameter3;
            static String stateParameter4;
            static String stateParameter5;


    public State(int number, String pkg1Loc, String pkg2Loc, String truckLoc, String planeLoc, String cityLoc) {

        stateParameter1 = pkg1Loc;
        stateParameter2 = pkg2Loc;
        stateParameter3 = truckLoc;
        stateParameter4 = planeLoc;
        stateParameter5 = cityLoc;

        stateValue = number;

    }


    public String getStateParameter1() {
        return stateParameter1;
    }

    public void setStateParameter1(String x) {
         stateParameter1 = x;
    }

    public String getStateParameter2() {
        return stateParameter2;
    }

    public void setStateParameter2(String x) {
         stateParameter2 = x;
    }

    public String getStateParameter3() {
        return stateParameter3;
    }

    public void setStateParameter3(String x) {
         stateParameter3 = x;
    }

    public String getStateParameter4() {
        return stateParameter4;
    }

    public void setStateParameter4(String x) {
         stateParameter4 = x;
    }

    public String getStateParameter5() {
        return stateParameter5;
    }

    public void setStateParameter5(String x) {
         stateParameter5 = x;
    }

    public int getStateValue() {
        return stateValue;
    }

This is the state class

public class Main {


    private static String[] pkg1Location = {"lhr","plane", "cdg", "truck", "south","north"};
    private static String[] pkg2Location = {"lhr","plane", "cdg", "truck", "south","north"};
    private static String[] truckLocation = {"cdg", "driving", "north","south"};
    private static String[] planeLocation = {"lhr","flying","cdg"};
    private static String[] parisLocation = {"north", "south"};
    private static String[] cityLocation = {"london", "paris"};
    private static String cdgAirport = "paris";
    private static String lhrAirport = "london";


    private static Node nodeStatus;

    private static Action nextAction;


    //actions with effects
    static Action loadPlaneP1 = new Action("loadPlaneP1",pkg1Location[1], pkg2Location[0], truckLocation[0], planeLocation[0], cityLocation[0], 30);
    static Action loadPlaneP2 = new Action("loadPlaneP2", pkg1Location[0], pkg2Location[1], truckLocation[0], planeLocation[0], cityLocation[0], 40);
    static Action fly = new Action("fly",pkg1Location[1], pkg2Location[1], truckLocation[0], planeLocation[1], cityLocation[0], 100);
    static Action unloadPlaneP1 = new Action("unloadPlaneP1",pkg1Location[2], pkg2Location[1], truckLocation[0], planeLocation[2], cityLocation[1], 50);
    static Action unloadPlaneP2 = new Action("unloadPlaneP2",pkg1Location[1], pkg2Location[2], truckLocation[0], planeLocation[2], cityLocation[1], 55);
    static Action loadTruckP1 = new Action("loadTruckP1",pkg1Location[3], pkg2Location[2], truckLocation[0], planeLocation[2], cityLocation[1], 60);
    static Action loadTruckP2 = new Action("loadTruckP2",pkg1Location[2], pkg2Location[3], truckLocation[0], planeLocation[2], cityLocation[1], 60);
    static Action drive = new Action("drive",pkg1Location[3], pkg2Location[3], truckLocation[1], planeLocation[2], cityLocation[1], 70);
    static Action unloadTruckP1 = new Action("unloadTruckP1", pkg1Location[5], pkg2Location[5], truckLocation[2], planeLocation[2], cityLocation[1], 40);
    static Action unloadTruckP2 = new Action("unloadTruckP2",pkg1Location[4], pkg2Location[4], truckLocation[3], planeLocation[2], cityLocation[1], 43);

    static State goal = new State(11, pkg1Location[5], pkg2Location[4], truckLocation[3], planeLocation[2], cityLocation[1]);

    static Action[] acts = {loadPlaneP1, loadPlaneP2, fly, unloadPlaneP1, unloadPlaneP2, loadTruckP1, loadTruckP2, drive, unloadTruckP1, unloadTruckP2 };


    public static void main(String args[]) {



    State state = new State(0, pkg1Location[0], pkg2Location[0], truckLocation[0], planeLocation[0], cityLocation[0]);

    Node startNode = new Node(state, 0);

    nodeStatus = startNode;


     int[] costs = {loadPlaneP1.getActionCost(), loadPlaneP2.getActionCost(), fly.getActionCost(), unloadPlaneP1.getActionCost(), unloadPlaneP2.getActionCost(), loadTruckP1.getActionCost(), loadTruckP2.getActionCost(), drive.getActionCost(), unloadTruckP1.getActionCost(), unloadTruckP2.getActionCost()};

     //HERE STARTS THE MECHANISM

     if(nodeStatus == startNode) {


        System.out.println("Old state parameters are " + "pkg1Location: " + state.getStateParameter1() + " pkg2Location: " + state.getStateParameter2() + " truckLocation: "+ state.getStateParameter3() + " planeLocation: " + state.getStateParameter4() + " cityLocation:"+ state.getStateParameter5());



                 for(int i = 0; acts[i].getActionCost() == getMinValue(costs); i++) {


                     //THIS IS THE PRECONDITION THAT IS NOT WORKING, DEFINED IN THE ACTION CLASS

                 if(acts[i].loadPlaneP1Precondition() == true) {

                     System.out.println("Precondition satysfied" + " with action name: " + acts[i].name);

                     if(acts[i].getActParameter1() != state.getStateParameter1()) {

                         state.setStateParameter1(acts[i].getActParameter1());
                     }

                     if(acts[i].getActParameter2() != state.getStateParameter2()) {

                         state.setStateParameter2(acts[i].getActParameter2());
                     }

                     if(acts[i].getActParameter3() != state.getStateParameter3()) {

                         state.setStateParameter3(acts[i].getActParameter3());
                     }

                     if(acts[i].getActParameter4() != state.getStateParameter4()) {

                         state.setStateParameter4(acts[i].getActParameter4());
                     }

                     if(acts[i].getActParameter5() != state.getStateParameter5()) {

                         state.setStateParameter5(acts[i].getActParameter5());
                     }
                 }

                         Node child = new Node(state, startNode, acts[i].getActionCost());


                        /*    List<Action> removeList = new ArrayList<Action>(Arrays.asList(acts));
                            removeList.remove(Arrays.asList(i));
                            acts = removeList.toArray(acts);*/


                         //nextAction = acts[i];

                         System.out.println("Costs array: "+  Arrays.toString(costs));
                         System.out.println("ActionID" +" " +  i);
                         System.out.println("The action choosen is " + acts[i].name);
                         System.out.println("State parameters updated are " + "pkg1Location: " + state.getStateParameter1() + " pkg2Location: " + state.getStateParameter2() + " truckLocation: "+ state.getStateParameter3() + " planeLocation: " + state.getStateParameter4() + " cityLocation:"+ state.getStateParameter5());

                     };




                     }  





            }

This is the main. The result that I obtain is

Old state parameters are pkg1Location: lhr pkg2Location: lhr truckLocation: cdg planeLocation: lhr cityLocation:london
Costs array: [30, 40, 100, 50, 55, 60, 60, 70, 40, 43]
ActionID 0
The action choosen is loadPlaneP1
State parameters updated are pkg1Location: lhr pkg2Location: lhr truckLocation: cdg planeLocation: lhr cityLocation:london       

This show that the precondtion is not satysfied and for this reason the state is not updated. The precondition that I developed is veryfied only if I define like this

public boolean loadPlaneP1Precondition() {

            if(Action.actParameter1 == State.pkg1Location[4]) {
                return true;
            }else {
                return false;
            }
    }

With this result

Old state parameters are pkg1Location: lhr pkg2Location: lhr truckLocation: cdg planeLocation: lhr cityLocation:london
Precondition satysfied with action name: loadPlaneP1
Costs array: [30, 40, 100, 50, 55, 60, 60, 70, 40, 43]
ActionID 0
The action choosen is loadPlaneP1
State parameters updated are pkg1Location: south pkg2Location: south truckLocation: south planeLocation: cdg cityLocation:paris

This means that the action that verify the precondition is loadTruckP2(the last of the array). But the action name printed is loadPlaneP1(the one that should be correct), updating differently that states parameter.

Why is this happening?

Coin flipping program only saying incorrect

I'm still new to Java, so apologies for the mess.

So a user would put in "heads" or "tails" into here:

System.out.println(labExample.headsOrTails("heads"));

And the program should randomly generate a heads or tails and also say whether or not your guess is correct. e.g. "Incorrect: you guessed heads and I flipped tails."

What I've made so far seems to only say that the guess is incorrect. Even when the guess matches. So I've definitely gone wrong somewhere, most likely the last few if/else statements.

public String headsOrTails(String guess) {
        String cointoss; //input and result
        String guessHeads = "heads"; //if guess == "heads"
        String guessTails = "tails"; //if guess == "tails"
        String coinHeads;
        String coinTails;
        String correct = "Correct: "; //if guess matches
        String incorrect = "Incorrect: "; //if guess doesn't match
        String result = ""; //end print of the result

            if (guess.equals("heads")) {
                guess = guessHeads;
            }
            if (guess.equals("tails")) {
                guess = guessTails;
            }

            if (Math.random() >= 0.5) {
                cointoss = " and I flipped heads";
                coinHeads = correct;
                coinTails = incorrect;
            }
            else {
                cointoss = " and I flipped tails";
                coinHeads = incorrect;
                coinTails = correct;
            }

            if ((coinHeads.equals(correct) && (guess.equals(guessHeads)))) {
                result = correct;
            }
            if ((coinTails.equals(correct) && (guess.equals(guessTails)))) {
                result = correct;
            }
            else result = incorrect; {

            }

        return result+"you guessed "+guess+cointoss;
    }

Any help or pointers would be amazing. Thanks.

How to return different array count in tableView numberOfRowsInSection in swift

I have tableView with one cell which contains one label.. i need to display different label text for different category. for that i have created empty iteamArray and i am trying to append iteamArray for different category using if condition. in the same way i need to return array count in numberOfRowsInSection but here i am unable to check if condition, it only goes out side return if i give return iteamArray.count then it displays all category values if i give return 0 it display nothing in tableview.

if i click water i need to show only water related iteamsArray in tabelview.. but here if i click any category it shows all category related values in tableview.. please help me in the code.

here is my code:

import UIKit

class PaymentTableViewCell: UITableViewCell{

@IBOutlet weak var pamntTypeLabel: UILabel!
}

class AllMakePaymentViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

var categoryName: String?
var iteamsArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    allPaymentService()
}
func allPaymentService(){

    let urlStr = "https://dev.com/webservices/api.php?rquest"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
        guard let respData = data else {
            return
        }
        guard error == nil else {
            print("error")
            return
        }
        do{
            let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
            //print("the all make payment json is \(jsonObj)")
            let billerdetailsArray = jsonObj["billerdetails"] as! [[String: Any]]

            for billerdetail in billerdetailsArray {
                self.categoryName = billerdetail["bcategoryname"] as? String

                if self.categoryName == "Water"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                    print("water arry \(self.iteamsArray.append(bName ?? ""))")
                }
                if self.categoryName == "Landline Postpaid"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                    print("Landline arry \(self.iteamsArray.append(bName ?? ""))")
                }
                if self.categoryName == "DTH"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                    print("DTH arry \(self.iteamsArray.append(bName ?? ""))")
                }
                if self.categoryName == "Electricity"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                    print("Electricity arry \(self.iteamsArray.append(bName ?? ""))")
                }
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        catch {
            print("catch error")
        }
    }).resume()
}
}

extension AllMakePaymentViewController: UITableViewDelegate, UITableViewDataSource {

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if categoryName == "Water"{
        return iteamsArray.count
    }
    if categoryName == "Landline Postpaid"{
        return iteamsArray.count
    }
    if categoryName == "DTH"{
        return iteamsArray.count
    }
    if categoryName == "Electricity"{
        return iteamsArray.count
    }
    return iteamsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PaymentTableViewCell
    cell.pamntTypeLabel.text = iteamsArray[indexPath.row]
    self.tableView.separatorStyle = .none
    return cell
}
}

Please help me in above code.

C# how to set a conditional statement to except user input?

I have a simple console App that converts pounds to kilograms and vice-versa. What I'm attempting to do is if the user enters lb then run the function to convert pounds to kilograms, else if the user enters kg, then run the function to convert kilograms to pounds.

During the setup part of the condition in main, I get an error "Use of unassigned local variable 'lb'

...The Code (snippets):

//method to convert KG to Lbs

public void ConvertKg()
        {
            Console.WriteLine("C# KG to LB program\n");

            Console.Write("Enter a number in KG: ");
            double kilograms = Convert.ToDouble(Console.ReadLine());

            double pounds = kilograms * 2.20462262185;
            Console.WriteLine(kilograms + " kilograms is " + pounds + " pounds");


        }

//method to convert Lbs to KG

 public void ConvertLb()
        {
            Console.WriteLine("C# LB to KG program\n");

            Console.Write("Enter a number  in lbs:");
            double pounds_userEntry = Convert.ToDouble(Console.ReadLine());

            double kilogram_userEntry = pounds_userEntry * 0.453592;
            Console.WriteLine(kilogram_userEntry + " kilograms is " + pounds_userEntry + " pounds");


        }

...main: string lb, kg; string userInput = "";

    Console.Write("Enter either lb or kg:");           

    if(userInput == lb) // where the error occurs
    {
        var k = new ConvertNumber();
        k.ConvertLb();
    }
    else
    {
        var l = new ConvertNumber();
        l.ConvertKg();

    }
    Console.ReadLine();

...the problem seems to be within the approach I'm using to set up the conditional statement to accept the user's input. ...could I get some help as to what I'm doing wrong?

How to use multiple conditions in an if statement

elif(mud == 1 and game_select == 'Mud + Fire' or game_select == 'Fire + Mud'):
        do something

The conditions that check game_select both work, but even if mud != 1 it still runs. How can i fix this?

Double If statement in windows Batch

I'll start with the code:

@echo off
set number=0

echo What would you like to add to %number%
echo 1. Add nothing
echo 2. Add 1
echo 3. Add number of your choosing

set /p test=

:: doesn't add any number
if "%test%" == "1" (
    echo You have choosen to not add anything
    pause
    goto end
)

::Adds number 1 to 0
if "%test%" == "2" (
    set /a number=number+1
    echo You have added 1 to the number
    goto end
)


::Gives choice to add 2 or 3 to number 0
if "%test%" == "3" (
    echo Which number would you like to add
    echo 1. Number 2
    echo 2. Number 3

    set /p option=

    ::Adds 2 to 0
    if "!option!" == "1"(
        echo You have added 2 to the number
        set /a number=number+2
        pause
    )

    ::Adds 3 to 0
    if "!option!" == "2"(
        echo You have added 3 to the number
        set /a number=number+3
        pause
    )
    goto end
)

:end
echo Your number is %number%
pause

This states the number as 0, and then gives you an option to add 0, 1, 2 or 3 to the number 0. I've done it this way so I can test out having an If statements inside of an if statement that asks for an input but I'm lost.

Adding 0 or 1 to number works fine, but as soon as you choose option 3 (wanting to add 2 or 3) it crashes.

I get the error: The syntax of the command is incorrect

I'm guessing it's a silly mistake, if you could point it out, that would be perfect.

excel VBA - inserting rows based on cell contents looped through all rows

I am trying to write a macro that tidies up and interrogates raw data exported from some analytical instrumentation. I would like it to look through one column (sample names) down all rows and look for indicators of specific sample types e.g. duplicates. Finding these indicators i want to insert a row, and in the new inserted row do some simple calculations based on the two rows above. For now i will just be happy getting the row insertion to work

Im a total newbie when it comes to VBA. I've brought a VBA for dummies book, but i'm struggling to see the light. I have cobbled together some code basically copied off google searches. I can get it to find the key word and insert 1 row, but it finds the first one and stops. There are multiple instances of these keywords in my data, and i want to insert a row below each

'original code - finds first keyword, inserts row and stops

Sub dup_finder()
    Dim colHeader As Range

    Set colHeader = Range("B1:B500")


Dim currCell As Range
Set currCell = Cells.Find("*_dup")

If Not currCell Is Nothing Then currCell.Offset(1, 0).EntireRow.Insert Shift:=xlDown


End Sub

'my attempt to include loop - inserts 500 rows below keyword! stops 
after first instance

Sub dup_finder()
Dim colHeader As Range
Dim row As Long
Dim currCell As Range

Set colHeader = Range("B1:B500")

Set currCell = Cells.Find("_dup")
        For row = 1 To 500
If Not currCell Is Nothing Then currCell.Offset(1, 0).EntireRow.Insert Shift:=xlDown

 Next row

End Sub

Want to use if else condition in selenium webdriver over locators

I have the following code to put in if else condition , my requirement is " if patient is established with practice then if portion executed , if not then else "enrollment request should sent".

public static void newPatient() {
     driver.findElement(By.xpath("//*[@id=\"ui-tabpanel-2\"]/div/ng-component/div[2]/p-dialog[1]/div/div[2]/div/div[2]/div/div[5]/div/div/div[1]/div[2]")).click();
     //Close tab
     driver.findElement(By.xpath("//*[@id=\"ui-dialog-19-label\"]/p-header/div/button[2]")).click();
 } 

 public static void establishedPatient(){
    //Select patient
     driver.findElement(By.xpath("/html/body/callingdr-app/apptemplate/div/div/div/page-tab/div/p-tabview/div/div/p-tabpanel/div/div/ng-component/div[2]/p-dialog[1]/div/div[2]/div/div[2]/div/div[2]/div/div/div[1]/div[1]")).click();
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     //Select appointment time with any doctor , here is Dr.Bella
     driver.findElement(By.xpath("/html/body/callingdr-app/apptemplate/div/div/div/page-tab/div/p-tabview/div/div/p-tabpanel/div/div/ng-component/div[2]/p-dialog[1]/div/div[2]/div/div[2]/form/div[3]/div/div[2]/div[5]/div/div[3]/div[11]/div/button")).click();
     //Give visit reason
     driver.findElement(By.xpath("/html/body/callingdr-app/apptemplate/div/div/div/page-tab/div/p-tabview/div/div/p-tabpanel/div/div/ng-component/div[2]/p-dialog[2]/div/div[2]/form/div/textarea")).sendKeys("Fever");
     //check checkbox
     driver.findElement(By.xpath("/html/body/callingdr-app/apptemplate/div/div/div/page-tab/div/p-tabview/div/div/p-tabpanel/div/div/ng-component/div[2]/p-dialog[2]/div/div[2]/div[3]/div[2]/p-checkbox/div/div[2]")).click();
     //Click on Request for an appointment button
     driver.findElement(By.xpath("/html/body/callingdr-app/apptemplate/div/div/div/page-tab/div/p-tabview/div/div/p-tabpanel/div/div/ng-component/div[2]/p-dialog[2]/div/div[1]/span[2]/p-header/div/button[1]")).click();
 }

Internationalization in the if statement

Tere is a dispute if i18n works in the case below

<ng-cointainer *ngIf="anything" i18n>Something to translate</ng-container>

according to one person, i18n won't work and it should look like this:

<ng-cointainer *ngIf="anything"><span i18n>Something to translate</span></ng-container>

My question is is there anythng wrong with the first way? If yes, then why it would not work?

How to use a while loop to find the opning and closing points

I'm new here.

I want do something like this: i need to find the index in which the condition is true the first time so to find an opening position this can be either on the positive or negative side (therefore i used the if else statement); so far it works, but hen when i found this position i want to store it in a table, but also use it to to find the next first position/index for which another condition is true (closing point). so in my example the first opening position is 387; to find the closing position i need to the first position for which is true that ratio >= m but also the index is greater than 387.; if i would do this right this position/index would be 1743 and this is what i should/need to use again to start over, what is the minimum value for which the condition of the opening position is true, but the index should be greater than 1743. It's quite a complicated question, but i mainly want to know, how can i arrange that the index 387; that in the else part for determining the closing position this index 387 is used as starting point, and then the 1743 is used to to check whether the first condition top part of the formula is true. This needs to be executed for the whole data set.


i <- starting_from

while (i <= length(retail_stocks$ratio)){
  if ((min(which((retail_stocks$ratio > (m + k*s))  == TRUE))) < (min(which((retail_stocks$ratio < (m - k*s)) == TRUE)))) {
  pos$open[i] <-  min(which(retail_stocks$ratio > (m + k*s)))
  i <- pos$open[i] 
if(min(which(retail_stocks$ratio <= m))){
    pos$close[i] <- (min(which(retail_stocks$ratio <= m)))
    i <- pos$close[i]
} else {
  pos$open[i] <- min(which(retail_stocks$ratio < (m - k*s)))
  #pos$close[i] <- min(which(retail_stocks$ratio >= m)) 
  i <- pos$open[i]
      if(min(which(retail_stocks$ratio >= m))){
    pos$close[i] <- (min(which(retail_stocks$ratio >= m)))
    i <- pos$close[i]
  }
}
}

NameError: free variable 'd' referenced before assignment in enclosing scope

I'm new to Python and I'm trying to know if code is possible :

chs = ch.split(' ')
d = { mot:ch.count(mot) for mot in chs if (mot not in d)}

These instructions aim to create a dictionary, based on my knowledge in other programming languages, I understand that count would be done every time a loop is iterated, so what I'm trying to do is to optimise and not do the count if the word is already counted.

Now the problem is that i get this error

NameError: free variable 'd' referenced before assignment in enclosing scope

which I totally understand, the variable d is not set yet.

So, what I'm looking for is to know if there is some temporary variable that has the values before enclosure.

mardi 29 octobre 2019

Multiple if conditions, without nesting

I have a sample piece of code below that I need some help on. The code sets the 'outcome' variable to False in the beginning and only should become True if all the 'if' conditions are met. Is there a more efficient way of doing this? I am trying to avoid nested 'if' statements.

Thanks!

    outcome = False

    while True:
        if a != b:
            print("Error - 01")
            break

        if a["test_1"] != "test_value":
            print("Error - 02")
            break

        if "test_2" not in a:
            print("Error - 03")
            break

        if "test_3" != "is long data string":
            print("Error - 04")
            break

        outcome = True
        break

how to display duplicate ID along with duplicate data in the python pandas

I have a data frame which looks below

k={'ID':[1,2,3,4,5,6],'Name':['John Danny','Micheal K','John Danny','jerred','John Danny','joe'],'phone':['1111',
                                                                                   '2222','2233','1111','2222','6666']}
df=pd.DataFrame(data=k)
df
    ID  Name       phone
    1   John Danny  1111
    2   Micheal K   2222
    3   John Danny  2233
    4   jerred      1111
    5   John Danny  2222

I need to find the duplicated in name and phone in the data frame so used the below-given code

df[df['Name'].duplicated(keep=False)].sort_values("Name")

duplicated based on name


ID  Name       phone
1   John Danny  1111
3   John Danny  2233
5   John Danny  2222

duplicated based on phone

    ID  Name       phone
    1   John Danny  1111
    4   jerred      1111
    2   Micheal K   2222
    5   John Danny  2222

but I want the result as follows

ID  Name      phone duplicated of name ids  duplicated of phone ids Duplicate_name  Duplicate_phone
1   John Danny  1111    3,5                    4                    Yes              Yes
2   Micheal K   2222                           5                     No              Yes
3   John Danny  2233    1,5                                          Yes              No
4   jerred      1111                           1                     No              Yes
5   John Danny  2222    1,3                    2                     Yes             Yes

I was able to find duplicate_name and duplicate_phone by using below code

df['Duplicate_name'] = df['Name'].duplicated(keep=False).map({True:'Yes', False:'No'})
df['Duplicate_phone'] = df['phone'].duplicated(keep=False).map({True:'Yes', False:'No'})

The problem is was not able dispaly ID in duplicated of phone ids and duplicated of name ids as above given result table how to do it?

How To set `session` in ajax and use the `session` in if-statement

I want to make a session in ajax but i have not found the solution and use the session in if-statement

I have already to make a session on controller and pass to javascript script but the method is doesn't work

controller when i set the session and want pass to js function

public function set_session_js($kelas) { return $this->session->set_userdata('kelas', $kelas); }

Script JS

function load_data() {
        $('.view_data').click(function() {
            var id = $(this).attr('data-id');
            $.ajax({
                type: "GET",
                url: "<?= site_url('request/get_modal') ?>",
                dataType: "JSON",
                data: {
                    id: id
                },
                success: function(data) {
                    var output = "";

                    for (var index in data) {
                        if (data.hasOwnProperty(index)) {
                            $('#ModalShow').modal({
                                backdrop: 'static',
                                keyboard: true,
                                show: true
                            });
                            output += "<tr data-id='" + data[index]['id_form'] + "'>";
                            output += "<td data-id='" + data[index]['id_form'] + "'>" + data[index]["name_item"] + "</td>";
                            output += "<td>" + data[index]["quantity"] + " " + data[index]["satuan"] + "</td>";
                            output += "<td>" + data[index]["date_process"] + "</td>";
                            output += "<td>" + data[index]["quantity_proses"] + " " + data[index]["satuan"] + "</td>";
                            output += "<td>" + data[index]["progres_by"] + "</td>";
                            output += "<td>" + data[index]["progres"] + "</td>";
                            output += "<td>";
                            // Buat Kondisi Status
                            if (data[index]['states'] == 'On Process') {
                                output += "<label class='label label-primary'>" + data[index]["states"] + "</label>" + "</td>";
                            } else if (data[index]['states'] == 'Pending') {
                                output += "<label class='label label-warning'>" + data[index]["states"] + "</label>" + "</td>";
                            } else {
                                output += "<label class='label label-success'>" + data[index]["states"] + "</label>" + "</td>";
                            }
                            // Buat Kondisi Hak Edit dan Hapus
                            if (data[index]['states'] == 'On Process') {
                                $.get('request/set_session_js/' + kelas, function (result) {
                                    console.log(result)
                                })
                            } else if (data[index]['states'] == 'Pending') {
                                output += "<td style='text-align:center'>" +
                                    "<a href='javascript:;' class='edit' data-id='" + data[index]['id_form'] + "'><i class='fa fa-edit'></i></a>" + " | " +
                                    "<a href='javascript:;' class='hapus' data-id='" + data[index]['id_form'] + "'><i class='fa fa-trash'></i></a>" + " | " +
                                    "</td>";
                            }
                            output += "</tr>";
                        }
                    }
                    $("#show_data").html(output);
                }
            });
        });
    }

I hope that the session can be called and want to use the session in an if-statement

How do you interpret this code correctly step by step? (New to programming)

My problem is that I dont know how the compiler runs through the different if statements correctly and why he skips some in this case.

I tried checking if the conditions from start to bottom are true or false and thus find the correct output of the program. But why doesnt the program output 84 here:

if (a > c) cout << 84;
else cout << 48

Full Program:

int main()
{
  constexpr int a{8};
  constexpr int b{4};
  constexpr int c{1};

  if (a < b < c)
    if (c > b > a)
      if (a > c) cout << 84;
      else cout << 48;
    else
      if (b < c) cout << 14;
      else cout << 41;
  else
    if (b < a < c)
      if (a < c) cout << 81;
      else cout << 18;
    else
      if (b < c) cout << 17;
      else cout << 71;

  return 0;
}

The program outputs only 41. Why?

Using "or" in an "if" statement in Try and Except in Python

I want to make the loop continue and catch errors like entering "bob" as an input or integers less than 1 and greater than 4.

salesNum = input("How many sales persons to process? ")
for num in salesNum:
    salesName = input("Enter Salesperson Name: ")
    salesLevel = 0
    while salesLevel == 0:
        try:
            salesLevel = int(input("Enter Salesperson Level: "))
            if salesLevel < 1 or salesLevel > 4:
                print("error, try again.")
                salesLevel = int(input("Enter Salesperson Level: "))
        except ValueError:
            print("error, try again")
            continue
    hoursWorked = float(input("Enter Hours Worked: "))
    salesAmount = float(input("Enter Number of Sales: "))
print("Clear")

It works fine if I make one error, but multiple errors don't get caught and the program moves on to the next questions. I have tried breaking the if statement up, but that doesn't solve the issue.

Are my if statements messing up with my menu?

I created a fishing game with a menu.A user simply enters a letter to do that option.However when I try to access the code under the corresponding if statement, for some reasons it either skips it or displays high score stats. I tried changing the letters to see if that was the issue that didn't work. Maybe its the way im comparing the user input string (im using .equals) or maybe its a bigger issue I don't see. In short my if statements arnt working as a menu and some if statements such as my r to 'ready up' for fishing dosnt do anything. Or my u to 'purchase upgrades' for the fishing rod.

//Intense Fishing Simulator 2019
//2019-10-29
//Ormim Bari
//to practice the usage of realtionships.
package com.mycompany.intensefishingsimulator2019_ormimbari;

 import java.io.*;

public class DriverClass 
{
    public static void main (String args[]) throws IOException
    {
        BufferedReader MyInput=new BufferedReader (new InputStreamReader(System.in));

        Fisher joe = new Fisher(); //creates the fisher

        System.out.println("Welcome to Intesne Fishing Simulator 2019");
        System.out.println("You join fisher Joe's in the intense world of Fishing");
        int money=0;
        int endGame=0;
        boolean purchase1=false;//if purchased firsst upgrade
        boolean purchase2=false;//if purchased last upgrade
        do
        {
            //menu
            System.out.println("Enter r when ready to catch a fish");
            System.out.println("Enter c to see total of cash earned");
            System.out.println("Enter f to see total amount of fish caught");
            System.out.println("Enter u to upgrade your fishing rod");
            System.out.println("Enter joe to see stats");
            System.out.println("Enter Exit to end game ");

            String strInput=MyInput.readLine(); //gathers ihnput

            //ends game
            if (strInput.equals("Exit"))
            {
                endGame=999;
            }
            //display hp and fishing rod damage
            if (strInput.equals("joe"))
            {
                strInput="";
                System.out.println("Joe has a total hp of " +joe.getHp());
                System.out.println("Joes fishingrod does a total of "+joe.fr.getDamage() +" damage");

            }
            //display career total of fish caught
            if (strInput.equals("f"));
            {
                strInput="";
                System.out.println("You caught a total of"+joe.GetCatches()+"fishes");

            }
            //display career total of cash earned
            if (strInput.equals("c"));
            {
                strInput="";
                System.out.println( "You earned a total of $"+joe.getCashTotal());

            }
            if (strInput.equals("u"))
            {

                if (purchase1==false)
                {
                    System.out.println("Welcome to the shop! The first upgrade is $30. To buy enter b");
                    strInput=MyInput.readLine();
                    if (strInput.equals("b"))
                    {
                        strInput="";
                       boolean sucess= joe.fr.Upgrade1(money, joe, joe.fr);
                       if (sucess==true)
                       {
                           purchase1=true;
                       }
                    }
                }
                if (purchase1==true)
                {
                    System.out.println("Welcome to the shop! The last upgrade is $50. To buy enter b");
                    strInput=MyInput.readLine();
                    if (strInput.equals("b"))
                    {
                        strInput="";
                       boolean sucess= joe.fr.Upgrade2(money, joe, joe.fr);
                       if (sucess==true)
                       {
                           purchase2=true;
                       }
                    }
                }
                if (purchase2==true)
                {
                    System.out.println("You purchased all the upgrades");
                }
            }
            //user chooses to 'ready up' to fish
            if (strInput.equals("r"))
            {
                strInput="";
                int endFishing=0;

                //creation of fish to fight
                Fish fish= new Fish();

                //ceratopm of all fish 
                TunaFish tf= new TunaFish(); 
                SilverCarp sc= new SilverCarp();    
                Shark shark= new Shark();

                //intro
                System.out.println("You have been approached by a " + fish.getType());
                do
                {
                    //instructions
                    System.out.println("Enter a to attack the fish or r to run away");
                    strInput=MyInput.readLine(); 
                    //if chosing to run away
                    if (strInput.equals("r"))
                    {
                        strInput="";
                        boolean sucess;
                        sucess=joe.RunAway();
                        //if sucesfull
                        if (sucess==true)
                        {
                            joe.RunAwaySucess(joe);
                            endFishing=999;
                        }
                        //if joe failed to runaway
                        if (sucess==false)
                        {
                            //if tuna
                            if (fish.getType().equals("Tuna Fish"))
                            {   

                                boolean damageGiven= tf.AttackChanceTuna();
                                //if tuna dosnt miss
                                if (damageGiven==true)
                                {
                                    //joe gets the damage 
                                    joe.HarmJoe(tf.returnTunaDamage());
                                    System.out.println("Joe has been harmed by the tuna for "+ tf.returnTunaDamage());
                                    System.out.println("Joe now has" + joe.getHp());

                                    //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999; //ends game
                                    }
                                }
                            }

                            //if carp
                            if (fish.getType().equals("Silver Carp"))
                            {
                                boolean damageGiven= sc.AttackChanceCarp();
                                //if carp dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(sc.returnCarpDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ sc.returnCarpDamage());
                                    System.out.println("Joe now has" + joe.getHp());
                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999; //ends game
                                    }
                            }
                            //if shark
                            if (fish.getType().equals("Shark"))
                            {
                                boolean damageGiven= shark.AttackChanceShark();
                                //if shark dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(shark.returnSharkDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ shark.returnSharkDamage());
                                    System.out.println("Joe now has" + joe.getHp());


                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999; //ends game
                                    }
                            }

                        }

                    }
                    //if attacking
                    if (strInput.equals("a"))
                    {
                        strInput="";
                        //tells user it did attack
                        fish.HarmFish(joe.fr.getDamage());
                        System.out.println("Joe has hurt " + fish.getType()+ "for "+ joe.fr.getDamage()+"damage");

                         //if tuna
                            if (fish.getType().equals("Tuna Fish"))
                            {
                                //damage the tuna
                                tf.harmTuna(joe.fr.getDamage());

                                boolean damageGiven= tf.AttackChanceTuna();
                                //if tuna attacks
                                if (damageGiven==true)
                                {
                                    //joe gets the damage if true
                                    joe.HarmJoe(tf.returnTunaDamage());
                                    System.out.println("Joe has been harmed by the tuna for "+ tf.returnTunaDamage());
                                    System.out.println("Joe now has" + joe.getHp());

                                    //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999;
                                    }
                                    //if tuna dies
                                    if (tf.getTunaHp()<=0)
                                    {
                                        //reward screen output
                                        System.out.println("You beat the tuna!You got " + tf.fl.getLootType());
                                        System.out.println("You sold the " + tf.fl.getLootType()+ "for $" + tf.fl.getLootPrice());
                                        joe.increaseCash(tf.fl.getLootPrice());
                                        System.out.println("You now have $" + joe.getMoney()); //cash update
                                        tf.healTuna();//reset for next potential round
                                        joe.CareerCashTotal(tf.fl.getLootPrice()); //add to highscore
                                        joe.addCatches(); // add to high score
                                        endFishing=999; //stops the fishing
                                    }
                                }
                            }

                            //if carp
                            if (fish.getType().equals("Silver Carp"))
                            {
                                //damages the tuna
                                sc.harmCarp(joe.fr.getDamage());
                                boolean damageGiven= sc.AttackChanceCarp();
                                //if tuna dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(sc.returnCarpDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ sc.returnCarpDamage());
                                    System.out.println("Joe now has" + joe.getHp());
                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999;
                                    }
                                    if (sc.getCarpHp()<=0)
                                    {
                                         //reward screen output
                                        System.out.println("You beat the silver carp!You got " + sc.fl.getLootType());
                                        System.out.println("You sold the " + sc.fl.getLootType()+ "for $" + sc.fl.getLootPrice());
                                        joe.increaseCash(sc.fl.getLootPrice());
                                        System.out.println("You now have $" + joe.getMoney()); //upgrade cash
                                        sc.healCarp();//reset for next potential round
                                        joe.CareerCashTotal(sc.fl.getLootPrice()); //add to high score
                                        joe.addCatches(); //add to high score
                                        endFishing=999; //stops the fishing
                                    }
                            }
                            //if shark
                            if (fish.getType().equals("Shark"))
                            { 
                                //harms the shark
                                shark.harmShark(joe.fr.getDamage());
                                boolean damageGiven= shark.AttackChanceShark();
                                //if shark dosnt miss
                                if (damageGiven==true)
                                {
                                    //harms joe
                                    joe.HarmJoe(shark.returnSharkDamage());
                                    System.out.println("Joe has been harmed by the silver carp for "+ shark.returnSharkDamage());
                                    System.out.println("Joe now has" + joe.getHp());


                                }
                                //if joe dies
                                    if (joe.getHp()<=0)
                                    {
                                        joe.EndGame(joe);
                                        endGame=999;
                                    }
                                //if shark dies
                                if (shark.getSharkHp()<=0)
                                    {
                                        //reward screen output
                                        System.out.println("You beat the Shark!You got " + shark.fl.getLootType());
                                        System.out.println("You sold the " + shark.fl.getLootType()+ "for $" + shark.fl.getLootPrice());
                                        joe.increaseCash(shark.fl.getLootPrice());
                                        System.out.println("You now have $" + joe.getMoney()); //updatees cash
                                        shark.healShark();//reset for next potential round
                                        joe.CareerCashTotal(shark.fl.getLootPrice()); //adds to high score
                                        joe.addCatches(); //adds to high score
                                        endFishing=999;
                                    }
                            }

                        }

                } while (endFishing!=999);
            }



        }while (endGame!=999);

        System.out.println("Thanks for joining Joe in the world of Intense Fishing ");


    }



}

how do I use operational operators with 3 variables?

I have 3 input fields with text. I want to use an if statement with logical operators to check if any of the input fields are blank, but I can't use or(||) for the 3 variables.

What is the right way to use logical operators?

let name = $("#name").val();
let email = $("#email).val();
let color = $("#color).val();

if(name == '' && ( email == '' || color == '') {
  console.log("please complete form");
 }
else {
//submit data
}

the code works as desired if I leave the name field blank, but because name is true the if statement accepts it. How can I make it so the if statement checks if any of the input fields are blank?

elif statement name checker

i am new to python and running into something super silly. While trying to run an elif statement i am getting some errors. not sure what is it that I am doing wrong.

if name == 'Alice':
       print('Hi Alice!)
    elif age < 12:
         print('You are not Alice, kiddo.')

When i run this in terminal I get the error.

NameError: name 'Alice' is not defined

I know that I can define name at the top on the lines

name = input('What is your name: ')

So that it will ask me for the name and it is defined as well.

But I enter the name != Alice say Alan. It throws this error

NameError: name 'age' is not defined

I want the elif clause to execute immeditely if age < 12 is True and name == 'Alice' is False. Not sure where am i going wrong.

How to keep a specif column based on row conditions?

Does someone knows how to get the next followed structure in Pandas?

I have a Pandas data frame that looks like this

ID  VAR1  VAR2  VAR3  VAR4  VAR5

1    TT    TG    .01  .09   .90
2    CC    TC    .20  .34   .56
3    GG    AG    .10  .20   .70
4    TC    TC    .17  .48   .35
5    AG    AG    .12  .46   .32
6    GG    TG    .15  .20   .65
7    TT    TC    .06  .24   .70
8    TT    CT    .11  .21   .68 
9    GT    GT    .05  .10   .85
  1. If the first 'letter' in [VAR2] (e.g T) it is doubled in [VAR1] (e.g. TT) -> take value from VAR3 (.01).
  2. If the combination of the letters in [VAR2] (e.g. TC) it is the same as in [VAR1] (e.g. TC) -> take value from VAR4 (.48).
  3. If the second 'letter' in [VAR2] (e.g G) it is doubled in [VAR1] (e.g GG) -> take value from VAR5 (.70).

Based on this information I would like my output data frame to look as follow:

ID  VAR1  VAR2   VAR6 

1    TT    TG    .01
2    CC    TC    .56
3    GG    AG    .70
4    TC    TC    .48
5    AG    AG    .46
6    GG    TG    .65
7    TT    TC    .06
8    TT    CT    .68
9    GT    GT    .10

Hopefully someone can give me a hint!

Thanks,

Ale.