jeudi 30 novembre 2017

Javascript conditional finish count

I have this function that is supposed to loop through these addition functions while they won't take the totals up past 100. However, the iteration stops and I need it to finish up with the hunger and danger value either being 100 or 0 depending on which. The numbers that pass through are first: (50,50) second: (0, 100). I can't seem to figure out how to change the addition/subtractions amount when the if condition is no longer met. My consoles are all displaying the last iteration before going over the conditional values.

~~~

function frodo(startingHungerValue, startingDangerValue) {

  var shv = startingHungerValue;
  var sdv = startingDangerValue;

  console.log('startingHungerValue:', shv, 'startingDANGERvalue:', sdv)



  return {
    dinnerOverFire: () => {
      if ((shv >= 0 && shv < 101) && (sdv >= 0 && sdv < 101)) {
        return {
          hunger: shv - 25,
          danger: sdv + 40
        }
      }
    },
    hidingInBush: () => {
      if ((shv >= 0 && shv < 101) && (sdv >= 0 && sdv < 101)) {
        return {
          hunger: shv + 35,
          danger: sdv - 20
        }
      } 
    }
  }
}

~~~

elseif statement with foreach loop error in laravel

I am trying to do a if else statement with a foreach loop but for some reason I am getting this error

Parse error: syntax error, unexpected 'elseif' (T_ELSEIF).

I know that this is a simple error but I can't seem to identify what is wrong here, did I do my code wrongly? Or is it something that need to be closed? (for the closing part, I have checked and I don't really see any problem with it) Can someone help me? Thanks a lot

profile.blade.php

@foreach($data as $value) 
  <tr> 
 @if($value->training_Status == 'No')
 <th><a href=""><span style="color: blue;"></span></a></th>
 @foreach($data1 as $value1)
  @elseif(($value1->blacklist == 'Yes') && ($value1->name == $value->Name))
 <th><a href=""><span style="color: red;"></span></a></th>
  @endforeach
 @else 
<th><a href=""></a></th>
 @endif 
 </tr> 
 @endforeach

Why I am getting compile time error as 'else' without 'if'. Can anyone explain me with detail

Why I am getting compile time error as 'else' without 'if'. Can anyone explain me with detail

class Test
    {
        public static void main(String[] args)
        {
            if(false)
                if(true)
                    if(false)
                    else
                        System.out.println("1");
                else
                    System.out.println("2");
            else
                System.out.println("3");
        }
    }

Programming a thermostat in Python with “if statement” logic for time scheduling

I am working on a thermostat that can be programmed to be off according to the time of day.

This is my thermostat function:

def thermostat(ac_on, acPower, temp_inside, Temp_desired):
   if temp_inside > Temp_desired:
        ac_on = True
   if temp_inside < Temp_desired:
        ac_on = False
   ac_heatflow = acPower if ac_on == True else 0
   return ac_heatflow, ac_on

Temp_desired is a set integer value, and temp_inside is the changing indoor temperature value that gets compared to Temp_desired (right now every couple of seconds) to see if the air conditioner (A/C) will be “on,” or “off.” ac_heatflow is the power usage when the A/C is on, and acPower is the A/C power value assigned outside of the function.

My issue now is that I want to now add a time component to my thermostat, where the the A/C can be programmed to be off. For example. The A/C will work normally throughout the day, but from 8:00am to 10:00am it must be off, and from 3:00pm to 5:45pm it must be off, so during these intervals ac_on = False, but outside these intervals the thermostat will revert back to the original method where it determines if the air conditioner is on/off based on the room temperature.

This is what I have been trying:

def thermostat(ac_on, acPower, temp_inside, Temp_desired, start, end, t):
    while t >= start or t <= end:
        ac_on = False 
    else:
        if temp_inside > Temp_desired + 2:
            ac_on = True
        if temp_inside < Temp_desired:
            ac_on = False
    ac_heatflow = 400 if ac_on == True else 0
    return ac_heatflow, ac_on

start is a start time of the interval, end is the interval end time and t right now is in seconds. There is a calculation of temperature every couple of seconds over a 24 hour period, so a full day is 86400 seconds. The issue with the above code is that there is no output, it seems as though Python is “hung” up on that initial while statement, so I have to stop the script. I also tried:

if t >= start or t <= end:
        ac_on = False 
else:
    if temp_inside > Temp_desired + 2:
        ac_on = True
    if temp_inside < Temp_desired:
        ac_on = False
ac_heatflow = 400 if ac_on == True else 0
return ac_heatflow, ac_on

But this sets all the values for ac_heatflow to 0.

I am unsure how to code the function so that it can be programmed to also take into account the time of day. Maybe this is a nested loop issue, or perhaps it requires a separate function that focuses on defining the time intervals and feeds those assignments into the thermostat function.

Calling a class function in an IF statment, keeps returning True

I have a class Player() with a function called use_potion(). When I am using use_potion() in an IF statement, at first it works fine. When the return value for use_potion changes, the if statement ignores the change!

Here's a section of the code:

class Player():
    def __init__(self):
        inventory = ["potion"]

    def has_potion(self):
        return any(item == "Potion" for item in self.inventory):

In another module:

from Player import Player

def available_actions():
    moves = ["go east","go west"]
    if Player().has_potion():
        moves.append("use potion")
    return moves

When I call available_actions(), it returns all three moves as it is supposed to. But when "potion" is removed from the Player().inventory, available_actions STILL returns all three moves instead of only "go east" and "go west". I have no idea why this is happening.

If a value exists in data.frame then... (R)

I have two data.frame:

A <- c("name", "city", "code")
B <- c("code", "city")

I would like to see whether each value of A$city exists in B$city and in that case to report the correspondent B$code value in a new column of A. Here is what I've done:

A$code <- ""
found <- is.element(A$city, B$city)

Then, how should I perform the if statement?

jinja for loop with multiple conditionals

I'm curious as to why this does not work :



It prints both foo and bar, while when I do :



It does not print foo as expected. How can I make it so it does not print both foo and bar?

I know I can easily do this in a separate if statement inside the for loop, but I am curious as to why the above solution does not work and how to make it work in one line.

Select dates only within a range of dates in another sheet by animal ID

I have two data sheets, one containing bird movement data at 30 minute intervals and another containing date ranges within which the birds were nesting. I am only interested in looking at the movement data within the nesting ranges (using short dates only). Here's a simplified example of the data (I have thousands of rows IRL):

Data frame 1:
Bird_ID     Date        
A           4/5/2015 
A           4/20/2015
A           4/28/2015
B           5/6/2016
B           5/30/2016
C           3/4/2014
C           3/9/2014

Data frame 2:
Bird_ID     Nest_start     Nest_end
A           4/2/2015       4/15/2015
B           5/21/2016      6/3/2016
C           4/1/2014       4/15/2014

I am looking for output like this:

Data frame 1.1:
Bird_ID     Date        Keep (0=no, 1=yes)?  
A           4/5/2015    1
A           4/20/2015   0
A           4/28/2015   0
B           5/6/2016    0
B           5/30/2016   1
C           3/4/2014    0
C           3/9/2014    0

Columns are of different lengths. I have encountered errors following the methods from other posts (but sorry if this is a repeat anyway!). Thanks in advance!

cant put if statement in loop C++

I have an assignment for school, very simple, just ordering burgers from a joint and calculating the costs. I've tried to use an if statement to make sure the user likes their order, but it keeps giving me and error, whether my variable "yesorno" is a string or a char.

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

int main() {
char yesorno;
int burgers, fries, drinks;
int i=0;
while (i=0) {
    cout<<"Aidan: 'Welcome to the Christopher Burger Joint!\nOur burgers are $4.00, fries are $2.50, and drinks are $1.50.";

    cout<<"\nHow many burgers will you be having today?";
    cin>>burgers;
    cout<<"\nHow many fries will you be having today?";
    cin>>fries;
    cout<<"\nand how many drinks for you today?";
    cin>>drinks;
    cout<<"\nSo here is your current order:\nBurgers: "<<burgers<<"\nFries: "<<fries<<"\nDrinks: "<<drinks;
    cout<<"Is this all?\nYes or No: ";
    cin>>yesorno;
    if (yesorno = "yes") {
        i=2;
    }

}
int grosstotal = (burgers*4)+(fries*2.5)+(drinks*1.5);
int tax = grosstotal*.12;
int total = tax+grosstotal;
cout<<"\nYour total before tax is $"<<grosstotal<<",\nYour tax is $"<<tax<<",\nAnd your total today is $"<<total<<".\nEnjoy!'";


return 0;
}

IF Statement Pyspark

My data looks like the following:

+----------+-------------+-------+--------------------+--------------+---+
|purch_date|  purch_class|tot_amt|       serv-provider|purch_location| id|
+----------+-------------+-------+--------------------+--------------+---+
|03/11/2017|Uncategorized| -17.53|             HOVER  |              |  0|
|02/11/2017|    Groceries| -70.05|1774 MAC'S CONVEN...|     BRAMPTON |  1|
|31/10/2017|Gasoline/Fuel|    -20|              ESSO  |              |  2|
|31/10/2017|       Travel|     -9|TORONTO PARKING A...|      TORONTO |  3|
|30/10/2017|    Groceries|  -1.84|         LONGO'S # 2|              |  4|

I am attempting to create a binary column which will be defined by the value of the tot_amt column. I would like to add this column to the above data. If tot_amt <(-50) I would like it to return 0 and if tot_amt > (-50) I would like it to return 1 in a new column.

My attempt so far:

from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf

def y(row):
    if row['tot_amt'] < (-50):
        val = 1
    else:
        val = 0
        return val

y_udf = udf(y, IntegerType())
df_7 = df_4.withColumn('Y',y_udf(df_4['tot_amt'], (df_4['purch_class'], 
(df_4['purch_date'], (df_4['serv-provider'], (df_4['purch_location'])))
display(df_7)

Error message I'm receiving:

SparkException: Job aborted due to stage failure: Task 0 in stage 67.0 failed 
1 times, most recent failure: Lost task 0.0 in stage 67.0 (TID 85, localhost, 
executor driver): org.apache.spark.api.python.PythonException: Traceback (most 
recent call last):
File "/databricks/spark/python/pyspark/worker.py", line 177, in main
process()
File "/databricks/spark/python/pyspark/worker.py", line 172, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/databricks/spark/python/pyspark/worker.py", line 104, in <lambda>
func = lambda _, it: map(mapper, it)
File "<string>", line 1, in <lambda>
File "/databricks/spark/python/pyspark/worker.py", line 71, in <lambda>
return lambda *a: f(*a)
TypeError: y() takes exactly 1 argument (2 given)

How can you use the : ? statement? [duplicate]

This question already has an answer here:

I know you can use the ":" or "?" statement to do the almost the same thing as the if method but how can I do it?

Javascript or Statement - with href [duplicate]

This question already has an answer here:

Goal: Depending on which "or" statement matches the text have a href change to the correct link.

I have a list of 250 jobs that I need to sort through and generate a top 10 list. The top 10 list is already being generated I now need to set the correct href for each job in the top 10. I'd really like to find a better way than doing literally 2,500 if statements checking each job (250 x 10 jobs to check).

My solution is an if statement which checks each rank. This works fine. However how do I determine which "rank" matched?

The $(this).attr section needs to change the correct rank's href. For example if rank4 matched entrepreneur I'd need rank4's href to change not the others. I tried to use 'this' with no luck.

Any advice? Thanks for the help!

What the variables look like: var rank2 = $('#jobRank2').html()

   if(rank1 || rank2 || rank3 || rank4 || rank5 || rank6 || rank7 || rank8 
   || rank9 || rank10 == "Entrepreneur"){
        $(this).attr("href", "/entrepreneur")
    }

Can anyone explain this?

while True:
    print ("wanna exit? type a number that not between(1-11)range")
    side1 = input("Type 1st side: ")
    side2 = input("Type 2st side: ")
    side3 = input("Type 3rd side: ")
    a= [1,11]
    if   (side1 not in a) :
            print("You exit,goodbye! ")
            break
    else:
            a = int(side1)
            b = int(side2)
            c= int(side3)
            perimeter = (a + b +c )
            print ("The perimeter of triangle is :", perimeter )

i input a number between 1 and 10 , however it outputed "you exit...." again and again

Unable to use else if in onActivityResult

For the simplicity below is my code in onActivityResult method inside fragment

  if (requestCode==ADD_ADDRESS_REQUEST_CODE){
        // do something
    }else if (requestCode==COUNTRIES_REQUEST_CODE){
        // do something
    }

But on the else if statement Android Studio says

Condition requestCode==COUNTRIES_REQUEST_CODE is always false

I have more than one results in my Fragment so I have to check them based on the request code putting else if statements the situation is as discussed above.
If I use only if statements like

if (requestCode==ADD_ADDRESS_REQUEST_CODE){
        // do something
    }
  if (requestCode==COUNTRIES_REQUEST_CODE){
        // do something
    }

The first condition is always true even if the request code for that is not yet set. ADD_ADDRESS_REQUEST_CODE would be set when a button in fragment will be pressed and the COUNTRIES_REQUEST_CODE is set on onCreateView method of the fragment. So when Fragment shows its GUI a toast is showing that is inside of first condition.

Can anybody explain a bit why is that and how can I fix it. Any effort will be appreciated.

Any way to simply this javascript function any further?

Here's the code I want to simplify further if possible (I got a whole list of ifs but this should give you a general idea of what I want):

function doc(type, name) {
    if (type === 'getid')return document.getElementById(name);
    if (type === 'getclass')return document.getElementsByClassName(name);
}

JavaScript if/else if/else statement is not working

This is my if/else if/ else statement:

var shirtWidth = 18;
var shirtLength = 33;
var shirtSleeve = 8.63;

// Small Shirts
if(shirtWidth >= 18 && shirtWidth < 20) {
        if(shirtLength >= 28 && shirtLength < 29)
        if(shirtSleeve >= 8.13 && shirtSleeve < 8.38) {
            console.log("S");
        }
}
// Medium Shirts
else if(shirtWidth >= 20 && shirtWidth < 22) {
        if(shirtLength >= 29 && shirtLength < 30)
        if(shirtSleeve >= 8.38 && shirtSleeve < 8.63) {
            console.log("M");
        }
}
// Large Shirts
else if(shirtWidth >= 22 && shirtWidth < 24) {
        if(shirtLength >= 30 && shirtLength < 31)
        if(shirtSleeve >= 8.63 && shirtSleeve < 8.88) {
            console.log("L");
        }
}
// XL Shirts
else if(shirtWidth >= 24 && shirtWidth < 26) {
        if(shirtLength >= 31 && shirtLength < 33)
        if(shirtSleeve >= 8.88 && shirtSleeve < 9.63) {
            console.log("XL");
        }
}
// 2XL Shirts
else if(shirtWidth >= 26 && shirtWidth < 28) {
        if(shirtLength >= 33 && shirtLength < 34)
        if(shirtSleeve >= 9.63 && shirtSleeve < 10.13) {
            console.log("2XL");
        }
}
// 3XL Shirts
else if(shirtWidth === 28) {
        if(shirtLength === 34)
        if(shirtSleeve === 10.13) {
            console.log("3XL");
        }
}
// Does not match any shirt sizes
else {
    console.log("N/A");
}

Everything works except when I get to the else statement at the end. It only works for numbers greater than the 3XL shirts. However, if the numbers are combination of measurements from the 6 categories, the else statement does not print. Does anyone know what I am doing wrong?

Mastermind recreation if statements stuck

I'm recreating the Mastermind game and I'm stuck on some "if" statements i am trying make it tell the user that if the color is not the same as in guess1but is the proper color is guess2 it will print "guess 1 right color wrong position"

Python V- 2.7.8

colors =  ('R','B','G','P','Y','O')
Color1 = random.choice(colors)
Color2 = random.choice(colors)
Color3 = random.choice(colors)
Color4 = random.choice(colors)
guess1 = raw_input("First Color: ") 
guess2 = raw_input("Second Color: ")
guess3 = raw_input("Third Color: ")
guess4 = raw_input("Fourth Color: ")
guesses = (guess1,guess2,guess3,guess4)
Allcolors = (Color1,Color2,Color3,Color4)

if guesses == Allcolors:
        print "All colors are correct!"
    if guesses != Allcolors:
####
        if guess1 == Color2 or Color3 or Color4:
            print "Guess 1 right color wrong position"
        if guess1 == Color1:
            print "Color 1 is correct"
####
        if guess2 == Color2:
            print "Color 2 is correct"
        if guess3 == Color3:
            print "Color 3 is correct"
        if guess4 == Color4:
            print "Color 4 is correct"

R if else statement using plyr or dplyr for multiple conditions

Here is a dataset:

> mydat
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.2
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.2 

I am trying to code; for each species and each section where obs==b2, if doy of b2 > doy of b3, then ranking=="2.4". If doy of b2 < doy of b3, then ranking=="2.2" (remains the same), so I get this result:

> mydat2
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.4
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.4 

I used the package plyr to avoid loops because I find loops difficult to understand. I know a lot of people use dplyr instead of plyr nowadays, so I'd by glad for an answer using either plyr or dplyr. Here is my clumsy try:

require (plyr)
mydat2 <- ddply(.data=mydat[mydat$obs == "b2",],
            .variables=c("species", "section"),
            function(x){
              return(data.frame(ifelse(x$doy>x$doy[x$obs=="b3"]), x$ranking=="2.4", x$ranking=="2.2"))})

I get "arguments imply differing number of rows: 0, 1" as error message, I'm not sure how to code this properly. Thank you for your help.

Add a condition to start a function in R

I have created a script that open all csv and xlsx files a directory contains. My issue appears when my directory doesn't contain one type of file. (ex : 5 csv and 0 xlsx OR 0 csv and 14 xlsx) Here is what my script looks like:

#step 1
file.list <- list.files(pattern='*.csv')
csv_df <- lapply(file.list, read.csv, header=TRUE)

#step 2
file.list <- list.files(pattern='*.xlsx')
xlsx_df <- lapply(file.list, read_excel_function)

I got an error message:

Error in do.call("rbind", xlsx_df) :
le second argument doit être une liste (the second argument must be a list)

Do you have any idea on how to add a condition that skip one step if the list.files return nothing?

PowerShell - How to tell if two objects are identical

Let's say you have two objects that are identical (meaning they have the same properties and the same values respectively).

How do you test for equality?

Example

$obj1 & $obj2 are identical

enter image description here

Here's what I've tried:

if($obj1 -eq $obj2)
{
    echo 'true'
} else {
    echo 'false'
}
# RETURNS "false"

if(Compare-Object -ReferenceObject $obj1 -DifferenceObject $obj2)
{
    echo 'true'
} else {
    echo 'false'
}
# RETURNS "false"

isset() returning nothing for NULL

I have written this php code

//check if user has active plan and search keyword is not empty
    if (!empty($request['advertisername']) && ($userSubscriptionType == env('AMEMBER_STD_PLAN_CODE') || $userSubscriptionType == env('AMEMBER_PRE_PLAN_CODE'))) {
        $advertisername = 'LOWER(post_owner) like "%' . strtolower($request["advertisername"]) . '%"';
    } else {
        //if search keyword is null, means page is loaded for first time
        if (!isset($request['advertisername'])) {
            $advertisername = "true";
        } else {//if search keyword is not null, and user has not active plan
            $response->code = 400;
            $response->msg = "Permission issues";
            $response->data = "";
            return json_encode($response);
        }
    }

Here $request['advertisername']=null coming from fronend. So this condition will be true if (!isset($request['advertisername'])) {. But unfortunately it's always going to last else block.

If i save $request['advertisername'] in a variable like this. Then this condition if (!isset($advertiserName)) { becomes true.

//check if user has active plan and search keyword is not empty
if (!empty($request['advertisername']) && ($userSubscriptionType == env('AMEMBER_STD_PLAN_CODE') || $userSubscriptionType == env('AMEMBER_PRE_PLAN_CODE'))) {
    $advertisername = 'LOWER(post_owner) like "%' . strtolower($request["advertisername"]) . '%"';
} else {
    //if search keyword is null, means page is loaded for first time
    $advertiserName=$request['advertisername'];
    if (!isset($advertiserName)) {
        $advertisername = "true";
    } else {//if search keyword is not null, and user has not active plan
        $response->code = 400;
        $response->msg = "Permission issues";
        $response->data = "";
        return json_encode($response);
    }
}

I checked the condition via var_dump(). Anyone can explain why it is happening?

Keypad 4*4 with Ardunio

Iam Using keypad 4*4 with an Ardunio Mega,I have sensors connected to the Ardunio I want to press a key from the keypad and have response in the same time,I dont want to wait till the loop continue, I want to save up to 10 numbers entered from the keypad,So is there a way to make the keypad as an interrupt for my code?

void loop() {


char key = kpd.getKey();

if (key != NO_KEY)

{

if (key == 'C') //clear the array

{

index = 0;

numbers[index] = '\0';

}

else if (key == '.')

{



numbers[index++] = '.';

numbers[index] = '\0';

}

else if (key >= '0' && key <= '9')

{

for(int z=0; z==10;z++)

{

numbers[index++] = key;

numbers[index] = '\0';
}
}

else if (key == 'A')

{

float len = atof(numbers); //conversion from string to numeric



 if(fona.callPhone(numbers)){
    Serial.println(F("RING!"));
    Serial.print(F("Phone Number: "));



Serial.println(numbers); //print out on serial monitor
}


}
else if (key == 'D')

{
 if ( fona.pickUp()) {
          Serial.println(F("Failed"));
        } 

}else if (key == '#')

{
 if ( fona.hangUp()) {
          Serial.println(F("Failed"));
        }

}}

  gas =analogRead(gasPin);
  dtostrf(gas, 4, 2,gass) ;
  Serial.println(gas);
  delay(1000); // Print value every 1 sec.

    val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
      delay(150);
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
      digitalWrite(ledPin, LOW); // turn LED OFF

      delay(300);    
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
  int ldrStatus = analogRead(ldrPin);

if (ldrStatus <=550) {

digitalWrite(led, HIGH);

Serial.println("LDR is DARK, LED is ON");

}

else {

digitalWrite(led, LOW);



}
valee = analogRead(tempPin);
float cel = (valee * 0.48828125)/2.12304; 
dtostrf(cel, 4, 2,temp) ;
Serial.print("TEMPRATURE = ");
Serial.print(cel);
Serial.print("*C");
Serial.println();
delay(1000);

Woocommerce Product Category Dependant Template IF statement

I am currently attempting to create a website that shows two different headers depending on the category of a product.

I was thinking of using an if statement, but cannot get it to work. This is my code:

    <head>
<?php get_header(); ?>
<?php get_product_category()?>
<?php if ( is_product_category ('miele')){
    get_template_part( 'template-parts/template-part' , 'miele-head' );
} 
else{
    get_template_part( 'template-parts/template-part' , 'head');
}
?>
</head>

<body>
<!-- start content container -->
<div class="row rsrc-content">

<?php //left sidebar ?>
<?php get_sidebar( 'left' ); ?>


<div class="col-md-<?php alpha_store_main_content_width(); ?> rsrc-main">
    <div class="woocommerce">
        <?php if ( get_theme_mod( 'woo-breadcrumbs', 0 ) != 0 ) : ?>
            <?php woocommerce_breadcrumb(); ?>
        <?php endif; ?>
        <?php woocommerce_content(); ?>
    </div>
</div><!-- /#content -->      

<?php //get the right sidebar ?>
<?php get_sidebar( 'right' ); ?>

</div>
<!-- end content container -->

<?php get_footer(); ?>

The product category I am trying to utilise is called miele, and there are two header template files, called 'head' and 'miele-head'

Thanks in advance!

Does a two parted condition with "and"/ && stop when one part is already false?

simplified example:

a = False
b = True

if a and b:
    #do stuff

Does python skip checking for b if a is already recognized as false because only one condition needs to be False for the whole statement to be False?

In my case i want to check an array for 3 conditions but want to stop if at least one of them is false (for a better runtime). Can i do

if a and b and c:
    #do stuff

or do i have to go the long way with

if a:
    if b:
        if c:
            return True
        else:
            return False
     else:
         return False
 else: 
     return False

or is there another way to check stuff like this?

Using IF statements in MySQL

So i have 2 tables of this format,

actual_data:

ID,ROLL_NO,ADM_DT,FEES
1,9895987650,2017-11-14,10000
2,78578686,2017-11-10,130
3,434343,2017-11-15,20

temp_data:

ID,R_NO,FS,FT
1,9895987650,9000,F1
5,9895987650,5000,F2
3,78578686,150,F3
4,123456,24141,F4

I'm trying to create a stored-procedure here,

DELIMITER $$    
CREATE PROCEDURE `myproc`()
BEGIN
SELECT a.*,b.* FROM actual_data a, temp_data b
    WHERE a.ROLL_NO = b.R_NO 
        AND 
        ((b.FS >= a.FEES AND b.FT IS NOT NULL) 
        OR 
        (b.FS < a.FEES AND b.FT IS NOT NULL)); 
END $$
DELIMITER;  

This will give me the following result:

ID,ROLL_NO,ADM_DT,FEES,ID,R_NO,FS,FT
1,9895987650,2017-11-14,10000,1,9895987650,9000,F1
1,9895987650,2017-11-14,10000,5,9895987650,5000,F2
2,78578686,2017-11-10,130,3,78578686,150,F3

Now this is where i'm getting stuck.

What i would like to do is,

IF b.FS >= a.FEES AND b.FT IS NOT NULL is TRUE, i would like to select R_NO,sum(FEES) GROUP BY R_NO HAVING sum(FEES) > 1000 ORDER BY R_NO from the above query result.

ELSE IF b.FS < a.FEES AND b.FT IS NOT NULL is TRUE, i would like to select R_NO,sum(FEES) GROUP BY R_NO HAVING sum(FEES) < 1000 ORDER BY R_NO from the above query result.

Is this possible to do through a stored-procedure? If so, could I get some suggestions as to how this can be done? I'm a newbie when it comes to MySql, so kindly help me out.

Store random number and score

I just started programming for few days. I want to ask the user different questions and if they type in the right question then I will give them a score of 5 marks for getting the question right, plus bonus marks which are given by using Random, this bonus(Random) is then added to the total score(score(5) + random) which is stored and used to add the next score of the following question and the process repeats with all the questions[5]. This is what I have done so far, but it keeps printing the same result for every question and I want to keep adding to the previous score.

        for(int n = 0; n <QArray.length; n++)
        {
        System.out.println("Question" + (n+1));
        System.out.println(QArray[n]);

            for(int m =0; m<3; m++)
            {
            String ans = scanner.nextLine();    
            Random dice = new Random(); 
            int t = dice.nextInt(9) + 1; 
            int scoremarks = 5;  
              if (ans.equalsIgnoreCase(AArray[n]))
              {
              System.out.println("That is correct!\nYour score is:" + scoremarks + "\nWith bonus your total score is:" + (scoremarks +t));
              //correct = false;
              break;
              }
              else 
              {
              System.out.println("That is incorrect!\nYou got 0 Marks\nYour score is 0!");
              }

mercredi 29 novembre 2017

How to reassign a value from one column where two other columns have the same values

Initial dataframe After values have been re-assigned

The dataset is a pandas data frame from a combination of two different datasets. df1 has the columns (Area, Efficiency, Event_x, Phase, Time_e). df2 has the columns (Time, Velocity, X, Y). They're related but sampled at different time frequencies. I've changed the time, which was in 24hrtime to be in total seconds so it's easier to match up. Essentially, the problem I'm trying to solve is: how do I re-assign the values of the df1 columns when Time and Time_e are equal. The first row is fine 47439 == 47439. The time of the second instance is 47442 but its on the row of 47439. I need to move those values down to where time is 47442 and repeat the same process for subsequent rows.

To complicate matters further, sometimes there are multiple instances at the same interval of Time_e. I'm hoping to post those beneath each other.

SQL SERVER IF THEN ELSE in Stored Procedure

I have a stored procedure that I pass an integer parameters to (@truncate). What I want is this.

if @truncate = 1
then 
 truncate some_table 
   do something else

else 
   do only the "do something else" (before the else) without truncating the table.. 

The "do something else" part of the code is quite long.. How do I do this without repeating the "do something else" code and making the SP longer than necessary?

Wrong redirect when data have been submitted using if else laravel

I am trying to get a request from the input I just got where if the request input recommendation is No or KIV, it will redirect to home if not it will redirect to another page. But the problem now is that if the recommendation I put is Yes and some other things as No, it will redirect me to home instead of another page. Can someone help me out? Thanks a lot

    public function eval(Request $request){
     $Evaluation = new evaluation;
        $personal_info = new personal_info;
        $Evaluation->recommendation = $request->input('recommendation');
        $Evaluation->training_schedule = $request->input('training_schedule');
        $Evaluation->training_date = $request->input('training_date');
        $Evaluation->PortalLogin = $request->input('PortalLogin');
        $id = $request->user_id;
        $id= personal_info::find($id);
        $id->evaluations()->save($Evaluation);

        if(($Evaluation->recommendation = $request->input('recommendation')) == 'No' || 'KIV')
            return redirect('/home');
        else{
    return redirect(url('/user/showtest/'.$id->id.'/test) );
}

Python, Program Assigning code to Random integer, and checking with user input not functioning

#test
import subprocess
import time
import random
programClass=[]
code=random.randint(100,1000)
print('This is your secret code! PLEASE WRITE THIS DOWN!')
print(code)
numRafflePeople=0

tester=1
while tester==1:
    code1=input('What is your name, phone number, and email?\n')
    print('code',code1)
    code=code
    if code==code1:
        print('Blah')
    time.sleep(5)
    tester=2
else:
    print('fail')
    tester=1

This program makes a random number, then checks to see if the inputed number is the same as the random number, however when I run the program the program does not seem to be able to identify they are the same...

The random number will be like 303 I will type 303, and the fail message will be printed, can someone please explain the error in my code?

Thanks in Advance!

TSQL IF Operator results invalid column

My objective, is to select the first available address. If there isn't a AddressCity, then I should select the AddressRegion, and if there is not a AddressRegion I should select the AddressCountry.

 IF  AddressCity IS NOT  NULL
 SELECT AddressName + ' is from ' + AddressCity
 ELSE
 IF AddressRegion IS NOT NULL
 SELECT Address+ ' is from ' + AddressRegion   
 ElSE
 IF AddressCountry IS NOT NULL
 SELECT AddressName + ' is from ' + AddressCountry
 FROM DBO.Address

When I execute it, I get Invalid column name 'AddressCity'

How to write R if statements and conditional variables?

I am trying to create a variable with conditions. For example, I want to create a new variable called SchoolLevel that equals 1 if the variable MATH is less than or equal to 1000. I want SchoolLevel to equal 2 if MATH is greater than 1000 or less than and equal to 2000. And I want SchoolLevel to equal 3 if MATH is greater than 2000.

I have tried looking on Google and tried to enter this:

if(MATH<=1000) SchooolLevel = 1

else if(1000<MATH & MATH<=2000) SchoolLevel = 2

But I get an error that says:

In if (MATH <= 1000) { :the condition has length > 1 and only the first element will be used}

Can anyone help me out? Thanks!

VBA: If statement in for loop

I seem to get a mismatch error when trying to write an if statement in a for loop.

This is the piece of code where I get the error.

Dim lastRow2 As Long
    lastRow2 = Worksheets("csvFile").Cells(Rows.Count, 1).End(xlUp).Row

Dim r As Integer
    For r = 3 To lastRow2
        If Worksheets("csvFile").Cells(r, 1) = "#N/A" Then
            Rows(r).EntireRow.Delete
        End If
    Next r

So the goal is to delete the row where in the first cell "#N/A" is entered as an value.

Hope you guys can help and loads of thanks in advance.

C++ Boolean Function Operands

So I've started working with c++ for my university classes and it's been going really well so far. There's a dilemma I'm having with a current question and I've got the basic code structure all figured out, there's just one problem with my output.

What I'm looking for e.g;

if (bool variable = true){ 

  output

else
  alternate output

I'm aware that this isn't a free debugging service place, but it would really help me in future projects as well and there aren't any bugs, it executes just fine.

My code:

#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

//function prototypes
bool calculateBox(double, double, double, double *, double *);

int main()
{
    //defining variables
    double length, width, height, volume, surfaceArea;

    cout << "Hello and welcome to the program.\nPlease enter the dimensions for the box in [cm](l w h): ";
    cin >> length >> width >> height;
    calculateBox(length, width, height, &volume, &surfaceArea);

    if (bool calculateBool = true) {
        cout << "Volume: " << volume << "cm^3" << endl << "Surface Area: " << surfaceArea << "cm^2" << endl;
    }
    else
        cout << "Error, value(s) must be greater than zero!" << endl;

    system("pause");
    return 0;
}

//functions
bool calculateBox(double length, double width, double height, double * volume, double * surfaceArea) {
    if ((length > 0) && (width > 0) && (height > 0)) {
        *surfaceArea = length * width * 6;
        *volume = length * width * height;
        return true;
    }
    else
        return false;
}

*Key, if the values do not meet the requirements, the output displays not the error message, but a strange string for surfaceArea and volume. It appears to skip over the 'else' statement.

My question - does my error lie within the return statements in the function? Or is it a logic problem with my 'if' statement in the main method?

How to set a different values to an input fields after selecting a combination of radio buttons using AND and OR selection in JQuery?

So the problem is this: I have 6 pairs of radio buttons each represents a “yes/no” statement. I have also 4 read-only input fields to which I need to assign a value (1 or 0) after the user selects a combination of radio buttons. The problem is this - there are this rules for value assignment:

1) if (question 1) OR (question 2) are “yes” -> combi(1) =1, combi(2, 3, 4)=0 (that was easy. My code works)
2) If (question 3) OR (question 4) OR (question 5) are “yes” -> combi(2) =1, combi(1,2,4)=0 (that was easy. My code works)
3) If (question 1) AND [(question 2) OR (question 3) OR (question 4)] are “yes” -> combi(3)=1, combi(1,2,4)=0 (here is the problem No 1...)
4) If (question 1) AND [(question 2) OR (question 3) OR (question 4)] AND (question 5) are “yes” -> combi(4)=1, combi(1,2,3)=0 (here is the problem No 2...)
5) If (question 1,2,3,4,5) are „no“ -> combi(1,2,3,4)=0. (that was easy. My code works).

The problem short - I need to make a AND and OR selection in JQuery based on the selected buttons. So I here is my code. I think the third and forth “else if” are with wrong selection...

Question 1
<input id="q1a" type="radio" name="q1"> yes
<input id="q1b" type="radio" name="q1"> no
<br/>
Question 2
<input id="q2a" type="radio" name="q2"> yes
<input id="q2b" type="radio" name="q2"> no
<br/>
Question 3
<input id="q3a" type="radio" name="q3"> yes
<input id="q3b" type="radio" name="q3"> no
<br/>
Question 4 
<input id="q4a" type="radio" name="q4"> yes
<input id="q4b" type="radio" name="q4"> no
<br/>
Question 5
<input id="q5a" type="radio" name="q5"> yes
<input id="q5b" type="radio" name="q5"> no
<br/>
Question 6
<input id="q6a" type="radio" name="q6"> yes
<input id="q6b" type="radio" name="q6"> no
<br/>

<input id="combi1" type="text" readonly="true">Combi1<br/>
<input id="combi2" type="text" readonly="true">Combi1<br/>
<input id="combi3" type="text" readonly="true">Combi1<br/>
<input id="combi4" type="text" readonly="true">Combi1<br/>

JQuery 
$('input').click(function(e){
if ($('#q1a').is(':checked') ||
$('#q2a').is(':checked')){
$('#combi1').val(1) &&
$('#combi2').val(0) &&
$('#combi3').val(0) &&
$('#combi4').val(0);
}
else if ($('#q3a').is(':checked') ||
$('#q4a').is(':checked') ||
$('#q5a').is(':checked')){
$('#combi1').val(0) &&
$('#combi2').val(1) &&
$('#combi3').val(0) &&
$('#combi4').val(0);
}
else if ($('#q1a').is(':checked') &&
$('#q3a').is(':checked') ||
$('#q4a').is(':checked') ||
$('#q5a').is(':checked')){
$('#combi1').val(0) &&
$('#combi2').val(0) &&
$('#combi3').val(1) &&
$('#combi4').val(0);
}
else if ($('#q1a').is(':checked') &&
$('#q3a').is(':checked') ||
$('#q4a').is(':checked') ||
$('#q5a').is(':checked') &&
$('#q6a').is(':checked')) {
$('#combi1').val(0) &&
$('#combi2').val(0) &&
$('#combi3').val(0) &&
$('#combi4').val(1);
}
else if ($('#q1b').is(':checked') &&
$('#q2b').is(':checked') &&
$('#q3b').is(':checked') &&
$('#q4b').is(':checked') &&
$('#q5b').is(':checked')){
$('#combi1').val(0) &&
$('#combi2').val(0) &&
$('#combi3').val(0) &&
$('#combi4').val(0);
}
})

Complexity Algorithm Analysis with if

I have the following code. What time complexity does it have?
I have tried to write a recurrence relation for it but I can't understand when will the algorithm add 1 to n or divide n by 4.

void T(int n) {
  for (i = 0; i < n; i++);

  if (n == 1 || n == 0)
    return;
  else if (n%2 == 1)
    T(n + 1);
  else if (n%2 == 0)
    T(n / 4); 
}

Conditional replace and delete column

I have a dataframe like so:

replaceanddropcolumn <- data.frame("avariable"=10,
                                   "bvariable"=5,
                                   "cvariable"=2)

  avariable bvariable cvariable
1        10         5         2

I want to use the grep function to find if 'cvariable' exists in the dataframe, then replace 'cvariable' with 'bvariable', and finally delete 'cvariable' from the dataframe. So the final output would look like this:

replaceanddropcolumn[["bvariable"]] <- replaceanddropcolumn[["cvariable"]]
replaceanddropcolumn[["cvariable"]] <- NULL

  avariable bvariable
1        10         2

The reason I need the if statement is that I want to keep the original dataframe if 'cvariable' does not exist eg. I have a dataframe like this:

replaceanddropcolumn <- data.frame("avariable"=10,
                                   "bvariable"=5,
                                   "dvariable"=14)

Thanks!

Why does my If statement work in console but not during execution?

still learning how to use R, and I could use some input on why my if statement isn't being executed. I have a function that takes as one of its arguments a single character vector representing a health condition. If that condition reads "heart attack" I then want to do some stuff to a subset of my data. My if statement looks like this:

if (outcome=="heart attack"){
    Do some stuff to my data
    }

If I read and subset my data like I do in my script file, and then pretend the if condition has been satisfied and proceed on with "Do some stuff to my data" everything behaves how I expect it, but when I run the script, none of the code inside the if block gets executed and despite defining variables inside the if statement, my environment window stays empty. Any idea why this might be?

charAt not working in java fraction calculator

This code returns false even when input has an underscore. Input would be something like 1_3/4 + 3 and would return 4_3/4

  String[] Separated = fraction.split(" "); //Splits the tokens up
  String firstToken = Separated[0]; // I created this to try to troubleshoot
  boolean Mixed = true; //This would determine how much I will need to split up
  for(int i = 0; i < firstToken.length(); i++) {
     if(firstToken.charAt(i) == '_') { 
        Mixed = true;
     }
     else {
        Mixed = false;
     }
  }

how to get a single variable from orderbychild query

I'm reading some data from firebase, and I'm trying to get an event nearest to user's date.

However, what I currently have is reading through all data, by orderbychild() method which triggers bunch of functions because of displayEvent() being run each time.

How can i effectively reduce this by getting var=i into single result first, then run displayEvent(). This seems to be scope problem, and needs revision.

function searchStartDate(array,i){

            var userDate = new Date(); // for now
            var userMonth= userDate.getMonth(); // => 9
            var userHour= userDate.getHours(); // => 9
            var userMinute=userDate.getMinutes(); // =>  30


            var dbRef = firebase.database().ref("/data/")


               // Sorted According to Start Date
                 dbRef.orderByChild("calEvent,startDate").on("child_added", function(snapshot) {



                  var searchDate = new Date(snapshot.val().calEvent.startDate);

                   var searchMonth =   searchDate.getMonth(); // => 9
                    var  searchHour= searchDate.getHours(); // =>  30
                    var searchMinute=  searchDate.getMinutes(); // => 51

                    var nearestDate, nearestDiff = Infinity;
                    var diff = +searchDate - userDate;



                     if(searchDate > userDate && diff > 0 &&  diff < nearestDiff){
                              nearestDiff = diff;
                              nearestDate = Date(); 
                           var i =  snapshot.key;

                             displayEvent(i);

                              var resultDate = Date(nearestDate);
                       };




                /*  console.log('The key is: ' + snapshot.key + ' The Value is: ' + snapshot.val().calEvent.startDate);*/
                    document.getElementById("eventtime").innerHTML = resultDate;


                 });


     }

choosing data frames from within a list of data frames

I am trying to select data frames from within a long list of data frames, based on whether certain columns are empty. Here is a reproducible example, along with the code I have written to try to solve this problem:

d1 <- data.frame(a=rnorm(5), b=1:5, c=rnorm(5))
d2 <- data.frame(a=1:5, b=rnorm(5), c = c(NA, NA, NA, NA, NA))
d3 <- data.frame(a=1:5, b=c(NA, NA, NA, NA, NA), c=c(1:5))

my_test_data <- list(d1, d2, d3)
group_1 <- list()
group_2 <- list()

for (i in 1:length(my_test_data)) {
if(!is.nan(my_test_data[[i]]$b)) {
group_1[i] <- my_test_data[i]
}
else if (!is.nan(my_test_data[[i]]$c)) {
group_2[i] <- my_test_data[i]
}
else NULL
}

I get warning messages saying:

Warning messages: 1: In if (!is.nan(my_test_data[[i]]$b)) { : the condition has length > 1 and only the first element will be used

and group 1 and group 2 are identical to my_test_data

All help greatly appreciated.

Condensing if loops that are affected by outcome of previous if loops

I have a program for a pet shop. I have a nested list where each column corresponds to an animal and the numbers in the columns show the number of that animal in each cage:

cages=[[1,5,2,3],[2,1,1,5],[0,4,1,1]]

So I have a list l containing 4 variables which contain the number of each animal, calculated with sum:

    dogs=sum(i[0] for i in cages)
    hamsters=sum(i[1] for i in cages)
    cats=sum(i[2] for i in cages)
    birds=sum(i[3] for i in cages)

    l=[dogs,hamsters,cats,birds]

So the variables are equal to: dogs=3, hamsters=10, cats=4, birds=9

The scenario is that a customer wants to buy all of one type of animal, for example they want to buy all of birds or all of hamsters, but we don't know which one of the four animals they will buy. The only thing I know it that they will buy two of the animals smallest in numbers (that will be dogs and cats). I need to update the list l so the program deletes the animal from the list since the animal is not in the shop now. Here is how I did it:

smallest=[]
for animal in l:
  smallest.append(min(l))
  break

for animal in smallest:
  while len(l)>3:
    if animal==dogs:
        l=[hamsters,cats,birds]

    elif animal==hamsters:
        l=[dogs,cats,birds]

    elif animal==cats:
        l=[dogs,hamsters,birds]

    elif animal==birds:
        l=[dogs,hamsters,cats]

Then I empty smallest to find the new smallest animal:

smallest.clear()

Then I try to do the same thing for the second smallest animal:

smallest=[]
for animal in l:
    smallest.append(min(l))
    break

for animal in smallest:
    while len(l)>2:

This is where I get stuck. Since I'm not supposed to know which animal was bought at first (the numbers in cages can vary each time I run the program because the pet store sells and buys animals all the time), I don't know how to define the l now. I will now need multiple if statements for example:

if animal(deleted before)==dogs and animal(being deleted now)==cats:
  l=[hamsters,birds]

elif animal(deleted before)==dogs and animal(being deleted now)==hamsters:
  l=[cats,birds]

and so on, and if I am not mistaken I will need four times as many if statements as before. Is there a way to condense this so that I only have four if loops like in the previous bit of code?

In python using Tkinter why isn't a new window opening under this IF statement?

I am trying to make a simple GUI for an alarm using Tkinter and the sound plays when the imputed time is reached. However, it should also open a new window with a snooze button on it that when pressed waits five minutes before the sound goes off again. For some reason this new window doesn't open and the rest of the code runs without error and I just can't figure out why. Any help is greatly appreciated.

if str(Time) == str(Alarm):

        winsound.PlaySound('Alarm.wav', winsound.SND_FILENAME) #Plays alarm sound

        GoingOff = Tk()   #Should open new window, why doesn't it open???
        GoingOff.geometry('309x225')    
        GoingOff.title('Wake Up')

        label2 = Label(GoingOff, text = '\nSnooze?')
        label2.pack()

        def Snooze5():   #Code for the snooze function to be called when the button is pressed.              
            time.sleep(300)
            winsound.PlaySound('Alarm.wav', winsound.SND_FILENAME)

        Snooze5 = Button(GoingOff,font=("Helvetica", 16), text="Snooze for 5 minutes", width = 16, height = 4, command=Snooze5)
        Snooze5.pack()      



else:
        time.sleep(5)

R tribble rename columns with regular expressions

I have multiple duplicated columns in a table after several dplyr::joins. A simple version of the table looks like this:

col1 col2 col3 col4.x col4.y col5.x col5.y

I want to get to rename to:

col1 col2 col3 col4 col5

I was able to remove the .y columns with select(tablename, -matches(".y"))

Resulting in:

col1 col2 col3 col4.x col5.x

From here, I am thinking the rename_if() should work, but I am at a loss as to how to get col4.x and col5.x renamed to col4 and col5.

Any advice would be appreciated.

Function to keep cars from hitting each other, but they are not slowing down in time

This is part of a simulation of vehicles slowing down before they hit the next car, this function is called at every timeout of a timer in my main class.

The issue that I am having is that the vehicles are coming to a stop in front of the car furthest from them rather than the one closest to them. And the car at the front of the lane is stopping altogether.

The first part of the function is trying to find the smallest gap between any two cars in the same lane, and then storing which car this is. This is then used in the second part of the function.

The second part of the function, after the j loop, is the part that tells the car to either speed up or slow down depending on how close it is to the car in front.

I'm not sure why the cars are responding to the wrong ones in front?

void Road::CheckAhead()
{
    int carahead = 0;
    for(int i = 0; i < fVectorOfVehicles.size(); i++){
        for(int j = 0; j < fVectorOfVehicles.size(); j++){
            cout << j << endl;

            if(fVectorOfVehicles[i]->GetPosition().GetY() == fVectorOfVehicles[j]->GetPosition().GetY()
                    && fVectorOfVehicles[i]->GetPosition().GetX() < fVectorOfVehicles[j]->GetPosition().GetX()){
                    //Only take into account the vehicles in the same lane and the vehicles ahead


                double smallest = 1000;

                double space = fVectorOfVehicles[j]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX();
                    //Find difference between vehicle j and i

                if(space < smallest){
                        //Only done if the difference between current two vehicles is smaller than others
                    smallest = space;
                    carahead = j;
                }
                    //Find the car ahead of [i]
            }
        }

            if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() < 70.0){
                    //If vehicle is too close the one ahead, slow down
                fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() - 0.5));

                if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() < 30.0){
                    fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() - 2));
                }

                if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() < 10.0){
                    fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() - 3));
                }
                    //The closer the vehicles get, the more they break
            }

            if((fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX()) > 60.0){

                fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() + 0.1));
            }
                //If vehicle is too far from the one ahead, speed up

            if(fVectorOfVehicles[carahead]->GetPosition().GetX() - fVectorOfVehicles[i]->GetPosition().GetX() == 80.0){
                fVectorOfVehicles[i]->SetValue("Velocity", (fVectorOfVehicles[i]->GetVelocity() + 0));
            }
                //If the distance is at 30, remain at the same speed


        if(fVectorOfVehicles[i]->GetVelocity() < 0){
            fVectorOfVehicles[i]->SetValue("Velocity", 0);
        }
            //Stop the vehicles from reversing

    }

}

JavaMail message.getSubject().equals gives NullPointerException

I'm having a problem with JavaMail and I just can't understand it. I want to search trough my mailbox for a mail with a certain subject (1234 in this case). I'm getting the subject with message.getSubject() and put it in an if statement and look if it's equal to 1234, but it gives me a NullPointerException every time. The weird thing is that if I'm trying to just printout the subjects of the mails (without the if statement), nothing seems to be wrong.

This is the code:

Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);

//Get all messages from inbox
Message[] messages = inbox.getMessages();

for (int i = 0; i < messages.length; i++) {
    if (messages[i].getSubject().equals("1234")) {
         System.out.println("Message found");
    }
}

This is the error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

At the following line:

if (messages[i].getSubject().equals("1234")) {

I hope you guys can help me with this problem.

Trouble comparing index to string literal

I am iterating over an object. For debugging purposes, I'm trying to log when a certain key is hit. For some reason, the if statement below never evaluates to true.

for (let key in tiles) {
    console.log(key)
    if (tiles[key].autoload) {
        app.loadWidget(key);
        if (key === 'social') {
            console.warn("Loading social widget");  //this never gets logged
        }
    }
}

Here is the full output from the first console.log:

10:10:44.111 app.js:357 nearby
10:10:44.112 app.js:357 social   //<--- WTF
10:10:44.113 app.js:357 clock
10:10:44.114 app.js:357 calendar
10:10:44.117 app.js:357 weather
10:10:44.119 app.js:357 addwidget
10:10:44.120 app.js:357 settings
10:10:44.121 app.js:357 account
10:10:44.122 app.js:357 debug

And I tried coercing it to make sure it wasn't a type issue using if ('' + key === 'social'). I also tried ==. It didn't help.

Here is the object definition:

let tiles = {
    'store': {
        name: 'store',
        autoload: true,
        loadOrder: 1,
        /* other attributes */
        isLoaded: false,
    },
    'social': {
        name: 'social',
        autoload: false,
        loadOrder: 1,
        /* other attributes */
        isLoaded: false,
    },
    /* etc, etc */
 }

I'm sure this is something simple I'm overlooking. Why is key never equal to 'social'?

let tiles = {
  'store': {
    name: 'store',
    autoload: true,
    loadOrder: 1,
    /* other attributes */
    isLoaded: false,
  },
  'social': {
    name: 'social',
    autoload: false,
    loadOrder: 1,
    /* other attributes */
    isLoaded: false,
  },
    /* etc, etc */
 }


for (let key in tiles) {
  console.log(key)
  if (tiles[key].autoload) {
    //app.loadWidget(key);
    if ('' + key === 'social') {
      console.warn("Loading social widget");
    }
  }
}

If, else if statement not working (only displays if)

It only displays the if statement doesn't get to the 2nd or the 3rd statement would appreciate some help :) THE HTML portion only displays out the "commentE" value sorry for the poor formatting :(

        var totalAmount = (conversion * sAmount);
        totalAmount = $("#totalAmount").val(totalAmount);

        var myadvice;
        myadvice = $("#myadvice").val();

        var great;
        great = localStorage.getItem("great");


        var commentE;
        commentE = localStorage.getItem("commentE");

        var between;
        between = localStorage.getItem("between");

        var betweenb;
        betweenb = localStorage.getItem("betweenb");

        var commentB;
        commentB = localStorage.getItem("commentB");

        var less;
        less = localStorage.getItem("less");

        var commentL;
        commentL = localStorage.getItem("commentL");


if (totalAmount >= great) {
    myadvice = $("#myadvice").val(commentE);
} else if ((totalAmount >= between) && (totalAmount <= betweenb)) {
    myadvice = $("#myadvice").val(commentB);
} else if (totalAmount <= less) {
    myadvice = $("#myadvice").val(commentL);

These are the HTML portion (index page to get input)

   <div data-role="navbar">
                            <ul>
                                <li>
                                    <label for="between">Between</label>
                                    <div class="ui-grid-a">
                                        <div class="ui-block-a">
                                            <input type="text" 
  name="between" id="between" placeholder="between" value="200">
                                        </div>
                                        <div class="ui-block-b">
                                            <input type="text" 
  name="betweenb" id="betweenb" placeholder="between" value="499">
                                         </div>
                                    </div>
                                </li>
                                <li>
                                    <label for="commentB">Comment</label>
                                    <input type="text" name="commentB" 
  id="commentB" placeholder="comments" value="OK">
                                </li>

                            </ul>
                        </div>

These are supposed to be the results (results page to display the input of previous page

   <div data-role="main" class="ui-content">
    <div class="ui-field-contain">
        <div data-role="fieldcontainer">
            <label for="advice"> My Advice is as follows: </label>
            <input type="text" name="advice" id="advice">
        </div>
    </div>
 </div>

PHP: Writing an if statement for different custom heads

I am creating a database of clients. I am creating error checks in the search function so that it redirects the user back to the search page if the user doesn't exist. I create a header like this:

header("Location: search.php?search=not-found");

I then want to write an if statement on the search.php page so that if the URL has "?search=not-found" at the end, then it displays an error that the user can see by the search box. Such as (I know this isn't correct):

if(url contains ['search.php?search=not-found']){

echo 'That user doesn't exist';

} else {

echo 'Please search for a user';

}

How do I write this if statement?

Copy and Paste to different sheets specific cells based on If statement

I have a pivot table that has suppliers and the dollar amount associated with said supplier. I need to copy the supplier name and value in a given cell that exceeds 750,000 for any supplier. Then I need to paste the supplier name and value to a form in the same workbook. The form has specific cells that the supplier and values need to be entered in to. I need all suppliers over 750,000. Then I have a parts pivot table that I need to take any part that exceeds 150,000 that isn't one of the suppliers and paste that to the same form as the suppliers. I would like the suppliers first and then the parts after on the form. I need to exclude the parts that are from suppliers that are already on the form from the supplier step. for example if supplier 1 was 750,000 and had a part that was 150,000 I would exclude that part from the form. I have included an image as an example of how it should look when complete. FYI the form has merged cells but the cells I would like to past into are not merged. Thanks

Recursion - insert value at the front and at the end of list

I am having some trouble with this method. It is supposed to insert a value at the given index.

    public Element insertElementAt(int value, int index) {

    if (index == 0 || this.next == null) { 
        Element newElement = new Element();
        System.out.println("you are in the loop");
        newElement.setNext(this);
        System.out.println("you are still in the loop");
        return this;
    }
else if (this.next !=null) {
        index--;
        this.next = this.next.insertElementAt(value, index);
        return this;
    }
    if (this.next== null){
        return this; 
    }
    return this;
}

The idea is, that the method should be able to insert a value at the front, in the middle and at the end of my Element. I am still pretty new to recursion, but have managed to come this far - also why i have added System.out.println.
I am pretty sure, that I only need to change/add/delete a line or two, but I cannot figure out where. Also I am sure it is in the if-statement.

Test cases just in case:

  @Test
public void testInsertElementAt_Front() {
    Element el = createElements(0, 1, 2);
    Element result = el.insertElementAt(11, 0);
    System.out.println(result.showValues());
    assertEquals(11, result.getValue());
    assertEquals(0, result.getNext().getValue());
}

@Test
public void testInsertElementAt_Middle() {
    Element el = createElements(0, 1, 2);
    Element result = el.insertElementAt(11, 1);
    System.out.println(result.showValues());
    assertEquals(0, result.getValue());
    assertEquals(11, result.getNext().getValue());
}

@Test
public void testInsertElementAt_End() {
    Element el = createElements(0, 1);
    System.out.println(el.showValues()); 
    Element result = el.insertElementAt(11, 2);
    System.out.println(result.showValues()); 
    assertEquals(0, result.getValue());
    assertEquals(1, result.getNext().getValue());
    assertEquals(11, result.getNext().getNext().getValue());
    assertNull(result.getNext().getNext().getNext());
}

And the output:

For testInsertElementAt_Front():
junit.framework.AssertionFailedError: expected:<11> but was:<0>

For testInsertElementAt_Middle():
junit.framework.AssertionFailedError: expected:<11> but was:<1>

For testInsertElementAt_End: java.lang.NullPointerException

Any help would be appreciated

if statement checks destination link [on hold]

Is there a way to have either PHP or Javascript check the destination of a path then assign a specific html?

I'm looking for a solution similar to this


<a href="target.com" target="_blank">target</a>

<a href="nottarget.com">nottarget</a>


But I don't know how to check the button destination path.

If statement is not accepting my input

Goal: When the user enters in a color not in the list, it should default to gray. If the user chooses a color in the list that color should be used.

What is actually happening: Color is always defaulting to gray.

Plain text example 1: Choose a color: yellow, green, red, purple or gray. User: Blue. Output: Color is gray.

Plain text example 2: Choose a color: yellow, green, red, purple or gray. User: Green. Output: Color is Green.

[CmdletBinding()]
param (

[Parameter(Mandatory=$True, HelpMessage="Choose yellow, green, red, purple or gray")]
[string]$color_select

)

$colors_list = "yellow", "green", "red", "purple", "gray", "random"

if ($color_select -notcontains $colors_list) {

$color_select = "gray"

}


Write-host "The color is: $color_select"

Avoid IF statements in a Fortran DO loops

In my Fortran program I have something similar to this do loop

do i = 1,imax
    if(period) then
        call g_period()
    else
        call g()
    endif
 enddo

I have this several places and sometimes several If loops within a do loop which checks whether I should call function X or Y. What is common for all this is that period is defined in the input file, and it is unchanged during the whole run time. Is there a way to avoid the if statements - because my speed is killed by all the checking stuff? Although, I want to maintain the generic why of being able to run the program one time with period = true and other times with period=false.

C: Many if to less lines

For an exercise, I must recode the "ls" function. Currently I'm using if(strcmp to gestionate the flags but I'm wondering if there is another way to do it with less lines. Thanks in advance and there you have my code.

void my_ls(int argc, char *argv[])
{
    if(strcmp(argv[1], "-a") == 0)
        minus_a(argc, argv);
    if(strcmp(argv[1], "-d") == 0)
        minus_d(argc, argv);
    if(strcmp(argv[1], "-F") == 0)
        minus_cap_f(argc, argv);
    multi_ls(argc, argv);
}

Jquery addClass and removeClass in if else statement not working

So i have created a class with a border. called border-check. This border only needs to show when the td.k-editable-area has no value (nothing written in the textarea).

I can add a class with the first line but once i add the if else statement it breaks down and wont add the class. So im not sure if its a problem of adding the class again or wether my if else statement is not correctly stated.

$("td.k-editable-area").addClass("border-check");

if ("td.k-editable-area" == "") {
    $("td.k-editable-area").addClass("border-check");
} else {
    $("td.k-editable-area").removeClass("border-check");
}

How do I implement an IF statement into a while loop, and keep while loop running indefinitely? (Bash)

Take the following while loop I made which outputs the amount of times "string" appears in the file (file path and string ommited) every 60 seconds.

while true; do /path/to/file | grep -i "string" | wc -l; sleep 60; done

What's the best/easiest way to implement an IF statement so that, if the output gets above 100 I can send an email. I need the while loop to continue running indefinitely.

how use rangesearch and if statement

I would like to use this function in a condition if :
[idx, D]=rangesearch(X,Y,0.5)

like : if one idx is not empty, i do my condition

if idx == 1
bla bla...
end

but I have an error because I don't use "==" with cells How to make if statement with this cell ?

How can I display Product Images to Logged In Users only, with Logged Out Users seeing an alternative image?

I would like to modify my WordPress/WooCommerce website, so that my Product Images have the following conditions:

Logged in site visitors:

I would like logged in visitors, to be able to see all of the WooCommerce Product Images.

Logged out site visitors:

I would like logged out visitors, to see an alternative image. Therefore, hide the Product Image. This alternative image, will be the same for every Product.

mardi 28 novembre 2017

bash if statement gives syntax error in console, but works properly

Using a bash if statement to check if two numbers in two different arrays are equal. It seems that on the condition where the statement should evaluate to false (ie. the two numbers are not equal) then console displays a syntax error.

Code in question:

for((i=0;i<=passes256Size;i+=1));do
    if((${passes212[$i]}==${passes256[$i]})); then
        passesBoth[$i]=${passes256[$i]}     
    fi
done

Error:

./partii.sh: line 46: 102==: syntax error: operand expected (error token is "=")
./partii.sh: line 46: ==103: syntax error: operand expected (error token is "==103")

The program still runs and gives me the desired result, however I get those two errors coming up during run time. Is there any way to fix this issue?

Simple text based game using HTML and JavaScript

I am kind of new to programming and learning the basics. My knowledge in programming in JavaScript is not the best but i'm trying :)

I am trying to code a very simple, adventure like, story text based HTML/JavaScript game. I have watched tutorials and read online on how to code my game. I have a few problems that I can't seem to figure out how to fix :(

Firstly, When the message comes up on the page and I minimize or go to another page, the message disappears and I have to refresh the page. I want it so it stays fixed on the page or have it in a modal pop up box thingy but don't know how to link my code to the modal box lol.

Secondly, When the user enters door 1, I want a story for that door, whereas, when the user types in door 2, I want the story to lead onto something else etc. Hope I have made sense lol xD I didn't want to come onto here and ask for help but I can't find any solutions :(

This is what I have done so far:

<!DOCTYPE html>
<html>
<head></head>

<body>
<script>

var choice = prompt("Door 1 or Door 2");
    if (choice == "Door 1"){
        confirm("Behind Door 1 is a dragon");
}

var choice2 = prompt("Do you want to attack or run?");
    if (choice2 == "attack"){
        confirm("You have killed the dragon");
    } else {
        (choice2 == "run")
        confirm ("You have been burnt by the dragon");
}

var door = prompt ("The dragon was gaurding the treasure room, Do you wish to enter?");
    if (door == "yes"){
        confirm("You have entered the treasure room");
    } else {
        (door == "no")
        confirm ("You have left the basement without the treasure!");
}

</script>

</body>
</html>

Thank you very much for taking time to read and the help :) appreciate it all!

Checking 3 values if are the same with If Statement

I am building a Tic Tac Toe game and I am wondering if this syntax could be valid. It seems the program sometimes is running correctly and sometimes not so i would like your opinion.

If ( (spacesArray[0] &&
      spacesArray[1] &&
      spacesArray[2] == (userDraw || compDraw))){
  }

So basically i am checcking positions 0,1,2 in an Array if they have the same value ("x" OR "o"). Is this syntax correct?

Loop in a loop and If statement?

I am a beginner programming, I want to ask multiple questions using arrays and tell the user whether he got each question right or wrong, which I managed to get it running, but now how do I implement the code so that the user will only have up to 3 attempts to get a question right.

for(int n = 0; n <QArray.length; n++)
{
    System.out.println("Question" + (n+1));
    System.out.println(QArray[n]);

    String ans = scanner.nextLine();

    if (ans.equalsIgnoreCase(AArray[n]))
    {
        System.out.println("That is correct!");
    }
    else   
    {     
        System.out.println("That is incorrect!");
    }
}

if-then-else expression works but cond does not in ocaml factorial function

let cond (a,b,c) = match a with | true -> t | false -> e

let rec fact n = cond (n=0,1, n * fact (n-1))

let rec fact n = if n=0 then 1 else n * fact (n-1)

in the above code segments, the first version gives a stack overflow exception while the second one works fine. what is the difference between these two? they seem to function the same but apparently don't.

hello! I need help i cant find out how to count repeated value

there is my code ... I need to find out how many times was element inputted (repeated)

    y=[]
    while True:
       x=input("element: ")
       x=x.strip()
       y.append(x)
       for t in range(len(y)-1):
           if x==y[t]:
             del y[-1]
           print("this element has been inputted" +count+"times")
           print(y)
</code>

If statement while using scanner java

I'm trying to read the line given by the user and take it and print out the right thing. Right now, when I enter Julian, it doesn't print anything.

import java.util.Scanner;

public class fantasyFootball {

    public static void main(String[ ] args) {
        Scanner reader = new Scanner(System.in); 
        System.out.println("Enter a name: ");
        String n = reader.toString();

        if("Julian".equals(n)){ 
            System.out.println("Win and Win: You go to the Playoffs");
            System.out.println("Lose and Win: ");
            System.out.println("Lose and Win: ");
            System.out.println("Lose and Lose: ");
        }
        reader.close();
    } 
}

Dynamically constructed if statement in one string variable

I am blacking out over issue and I am convinced I am thinking too complex about this, but summarized, my issue is about this:

// imagine this variable is dynamically filled by a loop with conditions inside
var condition = varA + " == " + varB + " && " + varC + " == " + varD;

if (condition) {
    // something
}

So it doesn't check whether varA equals varB and varC equals varD as what I intended, but instead it just sees it as a string and that appears to be always true anyway. I don't want, I want to see it actually checking whether varA equals varB etc.

Is there a way to parse this statement into something that actually can be a 'legit' if condition?

Thanks!

conversion from if statements to efficient for loop based solution for INSERTION SORT in Python

I have the following code that performs an insertion sort for 4 items in a list. It works, but it uses IF statements. I am interested in the various solutions that show a)conversion (based on my code and variables) to a simpler more efficient algorithm using loops where there is repetition and b) a clear explanation as to where/why what has been implemented.

The code for the insertion sort using IF statements:

def main():
  list=[4,1,2,6]
  print("original list:",list)
  cv=list[1]
  if cv<list[0]:
    list[1]=list[0]
    list[0]=cv
    print("Compare element 1 with 0:",list)

  cv=list[2]
  if cv<list[1]:
    list[2]=list[1]
    list[1]=cv
    print("Compare element 2 with 1 & shift 1 upto 2:",list)
    if cv<list[0]:
      list[1]=list[0]
      list[0]=cv
      print("Compare element 2 with 0 and shift 0 and 1 up:",list)

  cv=list[3]
  if cv<list[2]:
    list[3]=list[2]
    list[2]=cv
    print("Compare element 3 with 2 & shift 2 upto 3:",list)
    if cv<list[1]:
      list[2]=list[1]
      list[1]=cv
      print("Compare element 3 with 1 and shift 1 and 2 up:",list) 
      if cv<list[0]:
        list[1]=list[0]
        list[0]=cv
        print("Compare element 3 with 0 and shift 0 up:",list)

main()

How does this code above translate into a for loop/loop based solution + I'd also be interested in a recursive solution, but again derived directly from this one for teaching/learning purposes.

One could start, for example, by reocgnising that each iteration is done for lengthoflist-1 times.

So:

 for i in range((len(list))-1):
    cv=list[i+1]
    etc

I get that there will be an outer loop and an inner loop. How are these best constructed, and again, a clear explanation as to how the solution is derived from this original if-based code, is what I'm after.

Why is this string comparison not working? (difflib)

This code should be printing "I am unit Alpha 07" when the user says something like "what's your name", but for some reason the if statement never returns true. Please help!

import difflib
    while True:
     talk = input("Please say something > ")
     temp = (difflib.get_close_matches(talk, ['What is your name?', 'Hello', 'peach', 'puppy'],1,0.2))
     print(temp)
     if temp == "['What is your name?']":
      print("I am unit Alpha 07")
      break
     continue

    input()

Here's a screenshot

Sorry if this is really stupid.

Scanf to dynamic array with strings

Im trying to read numbers from input to dynamic array. From input I should read numbers like this { 1, 2, 3, 4, 5, 6}

while(1){
res = scanf("%1s",c);
  if ( strcmp(c,"{") || res == 0)
  {
    printf("Bad input.\n");
    free(arr);
    return 1;
  }
    while ( 1 ){
    res=scanf(" %d%1s ",&x,c);
      if ( res == 2 && ( !strcmp(c,",") || !strcmp(c,"}") )){
        arr[cnt++]=x;
        counter++;
        if(x<0){
          printf("Bad input.\n");
          free(arr);
          return 1;
        }
        if(res != 2){
        printf("Bad input.\n");
        free(arr);
        return 2;
        }
        if(cnt >= size);{
        size +=2;
        arr=(int*)realloc(arr,size*sizeof(int));
        }
        if ( !strcmp(c,"}")){
          break;
        }
      }
      if ( res != 2 || strcmp(c,",") || strcmp(c,"}")){
        printf("Bad input. %d - %s\n",res,c);
        free(arr);
        return 3;
      }





    }
break;

} But somehow when I type {1,2,3} its still show me bad input with return 3 even when I typed , and } ... And res == 2 too and c is , too ... It only read 1 and then it stopped ... Any ideas to help ?

excel VBA if loop reading .74 as greater than .99?

So the problem is I am going through a range and if either of the cells offset to its right are greater than 99% (.99) it is to export that sheet and clear the information. For some reason it is not reading properly and from what I've seen any number higher than 50% it is exporting and clearing. I'm not sure what I have wrong but any help would be greatly appreciated!

Sub Export_loop()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim Vol As Long
Dim Wght As Long
Dim LR As Long
Dim rng As Range
Dim rCell As Range

LR = Sheets("Summary").Range("B" & Rows.Count).End(xlUp).Row

Set rng = Sheets("Summary").Range("A2:A" & LR)

LR = Range("B" & Rows.Count).End(xlUp).Row

Sheets("Summary").Range("A2").Activate

Vol = ActiveCell.Offset(0, 7).Value
Wght = ActiveCell.Offset(0, 9).Value

For Each rCell In rng

If Vol > 0.99 Or Wght > 0.99 Then

Call Save_Out
    ThisWorkbook.Sheets(ActiveCell.Value).Activate
    Range("A3:N24").Clear
    Range("R3:R24").Clear
    Range("X3:X24").Clear

ThisWorkbook.Sheets("Summary").Activate
ActiveCell.Offset(1, 0).Select
    Vol = ActiveCell.Offset(0, 7).Value
    Wght = ActiveCell.Offset(0, 9).Value

Else

ActiveCell.Offset(1, 0).Select
    Vol = ActiveCell.Offset(0, 7).Value
    Wght = ActiveCell.Offset(0, 9).Value

End If

Next rCell

MsgBox "Exports Completed"

End Sub

How incorporate random-float into a command? NETLOGO

To eat ;to kill prey and eat it
  let kill one-of prey-here in-radius smell
  ;need to code in a variable for success too
  if kill != nobody
    [ask kill [ die ]
      set energy energy + 10000]
end

At present this is my command for my turtle to eat prey when they run into them on the map. I want to add a variable so that there is a chance they don't get to eat. I know I need to use random-float 1

if random float is > .4 [what happens] 

but i do not know where to add it into my eat commands so that it works.

can someone please advise?

Proper use of ifelse with & or &&

I have a df in R that I am trying to perform calculations on within a function.

I have computed change_price, change_quant, change_profit

What I am trying to do is select the old quantity normq if change_price and change_quant are both greater than 1 and select the new quantity NormQ if change_price > 1 & change_quant <= 1

So far I have tried several methods that dont seem to work properly, including:

  inData$norm_quant <- ifelse(inData$change_price >= 1 & inData$change_quant <= 1, inData$NormQ, inData$normq)

  inData$norm_quant <- ifelse(inData$change_price >= 1 && inData$change_quant <= 1, inData$NormQ, inData$normq)

  inData$norm_quant <- ifelse(inData$change_price >= 1 | inData$change_quant <= 1, inData$NormQ, inData$normq)

Ive tried so many other ways its pointless to list them all here. Point is, how can I correctly select the desired quantity based on the logical idea that price and quantity cannot both increase (so select the old quantity if they do but keep the new price)?

I know there is another thread on this subject, but its conclusions were not helpful to me so I am reposting this question.

How do you unit test if statements in angular

I have a function that subscribes a response from the NGRX store then uses the variable provided to change a message.

How do I test that the message changes when the variable updates?

  getData() {
    this.service.getPreferences().subscribe(res => {
      this.mypreference$ = res.mypreference;
    });
    if (this.mypreference$ == false) {
      (this.mypreferenceType = 'noPreference');
    } else {
      (this.mypreferenceType = 'Preference');
    }
  }

Protractor - select checkbox if not selected

I try execute in protractor following scenario:
1. Find checkbox
2. Check if it is selected
- If yes - go further
- If not - select it and go further

For some reason isSelected() function is not working with my checkbox, but I've found some solution. Below code works correctly:

expect(checkbox.getAttribute('aria-checked')).toEqual('false')

It checks some checkbox attribute which is 'false' if not selected and 'true' if selected. (but as a string)

Now the main question. How to write an 'if / else' statement to make it works?

I tried something like that:

if (expect(checkbox.getAttribute('aria-checked')).toEqual('false')) {
 checkbox.click();
}

But it always clicks on checkbox no mater if it was selected or not. I've tried also:

if (checkbox.getAttribute('aria-checked').toEqual('false')) {
 checkbox.click();
} 

But there is an error which says "It's not a function".

Could anybody help me with that?

Check Remote File for String

I need to check a remote file for a specific string. The result of this check will provide a condition for an if statement in a local bash script:

Attempted Code:

if ssh user@ip.add.ress.here "grep -qxF "NO CAUTION FLAGS" /home/user/public_html/some/directory/here/text.file";
then
echo "Ok"
URL="http://ift.tt/2BubfJ3"
else
echo "Bad"
URL="http://ift.tt/2k6GLZr"
fi

The result is Bad when it is expected to be Ok.

What's wrong here?

Naming a condition if-value for use in if block

To limit the amount of double code instances i would like to name my variables in if statement much like you do in for loops.

My expression:

var hours = if (this.substringBefore(":").toInt() != 0) 
   {this.substringBefore(":") + "h" }
   {else ""}

I want something like:

var hours = if (MY_VAR = this.substringBefore(":").toInt() != 0) 
   { MY_VAR + "h" }
   else { "" }

I mainly write in kotlin, but I'm interested in finding other languages that does this.

why if comparison doesn't work in java

i am making a Hash Table java code. In searching function, i doing some comparison in IF statement. but it doesn't doing any comparison. It will be easy question, but i need your help :)

here's is some part of my code.


while (table[pos]!=null) {
        if (table[pos]==key) {
            System.out.println("SEARCH "+key+" at INDEX "+home);
            return;
        }
        else {pos=h(home+p(i));
        i++;
        }
    }
    System.out.println("Failed to find "+key+".");
    return;

}


it doesn't work whether table[pos] and key are the same! but i add very simple assigning variable to another one. It work! I don't know why it works. I wanna know it xD

   while (table[pos]!=null) {
        int x = table[pos];
        if (x==key) {
            System.out.println("SEARCH "+key+" at INDEX "+home);
            return;
        }
        else {pos=h(home+p(i));
        i++;
        }
    }
    System.out.println("Failed to find "+key+".");
    return;

}

AS3 - Remove object permanently after leaving and coming back to frame

I'm creating a game, in this game you need to shoot 1 of 4 boats, shooting each one will make you go into a mini game. I want to be able to shoot a boat, it take me to the mini-game and then upon completing that i want to return to the original screen but have that boat removed. My code is looking like this,

    if (root["missile" + i].hitTestObject(ship1)) {
        gotoAndPlay(4);
        removeChild(ship1);
    }
    if (root["missile" + i].hitTestObject(ship2)) {
        gotoAndPlay(5);
        removeChild(ship2);
    }
    if (root["missile" + i].hitTestObject(ship3)) {
        gotoAndPlay(6);
        removeChild(ship3);
    }
    if (root["missile" + i].hitTestObject(ship4)) {
        gotoAndPlay(7);
        removeChild(ship4);
    }

With the above code, the ship is still present when returning. Any help would be greatly appreciated.

VBA - IF statement does not work

Sometimes I wonder why I even program anymore or why I use VBA... I have following code:

Private Sub CommandButton1_Click()
    Dim bSuccess As Boolean
    bSuccess = modGenerateGRList.GenerateGRList

    bSuccess = False

    If bSuccess Then
        CommandButton1.Select
        Selection.Delete
    End If
End Sub

It keeps deleting my button. It's supposed to delete my button when the called funktion was successfull. How can If bSuccess Then or If bSuccess = True Then result to true?

I used MsgBox bSuccess one line before the if, to show me that bSuccess was false and it would still delete my button.

When I delete the line bSuccess = modGenerateGRList.GenerateGRList, my code works fine. How can the function modGenerateGRList.GenerateGRList influence my code?

Count categories changes in Excel

I have specific problem which is best described by a picture.

image of the excel sheet

There are products which fall into category of a products A, B and C. Next to it you can find quantities of which they are produced. f you want to rebuild machine from cat. A to B etc. it will cost you time (ruling is described next to it).

I need to find a way how to determine time of rebuild. I did it manually and you can see it column C. However, I wish Excel would do it automatically. Later I am using data in solver.

Does anyone know solution to my problem? Thanks in advance.

lundi 27 novembre 2017

Copy one value in if to other part

Hello I want to copy a value that I got in if so I can use it on the next part of the code how can I do that? I can't use the value of begin on the part of elapsed_secs Thank you

int temp = temp + 1;
if (temp == 1)
    clock_t begin = clock();
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
gotoxy(50, 1); printf("Tiempo: %d", elapsed_secs);

If conditions based on number of inputs fields filled

I am currently attempting to do an Advanced Search function. Currently, I have a form with 7 possible input fields. What I am trying to achieve is that as users fill in the form fields, these fields will determine the conditions set for my backend to "filter" out the data.

Hence, if a user fields in 2 fields out of the 7, these 2 inputs fields will be used as my backend's filter conditions. If another users fills in 3 input fields out of the 7, then 3 conditions, and so on. Thus, users can choose to fill in any possible combinations/number of inputs: minimum 1 and maximum 7. The conditions will only be set when the input field is filled. (Hope you guys understand where I am coming from hahaha)

Thus, I would like to ask, how do I go about approch to doing this?

Using Python to Determine time from Sunset minus 2 hours to 10 pm

I have a project I'm trying to put into Python, but am not very strong with coding.

I have an array for sunset in local solar time, and want to use that to calculate an hourly load. I am given that the load runs from 2 hours before sunset until 10pm.

I'd like to set up an if statement that says if((sunset - 2) < hour < 22): then x calculation occurs. But it doesn't want to let me do that since sunset is an array.

days = np.arange (1, 366) #days to 365
    day_no = np.repeat(days, 24)    
    declination = pv.declination(day_no)
        sunrise, sunset = pv.sun_rise_set(latitude, declination, 0) 

        print('Local Solar Time of Sunrise and Sunset (24h): ', sunrise, sunset)
        for idx,  PV_Ah in enumerate(PV_Array_Ah): 
                day_number = np.floor(idx/24)
                hour = (idx - day_number*24)
            if ((sunset-2) < hour < 22):
                load = (4*3 + 20)*.93
                answer.append(load)
            else:
                load = 0

I'll also end up using my 'load' value in a plot, load on the y-axis vs every hour of the year on the x-axis.

How would I go about setting up the if statement for this calculation? And then recording the load in an array to plot?

A market system

i have a task to do it's a market system. i was asked to write a program - stores the items and its price - reads the items that the customers want to buy and the number of each item - when the user enters zero then print the bill

and this is my code i make two structs one of them to the stored items and the another to the brought items then switch case to make the user to choose if he want to print the bill or continue then two for loops and if statement to compare between the items that had been bought and the items that in the market and print what he bought and the quantity and the price but it doesn't work. the compiler doesn't print the values that in the if statement. what is the wrong?

 #include <iostream>
    #include <conio.h>
    using namespace std;

    void main()
    {
        struct details
        {
            char name[20];
            int price;
        }item[50];
        //struct details item[50];
        struct bought
        {
            char name[20];
            int quantity;
        }boughtItem[50];
        //struct bought boughtItem[50];
        int n, i, q, v, m = 0, c = 0;
        cout << "Enter number of the stored items: \n";
        cin >> n;
        for (i = 0; i < n; i++)
        {
            cout << "Item name: \n";
            cin >> item[i].name;
            cout << "price: \n";
            cin >> item[i].price;
        }
        while (!m)
        {
            cout << "Press 0 to print the bill and 1 to continue\n";
            cin >> v;
            switch (v)
            {
            case 1:
                cout << "Item name: \n";
                cin >> boughtItem[c].name;
                cout << "The quantity: \n";
                cin >> boughtItem[c].quantity;
                c++;
                break;
            case 0:
                m=1;
                break;
            }
        }
        cout << "             *****  INVENTORY ***** \n";
        cout << "----------------------------------------------------------------- - \n";
        cout << "S.N.|    NAME           |  QUANTITY |  PRICE \n";
        cout << "----------------------------------------------------------------- - \n";
        for (i = 0; i < c; i++)
        {
            for (q = 0; q < n; q++)
            {
                if (boughtItem[i].name == item[q].name)
                {
                    cout << i + 1, boughtItem[i].name, boughtItem[i].quantity, item[q].price*boughtItem[i].quantity;
                }
            }
        }
        cout << "----------------------------------------------------------------- - \n";
        _getch();
    }

Why is my code not breaking out of my loop when its suppose to and why is stuff repeating?

I am a beginner programmer so bare with me. I am currently working on a project for my coding class, where I am tasked with writing a program to simulate a batter facing a pitcher in a baseball game for one turn at bat. I think the problem in my code is a logic error, but I'm not quite sure how to fix it. I have tried added additional while loops and if statements but nothing has worked. The code in my batter class and pitcher class work completely fine, it's just the code in my driver. Stuff sometimes breaks out of loop when it's suppose to and other times it doesn't and sometimes it repeats the same line of text when it's not suppose to. I would really appreciate some help on this. Thank you so much in advance.

Here is my code.

The first part being the batter class:

public class Batter {

private String name;

private double average;

public boolean hit(){
     int rnum = (int) (Math.random() * 100 + 1);
     average = .250 * 100;


     if (rnum <= average){
         System.out.println(name + " got a hit!");
         return true;

     }

     if (rnum > average){
         System.out.println(name + " swung and missed");

     }
     return false;
}
public String getname(){

    name = "Alex Rodriguez";
    return name;
}

Here is the pitcher class:

  public class Pitcher {
 private String name;
  private double average; 

   public boolean pitch(){
   int rnum = (int) (Math.random() * 100 + 1);
   average = .80 * 100;
   if ( rnum <= average){

       return true;

   }
   if (rnum> average){
       //int ball = 0;
       //ball++;
       System.out.println(name + " threw a ball");
   }
   return false;
    }

    public String getname(){
   name = "Phil Hughes";
   return name;
   }
   }

This is the driver program:

     public static void main(String[] args) {

       Batter batter = new Batter();
    batter.getname();
    // making the pitcher object and calling the get name method.
    Pitcher pitcher = new Pitcher();
    pitcher.getname();
    System.out.println(pitcher.getname() + " is pitching to " + batter.getname());

     while (true) {
        int ball = 0;
        int strike = 0;
        // desiding if the hit method gets called on the batter object
        if (pitcher.pitch() == false) {

            ball++;

            System.out.println("The count is " + ball + " balls " + strike + " strikes");
        }
        if (pitcher.pitch()== false && ball ==4 ){
            System.out.println("The count is " + ball + " balls " + strike + " strikes");
            System.out.println(batter.getname() + " walked.");
            break;
        }

        if (batter.hit() == false) {

            strike++;
            System.out.println("The count is " + ball + " balls " + strike + " strikes");



        }
        if (batter.hit() == false && strike == 3){
            System.out.println("The count is " + ball + " balls " + strike + " strikes");
            System.out.println(batter.getname() + " struck out.");
            break;
        }

        if (batter.hit() == true && pitcher.pitch() == true) {
                break;
            }
    }
} }

This is what I get when I run my code:

Phil Hughes is pitching to Alex Rodriguez

Alex Rodriguez got a hit!

Alex Rodriguez swung and missed

Alex Rodriguez swung and missed

Phil Hughes threw a ball

The count is 1 balls 0 strikes

Alex Rodriguez swung and missed

The count is 1 balls 1 strikes

Alex Rodriguez swung and missed

Alex Rodriguez swung and missed

Alex Rodriguez swung and missed

The count is 0 balls 1 strikes

Alex Rodriguez got a hit!

Alex Rodriguez got a hit!