mardi 31 mai 2016

AngularJS Not able to use a proper logic for calling respective API on click event

For adding & removing bookmark, I am calling respective API, If already liked class is there then on clicking, removing liked class & then calling unbookmark API, if not liked the adding liked class & calling add bookmark API... but the if else condition only going in the first condition even when It should go in the else condition.

$scope.favouriteClick = function(data, isSet) { //API calls for updating server Bookmark Data
if (angular.isUndefined($scope.favorite)) {
    $scope.favorite = [];
}
if ($rootScope.isUserLoggedIn == true) {
    var requestParam = {
        "uid": lclStorage.get('userData')[0].uid,
        "token_key": lclStorage.get('userData')[0].token_key,
        'career_id': isSet.mySql_career_id
    }

    if ($(".favorite").hasClass("liked")) {
        if ($scope.favorite.indexOf(isSet.mySql_career_id) == -1) {
            appServices.doAPIRequest(appSettings.appAPI_ci.getCareerBookmarks.careerBMData, requestParam, null, 'userData').then(function(data) {});
            $scope.favorite.push(isSet.mySql_career_id);
        } else {
            appServices.doAPIRequest(appSettings.appAPI_ci.careerUnBookmarks.careerUnBData, requestParam, null, 'userData').then(function(data) {});
            var index = $scope.favorite.indexOf(isSet.mySql_career_id);
            $scope.favorite.splice(index, 1);
        }
    } else {
        appServices.doAPIRequest(appSettings.appAPI_ci.careerUnBookmarks.careerUnBData, requestParam, null, 'userData').then(function(data) {});
        var index = $scope.favorite.indexOf(isSet.mySql_career_id);
        $scope.favorite.splice(index, 1);
    }
} else {
    $rootScope.openLogin();
    $('.favorite').removeClass('liked');
}};

vb.net how to get a value with specific condition

Thanks in advance. I searched but still don't know how to write.

[premise] I got a DataView of a Table, and filtered and sorted it.

[Table] [After filtering, the table looks like this: ↓]1

I want to get the names under different condition. I wrote like this but it seems not correct.

If dv_Table1.Select("Code1 = '11'").Rows.Count > 0 Then
   drwWork.Item("Name") = dv_Table1.Item(0).Item("Name")

ElseIf dv_Table1.Select("Code1 = 12").Rows.Count > 0 Then
   drwWork.Item("Name") = dv_Table1.Item(0).Item("Name")
      If dv_Table1.Item(0).Item("Code2") = 1 Then
         drwWork.Item("Code") = Asterisk
      Else
      End If

Else
End If

My main goal is to get the different names according to different code 1. I sorted the table by Order as well. When the record number of [ code1 = 12, for example] is more than 2, I want to get the two names in order ASC.

The [ Item(0).Item("Name") ] part maybe incorrect I want to know the correct coding.

Thank you !

Why Control not goes in Else part and Toast, if login information provide wrong?

Here i Am triying to login all code work fine except else part when i provide wrong information it should goes else part and toast in postExecute. but it does not do anything when i provide wrong password or username. please see my code why control not goes in else part? what i am missing here?

private void login(final String username, String password) {

      class LoginAsync extends AsyncTask<String, Void, String>{

            private Dialog loadingDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loadingDialog = ProgressDialog.show(Login .this, "Please wait", "Loading...");
            }

            @Override
            protected String doInBackground(String... params) {


                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.accumulate("username", params[0]);
                } catch (JSONException e4) {
                    // TODO Auto-generated catch block
                    e4.printStackTrace();
                }
                try {
                    jsonObject.accumulate("password", params[1]);
                } catch (JSONException e3) {
                    // TODO Auto-generated catch block
                    e3.printStackTrace();
                }
                try {
                    jsonObject.accumulate("deviceToken", "2324h5gj345gj3hs4g5j34g");
                } catch (JSONException e5) {
                    // TODO Auto-generated catch block
                    e5.printStackTrace();
                }
                try {
                    jsonObject.accumulate("os", "android");
                } catch (JSONException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
                try {
                    jsonObject.accumulate("key", "MEu07MgiuWgXwJOo7Oe1aHL0ayM8VvP");
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }


                // 4. convert JSONObject to JSON to String
                String dataString = jsonObject.toString();


                InputStream is = null;
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("data", dataString));
                //nameValuePairs.add(new BasicNameValuePair("password", pass));
                String result = null;

                try{
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(
                            "http://ift.tt/24qaOb1");

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();

                    is = entity.getContent();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            }




    //Here control not goes else part if  password or username invalid

            protected void onPostExecute(String result){
                String s = result.trim();
                loadingDialog.dismiss();

                    JSONObject respObject;
                    try {
                        respObject = new JSONObject(s);
                        String active = respObject.getString("status_message");



                        if(active.equalsIgnoreCase("success")){
                            Toast.makeText(getApplicationContext(), s+"Login successfull", Toast.LENGTH_LONG).show();

                            session.createLoginSession("Android Hive", "anroidhive@gmail.com");

                            Intent intent=new Intent(Login.this,Welcome.class);
                            startActivity(intent);

                            finish();

                        }else {
                            Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_LONG).show();

          //Control not come here if information provide wrong and not toast.
                        }

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }



            }


        }

        LoginAsync la = new LoginAsync();
        la.execute(username, password);


}

New to javascript: whats wrong with my mobile detection code?

Here is EVERYTHING from my .js file :

function isMobile() {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

Additionally, in my html, I have the following if else statements and included ONLY the following in my header:

<script type="text/javascript" src="function.js" ></script>

The if else in my html is as follows:

<script>
            if( isMobile.any() ){
//load small video
}else{
//load full video
}

Now, I am a beginner. Can anyone tell me what might be wrong here? This is literally all the javascript related-ANYTHING in my code. Therefore if you know javascript, it might be obvious to you that something is missing, but don't assume that I have it and simply didn't add it to the post, because I don't. Like I said, this is literally everything. Any help?

for if/elseif loop not working in R

I want to calculate the sum of the following logic below. Basically add one to numTrade whenever the element switch between 0, 1, -1, and treat consecutive elements as 0, such that (0, 1, 1, 1) is counted as 1 and (1,0,-1,1) is counted as 3.

numTrade should return total of 4, but instead it returns 3. Can someone please explain why?

numTrade<-0

numUnits<-c(0,1,0,-1,1,1,-1)

for(i in 2:length(numUnits)){
  if(numUnits[i]>0 & numUnits[i-1]<0){
    numTrade<-numTrade+1
  }
  else if(numUnits[i]<0 & numUnits[i-1]>0){
    numtrade<-numTrade+1
  }
    else if(numUnits[i]!=0 & numUnits[i-1]==0){
      numTrade<-numTrade+1
    } 
      else {
        numTrade<-numTrade+0
      }
  print(numTrade)
} 

return a value depending on condition

assuming i have the following extension method:

public static string sampleMethod(this int num) {
    return "Valid";
}

how can i terminate sampleMethod and show a messagebox if num > 25 ?

if i try the code below i receive a red underline on the sampleMethod and says not all code path returns a value

public static string sampleMethod(this int num) {
    if(num > 25) {
        MessageBox.Show("Integer must not exceed 25 !");
    } else {
        return "Valid String";
    }
}

and if i add throw new Exception("..."); under the MessageBox.Show, everything goes well but the application terminates.

how can i show the MessageBox and terminate the Method instead if the condition is not met ?

thank you

My BatchRPG is not doing to If statements correctly

@echo off
title Batch RPG V1
color 0a
setlocal enabledelayedexpansion

:menu
cls
echo Welcome Home!
timeout /t 3 >nul
cls
echo Batch RPG Game!
echo ---------------
echo.
echo 1) Begin
echo.
echo 2) Exit
echo.
set /p input=C:\

if "%input%" == "1" goto name
if "%input%" == "2" exit
goto menu

:name
cls
echo Please select a name!
echo ---------------------
echo.
set /p name=Name:
cls
echo Is "%name%" correct?
echo ------------------
echo.
echo 1) Yes
echo.
echo 2) No
echo.
set /p input=C:\
if "%input%" == "1" goto new
if "%input%" == "2" goto name
goto name

:new
cls
set hp=100
set mhp=30
set pdmg=10
set mdmg=3
set lvl=1
set pexp=0
echo Would you like to battle an enemy?
echo ----------------------------------
echo.
echo 1) Yes
echo.
echo 2) No
echo.
set /p input=C:\

if "%input%" == "1" goto encounter1
if "%input%" == "2" goto new
goto new

:new2
cls
set hp=100
set mhp=30
set pdmg=10
set mdmg=3
echo Would you like to battle an enemy?
echo ----------------------------------
echo.
echo 1) Yes
echo.
echo 2) No
echo.
set /p input=C:\

if "%input%" == "1" goto encounter1
if "%input%" == "2" goto new
goto new

:encounter1
cls
echo %name% Level: %lvl%
echo Damage: %pdmg%
echo Health: %hp%
echo.
echo Skeleton Level: 1
echo Damage: %mdmg%
echo Health: %mhp%
echo.
echo.
echo What would you like to do?
echo --------------------------
echo.
echo 1) Attack
echo.
echo 2) Run
echo.
set /p input=C:\

if "%input%" == "1" goto attack
if "%input%" == "2" goto new
if "%input%" == " " goto encounter1
goto encounter1

:attack
cls
echo You are now attacking the enemy!
echo --------------------------------
timeout /t 2 >nul
echo.
echo The enemy is now attacking you!
echo -------------------------------
echo.
timeout /t 1 >nul
set /a hp=%hp% - %mdmg%
set /a mhp=%mhp% - %pdmg%

if %hp% == leq 0 goto lose
if %mhp% == leq 0 goto win
goto encounter1

:win
echo     You Win!    
echo ----------------
echo.
set /a pexp=%pexp%+25
echo 25 EXP Awarded! You now have %pexp%!
timout /t 1 >nul
echo.
echo.
echo Returning Home!
timeout /t 5 >nul
goto new2

:lose
echo     You Lost!    
echo -----------------
timeout /t 1 >nul
echo.
echo.
echo Returning Home!
timeout /t 5 >nul
goto new

I beleive that is is somewhere near the bottom, but when you run this, it will continue the fight even though i call for it to say you win when the monster hits 0 or less health. I beleive that it is the if-statements, but i can not prove that, im a beginer, so if you could make an other adjustments to make my code more compact, that would also help :D!

program only executing first IF statement

I'm currently having an issue where my program will only execute the first if statement, where it multiplies 'w' by 3.5, even if 'w' does not meet the requirements. If I put an input of 4, the output turns into 14 (4*3.5) where it should really be 34 (4*8.5) since the weight is between 3 and 10 lbs. I'm sure the fix is simple, but I can't seem to find it!

#include <iostream>
using namespace std;

int main()
{
float w, price;
cout << "Enter weight of package : ";
cin >> w;

if (0 < w <= 1)
{
    price = 3.5 * w;
}
else if (1 < w <= 3)
{
    price = 5.5 * w;
}
else if (3 < w <= 10)
{
    price = 8.5 * w;
}
else if (10 < w <= 20)
{
    price = 10.5 * w;
}
else if (20 < w <= 30)
{
    price = 12.5 * w;
}
else if (30 < w)
{
    cout << "The package cannot be shipped" << endl;
}
else
    cout << "Invalid input" << endl;
cout << "Weight : " << w << " lbs" << endl;
cout << "Shipping cost : $" << price << endl;
}

VBA function for multiple Ifs for multiple outcomes

I'm very new to the VBA functions/anything above basic user level computers. I'm trying to create a function in excel that returns a value (there are five values that the ratings can equate to) based on its rating in six different areas(or cells). Trying to auto populate the rating of a company based on the 6 different criteria.

Example If G34 > 84.99%, J34 >79.99%, K34 ="Yes" Then "T" but If G34 < 84.99%, J34 >79.99%, and K34 ="No" Then "T-". I've been trying an ElseIf statement but keep running into issues. Help is very appreciated!!!

Below is the very elementary full function that I'm trying to get:

IF(G34>84.99%, J34>79.99%, K34="Yes", M34 >89.99%, N34 = 100%, O34>89.99%, Then "T", 
IF(G34>74.99%, G34<84.99%, J34>79.99%, K34 = "Yes", M34 >79.99%, M34 <89.99%, N34 = 100%, O34 <89.99%, O34>79.99%, Then "T-", 
IF(G34>64.99%, G34<74.99%, J34<79.99%, G34 > 74.99%, K34 = "NO", M34 >64.99%, M34 <79.99%, N34 = 100%, O34 <89.99%, O34>79.99%, Then "P", 
IF(G34>59.99%, G34<64.99%, J34<74.99%, J34 > 59.99%, K34 = "NO", M34 >49.99%, M34 <64.99%, N34 < 100%, O34 < 79.99%, Then "P-", 
IF(G34<59.99%, J34<59.99%, K34 = "NO", M34 <49.99%, N34 < 100%, O34 < 79.99%, Then "U")))))   

Python 2.7 unknown syntax error

Here is my code

hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter Rate:")
r = float(rate)

if hrs <= 40
    pay = hrs * rate
    print pay

else hrs > 40
    pay = hrs * 15.75
    print pay

Here is the error message

486406789.415.py", line 6
    if hrs <= 40
               ^
SyntaxError: invalid syntax

Multiple else if conditions true

I have multiple elsif conditions in a else if statement.

What is the flow of the statement if multiple conditions are true? So in the simplistic example below which serves as a demonstration only, is the the second elsif condition ever reached?

my $i = 1;

if ($i == 1){
}
elsif (i == 2){
}
elsif (i == 1){
}
else{
}

If (search term) found, do (action). If not, end if

If you guys could help me out, that would be great because it would really help me.

Here's what I'm trying to do:

  1. Search for a cell with a specific term
  2. If found, copy the entire row that the cell is in and paste it into a row above it.
  3. If not found, do nothing and continue with the code

Here's my code:

Sub Test()
'
' Test Macro
'
' Keyboard Shortcut: Ctrl+b
'

    Range("A5").Select
    Cells.Find(What:="PL 1", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate
    If Not IsEmpty(ActiveCell.Value) Then
        ActiveCell.Rows("1:1").EntireRow.Select
        Selection.Copy
        Range("A5").Select
        ActiveSheet.Paste
    End If
    Range("A5").Select
    Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate
    If Not IsEmpty(ActiveCell.Value) Then
        ActiveCell.Rows("1:1").EntireRow.Select
        Selection.Copy
        Range("A6").Select
        ActiveSheet.Paste
    End If
    Range("A5").Select
    Cells.Find(What:="PL 3", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate
    If Not IsEmpty(ActiveCell.Value) Then
        ActiveCell.Rows("1:1").EntireRow.Select
        Selection.Copy
        Range("A7").Select
        ActiveSheet.Paste
    End If
End Sub

My code only works if the value is found. If it's not found it runs into the error below: enter image description here

Multiple Scenarios If Statement

I have the following 9 scenarios.

Click to view image

How do I create an If statement that captures all results?

NSNumber with if statement in different situations

I know to check whether 2 NSNumbers are the same you need to use ([A isEqualToNumber:B]) instead of (A == B) unlike NSIntegers.

However, I have just realized (A == B) works just fine in simulator and I'd like to know why.

The stranger thing is that on device, (A == B) STILL WORKS as long as the numbers are below 13 and from 13 it will stop working then only ([A isEqualToNumber:B]) works but that is if they're bigger than 12 otherwise (A == B) can still be used.

Why's that??

Processing click on node as pane

first time poster here!

I'm trying to create a game that has 2 super classes, 1 for good foods and 1 for bad (even though only 1 is present). To test this, I'm printing what the mouse is selecting into the console. I'm having the issue that it is only seeing the pane and never the node. I've been stuck on this for a long time, so help would be greatly appreciated.

Code is below:

    import java.util.ArrayList;
import java.util.Random;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.ImageCursor;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;


public class DentistLearningApp extends Application {
    FlowPane root;
    Pane game;
    Scene scene;
    Factory f = new Factory();
    int count=0;
    ArrayList<Sweets> sweets = new ArrayList<Sweets>();
    //Image cur = new Image("/res/x.png");


    EventHandler<MouseEvent> eh = new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {



            event.getSceneX();
            event.getSceneY();

            Boolean correct = false;



            if(correct==true) {
                System.out.println("crash");
                correct=false;
            }

            if(event.getSource() instanceof Pane) {
                System.out.println("pane");
                return;
            }


            for(Sweets s : sweets) { 
                if(((Node) event.getSource()).getBoundsInParent().intersects(s.getBoundsInParent())) {
                correct=true;
                System.out.println("????");
                }
            }




        }

    };

     EventHandler<MouseEvent> click = new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {

        }

    };

    AnimationTimer timer = new AnimationTimer() {
        @Override
        public void handle(long arg0) {

            //scene.setCursor(new ImageCursor(cur));


            count++;
            if(count<2)
                return;
            for(Sweets invader : sweets)
                invader.move();
            count=0;

        } 
    };



    public static void main(String[] args) {
        launch(args);

    }

    @Override
    public void start(Stage stage) throws Exception {


        root = new FlowPane();

        sweets.add(f.createProduct("Nice1", 10, 10));
        sweets.add(f.createProduct("Nice2", 100, 110));
        sweets.add(f.createProduct("Nice3", 400, 210));
        sweets.add(f.createProduct("Nice4", 200, 310));

        game = new Pane();
        game.setPrefSize(800,600);
        game.setStyle("-fx-background-color: #fffff0");
        scene = new Scene(root, 800, 600);


        //game.getChildren().add(testInvader);
        game.getChildren().addAll(sweets);

        timer.start();

        /*P1 P1 = new P1(0, 0, game);

        players.add(P1);

        game.getChildren().add(P1);*/
        game.setOnMouseClicked(eh);

        stage.setScene(scene);
        stage.show();
        root.getChildren().addAll(game);

    }

}

abstract class Sweets extends ImageView {



    Sweets(String imageFile, double x, double y)
    {
        this.setX(x);
        this.setY(y);
        this.setImage(new Image(DentistLearningApp.class.getResource("res/"+imageFile).toExternalForm()));
    }
    void update() {

    }
    public abstract void move();
}

class Cake extends Sweets {

    int dx=5,dy=4;

    Cake(String imageFile, double x, double y) {
        super(imageFile, x, y);
    }


    @Override
    public void move() {
        this.setX(this.getX()+dx);

        if(this.getX()>749 || this.getX()<-20) {
            dx=-dx;
        }

        this.setY(this.getY()+dy);

        if(this.getY()>530 || this.getY()<0) {
            dy=-dy;
        }


    }

}


class Chocolate extends Sweets {

    int dx=5,dy=-2;

    Chocolate(String imageFile, double x, double y) {
        super(imageFile, x, y);
    }

    @Override
    public void move() {
        this.setX(this.getX()+dx);

        if(this.getX()>749 || this.getX()<-20) {
            dx=-dx;
        }

        this.setY(this.getY()+dy);

        if(this.getY()>530 || this.getY()<0) {
            dy=-dy;
        }

    }
}

class Donut extends Sweets {

    int dx=1,dy=3;

    Donut(String imageFile, double x, double y) {
        super(imageFile, x, y);
    }

    @Override
    public void move() {
        this.setX(this.getX()+dx);

        if(this.getX()>749 || this.getX()<-20) {
            dx=-dx;
        }

        this.setY(this.getY()+dy);

        if(this.getY()>530 || this.getY()<0) {
            dy=-dy;
        }

    }
}

class Drink extends Sweets {

    int dx=8,dy=5;

    Drink(String imageFile, double x, double y) {
        super(imageFile, x, y);
    }

    @Override
    public void move() {

        this.setX(this.getX()+dx);

        if(this.getX()>749 || this.getX()<-20) {
            dx=-dx;
        }

        this.setY(this.getY()+dy);

        if(this.getY()>530 || this.getY()<0) {
            dy=-dy;
        }

    }

}



interface SweetFactory
{
    Sweets createProduct();

}
class Factory implements SweetFactory
{
    Sweets createProduct(String discrim, double x, double y)
    {
        if(discrim.equals("Nice1"))
            return(new Cake("cake.jpg",x,y));
        else if(discrim.equals("Nice2"))
            return(new Chocolate("chocolate.jpg",x,y));
        else if(discrim.equals("Nice3"))
            return(new Donut("donut.png",x,y));
        else if(discrim.equals("Nice4"))
            return(new Drink("drink.jpg",x,y));
        else
            return(null);
    }
    @Override
    public Sweets createProduct() {
        return null;
    }

Do I Have to Specialize Templates If Their Offending Code Is in an if(false)

Given the hierarchy:

struct base {};
struct a : public base {};
struct b : public base {};

I want to fill vector<base*> vecBase and vector<a*> aVec with this function:

template <typename T>
void foo(T* bar) {
    if (is_base_of_v<decltype(baseVec)::value_type, T>) baseVec.push_back(static_cast<decltype(baseVec)::value_type>(bar));
    if (is_base_of_v<decltype(aVec)::value_type, T>) baseVec.push_back(static_cast<decltype(aVec)::value_type>(bar));
}        

The problem here is that even though the static_cast will never be performed unless it's legal; calls like these fail to compile:

int myInt;
b myB;

foo(&myInt);
foo(&myB);

I know that I can specialize foo. Is that what I have to do here, or is there a way to tip the compiler off to the fact that the offending static_casts will never happen?

Using function in if/else statement php not working

I am currently caching data returned from twitter using php and angular.

In order to prevent exceeding the API limit I am caching the data returned in my php file

<?php
require_once('twitter_proxy.php');
// Twitter OAuth Config options
$oauth_access_token = '*****';
$oauth_access_token_secret = '*****';
$consumer_key = '*****';
$consumer_secret = '*****';
$user_id = '*****';
$screen_name = 'StackOverflow';
$count = 5;
$twitter_url = 'statuses/user_timeline.json';
$twitter_url .= '?user_id=' . $user_id;
$twitter_url .= '&screen_name=' . $screen_name;
$twitter_url .= '&count=' . $count;
// Create a Twitter Proxy object from our twitter_proxy.php class
$twitter_proxy = new TwitterProxy(
    $oauth_access_token,            // 'Access token' on http://ift.tt/1oHSTpv
    $oauth_access_token_secret,     // 'Access token secret' on http://ift.tt/1oHSTpv
    $consumer_key,                  // 'API key' on http://ift.tt/1oHSTpv
    $consumer_secret,               // 'API secret' on http://ift.tt/1oHSTpv
    $user_id,                       // User id (http://ift.tt/1lBV9ME)
    $screen_name,                   // Twitter handle
    $count                          // The number of tweets to pull out
);


    //check if the file exists
    if(!file_exists('twitter_result.json')) {
        // Invoke the get method to retrieve results via a cURL request
        $tweets = $twitter_proxy->get($twitter_url);
        //create a file with timestamp containing tweets
        $data = array ('twitter_result' => $tweets, 'timestamp' => time());
        file_put_contents('twitter_result.json', json_encode($data));
    }else {
        //if file exists check it has not been updated in 10 minutes
        //if not update the tweets and timestamp
        $data = json_decode(file_get_contents('twitter_result.json'));
        if ($data->{"timestamp"} > (time() - 10 * 60)) {
            // Invoke the get method to retrieve results via a cURL request
            $tweets = $twitter_proxy->get($twitter_url);
            $data = array ('twitter_result' => $tweets, 'timestamp' => time());
            file_put_contents('twitter_result.json', json_encode($data));
        }
    }

?>

I am trying to put the following into function so I can reuse as it repeats itself in the if/else statement. However, when I put the following code in the if/else statement it doesn't work.

function checkForUpdates() {
    $tweets = $twitter_proxy->get($twitter_url);
    $data = array ('twitter_result' => $tweets, 'timestamp' => time());
    file_put_contents('twitter_result.json', json_encode($data));
}

I want the if/else statement to look something like this:

    //check if the file exists
    if(!file_exists('twitter_result.json')) {
        checkForUpdates();
    }else {
        //if file exists check it has not been updated in 10 minutes
        //if not update the tweets and timestamp
        $data = json_decode(file_get_contents('twitter_result.json'));
        if ($data->{"timestamp"} > (time() - 10 * 60)) {
            checkForUpdates();
        }
    }

How to shorten this if code java

Iam creating this converter. there's three units that can be converted,kelvin,celcius and fahrenheit. I used two variables to check which unit is chosen. it's cek and cek2. Is there any way i can shorten this code? or i just have to add all possible combination using if statements as iam doing now?

 if (cek=="celcius"&&cek2=="celcius"){
  hasil.setText(nilai.getText());
  } //celcius ke celcius

  if (cek=="celcius"&&cek2=="fahrenheit"){
  double hasil1 = (nilai1*9/5)+32;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }

  if (cek=="celcius"&&cek2=="kelvin"){
  double hasil1 = nilai1+273.15;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }

  if (cek=="fahrenheit"&&cek2=="celcius"){
  double hasil1 = (nilai1-32)*5/9;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }
  ....................................

Nested Loop not working properly in Mastermind game

I recently started coding in Java and my coach gave me an exercise where I have to re-create the Mastermind game. To give an overview of this game: the computer creates an array with X random integers, and the user gets to input X integers as well. Location matters. The users scores "Gold" if he guesses an integer that is in the same spot as the computer generated array. If the integer is present in the array, but in the wrong spot, the users gets a "Silver" score. If the integer is not present in the array at all, the user gets a "NotFound" score. The final array should give the user a score for each place in the array, e.g. (Gold, Silver, NotFound)

I have tried to make a nested loop that scores the users guesses. It captures the score in a different array (yourScore[]). User guesses are captured in array "guessednums[]" and the computer generated array is called "nums[]". The size of all arrays has been set with a variable prior to the mentioned code.

What I want the code to do is to first check whether a user's guess matches with the computer choice on the same spot, and if that is the case set the matching space in the yourScore array to "Gold". Then, if the guess does not directly match, I want a loop to check whether the user guess is present in ANY place of the computer generated nums[] array, and to score it as "Silver" if that is the case. Finally, if this is not the case, I want the yourScore[] place to be set as "NotFound".

Matching guesses are properly scored as "Gold". The problem I am encountering is that sometimes the loop will not properly score a guess as "Silver", but instead mark it as "NotFound". I suspect that this has to do with the loop not properly initialising. I have read multiple questions on Stack Overflow and other articles as well, and played around with my code, but I keep running into similar issues.

I would love to get a second opinion on the code and see what I have done wrong.

for(int i = 0; i < size;  i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
            for(int j = 0; j < size; j++){
                if (guessednums[i] == nums[i]){
                yourScore[i] = "Gold";
                } else {
                    if (guessednums[i] == nums[j]){
                        yourScore[i] = "Silver";
                    } else if (guessednums[i] != nums[j]){
                        yourScore[i] = "NotFound";
                    } 
                }
            }
        }

lundi 30 mai 2016

Java - Cleaning up lots of if statements

I'm writing a little project in Java which is similar to the 2048 game, which is pretty much solely based on array manipulation. I wrote a solution to a problem I had, and it works perfectly, however the code is incredibly messy. If anybody could please help with cleaning it up, maybe by using a different technique or something, it is just lots of if statements.

// This bit gets rid of the empty tiles between numbers.
    // Eg {2,2,0,4} becomes {2,2,4,0}.
    for(int i =1; i<row.length; i++) {

        if(row[i-1] == 0)
        {
            row[i-1] = row[i];
            row[i] = 0;
        }
    }

    for(int j=row.length-1; j>=1; j--) {
        if(row[j-1] == 0 ) {
            row[j-1] = row[j];
            row[j] = 0;
        }
    }

    int nonEmpty = 0; // Count the number of non empty tiles
    for(int i=0; i<row.length; i++) {
        if(row[i] != 0)
            nonEmpty++;
    }

    if(nonEmpty == 2) {
        if(row[1] == row[0]) {
            row[0] *= 2;
            row[1] = 0;
        }
    }
    else if(nonEmpty == 3) {
        if(row[1] == row[0]) {
            row[0] *= 2;
            row[1] = row[2];
            row[2] = 0;
        }
        else if(row[2] == row[1]) {
            row[1] *= 2;
            row[2] = 0;
        }
    }
    else if(nonEmpty==4) {
        if(row[1] == row[0]) {
            row[0] *= 2;
            row[1] = 0;

            if(row[2] == row[3]) {
                row[2] *= 2;
                row[3] = 0;
            }
        }
        else if(row[2] == row[1]) {
            row[1] *= 2;
            row[2] = row[3];
            row[3] = 0;
        }
        else if(row[3] == row[2]) {
            row[2] *= 2;
            row[3] = 0;
        }

    }

    // Get rid of 0s between numbers again.
for(int i =1; i<row.length; i++) {

        if(row[i-1] == 0)
        {
            row[i-1] = row[i];
            row[i] = 0;
        }
    }

    for(int j=row.length-1; j>=1; j--) {
        if(row[j-1] == 0 ) {
            row[j-1] = row[j];
            row[j] = 0;
        }
    }

Every if/else if statement here is crucial as it takes care of all situations. I'm not asking for somebody to go through and clean it all up, but if I could just have some pointers or examples that'd be great.

Thanks guys

IF ELSE in SQL Stored Procedure

I'm trying to accomplish the IF ELSE statement in SQL Stored Procedure but it seems that it wont follow the condition. I tried to declare an static value for me to check it but its still the same. My problem is it wont go to ELSE even if the condition is wrong

Here's the code:

ALTER PROCEDURE [dbo].[Amount_Computation]
(
@OfficeID int,
@AccountID int,
@Amount int,
@NoOfMonths int,
@Percentage int,
@isRoundOf int,
@MaxAmount int,
@EmployeeType int
)
AS
declare @TotalAmount table(TotalAmount int)
declare @Casual table(CasualSalary int, OfficeID int)
declare @Regular table(RegularSalary int, OfficeID int)
declare @basic int

BEGIN

SELECT @Amount = 1,@OfficeID = 72,@AccountID = 733, @Amount = 0, @NoOfMonths = 12, @Percentage = 1.25, @isRoundOf = 1, @MaxAmount = 35000, @EmployeeType = 1

IF(@Amount = 0)
BEGIN
    insert into @Casual SELECT CAST(((select LEFT(CONVERT(nvarchar,CAST((Case when (basic * 22 > @MaxAmount) then @MaxAmount ELSE Basic * 22 END) AS INT)),LEN(CONVERT(nvarchar,CAST((Case when (basic * 22 > @MaxAmount) then @MaxAmount ELSE Basic * 22 END) AS INT))) - 3)) + '000' ) AS INT ) * @Percentage / 100 * @NoOfMonths as Casual, a.OfficeID FROM pmis.dbo.vw_RGPermanentAndCasual as a LEFT JOIN ifmis.dbo.tbl_R_BMSOffices as b ON b.PMISOfficeID = a.OfficeID WHERE a.OfficeID = @OfficeID and a.EmploymentGroup = '2'

    insert into @Regular SELECT CAST(((select LEFT(CONVERT(nvarchar,CAST((Case when (basic > @MaxAmount) then @MaxAmount ELSE Basic END) AS INT)),LEN(CONVERT(nvarchar,CAST((Case when (basic > @MaxAmount) then @MaxAmount ELSE Basic END) AS INT))) - 3)) + '000' ) AS INT ) * @Percentage / 100 * @NoOfMonths as Regular, a.OfficeID FROM pmis.dbo.vw_RGPermanentAndCasual as a LEFT JOIN ifmis.dbo.tbl_R_BMSOffices as b ON b.PMISOfficeID = a.OfficeID WHERE a.OfficeID = @OfficeID and a.EmploymentGroup = '1'

    insert into @TotalAmount SELECT SUM(CasualSalary) + SUM(RegularSalary) FROM @Casual as a LEFT JOIN @Regular as b ON b.OfficeID = a.OfficeID
END
ELSE IF(@Amount = 1)
BEGIN
    insert into @TotalAmount SELECT SUM(CasualSalary) as ELSE_IF FROM @Casual
END

END

/**SELECT CasualSalary FROM @Casual
SELECT RegularSalary FROM @Regular **/
SELECT TotalAmount FROM @TotalAmount

Explain the output of this loop

This is a question from a past paper that I am having issues with, the question and output is displayed below but I don't understand how this is achieved. Can someone please explain.

int main ()
{
    int a[5] = { 1 }, b[] = { 3, -1, 2, 0, 4 };
    for (int i = 0; i<5; i++)
    {
        if (!(a[i] = b[i])) // note: = not ==
            break;
        cout << a[i] << endl;
    }
}

Output:

 3
-1
 2

The use of parenthesis inside an if statement

I am in the process of learning PHP development as a beginner i would like to ask question regarding the use of if with isset. Here the two code:

Is there any difference between these two pieces of code:

if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )

And:

if (isset($_GET['s']) && is_numeric($_GET['s']))

In the first part the isset() and is_numeric() are inside an additional set of parenthesis.

But in the second they reside inside the if()'s parenthesis.

Is there any difference between the first and second snippet?

Thanks in advance for any explanation and clarification.

PHP & HTML Conditional Syntax Formating Assitance

I have been struggling to make this code work as I am a novice who just started coding. The php code works fine but i would like to add some condition html formatting instead of creating another page to display element.

$fileContent =
    '<tr class="file-sort" data-name="'.strtolower($filename).'" data-date="'.date("Y-m-d", strtotime($object['LastModified'])).'>" data-size="'.$object['Size'].'">
        <td>'.$y.'</td>
        <td><img src="'.$img.'">'.$filename.'</td>
        <!--<td><a href="'.$img.'" data-lightbox="image-set" data-title="'.strtolower($filename).'" ><img src="'.$img.'"style="width:65px;height:60px;cursor:zoom-in;" class="center_image"><span style="cursor:zoom-in">'.$filename.'</span></td>-->
        <td>'.date("M j Y, g:i A", strtotime($object['LastModified'])).'</td>
        <td>'.formatBytes($object['Size'], 0).'</td>  
        <td>
            <a href="download_file.php?key='.$s3->getObjectUrl($config['s3']['bucket'], $filepath).'" download="'.$filename.'" class="btn btn-primary"><img src="img/download.png"></a>
    ';

    if ($_SESSION['crew'] == 1) echo '<a href="files.php?key=' .$filepath. '" class="btn btn-danger"><img src="img/delete.png">';

    '</td>
    <!--<td class="center">
        <div class="checkbox">
            <label>
                <input type="checkbox" name="delete[]" value="'.$filepath.'">
            </label>
        </div>
    </td>-->
</tr>';

/***********************************/

$folderContent =
    '<tr class="file-sort" data-name="'.strtolower($subDir).'" data-date="'.date("Y-m-d", strtotime($object['LastModified'])).'>" data-size="'.$object['Size'].'">
        <td>'.$y.'</td>
        <td><img src="img/folder.png" style="width:35px;height:30px;"><a href="http://' . $_SERVER['HTTP_HOST'] . $SubFolderPath . '?prefix=' . urlencode($filepath) . '" >'.$subDir.'</a></td>
        <td>-</td>
        <td>-</td>
        <td>


        </td>
     </tr>';

Cleaning up pathologically-nested "if { } else { if { } else { if { ... } } }"

I currently have the misfortune of working on Somebody Else's C# code which has truly blown my mind. I have no idea how the person before me ever maintained this code, as its various pathologies have crashed the IDE, the compiler, the runtime environment...

The problem I'm facing today involves a 15 megabyte source file that features a truly mindblowing degree of pathological nesting. Code like:

if(var == 0) {
  // do stuff
}
else {
  if(var == 1) {
    // do stuff
  }
  else {
    if(var == 2) {
      // do stuff, identical word for word to the `var == 1` case
    }
    else {
      // etc.
    }
  }
}

This is a questionable stylistic choice at the best of times. However, this combines with another pathology of the code: some of these blocks are nearly a thousand levels deep. (The deepest I bothered to measure was well over 700.) I sincerely hope the person before me, as one of their final acts before being forcibly separated from this code, ran a styling tool that resulted in the abomination before me. I cannot conceive that they could possibly have written this code as it is now, especially since every third or fourth edit to the code crashes the IDE. (And sometimes deletes my copy of the source file, as a bonus.)

I wrote a simple regex-based tool to try to condense the simpler cases, but it seems to half-process and then corrupt this particular code. (I'm not sure whether it fails because this code also uses preprocessor conditionals from time to time, or because the longest of the matches would be almost 10MB long and Lua's regular expression matcher just can't cope.) I'm hoping there's a widely-used tool or technique that can reverse this problem. I already had to use astyle to clean up some other stylistic "issues" the code had. The --remove-brackets option for astyle almost does what I want, but requires that the bracketed statement be a single statement on a single line, which is very much not the case here... (And just to cross my "t"s, I checked; astyle did not create this particular problem.)

Loop gets stuck on 1st iteration

While trying to create a web crawler, I'm trying to define this function:

#a and b are lists.
def union(a, b):
    i = 0
    for e in b:
        if b[i] not in a :
            a = a.append(b[i])   
        i = i + 1    
    return a

then testing it, I input:

a = [1,2,3]
b = [2,4,6,9]
union(a,b)

It keeps giving me the error

TypeError: argument of type 'NoneType' is not iterable

I've seen a solution for this problem in another thread by editing my condition to if a and b[i] not in a:, but while testing, that only solves it until I append 1 element of b to a, then stops working.

Why `intersect` syntax does not work in R in an `if statement`?

I know the syntax of an IF statement in R:

if (1==1){
  print("this is true")
}

And I know that the stuff between the () should be evaluated to a logical. So, when I try this:

if (intersect(list(1),list(1,2)) != list()){
  print("this is also true")
}

I expected it to work, since the intersect(list(1),list(1,2)) != list() is evaluated as a logical type:

intersect(list(1),list(1,2)) == list()

Am I doing something obviously wrong? Thanks.

python pandas dataframe index match

In a python pandas dataframe "df", I have the following three columns:

song_id | user_id | play_count

I have a rating table I invented based on play_count (how many times a user listened to a song):

play_count | rating
1-33       | 1
34-66      | 2
67-99      | 3   
100-199    | 4
>200       | 5

I am trying to add a column "rating" to this table based on play count. For example, if play_count=2, the rating will be "1".

So it looks like this

song_id | user_id | play_count | rating
X232    | u8347   | 2          | 1
X987    | u3701   | 50         | 2
X271    | u9327   | 10         | 1
X523    | u1398   | 175        | 4

In excel I would do this with match/index, but I don't know how to do it in python/pandas.

Would it be a combination of an if/else loop and isin?

3 conditions in one if statement

this programm is supposed to check if the entered year is a leap year or not. But I'm already running in errors while compiling. The formula to check if it's leap year or not is the following:

If you can divide the year by 4 it's a leap year unless you can at the same time also divide it by 100, then it's not a leap year unless you can at the same time divide it by 400 then it's a leap year.

 public class Schaltjahr {
 public static void main (String[] args) {
     double d;
     String eingabe;
     eingabe = JOptionPane.showInputDialog("Gib das Jahr ein "); //Type in the year
     d = Double.parseDouble(eingabe);
     if ((d % 4 == 0) & (d % 100 == 0) && (d % 400 = 0) ) { 
         JOptionPane.showMessageDialog(null,"Es ist ein Schaltjahr"); //It is a leap year
     } else {
         if ((d % 4 == 0) & (d % 100 == 0) )) {
              JOptionPane.showMessageDialog(null, "Es ist kein Schaltjahr"); //It is not a leap year
         }    
     } else {
         if (d % 4 == 0) {
             JOptionPane.showMessageDialog(null, "Es ist ein Schaltjahr"); // It is a leap year
         }
     }
     }
 }

While compiling i get this error:

 Schaltjahr.java:16: error: illegal start of expression
             if ((d % 4 == 0) & (d % 100 == 0) )) {
                                                ^
Schaltjahr.java:19: error: 'else' without 'if'
         } else {
           ^
2 errors

I'm a total beginner and this is an exercise from my book. I lost the CD with the Source of it.

Find value in column and change cell to left with an if statment

This VBA script should take the value in the cell A37 and check if its in the C column of another worksheet. When the number is found the column to the left should be changed to 0. If it is already 0 then a message box will inform the user and if the number does not exist another message box will inform them of this.
This is the VBA I am using to accomplish this. However, every time I try to run it there is a "compile error: Next without For"

Sub Cancelled()

Dim x As Long
Dim regRange As Range
Dim fcell As Range
x = ThisWorkbook.Sheets("Welcome").Range("A37").Value
Set regRange = ThisWorkbook.Sheets("Registration").Range("C:C")
For Each fcell In regRange.Cells
    If fcell.Value = x Then
        ActiveCell.Offset(0, -1).Select
        If ActiveCell.Value = 1 Then
            ActiveCell.Value = 0
            MsgBox "Changed to zero"
            Exit Sub
        Else
            MsgBox "That registration number is already cancelled"
            Exit Sub
    End If
Next fcell
    MsgBox "That number does not exist"

End Sub

Javascript if statement with no else statement

function checksound(volume){
if (volume > 30)
sound = ‘loud’;
if (volume > 20)
sound = ‘good’;
if (volume > 0)
sound = ‘quiet’;
else sound = ‘no sound’;
return sound;
}

If the volume was entered as 31 would it return loud? I'm not sure as there is no else statement.

(PHP) IF-ELSE two conditions at once

I'm new to PHP, now I have some problems in IF-ELSE conditions

These are my codes so far.

<?php
include('DBconnect.php');
mysql_query("USE onlinerecruitment");

$app_id_check = "";
$app_pos_check = "";

$result = mysql_query("SELECT * FROM applicant_skill ");

?>

<table style="width:100%">
<tr>

<th>Applicant's Name</th>
<th>Last Name</th>
<th>Position Selected</th>
<th></th>
<th></th>

</tr>

<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){

$check_app_id = $row['App_Data_ID'];
$check_pos_id = $row['Position_ID'];

if($app_id_check != $check_app_id  && $app_pos_check != $check_pos_id){

            $skill_id = $row['Skill_ID'];
            $app_id = $row['App_Data_ID'];

            $result01 =mysql_query("SELECT * FROM required_skills WHERE Skill_ID = '".$skill_id."' ");
            $row01 = mysql_fetch_array($result01, MYSQL_ASSOC);

            $skill_name = $row01['Skill_Name'];
            $pos_id = $row01['Position_ID'];

            $result02 = mysql_query("SELECT * FROM position WHERE Position_ID = '".$pos_id."' ");
            $row02 = mysql_fetch_array($result02, MYSQL_ASSOC);


            $result1 = mysql_query("SELECT * FROM application_data_file WHERE App_Data_ID = '".$app_id."' ");
            $row1 = mysql_fetch_array($result1, MYSQL_ASSOC);

            $app_mail = $row1['App_Email'];

            $result2 = mysql_query("SELECT * FROM applicant_acct WHERE App_Email = '".$app_mail."' ");
            $row2 = mysql_fetch_array($result2, MYSQL_ASSOC);



        echo "<TR>";

        echo "<TD>".$row2['App_Name']."</TD>";
        echo "<TD>".$row2['App_LName']."</TD>";
        echo "<TD>".$row02['Position_Name']."</TD>";
        echo "<TD><a href='edit-testing-score-form.php?app_id=".$row['App_Data_ID']."&pos_id=".$row['Position_ID']."'>Edit Testing Score</a></TD>";
        echo "<TD><a onclick='javascript:confirmationDelete($(this));return false;' href='delete-testing-score.php?app_id=".$row['App_Data_ID']."&pos_id=".$row['Position_ID']."'>Delete</a></TD>";


        echo "</TR>";

        $app_id_check = $app_id;
        $app_pos_check = $pos_id;

    }

}

?>
</table>

This is my result so far

enter image description here

And this is my data in the database

enter image description here

According to my image of my database, the result should not be 2 rows in the table like in the first table. It now prints out only App_Data_ID 00001 and 00012 only which because they are first one who has not the same Position_ID.

My intended result, the table should print App_Data_ID 00001,00002,00012,00013,00014 and so on. It should not print when only App_Data_ID and Position_ID are exactly the same.

I think my logic in IF-ELSE condition is some kind wrong but I don't know why, Please help.

C the operator "?: " how does statement calling part work? [duplicate]

This question already has an answer here:

On Maxeler machines I am not allowed to use if-else statement so instead, I can only use: condition ? first_expression : second_expression;

On this following code piece, if my condition is false, does the code first run first_expression and than run second_expression. Or does it only run second_expression?

[Q]If it runs first_statement and then second_statement, how can I for code to run only second_statement?

//condition ? first_expression : second_expression;
out[m] =  withinBounds?sum[m]: (<condition>)  ? 
stream.offset(in[m], 0)   :  calculate_sum()  ;


If I ask this question in a larger picture: If condition_1 is false, does it only run calculate_sum(input_2), without running:

(<condition_2>) ?   stream.offset(in[m], 0)   : 
                     calculate_sum(input)

Second example:

out[m] =  withinBounds?sum[m]:
                    (<condition_1>) ?
                    (<condition_2>) ?   stream.offset(in[m], 0)   : 
                     calculate_sum(input)
                    :calculate_sum(input_2);

Batch- Use if-else with forfiles recursively

I use forfiles command to check if the files from a directory have the actual date:

forfiles /p C:\copies /s /m *.bak /d 0 
if %errorlevel% == 0 (
  echo OK
) else (
  echo Non OK
  EXIT /%errorlevel%
)

But the if-else statement only works with the last file. If I use the /c parameter it works fine but I can't use the else to do other think:

/c "cmd /c echo @file is outdated." 

What is the best way to use the if-else statement with forfiles?

Correct use if != nil || != "" ROR

Redirect to city_path if @city.name not equal nil and ""

If @city.name equal "" also redirect to city_path. How to fix it?

if (@city.name != nil || @city.name != "")
      redirect_to city_path
      else
      render 'index'
    end

sum inside if statement in PHP

somebody can explain me why this code:

$a = 0.1;
$b = 0.2;

if ($a + $b == 0.3) {
    echo "OK";
} else {
    echo "KO";
}

returns KO?

I don't understand why the sum result is different the float 0.3, considering that:

var_dump($a + $b);

returns: float(0.3)

The only hypothesis I have is that the comparison is made between only $b and 0.3 but the doubt remains because also in this case:

if ( ($a + $b) == 0.3) {

I get KO..

Python: Do I have to use else statements (unless mandated by code)?

I know of if, else and elif statements and frequently see all three of them used in others' code. However, this is contradictory to the way I use them, and I would like to know which would be a better practice. The main reason I'm concerned is because I recently learned that else statements can also be used in loops, even without if statements (like, in case there's an error).

# Other's code:

select = input("Enter 'a' to add, 's' to subtract, 'x' to exit: ")
if select == "a":
    # code
elif select == "s": 
    # code
elif select == "x": 
    return
do = input("Enter 'n' to print 1 and any other key to print 2)
if do == "n":
    print(1)
    return
else:
    print("2")
    return

# My code:

select = input("Enter 'a' to add, 's' to subtract, 'x' to exit: ")
if select == "a":
    # code
if select == "s": 
    # code
if select == "x": 
    return
print("some text")
do = input("Enter 'n' to print 1 and any other key to print 2)
if do == "n":
    print(1)
    return
print("2")
return

So, does there have to be an elif or else in the last line? Cuz I don't see the point of wasting one line of code when I can just directly type under the if statement.

dimanche 29 mai 2016

Java: Refresh a JTable in a if-loop using PreparedStatement (sql)

I'm trying to make a research window that would be able to find an information in a PostgreSql database using Phone number OR name of the person I look for. My problem is that my JTable is in a If-loop ( To check if the user search with the name or the phone number ) so if the user use the window to search two different people, my code will add a new JTable below the first one instead of refreshing it.

Here is the ActionListener that cause my problem.

        class OkListener implements ActionListener {
        public void actionPerformed(ActionEvent arg0){
            try {

            String name = nameField.getText();
            String phone = phoneField.getText();
            Connection conn = CCConnection.getInstance();
            if (!phone.isEmpty() && name.isEmpty() ){


                String sqlName = "select * from creditcopie where telephone = ?";
                PreparedStatement preparedStatementName = CCConnection.getInstance().prepareStatement(sqlName, ResultSet.TYPE_SCROLL_SENSITIVE, 
                        ResultSet.CONCUR_UPDATABLE);
                preparedStatementName.setString(1, phone);
                ResultSet rs = preparedStatementName.executeQuery();
                JTable table = new JTable(buildTableModel(rs));
                container.add(new JScrollPane(table));
                container.revalidate();
                container.repaint();


            }

            else if (phone.isEmpty() && !name.isEmpty() ){
                String sqlName = "select * from creditcopie where nom = ?";
                PreparedStatement preparedStatementName = CCConnection.getInstance().prepareStatement(sqlName, ResultSet.TYPE_SCROLL_SENSITIVE, 
                        ResultSet.CONCUR_UPDATABLE);
                preparedStatementName.setString(1, name);
                ResultSet rs = preparedStatementName.executeQuery();
                JTable table = new JTable(buildTableModel(rs));
                container.add(new JScrollPane(table));
                container.revalidate();
                container.repaint();
                confirmButton.setEnabled(false);

            }

            else{
                    JOptionPane.showMessageDialog(null, "Unable to do the research", "Error! ", JOptionPane.WARNING_MESSAGE);   
            }



            } catch (SQLException e) {

                e.printStackTrace();
            }


    }

And this is the buildTableModel

            public DefaultTableModel buildTableModel(ResultSet rs)
                throws SQLException {

            ResultSetMetaData metaData = rs.getMetaData();

            // names of columns
            Vector<String> columnNames = new Vector<String>();
            int columnCount = metaData.getColumnCount();
            for (int column = 1; column <= columnCount; column++) {
                columnNames.add(metaData.getColumnName(column));
            }

            // data of the table
            Vector<Vector<Object>> data = new Vector<Vector<Object>>();
            while (rs.next()) {
                Vector<Object> vector = new Vector<Object>();
                for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                    vector.add(rs.getObject(columnIndex));
                }
                data.add(vector);
            }

            return new DefaultTableModel(data, columnNames);

        }

if/else statement based on comma count

I am loading text file contents to GUI using this code. I use String.split() method to split the line. Now by counting commas in some line I want to set them to jComboBoxes and jTextFields. I tried to use if/else statement to switch condition for jComboBoxes and jTextFields in below code. But when I used if/else for 2 cases, that is commas<4 and commas<3, I found that jComboBoxes and jTextFields are interfere each other. In case of when commas==3, jTextField1 getting the value of t1[1] except t1[2].

I would like to ask how can I write if/else for this case without interfering each other (jComboBoxes and jTextFields)?

    String[] t1 = authors.toString().split(",");

      int commas = 0;
  for(int i = 0; i < authors.toString().length(); i++) {
     if(authors.toString().charAt(i) == ',') commas++;

   if(commas<4){
     jcb1.setSelectedItem(t1[0]);

     jTextField1.setText(t1[1]);

     jTextField2.setText(t1[4]);
 }
   else if(commas<3){
     jcb1.setSelectedItem(t1[0]);

     jTextField1.setText(t1[2]);

     jTextField2.setText(t1[3]);        
 }                  
 }
      System.out.println(commas);

C++, constructing a program that reads two real numbers and a character

I am trying to write a program that is able to read two real numbers followed by a character which is inputted by the user. Then the program will evaluate the two numbers by the character. The character can be any of the ones that I have listed below:
1. + (addition)
2. - (subtraction)
3. * (multiplication)
4. / (division)
5. % (remainder)

Below I have posted a few lines of code that I have written just to check if the values printed out are correct:

#include<stdio.h>

int main(){
    int a,b;
    char op;
    printf("Enter two real numbers followed by one these characters:+, -, *, /, or % : ");
    scanf("%d%d %c",&a,&b,&op);
    printf("%d %c %d",a,b,op);

    return 0; 
}

When I run the program the output is not what I expected. unexpected output
If anyone can explain why I see different values that would be greatly appreciated.

If else statement for partial cell match VBA

This is an extended question from Partial cell match

From this question, I managed to do an if statement. But I realised that I need an else statement too.

So when I added else to the if statement. It did not work accurately.

I tried by "elseif not" but it doesn't work neither. Any idea how do I change?

Testing if double from textfield has a value or not

Trying to check if double variable obtained from textfield has a value or not

let value:Double? = Double(valueTextfield.text!)

if(value.isEmpty()) X

if(value. == nil) X

if(value == 0) X

How do I do this

Python: else ValueError: (Speicifically ValueError In This Case)

I have a question which is unrelated to my code. I'm just curious. Why is it that I (I don't know about you) can only use a ValueError with a try and except loop? for example:

print("What is 1 + 1?")
while(True):
    try:
        UserInput = int(input(("Your answer here:"))
        if(UserInput == 2):
            print("Congratulations you are correct!")
            break
        else:
            print("That is incorrect. Try again!")
    except ValueError:
        print("That is not a number. Try again!")

This works perfectly fine (or at least it should) but, why (if not) would this next piece of code not work.

print("What is 1 + 1?")
while(True):
    UserInput = int(input("Your answer here:"))
    if(UserInput == 2):
        print("Congratulations you are correct!")
        break
    elif(UserInput != 2):
        print("That is incorrect. Try again!")
    else(ValueError):
        print("That is not a number. Try again!")

When I run this I get this error:

Traceback (most recent call last):
  File "python", line 9
    else(ValueError):
        ^
SyntaxError: invalid syntax

I know it is because ValueError only works (I think) with try and except loops but, why can't it not work in the above scenario? I assume they would give the same results but, I don't know everything. Maybe one of you amazingly smart people can tell me my that wont work or an alternative. Thank you for trying to clarify this to me :).

Expression or statement incorrect or possibly unbalanced (MATLAB)

if ((x % 2) == 1)
x = x - 1;
end

I don't get what I did wrong and can't find anything online, it's suppose to make a number even by subtracting 1 if it's odd btw.

How to use a function's if statement to use info from another function?

So I'm designing a sign-in AI, and I want it to work so that the admin name is Shawn. Here is my issue:

The program starts with the interface -

def interface():
username = input('Hello traveler, what is your name?  ')
lowerUsername = username.lower()
print()
print()
if lowerUsername == 'megan':
    print()
    print('So you are the one Shawn has told me so much about? You are looking beautiful today my dear ☺️🌷')
elif lowerUsername == 'shawn':
    OfficialSignInEdit()

So you can see at the end that if the user inputs that their name is 'shawn' at sign-in, it calls on the OfficialSignInEdit function, which is the admin sign in. It looks like this:

def OfficialSignInEdit():
print()
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
    print()
    print('Greetings Master Shawn, it is a pleasure to see you again 🙂')
else:
    print()
    res1 = input('Incorrect password, try again? (Yes/No)')
    lowres1 = res1.lower()
    if lowres1 == 'yes':
        print()
        print()
        OfficialSignIn()
    elif lowres1 == 'no':
        print()
        print()
        interface()

So I have pinpointed the source of my issue to be right here in this particular line:

if PossInputs('perio', 'What street did you grow up on?: ') == correct:
    print()
    print('Greetings Master Shawn, it is a pleasure to see you again 🙂')

this (just for your reference) is the PossInputs function:

def PossInputs(x, y):
term = x
question = input(y)
lowQuestion = question.lower()
words = lowQuestion.split()
if term in words:
    print()
    print (correct)
else:
    print()
    print (incorrect)

So what I want to happen is, when 'shawn' is entered as a name, the program will jump to the OfficialSignInEdit Function, and ask the question 'What street did you grow up on?'. Then IF the user enters the answer 'perio', the program will print 'correct', and then print the message 'Greetings Master Shawn, it is a pleasure to see you again'. I tried to say that IF PossInputs == correct (and I did define correct = 'correct', and incorrect = 'incorrect' outside all functions) then this would happen, but instead it prints 'correct', and then 'Incorrect password, try again? (Yes/No)', so how can I make a conditional statement that says that if the user answers 'perio', then it will print the welcome message?

Just for thoroughness sake, I also tried

if PossInputs('perio', 'What street did you grow up on?: ') == True

also without success...

anyways anything you can give me is extremely appreciated, if you have any questions or you would like to to clarify something about the written code, I would be more than happy to get back with you as soon as I can.

Thanks!

python if wait then statement

I'm new to coding so please forgive if this is simple... I am working on a raspberry pi python script and I am struggling to get the if statement to do what I want.

I can count fingers on a hand in a video stream and this is working fine.

Next I want to initiate a first event (beep) when 5 fingers (defects) are counted, and then proceed into a sub loop where if the 5 fingers subsequently change to zero fingers within a given time (2s) then another second event (click) happens.

this is what I have so far (not quite working):

if count_defects==5:
    os.system('mpg321 beep.mp3 -q')
    time.sleep(2)
    if count_defects<5:
        os.system('mpg321 click.mp3 -q')
else:
    cv2.putText(img, "Waiting", (50,50), font, 1, (255,255,255), 1)

Hope someone can help thanks

Python 3.5 convert values during re-write to new csv

I have a CSV file that I am writing to another file, but in the process want to change values based on greater then or less than. For example, in column for in the new file (row 2 from the old one) I want to transform the data from a number into a word, depending on the value in the column. My actual data has more columns, and thousands of lines, not exceeding 10k lines. Example is below:

Input.csv
duck,35,35
car,100,502
baseball,200,950
gun,500,495
taco,300,300
guitar,100,700
barbie, 200,25
gum,300,19

Desired Output.csv
duck,35,35,order now
car,100,502,order next month
baseball,200,950,no order necessary
gun,500,495,order next month
taco,300,300,order next month
guitar,100,700,order next month
barbie, 200,25,order urgent
gum,300,19,order urgent

This is my code so far, but I'm having trouble with the conversion of the amount into a new value. I think I need to use enumerate, but haven't found any examples in my research of a csv conversion with this method. Please assist.

import csv

with open('INTERIM RESULTS.CSV', 'r') as source:
  rdr = csv.reader(source)
  with open('INTERIM RESULTS FIXED.CSV', 'w', newline = '') as result:
    wtr = csv.writer(result)
    for r in rdr:
      wtr.writerow( ( r[0], r[1], r[2] ) )

EDIT: Taking Anonymous' advice, I came up with the below code. The problem is that somewhere in my "if" / "elif" statments I am not able to get the correct output. Output I currenlty get is not correct, listed below. Please assist.

import  csv 
CODE0 = '25'
CODE1 = '50'
CODE2 = '500'
CODE3 = '900'

with open('input.csv', 'r')  as  source, open('output.csv', 'w')  as  result: 
    reader = csv.reader(source) 
    writer = csv.writer(result) 
    for  row in  reader: 
        val = row[2]
    if val <= CODE0: # below 25 order urgent
            writer.writerow( ( row[0], row[1], row[2], 'order urgent'))
    elif val <= CODE1: # below 50 order now
        writer.writerow( ( row[0], row[1], row[2], 'order now'))
    elif val <= CODE2: # below 500 order next month
        writer.writerow( ( row[0], row[1], row[2], 'order next month'))
    elif val < CODE3: # below 900 order next month
        writer.writerow( ( row[0], row[1], row[2], 'order next month'))
    elif val >= CODE3: #over 900 no order necessary
        writer.writerow( ( row[0], row[1], row[2], 'no order necessary'))

Output.csv
duck,35,35,order now
car,100,502,order next month
baseball,200,950,no order necessary
gun,500,495,order now    (this is wrong, should be next month)
taco,300,300,order now    (this is wrong, should be next month)
guitar,100,700,order next month
barbie, 200,25,order urgent
gum,300,19,order urgent

Is 1st character in String, equals to last one in same String

I need Java solution. I want to do it with if, or for loop.

Code needs to check does some String "Ababa" have 1.st and last character same. a==a;b==b etc.

Loop to create multiple button in html and php

So basically what I am trying to do is using a loop to display multiple image and create a corresponding button to each image. If I pressed on the corresponding button, it will store the image into another database.

The first part display quite well. However, the second part I can hardly figure out how to determine the corresponding button for each image.

<?php while($row=mysqli_fetch_array($result)) { ?>
<div id="item">
  <?php echo '<img height="200" width="200" src="data:image;base64,'.$row[2]. '">';?>
  </br>
  <?php echo $row[ "name"];?>
  </br>
  <?php echo $row[ "price"];?>
  </br>
  <?php echo $row[ "description"];?>
  </br>
 <form>Quantity:
  <input type="text" value="" name="quantity" />
  </br>
  <input type="submit" value="add to cart" name="cart" />
 </form>
  <?php 
if (isset($_POST[ "cart"])){ 
$addtoname=$_SESSION[ 'username']; 
$addtoprice=$row[ 'price']; 
$addtodiscount=$row[ 'discount']; 
$addtoid=$row[ 'id']; 
$addtoimage=$row[ 'image']; 
$addtoquantity=$_POST[ 'quantity']; 
$hostname="localhost" ; 
$username="root";
$password="" ; 
$database="myproject" ; $con=mysqli_connect($hostname,$username,$password,$database) or die(mysqli_error()); 
$select=mysqli_select_db($con, "myproject")or die( "cannnot select db"); mysqli_query($con,"INSERT INTO cart(username,quantity,price,image,id,discount) VALUES('$addtoname','$addtoquantity','$addtoprice','$addtoimage','$addtoid','$addtodiscount')"); 
echo "success"; 
} 
else{ 
echo "fail"; 
}?>
</div>
<?php }//end of while ?>

It seems like it always go to fail AND never run into isset($_POST[ "cart"]))

Any tips will be much appreciated.

Thank you

Search in excel

Please help me with the problem below:

I am using IF(SEARCH('Fashion',A1)1,0) to search for word Fashion in Column A. It gives 1 when it finds word fashion but gives error #VALUE! when gets words such as 'Lifestyle' and 'Photography'.

Basically containing letters of word 'Fashion'.

samedi 28 mai 2016

In Java, trying to print how many digits in an integer evenly divide into the whole integer

I'm trying to print how many digits in an integer evenly divide into the whole integer.

Using mod 10 and division by 10, I got the last digits of the integer, and then did mod integer by each last digit. For some reason it's not working and I'm getting errors (https://repl.it/CWWV/3).

Any help would be greatly appreciated!

Scanner in = new Scanner(System.in);
    int singleD, n1;
    int counter = 0;
    int n = in.nextInt();
        n1 = n;
        singleD = n1%10;
        while (n1 > 0 && singleD > 0){
            n1 /= 10;  
            if(n%singleD == 0){
                counter++;
            }
        }
        System.out.println(counter);
        counter = 0;

how to validate both lowercase and uppercase letters

Below I have written a program to evaluate a letter grade and print a message based on how well the score is. Let's say I wanted to get that information from the user input, how would i be able to accept both lower and upper case letters?

 #include <stdio.h>
 int main (){
/* local variable definition */
char grade = 'B';

if (grade == 'A'){ 
printf("Excellent!\n");
}
else if (grade == 'B' || grade == 'C'){
printf("Well done\n");
}
else if (grade == 'D'){
printf("You passed\n" );
}
else if (grade == 'F'){
printf("Better try again\n" );
}
else {
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
 }

Using a series of if statements to check and see if a number is evenly divisible

How would I go about checking if a number entered by a user is evenly divisible by 2,3,4,5,7. If the value entered is evenly divisible I'd like the program to print out a statement for each number. If i used the % to check if the value is zero would that work?

#include<stdio.h>
int main() {
int number;
printf("Enter a number");
scanf("%d",&number);
if (number%2 == 0){
prinntf("%d is divisible by 2",number);
}
else if (number%3 ==0){
prinntf("%d is divisible by 3",number);
}
else if (number%4 == 0){
prinntf("%d is divisible by 4",number);
}
return 0;
}

This is what i wrote so far but I know there's a few errors.

if statement check not working in ruby

I have the following code, but when I run it, the code in the IF statement never gets executed.

I don't understand why the IF statement never gets executed despite the value of variable c and key being the same as shown in the output in bold below.

text = 'cab'

letters = {
  'a': 1,
  'b': 2,
  'c': 3,
}

text.split("").each do |c|
  puts c
  puts "Text #{c}"
  for key, value in letters

    puts "Key #{key}, Text #{c}, Value #{value}"
    if c == key
      puts "hello #{c}"
    end
  end
end

Output

c
Text c
Key a, Text c, Value 1
Key b, Text c, Value 2
Key c, Text c, Value 3
a
Text a
Key a, Text a, Value 1
Key b, Text a, Value 2
Key c, Text a, Value 3
b
Text b
Key a, Text b, Value 1
Key b, Text b, Value 2
Key c, Text b, Value 3

When changing the colour variable within if and else if statements it comes back with an error saying it is unassigned

I am trying to change the color of a ball randomly however when I try to use the color variable to become the color of the solid brush it says that it is unassigned. "Use of unassigned local variable 'ballColour'"

    xPos = xPos + GAP_SIZE;
    int colour = rand.Next(1, 40);
    Color ballColour;
    if (colour >= 1 && colour <= 9)
    {
        ballColour = Color.Blue;
    }
    else if (colour >= 10 && colour <= 19)
    {
        ballColour = Color.Orange;
    }

    else if (colour >= 20 && colour <= 29)
    {
        ballColour = Color.Green;
    }
    else if (colour >= 30 && colour <= 39)
    {
        ballColour = Color.Red;
    }
    else if (colour == 40)
    {
        ballColour = Color.Purple;
    }
    SolidBrush ballColourBrush = new SolidBrush(ballColour); //This is the one that returns the error.
    paper.FillEllipse(ballColourBrush, xPos, yPos, BALL_SIZE, BALL_SIZE);
                    xPos = xPos + BALL_SIZE;

Collatz sequence getting last number 1 repeated

    // Define the recursive function.
    int collatz(int p1)
    {
        // While Loop Starting
        while (p1>1)
        {
      //when the number is even
        if(p1%2==0)
        {
            p1 = p1/2;
            printf("%d ", p1);
        //using recursion
            return collatz(p1);
        }
        // Case where number is odd.
        elseif
        {
            p1 = 3*p1+1;
           //print function
            printf("%d ", p1);
           //using recursion
            return collatz(p1);
        }
        }
     }  
    // Main body.
    int main()
    {
       // Declare the variable and initialized it.
      int p1= 4;
      //print function
     printf("User Entered value  : %d\n", p1);
       // Display the number 
        printf("%d\n", collatz(p1));
        //End
        return 0;
    }

Output: I am getting the Output as : 2 ,1, 1 I should not get the last number 1 repeated.Could you please correct me where i have done mistake.Please do the needful.

How do I get this WHILE loop to work?

Currently doing an exercise that I thought I had done right, using an IF ELSE statement, but once submitted I was told instead to use a WHILE or DO-WHILE loop, and I'm having a bit of trouble. You'll see where I've used the WHILE loop, but it is giving me an infinite loop of the error message that I assigned to it and I don't know how to make it stop!

static void Main(string[] args)
    {
        decimal hours;
        const decimal HOURLY_RATE = 2.5m;
        const decimal MAX_FEE = 20.00m;
        Console.WriteLine("Enter the amount of hours parked:");
        hours = decimal.Parse(Console.ReadLine());
        decimal parkingCost = hours * HOURLY_RATE;

        while (hours < 1 || hours > 24) 
        {
            Console.Write("Enter correct amount of hours - 1 to 24. ");
        }

        if (parkingCost > MAX_FEE) 
        {
            Console.Write("Total fee is $" + MAX_FEE);
            Console.WriteLine(" Time parked in hours is " + hours);
        }
        else
        {
            parkingCost = hours * HOURLY_RATE;
            Console.WriteLine("The cost of parking is " + parkingCost.ToString("C"));
            Console.WriteLine("Time parked in hours is " + hours);
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}

So the idea is that I want for the "Enter correct amount of hours - 1 to 24. " to display if the user enters a number less than 1 or greater than 24, otherwise for the program to go ahead with the IF and ELSE statements.

How could you write the "if - then" logic for the game Yacht?

http://ift.tt/1X427Ct

I created 5 dice in my c++ program and they each roll random numbers from 1-6. So if you get all 1's its really simple. It's just:

if (dice1 == 1 && dice2 == 1 && dice3 == 1 && dice4 ==  1 && dice5 == 1)
{
int total = 50;
}

Also, summing all the dice is easy too. But how could you write the if-statement for "if two to four dice are the same then sum up those dice"? Is there a simple way you could do that?

if elif else program python

Shipping charges for an online orders are based on the value of the order and the shipping weight. Shipping is free if the value is over $100. Orders under $100 incur shipping charges as follows: Over 40 lbs: $1.09 per lb. Over 20 lbs: $0.99 per lb. Equal to or Under 20 lbs: $0.89 per lb. I need to write a python program that prompts the user to enter both the value and weight of an order, then displays the required shipping charges. But if the order value is $100 or more, weight is irrelevant and your program should not ask for it.

SO far I have figure out the coding for the shipping not sure about the other parts.

#Have user enter weight of order
weight = int(input('Enter the weight of your order:'))

#Determine shipping cost
if weight >= 40:
    total = weight * 1.09
elif weight >= 20:
    total = weight * 0.99
elif weight <=20:
    total = weight * 0.89

Thank you for your help!

swift2 Xcode7.0 Expected ',' separator [duplicate]

This question already has an answer here:

if ( username.isEqualToString("")||
            useremail.isEqualToString("") ||userpassword.isEqualToString("")||
            userphonenumper.isEqualToString("")
            ){
            let alert = UIAlertController(title: "Sign Up Failed!", message:"Please enter your data", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: ",ok", style: .Default) { _ in })
            self.presentViewController(alert, animated: true){}
        } 

I use Xcode7 and Swift2 when i run the application I get this error

the error in if statment

if ( username.isEqualToString("")||
            useremail.isEqualToString("") ||

Selected value in same page

When I open the page, $d = "". I select from selectbox the value fex. 45 and I want to gaiv $d the selected value in the same page without refresh it.

if ($_POST['select_day'] == "45") {
    $d = (1 * 86400) + $Stime;
}

And when I click on the button I cannot get $d=45. How can I do it?

CLIPS - if then else function gives [CSTRCPSR1] err

Here is the error summary:

CLIPS> (load "C:/Users/labor/Desktop/Witek/projekt.CLP")
Defining defrule: R1 +j+j
Defining defrule: R2 +j+j
Defining defrule: R3 =j+j+j
Defining defrule: imie-if =j=j+j+j

[CSTRCPSR1] Expected the beginning of a construct.

And here is the code for my CLIPS program. Basically I want it to react different if the name and last name are different from Abraham Lincoln.

(defrule R1
(initial-fact)
=>
(printout t "Enter your name:" crlf)
(bind ?name (read))
(assert (name ?name)))

(defrule R2
(name ?name)
=>
(printout t "Enter your last name" crlf)
(bind ?lastnm (read))
(assert (lastnm ?lastnm)))

(defrule R3
(and(name ?name)(lastnm ?lastnm))
=>
(printout t "How old are you " ?name "?" crlf)
(bind ?age (read))
(assert (age ?age)))

(defrule name-if
(name ?name)(lastnm ?lastnm)(age ?age)
=>
(if(and(eq ?name Abraham)(eq ?lastnm Lincoln))
then (printout t "Hello " ?name " " ?lastnm ", you are " ?age " years old bro" crlf))
else (printout t "Hello " ?name " " ?lastnm ", you are " ?age " years old" crlf)))

I copied the if statement logic from some webpage and I am not quite sure what, in this case, 'eq' stands for... i'd appreciate if you could additionally explain the role of it.

Regards, W

What does this statement do exactly

        if (dt.Rows[0][0].ToString() == "1")
        {
            this.Hide();

            Game GG = new Game();
            GG.Show();
        }
        else // else it will display this error
        {
            MessageBox.Show("Please enter the correct login details");
        }
    }

This is an if statement I am using for my game I am creating in c#. I'm trying to write internal commentary so I can describe each function properly and have a better understanding of the language. any help would be appreciated, Its just the top line i'm unsure about.

Conditional Axis in Lattice R

Here it comes a challenge. The target is to give format (bold/regular) to the y-axis in a dotplot under de condition of variable "Z" being higher/lower sd. I have already been able to introduce the formatting so I am now struggling on how to introduce the logic test.

   #dataframe
d<-data.frame(a=LETTERS[1:26],b=rnorm(26,50,10),c=rnorm(26,50,1))
#dotplot
dotplot(a~b,d,col="blue",pch=16,
        #simple plot comparing two vectors
        panel = function(x,col,y,...){
  panel.dotplot(x,col="blue",y,...)
  panel.xyplot(x=d$c,col="darkblue",y,...)
  mins=NULL
  maxs=NULL
  #a line showing the difference between "measures"
  for(i in 1:nrow(d)){
    mins[i]<-min(d$c[i],d$b[i])
    maxs[i]<-max(d$c[i],d$b[i])
  }
  panel.segments(x0=mins,y0=as.numeric(y),
                 x1=maxs,y1=as.numeric(y),col="red")
},
#the challenge of the conditional Y-axis
yscale.components = function(...){ 
  temp <- yscale.components.default(...) 
  loc <- temp$left$labels$at 
  print( temp$left$labels$labels <-   
           sapply( temp$left$labels$labels, 
                   function(x) if(a> x){ 
                     as.expression(bquote( bold(.(x)))) 
                   }else{ 
                     as.expression(bquote(.(x)))} )) 
  temp },
#a legend
key = list(columns=2, 
           points=list(pch=16,col=c("blue","darkblue")),
           text=list(c("measure","fitted"))))

I would like to consider this an advance code, so let me hear your thoughts!

vendredi 27 mai 2016

How to search for items in a list in python

Basically I have two lists of items, and I want to check if an item from the second list is in the first list. Then if that item is in the first list, I want to assign a value to a variable, if it is not in that list, I want to assign a different value to the same variable. (As below) Can this be done?

list1 = ['dog','cat','mouse']

list2 = ['dog','tutle','bird']

if list2 in list1:
    square = 77
else:
    square = 55

print(square)

Is it okay to wrap my google analytics code in an if statement? Not sure if it's receiving data from my site

Is it okay to wrap my google analytics code in an if statement? Not sure if it's receiving data from my site now. I have a small site that I developed that uses google analytics. I did this

local = os.getenv('_system_name')
context = {
    ...
    'local': local

}

and in my base.html template

   Liquid error: Unknown operator local

earlier I tested it by putting some code to make sure it showed when its not local. But now it seems like all the data has stopped. And I know that I have been getting traffic? This was earlier around 6 p.m. friday it's 12:30 now usually after 12 at night the system updated. Should I not have the script in an if statement or should I not worry because google systems may be updating or something. Thanks. And if some people want to know why I did that it's so I wouldn't have to keep commenting the code every time I performed a git push

R-function If statement for passing on variables

Im trying to write an if statement in an a function. It's for the x variable that either can be a cuple of the variables from the dataset or all of the variables in the dataframe, like: (Both X and Y are given like column names)

f<-function(y,x,data){if (x=="all"){something<-y+2}else{something<-y+5}} I get the error "the condition has length > 1 and only the first element will be used"

I'll appreciate all the help i can get. Thanks.

if-else styles and optimization

When you have a function whose behaviour depends on a series of conditions, you could compute it using differents if-return blocks or with a series of if-else blocks. Example computational schemas:

void f(params) // isolated if-blocks
{
    if (cond1) {
       // computational steps
       return;
    }

    if (cond2) {
       // computational steps
       return;
    }

    // computational steps of last case
 }

 void f() // unique if-else block
 {
    if (cond1) {
       // computation
    } else if (cond2) {
       // computation
    } else { // last condition
       // computation
    }
 }

I would say the first one is always more readable, but I don't know if the second one is best from a design (maintenance/error prone) or performance (branch prediction/compiler optimizations) point of view.

What are the pros and cons of both approaches? What other things have I not considered?

Value in one Cell subtracted before another cell can start calculating

B17=160 and never goes above 160 B17 goes down when B18, A19, B20, B22 are subtracted. When B23 has a number value, that value cannot affect B17, and B18 cannot be subtracted from B17 until the value in B23 is = 0. Only then can B17s 160 value go down by subtracting B18, A19, B20, B22.

I have spent the better part of 2 months trying every combo I can think of and nothing seems to be giving me the desired results.

Any assistance is welcome.

Why does outputting bits inside of an "if" or "when" always output 0? MySql 5.7

I've been working with some bit columns. I have to select one column or another based on a third column. That is not my question. Here's a simplified example to show what I've been encountering.

CREATE TABLE Testing (
ColType TINYINT(6),
Type1 BIT(1) DEFAULT b'0',
Type2 BIT(1) DEFAULT b'0'
);

Note that ColType is usually joined in via foreign key in the "real world" scenario.

INSERT INTO Testing
(ColType, Type1, Type2)
VALUES
(1, 0, 0),
(1, 0, 1),
(1, 1, 0),
(1, 1, 1),
(2, 0, 0),
(2, 0, 1),
(2, 1, 0),
(2, 1, 1);

This creates all the possible combinations of the 3 columns. The following is the queries I've run using this data.

SELECT 
*,
IF(ColType = 1, Type1, Type2) Output1,
(CASE WHEN ColType = 1 THEN Type1 ELSE Type2 END) Output2,
IF(ColType = 1, CAST(Type1 AS SIGNED), CAST(Type2 AS SIGNED)) Output3,
IF(ColType = 1, Type1=1, Type2=1) Output4
FROM
Testing;

CREATE TEMPORARY TABLE Describer
SELECT
*,
IF(ColType = 1, Type1, Type2) Output1,
(CASE WHEN ColType = 1 THEN Type1 ELSE Type2 END) Output2,
IF(ColType = 2, CAST(Type1 AS SIGNED), CAST(Type2 AS SIGNED)) Output3,
IF(ColType = 2, Type1=1, Type2=1) Output4
FROM
Testing;

DESCRIBE Describer;
SELECT * FROM Describer;

The results are:

ColType  Type1  Type2  Output1  Output2  Output3  Output4
1        0      0      0        0        0        0
1        0      1      0        0        0        0
1        1      0      0        0        1        1
1        1      1      0        0        1        1
2        0      0      0        0        0        0
2        0      1      0        0        1        1
2        1      0      0        0        0        0
2        1      1      0        0        1        1
----------
Field    Type            Null  Key  Default Extra
ColType  tinyint(6)      YES
Type1    bit(1)          YES        b'0'
Output1  int(1) unsigned YES        b'1'
Output2  int(1) unsigned YES        NULL
Output3  int(1)          YES        NULL
Output4  int(1)          YES        NULL
----------
ColType  Type1  Type2  Output1  Output2  Output3  Output4
1        0      0      0        0        0        0
1        0      1      0        0        0        0
1        1      0      1        1        1        1
1        1      1      1        1        1        1
2        0      0      0        0        0        0
2        0      1      1        1        1        1
2        1      0      0        0        0        0
2        1      1      1        1        1        1

My question is: why do certain versions of this query work and others not? I would expect the temp table to be holding the same values as shown in the first select, but that's clearly not the case. So why is there all of these mismatches of data?

Omitting the parent product from calculation

I'm having some issues addressing some calculations. I have a product page, and in that product page I have some related products that can be purchased as a group at a discounted price. I have everything working, but I am having issues omitting the parent product from the calculation/discounted percentage.

The code below is removing the parent prod from the discount, but if I add another group to the cart, it only omits the first parent and not the newly added parent.

How can I check the $buy_together_id and confirm only the first of each product with a unique id is omitted from the discount calculation?

My most recent addition to the code to tackle this issue, is both instances of if ($k != 0), but again it is only checking for the first parent and not all parents.

Thank you,

Sergio

<?php

   global $config, $current_area;

   if ($current_area != 'C' || !function_exists('func_bt_distribute_discount')){
       return;
   }

   $discount_to_add = 0;
   $group_discounts = array();

   $bts_in_cart = array();
   foreach ($products as $k => $v){
       if ($k != 0) {
           if ($v['buy_together_id']){
               foreach ($v['buy_together_id'] as $gid){
                   $bts_in_cart[$gid][] = $v['productid'];
               }
           }
       }
   }

   // Go through each product and calculate discount to be applied. //

   foreach ($products as $k => $v){

       if ($k != 0) {

           if ($v['buy_together_id']){

               foreach ($v['buy_together_id'] as $buy_together_id){

                   $_discount = 0;

                   if (!isset($GLOBALS['group_bt_discounts'][$buy_together_id])){
                       $GLOBALS['group_bt_discounts'][$buy_together_id] = func_query_first('SELECT * FROM xcart_buy_together_groups
                                                                                             WHERE groupid='.intval($buy_together_id));
                   }

                   $g_discount = $GLOBALS['group_bt_discounts'][$buy_together_id];
                   $price = defined('BT_ADD_TAXES') && BT_ADD_TAXES && $v['taxed_price'] ? $v['taxed_price'] : $v['price'];

                   // Discount //
                   if ($g_discount['discount']){
                       if ($g_discount['discount_type'] == 'P'){
                           $_discount = ($price / 100) * $g_discount['discount'];
                       } else {
                           $_discount = $g_discount['discount']/count($bts_in_cart[$buy_together_id]);
                       }
                   }

                   if ($_discount > 0){

                       /* Add to discount for the quantity */
                       if ($config['Buy_Together']['bt_apply_to_all'] == 'Y'){
                           $_discount *= $v['amount'];
                       }

                       // Change the product discount //
                       $products[$k] = func_bt_distribute_discount($products[$k], $_discount);

                   }

                   /* Cumulative total */
                   $discount_to_add += $_discount;
               }
           }
       }

   }

   $return['products'] = $products;
   $return['discount'] = $discount+$discount_to_add;
   $return['discount_orig'] = $discount+$discount_to_add;
?>

Compress an 'If' Statement

Hoping that this one doesn't cause much trouble in answering, but when writing this out in my Sudoku project, I knew there must be a better way of phrasing this if condition.

Thanks in advance guys.

public static void modVal(int r, int c, int x) {
    if((r>=1 && r<=9) && (c>=1 && c<=9) && (x>=1 && x<=9)) {
        sudoku.set(r,c,x);
    }
}

Why didn't the compiler warn me about an empty if-statement?

I'm using Keil uVision v4.74 and have enabled the option "All Warnings".

I wrote the following intentional code:

if(condition matched)
{
 //do something
}

When I rebuilt my project, I got 0 errors, 0 warnings.

However, when I accidentally wrote:

if(condition matched);
{
 //do something
}

I also got 0 errors, 0 warnings.

It was next to impossible for me to find out that a small ; following the if condition was the root of the problem.

Why didn't the compiler treat it as a warning and inform me?

Perl Loop not filtering right results

So guys I am searching through a mutliple log files using perl script and this is my while loop. for some reason I think my loop is searching only once and returning the first values it found. This result output is not returning all the possible values after reading the files.There are some missing values.

   #str_1,2,3,4 are my strings I am searching for 

    while ($line = <$fh>){

       if($line !~ /$str_1/ && $line =~ /$str_2/){
       open($fh, '>>report.txt');
       print $fh "$file : $line";
       close $fh;
        }
    if($line !~ /$str_3/ && $line =~ /$str_4/){

     open($fh, '>>report.txt');
     print $fh "$file : $line";  
       close $fh;

        }

    }

   }

      output: Number of Attendance = 1 INFO:21
              Number of Attendance = 2 INFO:21
              Number of Attendance = 1 INFO:21 

   # There are results such as Number of Attendance = 8 INFO:21 which my code is not able to search.

In R, search a dataframe for specific values, if found then select entire values and paste into new dataframe

In R, I am trying to search a column in a dataframe for a specific value. Once that value is found, I want to select the all of the data where that value exists, then copy and paste it into a new dataframe. I have a sample of the dataframe below. I am searching for a value "Storms" in the Storms column. If multiple "Storm" periods occur in a row, I want the program to select all of the data for that particular event and paste it into a new dataframe. The end goal is to get individual dataframes for each storm event. I am new in R so I don't have much to start with. I am planning on using the grep to search. Any help is appreciated.

DateTime    Rain (in)   Discharge (m^3/s)   TP (ug/s)   Storm
6/9/2014 0:00   0   0.105895833 9135.989427 No
6/9/2014 12:00  0   0.1055  9089.171776 No
6/10/2014 0:00  0   0.101979167 8726.453115 No
6/10/2014 12:00 0   0.095770833 8058.577397 No
6/11/2014 0:00  0   0.09625 8115.980183 Storm
6/11/2014 12:00 0   0.093625    7838.081703 No
6/12/2014 0:00  0   0.095   7989.704734 Storm
6/12/2014 12:00 0   0.093666667 7842.683567 No
6/13/2014 0:00  0   0.09375 7850.2027   Storm
6/13/2014 12:00 0   0.094125    7891.157636 Storm
6/14/2014 0:00  0   0.099458333 8456.241045 Storm
6/14/2014 12:00 0   0.101104167 8622.904117 Storm
6/15/2014 0:00  0   0.095229167 8007.199433 No
6/15/2014 12:00 0   0.091958333 7665.64586  No
6/16/2014 0:00  0   0.091979167 7665.606679 No
6/16/2014 12:00 0   0.088833333 7355.67491  No
6/17/2014 0:00  0   0.094333333 7918.867602 Storm
6/17/2014 12:00 0   0.120229167 10713.34331 Storm
6/18/2014 0:00  0   0.133854167 12259.29537 Storm
6/18/2014 12:00 0   0.1195625   10640.74235 No
6/19/2014 0:00  0   0.118395833 10504.82994 No
6/19/2014 12:00 0   0.116729167 10316.9778  No

File<-read.csv(file="C:\\R_Files\\P_Weather_12hr.csv",header=TRUE)
for (event in File){
  search<-ifelse(grep('Storm',File$Storm),select all of the data...
}