lundi 31 octobre 2016

for loop and if loop in R. Reference/print other column

df <-

      Name      DDay
1    Item1      5
2    Item2      3
3    Item3      3
4    Item4      1
5    Item5      1
6    Item6      1

Logic is:
For (i in seq(from=0, to=5, by=1){
If Dday == i
Print Corrensponding Name (Targets)

I've tried

for (i in seq(from=0, to=5, by=1)){
if(df$Dday == i){
print(df$Name)
}

Full of errors. How can I write this logic in R code?

Thank you.

Checking for enumeration equality is not working

I am having trouble getting the program to print either "Fruit", "Drink", or "Unknown" (followed by a newline) depending on the value of userItem. I have also tried switching (userItem == x) to (GroceryItem == x) and still no luck. I am stuck understanding on what my error is.

My Code:

import java.util.Scanner;

public class GrocerySorter {
   public enum GroceryItem {GR_APPLES, GR_BANANAS, GR_JUICE, GR_WATER};
      public static void main (String [] args) {

      GroceryItem userItem = GroceryItem.GR_APPLES;

      if (userItem == GR_APPLES) {
          System.out.println("Fruit"); 
      }
      else if (userItem == GR_BANANAS) {
         System.out.println("Fruit"); 
      }
      else if (userItem == GR_JUICE) {
        System.out.println("Drink"); 
      }
      else if (userItem == GR_WATER) {
        System.out.println("Drink"); 
      }
      else {
        System.out.println("Unknown");
      }

      return;
   }
}

Errors:

GrocerySorter.java:9: cannot find symbol
symbol  : variable GR_APPLES
location: class GrocerySorter
      if (userItem == GR_APPLES) {
                      ^
GrocerySorter.java:12: cannot find symbol
symbol  : variable GR_BANANAS
location: class GrocerySorter
      else if (userItem == GR_BANANAS) {
                           ^
GrocerySorter.java:15: cannot find symbol
symbol  : variable GR_JUICE
location: class GrocerySorter
      else if (userItem == GR_JUICE) {
                           ^
GrocerySorter.java:18: cannot find symbol
symbol  : variable GR_WATER
location: class GrocerySorter
      else if (userItem == GR_WATER) {
                           ^
4 errors

Why does this Not decrement "count" properly

I would've just posted the code, but this website decided to give me the finger just like my code.

How to store 2 variables and compare them

I am trying to accept user input for two people's hourly wage and the amount of hours of overtime they work per year.

using an algorithm I have researched, the program will tell both people the amount of money they make per year and the amount of taxes they pay, which is based on the amount that they make.

This is all fine and dandy. However, what I am now trying to do is to add a line at the end of the program which states who is paying more taxes. This would be accomplished with the method whoPaysMoreTaxes, but I have no idea what to include in that method. I know I would need a simple if/ else if/ else statement to get the job done, but I do not know how I would go about storing the taxes of person 1 and the taxes of person 2 and compare them. The output should be as follows I believe. The numbers 22, 100, 58, and 260 are user input:

Person 1's hourly wage: 22
Person 1's overtime hours for the year: 100
You will make $45540 this year
And you will pay $9108 in taxes
Person 2's hourly wage: 58
Person 2's overtime hours for the year: 260
You will make $133980 this year
And you will pay $40194 in taxes.
Person 2 is paying more taxes.

The issue I am having is finding a way to produce that final line that says who is paying more taxes.

public class conditionalsAndReturn
{
   public static void main(String[] args)
   {
       Scanner console = new Scanner(System.in);
       taxes(console, 1);
       taxes(console, 2);
   }
   public static void taxes(Scanner console, int personNum)
   {
      System.out.print("Person " + personNum + "'s hourly wage: ");
      int wage = console.nextInt();
      System.out.print("Person " + personNum + "'s overtime hours for the year: ");
      double totalOvertimeHours = console.nextInt();        
      int salary = annualSalary(wage, totalOvertimeHours);
      System.out.println("You will make $" + salary + " this year");
      System.out.println("And you will pay $" + taxation(salary) + " in taxes");
      System.out.println();   
   }

   public static int annualSalary(int wage, double totalOvertimeHours)
   {
      double workHoursPerWeek = 40 + totalOvertimeHours / 48;
      return (int)(weeklyPay(wage, workHoursPerWeek) * 48); 
    } 

   public static double weeklyPay(int wage, double workHoursPerWeek)
   {
       if (workHoursPerWeek > 40)
       {  
           return (wage * 40) + ((wage + wage / 2.0) * (workHoursPerWeek - 40));    
       }
       else
       {
          return wage * workHoursPerWeek;  
       }
    } 

   public static int taxation(int salary)
   {
       if (salary < 20000)
       {
           return 0;
       }
       else if (salary > 100000)
       {
           return salary * 3 / 10; 
       }
       else
       {
           return salary * 2 / 10;
       }
   }

  public static String whoPaysMoreTaxes(
}

How to set form input data to equal specific strings in a PHP If Else Statement? [duplicate]

This question already has an answer here:

I'm having trouble with this for some reason. Basically i'm trying to make it so that one person can go through. If the users name is equal to "Megan" "Renae" then the output will be Hello, "Megan" "Renae" but if there is anything else I want it to output I do not know you. I know this is probably something extremely simple and it is just going over my head but if someone could help you would stop my hair from turning grey! Thank you in advance to anyone that responds.

<form method = "POST" action = " ">
<p>Please enter your first name: <input type="text" name="fName"><br>
<p>Please enter your last name: <input type="text" name="lName"><br><br>
<input type="submit" class="btnSubmit"  name="submit"></p>
</form>

<?php
if ($_POST['submit'] != "") {
if ($_POST['fName'] = "Megan") {
 if ($_POST['lName'] = "Renae") {
 echo "<p>Hello, Megan Renae</p>"; }
else {
echo "<p>I do not know you</p>";     
}}}
?>

Netsuite Advanced PDF/HTML code item fulfilments

We have a template for item fulfilments that only works for the first 2 scenarios, (1 Complete & 2 partial);

1 Complete fulfilment for Sales Orders

  • 1st fulfilment (shows all SO items, shows all as shipped)

2 Partial fulfilments for Sales Orders

  • 1st fulfilment (shows all SO items, shows qty shipped + qty backorders)

  • 2nd/final fulfilment (shows remaining SO items, shows qty shipped)

3 (or more) Partial fulfilments for Sales Orders - PROBLEM SCENARIO

  • 1st fulfilment (shows all SO items, shows qty shipped + qty backorders)

  • 2nd fulfilment (shows all SO items, shows qty shipped + qty backorders)

  • etc. other partial shipments, same as above

  • Final fulfilment (shows remaining SO items, shows qty shipped)

Any order that has 3 or more partial shipments does not work. So, I want to completely re-write the list-item section of our fulfilments but I need some help with the code. This is the basic outline of what we need;

<#if record.item?has_content>

<#list record.item as item>
<#list salesorder.item as tranline>
<#if tranline.line==item.orderline>
<tr>
    <!-- item ID         --><td>${tranline.item}</td>
    <!-- U.O.M           --><td><#if tranline.units=="">Unit<#else>${tranline.units}</#if></td>
    <!-- Sales Order Qty --><td><#if tranline.quantityfulfilled==tranline.quantity>${item.quantity?c}<#else />${tranline.quantity?c}</#if></td>
    <!-- Fulfilled Qty   --><td>${item.quantity?c}</td>
    <!-- Backorder Qty   --><td><#if (tranline.quantity-tranline.quantityfulfilled)?int==0>&nbsp;<#else />${(tranline.quantity-item.quantity)?int}</#if></td>
    <!-- Column Spacing  --><td>&nbsp;</td>
    <!-- Item Description--><td>${item.description}</td>
</tr>

<!-- Items Unfulfilled/On Backorder -->
<!-- this is what I need help with -->
<!-- table layout set out similar to above -->
<!-- but including the header before list -->
<th>The following items are on Backorder:</th>
 <tr>
        <td><!-- item ID         --></td>
        <td><!-- U.O.M           --></td>
        <td><!-- Sales Order Qty --></td>
        <td><!-- column spacing  --></td>
        <td><!-- Backorder Qty   --></td>
        <td><!-- column spacing  --></td>
        <td><!-- Item Description--></td>
    </tr>

User default if statements not working

There seems to be something wrong with one of my if statements. Can anyone tell me why error is getting printed?

func getRecordToUpdate(_ locations:CLLocation)
        {
            if defaults1.object(forKey: "locationData") == nil{
                defaults1.set("yes", forKey: "locationData")
            }else{
                print("error")
                    if let loadedData = UserDefaults.standard.data(forKey: "locationData") {
                    if (NSKeyedUnarchiver.unarchiveObject(with: loadedData) as? String) != nil
                    {
                       print("good")
                    }
               }
          }
    }

This if statement is adding itself to the next row

Image showing row issue

This is adding the previous rows rating query every time a new row is displayed any ideas as to why its doing this? Have I failed to close the loop in some way?

Please help I have limited SQL, IF statement knowledge and it has been ruining my mind for days now

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


$sql = "SELECT sailors.id, sailors.habbo, ranks.rank, ranks.abv, rating.ratingabv, rating.rating, position.position FROM (((sailors INNER JOIN ranks ON sailors.rankid = ranks.rankid) INNER JOIN rating ON sailors.ratingid = rating.ratingid) INNER JOIN position ON sailors.pos_id = position.pos_id) WHERE sailors.rankid=30";
$result = $conn->query($sql);



if ($result->num_rows > 0) {
     // output data of each row
     echo"<div class='col-md-12'> <h1>W-5 Chief Warrant Officer Five (CWO5)</h1></div>";
     while($row = $result->fetch_assoc()) {

       $ast_query = $conn->query("select ast_list.ast_tag from (ast_list INNER JOIN ast ON ast.ast_id = ast_list.ast_id) where ast_sailor_id = '" . $row['id'] . "'");
       $str_ast = '';

          $last_promo = $conn->query("select promo.date, sailors.habbo, promo.promo_officer_id, sailors.id FROM (promo INNER JOIN sailors ON sailors.id = promo.promo_officer_id) WHERE promo_sailor_id = '" . $row['id'] . "' ORDER BY promoid DESC LIMIT 1");
          $str_promo = '';

          $last_promo3 = $conn->query("select promo.date, sailors.habbo, promo.promo_officer_id, sailors.id FROM (promo INNER JOIN sailors ON sailors.id = promo.promo_officer_id) WHERE promo_sailor_id = '" . $row['id'] . "' ORDER BY promoid DESC LIMIT 1");
          $str_promo3 = '';

          $last_promodate = $conn->query("select promo.date, sailors.habbo FROM (promo INNER JOIN sailors ON sailors.id = promo.promo_officer_id) WHERE promo_sailor_id = '" . $row['id'] . "' ORDER BY promoid DESC LIMIT 1");
          $str_promo2 = '';

         $rating_query = $conn->query("SELECT sailors.id, sailors.habbo, ranks.rank, ranks.abv, rating.ratingabv, rating.rating, position.positionabv, position.position FROM (((sailors INNER JOIN ranks ON sailors.rankid = ranks.rankid) INNER JOIN rating ON sailors.ratingid = rating.ratingid) INNER JOIN position ON sailors.pos_id = position.pos_id) WHERE sailors.id = '" . $row['id'] . "'");
       $str_rating = '';

          while($promo_array = $last_promo->fetch_assoc()){
              $str_promo .= $promo_array['habbo'];
          }
          while($promo_array2 = $last_promo3->fetch_assoc()){
                   $str_promo3 .= $promo_array2['id'];
       }

       while($promo_array2 = $last_promodate->fetch_assoc()){
                    $str_promo2 .= $promo_array2['date'];

       }


       while($ast_array = $ast_query->fetch_assoc()){
         $str_ast .= $ast_array['ast_tag'];
       }
         if ($ast_query->num_rows > 0) {
         $text  = "(" . $str_ast . ")";
} else { 
    $text = "";
} 

       while($rating_array = $rating_query->fetch_assoc()){

         $str_position .= $rating_array['positionabv'];

       }


         if ($row['position'] == "None"){

         $rating  = "". $row["ratingabv"]. "";
} else { 

    $rating = "/" . $str_position . "";
} 


                    echo " 
                    <div class='col-md-4'><div class='panel panel-default'>
                    <div class='panel-heading'>
                        <h4 class='text-white'><center><b>". $row["habbo"]. "</b></center></h4>
                    </div>

                    <div class='panel-body'>
                    <center>
                    <a href='sailor.php?id=". $row["id"] ."'>
                        <img class='img-responsive'  src='http://ift.tt/2eNO2IK". $row["habbo"]. "&direction=2' alt=''>
                        </a></center><br>
                        <center><p><b>USN: " . $row["abv"] . "" . $rating . "




                         " . $text . "</b>

                        <center><small>Last promoted by <a href='sailor.php?id=". $str_promo3 ."'>" . $str_promo . "</a> <br>  " . $str_promo2 . "</small></center>
                         <p></center>

                    </div>
                </div></div> ";

     }
} else {
     echo "";
}

$conn->close();
?>

Angular 2: if attr.title in html == array in component

<div class="kalender">
    <table *ngIf="datoer">
        <tr>
            <td *ngFor="let cell of ukeEn()" 
                [attr.title]="cell.id"></td>
                </div>
        </tr>
    </table>
</div>

I would like to check if attr.title (or cell.id) == any of the elements in an array called 'datoer', which is defined in my component. So I need to check the attr.title up against every value in the 'datoer' array. Then I want to add an element (for ex. 'div' or 'p') in the 'td' if this condition is true.

Is this possible? If you need more code samle to understand my problem, just ask.

Swift: Why I am not able to execute the following if-statement when comparing two strings

So I am developing this app, where there is a textfield, and when you write on it, it is taken to the next SecondviewController. However, if nothing is written on the textfield and you press "Done" button, it should give you an error.

For this I have made an IBOutlet for the NSTextField as this:

@IBOutlet var weblinklabel: NSTextField!

Then this 'done' button contains an IBFunction with the following if statement:

@IBAction func actionWeblinklabel(_ sender: Any) {

    if weblinklabel != "" {
    self.view.window?.close()
    } else {
    label1.isHidden = false
    }

Whatever is written in webllinklabel should be compared with an empty string, if weblinklabel has something in it then it should just close the current viewController otherwise it should give me a label (label1).

When I do this, I get this error:

Binary operator '!=' cannot be applied to operands of type 'NSTextField!' and 'String'

What am I doing wrong with my code. Thanks in advance! :)

Why isn't my python shell indenting automatically?

I've been given a question:

Write a piece of Python code that prints out one of the following messages:

"string involved" if either varA or varB are strings

"bigger" if varA is larger than varB

"equal" if varA is equal to varB

"smaller" if varA is smaller than varB


Here's my solution:

if type(VarA) == str or type(VarB)==str:
    print("string involved")
elif varA>varB:
    print("bigger")
elif varA==varB:
    print("equal")
else:
    print("smaller")

This looks exactly the same as the given answer, but it is incorrect, and I think it has something to do with my indentation. For some reason, after the if statement on the first line, the shell doesn't automatically indent the next line automatically. Why is this? I had to press TAB after each line. Also, what exactly is wrong with the code that I've written?

Different strings in if statement

Anyone know how to check similar strings in the if...else statement?

My code below is to check whether a user is in the custom restricted permission group so the system can allow/decline the access.

if ((myMemberships.indexOf(Sitetitle + "  Restricted  Readers")>=0) {
        oInstance.model.dcn[0]._recordSet[i].isMember=false;

But I want to write an array that will store different string combinations of Sitetitle + " Restricted Readers" such as SiteTitle restricted reader(s), SiteTitleRestrictedReader(s), SiteTitle restrict reader(s). So I can prevent administrators typing the group name wrong when they create the group name, and eventually cause the code fail.

LINQ to SQL: if statement in select

in c# i want to return IEnumerable with column with name isedit

my type of innerResult is IEnumerable

but i have error Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

 innerResult = (from f in innerResult

                                   select new
                                   {

                                      isedit =  (bool?)Convert.ToBoolean(((APS_WorkFlow_Activities).Contains(f.Field<Guid>("ActivityID")) ? false : true))
                                   });

My if statement "between" is giving me wrong result

I am new here. I have a problem with my if/else if statement.

I got this:

  if (unalumno.notas >= "90" && unalumno.notas <= "100") {
      unalumno.notas = "A";
  } else if (unalumno.notas >= "80" && unalumno.notas <= "89") {
      unalumno.notas = "B";
  } else if (unalumno.notas >= "70" && unalumno.notas <= "79") {
      unalumno.notas = "C";
  } else if (unalumno.notas >= "60" && unalumno.notas <= "69") {
      unalumno.notas = "D";
  } else if (unalumno.notas <= "59") {
      unalumno.notas = "F";
  }

All the else if statement is giving to me the right result in letters, but the first if continue giving the result in numbers. Hope can understand me. Sorry for english lol

Have a good day

Is there a limit to how many "OR" conditions I can enter in PHP?

Ok so I have a block of code in WordPress that has "OR" conditions inside of the "elseif" statement. here is the code:

   <?php } elseif($index == 1 || $index == 8 || $index == 9 || $index == 16 || $index == 17 || $index == 20 || $index == 21) { ?>

So the code works great up until $index == 20 || $index == 21

Is there a limit on how many times I can use || in the elseif statement?

LINQ to SQL : assign column alias name and set value

this linq must create column with name isedit and value false but it doesn't create

innerResult.Select(f => new
                         {
                             isedit  = false
                         });

Apply function only if columns respect condition

I’m new to R and i’m trying to learn fundamentals. I’m facing a small problem for which i can’t find a solution online.

What i want to do: write a function to lower case for all the columns in my data.frame if they respect a condition (class = factor)

This code works, but for all my columns :

lower = function(x) {data.frame(tolower(as.matrix(x)))}

I need more something like this, but it doesn’t work:

lower = function (x) { for (i in 1:length(x)) {
 if (class(i)=="factor") {
   data.frame(tolower(as.matrix(x))) 
 }
}}

x is my data.frame

Thank you

Y.P

How would one find and return Google sheets?

Hey guys I'm really new to sheets so thanks for the help! I'm working on some inventory data where I need to differentiate between left hand and right hand products. Basically I want to find a certain character in an cell, and if true it will return Left Handed or Right Handed or nothing if it doesn't apply. The return value would appear on a different cell. I'm trying something like this, hope it makes sense:

IF(FIND(" lh",a1)), Left Handed, "")

I want if cell has character (space)lh, true renturn Left Handed, false return blank. I had a different variation of the aforementioned formula yesterday where it worked in returning left Handed but got #Value! when " lh" was not in the name. After this hump I also need to incorporate two of statements in one formula for Right Handed and Left Handed. I hope all this makes sense, again thanks for the help. I'm in a cab right now and will provide a picture of my sheets once I get to work.

Else statement always executed c#

My Else statement is always being executed as well as the if statement.

If i log in as user 2 and any of the if or else-if statements are correct it will do that section of code but then it will always print "You can't send money to yourself" also.

Can anybody see what I've done wrong here as I've looked for the last 2 hours and can't see whats causing this?

if (loggedInUser == 2 && TaccountNumberTBox.Text == accountNo && TsortCodeTBox.Text == sortCode && amount <= balance2)
            {
                int bal;
                Int32.TryParse(TamountTBox.Text, out bal);
                balance2 = balance2 - bal;
                balance = balance + bal;
                MessageBox.Show("Funds sent");
                history = history + "£" + amount + " Sent to " + TnameTBox.Text + "\n";
                historyLbl.Text = history;

            }
            else if (loggedInUser == 2 && TaccountNumberTBox.Text != accountNo | TsortCodeTBox.Text != sortCode)
            {
                MessageBox.Show("The account you want to transfer to does not exist.");
            }
            else if (loggedInUser == 2 && amount > balance2)
            {
                MessageBox.Show("Insufficient funds");
            }
            else
            {
                MessageBox.Show("You can't send money to yourself");
            }

I'm new to programming and I'm not able to understand this code

class IfSample {
    public static void main(String args[]) {
        int x, y;
        x = 10;
        y = 20;
        if (x < y) System.out.println("x is less than y");
        x = x * 2;
        if (x == y) System.out.println("x is equal to y");
        x = x * 2;
        if (x > y) System.out.println("x is greater than y");
        if (x == y) System.out.println("x is equal to y");
    }
}

Output according to me should be

x is less than y
x is equal to y
x is equal to y

But the actual output is

x is less than y
x is equal to y
x is greater than y

Please explain me how is it possible?

return a matrix with ifelse in R

I have two matrices:

mat<-matrix(1:6,2,3)
mat2<-matrix(1:2,2,3)

and a parameter

a<-1

using ifelse, is it possible to return a matrix when a is a certain value? the code that I am using, does not work: e.g.

mat.new<-ifelse(a==1,mat,mat2)

if and else doesn't work

import java.util.Scanner;

public class Prova {
private static Scanner sc;
private static Scanner s;
private static Scanner ri;

public static void main(String[] args) {
    System.out.println("Ciao, come ti chiami?");
    String value;
    s = new Scanner(System.in);
    value=s.nextLine();
    System.out.println("Oh, " + value + " è un nome fantastico. Adesso ciò che dovrai fare è sceliere un numero n (più piccolo lo prendi e più faceile ti risulterà il problema) ");
    int i;
    sc = new Scanner(System.in);
    i =sc.nextInt();
  System.out.println(i*i*4);
  System.out.println("Che relazione c'è tra il numero scelto da te e quello dato da me ?");
  String risposta;
  ri = new Scanner(System.in);
  risposta=ri.nextLine();
  if (risposta.equals("è il quadrato moltiplicato per 4")){
  System.out.println("Complimenti! + 10 punti");}
  else { System.out.println("Oh no, hai sbaliato! - 2 punto");}
  System.out.println("Passiamo alla prossima domanda. Chi è il presidente della Repubblica Italiana? (scrivere nome e cognome in questo ordine e tutto minuscolo)");
  String risposta1;
  ri = new Scanner(System.in);
  risposta1=ri.nextLine();
  if (risposta1.equals("sergio mattarella")){
      System.out.println("Complimenti! + 5 punti");}
  else {System.out.println("Oh no, hai sbagliato! - 1 punto");
  }
  if (risposta.equals("è il qaudrato moltiplicato per 4") & risposta1.equals("sergio mattarella") );
  System.out.println("hai ottwnuto 15 punti");// something does't work here ! how can i say it? do you understandt my question?

I need some help because it does't work very well, can you understand what i mean when i say there is a problem?

TRIGGER UPDATE WITH IF CONDITION

create or replace
TRIGGER TR_SITECONTACT_UPDATE
AFTER  UPDATE OR INSERT  ON s_ct 
FOR EACH ROW
DECLARE
v_SID s_ct.sid%type;
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN   
IF :NEW.CTID != :OLD.CTID THEN
      UPDATE CT
      SET lastupdatedon =sysdate,
        LASTUPDATESITE=:NEW.SID
      WHERE CTID  = :NEW.CTID;
COMMIT;
END IF;
END;

Here it's possible to check whether lastupdatedCOF is null or not then use update statement, before update row i need to check lastupdatedCOF IS NULL OR NOT in CT Table. IF Null means i need to use below update statement

UPDATE CT SET lastupdatedon =sysdate, LASTUPDATESITE=:NEW.SID WHERE CTID = :NEW.CTID; COMMIT;

lastupdatedCOF IS NOT NULL Means

UPDATE CT SET lastupdatedon =sysdate, LASTUPDATESITE=:NEW.SID, lastupdatedCOF = NULL WHERE CTID = :NEW.CTID; COMMIT;

dimanche 30 octobre 2016

Program runs unpredictably with the exact same input values

I'm new to programming and java and have an assignment that I've been able to run properly- sometimes, but it is inconsistent. I ran it with certain values once and then directly tried re-running it with the same exact input as before. The next time or so it doesn't work. Please help point me to how to fix this unreliability. I can't find any reasons for this in my code. Please help.

import java.util.*; 
public class Calculator {

    public static void main(String[] args) { //void
        boolean done = false;
        Scanner console = new Scanner(System.in);
        while (!done){
            displayMenu();
            String selection = getUsersSelection(console);
            done = processSelection(selection, console);
            //caluculateResults(console);
        }
        System.out.println("Thank you for using this program");
    }

    private static boolean processSelection(String selection, Scanner console) {
        boolean done = false;
        if (!selection.equalsIgnoreCase("Q")){
            if (selection.equalsIgnoreCase("U")){
                caluculateResults(console);
                }
            else if (selection.equalsIgnoreCase("H")){

            }
            else {
                System.out.println("Incorrect entry...try again!");
            }
        }
        else {
            done = true;
        }
        return done;
    }

    private static void caluculateResults(Scanner console) {
        displayCalculatorInstructions();
        double operand1 = console.nextDouble();
        char operator = console.next().charAt(0);
        double operand2 = console.nextDouble();
        double result = 0.00; //double from int
        boolean isOperatorValid = true;
        if (operator == '+'){
            result = operand1 + operand2;
        }
        else if (operator == '-'){
            result = operand1 - operand2; 
}
        else if (operator == '*'){
            result = (double) operand1 * (double) operand2;
        }
        else if (operator == '/'){
            if (operand2 != 0.00){
                result = operand1 / operand2;
            }
            else {
                result = (int)Double.NaN;
            }
        }
        else if (operator == '^'){
            result = Math.pow(operand1, operand2);
        }
        else {
            isOperatorValid = false;
            System.out.println("Invalid operator");
}
        if (isOperatorValid){
            System.out.println("The result of your operation is: ");
            System.out.printf(operand1 +" "+operator+" "+operand2+" = %5.3f", result); 
            System.out.println();
        }
    }

    private static void displayCalculatorInstructions() {
        System.out.println("Enter a mathematical expression to evaluate");
        System.out.println("Valid operations are: +, -, /, *, ^ for power");
        System.out.println("Expression are entered with spaces between the values and operator");
        System.out.println("Here is the valid format:");
        System.out.println("\t<value><space><operator><space><value>");
        System.out.print("Your expression: ");
    }


    private static String 
    private static void displayMenu() {
        System.out.println("Enter one these options:");
        System.out.println("\tH for Help");
        System.out.println("\tU for using calculator");
        System.out.println("\tQ for exiting this program");
        System.out.print("Your selection: ");getUsersSelection(Scanner console) {
        String selection = console.next();
return selection;
    }

    }

}

Creating an if statement for two tkinter shapes entering the same coordinates?

I've been doing some research online and toying around with my code, but I can't seem to figure out how to create an if statement for my shapes created using tkinter-canvas.

It's difficult to word this correctly, but I would like to know how to create a condition where if two of my shapes enter the same coordinate area, I can make something happen.

How would you identify your shape or tags = " " in the statement? Would you create a boolean statement for if it is in a certain coordinate range?

Working the check box laravel 5.2

I am having problem working my check box basically am trying to save in a diff location if checkbox is true don't know what am doing wrong here is my code.Error displays

FatalErrorException in PostController.php line 64:syntax error, unexpected 'if' (T_IF)

thanks in advance.

creat.blade`

            <div>
                
                

            </div>

Postcontroller`

<?php 
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Session;

use Image;
class PostController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function store(Request $request)
    {
        // validate the data
        $this->validate($request, array(
                'title'         => 'required|max:255',
                'body'          => 'required'
            ));
        // store in the database
        $post = new Post;
        $post->title = $request->title;
        $post->body = $request->body;
        $checkbox = Input::get('check_box');

        $post->$checkbox

        if ($request->hasFile('featured_image')) {

          $image = $request->file('featured_image');
          $filename = time() . '.' . $image->getClientOriginalExtension();

            if (Input::get('check_box') === 'true') {
                $post->checkbox = 'true';  // UPDATE:must be true of course
                $location = public_path('images/profile' . $filename);
              Image::make($image->getRealPath())->resize('800', '400')->save($location);

            $post->image = $filename;

            } else {
                $post->checkbox = 'false'; // UPDATE:must be false of course
                $location = public_path('images/' . $filename);
              Image::make($image->getRealPath())->resize('800', '400')->save($location);


          $post->image = $filename;

        }

        $post->save();

        Session::flash('success', 'The blog post was successfully save!');
        return redirect()->route('posts.show', $post->id);
    }
    public function show($id)
    {
        $post = Post::find($id);
        return view('posts.show')->withPost($post);}
?>

Check against two arrays using for loop and if statement

I'm trying to run a check against two arrays (one has 4 objects, one just have a few strings) with for loops and if statement for a problem set.

The idea is to use for loop to iterate over every element in the object array and the string array, then use if statement to figure out matches and shove the matching string into a new array. Once all the elements are iterated, it returns the string if there is a matching one.

The problem is the function calls it a day once a single match in the object array is found and returns that only that instead of iterating over the rest of the elements in the object array.

var passengers = [
                                        { name: ["Michael Jackson"], paid: true }, 
                                        { name: ["Osama"], paid: false }, 
                                        { name: ["Harambe"], paid: true },
                                        { name: ["Pepe"], paid: true },
                                ];

var noFlyList = ["Jimmy", "John", "Pepe", "Osama"];

function checkNoFly(passengers, noFlyList) {
        for (var i = 0; i < passengers.length; i++) {
                for (var j = 0; j < noFlyList.length; j++) {
                        if (passengers[i].name[0] == noFlyList[j]) {
                                var passengerList = [];
                                passengerList.push(passengers[i].name[0]);
                                return passengerList;
                        }
                }
        }
        return true;
}

function processPassenger(passengers, testFunction) {
        for (var i = 0; i < passengers.length; i++) {
                if (testFunction(passengers[i])) {
                        return false;
                }
        }
        return true;
}

var allCanFly = processPassenger(passengers, checkNoFly);
if (!allCanFly) {
        console.log("We cannot fly because " + checkNoFly(passengers, noFlyList) + " is on the no-fly list");
}

Errors with SPSS Logical Operators and Strings In a Simple Expression

I'm having some unexpected errors in achieving the following functionality. In this example code, I have the temperature on several days of the week. For this generalized example, I'm interested in determining the days that are 72,74, or 65 degrees. As an output, a variable should be created that contains the day of the week that is within this temperature range. Also, please note that in these data there is only ever 1 day that would fall within have one of these temperatures.

Monday     Tuesday     Wednesday     Day of Interest    
72         78          80            
61         78          74            



Monday     Tuesday     Wednesday     Day of Interest    
72         78          80             2  
61         78          74             4

I wrote the following code, with the generous help of the great folks here at StackOverflow,

IF (Monday = 65 OR 72 OR 74) Day_Of_Interest = 2.
IF (Tuesday= 65 OR 72 OR 74) Day_Of_Interest = 3.
IF (Wednesday = 65 OR '72' OR 74) Day_Of_Interest = 4.
IF (Thursday = 65 OR 72 OR 74) Day_Of_Interest = 5.

but sadly it returns an error:

 IF A relational operator may have two numeric operands or two character 
string operands. To compare a character string to a numeric quantity,
consider using the STRING or NUMBER function.'

I tried changing the code to be akin to '65' OR '72', but this produced another error. I would really appreciate if anyone had any thoughts on how to make this work. I know the example above isn't the best, but it's the best I could think of. If you need anymore details I'd be more than happy to oblige. Thanks so much for your help!

"IF" statement inside End Submit does not work

I have to following code in my End Submit section (in Breezing Forms), which is supposed to be excecuted after form submit button is clicked. But for some reason IF statement does not work. Could you guys please correct the code (IF statement), so that I can use this code.

Thank you.

enter code here$this->execPieceByName('ff_InitLib');
$currencyValue=ff_getSubmit('depocurrency');

if($currencyValue!='EUR') {

echo '

<form method="POST" name="order_confirmation_form" 
action="http://ift.tt/2f3okhy">
<input type="hidden" name="receiver"  value="123456789"/>
<input type="hidden" name="formcomment"  value="'.ff_getSubmit( 'ordernumber' ).'"/>
<input type="hidden" name="label"  value="16078"/>
<input type="hidden" name="quickpay-form"  value="shop" />
<input type="hidden" name="targets"  value="Order No '.ff_getSubmit( 'ordernumber' ).'"/>
<input type="hidden" name="sum"  value="50.00" data-type="number" />
<input type="hidden" name="need-fio"  value="true"/>
<input type="hidden" name="need-email"  value="true"/>
<input type="hidden" name="need-phone"  value="true"/>
<input type="hidden" name="need-address"  value="false"/>
<input type="hidden" name="paymentType"  value="AC"/>
<input type="hidden" name="successURL"  value="http://ift.tt/2fkR751"/>
</form>

}

<script>
document.order_confirmation_form.submit();
</script>';

exit;

Python Name error: name not defined, trying to take value input of user to run if function [duplicate]

This question already has an answer here:

im trying to get the input from the user if they put 'yes' it takes that value and runs the if statement function. but i

from sys import argv

script, user_name  = argv # these determine the name of the user and the name of the script

prompt = '> '

print "hi %s, im the %s script." % (user_name, script) # format strings used to call variables when needed

print "i'd like to ask you a few questions"

print "do you like me %s?" % user_name

likes = input('yes') # likes is the varible for the user input

if likes ('yes') :

print "well i dont like you"

This is my error:

 File "ex14.py", line 8, in <module>
 likes = input('yes') # likes is the varible for the user input
 File "<string>", line 1, in <module>
NameError: name 'yes' is not defined
PS C:\Users\lucas\Python folder>

How to compare elements in a list of lists and compare keys in a list of lists in Python?

I have the following sequence:

seq = [['ATG','ATG','ATG','ATG'],['GAC','GAT','GAA','CCT'],['GCC','GCG','GCA','GCT']]

Here is a dictionary key that stores the value of amino acid for each of the codons (Triplet bases like ATG, GCT etc).

aminoacid = {'TTT' : 'F','TTC' : 'F','TTA' : 'L','TTG' : 'L','CTT' : 'L','CTC' : 'L','CTA' : 'L','CTG' : 'L','ATT' : 'I','ATC' : 'I','ATA' : 'I','ATG' : 'M','GTT' : 'V','GTC' : 'V','GTA' : 'V','GTG' : 'V','TCT' : 'S','TCC' : 'S','TCA' : 'S','TCG' : 'S','CCT' : 'P','CCC' : 'P','CCA' : 'P','CCG' : 'P','ACT' : 'T','ACC' : 'T','ACA' : 'T','ACG' : 'T','GCT' : 'A','GCG' : 'A','GCA' : 'A','GCG' : 'A','TAT' : 'Y','TAC' : 'Y','TAA' : 'STOP','TAG' : 'STOP','CAT' : 'H','CAC' : 'H','CAA' : 'Q','CAG' : 'Q','AAT' : 'N','AAC' : 'N','AAA' : 'K','AAG' : 'K','GAT' : 'D','GAC' : 'D','GAA' : 'E','GAG' : 'E','TGT' : 'C','TGC' : 'C','TGA' : 'STOP','TGG' : 'W','CGT' : 'R','CGC' : 'R','CGA' : 'R','CGG' : 'R','AGT' : 'S','AGC' : 'S','AGA' : 'R','AGC' : 'R','CGT' : 'G','GGC' : 'G','GGA' : 'G','GGG' : 'G',}

As one can see several codons can code for the same aminoacid (eg. GGT,GGC,GGA, GGG etc all code for Glycine (G) ). These are Synonymous (PSyn) and if codons code for different amino acids they are Non-Synonymous (PNonsyn)

In this code, I need to do the following:

  1. For each element in the list of lists, if there is a change in the bases AND they all code for the same amino acid, then increase count of PSyn by 1 and if it codes for different amino acids increment count PNonsyn by 1

    Here,

    ATG all code for M #However, all are ATG's no change in bases. So no increment in count
    
    GAC, GAT for D; GAA for E; and CCT for P #Codes for three different amino acids, increment count by 1
    
    GGT,GGC,GGA, GGG for G #Different bases but all code for same amino acids, increment count by 1
    
    

    OutPut: CountPsyn = 1 CountPNonsyn = 1

  2. Generate a list of amino acids that corresponds to the above seq. such that:

    Output : ['ATG','nonsyn','G'] #For sites with different aminoacids, the list should say nonsyn and for sites which had identical bases it should list the bases

I need help modifying the following code to get the program to work. I am not confident on how to call values from dictionary and check them against all the elements. Code Attempted:

countPsyn = 0
countPnonsyn = 0
listofaa =[]

for i in seq:
    for base, value in enumerate(i):        
        if value[i] == value[i+1]: #eg. ['ATG','ATG','ATG','ATG'] 
            listofaa.append(value)

        if value[i] != value[i+1]: 
            if aminoacid[value][i] ==  aminoacid[value][i+1]: #eg.['GCC','GCG','GCA','GCT']
                countPsyn =+ 1
                listofaa.append(aminoacid)
            else: #eg. ['GAC','GAT','GAA','CCT']
                countPnonsyn =+ 1
                listofaa.append('nonsyn')

File Output can be found [here][1] 

Java password program

Objective of program:

Program that requires the user to enter two passwords that are the same.

  1. The password must be at least 8 characters long.

  2. The password must contain at least:

    • ONE alpha character
    • ONE numeric character [0-9]
    • ONE character that is not alpha or numeric, such as: ! @ $ % ^ & * ( ) - _ = + [ ] ; : ' " , < . > / ?
  3. The password MUST NOT:

    • contain spaces;
    • begin with an exclamation [!] or a question mark [?];
    • contain repeating character strings of 3 or more identical characters, such as “1111” or “aaa”.

My code:

public class PasswordChecking { // start of class 

    public static void main(String[] args) { // start of main method

        String passWord1; // the first password the user will enter
        String passWord2; // the second password the user will enter


        // scanner method declared to get user input
        Scanner kb = new Scanner(System.in); 


        // asks the user to print out the first password
        System.out.print("Please enter a password: \n");
        passWord1 = kb.nextLine();

        // asks the user to print out the second password
        System.out.print("\nRe-enter the password: \n");
        passWord2 = kb.nextLine();

        // method call for the length of the character
        characLength(passWord1, passWord2);

        // method call for the characters that should be in the passwords
        if(!passContain(passWord1, passWord2)){
            System.out.println("\nYour password must contain at least: "
                       + "\n- one alpha character, "
                       + "\n- one numeric number, and "
                       + "\n- one character that is neither numeric nor alphabetical.\n");

            // if condition in the if statement is true, when the... 
            // program reaches this statement, the program is terminate 
            System.exit(0); 
        } // end of if statement

        // method call for what the password cannot contain
        if(!notContain(passWord1)){
            System.out.println("\nYour password must not contain:"
                       + "\n- spaces, "
                       + "\n- begin with '!' or '?', and "
                       + "\n- cannot contain repeating character of 3 or more "
                       + "identical characters.");

            // if condition in the if statement is true, when the... 
            // program reaches this statement, the program will terminate 
            System.exit(0); 
        } // end of if statement


        if(passWord1.equals(passWord2)){ 
            System.out.println("\nYour passwords are equal.");
        } // end of if statement 
        else{ // else statement
            System.out.println("\nYour passwords are not equal.\nPlease create two "
                                + "passwords that are equal.");
        } // end of else

    } // end of main()


    public static void characLength(String pass1, String pass2){ 

        // if statement to obtain at least 8 characters for the passwords
        if(pass1.length() < 8 && pass2.length() < 8){ 
            System.out.println("\nYour passwords must be at least "
                                + "8 characters long.");

            System.exit(0); 
        } // end of if statement 

    } // end of characLength()


    public static boolean passContain(String pass1, String pass2){
        boolean hasLetter = false; // if password has a letter - set to false
        boolean hasDigit = false; // if password has a digit - set to false
        boolean hasNotAB = false; // if password has a special character - set to false

        // enhanced for loop for the password to check if it has a letter, ... 
        // a digit and a special character
        for(char a: pass1.toCharArray()){
            // start of if statement
            if(Character.isLetter(a)){
                hasLetter = true;
            } // end of if statement 
            else if(Character.isDigit(a)){ // check if password has at leat 1 digit
                hasDigit = true;
            } // end of else if
            else { // else statement
                hasNotAB = true;
            } // end of else statement
        } // end of enhanced for loop

        return hasLetter && hasDigit && hasNotAB;

    } // end of passContain()


    public static boolean notContain(String pass){
        boolean hasSpace = false; // if password has a space - set to false
        boolean hasRepeating = false;// if password has 3 or more repeating characters - set to false
        int prevchar = -1; // the previous password dclared and set to -1
        int repeating = 1; // if password is repeating 

        if(pass.charAt(0) == '!' || pass.charAt(0) == '?') {
            return false;
        } // end of if statement

        // enhanced for loop to test different conditions to...
        // satisfy the requirments for an appropriate password
        for(char a: pass.toCharArray()){
            // tests if the password has a space
            if(Character.isSpaceChar(a)){
                hasSpace = true;

            // is the current character == the previous char?
            if(a == prevchar){
                // repeating is incremented to see if the passwords contain...
                // the same character 3 or more times in a row
                repeating++; 
                // does the password contain the same character 3 or more times in a row?
                if (repeating >= 3) {
                    hasRepeating = true;
                } // end of if statement
            } // end of if statement for previous character == current character
            else { // else statement
                repeating = 1;
                prevchar = a;
            } // end of else statement
        } // end of loop

        } 

        return !hasSpace && !hasRepeating;

    } // end of notContain()

} // end of PasswordChecking class

My problem:

The program allows me to enter three or more identical characters, when it shouldn't.

If Loop Not Working

So I can't seem to find out what is wrong with my code, Its good, i checked but it seems not to work. everything left out of what is shown is correct because i tested it before, so, well, here's my code...

1 = Stay 2 = Go 3 = South ''') while True: choice = raw_input("->") if choice == 1: time.sleep (2.5) '<' + str(Pname) + '> Lets Stay Here For Tonight' time.sleep (2.5) '<' + str(NPCChester) + '> But we have no other choice, we have nothing so we have to go out and find stuff as fast as possable!' time.sleep (2.5) '<' + str(NPCAnnabeth) + '> On the other hand, we have nothing so we should play it safe right?' time.sleep (2.5) '<' + str(NPCChester) + 'Fine...' time.sleep (2.5) break elif choice == 2: '<' + str(Pname) + '> Well, Lets Just Go' time.sleep (2.5) '<' + str(Pname) + "> But we should play it safe right after we lost everything because we're not prepared right?" time.sleep (2.5) break elif choice == 3: '<' + str(Pname) + '> How About We Go South' time.sleep (2.5) '<' + str(NPCAnnabeth) + "> But we're still going some where anyways I want to stay" time.sleep (2.5) '<' + str(NPCChester) + "well, we have tot go soo" break else: print "That Is Not A Choice" continue

Wrong written "if-statement" causes and consequences

So I know that the correct way is:

    if (x > y)
    {
        //...
    }
    else if (x = y)
    {
        //...
    }
    else 
    {
        //...
    }

Or for example if I want specific condition for last condition:

    if (x > y)
    {
        //...
    }
    else if (x = y)
    {
        //...
    }
    else 
    {
        if (x < y)
        {
            //...
        }
    }

But if it is wrong, like this one:

    if (x > y)
    {
        //...
    }
    else if (x = y)
    {
        //...
    }
    else if (x < y)
    {
        //...
    }

My question is why last one is wrong and what kind of failure it can cause?

For example, can it be cause of multiplication of process in last condition in if-statement?

Using string for comparison in "if" statement not working (SWIFT)

So I am in the process of developing this app for Mac and I am using Swift. I am just learning + developing the app side by side. I have the main viewController and when you press (+) button, it opens another viewcontroller with textfield. Now i have two buttons, one says "Done" and the other says "Cancel". If you press Cancel the viewController dismisses. However, if you press "Done" then whatever you added in that textfield appears in the first ViewController.

I want to run an if statement on "Done" button. So if you haven't written anything in the textfield and you press done, it gives you an error, and if you have written something, then it allows you to press Done and it dismisses!

I created an IBOutlet for the textfield:

@IBOutlet var weblinklabel: NSTextField!

Then whatever is stored in the weblinklabel is stored in another variable:

weblinklabel.stringValue = done!

Obviously, "done" is an optional string variable, assigned as this:

var done: String? = "" 

Now in my understanding, "done" variable if empty should give the error which in this case is a label that shows itself(which is isHidden = false' in viewdidload()) function initially.

This is the "if-statement" that I am trying to use:

  if done != nil {
            self.view.window?.close()

        }
        else {
            label1.isHidden = false
        }

I believe the placement of this code isn't right. I am placing it under IBAction of the "Done" button.

Any help in this regard, will be appreciated! thanks

Better way to write if/else conditions

I've got the following code where:

  • $urlParams is the school year from 7 to 11
  • $Comms['Overall'] is the total amount of "commendations" a student has

This code iterates through the numbers based on the school year to determine which "award" a student has got.

Is there a better way to write this code?

if($urlParams['y'] == 7){
    if((300 <= $Comms['Overall']) && ($Comms['Overall'] <= 599)){ $Award = "Bronze"; }
    elseif((600 <= $Comms['Overall']) && ($Comms['Overall'] <= 899)){ $Award = "Silver"; }
    elseif((900 <= $Comms['Overall']) && ($Comms['Overall'] <= 1199)){ $Award = "Gold"; }
    elseif((1200 <= $Comms['Overall']) && ($Comms['Overall'] <= 1499)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1500){$Award = "Diamond";}
}

elseif($urlParams['y'] == 8){
    if((250 <= $Comms['Overall']) && ($Comms['Overall'] <= 549)){ $Award = "Bronze"; }
    elseif((550 <= $Comms['Overall']) && ($Comms['Overall'] <= 849)){ $Award = "Silver"; }
    elseif((850 <= $Comms['Overall']) && ($Comms['Overall'] <= 1099)){ $Award = "Gold"; }
    elseif((1100 <= $Comms['Overall']) && ($Comms['Overall'] <= 1299)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1300){ $Award = "Diamond"; }  
}

elseif($urlParams['y'] == 9){
    if((200 <= $Comms['Overall']) && ($Comms['Overall'] <= 449)){ $Award = "Bronze"; }
    elseif((450 <= $Comms['Overall']) && ($Comms['Overall'] <= 699)){ $Award = "Silver"; }
    elseif((700 <= $Comms['Overall']) && ($Comms['Overall'] <= 899)){ $Award = "Gold"; }
    elseif((900 <= $Comms['Overall']) && ($Comms['Overall'] <= 1099)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1100){ $Award = "Diamond"; }
}

elseif($urlParams['y'] == 10){
    if((150 <= $Comms['Overall']) && ($Comms['Overall'] <= 399)){ $Award = "Bronze"; }
    elseif((400 <= $Comms['Overall']) && ($Comms['Overall'] <= 599)){ $Award = "Silver"; }
    elseif((600 <= $Comms['Overall']) && ($Comms['Overall'] <= 799)){ $Award = "Gold"; }
    elseif((800 <= $Comms['Overall']) && ($Comms['Overall'] <= 999)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1000){ $Award = "Diamond"; } 
}

elseif($urlParams['y'] == 11){
    if((150 <= $Comms['Overall']) && ($Comms['Overall'] <= 299)){ $Award = "Bronze"; }
    elseif((300 <= $Comms['Overall']) && ($Comms['Overall'] <= 499)){ $Award = "Silver"; }
    elseif((500 <= $Comms['Overall']) && ($Comms['Overall'] <= 699)){ $Award = "Gold"; }
    elseif((700 <= $Comms['Overall']) && ($Comms['Overall'] <= 849)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 850){ $Award = "Diamond"; }
 }

if and else both is being excuted

I have strange problem with a simple c program.

#include<stdio.h> 
#include<math.h>
#include<conio.h>
main() {
    int a, b, c, delta;
    float x1, x2;
    printf("Please Enter a,b,c :");
    scanf("%d%d%d",&a,&b,&c);
    delta = (b * b) - (4 * (a * c));
    if(delta < 0){
        printf("No roots!");
    } 
    else{
        if (delta >= 0){
            x1 = (-b + sqrt(delta)) / (2 * a);
            x2 = (-b - sqrt(delta)) / (2 * a);
        }
    }
    printf("r1=%f and r2=%f", x1, x2);
    getch();

}

when I enter 2 1 1, it seems, the program executes both if and else in line 10 and 13. The output is No roots!x1=0.0000 and x2=0.0000 what's wrong?

Using ifelse statement for multiple values in a column

I have a table with approximately 3000 rows with data in the form of :

Number  Type
10001   0
10005   7
10006   0
10007   14
10012   16
10022   14
10023   0
10024   0
10029   7
10035   17
10045   14

I want to add a third column so that the table looks like :

Number  Type   SCHEach
10001   0         0
10005   7         0
10006   0         0
10007   14        0
10012   16        1
10022   14        0
10023   0         0
10024   0         0
10029   7         0
10035   17        1
10045   14        0

where values in the SCHEach column are based on values in the Type column. If values in the Type column are 16,17,21, or 22, values in the SCHeach column should be 1. For any other values in the Type column, SCHEach values should be 0.

Right now I'm using the following

library(dplyr)
schtable$SCHEach = ifelse(
schtable$Type == 16 | 
schtable$Type == 17 | 
schtable$Type == 21 | 
schtable$Type == 22, 1, 0)

I am new to R and wanted to know if there is a way to do it without having to type the following separately for 16,17,21,and 22?

schtable$Type == 'number'

Passing pointers through for loops and if statements

I am trying to pass a pointer through this for loop but it doesn't work. This is just a block from my original code. I didn't want to overload you all with 200 lines of code! If you need all of it please ask.

Ok! so I used 3 printf's to see how far my code gets before it crashes. It gets to the printf( "2" ); before it crashes. So I am assuming it is something to do with "if ( *(userInput + i ) == sNumArray[j] )" I am not sure what I am doing wrong. As far as I know pointers dont use pointer[i] to cycle through each element they use *( pointer + i )?

I only started programming with c 4 weeks ago so sorry if I didn't explain this thoroughly. I am still learning the terminology etc

for ( i = 0; i < sUserInput_SIZE; i++ ) {

        printf( "1" );

    for( j = 0; j < sNumArray_SIZE; j++ ) {

        printf( "2" );

        if ( *(userInput + i ) == sNumArray[j] ) {

            validInput++;
            printf( "3" );

        }//End if( )

    }//End inner for( )

}//End outer for( )

Simple if statement with loop issue [duplicate]

This question already has an answer here:

I have an if statement here and there are no errors but it gives the wrong result:

Initial Code

import java.util.Scanner;

public class Decision {

public static void main(String args[]){

    String enter;

    Scanner inputanswer = new Scanner(System.in);

    System.out.println("welcome to a test");
    System.out.println("proceed? yes or no?");

    String decision1 = inputanswer.nextLine();  

    if ( decision1 == "yes" ){

        System.out.println("lets proceed");

    } else if ( decision1 == "no" ){

        System.out.println("Quitting now");

    } else {

        System.out.println("invalid");
    }

}

}

so when I type in yes or no for example it still comes out as invalid.

Also can someone help me put this in a loop so that when they do an invalid statement it resets to the question.

python: If loop returns wrong result

I wrote the following script trying to calculate portions in array a and stack the result to the original array:

import numpy


a = numpy.array([[1, 4, 4.555],
                 [2, 3, 9.112],
                 [3, 1, 7.322],
                 [1, 5, 3.911]])

i = 0
b = numpy.ones((4,1))
if i <= 2:
    b[i][0] = float(a[i][2])/(a[i][2]+a[i+1][2])
    b[i+1][0] = float(a[i+1][2])/(a[i][2]+a[i+1][2])
    i = i+2
print b
c = numpy.hstack((a,b))
print c

But the result were strange:

array b:
[[ 0.33328455]
 [ 0.66671545]
 [ 1.        ]
 [ 1.        ]]
array c:
[[ 1.          4.          4.555       0.33328455]
 [ 2.          3.          9.112       0.66671545]
 [ 3.          1.          7.322       1.        ]
 [ 1.          5.          3.911       1.        ]]

The first and second rows of array c was what I want, but the rest rows were strange. The result array I expected is:

[[ 1.          4.          4.555       0.33328455]
 [ 2.          3.          9.112       0.66671545]
 [ 3.          1.          7.322       0.65182943]
 [ 1.          5.          3.911       0.34817057]]

How to fix this? And is there more efficient coding to do this task?

How to use string from condition1 into condition2?

I have the following code:

<form action='' method='POST' id='form1'>
    imdbcode :  <input type='text' id='imdbcode' name='imdbcode' /><br/>
           <input type='submit' name='submit' value='Get'/>
 </form>
<?php
 if(isset($_POST['submit'])){
.
.
.
$title = ... ;


 echo "
 <form action='' method='POST' id='form2'>
           <input type='submit' name='Send' value='Send'/>
 </form>";
}

if(isset($_POST['Send'])){

//I WANT TO USE $Title from condition1 

} ?>

I want to use $title in second condition.

It prints $title in first condition! But doesn't print after closing condition!

How can I do that?

How to connect login forms to another forms? (I don't understand)

It was first time to join developer forums (CMIIW) to learning coding for my college. C++ Builder 6 was used in my department

So I had learning simple login forms, but I want to try to make "Login" button accessing another forms (or .cpp) such database system if login successful ("if" code) and I don't know what code for this. I had find this but I cannot figure it (because I am new student and I never know about app coding).

For example, login.cpp --> Press "login" --> "If-statement" --> "ShowMessage" --> database.cpp

What's code for accessing another form in "if-statement"?

Thanks :)

Sorry for my bad English

How to use Java Scanner import for If-Then Statement [duplicate]

This question already has an answer here:

How can you have user input a certain string and have a certain response? This is a piece of code I'm working on...

import java.util.Scanner;

public class AppetizerInformation {
    public static void main(String[] args) {
       System.out.print("Please enter an appetizer: ");
       Scanner userFoodInput = new Scanner(System.in);
       String appetizer = userFoodInput.next();
       if (appetizer = "Potato") {
            System.out.println("Good");
        }
    }
}

C++ condition is condition is right but does not work

I'm trying to build a simple program that asks for a grade whether it is numerical or general weighted average e.g. 75, 1.5 respectively. And when the user input a non numerical number a stated in the if condition, it prints error as stated also in the else condition. The problem is when I enter a 3-digit,4 , 5 digit number and so on, I get an error that is supposed to be Grade is not within the scope as stated in the nested if (else inside the if condition). Also the same thing happens when I enter 0. But the good thing is, when I enter a negative number or integer, it properly works well. Can I ask what is the problem with my condition? (Tnx in advance)

#include <iostream>
using namespace std;
int main ()
{
double grade;
cout<<"Enter Grade or GWA: ";
cin>>grade;
if (grade!=grade>='a'&&grade<='z'||grade!=grade>='A'&&grade<='Z') 
/*The first If condition states that the user will get an error if 
input a non-numerical integer or number.*/   
{
    if (grade<=5&&grade>=1)
    {
        if (grade>2.5)
            cout<<"Failed"<<endl;

        else
            cout<<"Passed"<<endl;
    }

    else if (grade<75&&grade>=0)
        cout << "Failed" << endl;

    else if (grade>=75&&grade<=100)
        cout << "Passed" << endl;

    else
        cout<<"Grade is not within the scope!"<<endl;   
}

else
    cout<<"Error!"<<endl;


cin.get();
return 0;
}

samedi 29 octobre 2016

What is a scripting language similar to python but with a BASH or javascript like syntax?

I normally use python for large (or cross platform) things and BASH for small things. I love the BASH syntax, so I really hate the fact that python doesn't use (curly) brackets/braces to enclose things like if statements. Is there a language with similar functionality to python that uses (curly) brackets/braces?

Example:

What I want:

if x=1 {
    do something
}

What python has:

if x=1:
    do something

Python - How to print out all letters from a list

There are given lots and I'm suppose to print out all letters, either uppercase or lower case. I'm also not allowed to use any built in functions. I'm having difficult printing out the list of letters. All i get in return is an empty closed bracket.

alphabet = "abcdefghijklmnopqrstuvwxyz"

alphabet2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def get_symbols(lot):
list = []
for i in lot:
    if (i == alphabet or i == alphabet2):
        list.append(lot);
return list

The given lot:

lot1 = [['.', '.', 'a', 'D', 'D'],
       ['.', '.', 'a', '.', '.'],
       ['A', 'A', '.', 'z', '.'],
       ['.', '.', '.', 'z', '.'],
       ['.', '.', 'C', 'C', 'C']]

My output:

Traceback (most recent call last):
File "tester4p.py", line 233, in test_get_symbols_2
def test_get_symbols_2 (self): self.assertEqual (get_symbols(lot1()),['a','D','A','z','C'])
AssertionError: Lists differ: [] != ['a', 'D', 'A', 'z', 'C']

Second list contains 5 additional elements.
First extra element 0:
'a'

- []
+ ['a', 'D', 'A', 'z', 'C']

Expected Output:

['a', 'D', 'A', 'z', 'C']

Python Drawing Pie Chart/Bar Graph using while loop

I'm having difficulty starting a while loop trying to generate a program that will generate a pie chart or bar graph from numbers that a user will input. How does the while loop need to be written so it's not looping forever? I know I could use a for loop for a finite sequence but i'm not too experienced in that. any guidance would be helpful!

from SimpleGraphics import *

print("Chart Menu: 1.Pie Chart, 2.Bar Chart")

chart = int(input("enter either 1 for pie chart or 2 for bar chart:"))

if chart == 1:

 title = input("Enter the title of the chart: ")

 numSec = int(input("Enter the number of sectors: "))

 tSum = int(input("Enter the total sum of all sector values:  "))

 gsize = int(input("Ehter the grid size (Between 10 and 400): "))

 yLabel = input("Enter the label for the Y-Axis:")

while loop

-the name of each sector

-the value each sector

-draw pie chart

if chart == 2:

title = input("Enter the title of the chart: ")

numCat = int(input("Enter the number of categories: "))

grid = int(input("Ehter the grid size (Between 10 and 400): "))

while loop

-name of each category

-value for that category

-draw bar graph

How can I run an if statement in the answer of a jOptionPane?

So what i'm trying is to do a specific task from the answer of the two options, here's some of the code, but i don't know what's going on here.

String[] sex = { boy, girl };
        JOptionPane.showOptionDialog(null,"Hey " +output1 +". Are  you a boy or a girl?", "Question",
        JOptionPane.YES_OPTION, JOptionPane.NO_OPTION,
        null, sex, sex[0]);




        if(sex == JOptionPane.YES_OPTION)
        {

Cambrigde exam python task - assistance needed

I'm preparing for an exam that's coming up soon about python and seem to have gotten stuck with a task.

The task says as follows:

Data is received as a stream of characters:

  • each stream of characters is a sequence of surnames
  • the start and end of a sequence is indicated by two * characters (**)
  • the surnames are separated by a # character

A typical character sequence is:

**ali#thomas#ghandi#akmar#smith#barija**

Write program code to:

  • input a character sequence (made up of one or more surnames

  • check that the character sequence has a valid format

  • calculate and output the number of surnames*

If anybody out there would be kind enough to help me out, even if it's just a little bit, I would be very grateful.

Thank you all very much for your time.

Cheers, Ben

If-statement to not print data unless it was sorted

I have this C program almost all completed. Option 1 asks the user to enter a fraction and then option 2 displays that fraction. option 3 sorts the fractions in ascending order, option 4 finds the min, median and max of my set of fractions. However. If the user selects option 4 before sorting the fractions, then a "Please sort the values first" should pop up. I know to add the if statement but not sure what the statement would be.

This is my code:

//This is my code:
#include <stdio.h>
#include <stdlib.h>

//Struct to hold fraction data
typedef struct fraction
{
 int numerator, denom;
}fraction;
double Calc_Frac(fraction b)
{
 return((double)b.numerator / b.denom);
 }



 int main()
 {  fraction arrFraction[100];

    int i = 0;
    int j;
    int num = 1;

    while (num == 1)
    {
        int choice;
        printf("\nPress 1 to enter a fraction\n");
        printf("Press 2 to view stored fractions\n");
        printf("Press 3 to sort fractions\n");
        printf("Press 4 to find min max median fraction\n");


        scanf("%d", &choice);


        if (choice == 1)
        {
            //Prompting user
            printf("\nEnter your fraction, numerator followed by denominator\n");

            //Reading values from user
            scanf("%d %d", &arrFraction[i].numerator, &arrFraction[i].denom);

            //Incrementing counter
            i++;

        }

        if (choice == 2) {
            printf("-------------------------\n");
            for (j = 0; j < i; j++)

            {
                printf("%d  %d/%d \n", arrFraction[j].numerator / 
arrFraction[j].denom, arrFraction[j].numerator%arrFraction[j].denom, 
arrFraction[j].denom);
            }
            printf("\n-------------------------\n\n");
        }



        if (choice == 3) {

            int min;
            fraction tmp;

            for (int k = 0; k < i; k++)
            {
                min = k;
                for (j = k + 1; j < i; j++)
                {
                    if (Calc_Frac(arrFraction[j]) <  Calc_Frac(arrFraction[min]))
                    {
                        min = j;
                    }
                }
                tmp = arrFraction[k];
                arrFraction[k] = arrFraction[min];
                arrFraction[min] = tmp;
            }

        }



        if (choice == 4)
        {

 if (//the statement ){
      printf("please sort values first"\n);
    }
      else
            {
                printf("Min fraction is: %d %d/%d\n", arrFraction[0].numerator / arrFraction[0].denom, arrFraction[0].numerator%arrFraction[0].denom, arrFraction[0].denom);
                printf("Median fraction is: %d/%d\n", arrFraction[i / 2].numerator, arrFraction[i / 2].denom);
                printf("Max fraction is: %d %d/%d\n", arrFraction[i - 1].numerator / arrFraction[i - 1].denom, arrFraction[i - 1].numerator%arrFraction[i - 1].denom, arrFraction[i - 1].denom);
            }

        }

    }

 system("pause");
 return(0);
 }

Choose column name of the first column which fits certain logical test

Input

Hi all, I have following input:

id <- c("a", "b", "c", "d")
target <- seq(from = 100, to = 400, length.out = 4)
a <- c(300, 304, 100, 405)
b <- c(300, 104, 100, 405)
c <- c(85, 304, 500, 405)
df <- as.data.frame(cbind(id, target, a, b, c))

I would like to add a new column "column" which indicates per row, which of the columns "a", "b", "c" would be the first column with a value smaller than the target solution. The requested output looks like this:

Required Output

df$column <- c("c", "b", "a", "NA")
df

I thought about a concenated if check per row and apply this to all rows with the apply function. However the abc columns are quite long (round 20, therefore a loop would be required) and the number of rows are about 4.000. Does anybody have an idea on how to solve it? Thanks! Nils

Foreach is not iterating properly /with wordpress

I am trying to iterate through three recent posts and display their thumbnail, title and permalink.

The first one has a slightly different look so there is an if statement as well to display the first one in a different setting and then iterate throguh the rest. What is happening instead, it is showing the first post three times with styling for both if and else.

I am not sure what am I doing wrong, thanks for any help!

<?php
      $recent =  wp_get_recent_posts( array('numberposts' => 3) );
        $i = 0;
        global $recent_post;
        foreach( $recent as $recent_post ) {
          if ($i == 0 ): ?>
              <div class="header_recent main">
                <a href="<?php the_permalink($recent_post); ?>">
                  <img src="<?php echo get_the_post_thumbnail($recent_post->ID); ?>"/>
                  <div class="overlay">
                    <h1><?php the_title_attribute($recent_post); ?></h1>
                  </div>
                </a>
              </div>
      <?php else: ?>
          <div class="header_recent side">
            <a href="<?php the_permalink($recent_post); ?>" title="<?php the_title_attribute($recent_post); ?>">
            <img src="<?php echo get_the_post_thumbnail($recent_post->ID); ?>"/>
                <div class="overlay">
                  <h1><?php the_title_attribute($recent_post); ?></h1>
                </div>
          </div>
    <?php endif; $i++; }
  wp_reset_postdata(); ?>

Also, I would really appreciate help with the warning about get_the_post_thumbnail function:
Notice: Trying to get property of non-object on line 29

why is my else statement not working java

package jdbc;

import java.sql.DriverManager;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.*;
import java.util.Scanner;  

public class driver2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int points =0;
        Scanner ievads = new Scanner(System.in);

        while(ievads.nextLine() != null){
    System.out.println("What Country");
    String lietotIn = ievads.next();
    {
    try {   
        Class.forName("com.mysql.jdbc.Driver");  
        java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/countries","root",""); 
        java.sql.Statement quer = con.createStatement();
        String kverijs = "select name from countries where name = '" +lietotIn+ "';";
        ResultSet rezult = quer.executeQuery(kverijs);
       // System.out.println(rezult.next());


        while(rezult.next()){
            String lietotajvards = rezult.getString("name");

                   if(lietotajvards.equalsIgnoreCase(lietotIn))
                   {
                       System.out.println("Yup");
                       points+=5;
                       System.out.println(points);

                   }
                   else {
                       System.out.println("no");
                       points-=3;
                       System.out.println(points);
                   }
        }
        }

  catch(Exception ex) {
            System.out.println("Kluuda: " +ex); 
    }

}

    }
    }
}

In the code above, I am taking input from scanner and checking to see if my word is in my database. If so I print yup if not no. In my scenario, my else is being skipped. Why is it that my if statement works but when I put in a phony value it does not print no and decrease points?

.matches() does not return expected java

System.out.println("tag " + status + " - " + status.matches("Not yet synchronized"));

I have this and it returns

I/System.out: tag Not yet synchronized - false

Meaning status value is Not yet synchronized but the condition

status.matches("Not yet synchronized")) return false wherein I expect it should return true.

Why does this happened.

This if is not working on Octave/Matlab

I have the code divided on three functions:

f.m (This function works)

function y=f(x)
y = x^2;
endfunction

df.m (The function that return the derivate of y=x^2. This function works)

function y=df(i)
  syms x,diff(f(x),x);
  subs(ans,x,i);
  y = ans;
endfunction

newton.m (maxIt = max of tries)

function [x1,nIt] = newton (f,df,x0,tol,maxIt)
   k=0;
   x=x0;
   nIt = 0;
   while (k<maxIt)
     if(df(x)== 0)
       fprintf("La derivada, da resultado 0");
       k=maxIt;
     else
       i = x - (f(x)/df(x))
       x = i;
       nIt = nIt + 1
       k=k+1;
     endif
  end
endfunction

Ok, i execute this comand "newton(@f,@df,0,10,2)", 2/3 of the program works good but if i do df(0), the result of this is 0 but the if dont works. I verify if df(0) return 0 and it´s ok. I´m new in Matlab/Octave. Sorry for the "english".

how to take specific(range) data from gps using pyhton

I am using adafruit ultimate GPS module connected to raspberry pi 3 B,I want to take a specific data from gps for example,if in range ( 103.467 E, 104.467 E) for longitude and latitude (1.556 N, 1.656 N) the program should print/run something,please help im very new to python and programming.

Here the current code that ive used to straight print coordinates without any range :)

import gps

session = gps.gps("localhost", "2947")

session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)

while True:

     try:

          report = session.next()

          if report['class'] == 'TPV':
              if hasattr(report,'lon'):
                  if hasattr(report,'lat'):
                      print 'latitude=',report.lat,'N','longitude=',report.lon,'E'


    except KeyError:
    pass
except KeyboardInterrupt:
    quit()
except StopIteration:
    session = None
    print "GPSD has terminated"

vendredi 28 octobre 2016

Javascript only 'Lights Out' game using if else statements

I was wondering if any of you could help me out with my code. I am struggling to find out how to make a 'lights out' game using only javascript. Attached is my code. My main question is how do I use if or if else statements to make the squares around the one clicked turn yellow. Your help is appreciated.

<style type="text/css">
        body {
            text-align: center;
            font-family: sans-serif;
        }
        table {
            margin: 0 auto;
            border-collapse: collapse;
            font-size: 52px;
            background-color: black;
        }
        table tr td {
            width: 100px;
            height: 100px;
            border: 2px solid white;
        }
    </style>

<center>


    <form name=lighttable>
        <table border>
            <tr>
                <td id="cell0" onclick="changeColor(this)"> </td>
                <td id="cell1" onclick="changeColor(this)"> </td>
                <td id="cell2" onclick="changeColor(this)"> </td>
                <td id="cell3" onclick="changeColor(this)"> </td>
                <td id="cell4" onclick="changeColor(this)"> </td>
            </tr>
            <tr>
                <td id="cell5" onclick="changeColor(this)"> </td>
                <td id="cell6" onclick="changeColor(this)"> </td>
                <td id="cell7" onclick="changeColor(this)"> </td>
                <td id="cell8" onclick="changeColor(this)"> </td>
                <td id="cell9" onclick="changeColor(this)"> </td>
            </tr>
            <tr>
                <td id="cell10" onclick="changeColor(this)"> </td>
                <td id="cell11" onclick="changeColor(this)"> </td>
                <td id="cell12" onclick="changeColor(this)"> </td>
                <td id="cell13" onclick="changeColor(this)"> </td>
                <td id="cell14" onclick="changeColor(this)"> </td>
            </tr>
            <tr>
                <td id="cell15" onclick="changeColor(this)"> </td>
                <td id="cell16" onclick="changeColor(this)"> </td>
                <td id="cell17" onclick="changeColor(this)"> </td>
                <td id="cell18" onclick="changeColor(this)"> </td>
                <td id="cell19" onclick="changeColor(this)"> </td>
            </tr>
            <tr>
                <td id="cell20" onclick="changeColor(this)"> </td>
                <td id="cell21" onclick="changeColor(this)"> </td>
                <td id="cell22" onclick="changeColor(this)"> </td>
                <td id="cell23" onclick="changeColor(this)"> </td>
                <td id="cell24" onclick="changeColor(this)"> </td>
            </tr>
        </table>
        <br>






        <script>




    function changeColor(o){
        o.style.backgroundColor=(o.style.backgroundColor=='yellow')?('transparent'):('yellow');
    }





        </script>

Trying to get percentage but keeps coming out 0 [duplicate]

This question already has an answer here:

I've been trying to figure this out for about 3 hours and I am finally almost done; I just need help with this last part. The problem is as follows: "Write a Java program that simulates the random flipping of two coins. At the start of the program prompt the user for the amount of times to flip the coin. Display each flip, and afterward display the percentages of heads and tails for each coin. Also, display the percentage that both coins were heads, and the percentage both coins were tails." I can't seem to figure out why I keep getting 0's for percentages on all of them.

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

        System.out.println("How many times would you like to flip the coins?");
        int n;
        n = in.nextInt();
        int coin1HeadsCount = 0;
        int coin2HeadsCount = 0;
        int coin1TailsCount = 0;
        int coin2TailsCount = 0;
        for (int i = 1; i <= n; i++)
        {
            int range = 2;
            int randomNum = (int) (range * Math.random()) + 1;
            int range2 = 2;
            int randomNum2 = (int) (range2 * Math.random()) + 1;
            if (randomNum == 1 &&
            randomNum2 == 1)
            {
                System.out.println("H H");
                coin1HeadsCount++;
                coin2HeadsCount++;
            }
            else if (randomNum == 1 &&
            randomNum2 == 2)
            {
                System.out.println("H T");
                coin1HeadsCount++;
                coin2TailsCount++;
            }
            else if (randomNum == 2 &&
            randomNum2 == 2)
            {
                System.out.println("T T");
                coin1TailsCount++;
                coin2TailsCount++;
            }
            else if (randomNum == 2 &&
            randomNum2 == 1)
            {                
                System.out.println("T H");
                coin1TailsCount++;
                coin2HeadsCount++;                
            }        
        }
        int total1Heads = (coin1HeadsCount / n);
        int total2Heads = (coin2HeadsCount / n);
        int total1Tails = (coin1TailsCount / n);
        int total2Tails = (coin2TailsCount / n);
        int bothHeads = ((coin1HeadsCount + coin2HeadsCount) / n);
        int bothTails = ((coin1TailsCount + coin2TailsCount) / n);
        System.out.println("Coin 1 was heads " + total1Heads + ", and tails " + total1Tails);
        System.out.println("Coin 2 was heads " + total2Heads + ", and tails " + total2Tails);
        System.out.println("The percentage both coins were heads was " + bothHeads);
        System.out.println("The percentage both coins were tails was " + bothTails);
    }
}

Output the corresponding value as well for the other chosen value (DO Loops)

PROGRAM ONE

REAL:: num1 = 200,num2 = 16,num3 = 10,num4
REAL:: counter,smallest

WRITE(*,*) "    Counter", "     num4"
WRITE(*,*) "    --------------------"
DO counter = 0.1,8,0.1
  num4 = (num1 * num2 * num3)/(counter * sqrt(num3**2 - counter**2))
  WRITE(*,*) counter,num4

  IF (counter == 0.1) THEN
     smallest = num4
  END IF

  IF (num4 < smallest) THEN
     smallest = num4
  END IF  

END DO
WRITE(*,*) "The smallest num4 is:", smallest

STOP
END PROGRAM ONE

The program needs to be ran to understand what I am trying to say.

This finds and displays the lowest "num4" value. What I also do want it to display is the corresponding "counter" value to the "num4" value. That "counter" value will go along with the last WRITE statement. It should say:

WRITE(*,*) "The smallest num4 is:", smallest, "for", counter

The output should be:

The smallest num4 is 640.021 for 7.10000

Bad operand types for binary operator ||

This is my line of code

if (tweet.indexOf("RT:" || "Rt:" || "rt:" || "rT:") > 0)

I am checking to see if the tweet the user inputs has any variations of rt:

JAVA: Why isn't my Switch Statement working?

Why isn't this switch statement changing the values of the object? For some reason when it runs any case, this.(anything) = (anything) doesn't change the value of the object. I want for example, in case "Living Room", this.upNext1 = "Pantry".

public class HauntedHouse {
public static class room{
    String previousRoom = "";
    String currentRoom = "Front Door";
    String upNext1 = "Living Room";
    String upNext2 = "Dining Room";
    String upNext3 = "Stairs";
    String object1 = "";
    String object2 = "";
    public room(){};
    public void room(String currentRoom){
        switch(currentRoom){
            case "Front Door":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Front Door";
                this.upNext1 = "Living Room";
                this.upNext2 = "Dining Room";
                this.upNext3 = "Stairs";
                this.object1 = "";
                this.object2 = "";
            case "Living Room":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Living Room";
                this.upNext1 = "Pantry";
                this.upNext2 = "1st Floor Bathroom";
                this.upNext3 = "";
                this.object1 = "Chest";
                this.object2 = "";
            case "Dining Room":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Dining Room";
                this.upNext1 = "Kitchen";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Candelabra";
                this.object2 = "";
            case "Stairs":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Dining Room";
                this.upNext1 = "Bedroom 1";
                this.upNext2 = "Bedroom 2";
                this.upNext3 = "Master Bedroom";
                this.object1 = "Candelera";
                this.object2 = "Shower";
            case "1st Floor Bathroom":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "1st Floor Bathroom";
                this.upNext1 = "";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Mirror";
                this.object2 = "Shower";
            case "Pantry":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Pantry";
                this.upNext1 = "";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Dusty recipe box";
                this.object2 = "Broom";
            case "Kitchen":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Kitchen";
                this.upNext1 = "Pantry";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Refrigerator";
                this.object2 = "Cabinet";
            case "Bedroom 1":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Bedrrom 1";
                this.upNext1 = "2nd Floor Bathroom";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Rocking Chair";
                this.object2 = "Window";
            case "2nd Floor Bathroom":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "2nd Floor Bathroom";
                this.upNext1 = "Bedroom 2";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Mirror";
                this.object2 = "Shower";
            case "Bedroom 2":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Bedroom 2";
                this.upNext1 = "Master Bedroom";
                this.upNext2 = "Bedroom 1";
                this.upNext3 = "";
                this.object1 = "Doll House";
                this.object2 = "Dresser";
            case "Master Bedroom":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Master Bedroom";
                this.upNext1 = "Master Bathroom";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Jewelry Box";
                this.object2 = "";
            case "Master Bathroom":
                this.previousRoom = this.currentRoom;
                this.currentRoom = "Master Bathroom";
                this.upNext1 = "";
                this.upNext2 = "";
                this.upNext3 = "";
                this.object1 = "Intricate Oil Lamp";
                this.object2 = "Shower";
        }

Having trouble getting my else statement to print in a while loop

Still very new to Python, so I apologize if anything in here is off. This is for a program where you enter a number, and get back a value. You have to enter a number, so I'm trying to make it say "different values needed" when the user enters a string. However, I have an int() around the input, which means I get the following error when I input a string:

ValueError: invalid literal for int() with base 10

My code is as follows:

while True:
 OVR = int(input('OVR?'))
 if OVR == 0:
   break
 elif OVR < 50:
   print('0.75M')
 elif OVR >= 50 and OVR < 60:
   print('8M')
 elif OVR >= 60 and OVR <= 70:
   print('15M')
 elif OVR > 70 and OVR <= 82:
   print('30M')
 elif OVR > 82:
   print("He's the GOAT, what do you think he wants?")
 else:
   print('different values needed')

I know it's probably a bad idea to have all those elifs, so I will eventually consolidate that into one formula. As said earlier, my main goal is that I want to make this so that it prints "different values needed" when the user enters a string. I've considered a try/except statement, but if I'm understanding them correctly, they are not really for calculating and printing things, and also couldn't take these elifs.

Java and mySQL why my if else statements are not working

Below I am asking the user to enter data, now if the user enters all field of data..then I get what i expect in return. Yet I want the user to be able to enter one value and print the entire row containing that one value the user entered. Now i am trying to use if else statements while the values are empty..but it is not working. Can someone tell me a better way?/ why this is not working?

import java.sql.DriverManager;
import java.sql.PreparedStatement;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSetMetaData;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class DbReader 
{
public static void main(String[] args)
{
Connection conn =  null;
Scanner in= new Scanner(System.in);
String testing = "";
String empty = "";
try
{                                                  
    Class.forName("com.mysql.jdbc.Driver");//need this for some reason
    conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/dealer", "root", "root");

    if(conn!=null)
    {
        System.out.println("connected successfully to database");
    }
    System.out.println("Please Enter Vehicle Information: ");
    System.out.println("Make");
    System.out.println("Color");
    System.out.println("Model");
    System.out.println("Year");
    String make = in.next();
    String color = in.next();
    String model = in.next();
    String year = in.next();
    //String userInput="FOR";
    if(make.equals(empty) && color.equals(empty)&& model.equals(empty)){
        testing ="SELECT * FROM cars WHERE year = '"+year+"';";
    }
    else if(make.equals(empty) && color.equals(empty)&& year.equals(empty)){
        testing ="SELECT * FROM cars WHERE year = '"+model+"';";
    }
    else if(make.equals(empty) && model.equals(empty)&& year.equals(empty)){
        testing ="SELECT * FROM cars WHERE year = '"+color+"';";
    }
    else if(model.equals(empty) && color.equals(empty)&& year.equals(empty)){
        testing ="SELECT * FROM cars WHERE year = '"+make+"';";
    }
    else
        testing = "SELECT * FROM cars WHERE make = '" + make+"' AND color = '"+color+"' AND model = '"+model+"' AND year = '"+year+"';";
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(testing);//this line causes me to lose connection why?..because i was printing from database not from table


    while(rs.next()) {
        if(rs.getString("make").equals(make) && rs.getString("color").equals(color))
        {
        System.out.println(" VIN: "+ rs.getString("vin"));
        //System.out.println(" MAKE: ");
        System.out.println(" MAKE: "+ rs.getString("make"));
       // System.out.println(" MODEL: ");
        System.out.println(" MODEL: "+ rs.getString("model"));
        //System.out.println(" COLOR: ");
        System.out.println(" COLOR: "+ rs.getString("color"));
        System.out.println(" PRICE: "+ rs.getString("price"));
        }else{
            System.out.println(" Sorry No Cars meet that descrption at this time ");
            }
    }
    st.close();
   rs.close();
    conn.close(); 
}catch(Exception e)
{
    System.out.println("not connected to database");
}
}
}

JAVA: Trying to update variables inside a for loop with statement. Only one variable gets updated

I'm new to Java and at a loss what I'm doing wrong. I'm just trying to save the highscore and then print it.

    int max = players[0].getHighScore();
    int bestIndex = 0;
    String bestName = "testing";

    for (int i = 1; i < players.length; i=i+1) {

        if (players[i].getHighScore() > max) {
            bestIndex = i;
            max = players[i].getHighScore();
            bestName = players[i].getName();
        }

    }
    System.out.println(bestIndex);
    System.out.println(max);
    System.out.println(bestName);

The variable max will update for every loop and then print the high score, no problems there. But the two other variables, bestIndex and bestName will just stay with the same value as initiated. I've even tried setting bestIndex and bestName to a constant and a string respectively inside the if statement but they won't change. If I remove the if statement, both will change, but ofcourse then I will just end up with the last entries, rather than the ones corresponding to the high score. So I figure the problem is with the if statement but other than that, I have no clue.

How does one change the value of a variable within an if statement

<body>
<pre>

<form>
<strong> Height:</strong>      <input id ="Height"><br/>
<strong> Base: </strong>       <input id ="Base"><br/>
<strong> Hypotenus: </strong>  <input id ="Hypotenus"><br/>
</form>

<button type ="Button" onclick="Evaluate()">Find Area</button>
<p id ="Answer"> Answer will appear here </p>
<script>
function Evaluate() {
    var H = document.getElementById("Height").value;
    var B = document.getElementById("Base").value;
    var Hy = document.getElementById("Hypotenus").value;

    if (B == NaN || null) {
        var Area = Math.sqrt(Math.pow(Hy, 2) - Math.pow(H, 2));
    }
    document.getElementById("Answer").innerHTML = Area;
}
</script>
</body>

I'm new to JavaScript and I've been trying to make a code that finds the formula of a triangle. My problem is after the if statement I would like to change the value of "Area" but I keep getting undefined everytime I run the code. How do I change the value of a variable within an if statement?

IBM dashDB sql statement for "insert row if not already existing"

I am currently working with the IBM dashDB and I need to know the sql statement for inserting a new row if this row does not already exist based to certain criteria. So, something like this:

INSERT INTO tablexyz (Col1, Col2, Col3) VALUES (val1, val2, val3) IF NOT EXIST (SELECT * FROM tablexyz WHERE val1 = x, val2 = y)

How can I do this?