mardi 31 janvier 2017

C++ program utilizing pointers branching and loops having output issues

This is a homework assignment that required the use of pointers to out put messages when the number input is divisible 3, by 5, and by 3 & 5. I have gotten the code to compile and run but I'm not getting my desired output and am not certain what needs changed. Here is my code:

#include <iostream>
#include <iomanip>

using namespace std;
using std::istream;

int main()
{
    const int i{3};                      // Variable initialization and declaration
    long* pnumber{};                     // Pointer definition and initialization
    long number1 {};                     // Declaration and initialization of variable number1
    long number2 [i];                    // Declaration and initialization of variable containing array of 3L numbers
    char indicator{ 'n' };               // Continue or not?

    pnumber = &number1;                  // Store address in a pointer

    for (;;)
    {
        cout << "Please enter any number less than 2 billion, "
             << "then press the Enter key: ";
        cin  >> number1;

        if (*pnumber % 3 == 0)           // Test if remainder after dividing by 3 is 0  
        {
            cout << endl
                << "Number: " << number1
                << "-Fizz" << endl
                << endl << "Do you want to enter another value (please enter y or n? ";
            cin >> indicator;           // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                  // Exit from loop
        }

        if (*pnumber % 5 == 0)         // Test if remainder after dividing by 5 is 0  
        {
            cout << endl
                << "Number: " << number1
                << "-Buzz" << endl
                << endl << "Do you want to enter another value (please enter y or n? ";
            cin >> indicator;         // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                // Exit from loop
        }

        if ((*pnumber % 3 == 0) && (*pnumber % 5 == 0))    // Test if remainder after dividing by 5 and 3 is 0 
        {
            cout << endl
                << "Number: " << number1
                << "-FizzBuzz" << endl
                << endl << "Do you want to enter another value (please enter y or n? ";
            cin >> indicator;         // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                // Exit from loop
        }

        else
        {
            cout << endl              // Default: here if not divisible by 3 or 5  
                << "Please enter another number."


                << endl << "Do you want to enter another value (please enter y or n? ";
            cin >> indicator;         // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                // Exit from loop
        }
    }

    pnumber = &number2 [i];               // Change pointer to address of number2

    for (;;)
    {
        cout << endl << endl 
             << "Please enter an array of number(s), where the number is less than 2 billion, "
             << "then press the Enter key: ";
        cin >> number2 [i];

        if (*pnumber % 3 == 0)           // Test if remainder after dividing by 3 is 0  
        {
            cout << endl
                << "Number: " << number2
                << "-Fizz" << endl
                << endl << "Do you want to enter another array (please enter y or n? ";
            cin >> indicator;           // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                  // Exit from loop
        }

        if (*pnumber % 5 == 0)         // Test if remainder after dividing by 5 is 0  
        {
            cout << endl
                << "Number: " << number2
                << "-Buzz" << endl
                << endl << "Do you want to enter another array (please enter y or n? ";
            cin >> indicator;         // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                // Exit from loop
        }

        if ((*pnumber % 3 == 0) && (*pnumber % 5 == 0))    // Test if remainder after dividing by 5 and 3 is 0 
        {
            cout << endl
                << "Number: " << number2
                << "-FizzBuzz" << endl
                << endl << "Do you want to enter another value (please enter y or n? ";
            cin >> indicator;         // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                // Exit from loop
        }

        else
        {
            cout << endl              // Default: here if not divisible by 3 or 5  
                << "Please enter another number."


                << endl << "Do you want to enter another value (please enter y or n? ";
            cin >> indicator;         // Read indicator
            if (('n' == indicator) || ('N' == indicator))
                break;                // Exit from loop
        }
    }

    cout << endl;
    return 0;
}

Haskell If Statement Condition

This is my first time getting into the more "academic" programming languages. Coming from the land of Java/C, I'm having quite some issues with If statements in Haskell. It seems all the examples use a single argument, and a simple gt, ls, or eq for comparisons.

What I'm attempting to do is check if a function's argument is even or odd, then return a value based off that result. This is to speed up the calculation of an exponent, as:

n^k = (n^(k/2))^2 if k is even

n^k = n * n^(k-1) if k is odd

Here's what I have so far:

fastExp1 :: Integer -> Integer
fastExp1 x y =
    if y `mod` 2 = 1
        then x * x^(y-1)
    else if y `mod` 2 = 0
        then (x^(y/2))^2
    else 0

I've tried to build it using guarded equations, but I just can't seem to get my head around how to build it:

fastExp2 :: Integer -> Integer
fastExp2 x y | (x `mod` 1) = 0     = (x^(y/2))^2
             | (x `mod` 1) = 1     = x * x^(y-1)
             | otherwise = 0

In Java, this isn't really any issue:

public static int fastExp1 (int x, int y) {
    if (y%2 == 0) {
        // The exponent was even.
        return (int) Math.pow((Math.pow(x,(y/2))), 2);
    } else if (y%2 == 1) {
        // The exponent was odd.
        return (int) Math.pow((x*x), (y-1));
    } else {
        return 0;
    }
}

I can confirm that the Java code works as intended, but with the Haskell I get:

C:\hello.hs:16:5:

parse error in if statement: missing required then and else clauses

Failed, modules loaded: none.

Ifelse statment across multiple rows

Looking to add a column based on the values of two columns, but over more than one row.

Example Dataset Code:

A = c(1,1,1,2,2,2,3,3,3,4,4)
B = c(1,2,3,1,2,3,1,2,3,1,2)
C = c(0,0,0,1,0,0,1,1,1,0,1)
data <- data.frame(A,B,C)

Dataset:

   A  B  C
1  1  1  0
2  1  2  0
3  1  3  0
4  2  1  1
5  2  2  0
6  2  3  0
7  3  1  1
8  3  2  1
9  3  3  1
10 4  1  0
11 4  2  1 

Ifelse statements:

What I am trying to achieve is "Create column D.If column C == 1 in any row where column A == x, column D = 1. Else column D == 0"

Desired Output:

   A  B  C  D
1  1  1  0  0
2  1  2  0  0
3  1  3  0  0
4  2  1  1  1
5  2  2  0  1
6  2  3  0  1
7  3  1  1  1
8  3  2  1  1
9  3  3  1  1
10 4  1  0  1
11 4  2  1  1

What I've done:

I've thought about it today but can't come up with a logical answer, I've tried looking at the data in long and wide formats but nothings jumped out.

Note: In actual application the number of times x appears in column C is not equal (some contain one repeat in the dataset, others contain 20).

Python Else won't work with Modules imported?

I've been testing stuff with modules specifically time module, and I tried doing "Else", but I just get a syntax error over the "Else", I've looked over the internet a lot, and on here, and I can't find anything, so I decided to ask Myself, I'm probably going to sound like the stupidest person on earth because of this.

Here's my code,

import time

input ("Hello, would you like to sleep?")
if input == "Yes":
    time.sleep(0.5)
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
print("You have awoken!")


else:
print("Alright.")

Guess the random number game

I am making a number guessing game and I do not know how to incorporate a certain number of guesses the users has to get the correct answer. I want the user to have only 3 guesses to guess the number but after 3 guesses, they lose if they do NOT get it correct. Here is my code below:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
srand ( time(NULL) );

cout << "Select a difficulty: 1) Easy, 2) Medium, 3) Hard " << endl;
int userlevel;
int userinput;
int randomNumber;
cin >> userlevel;
{
if (userlevel==1)
  cout << "You chose Easy: 3 chances to guess correctly" << endl;
  cout << "Pick a number between 1 and 10: " << endl;

  cin >> userinput;
  randomNumber = rand() % 10 + 1;

  if (randomNumber==userinput)
    cout << "You, guessed correctly! You win!" << endl;
  else
    cout << "I'm sorry, that is not correct. You lose." << endl;
}


{

  if (userlevel==2)
   cout << "You chose Medium: 4 chanaces to guess correctly" << endl;
   cout << "Pick a number between 1 and 50: " << endl;

     cin >> userinput;
     randomNumber = rand() % 50 + 1;

   if (randomNumber==userinput)
     cout << "You, guessed correctly! You win!" << endl;
   else
    cout << "I'm sorry, that is not correct. You lose." << endl;
  }


   {
    if (userlevel==3)
     cout << "You chose Hard: 5 chances to guess correctly" << endl;
     cout << "Pick a number between 1 and 100: " << endl;

     cin >> userinput;
     randomNumber = rand() % 100 + 1;

  if (randomNumber==userinput)
       cout << "You, guessed correctly! You win!" << endl;
     else
       cout << "I'm sorry, that is not correct. You lose." << endl;

 }
  return 0;
 }

Javascript Logical Operator Confusion

I have a complete working program, but I am very confused about the logic in a couple of my conditional statements after I fiddled with them in an attempt to get the program to do what I want.

    while (col < 5 || 20 < col || Number.isInteger(col)) {
        col = prompt("Columns (Int between 5 and 20): ","10");
        console.log("col " + col);
    }
    while (row < 5 || 20 < row || Number.isInteger(row)) {
        row = prompt("Rows (Int between 5 and 20): ","10");
        console.log("row " + row);
    }

    if (row>col) {size = 400/col;console.log("colmore");}
    else if (col>row) {size = 400/row;console.log("rowmore");}
    else {size = 400/col;console.log("same");}
    console.log("size " + size);

Now my program prompts for the number of Columns and then Rows. For example, I'll put in 20 for columns, and 5 for rows - columns are obviously more than rows then. So this happens:

col 20
row 5
colmore
size 20

Obviously that's what I want it to do, but I'm getting hung up because that first condition

if (row>col)

should mean if rows are more than columns, and the program should continue to the next statement... or am I just completely losing my mind...?

Excel - IF with 3 Outcomes

This question has been asked and answered, unfortunately when I adapt the answers to my situation all I get back is #Name. My need is a return out of "Positive", "Negative" or a no response, as follows

  • “Positive” any number >0
  • “Negative” any number <0 (negative number)
  • No return for a zero

I have tried =IF(A1=0;””;IF(A1<=0.01;”Negative”;“Positive”)) with using both semi-colons and commas.

Any help appreciated.

Not sure how to use switch method

I'm trying to make the app add a topping only if the box is checked. I was following a lesson and they showed me how to display the String with the true or false statement next to it. I don't want that. I actually want the string to appear only if the checkbox is checked. Thank you.

Hi this is the XML:

   <EditText
       android:id="@+id/edit_text"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Enter your Name"
       android:layout_margin="16dp"/>

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/chocolateCheckBox"
    android:text="Add Chocolate On Your Coffee"
    android:layout_margin="16dp"
    android:layout_below="@id/edit_text"
    />
<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/creamCheckBox"
    android:text="Add Cream On Your Coffee"
    android:layout_marginLeft="16dp"
    android:layout_marginBottom="8dp"
    android:layout_below="@id/chocolateCheckBox"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="QUANTITY"
    android:id="@+id/quantity"
    android:textSize="16sp"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="16dp"
    android:layout_below="@id/creamCheckBox"
    />


<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_margin="16dp"
    android:id="@+id/adding_layout"
    android:layout_below="@id/quantity">

    <Button
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:text="-"
        android:onClick="decrement"
        android:id="@+id/minus_button"
        android:width="48dp"
        android:height="48dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:id="@+id/quantity_text_view"
        android:textSize="16sp"
        android:textColor="#000000"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"/>
    <Button
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:text="+"
        android:onClick="increment"
        android:id="@+id/plus_button"/>
</LinearLayout>


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/order_summary"
    android:text="ORDER SUMMARY"
    android:textSize="16sp"
    android:layout_below="@id/adding_layout"
    android:layout_marginLeft="16dp"/>


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:id="@+id/order_summary_text_view"
    android:textSize="16sp"
    android:layout_margin="16dp"
    android:layout_below="@id/order_summary"
    android:textColor="#000000"/>


<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/order_button"
    android:text="ORDER"
    android:layout_marginLeft="16dp"
    android:layout_below="@id/order_summary_text_view"
    android:onClick="submitOrder"/>

  </RelativeLayout>
  </ScrollView>

and this is the java code:

public class MainActivity extends AppCompatActivity {

/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See http://ift.tt/1Shh2Dk for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See http://ift.tt/1Shh2Dk for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
int quantity = 0;

public String submitOrder(View view) {
    CheckBox addChocolate = (CheckBox) findViewById(R.id.chocolateCheckBox);
    boolean hasChocolate = addChocolate.isChecked();

    CheckBox addCream = (CheckBox) findViewById(R.id.creamCheckBox);
    boolean hasCream = addCream.isChecked();


    if (hasChocolate = true){
        String chocolate = "Add Chocolate to the coffee";
        return chocolate;
    }
    if (addCream.isChecked()){
        String cream = "Add Cream to the coffee";
        return cream;
    }


    EditText enterName = (EditText) findViewById(R.id.edit_text);
    Editable addName = enterName.getText();

    int price = calculatePrice();
    String priceMessage = createOrderSummary(addName, price, chocolate,        cream);
    displayMessage(priceMessage);
    return priceMessage;
}

/**  Calculates the price of the order.  */
private int calculatePrice() {

    return quantity * 5;
}


/** displays the number of coffee between the + and - buttons */
private void displayQuantity(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + number);
}
private String createOrderSummary(Editable enterName, int calculatePrice, boolean chocolate, boolean cream) {
    String priceMessage = "Name = " + enterName + "\nQuantity : " + quantity + "\n" + chocolate + "\n" + cream + "\nTotal: £ " + calculatePrice + "\nThank you!";
    return priceMessage;

}

public void increment(View view) {
    quantity = quantity + 1;
    displayQuantity(quantity);
}

public void decrement(View view) {
    quantity = quantity - 1;
    displayQuantity(quantity);
}




/**
 * This method displays the given text on the screen.
 */
private void displayMessage(String message) {
    TextView orderSummaryTextView = (TextView)   findViewById(R.id.order_summary_text_view);
    orderSummaryTextView.setText(message);
}

Excel -- how to return certain values if cells in a column match multiple criteria

I want to search for certain values in a column and return specific words based on those values.

In the screenshot below, I'd like rows B-D to function as one. So only return "Pumpkin Pie", "Cookies", and "Rice". The rest will fall into "Other"

Screenshot

IMDBpy KeyError: 'rating'

I'm trying to execute this code that shows me some IMDB movie ratings:

import json
import sys

import imdb
import sendgrid

NOTIFY_ABOVE_RATING = 7.5

SENDGRID_API_KEY = "API KEY GOES HERE"


def run_checker(scraped_movies):
    imdb_conn = imdb.IMDb()
    good_movies = []
    for scraped_movie in scraped_movies:
        imdb_movie = get_imdb_movie(imdb_conn, scraped_movie['name'])
        if imdb_movie['rating'] > NOTIFY_ABOVE_RATING:
            good_movies.append(imdb_movie)
    if good_movies:
        send_email(good_movies)


def get_imdb_movie(imdb_conn, movie_name):
    results = imdb_conn.search_movie(movie_name)
    movie = results[0]
    imdb_conn.update(movie)
    print("{title} => {rating}".format(**movie))
    return movie


def send_email(movies):
    sendgrid_client = sendgrid.SendGridClient(SENDGRID_API_KEY)
    message = sendgrid.Mail()
    message.add_to("trevor@example.com")
    message.set_from("no-reply@example.com")
    message.set_subject("Highly rated movies of the day")
    body = "High rated today:<br><br>"
    for movie in movies:
        body += "{title} => {rating}".format(**movie)
    message.set_html(body)
    sendgrid_client.send(message)
    print("Sent email with {} movie(s).".format(len(movies)))


if __name__ == '__main__':
    movies_json_file = sys.argv[1]
    with open(movies_json_file) as scraped_movies_file:
        movies = json.loads(scraped_movies_file.read())
    run_checker(movies)

But it returns me this error:

C:\Python27\Scripts>python check_imdb.py movies.json
T2 Trainspotting => 8.1
Sing => 7.3
Traceback (most recent call last):
  File "check_imdb.py", line 49, in <module>
    run_checker(movies)
  File "check_imdb.py", line 16, in run_checker
    imdb_movie = get_imdb_movie(imdb_conn, scraped_movie['name'])
  File "check_imdb.py", line 27, in get_imdb_movie
    print("{title} => {rating}".format(**movie))
KeyError: 'rating'

This happens because it's trying to print a movie that have no rating yet. I tryed if/else many times to fix it, but no success.

Trying to make age guessing game in Javascript with counter function; has not worked hitherto

Below is my code thus far for an educational exercise requiring that I make a guessing game with multiple hints and a counter function that terminates after four turns. I've searched SO extensively and found no help. I've reviewed my textbook to no avail. This code is as best as I can do with my present knowledge (class has only been on for a week, so admittedly that is paltry). Any assistance would be greatly appreciated!

if (answerSix != myAge) {
            while (guesses <= 4) {
                if (answerSix > myAge)
                    {alert('Too old!')};
                    guesses++;
                else if (answerSix < myAge)
                    {alert('Too young!')};
                    guesses++;
                }
                else if (guesses >= 4) {
                    {alert('You have guessed too many times! Game over!')};
                    {break};
                }
                }
            }
        else if (answerSix === myAge) {
                {alert('Got it like the \'79 SuperSonics!')};
                {break}
            }
            else {alert('Answer is invalid!')}

No listening to a flavor change if it is caused by an event from a Swing GUI

            public void flavorsChanged(FlavorEvent e) {
                Transferable contentsTransferable = clipboard.getContents(null);
                // NB the Transferable returned from getContents is NEVER the same as the 
                // clearing Transferable!

                if (!suppressOutput) {
                    System.out.println(String.format("# clipboard UPDATED, src %s, string %s, clearingT? %b", e.getSource(), e.toString(),
                            contentsTransferable == clearingTransferable));
                    try {
                        String stringData = (String)clipboard.getData(DataFlavor.stringFlavor);
                        System.out.println(String.format("# string data |%s|", stringData ));

                    } catch (UnsupportedFlavorException | IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } 
                }

                else {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            suppressOutput = false;                                
                        }
                    });

                }
                suppressOutput = true;
                clipboard.setContents(clearingTransferable, null);
            }
        });

    } 

});

I need to have the above not trigger when I have the event below triggered. The above will still need to trigger if I've copied anything otherwise. This is because I will be replacing the println with code to write what ever has been recently copied into a text file and don't want repeats of anything that would already be in the file.

// selection from first list above placed on clipboard
DefaultListSelectionModel m = new DefaultListSelectionModel();
m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
m.setLeadAnchorNotificationEnabled(false);
clipboardStorageList.setSelectionModel(m);

clipboardStorageList.addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent e) {
        String element = clipboardStorageList.getSelectedValue().toString();
        StringSelection stringSelection = new StringSelection(element);
        Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
        clpbrd.setContents(stringSelection, null);
      }
  });

Finding char index in a char

I want to have a function that returns an index of first occurrence of a char t in char s. My attempt, which is obviously wrong,is:

int f(char* s, char* t){
int a = strlen(t);
int counter=0;

   for(int i=0; t[i]!=0; i++){
    for(int j=0; s[j]!=0; j++){
        if(t[i]==s[j]){

        }
        break;
    }
    }
return j;
}

I wanted to find a first letter of char t in char s and then check whether next letter is identical in char s as in char t. And then return an index e.g. f("abaabb", "bb")=4.

I would prefer to keep this as simple as possible, nothing sophisticated to do this should be required. If this question could be improved please tell me how could i make it better?

Java, Should I use switch-case or if-else within a switch-case?

This program copies a string (a password) on the clipboard, and I want to add the option to copy a username as well. So if a user forgets his/her username on an online account (or is just lazy), it is possible to get that as well.

First the user chooses the game/whatever, then the user gets to choose what gets copied to the clipboard: the username or the password. So do I add another switch-case under all those options, or do I go with an if-statement? Should I put a function call under each of those?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package helloworldapp;

/**
 *
 * @author Au-Thor
 */
import java.util.Scanner; 
import java.awt.datatransfer.*;
import java.awt.Toolkit;

public class HelloWorldApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       int n = 1;
       String addedString = "replace"; //This is for later usage
       String titleNames[] = {"Planetside 2","Nasty Website","Useless Social Media Account","Someother"};
       Scanner userInput1 = new Scanner(System.in);
       String thePassword = "Nothing";

       System.out.println("Enter a key: "); //This is for later usage
       addedString=(userInput1.nextLine()); //This is for later usage

    while(n!=0){ 
        Scanner userChoice = new Scanner(System.in);  // Reading from System.in

        for(int i = 0; i < titleNames.length; i++){  //Menu print-out
            int h=i+1;
            System.out.println( "["+h+".] " + titleNames[i]); 
        }

        System.out.println( "\n[0.] Quit\n");         
        System.out.println("\nEnter a number: ");
        n = userChoice.nextInt(); // Scans the next token of the input as an int.

        switch (n) {
            case 1:  //Ask if the user wants the username or the password
                     thePassword = "MAD PASSWORD FOR MY ACCOUNT" ;
                     break;
            case 2:  thePassword = "Replace";
                     break;
            case 3:  thePassword = "Replace";
                     break;
            case 4:  thePassword = "Replace";
                     break;
            case 5:  thePassword = "Replace";
                     break;
            case 6:  thePassword = "Replace";
                     break;
            case 7:  thePassword = "Replace";
                     break;
            case 8:  thePassword = "Replace";
                     break;
            case 9:  thePassword = "Replace";
                     break;
            case 10: thePassword = "Replace";
                     break;
            case 11: thePassword = "Replace";
                     break;
            case 12: thePassword = "Replace";
                     break;
            case 0:
                break;
            default: System.out.println("\nOption does not exist");;
                     break;
        }
        System.out.println("Current: " +thePassword+"\n"); //Change this to the Page or Game the credentials are for

        String myString = thePassword;
        StringSelection stringSelection = new StringSelection(myString);
        Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
        clpbrd.setContents(stringSelection, null);
        }

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

Extra stuff: Is there something that could be done more efficiently (besides all of it :D)? Should I use more functions? Can I use a function to produce a switch-case structure that scales to the parameters given to it, to create all the switch cases with the same function, is that even possible?

Only the first if statement is executing in jQuery

I have two jQuery if statements that perform a remove() from a submenu. They work fine if there is only one true statement, but if there is an id1 & an id2 on the page, only the first if triggers.

if ($('#id1').length==0) { $('#submenu li').eq(2).remove();}

if( $('#id2').length==0) { $('#submenu li').eq(3).remove();}

MySQL event with IF-ELSE clause is not working

I have this event in my DB and it was working great without the IF-ELSE clause. It was like this before:

DELIMITER $$
CREATE EVENT update_count_days
ON SCHEDULE EVERY '1' minute
STARTS '2017-01-01 00:00:00'
DO 
BEGIN
     SET SQL_SAFE_UPDATES = 0;
    UPDATE bots SET days_from_start = datediff(current_date(),start_date);
END$$    
DELIMITER ;

However, When I've dropped the event and add the IF-ELSE clause, the event stopped working:

DELIMITER $$
CREATE EVENT update_count_days
ON SCHEDULE EVERY '1' minute
STARTS '2017-01-01 00:00:00'
DO 
BEGIN

    IF (end_date IS NULL) THEN
     SET SQL_SAFE_UPDATES = 0;
    UPDATE bots SET days_from_start = datediff(current_date(),start_date);
    else
     SET SQL_SAFE_UPDATES = 0;
    UPDATE bots SET days_from_start = datediff(end_date,start_date);
    END IF;
END$$    
DELIMITER ;

Can you please help me figure out what's the problem? Thank you!

How to call multiple function usinf if statement in python?

I want to do the following program in python :

def f1():
    a=1
    return a
def f2():
    a=2
    return a
r=raw_input("Enter no of functions you want :")
    if r=1:
    v1=f1() or v2=f2()
elif r=2:
    v1=f1()
    v2=f2()

How can I do this please help.

WP Job Board If Statement in job.php

Hi I am trying to write a custom if statement in the job.php using WP job board for when the company name equals career_edge to not display a disclaimer and all other instances to display the disclaimer. Below is what I creatively came up with. Not very advanced with php. Any help would be great!

<?php if($job->company_name == "career_edge"): ?>

<?php else; ?>
     <p>Disclaimer text goes here</p>
<?php endif; ?>

Drawing exercise in java

I should do this program in java that asks me to write a program that issues a V composed of asterisks like the following picture:

        *
       *
*     *
 *   *
  * *
   *

This is the program that I created but it does not work:

import java.util.*;

public class Disegnav{
  public static void main (String [] arg){
    Scanner sc = new Scanner(System.in);
    for(int i = 5; i>0; i--){
        int k = 9, l=0, x=3;
        for(int j = 0; j<=9 ; j++){
            if(i>3 && j<k)
                System.out.print(" ");
            else
                if(j==k || i==l || i==x)
                    System.out.print("*");
                else
                    System.out.print(" ");
            k--;
            l++;
            x--;
        }
        System.out.println();
    }
  }
}

bash break out of if statement in while loop

Not sure if it's possible but I'm trying to break out of an if statement that's in a while loop. I do not want to exit the while loop though. I tried using exit and break but both exit the while loop. The problem is that I don't know which folder the file I'm looking for is which is why I want to exit the current if statement when I match the searched file so that I can move on to the next serial number.

I have a txt file called 'drives-fw-sn.txt' that contains a list of serial numbers. Breakdown of code:

  • I read in one serial number at a time from drives-fw-sn.txt while a while loop
  • I search for a file called output_log using find
  • I then print the first occurrence of the serial number from the found file
  • Next I print that the log has been found and want

Here's a snippet of my code (there are more than 3 test folders). Note that it still contains the exit commands which exit the while loop.

while read node; do
   if find ./test1/*log* -maxdepth 2 -type f -name output_log -exec egrep -m 1 $node {} \; ; then
     echo "Log SN $node available"
     exit
   fi
   if find ./test2/*log* -maxdepth 2 -type f -name output_log -exec egrep -m 1 $node {} \; ; then
     echo "Log SN $node available"
     exit
   fi
   if find ./test3/*log* -maxdepth 2 -type f -name output_log -exec egrep -m 1 $node {} \; ; then
     echo "Log SN $node available"
     exit
   fi
done < drives-fw-sn.txt

XSLT: How to emulate an IF-ELSE clause

Problem:

IF COND1 = true
{
    WHEN COND2 = TRUE
    {
        PRINT X1
    }
    OTHERWISE 
    {
        WHEN COND3 = TRUE {PRINT X2}
        OTHERWISE {PRINT X3}
    }
}

I have use for COND1 and , for COND2 and COND3 but its printing value X1 for all conditions. Can someone pls tell me how to apply above scenario?

<xsl:if test="($Id='5')">
<xsl:choose>
 <xsl:when test="(Cond='') "></xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="(Cond='true')or(Cond='Y')">Y</xsl:when>                                                                                   
<xsl:otherwise>N</xsl:otherwise></xsl:choose>
</xsl:otherwise>    
</xsl:choose>
</xsl:if>

Redundant instructions in two conditions

I want to optimize the following code:

 for myFile in myFiles:
        file = open(filename, 'rt')
        try:
            if CLIENT == "C1":
                head = rows[:7]
                tail = rows[7:]
                for row in rows:
                    if "".join(row)!= "":
                        if not u_pass:
                            header = [ row.strip().replace(" ", "_") for row in row[3:] ]
                            u_pass = True
                        else:
                            self.usecases(row, data, index)

            elif CLIENT == 'C2':
                reader = csv.reader(file)
                firstline = next(reader)
                secondline = next(reader)
            else:
                for row in rows:
                    if "".join(row)!= "":
                        if not u_pass:
                            header = [ row.strip().replace(" ", "_") for row in row[3:] ]
                            u_pass = True
                            # Recuperation des donnees
                        else:
                            self.usecases(row, data, index)

The code below is repeated twice in the previous code, meaning there are some common instructions between these conditions "

for row in rows:

            if "".join(row)!= "":
                if not u_pass:
                    header = [ row.strip().replace(" ", "_") for row in row[3:] ]
                    u_pass = True
                else:
                    self.usecases(row, data, index)

lundi 30 janvier 2017

Alternate to If...else-if

What is best way to reduce the line of code for many if...else-if statements. Apart from the switch case

if(a>0 && a<=5){
a=5;
}
else if(a>5 && a<=10){
a=10;
}
else if(a>10 && a<=15){
a=15;
}
else if(a>15 && a<=20){
a=20;
}
.
.
.
.
.
else if(a>95 && a<=100)
a=100;
}

I have gone through many posts but could not find the feasable solution.

How to use IF-ELSE statement in a query?

I want to set a date for variable declared within a query depends on a condition. But I couldn't find a working solution for this.
Query

declare @dt datetime;SET @dt ='2010-08-02';set @dt=DATEADD(day,-1,@dt) 
declare @START datetime
declare @END datetime

set @START=(select DATEADD(dd, -(DATEPART(dw, @dt)-2), @dt) [Start])
set @END=(select DATEADD(dd, 8-(DATEPART(dw, @dt)), @dt) [End]);

END
PRINT @START
PRINT  @END 

What I want to do is set date for @START and @END depends on the date of @dt.

For loop not printing what I expect. Need assistance

int marsHeight = ml.getHeight() / 100 * 100; // measure by 100s despite height value
int chartHeight = (marsHeight >= 1000) ? marsHeight : 1000;
for (int i = 0; i <= (chartHeight / 100); i++)
{
    if (i == 0)
    {
        Console.WriteLine("{0}m: \t*", (marsHeight - (i * 100))); // in order to print in descending order: (height - (i * 100)
        continue;
    }
    Console.WriteLine("{0}m:", (marsHeight - (i * 100)));
}

If marsHeight is greater than 1000 the program will print out:

[marsHeight]m: 
[marsHeight - 100]m:  
...  
1000m:   
900m:  
800m:   
...   
0m:  // this works perfectly!

If marsHeight is less than 1000 (like 990)the program prints out:

900m: *  
800m:  
...  
0m:  
-100m:

What I want is this:

1000m:  
900m: *  
800m:  
...  
0m:  

I'm new to programming. Where am I going wrong with my logic?

Ruby: What is "Self" inside "If" Statement of Instance Method

What does "self" refer to when it's inside an "if" statement (or is it called block?) that is inside an instance method?

I'm referring to my code in the last method: "apply_discount"

I thought it'd get me the @total and @discount instance variables, but it's not doing so.

So, basically, how would I get these variables from the my place in the "if" statement I'm referring to by using "self"?

Or should I use another way?

class CashRegister

    attr_accessor :total, :discount

    def initialize(discount = 0)
        @total = 0
        @discount = discount
    end

    def add_item(title, price, quantity = 0)
        if quantity > 0
            self.total += (price * quantity)
        else
            self.total += price
        end
    end

    def apply_discount
        # total = self.total
        # discount = self.discount
        if self.discount > 0
            self.total = self.total - (self.total * (self.discount / 100.0))
            "After the discount, the total comes to $#{self.total}."
        else
            "There is no discount to apply."
        end
    end
end

Thanks for your help!

if statement is not working and is skipped to else part

//this is my source file, .cpp
#include <iostream>
#include <string>
#include "kingdom.h"
namespace westeros{
    void display(Kingdom pKingdom[], int kingdomElement, string KingdomName){
        cout << " ---------------- " << endl;
        cout << " Searching for kingdom " << KingdomName << " in westeros " << endl;
        if (pKingdom[kingdomElement].m_name == KingdomName){
            cout << " --------------------- " << endl;
            cout << KingdomName << ", population " << pKingdom[kingdomElement].m_population << endl;
            cout << " --------------------- " << endl;
        }
        else{
            cout << " --------------------- " << endl;
            cout << KingdomName << " is not part of Westeros. " << endl;
            cout << " --------------------- " << endl;
        }
    }
}

//this is my main file
#include <iostream>
#include "kingdom.h"
#include <string>
using namespace std;
using namespace westeros;

int main(void){
    int count = 0;
    Kingdom* pKingdoms = nullptr;
    pKingdoms = new Kingdom[count];
    display(pKingdoms, count, "Mordor");
    display(pKingdoms, count, "The_Vale");
    delete[]pKingdoms;
    pKingdoms = nullptr;
    return 0;
}

//this is my header file
#ifndef KINGDOM_H_
#define KINGDOM_H_
using namespace std;
namespace westeros{
    class Kingdom{
    public:
        char m_name[32];
        int m_population;  
    };
    void display(Kingdom pKingdom[], int kingdomElement, string KingdomName);
}
#endif

How it should work is that when I put in The_Vale in my array, it should say The_Vale, population, population size of kingdom in integer for my display function and

When I call for Mordor's case, since Mordor is not part of Westeros, it should print out message saying Mordor is not part of Westeros since I didn't put Mordor in my array.

But, the problem is that the code prints out message that THe_Vale is not part of Westeros when it should say The_Vale, population, and population size of vale since it is in the array. Does anybody know how to solve this problem?

Cash Register with Dollars and Quarters output in C

I have to program a cash register that has a user input the amount to be paid and it has to output the amount to be paid and then output the number of loonies required to pay the amount followed by the number of quarters required to pay the amount, etc... I've managed to out the amount to be paid as well as the number of loonies required by truncating the amount to be paid, but I'm at a loss as to how to solve the number of quarters, dimes, nickels and pennies required to pay. Here's my code:

#include <stdio.h>
#include <math.h>

int main (void)

{
        double cost;
        int loonies, quarters;
        float loonreq;


        printf ("Please enter the amount to be paid: ");
        scanf ("%lf", &cost);

        printf ("Change Due: $ %.2f\n", cost);

        loonies = cost;
        printf ("Loonies required: %d, ", loonies);

        loonreq = cost - loonies;
        printf ("balance owing: $ %.2f\n", loonreq);

        return 0;
}

gfortan error: Unclassifiable statement at (1) - Else if statement

I am a new Fortran user, trying to run a code that was given to me, with little instruction. When I try to compile, I get "Error: Unclassifiable statement at (1)" at every else if statement in the code. The same error does not occur for the initial if statement nor for the final else statement. Does anyone have any suggestions? Could it be to do with the line length at each of the else if statements?

      program main

  IMPLICIT REAL*8(A-H, O-Z)
  character fname1*30
c*******************************************
c***** input file: input_fslip
c*****             seismo_bellslip_100yr.dat
c***** output file: tapered_slip.dat
c*******************************************
c***** Define constants
  dimension bound(5,4),deficit(5),akb(4)

  open(1,file='input_fslip')
  rewind 1
  open(2,file='seismo_100yr.dat')
  rewind 2
  open(9,file='tapered_slip.dat')
  rewind 9

  do i=1,4
   read(1,*) (bound(j,i),j=1,5)
  end do
  read(1,*) (deficit(j),j=1,5)
cccc      read(1,*) exp_rate
  do i=1,4
   akb(i)=(bound(4,i)-bound(2,i))/(bound(3,i)-bound(1,i))
  end do

  do i=1,999999999
   read(2,*,end=900) alat,alon,depth,slipn,slipe
cccc segment D
  if(alat.le.((alon-bound(1,1))*akb(1)+bound(2,1)-bound(5,1))) then
     slipn_new = slipn * deficit(1)/100.0
     slipe_new = slipe * deficit(1)/100.0
cccc transition zone between D and C
  else if(alat.gt.((alon-bound(1,1))*akb(1)+bound(2,1)-bound(5,1)).
 *     and.alat.le.((alon-bound(1,1))*akb(1)+bound(2,1)+bound(5,1))) then
     aa=alat-((alon-bound(1,1))*akb(1)+bound(2,1)-bound(5,1))
     bb=((alon-bound(1,1))*akb(1)+bound(2,1)+bound(5,1))-alat
     ddefic=(deficit(2)*aa+deficit(1)*bb)/(aa+bb)
     slipn_new = slipn * ddefic/100.0
     slipe_new = slipe * ddefic/100.0
cccc segment C
  else if(alat.gt.((alon-bound(1,1))*akb(1)+bound(2,1)+bound(5,1)).
 *     and.alat.le.((alon-bound(1,2))*akb(2)+bound(2,2)-bound(5,2))) then
     slipn_new = slipn * deficit(2)/100.0
     slipe_new = slipe * deficit(2)/100.0

The code continues beyond here and there are several more else if statements, but I felt it unnecessary to include them, as they have similar structure. Let me know if I can provide any more info.

Thanks!

Error in an if statement not reponding to clauses

I need to make a file which will write basic statistics questions for a question bank.

I wrote a script in r in which in each cycle of a for statement a data set is created and then converted to a single frequency vector. Then a question is selected with the following pattern: "q1" in cycle 1, "q2" in cycle 2, "q3" in cycle 3, "q1" in cycle 4, "q2" in cycle 5, etc. This is performed by an if statement.

The questions and answers are written into a file named with the date.

The problem is that the answers are wrong, the program sometimes keeps the last value and I can't figure it out why. This is a sample output:

The code I'm using is the following:

Aaa <- function() 
{ 
  Qt  <<- readline(prompt="Iterations:")  
  } 

Aaa() 

##### Create file to sink to:#################
Date.<-Sys.Date()
Date.<-format(Date., format="%Y%m%d")
Archivo<- paste(Date.,".txt",sep="")

##### Create iterations ######################

sink(Archivo, append=FALSE)
cat("PRUEBA")
cat("\n")
sink(NULL)

for (i in 1:Qt){
  j<-(i/3-trunc(i/3))*3  

sink(Archivo, append=TRUE)

##### Generación de variables y cálculos #####  

  x<-round(rnorm(400,55,12),0)

  cuts<-seq(10.5,100.5,9)
  x<-x[x>10]
  x<-x[x<101]
  Table.<-hist(x,breaks = cuts,plot = FALSE)$counts
  Class. <- sample(3:9,1)

if (j==0) {
  Qstn <- paste("What is cum sum for class ",Class.,"?",sep="")
  Answ<-cumsum(Table.)[Class.]
} else if (j==1) {
  Qstn <- paste("What % of data corresponds to class ",Class.,"?",sep="")
  Answ<-Table.[Class.]/sum(Table.)*100 
} else if (j==2) {
  Qstn <- paste("Cummulative percent for class ",Class.,"?",sep="")
  Answ<-cumsum(Table.)[Class.]/length(x)*100 
}

##### List of questions #####
  cat(Table.,sep=", ")
    cat("\nQuestion ",i,":\n", 
      Qstn,"?\n",
    "=",Answ,"\n",
    "\n\n\n",
    sep="")

sink(NULL)
}

MYSQL Subquery returns more than 1 row Triggers after update

I try to make one triggers to auto change some of my data everything is okay mysql accept my triggers but after that when i try to update on data showing me that error

Subquery returns more than 1 row

First my database little huge about this i'm copy here what i select with limit 3

My trigger is

DELIMITER $$
CREATE TRIGGER test3 AFTER UPDATE ON `coupons_data_result`
BEGIN
DECLARE mac INT default 0;
DECLARE durum INT default 0;
DECLARE ms1 INT default 0;

SET mac =(SELECT match_guess_type_id FROM coupon_rows WHERE match_code=NEW.cpnd_benzersiz);
SET durum =(select cpnd_status FROM matchs_result where cpnd_benzersiz=NEW.cpnd_benzersiz);
SET ms1 =(select cpnd_macsonucu1 FROM coupons_data_result where cpnd_benzersiz=NEW.cpnd_benzersiz);

IF (durum=3) THEN
    IF(mac=1)THEN
        IF(ms=1)THEN
            UPDATE  coupon_rows SET match_result='1' WHERE match_code=NEW.cpnd_benzersiz;
        Else
            UPDATE  coupon_rows SET match_result='0' WHERE match_code=NEW.cpnd_benzersiz;
        END IF;
    END IF;
END IF;

END$$

DELIMITER ;

What i select on my database with limit 3

+---------------------+-------------+
| match_guess_type_id | match_code  |
+---------------------+-------------+
|                   3 | 20170130398 |
|                   0 | 20170130399 |
|                   2 | 20170130401 |
+---------------------+-------------+
3 rows in set (0.00 sec)

+-------------+----------------+
| cpnd_status | cpnd_benzersiz |
+-------------+----------------+
|           3 | 20170129312    |
|           3 | 20170129313    |
|           3 | 20170129314    |
+-------------+----------------+
3 rows in set (0.00 sec)

+-----------------+----------------+
| cpnd_macsonucu1 | cpnd_benzersiz |
+-----------------+----------------+
|               0 | 20170129312    |
|               1 | 20170129313    |
|               1 | 20170129314    |
+-----------------+----------------+
3 rows in set (0.00 sec)

End what i try to update list

+--------------+-------------+
| match_result | match_code  |
+--------------+-------------+
|            1 | 20170130398 |
|            3 | 20170130399 |
|            3 | 20170130401 |
+--------------+-------------+
3 rows in set (0.00 sec)

Ps: All match_code and benzersiz is on the table

Python 3: elif statements being skipped over in an if statement

I'm trying to write an if statement with elif statements and then an else statement at the end, except its completely skipping over my elif statements and it executes the else statement no matter what (even the if statement).

    word = input('Enter an all lowercase word to be translated: ')

    if word[:1] == ('a', 'e', 'i', 'o', 'u'):
        print(word + 'way')
    elif word[:2] ==('a', 'e', 'i', 'o', 'u') :
        print(word[1:] + word[0] + 'ay')
    elif word[:3] == ('a', 'e', 'i', 'o', 'u'):
        print(word[2:] + word[0:] + 'ay')
    else:
        print(word)

if i delete the last elif and else statements and turn the first elif statement into an else statement, it'll run through exactly how I want it to but I need the elif statements.

    if word[1] == ('a', 'e', 'i', 'o', 'u'):
        print(word + 'way')
    else:
        word[2] ==('a', 'e', 'i', 'o', 'u')
        print(word[1:] + word[0] + 'ay')

Excel: Use an if statement to return blank value for formulae and charts

Is there a way to have an if function return a value that will be ignored by both average functions and charts?

In Gnumeric, an open-source, Excel-like program, you can have an if function return "" and the cell will appear empty. If you take the average of a bunch of such cells, some with returned values and some with returned "", the "" will be completely ignored. And if you create a chart with those cells as data points, cells with "" will not have a point plotted.

However, doing the same thing in Excel doesn't seem to work. I've selected the "Show empty cells as: Gaps" option (described here) but it doesn't work. I think this is because the cell isn't technically empty.

Answers to similar questions suggest using "na()" in the if statement, but this messes with the averaging functions.

Does anyone know of a solution?


Note: While this subject area has been addressed before, I don't think this is a duplicate. Here are some similar questions:

IF statement: how to leave cell blank if condition is false ("" does not work)

Leave a cell blank if condition is false

Creating a chart in Excel that ignores #N/A or blank cells

gcc C if statement optimization

Does gcc optimize code such as:

if(cond)
    func1()
func2()
if(cond)
    func3()

If cond is constant? Also, what are good resources for learning more about C optimizations? (So I don't have to ask more stupid questions like this)

Populate records in a new worksheet based on values in another worksheet VBA

What I am trying to do is populate a new worksheet only with records based on certain values in a particular column on another sheet. As of now I have been able to populate the entire sheet without the condition to populate only the records that I want.

There is a column in the worksheet "Full View" named 'Update Status' (Column C) that has the values No Change, Updated, New, Closed. I need to only select those records in my new worksheet that I am populating below with only those records that have values such as No Change, Updated, New in the 'Update Status' Column. However, when I run this code, it gives me a blank workboook even though there are values in the full view workbook that has other values than closed in column C. Can someone please help? Thanks for your help in advance!

 Sub Scatterplot()

 Dim headers() As Variant
 Dim ws As Worksheet
 Set ws = Worksheets("Scatterplot Excel Template")

 'Clean Contents
 ws.Cells.ClearContents
 ws.Cells.Interior.ColorIndex = 0

 Sheets("New Risk Template").Range("B3:B4").ClearContents

 'Assign headers
  headers = Array("Record ID", "ID", "Title", "Summary", "Primary Risk     Type", "Secondary Risk Type", _
 "Primary FLU/CF Impacted", "Severity Score", "Likelihood Score", "Structural Risk Factors")

 With ws    
 For I = LBound(headers()) To UBound(headers())
  .Cells(1, 1 + I).Value = headers(I)
  Next I

  Dim book1 As Worksheet
  Dim lookFor As Range
  Set book1 = Worksheets("Full View")
  Set lookFor = book1.Range("B2:X1000")
  Dim row_count As Integer
  Dim col_count As Integer

  'Find the last row and column number
  Dim col_name As String
  Dim record_id As String
  Dim col_index As Integer
  row_count = book1.Range("C" & Rows.Count).End(xlUp).Row

  If book1.Cells(row_count, "C") = "Updated" And book1.Cells(row_count, "C") = "No Change" And book1.Cells(row_count, "C") = "New" Then

  'Loop for input values
  For I = 2 To row_count

  ws.Cells(I, 1).Value = book1.Cells(I + 1, 2).Value
  ws.Cells(I, 2).Value = Right(ws.Cells(I, 1).Value, 4)

  For j = 3 To 10
  On Error Resume Next
  col_name = ws.Cells(1, j)
  record_id = ws.Cells(I, 1)

  col_index = Sheets("Full View").Cells(2, 1).EntireRow.Find  (What:=col_name, _
  LookIn:=xlValues, LookAt:=xlWhole, _
  SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
  MatchCase:=False).Column

  ws.Cells(I, j).Value = Sheets("Full View").Cells(I + 1, col_index).Value
  Next
  Next
  End if

Unchecked box using checkboxInput in Shiny

I am trying to get my Shiny app to do one of two things based on the checked status of a checkboxInput.

When the box is checked, I can get my code to work. However, I can't figure out how to make unchecking the box lead to a unique result.

How do I do this?

Below is a reproducible example. - In this example, unchecking the box leads to an error reading "argument is of length zero."

library(shiny)

ui <-  fluidPage(
  checkboxGroupInput(inputId = "test.check", label = "", choices = "Uncheck For 2", selected = "Uncheck For 2"),
  verbatimTextOutput(outputId = "test")
)

server <- function(input, output) {

  output$test <- renderPrint({
    if(input$test.check == "Uncheck For 2") {
      1
    } else {
      2
    }
  })


}

shinyApp(ui = ui, server = server)

Is there perhaps an "if.unchecked" type of function I can use?

  • I've tried is.null with the same result as he above example....

Whats the difference between a statement and a function in python and the colour coding - Python

I've just started to learn to code but I don't know why 'print' is purple and 'if' is yellow and the difference between a statement and a function

How do I get event.key to display each letter in my html?

Thank you for taking the time to help!

I am working on a hangman game and am running into a small issue. I am able to see the userInput if it is any other letter than what's below in my if else statements. The problem is that I want it to display that event, and then display any other event that wasn't already keyed to displayed alongside. For example: if userInput is === "k" then userInput is === "b", I would like it to keep the display of "k" in my html and then alongside it "b".

Also if there is a better way to write my if else statement with a loop or using forEach that would be helpful. I am new to the concepts. Thanks again.

   document.onkeyup = function(event) {
            var userInput = event.key;

if (currentWord === "taco"){ if (userInput === "t" ) { document.getElementById("1st-letter").innerHTML = userInput; } else if (userInput === "a") { document.getElementById("2nd-letter").innerHTML = userInput; } else if (userInput === "c") { document.getElementById("3rd-letter").innerHTML = userInput; } else if (userInput === "o") { document.getElementById("4th-letter").innerHTML = userInput; } else { document.getElementById("incorrect-letters").innerHTML = userInput; } } else { alert("Code is working"); } };

if node value empty else

I have following code but even if node value is empty or populated I get same echo = is not set or empty

In my header I include xml file which include $linkwebsite = $element->getElementsByTagName('linkwebsite')->item(0) ;

<?php
    if (!empty($linkwebsite)){
    echo 'not empty';
}
else{
    echo 'is not set or empty';
}
?>

Checking numbers in an array

I want to write a function that returns true if and only if in an array t of size n i have every single number from 1,2, ... n

My idea was to:

bool g(int* t, int n){
    for(int i=0;i<n;i++){
        for(int j=n;j>0;j--){
        if(t[i]==n)
          break;
        else
          return false;
        }

    }
    return true;
}

However this for int t[6]={6,2,3,4,5,1}; returns zero which is wrong as all number from 1 to 6 are in an array.

How this could be improved? Furthermore how this question could be improved?

C# Changing Float Values with "Combo Box Selected Change"

I am trying to change Float values via a combo box with an if statement.

Id doesn't have to be an if statement but I figured it would of been the most logical way to approach this.

However when I try to change a float with an if statement from selected change on a combo box I get massive errors...

I want it to reflect a formula later on in the program, outside of the scope, so the floats change based on what they have selected in the dropdown.

My "IF" Statement

public void cmbSubClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSubClass.SelectedIndex == 1)
            {

               public float a = 0.86F; 
               public float b = 0.61F;
               public float c = 1.86F;  
            }
            if (cmbSubClass.SelectedIndex == 2)
            {
               public float a = 0.64F;
               public float b = 0.75F;
               public float c = 1.42F; 
            }
        }

An example of the Formula:

float zFormula = (a * val1) + (b * val2) + (c * val3)
textbox1.Text = Convert.ToString(zFormula);

I've tried to replicate the same thing with a class, but I can't seem to figure out how to do so.

Creating a function that returns cash from funds in Java

I'm attempting to create a function that returns coins after an item has been purchased. I'm not finished, but the code below is an attempt to find the number of quarters, dimes, nickels and pennies that should be returned:

    public String getChange(VendingMachine vendingMachine, Change change) {

    double dispensedQuarters = 0;

    double dispensedDimes = 0;

    double dispensedNickels = 0;

    double dispensedPennies = 0;

    double d = Double.parseDouble(vendingMachine.getFunds());
    if (d % .25 == 0) {
        dispensedQuarters = d / .25;
    } else if (d % .25 != 0) {
        double remainder = d % .25;
        d = d - remainder;
        dispensedQuarters = d / .25;

        if (remainder % .10 == 0) {
            dispensedDimes = remainder / .10;
        } else if (remainder % .05 == 0) {
            dispensedNickels = remainder / .05;
        } else if (remainder % .01 == 0) {
            dispensedPennies = remainder / .01;
        } else {
            dispensedDimes = dispensedNickels = dispensedPennies = 0;
        }

    } else if (d % .10 == 0) {
        dispensedDimes = d / .10;
    } else if (d % .05 == 0) {

        dispensedNickels = d / .10;
    }

Is there a more compact way of creating a function that will find the number of quarters, dimes, nickels, and pennies that should be returned?

How to compute the mean with a particular condition?

I want to compute the mean from the matrix TBM[x,y], where x and y are respectively the rows and columns. I want to compute the mean over not all rows (let see later why not all), in order to obtain TBM[s,y], where s is not equal to 1 but it could be s < x. Not all over the rows, because there is a condition: the time; If the t0 < t < t1 we compute the first mean. Next, we have t1 < t < t2, we compute the second mean, and so on...

So I could compute in 2 nested for cicle with a condition if over the time t, and put the mean in a new matrix. But how?

Date calculation within If-then Statement

I need to calculate the numbers of days between two date fields based on whether one of the dates is null or not. If the date variable is null I need to incorporate today's date. Please help with SQL.

ex.
if dbo.nameoftable[date1] <> " " then time = [date1] - [date2] elseif dbo.nameoftable[date1] = " " then time = ?todays date - [date2]endif;

Thank you!!

Workaround for systemverilog there is no `if compiler directive

In systemverilog there is no `if compiler directive. So the following lines are incorrect:

`define BITS 16

reg[`BITS-1:0] my_reg;

...
`if `BITS > 10
   my_reg[31] = 1'b0;
endif
...

Without `if there are warnings/errors.

How can I workaround or solve this?

How to use if else statement in sql with comparing 3 data

I would like to ask about how to create a select query that compare 3 value. Such as I got 3 data which is mobile, home and office. I want to display one row only for example if my mobile is a null value, it will display home, and if my mobile and home is null, it will display office. I try it with if else code, but only work when mobile is null, it will display home. But I can't get the result of office when mobile and home is null.

SELECT  CASE    WHEN client_mobile IS NOT NULL THEN client_mobile
            WHEN client_mobile IS NULL THEN client_home
            WHEN client_mobile IS NULL AND client_home IS NULL THEN client_office
            ELSE 0
           END
AS client_contact FROM contact; 

mobile    home    office
11111     22222   33333
(null)    (null)  44444

I would like to get the output of

111111

444444

I will be appreciate if someone can asnwer me. Thanks a lot.

Xpath IF for determining a value then if value is true count

For an IF statement in XPATH, What is the correct way to do something like:

xpath="if (x = 1000) then sum(SalesCount) else 0"

I tried this didn't worked. Thank you for the help.

passing an object in an instance method

I am trying to calculate the minutesUsed of a phone call between two people. However I'm pretty sure that in my public void phone(Customer name, int callLength) there is an error but I am not sure where. It may have something to do with the fact that Customer name is never used? Here are the conditions:

  1. If either customer has a "pay-as-you-go" plan and the number of callLength minutes exceeds the minutesRemaining for either "pay-as-you-go" customer, then the call is not allowed ... nothing happens.
  2. After the method is called, both customers' minutesUsed amounts should increase by callLength minutes.
  3. If the call was successful, each customers' number of callsMade should increase by 1.

I don't know if my if statements are faulty but any help would be greatly appreciated. Thanks!

//Cell Phone Class

    public class CellPhone {

    String model;
    String manufacturer;
    int monthsWarranty;
    float price;


    public CellPhone() {

    }

    public CellPhone(String model, String manufacturer, int monthsWarranty, float price) {
        this.model = model;
        this.manufacturer = manufacturer;
        this.monthsWarranty = monthsWarranty;
        this.price = price;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public int getMonthsWarranty() {
        return monthsWarranty;
    }

    public void setMonthsWarranty(int monthsWarranty) {
        this.monthsWarranty = monthsWarranty;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }


    }

//Phone Plan Class

public class PhonePlan {
    public int minutesAllowed;
    public int minutesUsed = 0;
    public int dataAllowed;
    public int dataUsed = 0 ;
    public boolean planType;

    public int dataRemaining;
    public int minutesRemaining;


    public PhonePlan(int minutesAllowed, int dataAllowed, boolean planType) {
        this.minutesAllowed = minutesAllowed;
        this.dataAllowed = dataAllowed;
        this.planType = planType;


    }



    public int getMinutesAllowed() {
        return minutesAllowed;
    }

    public void setMinutesAllowed(int minutesAllowed) {
        this.minutesAllowed = minutesAllowed;
    }

    public int getMinutesUsed() {
        return minutesUsed;
    }

    public void setMinutesUsed(int minutesUsed) {
        this.minutesUsed = minutesUsed;
    }

    public int getDataAllowed() {
        return dataAllowed;
    }

    public void setDataAllowed(int dataAllowed) {
        this.dataAllowed = dataAllowed;
    }

    public int getDataUsed() {
        return dataUsed;
    }

    public void setDataUsed(int dataUsed) {
        this.dataUsed = dataUsed;
    }


    public boolean getPlan() {

      return planType;
    }

    public void setPlanType(boolean planType) {
        this.planType = planType;
    }

    public int getMinutesRemaining() {
        return (minutesAllowed-minutesUsed);
    }

    public int getDataRemaining() {
        return (dataAllowed-dataUsed);
    }

    @Override
    public String toString() {
        if(planType)
        {
            return("Pay-as-you-go Plan with " + minutesAllowed + " minutes and " + dataAllowed+ " KB remaining");
        }
        else
        {
            return("Regular (" +(minutesAllowed +" minute, "+ dataAllowed/1000000f +" GB data)"
                    +") Monthly Plan with "+ minutesAllowed+" minutes and "+ dataAllowed+ " KB remaining"));
        }


    }
}

//Customer Class

public class Customer {

    String name; //Customer Name
    CellPhone cellPhone; // Cell phone object type
    PhonePlan phonePlan; //Phone plan Object type
    int callsMade;
    float balance = 0;

    int internetData;
    int minutesBought;
    int monthlyCharges;
    int voiceOvertimeCharges;
    int dataOverusageCharges;
    double HST;
    double totalDue;



    public Customer(String customerName,CellPhone cellPhone,PhonePlan Plan){
        this.name = customerName;
        this.cellPhone = cellPhone;
        this.phonePlan = Plan;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getCallsMade() {
        return callsMade;
    }

    public void setCallsMade(int callsMade) {
        this.callsMade = callsMade;
    }

    public float getBalance() {
        return balance;
    }

    public void setBalance(float balance) {
        this.balance = balance;
    }
    public CellPhone getCellPhone() {
        return cellPhone;
    }


    public void setCellPhone(CellPhone cellPhone) {
        this.cellPhone = cellPhone;
    }

    public PhonePlan getPlan() {
        phonePlan.minutesRemaining = phonePlan.minutesAllowed - phonePlan.minutesUsed;

        return phonePlan;
    }



    public void setPlan(PhonePlan phonePlan) {
        this.phonePlan = phonePlan;
    }

    @Override
    public String toString() {
        if(phonePlan.toString().equals("Regular")){
            return this.getName()+ " with a " + cellPhone.getManufacturer()+ " " +cellPhone.getModel()+" "+
                    "on a"+" "+phonePlan.toString()+" Plan "+"("+" "+phonePlan.getMinutesAllowed()+","+phonePlan.getDataAllowed()+"KB "+")"+"Monthly Plan with "+
                    phonePlan.getMinutesRemaining()+"minuutes remaining and "+" "+phonePlan.dataRemaining+" "+"KB remaining";
        } else {
            return this.getName()+ " with a " +cellPhone.getManufacturer()+" "+cellPhone.getModel()+
                    " on a " + phonePlan.toString()+ " Plan with " +phonePlan.getMinutesAllowed()+" minutes and " +
                    phonePlan.getDataAllowed()+" KB remaining";
        }

    }

    public void phone(Customer name, int callLength){
        if((phonePlan.toString().equals("Pay-as-you go")) && (callLength > phonePlan.minutesRemaining)){

            phonePlan.minutesUsed =  phonePlan.minutesUsed  + callLength;

        } else {
            callsMade = callsMade + 1;
            phonePlan.minutesUsed =  phonePlan.minutesUsed  + callLength;


        }
}

    public int buyMinutes(int minutesBought){
        if((phonePlan.toString().equals("Pay-as-you go"))){
            minutesBought = (int) (minutesBought * 0.40);
            balance  = balance + minutesBought;
            return minutesBought;
        }

        return minutesBought;

    }

    public void accessInternet(int internetData){
        this.internetData = internetData;

    }


    public int Customer(int monthlyCharges){
        if((phonePlan.toString().equals("Regular")) && (phonePlan.minutesAllowed == 100)){
            monthlyCharges = 15 + (phonePlan.dataAllowed * 10);
            return monthlyCharges;
        } else{
            monthlyCharges = 25 + (phonePlan.dataAllowed * 10)+ minutesBought;
            return monthlyCharges;
        }
    }

    public Customer(double voiceOvertimeCharges, double dataOverusageCharges){
        if((phonePlan.toString().equals("Regular")) && (phonePlan.minutesAllowed == 100) && (phonePlan.minutesUsed > 100)){
            voiceOvertimeCharges = (phonePlan.minutesUsed - phonePlan.minutesAllowed)* 0.15;
        } else {
            voiceOvertimeCharges = (phonePlan.minutesUsed - phonePlan.minutesAllowed)* 0.15;

        }
        if((phonePlan.toString().equals("Regular")) && (phonePlan.minutesAllowed == 100) && (phonePlan.minutesUsed > 100)){
            dataOverusageCharges = (phonePlan.dataUsed - phonePlan.dataAllowed)* 0.00005;
        } else {
            dataOverusageCharges = (phonePlan.dataUsed - phonePlan.dataAllowed)* 0.00005;

        }
    }

    public void printMonthlyStatement(){
        if((phonePlan.toString().equals("Regular"))){

        System.out.println(String.format("\n%17s%15s","Name:", name));
        System.out.println(String.format("%19s%15s","Plan Type: ", phonePlan));
        System.out.println(String.format("%19s%10d","Minutes Used: ", phonePlan.minutesUsed));
        System.out.println(String.format("%19s%10d","Calls Made: ", callsMade));
        System.out.println(String.format("%17s%10d","Monthly Charges: ", monthlyCharges));
        System.out.println(String.format("%17s%10.2f","Voice Overtime Charges: ", voiceOvertimeCharges));
        System.out.println(String.format("%17s%10.2f","Data Overusage Charges: ", dataOverusageCharges));
        HST = (monthlyCharges + voiceOvertimeCharges + dataOverusageCharges) * 0.13f;
            System.out.println(String.format("%19s%10.2f","HST: ", HST));
        totalDue = monthlyCharges + voiceOvertimeCharges + dataOverusageCharges + HST;
            System.out.println(String.format("%19s%10.2f","Total Due: ", totalDue));
        }
        else{
            // pay-as-you-go plan
            System.out.println(String.format("\n%17s%15s","Name:", name));
            System.out.println(String.format("%19s%15s","Plan Type: ", phonePlan));
            System.out.println(String.format("%19s%10d","Minutes Used: ", phonePlan.minutesUsed));
            System.out.println(String.format("%17s%10d","Minutes remaining: ", phonePlan.minutesRemaining));
            System.out.println(String.format("%19s%10d","Data Used: ", phonePlan.dataUsed));
            System.out.println(String.format("%19s%10d","Data Reaminging: ", phonePlan.dataRemaining ));
            System.out.println(String.format("%19s%10d","  Calls Made: ", callsMade));
            System.out.println(String.format("%19s%10d","Monthly Charges: ", monthlyCharges));
            HST =  monthlyCharges * 0.13f;
            System.out.println(String.format("%19s%10.2f","HST: ", HST));
            totalDue =  monthlyCharges + HST;
            System.out.println(String.format("%19s%10.2f","Total Due: ", totalDue));
        }

    }


}

The following code is the testing code for the classes above:

//CallStimulationTestProgram

    public class CallStimulationTestProgram {
        public static void main(String args[]) {
        // Create some phone objects
        CellPhone iPhone = new CellPhone("iPhone 6Plus", "Apple", 12, 915.00f);
        CellPhone galaxy = new CellPhone("Galaxy S7", "Samsung", 18, 900.00f);
        CellPhone priv = new CellPhone("PRIV", "BlackBerry", 12, 890.00f);
        // Create some customer objects. Only Tim and April have a "pay-as-you-go" plan
        // (identified by a true Boolean value), the others are on standard monthly plans
        // (identified by a false Boolean value). Realistically, these purchases would
        // occur at different times on different days but we are assuming that all 5
        // Customers purchase at the same time.
        Customer rob = new Customer("Rob Banks", iPhone, new PhonePlan(200, 2500000, false));
        Customer april = new Customer("April Rain", galaxy, new PhonePlan(200, 1000000, true));
        Customer rita = new Customer("Rita Book", priv, new PhonePlan(100, 500000, false));
        Customer sue = new Customer("Sue Permann", iPhone, new PhonePlan(100, 2500000, false));
        Customer tim = new Customer("Tim Bur", iPhone, new PhonePlan(30, 0, true));
        // Show the Customers
        System.out.println("\nHere are the customers:\n");
        System.out.println(rob);
        System.out.println(april);
        System.out.println(rita);
        System.out.println(sue);
        System.out.println(tim);
        // Have the customers make some phone calls to other customers
        rob.phone(sue, 12); // a 12 minute call from Rob's phone to Sue's phone
        rita.phone(april, 27);
        rob.phone(tim, 3);
        tim.phone(rita, 19);
        // This line now assumes that Tim's call was cut off after 8 minutes,
        // because his plan only allows 8 more minutes.
        tim.phone(sue, 8);
        // Output to show how the remaining unused minutes on each account
        // have changed
        System.out.println("\nRob's minutes = " + rob.getPlan().getMinutesRemaining());
        System.out.println("April's minutes = "+ april.getPlan().getMinutesRemaining());
        System.out.println("Rita's minutes = " + rita.getPlan().getMinutesRemaining());
        System.out.println("Sue's minutes = " + sue.getPlan().getMinutesRemaining());
        System.out.println("Tim's minutes = " + tim.getPlan().getMinutesRemaining());
        // Try some more calls
        rob.phone(tim, 1); // Should not connect at all
        rob.phone(sue, 1);
        sue.phone(tim, 1); // Should not connect at all
        // Tim gets his phone working again by paying for more minutes
        tim.buyMinutes(100);
        // Output to show how the remaining unused minutes on Tim's account has changed
        System.out.println("\nTim's minutes = " + tim.getPlan().getMinutesRemaining());
        // Tim lets Rob know that his phone is working again.
        // Then Rob tells Sue who then phones Tim to chat.
        tim.phone(rob, 24); // OK now rob.phone(sue, 15);
        sue.phone(tim, 68); // Sue's limit will exceed and she must pay extra
        rita.phone(sue, 65); // Both customers exceed their minutes and must pay extra
        // Output to show how the remaining unused minutes on each account have changed
        System.out.println("\nRob's minutes = " + rob.getPlan().getMinutesRemaining());
        System.out.println("April's minutes = "+ april.getPlan().getMinutesRemaining());
        System.out.println("Rita's minutes = " + rita.getPlan().getMinutesRemaining());
        System.out.println("Sue's minutes = " + sue.getPlan().getMinutesRemaining());
        System.out.println("Tim's minutes = " + tim.getPlan().getMinutesRemaining());
        // Now simulate internet data access
        rob.accessInternet(45600); // used up 45.6MB
        rita.accessInternet(2700000); // use up 2.7GB
        rob.accessInternet(1200000); // use up 1.2GB
        tim.accessInternet(10000); // attempt to use 10MB ... won't work
        sue.accessInternet(2500000); // used up exactly 2.5GB
        april.accessInternet(1900000); // attempt to use 1.9GB, only 1GB used, then stops
        // Output to show how the remaining unused data on each account have changed
        System.out.println("\nRob's data = " + rob.getPlan().getDataRemaining() + "KB");
        System.out.println("April's data = "+ april.getPlan().getDataRemaining() + "KB");
        System.out.println("Rita's data = " + rita.getPlan().getDataRemaining() + "KB");
        System.out.println("Sue's data = " + sue.getPlan().getDataRemaining() + "KB");
        System.out.println("Tim's data = " + tim.getPlan().getDataRemaining() + "KB");
        // Pretend that the month is over and print out all of the billing statements
        rob.printMonthlyStatement();
        april.printMonthlyStatement();
        rita.printMonthlyStatement();
        sue.printMonthlyStatement();
        tim.printMonthlyStatement();
        }
    }

Check string for a character loop

I need to validate user input string to make sure it contains a comma. If it does not contain a comma it must print "Error" and allow for the user to re-enter input. I'm just not sure which loop to use. If else may work, but I need it to loop back to the scanner for the user input. Or a while loop that uses .contains? Thanks.

Removing empty element from Array(Java)

I'm trying to remove the empty element from the array by copying the existing element to a new array. However, initialization of the new array is causing my return value to be null even when I initialize it within the for loop.

public String[] wordsWithout(String[] words, String target) {
    for(int i = 0; i < words.length; i = i +1){
        String store[] = new String[words.length];
        if (words[i] == target){
            words[i] ="";
        }
        else if(words[i] != target){
            words[i] = store[i];
        }       
    }
    return words;
}

One char from the other bool function

I want to have a function that is going to return true if and only if a char* s could be obtained from char* t by simply crossing out certain letters e.g. g("ERT", "EAARYT")=true and g("ERT","ABCT")=false.

My idea for this code is the following:

bool g(char* s, char* t) {
    for (int i=0; s[i]!=0;i++) {
        for (int j=i; t[j]!=0; j++) {
            if (s[i]==t[j]) {
                return true;
            }
        }
    }
    return false;
}

Obviously it does not work as it only check whether the first letter is present and then immediately returns true. How should i change that?

I would prefer to use nested loops/if constructions this should be more than doable with that.

Returning from an if block Java

I have this trivial piece of code :

public ModelAndView postLoginPage(@ModelAttribute("user") User user, ModelMap model,
                                      HttpServletRequest req, HttpServletResponse res) {

        if (user != null) {
            logger.log(Level.INFO, "\n\n [*][*][*][*][*] user not null ");
            if (user.getUsername().equals("jon")){
                return new ModelAndView("echo", "user", user);
            }
        }else 
            return new ModelAndView("oops", "user", user);

    }

With a return nested in a double if. it seems java is complaining about this not being a viable return statement ? Why is this an error ?

Strange behaviour of an IF condition

$a = 101;

if (isset($a) && is_int($a) && in_array($a, range(1, 100))) {
  echo "TRUE";
} else echo "FALSE";

Why this condition returns FALSE as it should be while this IF:

if (isset($argv[1]) && is_int($argv[1]) && in_array($argv[1], range(1, 100))) {
  echo "TRUE";
} else echo "FALSE";

returns also FALSE where value passed as first parameter is 50 which is in range??? PHP-CLI is 7.0.9-TS-VC14-x64

Thanks in advance

Empty result SQL Query

Else if is not showing the output.. what seems to be the problem here?

<?php 
$wp_user_search=$ wpdb->get_results("SELECT * FROM wp_hdoi_mentor where status='active' ORDER BY mentor_id");

foreach ( $wp_user_search as $user_info ) {
    $user_id=$user_info->user_id;
    $role=$user_info->user_role;

    if( $role=='Mentor'){

        echo '<tr><td class="match">' .$user_info->mentor_id. '</td>';
        echo '<td class="match">'. "<a href='mentor.php?id=$user_id'>" .$user_info->first_name.'&nbsp;'.$user_info->last_name.'</a>'.'</td>';
        echo '<td class="match">' .$user_info->email_address.'</td>';
        echo '<td class="match">' .$role.'</td>';
    }

    if(!empty($role)) {
        echo 'no record found'; 
    }
} ?>

If 'X' and 'O' not in string, then: [duplicate]

This question already has an answer here:

While studying to a test, I got this problem that I could not solve. I was doing a program that analyses a list of strings of three characters, '.', 'X', and 'O'. The program had to interpret the combinations of these strings and return the number of columns, lines or diagonals in which it was still possible to fill with 'X' or 'O' (tic-tac-toe game). So I wanted to make a condition which is verbally like this:

If both 'X' and 'O' are not in the string, then...

So I wrote :

if ('X' and 'O') not in string:
    count = count + 1

But it the condition is false if the string is '..O', and I don't understand why.

python for-loop only executes once?

def Vin(t):
    inputs = []
    for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            Vin = (1)
            inputs.append(Vin)
        else:
            Vin = (-1)
            inputs.append(Vin)

        return inputs

when i use this function on a range of t values i only get one result,

i.e.

input1=Vin(tpoints)
print (input1)

only gives [1], whereas i want the function to do it for every t value.

thanks

matching and replacing values in a data frame using loop and if condition

I have a data frame like this

    v1  v2
1   a   b,c
2   b   d,a
3   c   c,a

I want to check each row values contains a specific value find it and replace it by another value using a loop and if else condition. For instance here in the first row of second column means "b,c" doesn't contain "a" the value of the first row of the first column so we have to take "b,c" and replace it with "a" in column v2 in rows which contains "a". So by doing this since the second & third rows of the second column would contain their values in the first column so we have to skip them. The final result would be

    v1  v2
2   b   d,b,c
3   c   c,b,c

I have written this but I couldn't achieve the final result I wanted:

df<-data.frame(v1=c("a","b","c"),v2=c("b,c","d,a","c,a"),stringsAsFactors=F)
df$v1 <- as.character(df$v1)
df$v2 <- as.character(df$v2)
df2<-data.frame()
for(i in 1:nrow(df)){
    if(grep(df[i,1], df[i,2])==0){
      res<-sub(df[i,1],df[i,2], df[,2])
      df2<-data.frame(x=df[,1],y=res, row.names=NULL)
    }
    else(grep(df[i,1], df[i,2])!=0)
    next

    print(df2)
  }

dimanche 29 janvier 2017

A Basic Code Wars Challenge

Hi everyone this is one of those times, where the solution is staring me right in the face but I can't seem to find it! So please be patient with me: The instruction is the following:

Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.

Numerical Score Letter Grade

90 <= score <= 100  'A'
80 <= score < 90    'B'
70 <= score < 80    'C'
60 <= score < 70    'D'
0 <= score < 60 'F'

Tested values are all between 0 and 100. Theres is no need to check for negative values or values greater than 100.

Here is my solution:

function getGrade (s1, s2, s3) {
  var score = (s1 + s2 + s3) / 3;
  if (90 <= score && score >= 100) {
      return 'A';
  } else if (80 <= score && score > 90) {
    return 'B';
  } else if (70 <= score && score > 80) {
    return 'C';
  } else if (60 <= score && score > 70) {
    return 'D';
  } else if (0 <= score && score > 60) {
    return 'F';
  }
}

getGrade(5,40,93);
getGrade(30,85,96);
getGrade(92,70,40);

Can't for the life of me figure out what I am doing wrong.

Scheme- if condition doesn't return

I have a simple piece of code but I don't know why it doesn't return.

(define (check n)
   (if (= (/ n 10) 0)
     1
     2))

So it is basically suppose to check if n/10 would give a 0, and if so it should return 1, if not it should return 2. but if i run:

(check 3)

It just doesn't return at all. It's as though its staying in an infinite loop. Any help would be great! Thanks.

Python math code greater than and less than not working

import numpy as np
import random
i = random.randint(1,100)
if i > 0 and i <16:
    print ("Broken")
else if i > 16 and i > 100
    print ("Not broken")

I am trying to make it if the number is between 1 to 15 the racquet is broken but if it is 16-100 it is not broken. It says it is invalid syntax in python. Why is it invalid syntax?

More efficient code (Seemingly too many if statements)

I've looked into this but I couldn't find anything that helped me (Apologies if the answer to something similar is out there that could have helped me). I'm writing a currency converter that suffers from tons of if's that just doesn't seem efficient nor can I imagine very nicely readable, so I'd like to know how I can write more efficient code in this case:

prompt = input("Input") #For currency, inputs should be written like "C(NUMBER)(CURRENCY TO CONVERT FROM)(CURRENCY TO CONVERT TO)" example "C1CPSP"

if prompt[0] == "C": #Looks at first letter and sees if it's "C". C = Currency Conversion
    #CP = Copper Piece, SP = Silver Piece, EP = Electrum Piece, GP = Gold Piece, PP = Platinum Piece
    ccint = int(''.join(list(filter(str.isdigit, prompt)))) # Converts Prompt to integer(Return string joined by str.(Filters out parameter(Gets digits (?), from prompt))))
    ccalpha = str(''.join(list(filter(str.isalpha, prompt)))) #Does the same thing as above expect with letters

    if ccalpha[1] == "C": #C as in start of CP
        acp = [ccint, ccint/10, ccint/50, ccint/100, ccint/1000] #Array of conversions. CP, SP, EP, GP, PP
        if ccalpha[3] == "C": #C as in start of CP
            print(acp[0]) #Prints out corresponding array conversion
        if ccalpha[3] == "S": #S as in start of SP, ETC. ETC.
            print(acp[1])
        if ccalpha[3] == "E":
            print(acp[2])
        if ccalpha[3] == "G":
            print(acp[3])
        if ccalpha[3] == "P":
            print(acp[4])
    if ccalpha[1] == "S":
        asp = [ccint*10, ccint, ccint/10, ccint/10, ccint/100]
        if ccalpha[3] == "C":
            print(asp[0])
        if ccalpha[3] == "S":
            print(asp[1])
        if ccalpha[3] == "E":
            print(asp[2])
        if ccalpha[3] == "G":
            print(asp[3])
        if ccalpha[3] == "P":
            print(asp[4])
    if ccalpha[1] == "E":
        aep = [ccint*50, ccint*5 ,ccint , ccint/2, ccint/20]
        if ccalpha[3] == "C":
            print(aep[0])
        if ccalpha[3] == "S":
            print(aep[1])
        if ccalpha[3] == "E":
            print(aep[2])
        if ccalpha[3] == "G":
            print(aep[3])
        if ccalpha[3] == "P":
            print(aep[4])
    if ccalpha[1] == "G":
        agp = [ccint*100, ccint*10, ccint*2, ccint, ccint/10]
        if ccalpha[3] == "C":
            print(agp[0])
        if ccalpha[3] == "S":
            print(agp[1])
        if ccalpha[3] == "E":
            print(agp[2])
        if ccalpha[3] == "G":
            print(agp[3])
        if ccalpha[3] == "P":
            print(agp[4])
    if ccalpha[1] == "P":
        app = [ccint*1000, ccint*100, ccint*20, ccint*10, ccint]
        if ccalpha[3] == "C":
            print(app[0])
        if ccalpha[3] == "S":
            print(app[1])
        if ccalpha[3] == "E":
            print(app[2])
        if ccalpha[3] == "G":
            print(app[3])
        if ccalpha[3] == "P":
            print(app[4])

Trouble with If Statement Inside For Loop

So I'm trying to use this code to print a statement if it reaches the end of the loop without break being called in the statement before it which would mean that the program got a match and then needs to print it. However, my if (k+1...) statement never gets branched into always skipped over. Why would this be?

else {
            cout << "test" << endl;
            looklen = look.length();
            for (j = 0;j < numdist;j++) {
                for (k = 0;k < looklen;k++) {
                    //cout << "test2" << endl;
                    if (look[k] = '?') {
                        k++;
                        continue;
                    }
                    else if (look[k] != distinct[j][k]) {
                        break;
                    }
                    if (k + 1 == looklen) {
                        cout << "test3" << endl;
                        cout << look << " : matches " << distinct[j] << " " << distinctnum[j]+1 << " time(s)." << endl;
                    }
                }

            }
        }

python multiples of 19

I have been working on this for a few days now. I have looked at several tutorials and read in my book, I am very new to coding.

I am required to write this program

This program should prompt the user to enter an exact multiple of 19 that is greater than 200. Then, the program should analyze the input and display a response to each of the four possible results of the analysis. See sample runs below.

Enter an exact multiple of 19 that is greater than 200 76 No, 76 is a multiple of 19 but it is not greater than 200

Enter an exact multiple of 19 that is greater than 200 55 55 is not over 200 and also is not a multiple of 19

Enter an exact multiple of 19 that is greater than 200 222 222 is over 200 but is not a multiple of 19

Enter an exact multiple of 19 that is greater than 200 380 Good input. 19 divides into 380 exactly 20 times

this is what I have so far

#promt user to enter an exact multiple of 19 that is larger than 200
#assign variable a to user input
def main () :
    random = int(input('Enter an exact multiple of 19 that is greater than 200:'))

    number = random / 19


    if random > 200 :
        print('Good input 19 divides into', random , 'exactly' , number ,'times')


    if random % 19 == 0 or random <200:
        print('is a multiple of 19')

    else:
        print('is not a multiple of') 


main () 

i can get the program to spit out the line for the user inputting 380 but I am at a loss as far as how to write up the other outputs. Help would be awesome!!!

Calling IF Statement method in C#

I have noticed that I am repeating a lot of my code.. What I want to do is store the below if-statement in a method so that it can be called at any time. Below is an example of my code.

if (result.Equals("") && type == "")
            {
                JObject jobj = JObject.Parse(Helper.callerClass(@""));
                var titleTokens = jobj.SelectTokens("...title");
                var values = titleTokens.Select(x => (x as JProperty).Value);

                if (titleTokens.Contains(s))
                {
                    MessageBox.Show("");
                }
                else
                {
                    MessageBox.Show("");
                }
            } 

Does "true" in C always mean 1?

Please consider these piece of C code:

if ((value & 1) == 1)
{

}

Assuming value equals 1, will (value & 1) return 1 or any unspecified non zero number?

MySQL SELECT IF statement

I have 4 tables; loans (has 'user_id'), users (has 'student_ID' and 'teacher_ID'), student, and teacher.

The code I tried:

SELECT *FROM loans LEFT JOIN users ON loans.user_id=users.user_id
(
IF student_ID='1' THEN (SELECT *FROM teacher)
ELSE (SELECT *FROM student)
)

The code is not working properly. I want the loans display the student or teacher name from users. I have tried similia work, and it doesn't work either.

If Linear Programming Decision Variable >= 0 then >= 3000

I am trying to use the solver in Excel to create a linear program to minimize mutual fund expenses. My decision variables are the amounts invested in each fund. If anything is invested, it must meet the fund minimum. How can I program this?

Amount invested in Fund 1 >= if Amount Invested in Fund 1 > 0, then Amount Invested in Fund 1 >= 3000 else Amount Invested = 0

Any help is greatly appreciated. Thanks.

How do i make each of my if statements run individually ? (Java)

Im attempting to program a 'Name Guesser'. This game relies heavily on if statements and randomisation. I have a problem which i don't know how to fix, my if statements can only run in a sequence, and not separately! I want to be able to guess the selected name in any given order, but currently i can only guess the name in one order. Eg. C H R I S is the only way to guess the name correctly, any other sequence of characters will not work. What can i do to fix this?

Note - Chris is the only name implemented so far.

My NameGuesser class:

        import java.lang.reflect.Array;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
    import java.util.Scanner;


    public class NameGuesser {

        public static class Mark{
            public static  boolean M = false;
            public static  boolean A = false;
            public static  boolean R = false;
            public static  boolean K = false;
        }   


        public static void main(String[] args) {
            // TODO Auto-generated method stub
    Scanner reader1 = new Scanner(System.in);
            String Guessspace = "_ _ _ _";

            boolean Mark = true;
            int Lives = 3;
            int Guessingmode = 0;
    String[] Names = {"Mark", "Adam", "Joel"};
    String Random = (Names [new Random().nextInt(Names.length)]);

    List<String> Markletters = new ArrayList<String>();
    Markletters.add("M");
    Markletters.add("A");
    Markletters.add("R");
    Markletters.add("K");




    System.out.println(Random);

    if (Random == "Mark"){
         Guessingmode = 1;
        }
    if (Random == "Adam"){
            Guessingmode = 2;
        }
    if (Random == "Joel"){
            Guessingmode = 3;
        }

     {







if (Guessingmode == 1){
    String Nameguess = reader1.next();            
         if(Markletters.contains(Nameguess)){


        if (Nameguess.equals("M")){
               NameGuesser.Mark.M = true; 
               GuessSpace GuessSpace;
               GuessSpace = new GuessSpace();
               GuessSpace.GuessSystem();       
        }
              }




               Nameguess = reader1.next();
               if(Markletters.contains(Nameguess)){


            if (Nameguess.equals("A")){
             NameGuesser.Mark.A = true; 
             GuessSpace GuessSpace;
              GuessSpace = new GuessSpace();
              GuessSpace.GuessSystem();
            }
               }



                   Nameguess = reader1.next();
                   if(Markletters.contains(Nameguess)){


                   if (Nameguess.equals("R")){
                NameGuesser.Mark.R = true;
                 GuessSpace GuessSpace;
                 GuessSpace = new GuessSpace();
                 GuessSpace.GuessSystem();
            }
               }



                   Nameguess = reader1.next();
                   if(Markletters.contains(Nameguess)){


            if (Nameguess.equals("K")){
                NameGuesser.Mark.K = true; 
                GuessSpace GuessSpace;
                GuessSpace = new GuessSpace();
                GuessSpace.GuessSystem();
            }
               }


}
 }
    }
}

My GuessSpace class:

   public  class GuessSpace extends NameGuesser{

public void GuessSystem() {
    if( NameGuesser.Mark.M == true){
        System.out.println("M _ _ _");
        }


                    if( NameGuesser.Mark.M == true){
                        if( NameGuesser.Mark.A == true){
                            System.out.println("M A _ _");
                    }
                            }

                                if( NameGuesser.Mark.M == true){
                                    if( NameGuesser.Mark.A == true){
                                        if( NameGuesser.Mark.R == true){
                                                System.out.println("M A R _");
                                }   
                                        }
                                    }


                                            if( NameGuesser.Mark.M == true){
                                                if( NameGuesser.Mark.A == true){
                                                    if( NameGuesser.Mark.R == true){
                                                        if( NameGuesser.Mark.K == true){
                                                            System.out.println("M A R K");
                                                            System.out.println("Well done! You guessed my name!");
                                                            System.exit(0);
                                                        }
                                                    }
                                                }
                                            }

}   
}