mardi 31 octobre 2017

while loop terminating early with nested if statement

I'm writing a condition check for a simple input via prompt() in JavaScript. The idea is to repeat a prompt until the user supplies a positive integer.

In particular, if I submit a negative integer, it correctly prompts me again via case 3. However, if I answer the second prompt again with a negative integer, the code unexpectedly leaves the while loop.

In the if statement:

Case 1: checks if the user 'cancels' the prompt box (or returns an empty string), in which case I set a variable 'cancelGridCreation' to 'true' to later cancel the encapsulating process (outside of the included code), and then terminate the while loop by setting the variable 'waitingForQualifyingAnswer' to 'false'.

Case 2: checks if the response is an acceptable integer (number, integer, positive), and sets the conditional variable 'false' to terminate the while loop.

Case 3: prompts the user again, with the idea that the newly entered data will be checked again by the same 3 'if' cases.

User inputs matching cases 1 and 2 seem to work fine. However, as mentioned above, entering a negative integer 2 times terminates the while loop. See the console output that I received, entering -10 and then -20. As well, the console.log() outputs don't seem to occur in an order matching their location in the code (perhaps a processing time-lag issue?). You'll see that the console.log() from case 3 outputs before the "initial size entered" console.log(), which is coded before the while loop even starts.

Similar results seem to occur whenever case 3 is followed by another case 3 (regardless whether input is negative integers, decimals, or strings), as well as case 3 followed by case 1 (of course, here case 1 would terminate the loop, but the console log statements still seem to occur out of order).

Link to interactive code at JSBin: http://ift.tt/2xJ0e4r

JavaScript Code:

let cancelGridCreation = false;
let waitingForQualifyingAnswer = true;
let answer = prompt('Please enter the number of rows/columns, as a positive integer:', '16');
let gridSize = parseFloat(answer, 10);
console.log('initial size entered: ' + gridSize);
while (waitingForQualifyingAnswer === true) {
  console.log('top of while loop');
  if (answer == null || answer == "") {
    console.log('prompt - canceled');     
    cancelGridCreation = true;
    waitingForQualifyingAnswer = false;
  } else if (typeof gridSize === 'number' && gridSize % 1 === 0 && gridSize > 0) {
    console.log('prompt - good answer: ' + gridSize);
    waitingForQualifyingAnswer = false;
  } else {
    console.log('prompt - BAD answer: ' + gridSize);
    answer = prompt('Incorrect format entered.  Please enter the number of rows/columns, as a positive integer:', '16');
    gridSize = parseFloat(answer, 10);
    console.log('new size entered: ' + gridSize);
  }
  console.log('end of while loop');
}
console.log('done:');
console.log(gridSize);

Console Output was as follows (having entered -10 at the first prompt, and -20 at the second prompt):

    "prompt - BAD answer: -10"
    "top of while loop"
    "initial size entered: -10"
    "new size entered: -20"
    "end of while loop"
    "done:"
    -20

I'm pretty new, and realize there may be more concise ways to accomplish this. I'm interested in suggestions, however, I"m also keen to figure out why the while loop is ending when only case 3 inputs are being submitted.

Please note: The console.log() statements are only of a simple means of debugging. I realize a parseInt() would truncate any decimals, but I chose to allow integers as an acceptable size.

Thank you for any advice you can offer :)

Printing biggest even number with multiple scanf

I would like to get an output of the biggest even number. but when i input 1 2 3 (3 scanf) the output is 4.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int ary[100];
    int x,y=0;
    int amount;
    scanf("%d",&amount);fflush(stdin);
    for(x=1;x<=amount;x++)
    {
        scanf("%d",&ary[x]);
        if(ary[x]%2==0)
        {
            if(ary[0]<ary[x])
            {
                ary[0]=ary[x];
            }
        }
    }
    printf("%d",ary[0]);

    getchar();
    return 0;
}

Working with do-while loops

So this is my 4th project, and my project is this: Create a program to allow a user to play a modified “craps” games. The rules will be as follows:

1) User starts with $50.00 as their total. 2) Ask the user for their bet (maximum bet is their current total). 3) Throw a pair of dice.

a) If the total value is 7 or 11, the user is an instant winner. The user has the amount bet added back into their total. Ask the user if they wish to play again and if so they start at step two above. b) If the total value is 2, 3, or 12, the user is an instant loser. The user has the amount bet deducted from their total. Ask the user if they wish to play again and if so they start at step two above. c) If the total is anything else, remember this total as the “point” and roll again.

i) If the new total is equal to the “point”, the user wins and the process is the same as winning in (a) above ii) If the new total is a 7, the user loses. And the process is the same as losing in (b) above. iii) If the new total is anything else the user must roll again and again try to match the “point” of the first roll.

This is the code I have so far. Everything works fine like it's supposed to, except the program loops itself without me inputting 'y' or 'Y'. It keeps looping itself until the program gets a total (dice_total) that allows you to win or lose, then ask you to if you want to restart the game. Any other total would just cause the program to keep looping. Also, this is my first time using do-while loops, so I am not sure if I did it correctly.

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <time.h>
#include <string>
using namespace std;

int main()
{
//Declaring Variables**********
char again = 'y';
char play = 'r';
double starting_amount = 50.00;
double bet_amount = 0.00;
int dice1;
int dice2;
int dice_total;

//*****************************
srand(time(NULL));// Setting true random seed
//*****************************
//Restart the game, if you win or lose.
while (again == 'y' || again == 'Y')//Beginning of the again while loop
{
    //Setting the execution of the program***************************************************************
    cout << "You currently have this amount of money to bet $" << starting_amount << endl;
    cout << "How much do you want to bet?" << endl;
    cin >> bet_amount;
    double current_amount = starting_amount - bet_amount;
    cout << "You are betting $" << bet_amount << " and you have $" << current_amount << " left" << endl;
    //***************************************************************************************************

    do
    {//Beginning of do-while
        int point = 0;
        dice1 = rand() % 6 + 1;
        dice2 = rand() % 6 + 1;
        dice_total = dice1 + dice2;

        cout << "Throwing dices, standby........." << endl;
        cout << "You got " << dice1 << " and " << dice2 << " for a total of " << dice_total << endl;
        //If statements to set the win or lose settings.
        if (dice_total == 7 || dice_total == 11)
        {
            cout << "You are a winner congrats :D Would you want to play again? <Press y to play again>" << endl;
            cin >> again;
        }
        else if (dice_total == 2 || dice_total == 3 || dice_total == 12||current_amount==0.00)
        {
            cout << "You lost, well better luck next time!!!<Press y to play again" << endl;
            cin >> again;
        }
        else
        {
            point++;
            cout << "Your score is " << point << " would you want to keep playing? <Press r, to keep playing" << endl;
        }

    }//End of do
    while (play == 'r' || play == 'R');
        cout << "Game has ended, would you want to restart the whole game?" << endl;
        cin >> again;
    }//End of the again while loop

}

Power Shell list box doesn't return Var

I am trying to create a Popup asking a user to select a department and then based on the department run a selection of Choco commands to install software each department needs to use. I'm running into an issue with it not returning the selected #var.

Troubleshooting so far has shown that no matter what item I select in the list it just run the commands under the first IF section and then stop going.

I've tried to scalre down my code to just ask it to print each business department so I could check the list box setup and I can't find what i'm missing.

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Department"
$objForm.Size = New-Object System.Drawing.Size(249,190) 
$objForm.StartPosition = "CenterScreen"

#OK Button action
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$TSDepartment=$objListBox.SelectedItem;$objForm.Close()}})

#Ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(10,115)
$OKButton.Size = New-Object System.Drawing.Size(200,30)
$OKButton.Text = "OK"
$OKButton.Add_Click({$TSDepartment=$objListBox.SelectedItem;$objForm.Close()})
$objForm.Controls.Add($OKButton)

# List box Lable
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20) 
$objLabel.Size = New-Object System.Drawing.Size(200,20) 
$objLabel.Text = "Please select a Department:"
$objForm.Controls.Add($objLabel) 

#list box Side
$objListBox = New-Object System.Windows.Forms.ListBox 
$objListBox.Location = New-Object System.Drawing.Size(10,40) 
$objListBox.Size = New-Object System.Drawing.Size(200,20) 
$objListBox.Height = 70

#pick list
[void] $objListBox.Items.Add("Call-Center")
[void] $objListBox.Items.Add("Law-Office")
[void] $objListBox.Items.Add("Admin-Support")
[void] $objListBox.Items.Add("Base")
[void] $objListBox.Items.Add("IT")

$objForm.Controls.Add($objListBox) 
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

#resulting var
#$TSDepartment

# Simple PowerShell ElseIf
# Admin-Support softwre list
if ($TSDepartment = "Admin-Support")  
{
'Admin Support Software'
choco upgrade chocolatey    
get-executionpolicy         
set-executionpolicy remotesigned                        

choco   install 7zip    --ignore-checksum
choco   install adobereader --ignore-checksum
choco   install cutepdf --ignore-checksum
choco   install jre8    --ignore-checksum
choco   install Silverlight --ignore-checksum
choco   install vlc --ignore-checksum
choco   install webex   --ignore-checksum

} 

# Law Office softwre list
ElseIf ( $TSDepartment = "Law-Office")  
{
'Law Office Software'
choco upgrade chocolatey    
get-executionpolicy
set-executionpolicy remotesigned

choco install 7zip --ignore-checksum
choco install adobereader --ignore-checksum
choco install cutepdf --ignore-checksum
choco install vlc  --ignore-checksum
choco install jre8 --ignore-checksum
choco install rsclientprint --ignore-checksum
choco install Silverlight --ignore-checksum
choco install webex --ignore-checksum
} 

# Call Center softwre list
ElseIf ( $TSDepartment = "Call-Center")  
{
'Call Center Software'
choco upgrade chocolatey    
get-executionpolicy         
set-executionpolicy remotesigned            

choco   install adobereader --ignore-checksum
choco   install cutepdf --ignore-checksum
choco   install jre8    --ignore-checksum
choco   install Silverlight --ignore-checksum
choco   install vlc --ignore-checksum
choco   install webex   --ignore-checksum
choco   install Silverlight --ignore-checksum
choco   install softphone   --ignore-checksum
}

# IT softwre list
ElseIf ( $TSDepartment = "IT")  
{
'IT Software'
choco upgrade chocolatey    
get-executionpolicy         
set-executionpolicy remotesigned            

choco   install 7zip    --ignore-checksum
choco   install adobereader --ignore-checksum
choco   install cutepdf --ignore-checksum
choco   install jre8    --ignore-checksum
choco   install Silverlight --ignore-checksum
choco   install vlc --ignore-checksum
choco   install webex   --ignore-checksum
choco   install Firefox --ignore-checksum
choco   install foxitreader --ignore-checksum
choco   install Ghostscript.app --ignore-checksum
choco   install GoogleChrome    --ignore-checksum
choco   install greenshot   --ignore-checksum
choco   install notepadplusplus --ignore-checksum
choco   install PowerShell  --ignore-checksum
choco   install putty   --ignore-checksum
choco   install sysinternals    --ignore-checksum
choco   install windirstat  --ignore-checksum
choco   install wireshark   --ignore-checksum
}

# Base Software List
ElseIf ( $TSDepartment = "Base")  
{
'Base Software'
choco upgrade chocolatey    
get-executionpolicy         
set-executionpolicy remotesigned            

choco   install adobereader --ignore-checksum
choco   install cutepdf --ignore-checksum
choco   install jre8    --ignore-checksum
choco   install Silverlight --ignore-checksum
choco   install webex   --ignore-checksum
}

# null Software List
Else
{
'Upgrade Choco'
choco upgrade chocolatey    
get-executionpolicy         
set-executionpolicy remotesigned            
}

PL/SQL Will this if then statement work?

If p_CreditHour is between 0 and 30 (including), the system prints "This student is a Freshmen" on the screen; if between 31 and 60 credits, print "This student is a Sophomore", between 61-90 credits, print "This student is a Junior"; for more than 91 credits, print "This student is a Senior."

Does the following program reflect the logic of the previous problem?

IF credit <= 30 THEN
     dbms_output.putline ('This student is a Freshmen'.);
END IF;
IF credit <= 60 THEN
     dbms_output.putline ('This student is a
Sophomore.');
END IF;
IF credit <= 90 THEN
     dbms_output.putline ('This student is a Junior.');
END IF;
IF credit > 90 THEN
     dbms_output.putline ('This student is a Senior.');
END IF;

Where's my flaw in this crafting system?

I'm not very good at debugging and haven't been with java for long enough to see any errors.
So, how I'm making my crafting system is in four steps:

1) I test if the player is in a crafting block with

if(!Crafting.isOpen())
    return;

2) If that is true then I test if the player has specific items with

if(inventoryItems.contains(//certain item) && inventoryItems.contains(// certain item) {
    g.fillRect(100, 100, 100, 20);
    g.setColor(Color.white);
    g.drawString("Craft " + // certain item, 110, 111);
} else 
    return;

3) If all of that is true I test if the mouse touches the craft "button" with

if(Mouse.MouseX() >= 100 && Mouse.MouseX() <= 200 && Mouse.MouseY() >= 100 & Mouse.MouseY() <= 120) {
    inventoryItems.add(// certain item);
}

I feel like step 2 is wrong, but I can't find any error; also, is there any alternative to .contains();?

Determine if three side lengths form an obtuse triangle c++

I have a program that determines whether or not a triangle is an obtuse triangle. The program instructs the user to input 3 side length values (s1,s2,s3). If the squared value of the smaller two side length values is less than the squared value of the largest side value then it is an obtuse triangle.

For Example:

s1 = 3, s2 = 5, s3 = 9

3^2 + 5^2 < 9^2

34 < 81

This is an obtuse triangle.

I have two versions of my program shown below that both give the same output. My question is which one is more efficient? or is there another version that is more efficient than my two versions?

Version 1:

double s1,s2,s3;
cout << "Enter three numbers -> ";
cin >> s1 >> s2 >> s3;
if (max(max(s1,s2),s3) == s1){
    if(pow(s2,2)+pow(s3,2) < pow(s1,2)){
        cout << "This is an obtuse triangle";
    } else {
        cout << "Not an obtuse triangle";
    }
} else if (max(max(s1,s2),s3) == s2){
    if(pow(s1,2)+pow(s3,2) < pow(s2,2)){
        cout << "This is an obtuse triangle";
    } else {
        cout << "Not an obtuse triangle";
    }
} else {
    if(pow(s1,2)+pow(s2,2) < pow(s3,2)){
        cout << "This is an obtuse triangle";
    } else {
        cout << "Not an obtuse triangle";
    }
}

Version 2:

double s1,s2,s3;
cout << "Enter three numbers -> ";
cin >> s1 >> s2 >> s3;
if( max(s1,s2) < s3){
    if(pow(s1,2) + pow(s2,2) < pow(s3,2)){
        cout << "This is an obtuse triangle";
    } else {
        cout << "Not an obtuse triangle";
    }
} else {
    if(pow(min(s1,s2),2) + pow(s3,2) < pow(max(s1,s2),2)){
        cout << "This is an obtuse triangle";
    } else {
        cout << "Not an obtuse triangle";
    }
}

How to restart a script from a specific point?

Is there a way to make this script

#!/bin/bash

X=0

while true; do
    if [ $X -eq 10 ]; then
        sudo rm -r /var/log/daemon.log
        sudo rm -r /var/log/syslog
        sudo reboot
    fi

  expressvpn disconnect

    while timeout 2 ./typer; [ $? -eq 124 ]
    do
        exec $0
        let X++
    done
done

Restart from after the statement X=0 if the command times out so that the counter doesn't reset? I'm using exec $0 but it resets the counter every time I guess

Looking for an equivalent function without use if statement

I’ve this function

int f(int x) {
  if (x == 0)
    return 0;
  return 1;
}

Is possible to write an equivalent function without use the if statement?

how can I get the count of visits per participant taking into account the hours when they went to their appointment in R

I have a dataset like the one below but with much more participants. Just copy and paste the following code in R:

d <- structure(list(id = c(33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L), VisitDate = c("10/12/14", "10/12/14", "10/13/14", "10/14/14", "11/7/14", "11/7/14", "11/8/12", "11/8/14", "11/9/12", "4/17/13", "5/29/15", "10/26/12", "10/29/12", "11/7/13", "2/15/17", "2/9/15", "3/6/17", "3/7/13", "4/8/16", "4/8/16", "7/28/14", "9/14/12", "9/18/15", "9/18/15"), VisitHours = c(13L, 15L, 10L, 11L, 10L, 9L, 13L, 11L, 11L, 22L, 9L, 16L, 14L, 10L, 11L, 10L, 9L, 14L, 13L, 14L, 13L, 10L, 10L, 14L)), .Names = c("id", "VisitDate", "VisitHours"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -24L), spec = structure(list(cols = structure(list(id = structure(list(), class = c("collector_integer", "collector")), VisitDate = structure(list(), class = c("collector_character", "collector")), VisitHours = structure(list(), class = c("collector_integer", "collector"))), .Names = c("id", "VisitDate", "VisitHours")), default = structure(list(), class = c("collector_guess", "collector"))), .Names = c("cols", "default"), class = "col_spec"))

Here, there are two participants with ids 33 and 45 whom had different appointments or visits at different dates and times. Basically, each VisitDate should count as one visit, except when the difference between VisitHours for the same day equals or is greater than 3. If it's lower than 3, then I want it to count as just one visit.

First, I would like to get a variable that would count the number of visits. For example, for participant 33, on the day 10/12/14, had two visits, but these were very close to each other (one at 13 and the other one at 15, see column VisitHours), so these visits should count only as one visit. On the other hand, participant 45 had two visits on 9/18/15 and these were far away from each other (one at 10 and other at 14, see column VisitHours), so these visits should count as two visits even if they were on the same day because the difference between VisitHours for the same day equals or is greater than 3. See the dataframe below as an example of how this should look like:

structure(list(id = c(33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L, 45L), VisitDate = c("10/12/14", "10/12/14", "10/13/14", "10/14/14", "11/7/14", "11/7/14", "11/8/12", "11/8/14", "11/9/12", "4/17/13", "5/29/15", "10/26/12", "10/29/12", "11/7/13", "2/15/17", "2/9/15", "3/6/17", "3/7/13", "4/8/16", "4/8/16", "7/28/14", "9/14/12", "9/18/15", "9/18/15"), VisitHours = c(13L, 15L, 10L, 11L, 10L, 9L, 13L, 11L, 11L, 22L, 9L, 16L, 14L, 10L, 11L, 10L, 9L, 14L, 13L, 14L, 13L, 10L, 10L, 14L), CountVisits = c(1L, 0L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L)), .Names = c("id", "VisitDate", "VisitHours", "CountVisits"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -24L), spec = structure(list(cols = structure(list(id = structure(list(), class = c("collector_integer", "collector")), VisitDate = structure(list(), class = c("collector_character", "collector")), VisitHours = structure(list(), class = c("collector_integer", "collector")), CountVisits = structure(list(), class = c("collector_integer", "collector"))), .Names = c("id", "VisitDate", "VisitHours", "CountVisits")), default = structure(list(), class = c("collector_guess", "collector"))), .Names = c("cols", "default"), class = "col_spec"))

At the end, I want just one row for each participant and the sum of the visits that were calculated in the previous dataframe:

d1 <- structure(list(id = c(33L, 45L), CountAllVisits = c(8L, 12L)), .Names = c("id",  "CountAllVisits"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,  -2L), spec = structure(list(cols = structure(list(id = structure(list(), class = c("collector_integer", "collector")), CountAllVisits = structure(list(), class = c("collector_integer", "collector"))), .Names = c("id", "CountAllVisits")), default = structure(list(), class = c("collector_guess", "collector"))), .Names = c("cols", "default"), class = "col_spec"))

Thank you!

not going into the for loop vbscript

I have two arrays and I need to compare their values. I wrote a for loop and when I am trying to debug its not going into the loop at all.

Dim i, value
dim flag
i = 0
For i = 0 To UBound(groupName_LocationsTable) -1
    flag = False
        If groupName_LocationsTable(0,i) = groupName_getLocationsAPI(0,i) Then
            flag = True
        End If
Next 
If flag Then
    Response.Write groupName_LocationsTable(i) & " not found<br />" "Pass"
Else
    Response.Write groupName_LocationsTable(i) & " not found<br />"
End If

Why am I getting a crash when I let the user leaving the field blank and entering a negative values at the same time as leaving some field blank

public void add() {

    // declaring and initializing the blank for if statement
    String blank = "";

    // getting the informations from the imputs
    firsts = first.getText();
    lasts = last.getText();
    s1 = w1.getText();
    s2 = w2.getText();
    s3 = w3.getText();
    s4 = w4.getText();

    // equalling the same variables so it will help to make if statement work properly

    fs = firsts;
    ls = lasts;
    ss1 = s1;
    ss2 = s2;
    ss3 = s3;
    ss4 = s4;

    iw1 = Integer.parseInt(s1); // converting from string to integer for week 1
        iw2 = Integer.parseInt(s2); // converting from string to integer for week 2
        iw3 = Integer.parseInt(s3); // converting from string to integer for week 3
        iw4 = Integer.parseInt(s4); // coverting from string to integer for week 4

    if (fs.equals(blank) || ls.equals(blank) || ss1.equals(blank) || ss2.equals(blank) || ss3.equals(blank) || ss4.equals(blank)) {
        JOptionPane.showMessageDialog(null, "You have not type in one or more blank fields. Please try again.");// display the mesage
    } else if (iw1 < 0 || iw2 < 0 || iw3 < 0 || iw4 < 0) {

        JOptionPane.showMessageDialog(null, "You typed the point(s) in negative value(s). Please try again by entering a positive value(s).");// display the mesage
    } // adding the new passenger info into the data
    else {


        firstn.add(firsts);
        lastn.add(lasts);
        we1.add(iw1);
        we2.add(iw2);
        we3.add(iw3);
        we4.add(iw4);
    }

}

I am getting a crash on the program when I hit add button when I left some field blanks and putting - values for week 1, 2, 3, and 4. Can you help me please. aaaaaaaaaysdioyudewdwdewywdwey8wed9wyde9wdy8e89yw9dewy8d9dweyd8e9wdy8e8dy8e98wdy89e8yd8y9ey8dy8ey8yd8y8e8d8yywydy8y8dy8yedeyd88yed8ye8d8eyd8de8edwy8ey0edwyewwy80w8yey8dy8edydyedshuchiudhucudchdhcudgiyf989fy8e8dyd9ydfchudhchudhuucduhhudhhdudud98e8de8wy8dywyy8eyy8eyyeyfe9y77fhcdc8jc8jcj8c8ew0e0we88fufh

Create distinct result set with two datasets

In SAS, I have the following two datasets:

Dataset #1: Data on people's meal preferences

   ID |  Meal   | Meal_rank
    1   Lobster       1
    1   Cake          2
    1   Hot Dog       3
    1   Salad         4
    1   Fries         5
    2   Burger        1
    2   Hot Dog       2
    2   Pizza         3
    2   Fries         4
    3   Hot Dog       1
    3   Salad         2
    3   Soup          3
    4   Lobster       1
    4   Hot Dog       2
    4   Burger        3

Dataset #2: Data on meal availability

  Meal   | Units_available
  Hot Dog     2
  Burger      1
  Pizza       2

In SAS, I'd like to find a way to derive a result dataset that looks as follows (without changing anything in Dataset #1 or #2):

   ID |  Assigned_Meal
    1   Hot Dog
    2   Burger
    3   Hot Dog
    4   Meal cannot be assigned (out of stock/unavailable)

The results are driven by a process that iterates through the meals of each person (identified by their 'ID' values) until either:

  1. A meal is found where there are enough units available.
  2. All meals have been checked against the availability data.

Notably:

  1. There are cases where the person lists a meal that isn't available.

The dataset I'm working with is much larger than in this example (thousands of rows).

Here is SAS code for creating the two sample datasets:

    proc sql;
       create table work.ppl_meal_pref
           (ID char(4),
            Meal char(20),
            Meal_rank num);

    insert into work.ppl_meal_pref
        values('1','Lobster',1)
        values('1','Cake',2)
        values('1','Hot Dog',3)
        values('1','Salad',4)
        values('1','Fries',5)
        values('2','Burger',1)
        values('2','Hot Dog',2)
        values('2','Pizza',3)
        values('2','Fries',4)
        values('3','Hot Dog',1)
        values('3','Salad',2)
        values('3','Soup',3)
        values('4','Lobster',1)
        values('4','Hot Dog',2)
        values('4','Burger',3)
        ;
    quit;
    run;

    proc sql;
       create table work.lunch_menu
           (FoodName char(14),
            Units_available num);

    insert into work.lunch_menu
        values('Hot Dog',2)
        values('Burger',1)
        values('Pizza',1)
        ;
    quit;
    run;

I've tried to implement loops to perform this task, but to no avail.

Python: Element-wise implementation of 'in' conditional operator

So, I have two lists:

x =[170 169 168 167 166 165 183 201 219 237 255 274 293 312 331 350]
y =[201,168]

I want to write a conditional if statement that is true only if all the contents of y are in x. How do I do this?

E.g. -- assert(y[0] in x) and assert(y[a] in x) both give True, but assert(y in x) gives False. Similarly, assert( any(y) in x ) raises an error as well.

How i can set two roles in one "if"

How I can set two roles in one "if", like:

if (value == 0 and value >3) {  

           }

PYTHON, if-statement meets only first condition. PuLP

I am trying to use PuLP to optimize a system, minimizing the cost of it. I am using multiple If's and the problem is that it always meets the first condition. Here is my code. I hope someone can help me, as I am just starting to learn about this language.

import numpy as np
import pandas as pd
from pulp import *

idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
d = {
'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx),
'hour':pd.Series(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'], index=idx),
'output':pd.Series([0,0,0,0.087,0.309,0.552,0.682,0.757,0.783,0.771,0.715,0.616,0.466,0.255,0.022,0,0,0,0,0,0,0,0,0], index=idx)}
cfPV = pd.DataFrame(d)


idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
d1 = {
'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx),
'hour':pd.Series(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'], index=idx),
'output':pd.Series([0.528,0.512,0.51,0.448,0.62,0.649,0.601,0.564,0.541,0.515,0.502,0.522,0.57,0.638,0.66,0.629,0.589,0.544,0.506,0.471,0.448,0.438,0.443,0.451], index=idx)}
cfWT = pd.DataFrame(d1)


prob = LpProblem ("System", LpMinimize)

CPV = LpVariable ("PVCapacity",0) #PV Capacity in kW
CWT = LpVariable ("WTurCapacity",0) #WT Capacity in kW
CBA = LpVariable ("BatteryCapacity",0) #Battery Capacity kW

prob+= 63.128*CPV + 88.167*CWT + 200*CBA, "TotalCostSystem"

xEne = 0
xREin = 0
xBin = 0
xBout = 0
SOCB = 0
xPEMin = 0
xOvEn = 0
xSum = 0

CPEM = 230

for i in idx:

xEne = (CPV*cfPV['output'][i]+CWT*cfWT['output'][i])

#Low limit for Variables
prob += (CPV*cfPV['output'][i]+CWT*cfWT['output'][i]) >= 0
prob += xREin >= 0
prob += xBin >= 0
prob += xBout >= 0
prob += SOCB >= 0
prob += xPEMin >= 0
prob += xOvEn >= 0
prob += xSum >= 0
prob += CBA >= SOCB
prob += xBin <= (CBA - SOCB)
prob += xBout <= SOCB

#Cases

#Case 1 xEne > CPEM
if xEne >= CPEM:

xREin = CPEM
xBout = 0
xOvEn = xEne - CPEM 

#Case 1.1 xOvEn < CBA - SOCB
if (value(xOvEn) <= (CBA - value(SOCB))): 
xBin = xOvEn

#Case 1.2 xOvEn > CBA -SOCB
else: 
xBin = CBA - SOCB 

#Case 2 xEne < CPEM
else:
xREin = xEne
xBin = 0 
xOvEn = 0

#Case 2.1 SOCB > CPEM - xREin
if (value(SOCB) >= (CPEM - value(xREin))):
xBout = (CPEM - xREin)

#Case 2.2 SOCB < CPEM - xREin 
else:

xBout = SOCB 

SOCB = SOCB + xBin - xBout
xPEMin = xREin + xBout 

xSum += xPEMin

prob += xSum >= 5000


prob.writeLP("PVWTBattSyste.lp")

prob.solve()

The solution given always meets first condition. Also, when the condition is not met (changing CPEM to 50000000000000, for example) the if works as it is true.

Thank you in advance!

Nested if else statement in R with multiple string in each cell

I would like to do an if else statement with multiple conditions. I have two data frames, first one looks like this:

prefix <- "sample"
suffix <- seq(1:100)
id <- paste(prefix, suffix, sep="")
indv_df <- data.frame(id, count = matrix(ncol=1, nrow=100))

And the first 15 rows of indv_df looks like this:

           id count
1     sample1    NA
2     sample2    NA
3     sample3    NA
4     sample4    NA
5     sample5    NA
6     sample6    NA
7     sample7    NA
8     sample8    NA
9     sample9    NA
10   sample10    NA
11   sample11    NA
12   sample12    NA
13   sample13    NA
14   sample14    NA
15   sample15    NA

The second table called row1 that I have looks like this:

 Hom <- paste("sample2", "sample3", "sample4", sep=",")
 Het <- paste("sample5", "sample6", "sample7", sep=",")
 Missing <- paste("sample10", "sample11", sep=",")
 row1 <- data.frame(Hom, Het, Missing)

looks like this:

                      Hom                     Het           Missing
1 sample2,sample3,sample4 sample5,sample6,sample7 sample10,sample11

I am trying to do if else statement that if the first row's id does not match any of the second table's content, write "0" in the first table's first row, second column. This is what I tried but didn't work, which I am not too surprised since this is my first if else statement. I know it should be straight forward but I tried a few different methods none worked


> if(grep(indv_df$id[1], row1$Hom)){
+   apply(indv_df[1,2]=="2")
+ } else if(grep(indv_df$id[1], row1$Het)){
+   apply(indv_df[1,2]=="1")
+ } else if(grep(indv_df$id[1], row1$Missing)){
+   apply(indv_df[1,2]=="missing")
+ } else (apply(indv_df[1,2]=="0"))

this is the error message I got:

Error in if (grep(indv_df$id[1], row1$Hom)) { : 
  argument is of length zero

The real dataset has 4 million rows in the second data.frame, so I am just testing the first step..... once I get through this I will try to do that in a loop for all rows. :D Thank you for all the help in advance.

nested if else statement in R with FIRST from SAS

I would like to replicate the following SAS code in R:

     if first.permno then do;
 LME=me/(1+retx); cumretx=sum(1,retx); me_base=LME;weight_port=.;end;
 else do;
 if month(date)=7 then do;
    weight_port= LME;
    me_base=LME; /* lag ME also at the end of June */
    cumretx=sum(1,retx);
 end;
 else do;
    if LME>0 then weight_port=cumretx*me_base;
    else weight_port=.;
    cumretx=cumretx*sum(1,retx);

My code in R is:

CRSP_merged1 <- within(CRSP_merged1, 
          if(CRSP_merged1$PERMNO != lag(CRSP_merged1$PERMNO)){
            CRSP_merged1$lag_ME <- CRSP_merged1$ME/(1+CRSP_merged1$RET_ADJ)
            CRSP_merged1$cumret <- sum(1, CRSP_merged1$RET_ADJ)
            CRSP_merged1$ME_base <- CRSP_merged1$lag_ME
            CRSP_merged1$weight_port <- 0
          } else if (month(CRSP_merged1$Date) == 7){
            CRSP_merged1$weight_port <- lag_ME
            CRSP_merged1$ME_base <- CRSP_merged1$lag_ME
            CRSP_merged1$cumret <- sum(1, CRSP_merged1$RET_ADJ)
          } else if (CRSP_merged1$lag_ME > 0){
            CRSP_merged1$weight_port <- CRSP_merged1$cumret * CRSP_merged1$ME_base
          } else {
            CRSP_merged1$weight_port <- 0
            CRSP_merged1$cumret <- CRSP_merged1$cumret * sum(1, CRSP_merged1$RET_ADJ)
}
)

I am especially struggling to replicate the FIRST function from SAS. I looked at a number of posts in the forum like http://ift.tt/2h33FQ9 but I wasn`t able to amend this to my case. What I am trying to achieve is: My dataframe "CRSP_merged1" is sorted by date and PERMNO (which is a stock identifier). For every row in the dataframe, if its a new PERMNO go the first if-loop and create the new dataframe variables "lag_ME", "cumret", "ME_base" and "weight_port". If the month of the date is 7 go the second if-loop and adjust the new variables, if ME>0 go the third loop, otherwise go the last loop. Thanks for any help with this!

Bash testing -n

I thought the -z option in a bash test would be true if the condition evaluates to null and -n would be true if the condition is not null. So then why is this happening?

var1=
echo ${#var1} # 0

[ -n $var1 ] && echo 'hi' # hi
unset var1
[ -n $var1 ] && echo 'hi' # still prints hi!

Excel if Statement replacing value in columns

I need some assistance with an if statement or a formula.

I have two columns K & L and both of them have values. If Column L has a value "X" I want Column K's value to be replaced with the one in Column L. However when there is no value in Column L, I want the value in Column K to remain as is.

Value in Column K to be replaced by the value in Column L only if available, if not leave it unchanged.

why the if-else does not loop

I find my prog's if-else does not loop, why does this happen and how can I fix it for checking?

for x in range(1,11):
    num = int(input("Please enter number "+str(x)+" [10 - 100]: "))

    if num >= 10 and num <= 100:
        inList.append(num)
    else:
        num = int(input("Please enter a valid number: "))

print(inList)

I found that the if-else only did once, so when I enter invalid num for the 2nd time, the prog still brings me to the next input procedure. What happen occurs?

Please enter number 1 [10 - 100]: 1
Please enter a valid number: 1
Please enter number 2 [10 - 100]:

Additionally, may I ask how can I check the inList for duplicated num, and then remove both of the num in the list?

If statement gives condition is always true

When I use If statement it gives me that the condition x is always true although I use the same code in another app and its work ,but in this case I use it in onOptionsItemSelected method for my menu ,So can someone help ??

public class Wellcome extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wellcome);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

        }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.chang_language, menu);
    return true;
}
 Boolean x=true;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   int id = item.getItemId();
   if (id == R.id.arabic) {
       if (x =true) {
           setLocale("en");
           x = false;
       } else  if (x =false) {
           setLocale("ar");
           x = true;
       }
     return true;
   }
    return super.onOptionsItemSelected(item);
}
public void setLocale(String lang) {
    java.util.Locale myLocale = new Locale(lang);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    Configuration conf = getResources().getConfiguration();
    conf.locale = myLocale;
    getResources().updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, Wellcome.class);
    startActivity(refresh);
       }
     }

Multiple conditions using an AND if Statement, javascript

can anyone tell me what's wrong with this if statement? If I use either of the two main conditions on their own the statement works fine but when I add that middle && statement it stops working. I've searched online and can't see what's wrong Please, help! :) ps. I can even change that middle && to a || statement and it works as well. I'm so confused...

if ((containerId.id == "LineOne" && dropLoc == "dropLocation1.1") && (containerId.id == "LineTwo" && dropLoc == "dropLocation2.2"))
        {
            alert("finished");
            cdpause();      
        }

Stop If and Else stetment on Counting

I want to create the page that show loading and than show the random number with time, but the problem is when loading switch to random number, that random number change again to loading (looping).

here is my code :

<div class="spinner" id="box1">
  <div class="double-bounce1"></div>
  <div class="double-bounce2"></div>
</div>
<div class="suhu" style="display:none" id="box2">
 <span style="color: #E74C3C; font-size: 30px; text-align: center;">
    Suhu Anda : </span><span id="decimalgenerate" style="font-size: 30px;"></span><span style="font-size: 30px;">&#8451;<br/></span><span style="color: #E74C3C;"></span>
</div>

and here is the JS code :

setInterval(function thing() {

      var b1 = document.getElementById('box1');
      var b2 = document.getElementById('box2');

      if(b1['style'].display == 'none')break; {
        b1['style'].display = 'block';
        b2['style'].display = 'none';

      } else {
        b1['style'].display = 'none';
        b2['style'].display = 'block';

      }


    }, 7000);

Is there a difference in efficiency between checking "if something is or else" and "if something isn't or else"

For example, right now I have a Python code that is used with Sympy and I have to check if an input is string and act according to that.

I am curious if it is different when you check:

if(True):
    Thing1()
else:
    Thing2()

Or:

if(False):
    Thing1()
else:
    Thing2()

For example with my code, I can check if something is a string/word and then turn it into a Sympy symbol and then assign it to an array, else assign it as an int to array. Or I can check if something ISN'T a string/word, and if it isn't, assign it as an int, else assign it as a Sympy symbol.

So my question is, is there a difference between checking "True or False" and "False or True"? Does it depend on input being more "Trues" than "Falses" or vice versa?

Batch file to search multiple subdirectories for file/folder, if found, copy that subdirectory to another location

Firstly, I apologise for the lack of preliminary code. I am very novice at this stuff. I have spent a few hours Googling and tried a few different things however, nothing is working out. I didn't think there was much point copy pasting something here, which may be on completely the wrong track. If, despite that, you're interested in my query, please read on.

I am wanting to search all sub-folders under a specific folder for another folder/file/file extension and if that file/folder exists, copy the folder to another location. The Folder structure, up to the point where the file or folder is found would need to be intact (with only the folders necessary to get to that folder).

Example folder structure:

\Drive1

\\Folder123
\\\FodlerA
\\\\Folder!
\\\\Folder@
\\\\Folder#

\\Folder456
\\\\FolderA
\\\\Folder!
\\\\Folder$
\\\\Folder#

\\Folder789
\\\FolderA
\\\\Folder!
\\\\Folder@
\\\\Folder%

Let's say I wanted to search Drive1 for every instance of Folder@ and then copy that folder (and contents) to a new location with the necessary folders to get to Folder@.

So I would end up with something like:

Drive2:
Folder123/FolderA/Folder@
Folder789/FolderA/Folder@

If the in-between folders were excluded and I just ended up with:

Folder123/Folder@
Folder789/Folder@

This would suffice.

Is something like this possible? Any guidance would be appreciated.

how to make alerts appear if the number of infant is more than adults

I want to make the alert appear if the number of infant is more than adults. I've tried but it looks like something went wrong. Please help.. thanks before

ex: http://ift.tt/2yZ4y3c

var button = $('#submit'),
    adult = $('#adult option:selected').val(),
    infant = $('#infant option:selected').val();

if(adult > infant) {
 $("#alert").hide;
}
else if(adult == infant) {
 $("#alert").hide;
} 
else {
 $("#alert").show;
}

Using If else conditions on Vectors

I am having issues with the following piece of logic. Basically i have a dataframe of stocks for MS and Apple. I want to excute buy and sell conditions based on certain price comparisons. But R does not allow me to use If Else conditions with vectors how do i overcome this scenario

if (mydatastocks$MS<120){
  if (mydatastocks$MS>110 & mydatastocks$MS<120){
    print("buy small")
  }else{
    print("Buy Huge")
  }
} else{
      if(mydatastocks$MS>120)
      print("Ignore")
}

lundi 30 octobre 2017

Need help writing and reading files and storing data into lists

I need help with a weighted grade calculator, i have the bits that i need to calculate the data and the weighted averages. My problem is importing the data and storing it. I think i need to use lists but im just not sure how to separate each entry, I know I can use .split() and i will probably do that. But my real problem is figuring out how to store these values and then write to an output file.

So this is what the .txt file will look like for the input that i am importing to my program with a "open("scores.txt","r")" command

Babbage, Charles
10.0   9.5    8.0  10.0
 9.5  10.0    9.0
85.0  92.0   81.0
Turing, Alan
10.0   8.0    6.0
10.0  10.0    9.0   9.5
90.0  92.0   88.5
Hopper, Grace
10.0  10.0    8.0
10.0  10.0    9.0   9.5
90.0  92.0   88.0
Van Rossum, Guido
 7.5   8.5
 7.5   8.5    6.0   9.0
68.0  81.0   70.0
Backus, John
 9.5   9.5   10.0   8.0   9.5  10.0
 7.5   8.5    6.0   9.0  10.0
99.0  93.0  100.0
Crawley, Bryan
 6.0
 7.5
70.0  60.0   55.5

I tried using s.isdigit and s.isalpha and that didnt really work. 1st line is quizzes, 2nd line is projects, and third is exams. Number of quizzes and exams are arbitrary, the exams will always have three.

Here's what the output needs to look like:

Babbage, Charles      89.4   B
Turing, Alan          91.3   A
Hopper, Grace         92.7   A
Van Rossum, Guido     75.5   C
Backus, John          94.4   A
Crawley, Bryan        63.9   D

Here is what my code looks like now:

quiz_scores = []

while True:
    score = float(input("Quiz #{} ----- ".format(len(quiz_scores)+1)))
    if score == -1:
        break
    quiz_scores.append(score)
quiz_total = sum(quiz_scores) - min(quiz_scores)
if len(quiz_scores)>1:
    quiz_avg =  (quiz_total/((len(quiz_scores))-1)*10)
else:
    quiz_avg = (quiz_total/(len(quiz_scores)*10)

print()

project_scores = []

while True:
    score2 = float(input("Project #{} -- ".format(len(project_scores)+1)))
    if score2 == -1:
        break
    project_scores.append(score2)

project_total = sum(project_scores)
project_avg = (project_total/(len(project_scores))*10)

print()

exam1 = float(input("Exam #1 ----- "))
exam2 = float(input("Exam #2 ----- "))


print()

final = float(input("Final Exam -- "))

average = ((quiz_avg*.15)+(project_avg*.20)+(exam1*.20)+(exam2*.20)+(final*.25))

print("Average ---- %.2f" % average)



if 90 <= average <= 100:
    print("Grade ------- A")
if 80 <= average < 90:
    print("Grade ------- B")
if 70 <= average < 80:
    print("Grade ------- C")
if 60 <= average < 70:
    print("Grade ------- D")
if 0 <= average < 60:
    print("Grade ------- F")

Definitely looking to learn here, not just copy and paste what you comment; so please bear with me if i have some questions for you.

Thank you guys, this community has been very helpful.

#N/A Error When using MATCH Across Multiple Sheets

=IF(OR(AND(MATCH($A2,'Day 1'!$A:$A,0),MATCH($B2,'Day 1'!$B:$B,0)),AND(MATCH($A2,'Day 2'!$A:$A,0))),"YES","NO")

I have a master database in which I inserted the formula above in cell E2. My goal is to search multiple sheets (in this case “Day 1” and “Day 2”), for a person’s first and last name (first name is in A2, last name is in B2). If there is a row in any sheet where a match is found, I want a value of “YES” to be returned. . . if no match is found in any sheet, I need “NO” to be returned.

What happens with the above formula:

  1. If a match in sheet “Day 1” is found but there none in “Day 2”, I get an #N/A error despite the first match.
  2. I can never get a value of “NO” to be returned.
  3. The only way “YES” is returned is if both “Day 1” and “Day 2” satisfy this piece:

    AND(MATCH($A2,'Day 1'!$A:$A,0),MATCH($B2,'Day 1'!$B:$B,0)

For #3 one of my problems is that it is possible for the match I’m looking for to be in only one or both sheets.

Ultimately I’d like to have this formula look for a match in up to 7 different sheets but so far I can barely get this to work with 2.

Huge thanks in advance for your time (it is much appreciated)!

One of the else if statements doesn't perform even if the condition verifies

Whenever I write a name with over 6 letters it still prints

that isn't a very long name

instead of

that's such a long name

I know this must be a basic question and that it might be pretty straightforward, but I just can't get it to work. I would appreciate any ideas on why it doesn't perform as it's supposed to.

let myName = prompt('What is your name?');

if (myName.length <= 3) {
  document.write('That is such a short name!');
}
else if (3 < myName.length < 6) {
  document.write('That isn\'t a very long name');
}
else if (myName.length >= 6) {
  document.write('That\'s such a long name!');
} 
else {
  document.write('Nop');
}

Is this an example of a ternary condition or is it something unrelated / different, i = j = 0?

I recently learned about ternary condition (specifically using : and ?, colons and questions marks, to create a condition that uses the question mark as an if statement, and the semicolon as a else statement. I recently came across the statement, i = j = 0. Is this the same type of condition? Is the statement saying:

if j = 0
{
    i == j
}
else
{
    i != j
}

Or is it referring to something different that I haven't learned yet, if so, please state what the statements purpose is, and how it works. Additionally, I couldn't find this exact question on the site, but if this is a duplicate, or if there is another website that you could refer we to that answers the question, I would be happy to delete to question, and then I would go and see what that website's information is. I would appreciate your input though, as I believe that this site does the best of any other site as for as explanations. Thank you all for your help! If you have any questions fell free to ask in the comments!

Ifelse statement syntax multiple conditions is broken

I am having some trouble with a nested ifelse statement. I have the following code written. It should force a TRUE or FALSE but I am getting some NAs. Can you help me figure out where its broken?

data looks something like...

Name<- c(Jon,Jim,Jake,Jess,Jill,Jay,Jason)
LinkFlag<- c( NA,  NA,  NA,  NA,  NA, NA, NA)
1<- c(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
2<- c(2.5,  NA,  NA,  NA,  NA, 3.0,  NA)

spread_wide<-c(Name,LinkFlag,1,2)

The intended Result is that there are no NAs

sw_RESULTS$EvalSeq1to2<-ifelse(spread_wide$`1` == 99, TRUE, 
                   ifelse(spread_wide$`1` == (spread_wide$`2`-1), TRUE,  
                           ifelse(is.na(spread_wide$`2`),TRUE,   
                                       ifelse(spread_wide$`2` ==99,TRUE,
                                            ifelse(spread_wide$`1`== (spread_wide$`2`-0.5),TRUE, 
                                                       ifelse(spread_wide$`1` == spread_wide$`2`, TRUE,  
                                                                   ifelse(spread_wide$`LinkFlag`=='FlagforSkip", TRUE,
                                                                                                                                 FALSE)))))))

How can I show/hide divs depending on dropdown selection?

I am just learning javascript and I could use some help. I have found a way to show #divA if one of the first two options are selected but how can I show #divB if the third option is selected? I don't want these divs to show unless the corresponding option is selected in the dropdown menu.

HTML:

<select class="form-control" onchange="showOptionsBelow(this)">
      <option></option>
      <option value="First option">First option</option>
      <option value="Second option">Second option</option>
      <option value="Third option">Third option</option>
</select>

<div id="divA" style="display:none;"></div>
<div id="divB" style="display:none;"></div>

Javascript:

<script>
function showOptionsBelow(elem) {
    if (elem.value == "First Option" || elem.value == "Second Option") {
      document.getElementById("divA").style.display = "block";
    } else {document.getElementById("divA").style.display = "none";
    }
}
</script>

Python 3.5 Fast Food Calculator

I am writing a simple program in Python. But I can't figure why it is not storing a value for Hcount, Scount, and Fcount. Also, it is not displaying the tax correctly. Any help would be appreciated

while True:

print("MacDoogle's:")
print("1. Hamburger = $1.50")
print("2. Soda      = $1.15")
print("3. Fries     = $1.25")
print("4. Complete Order")


choice = int(input('Make a selection: '))
while choice < 1 or choice > 4:
    choice = int(input('Enter a valid selection: '))

Hcount =0
Scount =0
Fcount =0 

if choice > 0 and choice <4:

    if choice == 1:
        amount1=int(input("Enter number of Hamburgers: "))
        Hcount += amount1

    elif choice == 2:
        amount2=int(input("Enter number of Sodas: "))
        Scount += amount2

    elif choice == 3:
        amount3=int(input("Enter number of Fries: "))
        Fcount += amount3

if choice == 4:
    sub=int((Hcount * 1.50) + (Scount * 1.15) + (Fcount * 1.25))
    tax=int(sub * 0.09)
    total=int(sub + tax)
    print('Number of Hamburgers:', format(Hcount, '3.0f'))
    print('Number of Sodas:', format(Scount, '3.0f'))
    print('Number of Fries:', format(Fcount, '3.0f'))
    print('Subtotal:', format(sub, '3.2f'))
    print('Tax:', format(tax, '3.2f'))
    print('Total:', format(total, '3.2f'))
    break

What is the reason why isn't this code running properly in C?

I am trying to learn C but my code is not running properly.It always gives fatal error.I think there is a problem in for loop.How can i fix it?

#include<stdio.h>
int main( void )
{
   int a  ;
   int b = 1 ;
   int i = 0 ;
   printf("Enter a number:");
   scanf("%d",&a);

   if(a=0)
       printf("Factorial=1");

   else if (a > 0){
       for(i=1 ; i<=a ;i++){
       b = 1;
       b *= i; 
       }
       printf("Factorial=%d",b);
   }     
   else  
       printf("FATAL ERROR");

return 0;
}

VBA InStr with multiple Strings

I want to check multiple strings with InStr and replace them if necessary.

Something like:

s1 = "ABC"  s2 = "ABCD" s3 = "ABCDE"

If InStr(s1,"D") <> 0 Then
   s1 = ""
End If
If InStr(s2,"D") <> 0 Then
   s2 = ""
End If
If InStr(s3,"D") <> 0 Then
   s3 = ""
End If

I'm sure there is a easier and more intuitive way to do this but i just dont know how.
Maybe with Loop or Case ?

Thanks in Advance

c# the functions cant return value because of paths

enter image description here There is a return path problem I don't know what is the error reason. Actually the program structure is simple and clear

Python 3 Check for exact input and repeat until correct answer given [duplicate]

This question already has an answer here:

I have never asked a question as it makes me nervous and I'm a potato. I'm very new and feel intimidated asking but I want to code and I can't because I'm stuck. I'm trying to make a text based game. this game requires specific input. and I'm trying to def a block of code specifically for that but I'm coming up with nothing.

So anyway, Here's what I'm trying to do. First there's user input. just a single word to make things easier on myself. based on what they type the program will do one of several different things. To prevent the program from crashing I need input to be specific or either the program will crash, or nothing will happen, or it will loop forever. Now I've tried looking up answers, I tried coming up with my own, I've looked all through stack overflow, I tried youtube... So this is what I've tried, and nothing has worked and for all intents and purposes... it seriously looks to me like it should work... why is it not working?! :'(

while True:
    print('what direction?')
    path1 = input()
    path = path1.lower()
    if path1 != 'south':
        print('north or south?')
    elif path1 != 'north':
        print('north or south?')
    elif path == 'north':
        print(path)
        break
    elif path == 'south':
        print(path)
        break

(doesn't work just loops)

while True:
    print('what direction?')
    direc = input()
    direc = direc.lower()
    if direc in x:
        print('you chose ' + direc)
        break
    elif direc not in 'abcdefghijklmnopqrstuvwxyz':
        print('letters only')
    else:
        break

(ends up accepting any input except it does print 'letters only' if a number is inputted)

The rest were kind of variations of this, I also tried to put north and south in a list and do it that way but it didn't work either. Please help me figure out what the best way is to define a function that forces the player to pick a specific option otherwise repeat the question until correct input is provided. <3 Please and thank you to everyone.

Error with if statement: the condition has length > 1 and only the first element will be used

I'm having trouble with an if statement. I have a data frame (data) with a column of district populations (pop82). There are three different population cutoffs, and I want to find which cutoff each district's population is closest to and then create a variable according to that answer:

low <- 10188
middle <- 13584
high <- 16980

limit.diff <- rep(NA, length(data$X))
dist.to.cutoff <- rep(NA, length(data$X))
pscore <- rep(NA, length(data$X))

for (i in length(data$X)){
  low.diff <- abs(data$pop82 - low)
  middle.diff <- abs(data$pop82 - middle)
  high.diff <- abs(data$pop82 - high)
  cutoff.diffs <- c(low.diff, middle.diff, high.diff)
  closest.cutoff <- sort(cutoff.diffs)[1]
  if (closest.cutoff == low.diff){
    pscore[i] <- low.diff/low * 100
  } else if (closest.cutoff == middle.diff){
    pscore[i] <- middle.diff/middle * 100
  } else if (closest.cutoff == high.diff){
    pscore[i] <- high.diff/high * 100
  } else if (closest.cutoff == low.diff & closest.cutoff == middle.diff){
    pscore[i] <- low.diff/low * 100
  } else if (closest.cutoff == middle.diff & closest.cutoff == high.diff){
    pscore[i] <- middle.diff/middle * 100
  }
}

I get an error: the condition has length > 1 and only the first element will be used.

Can anyone help me with this?

Thanks

Multiple conditions in if statement (Liquid)

Is it possible to put multiple conditions inside a single if statement in Shopify Liquid?

For example this is what I have:


//do something

The reason I'm wondering is because syntax highlighting stops after the first "and" operator, as if everything after that has incorrect syntax.

Modulo if statement not producing expected output

I have coded a math problem prompter. And want to make sure that in the case of division. the outcome is only whole numbers and not being divided by 0. Using the following code.

while tries < problems:
    print("What is ....")
    print()
    num1 = random.randint(0,9)
    num2 = random.randint(0,9)
    operation = random.randint(1,4)
    if operation == 1:
        op = '-'
    if operation == 2:
        op = '+'
    if operation == 3:
        op = '/'
        while num2 == 0 or num1%num2 > 0:

               num1 = random.randint(0,9)
               num2 = random.randint(0,9)

However. The only problems that are generated are such that the answer is always 1. 0. or the numerator. For instance only: 4/1 5/1 6/1 or 0/5 0/6 0/6 or 3/3 2/2 1/1

setText() not working in my code

I am making a app. When I try to setText on my TextView it does not work!

scoreteam_a and scoreteam_b does not setText(). The if statements do not work too. please help me. What's wrong in my code? teama and teamb setText() method works but not on scoreteam_a and scoreteam_b. I directly acces varibales from activiy in the methods.

Here's my code :

     package com.example.android.courtcounter;

     import android.content.Intent;
     import android.os.Bundle;
     import android.support.v7.app.AppCompatActivity;
     import android.view.View;
     import android.view.animation.AlphaAnimation;
     import android.view.animation.Animation;
     import android.widget.TextView;

     public class FinishActivity extends AppCompatActivity {
       Bundle bundle;
       String teama_name;
       String teamb_name;
       int scoreteama;
       int scoreteamb;
String scoreTeamAString;
String scoreTeamBString;
private TextView winnera;
private TextView winnerb;
private TextView draw;
private TextView teama;
private TextView teamb;
private TextView scoreteam_a;
private TextView scoreteam_b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_finish);



    bundle = getIntent().getExtras();

    winnera = (TextView) findViewById(R.id.winnera);
    winnerb = (TextView) findViewById(R.id.winnerb);
    draw = (TextView) findViewById(R.id.draw);
    teama = (TextView) findViewById(R.id.teama);
    teamb = (TextView) findViewById(R.id.teamb);
    scoreteam_a = (TextView) findViewById(R.id.scoreteama);
    scoreteam_b = (TextView) findViewById(R.id.scoreteamb);

    teama_name = MainActivity.teamAName;
    teamb_name = MainActivity.teamBName;
    scoreteama = ScoringActivity.scoreTeamA;
    scoreteamb = ScoringActivity.scoreTeamB;
    scoreTeamAString = ScoringActivity.stringTeamA;
    scoreTeamBString = ScoringActivity.stringTeamB;

    Animation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(50); //You can manage the blinking time with this parameter
    anim.setStartOffset(20);
    anim.setRepeatMode(Animation.REVERSE);
    anim.setRepeatCount(Animation.INFINITE);

    if (scoreteama > scoreteamb) {
        winnera.setVisibility(View.VISIBLE);
        winnera.startAnimation(anim);
    } else if (scoreteamb > scoreteama) {
        winnerb.setVisibility(View.VISIBLE);
        winnerb.startAnimation(anim);
    } else if (scoreteamb == scoreteama) {
        draw.setVisibility(View.VISIBLE);
        draw.startAnimation(anim);
    }

    teama.setText(teama_name);
    teamb.setText(teamb_name);
    scoreteam_a.setText(ScoringActivity.stringTeamA);
    scoreteam_b.setText(ScoringActivity.stringTeamB);



    TextView shareButton = (TextView) findViewById(R.id.share);
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, teama_name + " vs " + teamb_name + "\n" + teama_name + " = " + scoreteama + "\n" + teamb_name + " = " + scoreteamb);
            startActivity(shareIntent);
        }
    });
}

public void newmatch(View v) {
    Intent intent = new Intent(FinishActivity.this, MainActivity.class);
    startActivity(intent);
    winnera.setVisibility(View.INVISIBLE);
    winnerb.setVisibility(View.INVISIBLE);
    draw.setVisibility(View.INVISIBLE);
    winnera.clearAnimation();
    winnerb.clearAnimation();
    draw.clearAnimation();
   }
   }

Why do I get undefined variable in an if statement?

I get an error for undefined function or variable in the if statement (last line before last end), when I have already assigned the equalities.

l_min = nan(372,1);
A = randn(372,3);
B= randn(372,3);
for t=1:372
    min_ct = min( A(t,:));
      if min_ct == A(t,1);
        l = B(t,1);
        if min_ct == A(t,2);
            l = B(t,2);
        elseif min_ct == A(t,3);
            l = B(t,3);
        end
    end
    l_min(t) = l;
end

Could anyone help with this one?

how to avoid repeat the condition many times by if statement in python?

there is better way to avoid repeat the condition many times by if statement?

 for entity in entities:
        if (entity.entity_id.startswith('sensor') and  "sourcenodeid" not in entity.entity_id and "interval" not in entity.entity_id and "previous"  not in entity.entity_id and "exporting" not in entity.entity_id and "management" not in entity.entity_id and "yr" not in entity.entity_id and "alarm" not in entity.entity_id ):
            data = remote.get_state(api, entity.entity_id)
            #print(data)

i tried with or but it doesnt york properly because i got entity with condition yhich sould not be store it in data

Multiple if statemens in one Function in SML

i want to write a function in SML which check if the parameters a,b,c are true and then increase the value x everytime by 1.0 - 3.0. For Example:

fun calc(a:bool, b:bool, c:bool, d:int) = 
let
    val x = 0.0
in
    if a=true then x+1.0 else x+0.0
    ;if b=true then x+2.0 else x+0.0
    ;if c=true then x+3.0 else x+0.0
    ;if d<120 then x+4.0 else x+0.0
end

If i run this code with a,b and c true and d<120, then i get the output: val it = 0.0 : real

but i want to get the output of x. (Sorry for my bad english)

Javascript Simple If/Else statement for time

I have a task where the user can input the time (hour, minute, second) then he can give a second time (hour, minute, second) but this second time has to be in the same day as the first one and it have to be a later one. Example the user inputs 12:59:59, then 13:00:00. If its correct then it have to substract them.

I have been trying if the second hour is bigger then substract the hour, but the problem is with the minutes / seconds. I can't substract 0 from 59 or so..

Formatting Pivot table if mutiple adjacent cells are blank

I am trying to create a conditional formatting rule that if 5 adjacent cells are blank in the same row in a pivot table that it will highlight all 5 cells.

I already have blank cells highlighted but I can't figure out the rule for multiple. For example if A1 has a value of 1 and A2-A8 are blank but A9 has a value of 2 how do I highlight A2-A8 so that it stands out from single blank cells.

ImageView via If/Else Statement [duplicate]

This question already has an answer here:

I'm currently working on displaying image on ImageView via If/Else Statement, I need help on displaying via if else, the problem is it is always showing the first one.

JAVA

greetingTextView = (TextView) findViewById(R.id.greeting_text_view);
totpoints = (TextView) findViewById(R.id.au_tpresult);
totshare = (TextView) findViewById(R.id.au_tsresult);
btnLogOut = (Button) findViewById(R.id.logout_button);
cardshow = (ImageView) findViewById(R.id.card_stack);

Intent intent = getIntent();
String user = intent.getStringExtra("fullname");
String user1 = intent.getStringExtra("totalpoints");
String user2 = intent.getStringExtra("totalshare");
String user3 = intent.getStringExtra("cardtype_id");

greetingTextView.setText(user);
totpoints.setText(user1);
totshare.setText(user2);

if (user3 == "0" {
    ((ImageView) findViewById(R.id.card_stack)).setImageResource(R.drawable.thar_silver);
} else if (user3 == "1") {
    ((ImageView) findViewById(R.id.card_stack)).setImageResource(R.drawable.thar_gold);
} else if (user3 == "2") {
    ((ImageView) findViewById(R.id.card_stack)).setImageResource(R.drawable.thar_uaeu);
}

cardtype_id from database returning = "0", "1" or "2"

XML

<ImageView
    android:id="@+id/card_stack"
    android:layout_gravity="center_horizontal"
    android:layout_width="407dp"
    android:layout_height="230dp"
    android:layout_marginTop="10dp"
    app:srcCompat="@drawable/thar_silver"
    android:layout_weight="0.73" />

Thank you in advance!

dimanche 29 octobre 2017

calculating values in a string

Hi I am new to java programming,

value in a textbox is 322+1*3-5

HERE'S MY PROGRAM FOR IT.

        String abc = tf1.getText();

        String operands[]=abc.split("[+-/*]");
        String operators[]= abc.split("[0-9]");

        int agregate = Integer.parseInt(operands[0]);
        System.out.println(agregate);

        for(int i=1;i<operands.length;i++)
            {
                if(operators[i].equals("+"))
                    {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate+c;
                    }
                else if (operators[i].equals("-"))
                    {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate-c;
                    }
                else if (operators[i].equals("*"))
                {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate*c;
                    }
                else 
                    {
                    int c = Integer.parseInt(operands[i]);
                    agregate = agregate/c;
                    }

could someone help to correct this program to return right value

Guess Variables

I'm making a card game and I dont know how to make the first card guess separate from the second card guess. I've looked at some examples on different codepens, but the code is kind of hard to understand. This is what I have so far..

var cards = [
"flower", "happy", "moon",
"rocket", "taco", "tree"
];
cards.forEach(function(card) {
     $(`button.${card}`).click(function() {
      var card1 = $(`button.${card}`).val();
      var card2 = $(`button.${card}`).val();

      console.log(`card1 is ${card1}`);
      console.log(`card2 is ${card2}`);

     });
});

Else not showing good message

What my problem is, is that, when $kwota is the same as $sms_wallet in mysql database, it's still showing wrong message. I don't know what's wrong here. If anyone knows what's wrong here, respond please.

    if($get)
{
    $get = json_decode($get);

    if(is_object($get))
    {
        if($get->error)
        {
            echo $get->error;
        }
        else
        {
            $status = $get->status;

            if($status=="ok")
            {
                $q = mysql_result(mysql_query("SELECT sms_wallet FROM sms WHERE id = $key"),0);
                $kwota = $get->kwota;
                if ($kwota == $q) {
                $time = time();
                $cmd = $row['command'];
                mysql_query("INSERT INTO sms_database (user, buy_time, smskey, service, command) VALUES ('$username', $time, '$code', '$id', '$cmd')");
                foreach(explode(";", $row['command']) as $key)
                rcommand($rconIp, $rconPort, $rconPass, 10, $username, trim(str_replace("{GRACZ}", $username, $key)));
                $_SESSION['message'] = "code correct.";
                }                   
                if ($kwota !== $q) {
                    $_SESSION['message'] = "incorrect code.";
                }
            }
        }
    }
    else
    {
        echo "Nieznany błąd API.";
    }
}
else
{
    echo "Błąd połączenia z API.";
}   
fclose($get); 

Header("Location: /?action=sms&key=".$id."");
die();
}

How can I make this If Loop into a dictionary valid for Python

Am working on a fun little python project, and I am stuck trying to adapt my If loop into Dictionary, but I am just not sure how to implement this function, as I need multiple conditions to be tested.

I have Six Booleans, (bool1-bool6) that can obviously be T or F, and I need to test every possible combination of these booleans, so that I can tell my program where to draw the images.

There are 64 Possible combinations.

We can do this with 3 booleans to make it simple, There are 8 Possible combinations for 3 booleans.

If we imagine that 1=true and 0=false, then the possible combinations can be represented as such.

000
001
010
011
100
101
110
111

an if loop to represent this would be,

if (bool1==false and bool2==false and bool3==false)
      do stuff
elif (bool1==false and bool2==false and bool3==true)
     do stuff
elif (bool1==false and bool2==true and bool3==false)
     do stuff

and so on...

Please unless you can find a way to simplify this process, (understanding that I need to check ALL POSSIBLE combinations of booleans), there is no need to criticize my question. I am simply unsure of how to progress from here, and would greatly appreciate some help.

I have written out a 64 statement If Loop, and am currently working on that solution, though both myself and I'm sure my cpu would prefer a quicker method.

how to use Ascii code of alphabet as a condition in java...?

i wants to read the string to make it post-fix from infix....so I need to place check of alphabet as a condition...if alphabet then put it on the next string directly.

samedi 28 octobre 2017

Python - if name shows up in a specific position in the directory path

I am trying to write a if statement for a directory path. For example,

names = "Mary", "Joe", "John"
path = "C:/a/b/c/d/e"

If names shows up in specifically position d, then do sth. What is the syntax that I can use? Thanks

do while loop return 2 if statements

I have the following code which is returning 2 parameters at once. Namely if I type in -25 I get two results where I only want the one that states you get "0" at the rate of 0. Please see attached picture for output reference

Attached image.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Problem2
{
    class Program
    {
        static void Main(string[] args)
        {
            const decimal fifty = 7.25M;
            const decimal hundred = 15.75M;
            const decimal overhundred = 21.50M;
            decimal sumfifty = 0.0M;
            decimal sumhundred = 0.00M;
            decimal sumoverhundred = 0.00M;
            decimal sentinel;

            WriteLine("\n*** PROBLEM 4 ***\n");


            do
            {
                Write("How many pieces? ");
                Write("Enter any whole number or -999 to quit: ");
                stenter code herering input = ReadLine();
                sentinel = Convert.ToDecimal(input);

                sumfifty = sentinel * fifty;
                sumhundred = sentinel * hundred;
                sumoverhundred = sentinel * overhundred;

                if (sentinel >= -998 && sentinel <= 0)
                    {
                        WriteLine("At 0 pieces at $0.00 per piece, you've earned $0.00.");
                    }
                    if (sentinel >= 1 && sentinel <= 49)
                    {
                        WriteLine("At {0} pieces at {1} per piece, you've earned {2}.\n", sentinel, fifty, sumfifty);
                    }
                    else if (sentinel >= 50 && sentinel <= 100)
                    {
                        WriteLine("At {0} pieces at {1} per piece, you've earned {2}.\n", sentinel, hundred, sumhundred);
                    }
                    else
                    {
                        WriteLine("At {0} pieces at {1} per piece, you've earned {2}.\n", sentinel, overhundred, sumoverhundred);
                    }
                //}

            } while (sentinel != -999);

            WriteLine("\nThanks for using our system.");
            Write("Press any key to continue...");
            ReadKey();
        }
    }
}

Getting Data from a method issue

I have a method to set state but when I initialize in main method one false and one true statement I am not seeing the change I should be inside of the output. Could someone explain why this is because if state is declared I would assume it would go through the if statement but the state never gets altered from the declared variable in main method?

public void setState(String state)
{
    this.state = state;

if(state == "MA" || state == "PA")
{
    this.state = state;
}
else
{
    this.state = "Invalid Entry";
}
}

where to write the final (else statement) in this python code?

i am new at learning python and i like to try things so i wrote this if and else statements in (python 3.4.3) shell but i don't know where to write the final else statement that leads to all 4 values are false.

this is a screenshot of the code because the code inserting feature here always cutting a big part of my code note that :

a=False
b=False
c=False
d=False

If condition statement erroring "There are coding standard violations (Java)

I am working on a customization where conditions are based on participant disability value "Y" and relation code child value "C".

Build Error points to: "There are coding standard violations" ; Avoid using if statements without curly braces.

If client wants to display disability footnote on the page and dpnd is disable ; baseFtnt2 is the footnote that needs show.

I believe the error is in the syntax:

            if (
                dpndEvntBean.getHasDpndDsbl() &&
                    item.getDsblCd()
                    .trim()
                    .equals("Y") && ddb.getRltnCd().trim().equals("C"));

        {
            ddb.addFtntIdListEntry("baseFtnt2");
        }

Any help would be appreciated! Thanks in advance

how to insert if statement in Wordpress Functions.php file

I am using woocommerce and I am editing the wordpress functions.php file.

My store has two checkout pages, one before admins review orders (CHECKOUT) and the other after admins approve orders (final-checkout).

I'd like to remove the billing info from the first checkout page, and only display it in the second (final) checkout page.

In the functions.php page, I used the following if statement, but its not working. I think the if statement is being tested against the functions.php page, rather than the checkout page.

if ( is_page( 'checkout' )){

        add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

            function custom_override_checkout_fields( $fields ) {
                unset($fields['billing']['billing_first_name']);
                unset($fields['billing']['billing_last_name']);
                unset($fields['billing']['billing_company']);
                unset($fields['billing']['billing_address_1']);

                return $fields;
            }

 }

If someone can help me only show the billing info on the second checkout page and not the first, it would be very much appreciated

THANKS

comparing and displaying string from shortest to longest in java

I am writing a program which uses name.length method which will read in 3 different strings, calculate the number of characters in each string and list each string from least number of character to the highest number of characters. I also need to write this program using if and else statements or case and switch statements. Thanks for your help!

why is the 'else' a syntax error in my pyton code?

I can't find the reason why the 'else' at the end of my code is considered a syntax error. Any ideas?

balagan = "9abbcd" 
first_char_dig = balagan[0].isdigit(0)
if first_char_dig:
    if first_char_dig < 9:
        a0_new = int(balagan[0]) + 1
    else:
        a0_new = 0
else:
    a0_new = balagan[0]
a1_new = balagan[-2]
amin2_new = balagan[1]
mid_balagan_len = len(balagan) / 2
mid_balagan = balagan[mid_balagan_len]
if mid_balagan.isdigit():
    mid_new = mid_balagan
else:
    if mid_balagan.isupper():
        mid_new = lower(mid_balagan)
    else:
        mid_new = upper(mid_balagan)
if balagan[mid_balagan_len] != balagan[-2]:
    new_str = str(a0_new)+ str(a1_new) + balagan[2:mid_balagan_len] + str(mid_new) + [balagan[mid_balagan_len+1:-2] + str(amin2_new) + balagan[-1]
**else: #why is this a syntex error?**
    new_str = str(a0_new) + str(a1_new)+ balagan[2:mid_balagan_len] + str(mid_new) + str(amin2_new) + balagan[-1]
print new_str

difference between if throws and try

I have been using Team Tree house along with other methods to learn Java. Well in one of the videos we made a IF statement that used a throw exception. Nothing to crazy. The thing is when I create on it still throws the crazy long message with it. Just to clarify not talking about using a try catch here just using a if to throw a exception. a perfect example is if getting input and want to check if the input is blank or not. if its blank throw a exception to say its blank. Well the message works, I just get the long message with it. So how do I only get my message?

If /ELse In SQL Using Parameter to distinguish a Percentage to be added to Value Column

I am trying to write a SQL stored procedure using If/Else that takes the Integer from IncPercent as a parameter and IF the IncPercent is under 10 treats that as a percentage to be added to the value column on OrderDetails table. ELSE if it is 10 or above it only adds 10 percent to the value column on OrderDetails table.

    Create Procedure spAddPercentage
    (
    @IncPercent int
    )
    AS
    BEGIN 
    IF ( @IncPercent < 10 ( SELECT Value From OrderDetails)
    UPDATE Value from OrderDetails
    THEN SUM([Value] * @IncPercent / 100 + Value)
    END IF
    ELSE ( @IncPercent > 10 ( SELECT Value FROM OrderDetails)
    UPDATE Value FROM OrderDetails 
    THEN  Value * 1.1
    END ELSE
    END

Ifelse with multiple condition on date object and ouput as difference between to dates using R

I want to create sequential from 2/1/2016 to 12/1/2017. If opendate of issue is less than equal to 1/1/2016 and fixeddate is greater than equal to 2/1/2016 then difference between opendate1 and 1/1/2016 in days else 0

All the dates are in %m/%d/%Y format

It should give ouput like below;

Open_DateTime OPEN_MONTH FIX_MONTH 2/1/2016 3/1/2016 /1/2016 1/30/2016 1/1/2016 2/1/2016 1.32 0.00 0.00 1/31/2016 1/1/2016 2/1/2016 0.09 0.00 0.00 1/12/2015 1/1/2015 3/1/2016 384.01 413.01 0.00 12/10/2015 12/1/2015 10/1/2017 52.27 81.27 112.27

vendredi 27 octobre 2017

How can I can I reference number 1, 2, or 3 in my echo statement to say "First number is not numeric! Please enter a numeric value for number 1"?

Do I need to reference my form?

<form action="form1.php" method="POST">
<fieldset>
<legend>Please input numeric value in each of three text boxes below:
</legend>
<p><label for="number">number 1: <input type="text" name="number" size="9">
</label></p><br>
<p><label for="number">number 2: <input type="text" name="number2" size="9">
</label></p><br>
<p><label for="number">number 3: <input type="text" name="number3" size="9">
</label></p><br>
</fieldset>
<div id="center"><input type="submit" value="Submit"></div>
</form>

I want be able to have my echo statement state that I am missing a number from one of my textboxes

if(empty($_POST['number']) || empty($_POST['number2']) || 
empty($_POST['number3'])){
        echo "You forgot to values for all three textboxes";
    } else { if(!is_numeric($_POST['number']) || 
is_numeric($_POST['number2']) || is_numeric($_POST['number3'])){
        echo "First number is not numeric! Please enter a numeric value for 
number 1";
        }
    }

Perl directory is getting past if(! -d) statement?

Okay so I have a program that basically looks into a passed in directory, if any file names match a pattern I will make a directory and move that specific file and any that matches it (regardless of extension) into that directory. Now if they don't match I should move them into the PassedInDir/misc/ directory.

I have a condition in both cases to avoid passing in any directory (as my program isn't ready to deal with those yet) something like if( ! -d $fp).

Everything works fine when I run it the first time in the directory. However when I run it again on the same directory (which should now only contain directories) I get the Error Could not move file assignmentZ to destination DataB/misc at projectSorter.pl line 16.. AssignmentZ is a directory however its somehow getting past the (!-d) in the second case.

#!/usr/bin/perl -w
use File::Copy;
if(@ARGV < 1){
    print "\nUsage: proj6.pl <directory>\n\n";
    exit;
}
die("\nDirectory $ARGV[0] does not exist\n\n") if( ! -e $ARGV[0]);
opendir( DIR, $ARGV[0]) or die("\nCould not open directory $ARGV[0]\n\n");
while(($fp = readdir(DIR))){
    if($fp =~ m/proj(.*)\./){
        (! -d "$ARGV[0]/assignment$1") && (mkdir "$ARGV[0]/assignment$1");
        move("$ARGV[0]/$fp" , "$ARGV[0]/assignment$1") or die("Could not move file $fp to destination $ARGV[0]/assignment$1");
    }
    elsif(! -d $fp){  #gets past here!!!
        (! -d "$ARGV[0]/misc") && (mkdir "$ARGV[0]/misc");
        move("$ARGV[0]/$fp" , "$ARGV[0]/misc") or die("Could not move file $fp to destination $ARGV[0]/misc");
    }
}

It the only directory to do it out of the ones previously made by running my program once. I am curious about why this is happening.

Do something If post has a term from a custom taxonomy

I've got a custom taxonomy "library" that has 2 terms in it: "fiction" and "novels"

I am trying to do a function depending on what term from this taxonomy my post has.

So if the post is assigned to "fiction", I need to //do something, and if the post is assigned to "novels" that I need to //do something else

At very first, I've been trying with is_tax, but that doesn't seem to work as expected:

if ( is_tax('library','fiction' ) ) {   
    //do something
  } elseif ( is_tax('library','novels' ) ) {    
    //do something else
  }

I have also tried has_term but that doesn't work for me either.

if ( has_term ('fiction','library' ) ) {    
        //do something
      } elseif ( has_term ('novels','libary' ) ) {  
        //do something else
      }

So I want to give it a go with wp_get_post_terms, but I'm not sure exactly how to execute this one.

I'm trying this:

$terms = wp_get_post_terms( $post->ID, 'library' );
foreach ( $terms as $term ) {
        if($term->name == 'fiction') {
            // do something
        }
        elseif($term->name == 'novels') {
            // do something else
        }
}

Am I missing something there? Specially this last one?

How to populate a ListView using an if statement?

Basically this is what i want to happen:

if (condition is met){
    //add string to listview to be displayed
}


if (condition is met){
    //remove string from listview and replace with a different string
}

Java if statement returns opposite

i have this code:

try {
        String mode = readFile("fullScreen" , "0");
        if(mode == "fullScreen"){
            fullScreenBox.setSelected(true);
        }else{
            fullScreenBox.setSelected(false);
            System.out.println(mode);
        }
     } catch (URISyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }

the code Reads a File with name "fullScreen" if its not exists returns "0" i set an if statement. The file inside right "fullScreen" and i have a println over there to check it and indeed i get the word "fullScreen" but the program do the nagitave action.

what should be the error.

The problem is that i'm using the readFile and also if statements with other files in the same folder and works fine.

MySQL - If query returns error

I want an if query like below.

set @i=1;
set @j=2;
if @i < @j then select * from test limit 1;
end if;

Im getting the below error,

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if @i < @j then select * from test limit 1' at line 1

Also tried this in procedure,

DELIMITER $$
DROP PROCEDURE IF EXISTS test $$
create procedure test ()
set @i=1;
set @j=2;
if @i < @j then select * from test limit 1;
end if;
END $$


ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if @i < @j then select * from test limit 1;
end if;
END' at line 1

Can anyone help me to fix this?

Shaders.metal producing Errors in Swift 4

I am fairly new to swift and have a code as follows which I want to run faster:

for a in 0 ..< max {
  for b in 0 ..< max1 {
    //Do some calculations from which variables c,d and e stem. The calculations are dependent on a and b.
  //Checking if the indices are within the bounds of array.
    if(c>-1 && c<data[0].count && d>-1 && d<data[0][0].count&& e>-1&&e<data.count) {
     array.append(UInt8(data[e][c][d])
      }
      else{
      array.append(UInt(0))
      }
   }
}

From measuring the time needed I found that if and the read from the array cost most time. However the if has the greatest impact. I already tried to use data.indices.contains which brought a little improvement but not yet enough. If I add “array.append(UInt8(0))” and “continue” inside the second for loop as the first statement, everything runs fast enough. Is there a way to speed these things up? Can’t I just catch the error which returns if one of the indices is out of bounds? In Java it is Index out of bounds and I could’ve just catched it. Concerning the data array I tried to make it into a one dimensional array which caused a lot of trouble because I was no more able to check if the indices are inside the bounds of the array.

The code above runs with the extra calculations in about 0.021 s and with the use of a ternary operator instead the if in about 0.019 s. With the use of preinitializing the array to just 0s and deleting the else statement I get an additional improvement to about 0.018 s. Totally I would need it to run in about 0.001s. Is there a way to do it?

I even tried to run it with metal in parallel which was even a little slower ...

Help would be greatly appreciated. 👍

Python repeat until a no is given? [duplicate]

This question already has an answer here:

I have this code and it works, but I want to ask the user if they want to search again and then repeat the if statement until they say no and then close it out.

f = open("daily.txt","r")
print "What name? "

while True:
    s = raw_input('>  ')
    if s in f.read():
        print "name is listed"
        break
    else: 
        print 'name is not listed'
        break


f.close()
print('n\)

raw_input("Press enter to continue....")

ggplot in an ifelse statement prints list of data instead of plot

I'm a little confused by this behavior:

test = 2
y = data.frame(a = 1:4, b = c(1, 1, 2, 3))
p = ggplot(data = y, aes(x = a, y = b)) + 
  geom_line()

ifelse(test == 2, p + labs(caption = "XXX"), p) ## prints y in a list
p + labs(caption = "XXX")                       ## prints plot

Why does the ggplot print a list only when put inside an ifelse statement?

VueJS add class depending item v-for

I would like make a table stripped green or red (boostrap). Here is the context : I receive a list from an ajax call and here is the table row :

<tr v-for="item in items" class=getStyle(item)>
<td></td>
</tr>

My list of item is :

public class Wall
{
    public String Line{ get; set; }
    public BookRetrive Type { get; set; }
}

The value of Type is a Enum (Value == 0 / 1) when he is receive by the ajax call. So if the item.type == 0, i would like to add the class "table-success" otherwise is would like to add the class "table-error".

computed: {
            getStyle(item) {
                return item.type === 0 ? "table-success" : "table-error";
            }
        }

But i can't get it, could you help me please. Thank you

Writing a program that prints N sentences

So the code is supposed to print N number of sentences. So when the user enters 1 it prints one sentence, the first one in the array, "The light is red." Problem is when user enters 2 it also gives one sentence and when user enters 4 it prints 3 and so on...

This is the code I've written.

import java.util.Scanner;

public class RedYellowGreen {

    public static void main (String []args){
    System.out.println("How many sentences would you like to print?");
    Scanner scan= new Scanner (System.in);
    int length= scan.nextInt();
    String[]sent={"The light is Red.","The light is Yellow.","The light is Green."};
    for(int i=0;i<length;i++){
        if(length>0){
           System.out.println(sent[i]);

      }

        if(i==2){
          i-=3;
    }
     length--;

}

}
}   

Using a set method in an if statement

In my program the user is supposed to be able to make a deposit. There are no errors or anything but the problem is the balance stays the same. The method works outside the if statement however.

if (selection == 'A')
    {

        System.out.println("There is currently $"+currentBalance+" in this account.");
        System.out.println("How much do you want to add?");
        name.addToBalance(input.nextInt());
        System.out.println("There is now $"+currentBalance+" in this account");


    }

If/Else statement doesn't work properly in c++

I'm a newbie programmer and I had a problem with if/else statement in my code. the first and the second conditions work pretty well, but the last "else",which is supposed to return the main input(the entered "n") without any change, returns incorrect answer. where is the problem? The code is below:

#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
if (n>3000000){
 n=n*0.9;
 cout<<n;

}//if

else if (2000000<n<3000000){
n=n*0.95;
n=n*0.97;
cout<<n;

}//if

else
cout<<n;
return 0;
}//int

bash scripting: if condition

I am passing command line arguments to a script, say a.sh.

From a.sh, I use "$@" to pass all those arguments to another bash script (user_pref.sh). In this bash file, I am trying to assign either 0 or 1 based on the parameters received from a.sh using basic if condition. But for some reason, I am not able to reason the correct value and all my variables are set to 0. I am new to bash scripting and would really appreciate any help here. I have referred different post on the site but they have not helped me resolve my issue so far.

a.sh code

#!/bin/sh

/home/postgres/viraltest_scripts/user_pref.sh "$@" &> /home/postgres/viraltest_scripts/logs/refresh_dev_sql.log

user_pref.sh Code:

#!/bin/sh
## assigning default values
a=1
b=1
c=1
if [[ $1 -eq 0 ]]
then
    a=0
fi

if [[ $2 -eq 0 ]]
then
    b=0
fi

if [[ $3 -eq 0 ]]
then
    c=0
fi

Irrespective of what I pass from a.sh, All the variables in user_pref.sh are assigned 0. Can anyone point out what am I doing wrong with the If statement? PS: I am aware of assigning a=$1 but for the purpose of my application, I have to explicitly assign 0 or 1 instead of doing a=$1.

Python Invalid Syntax on else part of method? [on hold]

I have an 'Invalid Syntax' error on the 'else' line and I have no idea why, any help would be appreciated

def isolate_tfidfs(dictionary):
    new_dict = {}
    for word in dictionary:
        for docid in dictionary[word]:
            if docid in new_dict.keys():
                new_dict[docid].append(dictionary[word][docid]
            else:
                new_dict.update(docid:[dictionary[word][docid]) 
    return new_dict

Nested nested nested IF statements in Excel

Extra       Cost_Code  Description2               Total_Estimate
357911410   09-7500    Kitchen - L1 Cabinets            930
357911435   09-7500    Kitchen - Upgrade Hardware       138
357911450   09-7500    Kitchen CountertopsBacksplash    -700
357911450   09-7600    Kitchen CountertopsBacksplash    2570
357911615   15-4000    Kitchen Single Bowl Sink         60
357911630   15-4000    Kitchen L1 Faucet Classic Stai   150

I have the above data in an excel spreadsheet. You will see how the extras numbers repeat and the cost code numbers repeat. I need a nested IF statement or a nested VLOOKUP statement that says:

if extra = # AND Cost Code = # then display Total Estimate

I'm screwing up my VLOOKUP statements and it's showing me 35711450 and 09-7500 twice instead of 35711450 and 09-7500 and on the next line 35711450 and 09-7600 , which would result in -700 and 2570

Help. THANKS!

Codition if ternary codition

I made this code in php 7.1 want to do a ternary condition and i got syntax error from this line in my code:

 ( (is_null($json['apellido_paterno']) || trim($json['apellido_paterno']==='')) ? $json['apellido_materno'] : $json['apellido_paterno']));


LasName SecondName  Result
Herrera Gonzales    Herrera
        Gonzales    Gonzales
Null    Gonzales    Gonzales

How can i make a program that reads the date(hour,minutes,seconds) then it subs it from the second date

I have a task to create a program where the user gives the Hour, Minute, Second, then he gives an other Hour,Minute,Second then the program should substract the second date from the first one.

I have been trying to not use the date format, but i cant get it to work.

The date have to be in a 24h format, and these two dates have to be in the same day. So if i write 12:59:59 then i couldnt set the second date to 12:59:58 just 13:00:00.

How to apply based on condition check in reactjs?

RepresentationType: Table RepresentationType: Chart For both the C3 charts and Table I will be getting (temp.chartDataSo.chartLibraryType == 'C3') chartLibraryType as c3 only.

else if (temp.chartDataSo && (temp.chartDataSo.chartLibraryType == 'C3')){
        result.chartLib = 'C3';
        result.columns = temp.columns || [];
        result.axis = temp.axis || {};
    }else if (temp.chartDataSo && (temp.chartDataSo.chartLibraryType == 'D3')){
        result.chartLib = 'D3';
        result.x = temp.x;
        result.chartType =  temp.chartType.toLowerCase() || '';
        result.y = temp.y || [];
        result.title = temp.chartName;
        result.chartData = temp.chartData || [];
    }
    return result;

In the below logic i need to insert if else logic based on representation Type

else if (temp.chartDataSo && (temp.chartDataSo.chartLibraryType == 'C3')){
    result.chartLib = 'C3';
    result.columns = temp.columns || [];
    result.axis = temp.axis || {};
}

I need to check the temp.chartDataSo.representationType as shown in screenshot

If the representationType is chart then i need to load

            result.chartLib = 'C3';
           result.columns = temp.columns || [];
           result.axis = temp.axis || {};

If the representationType is Table then i need to load

           result.chartLib = 'Table';
           result.columns = temp.columns || [];