dimanche 31 mai 2015

Problems with matrix indexing using for loop and if condition

I to do some indexing, something like what follows:

for c=1:size(params,1)
    for d=1:size(data,2)
        if params(c,8)==1
            value1(c,d)=data(params(c,11),d);
        elseif params(c,8)==2
            value2(c,d)=data(params(c,11),d);
        elseif params(c,8)==3
            value3(c,d)=data(params(c,11),d);
        end
    end
end

The problems with this is that if we have params(:,8)=1,3,1,3,2,3,1... then value1 will contain all zeros in rows 2, 4, 5, 6, etc. These are the rows that do not have 1 in column 8 in params. Similarly, value2 will contains all zeros in rows 1, 2, 3, 4, 6, 7... and value3 will contain all zeros in row 1, 3, 5, 7, .... Could anyone tell me how to index so I don't have 'gaps' of zeros in between rows? Thanks!

Issues with If/Then statements

I am using a home made collision detection system for a game I am making, and it works alright- if there is only one object it collides with. It will only give collision detection for the bottom most object. I tested and it registers collision between other objects, but it doesn't limit the movement speed. I think this is because of the nature of if/then statements.

How can I make it check all instanced of blocks with id of 1 for collision?

To explain my variables:

coll is an ArrayList of rectangles that I thought could be used to check for collision.

mU is moveUp, mL is moveLeft, and so on.

xOffset and yOffset are used in drawing the map. They control how far the map is drawn form (0, 0)

vel is the player speed. It equals one in the case.

The relevant code:

    private void blockCheck() {

    for(int i = 0; i < numCols; i++ ) {
        for(int c = 0; c < numRows; c++) {
            if(World[c][i] == 0) {
                solid = false;
            }
            if(World[c][i] == 1)
                solid = true;
            if (solid == true)
                collision(c, i);
            }
        }
    }

private void collision(int c, int i) {
    checkCollisionTop(c, i);
    checkCollisionLeft(c, i);
    checkCollisionRight( c, i);
    checkCollisionBottom(c, i);
}

private void checkCollisionBottom(int c, int i) {

        Rectangle t = new Rectangle(c * 16 + (int)xOffset, i * 16 + 4 + (int)yOffset, pR.width, pR.height);
        if(!coll.contains(t))
            coll.add(t);

        if (pR.intersects(t)) {
            mU = false;
            System.out.println("Collision on Botton");
        } else mU = true;

}

private void checkCollisionRight(int c, int i) {

        Rectangle t = new Rectangle(c * 16 + 4 + (int)xOffset, i * 16 + (int)yOffset, pR.width, pR.height);
        if(!coll.contains(t))
            coll.add(t);
        if (pR.intersects(t)) {
            mL = false;
        } else mL = true;


}

private void checkCollisionLeft(int c, int i) {



    Rectangle t = new Rectangle(c * 16 - 4 + (int)xOffset, i * 16 + (int)yOffset, pR.width, pR.height);
    if(!coll.contains(t))
        coll.add(t);
    if (pR.intersects(t)) {
        mR = false;
    } else mR = true;


}

private void checkCollisionTop(int c, int i) {


    Rectangle t = new Rectangle(c * 16 + (int)xOffset, i * 16 - 4 + (int)yOffset, pR.width, pR.height);
    if(!coll.contains(t))
        coll.add(t);
    if (pR.intersects(t)) {
        mD = false;
    } else mD = true;


}

private void moveCamera() {


    if(keysDown.contains(KeyEvent.VK_W) && mU == true) {

        yOffset = yOffset + vel;
        for (int i = 0; i < coll.size(); i++) {
            coll.remove(i);
            i--;
        }

    }
    if(keysDown.contains(KeyEvent.VK_D) && mR == true) {

        xOffset = xOffset - vel;
        for (int i = 0; i < coll.size(); i++) {
            coll.remove(i);
            i--;
        }
    }
    if(keysDown.contains(KeyEvent.VK_S) && mD == true) {

        yOffset = yOffset - vel;
        for (int i = 0; i < coll.size(); i++) {
            coll.remove(i);
            i--;
        }
    }
    if(keysDown.contains(KeyEvent.VK_A) && mL == true) {

        xOffset = xOffset + vel;
        for (int i = 0; i < coll.size(); i++) {
            coll.remove(i);
            i--;
        }
    }

}

MySQL IF IS NULL ERROR

I want to test if a select-statement is null but I'am already failing with the case analysis:

SET @dublicate = NULL;
IF @dublicate IS NULL THEN
    SELECT * FROM mysql.user;
END IF;

This should ever return the selection but I just get the following error:

#1064 - You have an error ... near 'IF @dublicate IS NULL THEN SELECT * FROM mysql.user; END IF' at line 2

and i really dont know whats wrong.

Many thanks in advance

KillerMelone

Comparing Equality of Three Strings Java

I know this is a very basic question, but I am always trying to find ways to make my code a clean and concise as possible. Is there a way to compare the equality of three or more strings in a single if() statement? I am currently using the && operator to progressively compare each string. However, as you could imagine, between long variable names and methods being called, these if() statements get very cluttered very quickly. Additionally I am planning to have an unknown number of these Strings, and would like to avoid complex for loops with cluttered if()s nested inside of them. This is what my code currently looks like:

String a = new String("a");
String b = new String("b");
String c = new String("c");
if(a.equals(b) && b.equals(c)) {
    doSomething();
}

Is there a way, or a collection of some sort that I can use that would allow me to compare these values more like this:

if(a.equals(b).equals(c)) {
    doSomething();
}

nested if statement in C#

I get the command prompt to come up and get the correct answer for Bad Score, but if I try to type in a good grade (800) it does nothing. Any help would be greatly appreciated. I am new to this so I apologize my coder isn't pretty.

        //variables
        string firstName, lastName, grades = "";
        double points = 0, percent = 0;


        //Greeting
        Console.WriteLine("The purpose of this program is to allow the teacher to calculate the percentage and final grade for students in their class.");

        //Display and Inputs
        Console.WriteLine("\n\nPlease enter the students first name.");
        firstName = Console.ReadLine();

        Console.WriteLine("\n\nPlease enter the students last name.");
        lastName = Console.ReadLine();

        Console.WriteLine("\n\nPlease enter the points that the student received.\n\n");
        points = Convert.ToDouble(Console.ReadLine());

        //Display after points are entered
        if (points < 0 || points > 1000 ) 
        {
            Console.WriteLine("Bad Score!");
        }
        else 
        {
            percent = points / 1000;
            if (percent >= .9)
            {
                grades = "A";
            }
            else if (percent >= .8)
            {
                grades = "B";
            }
            if (percent >= .7)
            {
                grades = "C";
            }
            else if (percent >= .6)
            {
                grades = "D";
            }
            if (percent >= .0)
            {
                grades = "F";
            }
            else
            {
                 Console.WriteLine("WRONG!!");
            }
        }               
        grades = Console.ReadLine();

        //Outputs
        Console.WriteLine(firstName); 
        Console.WriteLine(lastName);
        Console.WriteLine(points);
        Console.WriteLine(percent.ToString("P"));
        Console.WriteLine("so they made an" + grades);

        //Closing statement
        Console.WriteLine("Goodbye");
        Environment.Exit(1);
    }
}

}

Try - Catch in if - else if instruction

I was able to implement the function of the try - catch for the variable choice and it works great. I have a problem with variable stopnie. I want to check if this is numerical value. I tried to throw it in the try catch, unfortunately without success

class Task {

public static void main(String[] args) {
    Scanner user_input = new Scanner (System.in);
    System.out.println("Pick 1 to convert Fahrenheit to Celsius");
    System.out.println("Pick 2 to convert Ceslius to Fahrenheit");
    int choice = 0;
    double stopnie = 0.0;
    double convert = 0.0;
    DecimalFormat df = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
    boolean loop = true;

while (loop) 
{
    try 
    {
        choice = user_input.nextInt();
        loop = false;
    } 
    catch (Exception e) 
    {
        System.out.println("Bad value");
        System.out.println("Try again");
        user_input.next();

    }
}

    if(choice == 1) 
    { 
        System.out.println("Let me know Celsius value");
        stopnie = user_input.nextDouble();
        convert = stopnie/1.8-35;
        System.out.println(stopnie + " C " + " = " + df.format(convert) + " F");
    }

    else if (choice == 2) 
    {
        System.out.println("Let me know Fahrenheit value");
        stopnie = user_input.nextDouble();
        convert = stopnie*1.8+35;
        System.out.println(stopnie + " F " + " = " + convert + " C");

    }

    else 
    {
        System.out.println("Bad value");
    }

}   

}

List.Contains always returning false

I am trying to implement a really basic A* implementation.

I have a 'completed' list that contains coordinates of all previously assessed nodes.

For the sake of argument, lets say I am trying to get from (1,0) to (3,0).

After the third iteration, my 'completed' list contains (1,0) and (2,0). It is currently assessing all of the neighbours around 2,0. This includes the already assessed (1,0).

When calling completed.Contains(neighbour), where neighbour = (1,0) it should return true. However it somehow does not meet the condition. Thus creating a duplicate node and assesses in an infinite loop.

The below is an example in code of what is happening. Point = Simple object containing an X and Y.

point1 = new Point(1,0);
point2 = new Point(2,0);
neighbour = point1;

var completed = new List<Point>();
completed.Add(point1);
completed.Add(point2);

if(completed.Contains(neighbour))
{
     // Do something. (In my code, this should break a loop, so...)
     continue;
}
// However, this is happening instead...
if(!completed.Contains(neighbour))
{
    // Adds to the list of the next node to be worked on. Thus creating a loop.
}

There are more conditions on these if's in my actual code, but for arguments sake and for my sanity I have made them basic as above, to no avail. I'm not sure why it cannot see the existing value. Is it because I am not looking at the values themselves, but just the index? (Therefore 1,0 never exists)?

combine sprintf with IF condition

I'm stuck with a stupid problem. I was asked to arrange some changes in a php website template. So here is the code for the header/hyperlink:

<?php the_title( sprintf( '<h1 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h1>' ); ?>

And this should be combined with:

<?php if( in_category('local-msr') ) { echo 'target="_blank" '; } ?>

I have tried something like this:

<?php the_title( sprintf( '<h1 class="entry-title"><a href="%s" rel="bookmark" if( in_category('local-msr') ), echo 'target="_blank">', esc_url( get_permalink() ) ), '</a></h1>' ); ?>

But without succes.

Any ideas on how to make this work? Thanks!

if stantement is not working properly with an and comparision between a string and a dictionary

Should Return True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False.

def is_valid_word(word, hand, word_list):
### word = string, hand = dictionary, word_list = string
   count = 0
   for letter in word:
       if letter in hand and word_list:
           count += 1
   if count == len(word):
       return True
   else:
       return False


is_valid_word('star', {'a': 0, 's': 3, 'i': 0, 'e': 1, 'l': 1, 't': 3,'r':1}, 'sctdahr') ##returns true
is_valid_word('star', {'i': 0, 'e': 1, 'l': 1, 't': 3,'r':1}, 'sctdahr') ###returns false
is_valid_word('star', {'a': 0, 's': 3, 'i': 0, 'e': 1, 'l': 1, 't': 3,'r':1}, 'sc') ###returns true

Why the last statement is returning True instead of False?

Using a while loop on a query

I have the following query, but my problem is the following:

 $insert_email = "select * from customers";
$run_email = mysqli_query($con, $insert_email);

$find_email = mysqli_fetch_array($run_email);
$demail = $find_email['customer_email'];

echo $demail;

My problem is that at its current state it only returns the first item in this customers table, I would want it to return all of the customer_email in that row and not just the first one.

This is because I would later want to compare it

if($email!= $demail){

where if the email entered by the user during registration is found in the database than I will tell the user the email is already in use by throwing in an else statement.

Why is my if/else statement always skipping to the else

I have tried reading this every way I can think of and for the life of me I can't figure out why the if/else statement in the actionlistener will never evaluate the if statement to true. This program is meant to open a JFrame with 3 panels. 2 of them have 8 Random buttons with letters on them. When a button is clicked it is supposed to say if it's a vowel or a consonant. However my program always evaluates the button to a consonant. Where am I not seeing the logical flow of info in the program?

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;


public class JVowelConsenant extends JFrame {

private JPanel contentPane;
ArrayList list = new ArrayList(0);



/**
 * Launch the application.
 */
public static void main(String[] args) {

            try {
                JVowelConsenant frame = new JVowelConsenant();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


/**
 * Create the frame.
 */
public JVowelConsenant() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 585, 371);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));

    JPanel panel = new JPanel();
    contentPane.add(panel);
    panel.setLayout(new GridLayout(2, 2, 0, 0));

    JPanel panel_1 = new JPanel();
    contentPane.add(panel_1);
    panel_1.setLayout(new GridLayout(2, 2, 0, 0));

    JPanel panel_2 = new JPanel();
    contentPane.add(panel_2);
    panel_2.setLayout(new GridLayout(2, 2, 0, 0));

    String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

    JButton[] letters = new JButton[26];
    for(int i = 0; i<8; i++){

        random_Letters();
        }



     for( int i = 0; i<26; ++i){
        letters[i] = new JButton();
        letters[i].setText(alphabet[i]);


        letters[i].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) { 
                    if(arg0.getSource().equals("A")||arg0.getSource().equals("E")|| arg0.getSource().equals("I")||arg0.getSource().equals("O")||arg0.getSource().equals("U")){
                        JLabel letter_identity = new JLabel("This letter is a Vowel");
                        panel_2.removeAll();
                        panel_2.add(letter_identity);
                        panel_2.revalidate();
                    }
                    else{
                        JLabel letter_identity = new JLabel("This letter is a Consenant");
                        panel_2.removeAll();
                        panel_2.add(letter_identity);
                        panel_2.revalidate();
                    }

            }
        });
    }


    for(int i = 0; i<4;++i){
    panel.add(letters[(int) list.get(i)]);
    panel_1.add(letters[(int) list.get(i+4)]);
    }

}

void random_Letters(){
    Random random = new Random();
    int random_1 = random.nextInt(26);
    int check_point =exclusion(random_1);
    while(check_point == 0){
        random_1= random.nextInt(26);
        check_point = exclusion(random_1);
    }
}

int exclusion(int x){
    int marker = 0;
    if(!list.contains(x)){
        list.add(x);
        marker = 1;
    }
    return marker;


}

}

IF Statement manipulates variable without writing to it

I hope the Arduino Experts can help me with my Problem.

I have a Gesture, Color, Proximity and Light Sensor (All in One) connected to an Arduino UNO. I am trying to change the Gain of Gesture Sensing depending on the Proximity Value. Everything works perfectly fine if i don't use the if statement which checks and compare the current proximity value stored in a variable. The If Statement is never supposed to write or anyhow change the variable as it ONLY reads from it but exactly that seems to happen here.

This is the complete Code:

#include <I2C.h>

uint8_t prox;
uint8_t gain;

void setup() {
  Serial.begin(9600);
  I2c.begin();
  I2c.setSpeed(1);
  I2c.pullup(1);
  tmginit();
}

void tmginit() {
  prox = 0;
  gain = 1;
  I2c.write(57, 128, 69);  //0x80 Gesture, Proximity and Power enabled
  I2c.write(57, 171, 3);   //0xAB Hardware interrupt and gmode enabled
  I2c.write(57, 142, 224); //0x8E PPLEN 32µs
  I2c.write(57, 143, 0);   //0x8F LDRIVE 100% Mode
  I2c.write(57, 144, 16);  //0x90 LEDBOOST 300% and 2x prox gain
  I2c.write(57, 160, 0);   //0xA0 Gesture Proximity Entry Threshold set to 0
  I2c.write(57, 161, 255); //0xA1 Gesture Exit Threshold set to maximum
  I2c.write(57, 163, 0);   //0xA3 Gain set to 4x
  I2c.write(57, 164, 2);   //0xA4 Gesture North Offset
  I2c.write(57, 165, 1);   //0xA5 Gesture South Offset
  I2c.write(57, 166, 224); //0xA6 Gesture PWM Length set to 32µs
  I2c.write(57, 167, 1);   //0xA7 Gesture West Offset
  I2c.write(57, 169, 2);   //0xA9 Gesture East Offset
}

void loop() {

  prox = 0;
  Serial.println();
  I2c.read(57, 156, 1); // Proximity Value
  prox = I2c.receive();
  Serial.println("PROX:");
  Serial.println(prox);

  if ((prox >= 225) && (gain != 1))
  {

    I2c.write(57, 163, 0);
    gain = 1;

  }

  else if ((prox >= 100) && (prox < 225) && (gain != 2))
  {

    I2c.write(57, 163, 32);
    gain = 2;

  }

  else if ((prox >= 30) && (prox < 100) && (gain != 4))
  {

    I2c.write(57, 163, 64);
    gain = 4;

  }

  else if ((prox >= 0) && (prox < 30) && (gain != 8))
  {

    I2c.write(57, 163, 96);
    gain = 8;

  }

  Serial.println();
  Serial.println("GAIN:");
  Serial.println(gain);
  Serial.println();


  I2c.read(57, 252, 1); //FIFO N

  Serial.println(I2c.receive(), DEC);
  I2c.read(57, 253, 1); //FIFO S

  Serial.println(I2c.receive(), DEC);
  I2c.read(57, 254, 1); //FIFO W

  Serial.println(I2c.receive(), DEC);
  I2c.read(57, 255, 1); //FIFO E

  Serial.println(I2c.receive(), DEC);

  delay(500);


}

The Proximity Value outputs really strange values if i have the if and else if block actively running. But when I comment the complete if and else if Block out, everything runs perfectly. The Proximity Value changes when i come near the sensor or when i go away from the sensor.

Example:

I am very close to the Sensor. The Proximity Value is somewhere between 200 and 255 (255 is max). This is the correct behaviour.

Now i activate the if and else if block and do the same thing again

I am very close to the Sensor. The Proximity Value is somewhere between 5 and 10 (255 is max)

Only the very first read WITH if and else is correct. From then on all this weird stuff starts to happen.

Please help!

Thank You.

samedi 30 mai 2015

IF Condition (Excel) - Join Multiple Columns

I need to tally the number of times a term appears.

Unfortunately, the terms were not well organized so a term may appear in more than one column - so I can't use just =If(A1="HEALTH",1,0) because "HEALTH" appears in multiple columns A, B, C etc.

I've tried nesting - =IF(A1="HEALTH",1,IF(B2="HEALTH",1,0)) - but haven't had much success there either.

Maybe my formula's wrong? Or should I look to a different condition in Excel and if so, which?

Thanks in advance for your help.

Cheers,

Sam

else if function and arrays

I am trying to make a simple prompt function in javascript that will allow for two responses that both refer to separate arrays but when I open up the javascript document in console log, the only array that is recognized is the one for when the user inputs "no" in to the prompt box. And regardless of whether the user inputs "yes" or neither "yes" nor "no", the console log only refers to theKicker array and only prints out strings from theKicker. It won't print out strings from fieldGoal, neither will it print out "that's not the way! try again!" when the user inputs something that is neither "yes" or "no" in to the prompt box. Here is the code:

var arrayWoes= ["Ah what a buzzkill", "How dare you", "You are the worst", "I fart in your general direction", "How about you get out of town"];
var arrayYes= ["You marvelous user", "You must be pretty great. Welcome to   the fold.", "You are true of heart and steady of mind", "You're just a good one,   aren't you?"];
var theKicker= arrayWoes[Math.floor(Math.random() * (arrayWoes.length))];
var fieldGoal= arrayYes[Math.floor(Math.random() * (arrayYes.length))];
var select= prompt("Ready for an adventure?");
if(select= "no") {
    console.log(theKicker);

}
else if(select= "yes") {
    console.log(fieldGoal);

}
else {
    console.log("That's not the way! Try again!");

   }

I have combed over the code over and over again and tried to see if any errors existed and I looked over several sites (including the work I have been doing at Code Academy, w3schools, stack overflow forums, ect.) but I couldn't find anything that referred to my specific issue. Any help is appreciated.

Trouble in a program to convert between currencies in C++

I've made a simple program in C++ to convert between currencies, as part of a lesson. It asks for a numerical value and then a letter (y, e or p) to represent one of the supported currencies. When using 'y' or 'p' you can input the numerical value and character together or separated by a space (ie: "100y" or "100 y") and it'll work fine. However, for the letter 'e' only, if I enter both together, it doesn't recognize as a valid input. Does anyone have any idea why?

Here's the code:

#include <iostream>

int main()
{
using namespace std;
constexpr double yen_to_dollar = 0.0081;    // number of yens in a dollar
constexpr double euro_to_dollar = 1.09;     // number of euros in a dollar
constexpr double pound_to_dollar = 1.54;    // number of pounds in a dollar

double money = 0;                           // amount of money on target currency
char currency = 0;
cout << "Please enter a quantity followed by a currency (y, e or p): " << endl;
cin >> money >> currency;

if(currency == 'y')
    cout << money << "yen == " << yen_to_dollar*money << "dollars." << endl;
else if(currency == 'e')
    cout << money << "euros == " << money*euro_to_dollar << "dollars." << endl;
else if(currency == 'p')
    cout << money << "pounds == " << money*pound_to_dollar << "dollars." << endl;
else
    cout << "Sorry, currency " << currency << " not supported." << endl;

return 0;
}

Mastermind game if statement problems

I am trying to make it so when two or more of my if statements work they dont both print instead they just say two are in the correct spot or more it more works. Im not sure if im suppose to make more if statements of if i am suppose to use another statement or a forloop.

               //If Statements
                if (Gameboard[0] == Secret_code[0]) {
                    System.out.println ("You have one in the correct spot");
    } 
                if (Gameboard[1] == Secret_code[1]) {
                    System.out.println ("You have one in the correct spot");
    }
                if (Gameboard[2] == Secret_code[2]) {
                    System.out.println ("You have one in the correct spot");
    }
                if (Gameboard[3] == Secret_code[3]) {
                    System.out.println ("You have one in the correct spot");
    }

}
}

invalid sql statement when writing if clause in a trigger

i am new to writing sql statements. I am trying to write a trigger on a table after insert. The original functionality of the trigger is very lengthy. However just at the beginning i am getting compilation error for invalid sql statement. the code segment is mentioned below drop trigger bill_update;

create or replace trigger bill_update
after insert on SingleFoodOrder
for each row
declare
f_price number;
old_bill   number;
f_quantity     number;
p_bill  number;
foodID number;
orderID number;
order_date Date;
s_date Date;
f_date Date;
f_dis  number;
a number;
b number;
c number;
BEGIN
        if :new.Order_ID is not NULL THEN
                   foodID := :new.Fooditem_ID;
                   orderID := :new.Order_ID;
                   f_quantity := :new.Quantity;
        end if;
end;
/

This code is for the simplicity's sake for the error. If i remove the if,end if part then it compiles with no error. But adding the if part gives the error. I have order_id collumn in the singlefoodorder table which can be set to null just to make clear. Where is the problem?

Swift check if multiple strings are empty throws "Could not find overload for '||' that accepts the supplied arguments"

In the following class:

class User{
    var _id: String?
    var _enabled: Bool?
    var _username: String?
    var _email: String?

    func create(callback: ((error: Bool, message: String?, json: JSON?, user: User?)->Void)?) -> Void{

        // Check the required attributes are filled
        if (_username.isEmpty || _email.isEmpty || _enabled.isEmpty){
            // Do stuff to say error
        }else{
            // Do stuff to say success
        }

    }

}

The if statement throws a compile error of "Could not find overload for '||' that accepts the supplied arguments".

Why is Swift acting like this and how else can you check to see if one or more of multiple strings are empty without using a for loop?

C# Speech Recognition Searching Google

I've been working on an AI in C# for a while now and I finally figured out how to add part of the speech as a variable. However the problem I'm having now is it's running everything I say and searching google. I only want it to start the search if I start off by saying "Google". What should I be doing differently?

Here's a little bit of the code I have right now:

How can I change this so it only searches when I start off by saying Google and I'm still able to run my other commands from the text file??

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //Load Grammar
        GrammarBuilder gBuilder = new GrammarBuilder();
        gBuilder.Append(new Choices(System.IO.File.ReadAllLines(@"C:\Users\ThatOneCodeNoob\Desktop\EVA 1.0\Commands.txt")));
        Grammar grammar = new Grammar(gBuilder);
        DictationGrammar dictation = new DictationGrammar();
        gBuilder.AppendDictation("google");

        recEngine.LoadGrammarAsync(grammar);
        recEngine.LoadGrammarAsync(dictation);
        recEngine.SetInputToDefaultAudioDevice();
        recEngine.RecognizeAsync(RecognizeMode.Multiple);
        recEngine.SpeechRecognized += recEngine_SpeechRecognized;
        sSynth.Speak("EVA, online");
    }

    //Speech Recognized
    void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        if (e.Result.Text.StartsWith("google")) ;
        {
            string query = e.Result.Text.Replace("google", "");
            System.Diagnostics.Process.Start("http://ift.tt/1pUWlSX" + query);
            return;
        }
        switch (e.Result.Text)
        {

               //Open Commands
            case "open facebook":
                sSynth.Speak("Opening facebook for you now");
                System.Diagnostics.Process.Start("http://ift.tt/g8FRpY");
                break;

            case "open pandora":
                sSynth.Speak("Opening Pandora for you");
                System.Diagnostics.Process.Start("http://www.pandora.com/");
                break;

            case "open youtube":
                sSynth.Speak("Loading YouTube now");
                System.Diagnostics.Process.Start("http://www.youtube.com/");
                break;

            case "open google chrome":
                System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
                sSynth.Speak("starting chrome for you");
                break;

            case "minimize":
                try
                {
                    sSynth.Speak("minimizing");
                    ActiveForm.WindowState = FormWindowState.Minimized;
                    break;
                }
                catch
                {
                    sSynth.Speak("I can't minimize this window sir");
                    break;
                }

                //Date/Time Commands

            case "whats the time":
            case "what time is it":
                sSynth.Speak(DateTime.Now.ToShortTimeString());
                break;

            case "what day is it":
                sSynth.Speak(DateTime.Now.ToString("dddd"));
                break;

            case "whats today":
                sSynth.Speak(DateTime.Now.ToLongDateString());
                break;

            case "whats todays date":
            case "whats the date":
                sSynth.Speak(DateTime.Now.ToString("dd/M/yyyy"));
                break;

                //Social Commands

            case "thanks":
            case "thank you":
                {
                    sSynth.Speak("You're welcome");
                    break;
                }

            case "goodbye":
                sSynth.Speak("goodbye for now sir");
                Application.Exit();
                break;

            case"eva":
                sSynth.Speak("yes sir");
                break;

                //Offline & Online

            case "go offline":
                sSynth.Speak("I will await further orders");
                GoOffline();
                break;

            case"wake up":
            case"come back":
            case "come online":
                ComeOnline();
                break;

        }

    }

IF operations on variables

I'm building a script in bash for use on Linux (SLES 11SP3). I'd like to check whether a certain process exists by looking up it's pid using this syntax:

pid="$(ps -ef | grep -v grep | grep /sbin/syslog-ng | awk '{print $2}')"

This fills variable pid with the pid of the syslog-ng process. Then I want to use this variable in an if statement:

if [ ${pid} > 0 ]; then
  do something
else
  do something else
fi

The problem is that this if statement seems to always be false, even if the variable pid has a value higher than 0. So, the else part is always executed instead of the correct (if condition is true) statement.

I had a similar issue with the use of wc -l to check the existence of filesystems:

exist_tmp=$(df -x fuse.gvfs-fuse-daemon -h | grep /tmp | wc -l)
if [ ${exist_tmp} > 0 ]; then
  do something
fi

This would not work, even if the variable has a value of 1, indicating the existence of a /tmp filesystem. It started working (or at least doing what I wanted it to do), when I changed the syntax to this:

if [ ${exist_tmp} != 0 ]; then
  do something
fi

The difference between greater than 0 and not equal to 0 eludes me a bit in this used case.

The questions therefor are:

  1. Does anybody have an idea why the pid lookup and if statement won't do what I want it to do?
  2. Does anybody have an idea what the problem with the > 0 and != 0 might have been?

Any input is greatly appreciated!

Not going into if statement if object is found

I'm trying to display a result in a textbox if a book is found. The thing is that the book is stored and is in a list, but the code won't execute that the book is found. Instead it's displaying that the book is not found. Can anyone help out pls? Thanks

 Resource found = new Library().binarySearch(txtTitle.Text);

        if(found != null)
        {
           txtResult.Text = found.ToString();
        }
        else
        {
            txtResult.Text = "Item not found";
        }

vendredi 29 mai 2015

Java: values are the same but if statement to check if they're equal won't work?

i'm trying to see if two Song() objects are the same to eventually throw a duplicate song entry Exception but i've encountered some troubles. The if statement to check if they're equal just does not want to accept them as equal. I made the console print their values on each song entry as a test and they were printing as the same but the if statement was not initializing. Here is my code:

            case 1: //ENTER A SONG TO DATABASE

            try {
            Song newSong = enterSong();
            int logSize = database.getLogicalSize();
            if (logSize>0){
                System.out.println(newSong.getName() + " " + database.getSongName(0));
                if (newSong == database.getSong(0)){
                   throw new Exception("Exception: duplicate song entry!");
    }
    }
                database.addSong(newSong);
            }
            catch (Exception e){
                System.out.println(e.getMessage());
            }

            break;

Multiple same values in Column A, need to find the greater date in column B

I'm stumped on a particular problem with some data that's imported to me. I have zero control over how the data is coming in. (Just to clarify that point).

I have two columns and 107,000 rows.

Column A has an ID#, Column B has the corresponding Date.

The issue I have is that Column A can have multiple identical values, and the corresponding date value in Column B has different or same dates.

I'm looking to add column C with a way to look up the cell in Column A, check it against the rest of column A, find any matches, and then return the Max/most recent date from column B for that ID#.

If-statement invalid syntax, but syntax is fine

if screen[v2, v1] == 1: if number > 3: screen_b[v2, v1] = 0 elif screen[v2, v1 == 0: if number < 2: screen_b[v2, v1] = 1

I keep getting an error on the "if number < 2:" line. I have stared at it for like 10 minutes and looked all over the place for a solution, but alas i have to rely on this.

Program does not enter if statement

So I have a mistake detection program that should detect a "mistake" if the current word (String cWrd) is not contained in a static array (passed as a parameter). If the word is not found in the array, "boolean found" remains false and a JLabel is set to "wrong category" for some period of time. However, the method does not appear to execute even when cWrd is not contained within the array.

CODE:

//Mistake method

public void mistake(String[] arr)

{
        int i = 0;
        boolean found = false;
        while (i < arr.length && found == false)
        {
            if (arr[i].equals(cWrd))
            {
                found = true;
            }
            i++;
        }
        if (found = false)     //The program never enters this if statement
        {
        lmid.setText("Wrong Category!");
        try {
            t1.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }


}

I am getting an else without if error and I don't understand why - JAVA

public class ProblemFour

{

    public static void main(String[] args)
    {

            boolean externalCheck = true;
            boolean internalCheck = true;
            String Str = new String();
            int prod = 0;
            int mod = 0;

                    while (externalCheck == true){

                            for (int a = 999; a>99; a--){
                                    for(int b = 999; b>99; b--){
                                            prod = a*b;
                                            Str = Integer.toString(c);

                                                    if (internalCheck == true && mod < Str.length()/2){

                                                            if (c%2 ==0){
                                                                    for(int i =0; i<Str.length(); i++){
                                                                            if(Str.substring(i) != Str.substring(Str.length()-1)){
                                                                                    internalCheck = false;
                                                                            }
                                                                            else{
                                                                                    mod++;
                                                                            }
                                                                    }
                                                            else{
                                                                    String S= Str.substring(0,(Str.length()-1)/2) + Str.substring(Str.length()/2, Str.length());

                                                                            for(int i =0; i<S.length(); i++){
                                                                                    if(S.substring(i) != Str.substring(S.length()-1)){
                                                                                             internalCheck = false;
                                                                                    }
                                                                                    else{
                                                                                            mod++;
                                                                                    }
                                                                            }
                                                            }

                                                    }
                                                    else {
                                                            return Str;
                                                            System.out.println(Str);
                                                            externalCheck = false;
                                                    }

I am getting an error that says I have an else without and if and I don't understand where this is coming from. Specifically on line 31. What more detail do i need. is this not enough detail

Debugging Conway's Game of Life Graphics?

I am trying to make a simple version of Conway's Game of Life where the computer generates a grid of rectangles and fills in the rectangles that represent "live" cells. The problem I am having is that I cannot get the grid to clear after the first pattern, so all the patterns are generated on the same grid and it looks like a big blob of colored rectangles.

Here is my code:

public class GameofLife {
static JPanel panel;
static JFrame frame;
public static void main(String[] args) throws InterruptedException{
    int [][] array = new int [17][17];
    /*
     * Set the pattern for Conway's Game of Life by manipulating the array below.
     */
    array[2][4]=1;
    array[2][5]=1;
    array[2][6]=1;
    panel = new JPanel();
    Dimension dim = new Dimension(400,400);
            panel.setPreferredSize(dim);
    frame = new JFrame();
    frame.setSize(1000, 500);
    Container contentPane =    frame.getContentPane();
    contentPane.add(panel);
    frame.setVisible(true);
    /*
    * Runs the Game of Life simulation "a" number of times.
    */
    int [][] end = new int [array.length][array[0].length];
    int a=0;
    while(a<4){
        for(int i=1; i<=array.length-2; i++)
        {
            for(int j=1; j<=array[0].length-2; j++)
            {
                int counter = surround(array,i,j);
                if(array[i][j]==1 && counter<=2)
                {
                    end[i][j]=0;
                }
                if(array[i][j]==1 && counter==3)
                {
                    end[i][j]=1;
                }
                if(array[i][j]==1 && counter>4)
                {
                    end[i][j]=0;
                }
                if(array[i][j]==0 && counter==3)
                {
                    end[i][j]=1;
                }
                if(array[i][j]==1 && counter==4)
                {
                    end[i][j]=1;
                }
            }
        }
        Graphics g = panel.getGraphics();
        Graphics(array,g);
        a++;
        for(int i=0; i<array.length; i++)
        {
            for(int j=0; j<array[0].length; j++)
            {
                array[i][j]=end[i][j];
                end[i][j]=0;
            }
        }
        Thread.sleep(1000);
        g.dispose();
    }
}

    public static int surround(int[][] initial, int i, int j){
    int[][] surrounding = {{initial[i-1][j-1],initial[i-1][j],initial[i-1][j+1]},
            {initial[i][j-1],initial[i][j],initial[i][j+1]},
            {initial[i+1][j-1],initial[i+1][j],initial[i+1][j+1]}};
    int counter = 0;
    for(int a=0; a<=2; a++)
    {
        for(int b=0; b<=2; b++)
        {
            if(surrounding[a][b]==1)
            {
                counter ++;
            }
        }
    }
    return counter;
}

    public static void Graphics(int[][] array, Graphics g)
{
    int BOX_DIM=10;
    for(int i=0; i<array.length; i++)
    {
        for(int j=0; j<array[0].length; j++)
        {
                g.drawRect(i*BOX_DIM, j*BOX_DIM, 10,10);
                g.setColor(Color.BLACK);
                if(array[i][j]==1)
                {
                    g.fillRect(i*BOX_DIM, j*BOX_DIM, 10, 10);   
                }
        }
    }

}

}

Any help is much appreciated!

How to check if variable is an empty Object {}? [duplicate]

This question already has an answer here:

enter image description here

function setUserName() {
    var usr = AuthService.getUser();

    if (typeof usr !== "undefined") {
        vs.user = usr;
    } else {
        vs.user = 'Settings';
    }

    // if (usr.username === undefined && usr.username === null) {
    //     vs.user = 'Settings';
    // } else {
    //     vs.user = usr;
    // }

    console.log(usr);
}

In my code above usr is currently an empty Object {} how should this check be written so that it skips down to the else and set vs.user to 'Settings'?

Python what is wrong with my if statement? (raw_input)

What I want to check for is if the user input is an empty string. I want the code to execute and output: "No input", however whenever I enter no input it goes to the next if statement and executes that with a blank value.

import urllib
import re 
myString = " "
i = 0

def getStockPrice():
    text_file = open("data.txt", "w")
    url = "http://ift.tt/Jz88mB" + symbolslist
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()

    regex = '<span id="yfs_l84_' + symbolslist+ '">(.+?)</span>'
    pattern = re.compile(regex)

    price = re.findall(pattern,htmltext)
    if str(price) == myString:
        print "No input"
    else:
        print "the price of", symbolslist," is ", price
        text_file.write(str(price))
        text_file.close()




dino = raw_input("What stock would you like to Check?: ")
symbolslist = dino
getStockPrice()

while i < 1000:
    lilly = raw_input("What other stocks do you want to check?: ")
    symbolslist = lilly
    getStockPrice()

Is there a difference between "if not x in mylist:" and "if x not in mylist:" [duplicate]

This question already has an answer here:

Is there any difference between the two?

t = [1,2,3,4]
if 5 not in t:
    print "ok"
if not 5 in t:
    print "ok"

ok
ok

Can I synchronize reads of control variables?

The following code will work, but I slightly resent having to write the isRunning() method:

class Test {
    private boolean running;
    public void startX() {
        synchronized(this) {
            running = true
        }
        while (isRunning()) {
            //do something
        }
    }
    public synchronized void stopX() {
        running = false;
    }
    private synchronized boolean isRunning() {
        return running;
    }
}

Can I synchronize reads of the running variable in the while (running){} in some other way, or do I have to write the isRunning() method? The same question applies to other control variables as well, eg

for (;running;) {}

or

if (running) {}

In all of these cases it seems as though you're forced into writing a pointless method to get the synchronization correct. Am I missing something?

If/else statement: Search through multiple possible values only finds last value (javascript)

I have a form with various inputs to search an address. Only the province and postal code first appear when you load the page, but there is the option to open a toggle to display more options such as street name etc. Basically, what I'm trying to achieve is for the toggle to remain open when the page loads again if the select and text inputs are not empty ('' and 0).

I have most of the logic down, but my problem is that my if/else statement is only looking at the last value it is getting.

var allInputsValue;
var allInputs; //for testing purposes

$('.address-options').each(
    function(){
        allInputs = $(this); //for testing purposes
        allInputsValue = $(this).val();
        //console.log('Type: ' + allInputs.attr('type') + ' Name: ' + allInputs.attr('name') + ' Value: ' + allInputs.val());
        //console.log(' ID: ' + allInputs.attr('id') + '\n' + ' Value: ' + allInputs.val());
        console.log('Value: ' + allInputsValue);
    }
);

//if($('#civicNo').val() == '', $('#streetName').val() == ''){
if(allInputsValue === '' || allInputsValue === 0){
    alert("Empty fields");
    if (localStorage) {
        localStorage.setItem('addressOptions', 'closed');
    }
    togglePane("closed");
}else{
    alert("Fields not empty");

    if (localStorage) {
        localStorage.setItem('addressOptions', 'open');
    }
    togglePane("open");
}

I'm trying to keep the code fairly clean without having to do an else if for every input ID.

In the console log I get back all the correct values I am looking for. What am I missing?

Comparing strings of text files

I have three text files: file1 file2 and file3 all of which contain emails. file1 is supposed to have all the emails in there, file2 has all emails that are A-M, and file 3 have emails from n-z (This is not important but I figure it would help give a little context.)

I am writing a console application program in c# that will look at these three files, and if there is an email that is not 1 that where it should be, then it will write to a masterfile that will say what needs to be added to what.

For example, lets say I have the email ill27@hotmail.com (this is not my email it is just an example.) If it is found in file1 but not in file2, the output of the masterfile needs to be "this email needs to be added to file2: ill27@hotmail.com". Now if it was reversed, and the email was found in file2 but not in file1, then the output should be "this email needs to be added to file1: ill27@hotmail.com"

As part of my code, the answer I am looking for needs to be in some sort of foreach loop and if statements, however I am a little lost in what I need to put in. If someone could please help me in figuring out what it is I have to use in my statements I would very much appreciate it. If someone has a question about any of this please feel free to ask!

        //Making a list for file1
        List<string> listFullPack = new List<string>();
        string line;
        StreamReader sr = new StreamReader("file1");
        while ((line = sr.ReadLine()) != null)
        {
            listFile1.Add(line);
        }
        sr.Close();

        //Making a list for file2
        List<string> listDen1 = new List<string>();
        string line1;

        StreamReader sr1 = new StreamReader("file2");
        while ((line1 = sr1.ReadLine()) != null)
        {
            listFile2.Add(line1);
        }
        sr1.Close();

        //Making a list for file3
        List<string> listDen2 = new List<string>();
        string line2;

        StreamReader sr2 = new StreamReader("file3");
        while ((line2 = sr2.ReadLine()) != null)
        {
            listFile3.Add(line2);
        }
        sr2.Close();


        //This will double check that emails are in
        foreach (string element in listFullPack)
        {
            System.Console.WriteLine(element);
            Debug.WriteLine(element);

            if (element == "jimbob@hotmail.com")
            {

                Debugger.Break();
            }

        }

        //this will compare the file1 list to the file2 list
        var firstNotSecond = listFile1.Except(listFile2).ToList();
        var secondNotFirst = listFile2.Except(listFile1).ToList();

        //this will compare the file2 list to the file3 list
        var firstNotThird = listFile1.Except(listFile3).ToList();
        var thirdNotFirst = listFile3.Except(listFile1).ToList();

        //this will compare the file2 list to the file3 list
        var secondNotThird = listFile2.Except(listFile3).ToList();
        var thirdNotSecond = listFile3.Except(listFile2).ToList();

        foreach (string element in listFile1) // This is where I am lost

        {

            if (!)
            {

            }
        }


    }
}
        }

Scheme several actions if an if-statement proves true

The way I understand a scheme if-statement is that the first condition is when the if-statement is true, and the second statement is when it is false. What if I want several conditions for when the statement proves true?

An example:

(if (= a b)
    (set! ([a 2]))  // This shall happen when true
    (set! ([b 4]))  // This shall happen when true

    (set! ([a b])) // This shall happen when NOT true

Is it possible to do something like that?

If cell = #N/A, use another vlookup

I have this Excel VBA macro which runs really well

    Sub PCMSLookupTool()
    Dim LastRow As Long
    With Sheets("Lookup Tools")   '<-set this worksheet reference properly
        LastRow = .Range("A" & Cells.Rows.Count).End(xlUp).Row
        With .Range("J10:J" & LastRow)
          .Formula = "=VLOOKUP(A10, 'PCMS-dump'!A:B, 2, FALSE)"
          .Cells = .Value2
        End With
    End With
End Sub

But I need to make it so if it does not find a value (returns #N/A) to run another vlookup ("=VLOOKUP(A10, 'Imported in PCMS'!A:C, 3, FALSE)"

How would I go about to do this?

if and else if do the same thing

I'm trying to refactor an if-else chain that doesn't look particularly good. My common sense is telling me that I should be able to call my method only once but I can't figure out an elegant way to do it. Currently what I have is:

if(condition1)
  do method1;
else if(condition2)
  do method1;

Which looks hideous. There's repeat code! The best I can come up with is:

if(condition1 || (!condition1 && condition2))
  do method1;

But this also looks bad, since I'm negating condition1 after the or, which seems unnecessary...

I made a truth table for this thinking it was maybe the case for a specific operator like xor but I don't know of any operators that deal with this:

 c1| c2| r
 0 | 0 | 1
 0 | 1 | 1
 1 | 0 | 0
 1 | 1 | 1

And in case anyone is interested, the real-life problem I'm having is that I got 2 intances of Fancytree in javascript and I want to set some rules to transferring nodes between them. Tree A can only transfer lone nodes to Tree B, while Tree B can reorder itself freely, so I put this on Tree B's dragDrop event:

if(data.otherNode.tree === node.tree){ 
  data.otherNode.moveTo(node, data.hitMode);
}
else if(!data.otherNode.hasChildren()){
  data.otherNode.moveTo(node, data.hitMode);              
}

SSIS If String Isn't Present, Redirect Records

I'm using SSIS 2008 R2 and I'm trying to figure out the right components to check if one of two strings are present within a string. If so a boolean value should be assigned. If neither are present, the package should redirect the records to a different component.

I've tried using a derived column to do this but am struggling to check for two strings. So far I've used the expression:

(FINDSTRING(fixed_notes,"no answer",1) > 0) ? (DT_BOOL) FALSE : (DT_BOOL) TRUE 

This will not do though as I need to assign TRUE if fixed_notes contains answered, False if fixed_notes contains no answer and finally redirect any records that contain neither answered or no answer.

Could anyone help with how to achieve this?

Removing ifs based on type and list of parameters

I will to refactor following recursive method:

public static void Initialize(Control control, DocumentContainer container, ErrorProvider provider)
        {
            if (control == null)
            {
                return;
            }

            var controlWithTextBase = control as IControlWithText;
            if (controlWithTextBase != null)
            {
               controlWithTextBase.DocumentLoaded = true;
               controlWithTextBase.Initialize(container, provider);
            }

            var custom = control as CustomCheckbox;
            if (custom != null)
            {
                custom.DocumentLoaded = true;
                custom.Initialize(container);
            }

            foreach (Control subControl in control.Controls)
            {
                Initialize(subControl, container, provider);
            }
        }

As you can see, depends on type of winforms control this code initialize a control. It starts with main form, and this contains custom controls(IControlWithText,CustomCheckbox) and default winforms forms. I would create 3 Initializators and to every a method CanInitialize depending on type of a control, but even then I have no idea how can I skip those "ifs", which I need to know if I need send this ErrorProvider to method Initialize.

I would be very grateful for your help!

Issues with PHP IF statements

I'm having a weird issue with 2 pages of mine, that employ somewhat of an improvised Captcha code validation.

The Captcha consists of only 5 different images, called captcha1.jpg to captcha5.jpg.

The second page in the sequence validates the captcha by using the following code:

if ($_SESSION['image'] = "captcha1.jpg") {

 if ($_POST['captcha'] == "634K6") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

if ($_POST['captcha'] == "634k6") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

else {

header('Location: step1_captcha_redo.php');
die();

}

}



if ($_SESSION['image'] = "captcha2.jpg") {

 if ($_POST['captcha'] == "4eT99") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

if ($_POST['captcha'] == "4et99") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

else {

header('Location: step1_captcha_redo.php');
die();

}

}



if ($_SESSION['image'] = "captcha3.jpg") {

 if ($_POST['captcha'] == "AGA2P") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

if ($_POST['captcha'] == "aga2p") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

else {

header('Location: step1_captcha_redo.php');
die();

}

}



if ($_SESSION['image'] = "captcha4.jpg") {

 if ($_POST['captcha'] == "hKYK8") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

if ($_POST['captcha'] == "hkyk8") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

else {

header('Location: step1_captcha_redo.php');
die();

}

}



if ($_SESSION['image'] = "captcha5.jpg") {

 if ($_POST['captcha'] == "NG6j5") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

if ($_POST['captcha'] == "ng6j5") {
 
 echo $contents;
 mail($to,$subject,$msg,$from);
 die();

}

else {

header('Location: step1_captcha_redo.php');
die();

}

}

$_SESSION['image'] is initialized on the first page, depending on the image that will be randomly selected - I've tested and echoed its contents multiple times, and it works just fine.

The problem I'm having here is that the only captcha code that is correctly validated, is captcha1.jpg ( the first IF statement in the list ). For some reason, all the other 4 are correctly defined, but always resolve to FALSE, even if the correct one is entered, and the ELSE statement is therefore executed.

What am I doing wrong here?

How to improve find and replace function in javascript

I've got this neat find and replace from form input function, with which You people helped me a lot. Now, I would want to improve it a bit. For time being script is taking all kind of data put into my forms - words, single characters, commas, spaces and such. I want it to take in only full words, preferably even few at a time (but not neccessarily sentences, if that makes any sense to You) and discard unwanted rest with return message of `search params invalid'. Thing is I'm just starting with JavaScript (I'm scared stiff of jQuery) and apparently got a little in over my head with it. But geting on, that's my code:

        function wordReplace()
    {
        var div = document.getElementById('main');
        var find = document.getElementById('replaced').value;
        var replace = document.getElementById('replacement').value;

        var re_Find = new RegExp(find, 'gi');
        var matches = div.innerHTML.match(new RegExp(find, 'gi'));

        if (matches) 
            {
                div.innerHTML = div.innerHTML.replace(re_Find, replace);
            }
        else if (document.getElementById('replaced').value == "")
            {

            }
            matches = matches ? matches.length : 0;
            alert("Zamieniono " + matches + " słów!");

As You can see, it takes everything and anything in now. Figured else if is a way to go, but I hit the wall since then. Any ideas what to do next?

if-else conditions depending on previous value

I want to create a vector z which contains only 1 or -1. If 1 or -1 is needed depends on the Value of RSI:

If RSI is greater than 70, z should be -1
If RSI is less than 30, z should be 1

For all other cases: z should have the same number as the previous z.
That means z = z(t-1)

RSI is a vector containing numbers between 0 and 100. So far I have used the ifelse condition.

rsi <- RSI(YENDOL, n=14)

z <- 0

z <- ifelse(rsi >= 70,-1,z)
z <- ifelse(rsi <= 30,1,z)

With this I have created a z vector containing 0, 1 and -1. The next step would be to change the zeros into 1 or -1 depending on the previous value (z t-1). That is the point where I'm stuck. I need the vector later on to multiply it with another vector.

jeudi 28 mai 2015

How if statement work in for loop

This code find the maximum element of a dynamic array

int i, n, *x, max;
    cout << "eneter a number: ";
    cin  >> n;
    x = new int[n];
    max = x[0];
    for (i = 0; i < n; i++)
    {
        if (x[i] > x[0])
            {
            max  = x[i];
            }
    }
    cout << max << endl;

    delete []x;

Let's assume my input be :

    n=4
   {3, 22, 15, 17}

So the output is 22

I don't understand how if select the 22 as max.

This is my understanding of how it works:

n=4
{3, 22, 15, 17}

x[0] = 3 
first loop i=0 -> x[0]>x[0] false

x[1] = 22
second  loop i=1 -> x[1]>x[0] true

x[2] = 15
third loop i=2 -> x[2]>x[0] true

x[3] = 17
forth loop i=3 -> x[3]>x[0] true

I know I'm wrong but as my assumption the 17 must be the maximun value. What am I missing here?

How and Why is this If condition satisfying when value is false in C#

I have this strange problem in Windows Phone Application. Hitting hardware Back button exits the application when it should have shown the previous page. While debugging, I found something really strange.

If Condition satisfied for false

In this method, this.Frame is Not null (as shown in 3rd pin) but this.Frame.CanGoBack is False (as shown in 1st pin) which means the && (Bit wise AND) operator should make this condition as false and it does (as shown in the second Pin). Still debugger stepped in the condition to execute(as you can see below second pin).

This is really strange and This only exits my application.

JavaScript "If" Statement Regarding Checkbox Not Working

I have set up an "if" statement in JavaScript that is to check whether or not a checkbox is checked. However, it does not seem to be working. It refers to a checkbox within a form, and the ID for the checkbox is "t1." Please let me know if there is anything apparent that would make it not function properly! It is to be executed when a button on the page is clicked, which should work properly without the "if" statement around it.

The code is below:

var t1v = document.getElementById("t1")

if (t1v.checked) {
    document.getElementById("l1q1").style.display = "inline";
    document.getElementById("1q1-1").style.display = "inline";
    document.getElementById("l1q1-1").style.display = "inline";
    document.getElementById("1q1-2").style.display = "inline";
    document.getElementById("l1q1-2").style.display = "inline";
    document.getElementById("1q1-3").style.display = "inline";
    document.getElementById("l1q1-3").style.display = "inline";
    document.getElementById("1q1-4").style.display = "inline";
    document.getElementById("l1q1-4").style.display = "inline";
}

Oracle Stored Procedure - How to compare type NUMBER with intergers?

I have following stored procedure. Parameter FLAG_ passed in is only allowed to accept null, 0 or 1. But the condition checking (FLAG_ != 0 OR FLAG_ != 1) doesn't work. I guess this is because type for FLAG_ is NUMBER which include float. Is there a way to compare NUMBER to INT ?

create or replace PROCEDURE "ADD_RMV_FLAG"
(
  TEXT OUT VARCHAR2 
, FLAG_ IN NUMBER -- empty, 0 and 1 only values accepted.
) AS

BEGIN
-- input pramameters checking
IF FLAG_ is not null
THEN
   IF (FLAG_ is not null AND (FLAG_ != 0 OR FLAG_ != 1))
   THEN
     raise_application_error(-20001, 'ERROR: only empty, 0 or 1 is accepted   
     for FLAG. Passed in ' || FLAG_);
   END IF;
 END IF;
END ADD_RMV_FLAE

USING IF with UPDATE MYSQL

Im trying to do an update with a IF function

IF(SELECT 'FUNCION' FROM tickets 
  WHERE (FUNCION = COR) AND (tickets.CLIENTE=clientes.CLIENTE)) 
THEN UPDATE `clientes` SET `ESTADO` = 'I';

I tried this but it seems I have a syntax error.

How can I get this to work?

EDIT: I want to update 'ESTADO' to 'I' if 'FUNCION', from another table, is 'COR' and the fields 'CLIENTE' match each other.

JavaScript - If statement always returning true

I have some JavaScript that I want to search for a class name in the HTML, and then detect the height of a couple elements within that div, add them together, and display the total height in an alert. The following code appears to be running perfectly, but I noticed that the code will run regardless of what the class name is, even if that class doesn't exist within the HTML. How can I rewrite the if statement so it only runs the code once it comes across a div with the specified class name? I don't want it to detect the height of the wrong h1 and p elements. Thanks for any help.

HTML:

<div class="testing">
    <h1>Understanding Scope</h1>
    <p>By understanding code's <em>scope</em>, we know when that code affects only one part of our code, or the entire codebase.  If we create things that are <em>global</em> in scope, we are giving any code the supreme power to control our code.   So we want to protect our code by being very careful when creating things that are global in scope. This is especially important if you plan on using JavaScript libraries like jQuery.</p>
</div>
<h1>Local Scope</h1>
<p>JavaScript uses <em>function scope</em>, meaning every time we create a new function the scope changes.  Any code inside that function is <em>local</em> to that function. Code that is local in scope is not accessible to outside code.</p>

JavaScript:

function testing(){
        if (document.getElementsByClassName('testing')){
            var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight;
            var textHeight = document.getElementsByTagName('p')[0].offsetHeight;
            var totalHeight = headerHeight + textHeight;


            alert(totalHeight);

        }
    }
testing();

SAS Code IF statement with day of the week logic

I have a large set of SAS code that is run daily. I have been tasked with adding additional code to the file but have it only run on Mondays.

I have googled for some general IF logic but not finding anything concrete.

I think the IF statement should look like this:

If WEEKDAY(TODAY()) = 1

Does this look correct to check if current day is Monday? Also, what are the equivalent of an open and close brace in SAS?

How to find dates based on mathematical calculations

I have a excel sheet with three columns:

  1. List of duplicate IDs of customers.
  2. Amount spent by them in $.
  3. Date of the spend.

The sheet is sorted on the 1st column i.e. List of duplicate ID's of customers. Every time a customer spends something it is recorded in the excel sheet with the ID, spent amount and date of spend.

What I want to extract is the 'ID'(1st column), 'Collective amount spend'(2nd column) and 'date' (3rd column) on which a particular customer has reached the cumulative spend of $500 for all those customers.

Can anyone help in how it can be done easily in MS excel?

**Customers**        **Amount**        **Date**
00000000001             $200           12/01/15
00000000001             $300           12/08/15
00000000001             $100           12/25/15
00000000002             $200           12/03/15
00000000002             $400           12/09/15
00000000003             $200           12/11/15
00000000003             $100           12/15/15

This is some sample data to simplify the question. I would like to get a sheet as follows:

**Customers**        **Amount**        **Date**
00000000001             $600           12/08/15
00000000002             $600           12/09/15

Let's say we are updating the data as follows:

**Customers**        **Amount**        **Date**
00000000001             $200           12/01/15
00000000001             $200           12/08/15
00000000001             $100           12/25/15
00000000002             $200           12/03/15
00000000002             $400           12/09/15
00000000002             $100           12/13/15
00000000003             $200           12/11/15
00000000003             $100           12/15/15

And the result we get back now should be as follows:

**Customers**        **Amount**        **Date**
00000000001             $500           12/25/15
00000000002             $700           12/09/15

prob in selecting multiple fields using If cond., in mysql with left join-

Any help is appreciated --

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as receiverimage, re.fName as receiverfName , re.lName as receiverlName , re.add' at line

SELECT co.*, 
if(( co.senderid = 1) , ( re.image as receiverimage, re.fName as receiverfName , re.lName as receiverlName , re.address as receiverAddress , re.city as receivercity , re.state as receiverstate, re.country as receivercountry, re.zipCode as receiverzip),(se.address as senderAddress,se.city as sendercity , se.state as senderstate , se.country as sendercountry , se.zipCode as senderzip , se.image as senderimage ,se.fName as senderfName, se.lName as senderlName )) 
FROM contacts as co
LEFT JOIN users as se ON( se.id = co.senderid )
LEFT JOIN users as re ON( re.id = co.receiverid )
where (senderid = 1 OR receiverid = 1) 

-- is that selecting multiple fields on join table is not valid with or something else ?

I am unable to figure out the exact reason , basic prob. here is to select few fields based on if condition from user table based on join.

Android java: how to use if-then-else

i'm using eclipse with ADT plugin, and i'm developing an app where i want to use if then and else. i want to do this

if file.txt not exist
then do    
startDownload();
readFile();
else  delete file.txt

Switch Statement: Is the logic different in C v/s. other languages like Java?

I am going through this tutorial on C programming. It says:

The switch-statement is actually entirely different(from other languages) and is really a "jump table". Instead of random boolean expressions, you can only put expressions that result in integers, and these integers are used to calculate jumps from the top of the switch to the part that matches that value. Here's some code that we'll break down to understand this concept of "jump tables".

But, cases of switch statement needs to be compared until a match is found(otherwise default is returned.)

How is it different from multiple if-else statements then? Or, it is just a syntactic sugar? Am I missing something important here?

JavaScript - If statement using .offsetHeight not working

I'm new to JavaScript and am practicing. I'm trying to display the combined height of the h1 and p elements that are within the div that has a class name of "test". I've looked up all sorts of stuff and feel like I'm really close, but can't quite get this to work. Anyone able to help?

HTML:

<div class="test">
    <h1>Understanding Scope</h1>
    <p>By understanding code's <em>scope</em>, we know when that code affects only one part of our code, or the entire codebase.  If we create things that are <em>global</em> in scope, we are giving any code the supreme power to control our code.   So we want to protect our code by being very careful when creating things that are global in scope. This is especially important if you plan on using JavaScript libraries like jQuery.</p>
</div>
<h1>Local Scope</h1>
<p>JavaScript uses <em>function scope</em>, meaning every time we create a new function the scope changes.  Any code inside that function is <em>local</em> to that function. Code that is local in scope is not accessible to outside code.</p>

JavaScript:

function testing(){
    if (document.getElementsByClass('test')){
        var headerHeight = document.getElementsByTagName('h1').offsetHeight;
        var textHeight = document.getElementsByTagName('p').offsetHeight;
        var totalHeight = headerHeight + textHeight;

        alert(totalHeight);
    }
}

testing();

Javascript if/if else/else not working

So I have this javascript, but it's not working.

var verbs = [ ["ambulo", "ambulare", "ambulavi", "ambulatus"], ["impedio", "impedire", "impedivi", "impeditus"] ]
var verbNumber = verbs.length - 1;

function randomIntFromInterval(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}

/* Picks a verb */
var thisVerb = verbs[randomIntFromInterval(0, verbNumber)];

/* Checks the conjugation */
var second = thisVerb[1];
var secondLength = second.length;
var start = secondLength - 3;
var secondEnding = second.substring(start, secondLength);
var conjugationNumber = 0;

if (secondEnding === "are") {
conjugationNumber = 1;
} else if (secondEnding === "&#275;re") {
conjugationNumber = 2;
} else if (secondEnding === "ere") {
conjugationNumber = 3;
} else if (secondEnding === "ire") {
conjugationNumber = 4;
} else {
console.log("error");
};      

/* Randomly picks how to conjugate */
var tense = randomIntFromInterval(1, 6);
var person = randomIntFromInterval(1, 3);
var number = randomIntFromInterval(1, 2);
var voice = randomIntFromInterval(1, 2);

/* Conjugates */
var thisDictEntry = 0;

if ((conjugationNumber === 1 || 2) && (tense === 1 || 2 || 3)) {
thisDictEntry = 2;
} else if ((conjugationNumber === 3 || 4) && (tense === 1 || 2 || 3)) {
thisDictEntry = 1;
} else if ((tense === 4 || 5 || 6) && (voice === 1)) {
thisDictEntry = 3;
} else if ((conjugationNumber === 3 || 4) && (voice === 2)) {
thisDictEntry = 4;
} else {
console.log("Error");
};

What should happen is a random verb (array within an array) is picked, then becomes randomly conjugated. All the code works up until the if/else if/else statements under the /* Conjugates */. That, for some reason, always sets thisDictEntry to 2.

Why?

How to minimize the use of if else if in XMLStreamReader while parsing complex XML

I have the sample XML data below which I want to convert to a simple XML form.

I have to create multiple XML data based in the occurrence of certain element-value in the main XML data.

The logic is embedded inside a XMLStreamReader. While doing that I have to use multiple if else if and the code looks just messy. It seems like the if else if logic seems to grow if the xml tag contains grows.

  1. Is there a better design pattern to implement this logic?

  2. I have to convert the XML into Serializable Object, Is DOM better option here?

XML:

    <Bank createdTs="2014-11-26T16:50:13" xmlac = "http://ift.tt/1eqg2i8" xmlac:trans="http://ift.tt/1ceGqK8" xmlac:vref="http://ift.tt/1eqg2ia">
<Transaction id="6f42cfee-ddd6-4d70-a6f7-a153d182c2b3" trans:type="deposit" trans:method="check">
    <UserRef status="Verify" vref:code="13" />
    <Account accountID="10002548" accountCategory="Checking">
        <TransactionRecord>
            <UserID>keith-kolmos</UserID>
            <Amount>4480</Amount>
            <LocationID>520</LocationID>
            <DateTimeStamp>2015-01-23T10:25:18</DateTimeStamp>
            <Comments>Check Verification Required</Comments>
        </TransactionRecord>
    </Account>
</Transaction>
<Transaction id="6f42cfee-ddd6-4d70-a6f7-a33d162c2b3" trans:type="withdraw" trans:method="cash">
    <Account accountID="10002548" accountCategory="Checking">
        <UserRef status="Complete" vref:code="10"/>
        <TransactionRecord>
            <UserID>zoe-danbur</UserID>
            <Amount>470</Amount>
            <LocationID>234</LocationID>
            <DateTimeStamp>2015-03-13T11:27:10</DateTimeStamp>
            <Comments/>
        </TransactionRecord>
    </Account>
</Transaction>
<Transaction id="6f42cfee-ddd6-4d70-a6f7-a0124d182c2b0" trans:type="deposit" trans:method="check">
    <Account accountID="10002548" accountCategory="Checking">
    <UserRef status="verify" vref:code="1"/>
        <TransactionRecord>
            <UserID>susan-wood</UserID>
            <Amount>585</Amount>
            <LocationID>127</LocationID>
            <DateTimeStamp>2015-03-25T09:20:32</DateTimeStamp>
            <Comments>Check Verified, photo ID presented</Comments>
        </TransactionRecord>
    </Account>
</Transaction>

XML DAO:

    public class BankDAO implements Serializable {
           private String accountID;
           private String accountCategory;
           private String transactionID;
           private String transactionType;
           private String transactionMethod;
           private String transactionStatus;
           private String transactionCode;
           private String userID;
           private String locationID;
           private String transactionAmount;
           private String dateTimeStamp;
           private String comments;

           //getters 
           //setters
           //toCustomXMLs
}

XML Parsing Logic Implementation:

public BankDAO parseXML(String xml) throws XMLStreamException, FactoryConfigurationError{
        XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()));

        BankDAO bank = new BankDAO();

        String currentElement = "";
        while (xmlReader.hasNext()){
            int code = xmlReader.next();
            switch(code){
            case START_ELEMENT:
                currentElement = xmlReader.getLocalName();
                break;
            case CHARACTERS:
                if (currentElement.equalsIgnoreCase("Transaction")) {
                    bank.setTransactionID(xmlReader.getAttributeValue("http://ift.tt/1ceGqK8","id"));
                    bank.setTransactionType(xmlReader.getAttributeValue("http://ift.tt/1ceGqK8","type"));
                    bank.setTransactionMethod(xmlReader.getAttributeValue("http://ift.tt/1ceGqK8","method"));
                } else if (currentElement.equalsIgnoreCase("UserRef")) {
                    bank.setTransactionStatus(xmlReader.getAttributeValue(null,"status"));
                    bank.setTransactionCode(xmlReader.getAttributeValue("http://ift.tt/1eqg2ia","code"));
                }else if (currentElement.equalsIgnoreCase("Account")){
                    bank.setAccountID(xmlReader.getAttributeValue(null,"accountID"));
                    bank.setAccountCategory(xmlReader.getAttributeValue(null,"accountCategory"));
                }else if (currentElement.equalsIgnoreCase("UserID")){
                    bank.setAccountID(xmlReader.getAttributeValue(null,"UserID"));
                }else if (currentElement.equalsIgnoreCase("Amount")){
                    bank.setTransactionAmount(xmlReader.getElementText());
                }else if (currentElement.equalsIgnoreCase("LocationID")){
                    bank.setLocationID(xmlReader.getElementText());
                }else if (currentElement.equalsIgnoreCase("DateTimeStamp")){
                    bank.setDateTimeStamp(xmlReader.getElementText());
                }else if (currentElement.equalsIgnoreCase("Comments")){
                    bank.setComments(xmlReader.getElementText());
                }
            }
        }
        return bank;
    }

excel sheet using logical operators

I have a a column of data in excel sheet

I want to filter those values the cell have values greater than previous or next cell eg i have values in Excel sheet in column A

Then my logic is

If (A2>A1 & A2>A3)
Then B2=1
else B2=0

I need to execute it for 1000 rows in column A. so something like if(currentcellnum value > currentcellnum-1 value and currentcellnum> currentcellvaluve+1) then print in adjacent column of current cell 1 else 0

Thanks and regards

Shortening if() with string.equals method

Is there any way to shorten this if() statement? To avoid repeating string.equals() somehow?

else if (extension.equals("jpg") || extension.equals("JPG") || extension.equals("png") || extension.equals("PNG") || extension.equals("bmp") || extension.equals("BMP") || extension.equals("jpeg") || extension.equals("JPEG"))
            {
                tmp.setIcon(new ImageIcon(getClass().getResource("/menage/Resources/imageIco.png")));
            }

To something looking similar to this :

    else if (extension.equals(("jpg")||("JPG")||("png")||("PNG")||("bmp")||("BMP")||("jpeg")||("JPEG")))
    {
    tmp.setIcon(new ImageIcon(getClass().getResource("/menage/Resources/imageIco.png"));)
    }

I am aware that this question looks odd, however if() with such long conditions list is unclear and requires a lot of writing as well.

This mergesort should "of" failed, right?

I noticed something weird while reviewing this mergesort implementation on Code Review

/************************************************************
 * Mergesort implementation
 ***********************************************************/

function sort(array) {
  var len = array.length;
  var middle = Math.floor(len*0.5);
  var left = array.slice(0,middle);
  var right = array.slice(middle, len);

  if (len == 1) {
    return array;
  } else {

  }

  return merge(sort(left), sort(right));
}


function merge(left, right) {
  var a = left.length;
  var b = right.length;


  if (a > 0 && b > 0) {
    if (left[0] > right[0]) {
      return [].concat(left[0], merge(left.slice(1,a), right));
    } else {
      return [].concat(right[0], merge(right.slice(1,b), left));
    }
  } else if (a == 0) {
    return right;
  } else of (b == 0)
    return left;

}


/************************************************************
 * Demonstration
 ***********************************************************/

function doSort() {
    var array = document.getElementById('in').value.split(/[, ]+/).map(function(e) {
        return parseInt(e);
    });
    var sorted = sort(array);
    document.getElementById('out').value = sorted;
}

function generateRandom(len) {
    var array = [];
    for (var i = 0; i < len; i++) {
        array.push(Math.round(Math.random() * 100));
    }
    document.getElementById('in').value = array;
};

generateRandom(20);
<button onclick="generateRandom(20)">⬇︎ Generate random numbers ⬇︎</button>
<div><input id="in" size="80"></div>
<button onclick="doSort()">⬇︎ Sort ⬇︎</button>
<div><input id="out" size="80" disabled></div>

The last conditional branch is else of rather than else if. Normally, else of should result in a syntax error. Yet, no matter how hard I try, I can't trigger the syntax error — it always successfully returns an array sorted in descending order!

I know, else of (b == 0) could just be replaced by else, but still, I want to know: How could this code possibly work?

Method to refactor the ‘if’ in Python?

The code like this:

def func(param):
"""
:param 'A' or 'B' or 'C'
"""

var1 = do_something_1()
if param == 'A':
    var1 = do_something_A_1()

var2 = do_something_2(var1)
if param == 'B':
    var2 = do_something_B_1()

var3 = do_something_3(var2)
if param == 'A':
    var3 = do_something_A_2()

var4 = do_something_4(var3)
if param == 'A':
    var4 = do_something_A_3()

var5 = do_something_5(var4)

return var5

I was wondering that whether there's a way to refactor the 'if' statements in this code.

Anyone has ideas about this?

excel nested if multiple logical tests

I have read other threads on this topic, however I found no answers. I have three colums, of which I want to test column a and b and if true I want the som of the results in colum c.

         a      b      c
  1     ba     za       2
  2     ba     az       2
  3     ca     za       2
  4     ca     az       2 
  5     ba     za       2

I want to find the sum if column a = ba and column b = za. So in this example the sum of those would be 4. This is the Excel forumala I have, however it keeps giving the result of 0.

This formula is a nested if.

=Sum(IF(And((a1:a5="ba");b1:b5="za");c1:c5;0))

Can someone please help me with finding the correct formula? I have been breaking my head about this particular formula.

I have been using excel for a while now, and quite got the hang of all the formulas, however this is the only problem I could not wrap my head around.

Laravel redirect from private method with errors

I have the following code:

public function store(Request $request)
{
        $this->validateData($request->all());

        // store something

        return redirect()->action('controller@index')->withMessage( 'Saved Successfully' );
}

private function validateData($requestParams)
{
    try 
    {
        $validator->validate( $requestParams );
    } 
    catch ( ValidationException $e ) 
    {
        redirect()->action('controller@create')->withInput()->withErrors( $e->get_errors() )->send();
        exit(); // this causes the withErrors to not be there
    }
}

If I remove the exit();, the error messages will appear, but also the store function will be executed (see // store something). I know I can rewrite my code like:

if($this->validateData($request->all()))
{
    // store something

    return redirect()->action('controller@index')->withMessage( 'Saved Successfully' );
}

But I don't want the ugly if statement here. There must be a way to redirect with the flash messages without it.

Thanks in advanced!

GAMS If-Else If-Else multiple loop conversion to MILP statements

I am working on MILP model of GAMS and want to convert If-Else if-Else loops to MILP statements. The code is as follows:

set I /a b c/;

Parameter1 /

a 1.5

b 1.8

c 2.3 /;

Parameter2/

a 1

b 1

c 2 /;

Parameter3/

a 2

b 2.5

c 3 /;

Parameter4/

a 1.5

b 1

c 2 /;

If Parameter1 < Parameter2

(

If Paramater3 < Parameter2

(Variable 1 = Parameter3;)

Else

(Variable1 = Parameter2;)

)

Else if Parameter1 > Parameter2

(

If Parameter3 < (Parameter1 + 0.75)

(Variable 1 = Parameter3;)

Else

(Variable 1 = Parameter1 + 0.75;)

)

Else if Parameter1 = Parameter2

(

If Parameter3 < (Parameter1 + 0.25)

(Variable 1 = Parameter3;)

Else

(Variable 1 = Parameter1 + 0.25;)

)

Obj..

x =e= sum(I,Variable1*Parameter4);

Kindly guide on how to convert the If-Else loop into GAMS MILP model. Thanks in advance

mercredi 27 mai 2015

else if condition is not working

I need to check in two of string, if those string contains any particular string or not e.g i need to search if my both of strings contains "Australia" or not. If not then append "Australia" to the string in which "Australia" is not present, for this i am writing this

 NSString *startLocationAddress = @"Any address for start location";
 NSString *endLocationAddress = @"Any address for end location";

 if ([startLocationAddress rangeOfString:@"Australia"].location == NSNotFound)
 {
     NSLog(@"string does not contain Australia");
     startLocationAddress = [startLocationAddress stringByAppendingString:@",Australia"];
 }
 else if ([endLocationAddress rangeOfString:@"Australia"].location == NSNotFound)
 {
     NSLog(@"string does not contain Australia");
     endLocationAddress =[endLocationAddress stringByAppendingString:@",Australia"];
 }
 else {
     NSLog(@"string contain Australia");
 }

As my both of strings does not contains "Australia". First if condition is working fine and it append "Australia" to the string but second else if condition is not working. Although i applied the different approach to solve my problem, but i need to know what is wrong in this code. Any help would be highly appreciable. Thanks.

PHP if statement error

My question is: Why does the script enter ALL if statements? Even if the "in array" question shouldn't let them.

First I show you the array which I am getting back from my model: In this case the array is just like array([0] => array()) because I only get 1 row back from my DB.

array(1) {
  [0]=>
  array(7) {
    ["Kunden_ID"]=>
    float(250)
    ["Kundentyp_ID"]=>
    float(1)
    ["kundentyp_row_id"]=>
    int(100)
    ["ext_kdnr"]=>
    float(0)
    ["kundentyp_anmerkung"]=>
    string(0) ""
    ["status"]=>
    string(0) ""
    ["name"]=>
    string(4) "ROLA" // Thats what we are looking for in our statements
  }
}

Now to the code:

    $result_array = $showAllgemeineKundendaten -> show_client_more($_SESSION['id'], 3); // get result array from model
    $rola = false; 
    $rola_pos = false;

    $rola_obc = false;
    $rola_obc_pos = false;

    $myto_fai = false;
    $myto_fai_pos = false;

    $omv = false;
    $omv_pos = false;

    $vat = false;
    $vat_pos = false;

    $plaketten = false;
    $plaketten_pos = false;

    $spedition = false;
    $spedition_pos = false;

    $moest = false;
    $moest_pos = false;

    $berufungen = false;
    $berufungen_pos = false;

    $diverse = false;
    $diverse_pos = false;

    $arr_length = count($result_array);
    echo $arr_length; // array length equals 1 since we only have 1 idx

    $rola_row = 0;
    $rola_obc_row = 0;
    $myto_fai_row = 0;
    $omv_row = 0;
    $vat_row = 0;
    $plaketten_row = 0;
    $spedition_row = 0;
    $moest_row = 0;
    $berufungen_row =0;
    $diverse_row = 0;

    echo "<pre>";
    var_dump($result_array);
    echo "</pre>";

    for($i = 0; $i < $arr_length; $i++){ // for runs only once since we only get 1 row back
        if(in_array("ROLA", $result_array[$i])){ 
// check if you find the string "ROLA" in the array idx $i
            $rola = true;
            $rola_pos = $i;
            $rola_row = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>ROLA TYP AKTIV";
        }
        if(in_array("ROLA_OBC", $result_array[$i])){
            $rola_obc = true;
            $rola_obc_pos = $i;
            $rola_obc_row = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>ROLA OBC TYP AKTIV";
        }
        if(in_array("MYTO_FAI", $result_array[$i])){
            $myto_fai = true;
            $myto_fai_pos = $i;
            $myto_fai = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>MYTO FAI TYP AKTIV";
        }
        if(in_array("OMV", $result_array[$i])){
            $omv = true;
            $omv_pos = $i;
            $omv = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>OMV TYP AKTIV";
        }
        if(in_array("VAT", $result_array[$i])){
            $vat = true;
            $vat_pos = $i;
            $vat = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>VAT TYP AKTIV";
        }
        if(in_array("PLAKETTEN", $result_array[$i])){
            $plaketten = true;
            $plaketten_pos = $i;
            $plaketten = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>PLAKETTEN TYP AKTIV";
        }
        if(in_array("SPEDITION", $result_array[$i])){
            $spedition = true;
            $spedition_pos = $i;
            $spedition = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>SPEDITION TYP AKTIV";
        }
        if(in_array("MOEST", $result_array[$i])){
            $moest = true;
            $moest_pos = $i;
            $moest = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>MOEST TYP AKTIV";
        }
        if(in_array("BERUFUNGEN", $result_array[$i])){
            $berufungen = true;
            $berufungen_pos = $i;
            $berufungen = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>BERUFUNGEN TYP AKTIV";
        }
        if(in_array("DIVERSE", $result_array[$i])){
            $diverse = true;
            $diverse_pos = $i;
            $diverse = $result_array[$i]["kundentyp_row_id"];
            echo "<br/>DIVERSE TYP AKTIV";
        }
    }

As you see the result array contains the string "ROLA" therefore the first IF statement should be true and executed. Which is the case. BUT all other if statements appear to be true as well. Why?

If statements are ignored

I have a simple calculator for finding the dimensions of a couple shapes. It's supposed to be set up so the first function has a set of if statements that trigger one and only one of the other functions based on user input. But instead it's triggering all of them no matter what my answer is. It skips the prompt for the circle one and goes through the prompts for the other two. It does give me a result for all three in the console and the console keeps telling me, no matter what input I put in, the answers to my shape functions is NaN. There's definitely a variable problem there but I can't figure it out. The console isn't bringing up any errors to me right now. Sorry there isn't a comment for everything yet.

//Lee_Matthew_Functions_Assignment_5/26/2015

        //Main Function

        function theConjurer() {
            firstQuestion = prompt("Hi! This is my shape dimension calculator! I have three different shapes in this version but I can always add more! For now I have these three:\nCircle Area\nSphere Volume\nRectangular Prism Volume\n\nEnjoy!!!"); //The answer to this prompt is supposed to spring one of the functions below.

            if(firstQuestion === "Circle" || "Circle Area") { //If the answer is one of these strings, then it triggers the circle area function.
                calcCircleArea();
            }

            if(firstQuestion === "Sphere" || "Sphere Volume") { //This one triggers the sphere volume function.
                calcSphereVolume();
            }

            if(firstQuestion === "Prism" || "Rectangular Prism" || "Prism Volume" || "Rectangular Prism Volume") { //This one is for volume of a rectangular prism.
                calcPrismVolume();
            }

            else {  //Anything else just brings up another prompt for the same answers.
                firstQuestion = prompt("Sorry, that's not one of the options I have right now. Try again!");
            }
        }

        theConjurer(); //To automatically bring up the starting function.


        //Function for Dimensions of a Circle

        var pi = 3.14; //pi rounded down to the hudredths place.

        calcCircleArea(pi, radius); //Variable declarations.

        function calcCircleArea(p, r) { //
            var circleArea = p * Math.pow(r, 2);
            console.log("The circle you've entered is " + circleArea + " square units!");
        }


        //Function for Volume of a Sphere

        calcSphereVolume(fourThirds, pi, radius);

            var fourThirds = (4/3);
            var radius = prompt("Do you know the diameter of your sphere? Just half that is your radius! What's the radius?"); //User input for the shape's radius.

        function calcSphereVolume(f, p, r) {
            var sphereVolume = f * p * Math.pow(r, 3);
            console.log("Your sphere is " + sphereVolume + " cubed units! Congradulations!");
        }

        //Function for Dimensions of a Rectangular Prism

        var length = prompt("What's the length of this prism?"); //User input for the shape's length.
        var width = prompt("What's the width?"); //User input for the shape's width.
        var height = prompt("What is the height?"); //User input for the shape's height.

        calcPrismVolume(length, width, height); //Storage for the above three variables.

        function calcPrismVolume(l, w, h) { //Function and its parameters.
            var prismVolume = l * w * h; //New variable made from multiplying those parameters.
            console.log("Your prism is " + prismVolume + " cubed units!"); //Output of shape's area.
        }

if else android coding

i am doing a if else android coding but it seen that the code don't take data string from selection which is a "textview" and match it to my pre define in the condition of the if else. i wonder is it my coding is wrong? below is my codes.

private static final String[] items={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "R"};

@Override
public void onCreate(Bundle icicle) {
  super.onCreate(icicle);

  Fabric.with(this, new Crashlytics());

  setContentView(R.layout.activity_main);

  selection=(TextView)findViewById(R.id.text0);  
  Spinner spin=(Spinner)findViewById(R.id.spinner0);  
  result=(TextView)findViewById(R.id.result);

  spin.setOnItemSelectedListener(this);

  ArrayAdapter<String> aa=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);

  aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spin.setAdapter(aa);
  result.setText("");



  if (selection.equals(a)){
      int aaa = (1*100);
      result.setText(String.valueOf(aaa));

  }

  else if (selection.equals("1")){
      int aaa = (2*10);
      result.setText(aaa + "");
  }

  else if (selection.equals("2")){
      int aaa = (3*1);
      result.setText(String.valueOf(aaa));

  }

  else if (bb.equals("R")){
      result.setText(".");
  }


}