mercredi 1 juin 2016

if condition best practice

I have the following:

if(A==B)
{
  //do stuff
}

if(C==B)
{
  //do stuff
}


  if(A==B)
    {
      //do stuff
    }
    else if(C==B)
    {
      //do stuff
    }

What is the difference between the two? I get the meaning of it but. I have seen programmers prefer the first one instead of the 2nd one? why?

I personally prefer the 2nd one.

Python3 If statement not changing variable

I am not quite sure how to describe this problem so i will just say what it's supposed to do and what it is actually doing.

what's supposed to happen in the below code is when i run car_name.drive()

if random.choice(EVENTS) == "gas_station":
    AT_GAS_STATION = True
    print("You are at a gas station")

and if AT_GAS_STATION is true is prints'you are at a gas station' which it does, but if i then run car_name.refuel it should execute this part:

elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == True:
        self.fuel_level = self.fuel_capacity
        print("Your fuel tank is full")

But it does not it instead executes this:

elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == False:
        print("You are not at a gas station and therfore can't fill up")

what i mean is that an idle session would look like this:

>>> from car import Car
>>> pilot = Car("honda", "pilot", 2003, 19, "blue")
>>> pilot.drive()
You are at a gas station
The car is moving
>>> pilot.refuel()
You are not at a gas station and therfore can't fill up

So i believe that the problem is it is not changing AT_GAS_STATION to False

I have tried running getattr(pilot, "self.fuel_level") to see if i had filled up but just printed the wrong message but i got this:

Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
    getattr(pilot, "self.fuel_level")
AttributeError: 'Car' object has no attribute 'self.fuel_level'

The full code:

import random

EVENTS = [
    "gas_station",
    "nothing",
    "nothing",
    "nothing",
    "nothing",
    "nothing"]
random.shuffle(EVENTS)
AT_GAS_STATION = False

class Car():
    """Your car."""

    def __init__(self, make, model, year, fuel_capacity, color=None):
        """Atributtes of your car, fuel in gallons."""
        self.color = color
        self.make = make
        self.model = model
        self.year = year
        self.fuel_capacity = fuel_capacity
        self.fuel_level = self.fuel_capacity
        if self.year < 2000:
            print("Your car is old")

    def refuel(self):
        """Fill up your gas."""

        if self.fuel_level >= self.fuel_capacity:
            print("Your tank is already full :P")
        elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == False:
            print("You are not at a gas station and therfore can't fill up")
        elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == True:
            self.fuel_level = self.fuel_capacity
            print("Your fuel tank is full")

    def drive(self):
        """Drive your car"""
        self.fuel_level = self.fuel_level -1

        if random.choice(EVENTS) == "gas_station":
            AT_GAS_STATION = True
            print("You are at a gas station")
        elif random.choice(EVENTS) != "gas_station":
            AT_GAS_STATION = False

        if self.fuel_level < 1:
            print("You need more gas")
        elif self.fuel_level <= self.fuel_capacity /2:
            print(self.fuel_level -1)
        else:
            print("The car is moving")

    def specs(self):
        """Display specs of your car"""
        print(self.color,self.year,self.make,self.model,self.fuel_capacity, "Gallons")

Hopefully i have provided enough information but if you want more just ask.

Python3 If statement not changing variable

I am not quite sure how to describe this problem so i will just say what it's supposed to do and what it is actually doing.

what's supposed to happen in the below code is when i run car_name.drive()

if random.choice(EVENTS) == "gas_station":
    AT_GAS_STATION = True
    print("You are at a gas station")

and if AT_GAS_STATION is true is prints'you are at a gas station' which it does, but if i then run car_name.refuel it should execute this part:

elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == True:
        self.fuel_level = self.fuel_capacity
        print("Your fuel tank is full")

But it does not it instead executes this:

elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == False:
        print("You are not at a gas station and therfore can't fill up")

what i mean is that an idle session would look like this:

>>> from car import Car
>>> pilot = Car("honda", "pilot", 2003, 19, "blue")
>>> pilot.drive()
You are at a gas station
The car is moving
>>> pilot.refuel()
You are not at a gas station and therfore can't fill up

So i believe that the problem is it is not changing AT_GAS_STATION to False

I have tried running getattr(pilot, "self.fuel_level") to see if i had filled up but just printed the wrong message but i got this:

Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
    getattr(pilot, "self.fuel_level")
AttributeError: 'Car' object has no attribute 'self.fuel_level'

The full code:

import random

EVENTS = [
    "gas_station",
    "nothing",
    "nothing",
    "nothing",
    "nothing",
    "nothing"]
random.shuffle(EVENTS)
AT_GAS_STATION = False

class Car():
    """Your car."""

    def __init__(self, make, model, year, fuel_capacity, color=None):
        """Atributtes of your car, fuel in gallons."""
        self.color = color
        self.make = make
        self.model = model
        self.year = year
        self.fuel_capacity = fuel_capacity
        self.fuel_level = self.fuel_capacity
        if self.year < 2000:
            print("Your car is old")

def refuel(self):
    """Fill up your gas."""

    if self.fuel_level >= self.fuel_capacity:
        print("Your tank is already full :P")
    elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == False:
        print("You are not at a gas station and therfore can't fill up")
    elif self.fuel_level < self.fuel_capacity and AT_GAS_STATION == True:
        self.fuel_level = self.fuel_capacity
        print("Your fuel tank is full")

def drive(self):
    """Drive your car"""
    self.fuel_level = self.fuel_level -1

    if random.choice(EVENTS) == "gas_station":
        AT_GAS_STATION = True
        print("You are at a gas station")
    elif random.choice(EVENTS) != "gas_station":
        AT_GAS_STATION = False

    if self.fuel_level < 1:
        print("You need more gas")
    elif self.fuel_level <= self.fuel_capacity /2:
        print(self.fuel_level -1)
    else:
        print("The car is moving")

def specs(self):
    """Display specs of your car"""
    print(self.color, self.year, self.make, self.model, self.fuel_capacity, "Gallons")

Hopefully i have provided enough information but if you want more just ask.

R code to compute missing months to an end date

I'm trying to run a web visit analysis locked to the end date of a subscription contract. Here is an example of my data in a csv file: enter image description here

I need to do the following: 1. based on the enddateM value (the month in which the contract has been renewed), I need to derive the time-to-the-end-date. to make it simple, if the enddateM is 12 (December), then Nov-14 needs to be labeled as "-1 month" (create a new column), Oct-14 as "-2 months" and so on backward. I would also like to have the values copied in the new column. so the value in the Nov-14 column should be copied in the "-1 month" column. I have NO idea of how I am supposed to do that on R, is there an easy way to do it? Thanks

If then Else Excel VBA - "End If" needed?

so I m writing a UDF in Excel vba of the kind:

function ... if ... then ... else for i... to ... equations ... next i * end function

Now I noticed, that the function seems to work just fine, however I was wondering whether I shouldnt be using an "end if" at the position of (*) in the code? If I do, I receive an error msg stating there was no if corresponding IF to that "end if" block, though!? So in general, isn't there a Need for an "end if" in if then else constructions ? Thanks in advance!

/edit: 'if ... then ... else' is a one liner. However the else block does contain multiple lines and in particular a loop...

Change ng-if statement in app.js from controller

I want to change my ng-if value "loggedIn" in index.html from my login/login.js by using this codes

$scope.doLogin = function() {
    console.log('Logging in as ', $scope.loginData.email);
  AuthService.login($scope.loginData)
    .then(function() {
        $rootScope.loggedIn = true;
        $scope.layout = 'styles';
        $state.go('app.mainReg');

        $stateParams.id = $currentUserId;
        console.log($currentUserId);
    });
};

and I have this kind of stateProvider in my app.js

.state('app', {
            url:'/',
            abstract: true,
            views:{
                'bodyLogin': {
                    templateUrl : 'views/login/body.html',
                    controller  : 'BodyController'
                },
                'bodyMain': {
                    templateUrl : 'views/main/body.html',
                    controller  : 'BodyController'
                }
            }
        })
.state('app.mainUnreg', {
            url:'home',
            views: {
                'content@app': {
                    templateUrl : 'views/login/home.html',
                    controller  : ''
                }
            }
        })
.state('app.mainReg', {
            url:':userID',
            views: {
                'header@app': {
                    templateUrl : 'views/main/header.html',
                    controller  : ''
                },
                'sidebar@app': {
                    templateUrl : 'views/main/sidebar.html',
                    controller  : ''
                },
                'middle@app': {
                    templateUrl : 'views/main/home.html',
                    controller  : ''
                },
                'footer@app': {
                    templateUrl : 'views/main/footer.html',
                    controller  : ''
                }
            },
            controller: 'MainController'
        })

and I separate each state by div

<div ng-if="!loggedIn" ui-view="bodyLogin" class="site-wrapper" ui-sref-active="app.mainUnreg"></div>

<div ng-if="loggedIn" ui-view="bodyMain" ui-sref-active="app.mainReg"></div>

but, I seems that it didn't give any effect, even I have logged in and being redirected, the statement for loggedIn didn't change, still false

I have put the files in GitHub

Does anyone have any idea where I made some mistake, so my loggedIn statement couldn't be changed?

How to fetch data and display on the list according many value must display from temporary value

I'm trying to display data from a database. I was able to do it, but I don't know how to only fetch data according the values I have. For example:

I have a value a = 5; then data to display will be : data1, data2, data3, data4, data5 (< display 5 data).

But I don't know how to do that. Any help is appreciated. Here is my code:

//Temporary Value     
final double a =  Math.floor(Double.parseDouble(transportResultA) / 10);
final double b =  Math.floor(Double.parseDouble(transportResultB)/10);
final double c =  Math.floor(Double.parseDouble(transportResultC)/10);

Fetch data code :

for (int i = 0; i < response.length() ; i++) {
                                try {
                                    JSONObject obj = response.getJSONObject(i);
                                    Exercise exercise = new Exercise();
                                    if (obj.getString("KindOf").equals(textKindOF.getText().toString()) && obj.getString("Type").equals("Cardio")) {
                                            exercise.setTipe(obj.getString("KindOf"));
                                            exercise.setJenis(obj.getString("Type"));
                                            exercise.setMainmuscle(obj.getString("Name"));
                                        exerciseList.add(exercise);

                                   }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

If I change how many data I want to fetch, I change response.length() to a data success only 5 data, but when I try to change obj.getString("Type").equals("Cardio") with other type like obj.getString("Type").equals("Strength") data didn't display. What seems to be wrong with my code?