dimanche 31 janvier 2016

execute two insert and select statement as per the return value?

@SuppressWarnings("unchecked")
public TblSeed getSeed(String tableName, String tableName1) {
    Session session = this.sessionFactory.getCurrentSession();

        List<TblSeed> list = new ArrayList<TblSeed>();
        TblSeed tblSeed = null;
        try{
            Query query = session.createQuery("from TblSeed where seedName =:tableName");
        query.setParameter("tableName", tableName);

            list = query.list();
            if(list!=null && list.size()>0){
                tblSeed = list.get(0);
                }

        Query query1 = session
                .createQuery("from TblSeed where seedName =:tableName1");
        query.setParameter("tableName1", tableName1);

        list = query1.list();
        if (list != null && list.size() > 0) {
            tblSeed = list.get(0);
        }

        }catch(Exception ex){
            tblSeed = null;
            logger.error("Exception:",ex);
        }
        return tblSeed;

}



    TblSeed tblSeed = getSeed("TblTransactions",
            "TblTransactionsRepository");
    String format = "%"+(tblSeed.getSeedMaxValue()+"").length()+"s";
    long id= (tblSeed.getSeedCurrentCtr()!=null?tblSeed.getSeedCurrentCtr():tblSeed.getSeedBaseCtr())+tblSeed.getSeedIncrementCtr();


    String tblTransactionsRowName1 = ApplicationProperties
            .getValue("TblTransactionsROWNAMELIST1");
    String qInsertSelect1 = "select "
            + tblTransactionsRowName1
            + " "
            + " from "
            + srcTable
            + "Temp a, "
            + destTable
            + "Temp b "
            + " where  1=1 and a.reconFlag = b.reconFlag  and coalesce( b.reconFlag, 'B' ) = '"
            + autoFlag + "'" + joinQ;
    System.out.println("qInsertSelect1-------->" + qInsertSelect1);

Here, tblSeed returns two tables(i.e TblTransactions and TblTransactionsRepository) as per my source. In below i am getting the max id of that TblTransactions table inserting into it.

Query is- Similarly how can i insert tha same into TblTransactionsRepository as per the return value of tblSeed enter code here.

I am trying to do this like this

    TblSeed tblSeed = getSeed("TblTransactions",
            "TblTransactionsRepository");
    String format = "%"+(tblSeed.getSeedMaxValue()+"").length()+"s";
    long id= (tblSeed.getSeedCurrentCtr()!=null?tblSeed.getSeedCurrentCtr():tblSeed.getSeedBaseCtr())+tblSeed.getSeedIncrementCtr();


    String tblTransactionsRowName1 = ApplicationProperties
            .getValue("TblTransactionsROWNAMELIST1");
    String qInsertSelect1 = "select "
            + tblTransactionsRowName1
            + " "
            + " from "
            + srcTable
            + "Temp a, "
            + destTable
            + "Temp b "
            + " where  1=1 and a.reconFlag = b.reconFlag  and coalesce( b.reconFlag, 'B' ) = '"
            + autoFlag + "'" + joinQ;
    System.out.println("qInsertSelect1-------->" + qInsertSelect1);
    List<Object> objList = null;
    try{
        Query queryInsertSelect1 = this.sessionFactory.getCurrentSession()
                .createQuery(qInsertSelect1);
        // queryInsertSelect.setParameter("reconProcessId",
        // Integer.parseInt(reconProcessId));
        objList = queryInsertSelect1.list();
        Query queryInsertSelect3 = this.sessionFactory.getCurrentSession()
                .createQuery(qInsertSelect3);
        objList = queryInsertSelect1.list();
        logger.debug("objList :"+objList!=null ?objList.size():0);
    }catch(Exception ex){
        logger.error("Exception :",ex);
        ex.printStackTrace();
    }

Why doesn't if else shorthand work with break - Python

I have been trying break out of loop when a condition is matched. I've tried one-liners below:

break if a is not None else time.sleep(1)

and this

a is not None and break
time.sleep(1)

Both are not working & throwing SyntaxError while the straight forward works fine.

if a is not None:
    break
time.sleep(1)

While I've no problem with using it this way, I just want to know why the syntax for above is wrong.

Creating a new column with a function's output, row by row

I have a data frame with a column of values (CVT_revenue$V4) ranging from 1 to 100. I want to apply a function to each of the values in the column and create a new column with the function's output. For example, if CVT_revenue$V4 had 45 in its first row, I would want the function to perform the calculation in the first else if statement, then put the output into the first row of the new column.

This is what I've tried:

actualRevenues <- function(df, column){
  for (i in 1:nrow(df)){
    if (column[i] < 33){
      df$actualRevenue <- (column[i] * 22000 + 300000)
    } else if(column[i] > 32 & column[i] < 67){
      df$actualRevenue <- ((column[i] - 32) * 33000000 + 1000000)
    } else {
      df$actualRevenue <- ((column[i] - 66) * 9090909 + 100000000)
    }
      }
}
actualRevenues(CVT_revenue, CVT_revenue$V4)

I think mapply might be the easiest way to accomplish this, but I'm not sure why my code isn't working. If I put a print statement after the else statement, I can see that it's calculating the same value over and over again. This is a snippet from the printed results:

    [1] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08
  [10] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08
  [19] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08
  [28] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08

Thanks for your help.

Does all Object Oriented design come down to reducing conditionals?

I'm getting the sense that reputable OO design and patterns come down to reducing conditional statements (if statements). This would be very general statement, and wondering if it's true. If it's not true, can you provide an example.

To be clear - My question is purely academic. It is not concerned with the realities and practicalities of crafting software. For example, the question is ignoring tradeoffs like understandability vs complexity.

Is there a way to work around using a break statement?

I have a working binary search function that asks a to user input a name and it will search for it in the Student array structure and display the corresponding average GPA for that student. It will keep looping for the user to enter in a name to search for unless the user enters in a period.

The problem I have is the break statement I am using. The requirements for this function that I need to follow does not allow me to use a break statement.

However, if I remove the break statement, my binary search will infinitely print out the output statement and will not work properly anymore.

Is there a way for me to work around this and not use a break statement? I have a feeling I could be using several if statements instead of the break statement.

void binarySearch(Student* ptr, int MAXSIZE)
{
   string target;
   string period = ".";

   int first = 0,
   last = MAXSIZE - 1,
   mid;

  do
  {
    cout << "Enter student name (Enter . to stop): ";
    cin  >> target;

    while (first <= last)
    {
        mid = (first + last) / 2;
        if (ptr[mid].name.compare(target) == 0)
        {
            cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
            first = 0;
            last = MAXSIZE - 1;
            break; // I am stuck on making the binary search work without using this break statement
        }
        else if (ptr[mid].name.compare(target) < 0)
            last = mid - 1;
        else
            first = mid + 1;
    }
    if (first > last && target.compare(period) != 0)
    {
        cout << "This student was not found. Enter another name" << endl;
        first = 0;
        last = MAXSIZE - 1;
    }
  } while (target.compare(period) != 0);
}

how do i change the text inside a button using a php if else statement?

Im on a dynamic webpage written in php and would like to have an if else statement that would look inside mysql database table and check if the string "description" is present inside a certain database table column. if the word "description" is present echo "Visit Discounted Venue" text inside the button, else echo "Visit venue website" string inside the button.

I currently have the code below, its in a php file.

<?php 
  if(stripos( $forum_data['venue_url_text'],"discount") == false) ?>

" class="btn" target="_blank" rel="nofollow"> VISIT VENUE WEBSITE

" class="btn" target="_blank" rel="nofollow"> VISIT DISCOUNTED VENUE

How to write an IF statement in excel for times and dates in the same cell

I am trying to find out if an event occurs between two other events.

For all three events, I have the date in one column, the time in another column and then the date followed by the time in a third column. Columns three is formatted like this =TEXT(B1,"dd/mm/yyyy ")&TEXT(A1,"hh:mm:ss")

The table looks like this:

  |   a   |   b   |    c    |
_____________________________
1 | time  | date  |time/date|
2 | time  | date  |time/date|
3 | time  | date  |time/date|

Row 1,2 and 3 are each event. Let's say we're trying to work out if event 3 occurs within event 1 and 2. The formula I have so far goes in D1 and looks like this:

=IF(AND(DATEVALUE(C3)>=DATEVALUE(C1),DATEVALUE(C3)<=DATEVALUE(B3)),TRUE,FALSE)

I have various different sets of events that I want to check in a similar way, but it's not working for me. I have made sure that each cell I'm referring to is formatted correctly i.e date is dd/mm/yyy and time is hh:mm:ss etc but it's not working for some reason.

Haven't found an answer to this anywhere so I would really appreciate some help.

Thanks in advance!

If Statement: Compare multiple ints

I'm developing an app that is getting quite large after 1 year. So I'm trying to improve its performance in all aspects. I'm not a professional, I've been teaching myself programming for the past year, and when I look back some lines I wrote in the past they look so silly, like the one below:

    if (screenPos == 0 || screenPos == 20 || screenPos == 22){

//do something
} else {

}

Is there a simplest/shorter way to compare a value with several ints?

something like:

    if (screenPos != 0, 20, 22){
    //do something
} 

or maybe add this numbers in a array list and check "if(screenPos exists in the Array)"?

I know is a newbie question, sorry about that. I've been looking around for an answer, but haven't found it.

Thanks in advance

Comparing a file to another file

import sys
import os
import glob
directorylist = ["A", "B", "C", "D"]

for directory in directorylist:
    for file in glob.glob(os.path.join(directory, "tobecompared(*).txt")):
        with open(file) as f:
                a=0
                fdata = f.readlines()
                for line in fdata:
                    with open ("/Users/Student/Desktop/folder/pool.txt", "r") as pool:
                        if line in pool:
                            a=a+1
                print a

I want to compare lines in text files (tobecompared1.txt, tobecompared2.txt) to the lines in another text file (pool.txt). The folder contains the folders A, B, C, and D. The pool.txt is in the folder while the tobecompared(*).txt files are in the directories A, B, C. This code aims to print the no. of lines in the tobecompared text files that are present in the original pool.

This code prints 0 repeatedly, so I'm guessing there is an issue with the loops that increases the value of a by 1. What is really aimed at is:

Say the pool.txt is

A
B
C
D

tobecompared(01).txt in A is

A
A
F
H
C
B

tobecompared(02).txt in A is

A
B
C

tobecompared(01).txt in B is

G
D
C

The output would be:

4
3
2

Small Basic How do I get my players square to "die" even if my enemies square can't be matched up exactly to it?

Here's the code:

'Player and Enemy Variables
PlayerX = 0
PlayerY = 339
EnemyX = Math.GetRandomNumber(590)
EnemyY = 339
'Just setting up
GraphicsWindow.Show()
GraphicsWindow.Width = "600"
GraphicsWindow.Height = "400"
GraphicsWindow.KeyDown = OnKeyDown
'Ground, Enemy, and Player Drawn
GraphicsWindow.FillRectangle(0,350,600,50)
GraphicsWindow.DrawRectangle(PlayerX,PlayerY,10,10)
GraphicsWindow.DrawRectangle(EnemyX,EnemyY,10,10)
GraphicsWindow.DrawBoundText(50,50,100,"WASD")
Sub OnKeyDown
  'What button was pressed? 
  If (GraphicsWindow.LastKey = "W") Then
    GraphicsWindow.Clear()
    PlayerY = PlayerY - 10
    GraphicsWindow.FillRectangle(0,350,600,50)
    GraphicsWindow.DrawRectangle(PlayerX,PlayerY,10,10)
    GraphicsWindow.DrawRectangle(EnemyX,EnemyY,10,10)
    GraphicsWindow.DrawBoundText(50,50,100,"WASD")
  EndIf
  If (GraphicsWindow.LastKey = "S") Then
    GraphicsWindow.Clear()
    PlayerY = PlayerY + 10
    GraphicsWindow.FillRectangle(0,350,600,50)
    GraphicsWindow.DrawRectangle(PlayerX,PlayerY,10,10)
    GraphicsWindow.DrawRectangle(EnemyX,EnemyY,10,10)
    GraphicsWindow.DrawBoundText(50,50,100,"WASD")
  EndIf
  If (GraphicsWindow.LastKey = "A") Then
    GraphicsWindow.Clear()
    PlayerX = PlayerX - 10
    GraphicsWindow.FillRectangle(0,350,600,50)
    GraphicsWindow.DrawRectangle(PlayerX,PlayerY,10,10)
    GraphicsWindow.DrawRectangle(EnemyX,EnemyY,10,10)
    GraphicsWindow.DrawBoundText(50,50,100,"WASD")
  EndIf
  If (GraphicsWindow.LastKey = "D") Then
    GraphicsWindow.Clear()
    PlayerX = PlayerX + 10
    GraphicsWindow.FillRectangle(0,350,600,50)
    GraphicsWindow.DrawRectangle(PlayerX,PlayerY,10,10)
    GraphicsWindow.DrawRectangle(EnemyX,EnemyY,10,10)
    GraphicsWindow.DrawBoundText(50,50,100,"WASD")
  EndIf
  'Keep in the Graphics Window!
  If (PlayerX < 10) Then
    PlayerX = 10
  EndIf
  If (PlayerX > 590) Then
    PlayerX = 590
  EndIf
  If (PlayerY < 10) Then
    PlayerY = 10
  EndIf
  If (PlayerY > 339) Then
   PlayerY = 339
  EndIf
  'Player and Enemy Collide.
  If (PlayerX = EnemyX And PlayerY = EnemyY) Then
    GraphicsWindow.DrawBoundText(100,50,100,"NO!")
  EndIf

EndSub

And heres the problem. To make it look nice and not be super slow, whenever the Player is moved, it's moved in multiples of 10. However the Enemy's X axis is random, and not always on a multiple of 10. What I'm trying to do is whenever my Player's square is inside my Enemy's square, it will display "NO!" on the Graphics Window. But I can't unless the random number that the Enemy's X axis is on is a multiple of 10. How can I work around this?

Testing an array for a function with javascript/jQuery

I'm currently pulling last names out of a document and copying them to clipboard in a userscript using...

    var txt = $('p.overview.text').text();
    var lastName = txt.match(/Last Name: (.*)/)[1].split("First Name: ", 1);
    GM_setClipboard(lastName);

But I want to test the lastName against an array to make sure it's not any of these "I", "II", "III", "IV" etc. Because the system that is giving me the document and last name within sometimes screws up and gives me the roman numeral (instead of the last name) if the person has one (ie Jerry Louis VI = "VI" instead of "Louis").

What I've tried just to test this first before running it is on the actual documents

    var txt = $('p.overview.text').text();
    var lastName = txt.match(/Last Name: (.*)/)[1].split("First Name: ", 1);
    var lastNameVal = lastName[0]; // This is the correct variable for actual use
    lastNameVal = "I"; // This is how I am testing it, will delete when done with testing

    if (lastNameVal.text !== "I") {
        GM_setClipboard(lastNameVal);
    }

The above works in that it detects that the variables value as "I" after assigning it. But obviously I need to test this against an array of roman numerals, probably going up to XII or so. I've tried creating an array within the if statement using || (or) operator to test against like so...

        if (lastNameVal !== "I" || "II" || "III") {
        GM_setClipboard(lastNameVal);
    }

But that is not working... What would be the best way to accomplish this? Thanks

C++ if/else grid system

I am trying to create a C++ program that will move an X on a 4x4 grid and display each move. We are not allowed to use arrays because we haven't learned how yet. I know that I am supposed to use 16 if/else statements, but I am not sure what to do from there. I know there is an easier way than mapping out each possible option because that would take forever!!! What do I do???

d3.js function to count data belonging to a category and bigger than 0

I am trying to create a function that counts the people of each category that have a value bigger than 0. If this is my data...

DATA.CSV
name; category; value
name1; A; 10
name2; A; 0
name3; A; 5
name4; B; 7
name5; B; 3
name6; C; 0

...I should get the following results

count(dataset, "A")=2
count(dataset, "B")=2
count(dataset, "C")=0

I tried a for loop with an if statement inside but it is not working.

    function count (dataset, chosenCategory) {
    var count = 0;
    for (d in dataset) {
        if (d.category==chosenCategory && d.value>0) {
                count += 1;
            } else {
                count += 0;
            }

        }
    }

What am I doing wrong?

Simple Tic Tac Toe AI in Python 2.7 won't work

I'm creating a Tic Tac Toe game and I do it only by my idea - the online courses show a bit too difficult code for me as I am a beginner. Everything works fine in my code but when it comes to computer move there is always a problem I cannot find and solve.
I made three functions that search for a free place in a line:

  • vertical
  • horizontal
  • diagonal

By the names of that functions you can guess how my functions search.
For your information:

  • pl_array is the array which contains moves and is displayed
  • player_choice and computer_choice are the signs 'X' and 'O'
  • choice1 and choice2 was supposed to be player's and computer's signs

I want to check if computer can win and if not, check if it can block the player - that's why I created functions with choice1 and choice2 arguments.

def vertical(pl_array, choice1, choice2):
    table = [0, 1, 2]
    for item in table:
        if pl_array[0][item] == pl_array[1][item] == choice1 and pl_array[2][item] != 'X' and pl_array[2][item] != 'O':
            pl_array[2][item] = choice2
            return pl_array
        elif pl_array[1][item] == pl_array[2][item] == choice1 and pl_array[0][item] != 'X' and pl_array[0][item] != 'O':
            pl_array[0][item] = choice2
            return pl_array
        elif pl_array[0][item] == pl_array[2][item] == choice1 and pl_array[1][item] != 'X' and pl_array[1][item] != 'O':
            pl_array[1][item] = choice2
            return pl_array
        else:
            return False

def horizontal(pl_array, choice1, choice2):
    table = [0, 1, 2]
    for item in table:
        if pl_array[item][0] == pl_array[item][1] == choice1 and pl_array[item][2] != 'X' and pl_array[item][2] != 'O':
            pl_array[item][2] = choice2
            return pl_array
        elif pl_array[item][0] == pl_array[item][2] == choice1 and pl_array[item][1] != 'X' and pl_array[item][1] != 'O':
            pl_array[item][1] = choice2
            return pl_array
        elif pl_array[item][1] == pl_array[item][2] == choice1 and pl_array[item][0] != 'X' and pl_array[item][0] != 'O':
            pl_array[item][0] = choice2
            return pl_array
        else:
            return False

def diagonal(pl_array, choice1, choice2):
    if pl_array[0][0] == pl_array[1][1] == choice1 and pl_array[2][2] != 'X' and pl_array[2][2] != 'O':
        pl_array[2][2] = choice2
        return pl_array
    elif pl_array[0][0] == pl_array[2][2] == choice1 and pl_array[1][1] != 'X' and pl_array[1][1] != 'O':
        pl_array[1][1] = choice2
        return pl_array
    elif pl_array[1][1] == pl_array[2][2] == choice1 and pl_array[0][0] != 'X' and pl_array[0][0] != 'X':
        pl_array[0][0] = choice2
        return pl_array
    # The code above search for an empty place in the first line
    # and the code below does the same for the second line
    elif pl_array[0][2] == pl_array[1][1] == choice1 and pl_array[2][0] != 'X' and pl_array[2][0] != 'O':
        pl_array[2][0] = choice2
        return pl_array
    elif pl_array[0][2] == pl_array[2][0] == choice1 and pl_array[1][1] != 'X' and pl_array[1][1] != 'O':
        pl_array[1][1] = choice2
        return pl_array
    elif pl_array[1][1] == pl_array[2][0] == choice1 and pl_array[0][2] != 'X' and pl_array[0][2] != 'O':
        pl_array[0][2] = choice2
        return pl_array
    else:
        return False

Those are my three mentioned functions and the code below presents the computer's turn. To find where i made the mistake I have added the print statements but it just confused me more.

def computer_move(pl_array, player_choice, computer_choice):
    print 'Poziom 0'
    if horizontal(pl_array, computer_choice, computer_choice) == False:
        print 'Poziom 1'
        if vertical(pl_array, computer_choice, computer_choice) == False:
            print 'Poziom 2'
            if diagonal(pl_array, computer_choice, computer_choice) == False:
                print 'Poziom 3'
                if horizontal(pl_array, player_choice, computer_choice) == False:
                    print 'Poziom 4'
                    if vertical(pl_array, player_choice, computer_choice) == False:
                        print 'Poziom 5'
                        if diagonal(pl_array, player_choice, computer_choice) == False:
                            print 'Poziom 6'
                            x = random.randint(0, 2)       # it makes moves randomly
                            y = random.randint(0, 2)       # in both cases
                            while pl_array[x][y] == "X" or pl_array[x][y] == "O":
                                x = random.randint(0, 2)       # it makes moves randomly
                                y = random.randint(0, 2)
                            else:
                                pl_array[x][y] = computer_choice
                                return pl_array

I know it's a lot of code but I asked another question about it - here's link to that.
Why won't it work?
Where have I made a mistake?
Do I call if statements properly in computer's turn?
Any help appreciated.

Pig if-else condition

I have a file, that I'm loading to pig and doing some nice work on it. Everything goes smoothly until I reach to the point in which I need to use a condition, a kind of if-else statement. I want to check if the variable syn is not blank, in which case (if TRUE) the value would be 1, else it would be 0.

Here's the code

B = foreach A generate t, (syn!='' ? 1 : 0) as s;

The command runs without a glitch but when i dump the results, this happens:

(8758.414086,)
(8758.457255,1)

So when the condition is TRUE the value is added to B. But, I cannot seem to understand why on earth the else part is being left out, instead of adding the 0. Any help would be much appreciated.

Please help me to get this PHP code work correctly

<?php include 'header.php'; 
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$con = mysql_connect("localhost","root","");
$db_selected = mysql_select_db("layout",$con);
$name = $_POST['name'];
$password = $_POST['password'];
if($_POST["submit"] == "LOGIN" )
{
    $sql = "SELECT username,password from secure";
    $result = mysql_query($sql,$con);
}
while($row = mysql_fetch_array($result,MYSQL_BOTH))
{
if($row['username'] == $name and $row['password'] == $password)
   {
     echo "welcome " .$name;
   }
     else
   {
    echo "Wrong Credentials";
   }
}
?>

I'm a beginner. I wrote this PHP code for a sign in form. But it's showing "Wrong Credentials" followed by "Welcome George", even if the username and password matches. And if the username and password doesnt match it shows as "Wrong Credentials" followed by another "Wrong Credentials". Please help. Thanks in advance.

if else as part of a concatenating string

I would like to include an if statement which would check if $plan has a particular value, and echo different values according to the value. This is part of a concatenating string, and I would like it to be at the position it is currently, rather than echoing at the before $message, as it is doing currently.

if ($_POST) {
    $name = $_POST['firstlastname'];
      others
            $plan = $_POST['plan'];
    /* plan 1*/
    $plan1_width = $_POST['plan1_width'];
    $plan1_length = $_POST['plan1_length'];     

    $empty = false;

            $message = "<html><body>".
            "<h3>Client Details</h3>".
            "<p><b>Name: </b>".$name."</p>".
            "<p><b>Email: </b>".$guest_email."</p>".
            "<p><b>Phone: </b>".$phone."</p>".
            "<p><b>Address: </b>".$address."</p>".
            "<p><b>City: </b>".$city."</p>".
            "<p><b>Postcode: </b>".$postcode."</p>".
            "<p><b>Country: </b>".$country."</p>".
            "<p><b>Comments: </b><br>".$comments."</p>".
            "<hr>".
            "<h3>Tiles Selected</h3>".
            $tiles.
            "<hr>".
            "<h3>Plan</h3>".
            "<p><b>Plan Selected: </b>".$plan."</p>".
            "<hr>";
            /* point of reference */
            if ($plan == "Enkel bankskiva")  {
                echo "<p><b>Width:</b> ".$plan1_width ."</p>".
                "<p><b>Length:</b>".$plan1_length ."</p>";
            } else  {
                echo "something else";
            }
            "</body></html>";

            $to = "christabelbusuttil@gmail.com"; //<== enter personal email here

                    // headers
            $headers = "From: $email_from \r\n";
            $headers .= "Reply-To: $guest_email \r\n";
            $headers .= "BCC: krista_126@hotmail.com\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
            //Send the email!
            mail($to, $email_subject, $message, $headers);

            echo $email_subject ."<br>";
            echo $to ."<br>";
            echo $message ."<br>";
            echo $headers ."<br>"; 


        }
}

Greater than condition is met even though it should not?

In my code I am trying to make a chat delay system and all the variables are correct but the greater than condition is being met even though it should not. I added a console.log to check the numbers

    function sendChat(str) {
    if (wsIsOpen() && (str.length < 200) && (str.length > 0) &&
    (Math.round(new Date() / 1000)) > (lastchat + delay2) ) {
        for (var i = 0; i < arrayLength; i++) {
                if (str.toLowerCase().indexOf(badWords[i]) < 0){
                }
                else{
                    swear = true;
                    console.log(badWords[i])
                }
            }
        }
        if (swear == false) {
            var msg = prepareData(2 + 2 * str.length);
            var offset = 0;
            msg.setUint8(offset++, 99);
            msg.setUint8(offset++, 0); // flags (0 for now)
            for (var i = 0; i < str.length; ++i) {
                msg.setUint16(offset, str.charCodeAt(i), true);
                offset += 2;
            swear = false;
        }
        var a2 = msg;
        wsSend(msg);
        //console.log(msg);
        lastchat = Math.round(new Date() / 1000);
        console.log(Math.round(new Date() / 1000) + ">" + (lastchat + delay2))
    }
}

In console it says: main_out.js:838 1454261443>1454261445

What would it look like as an diagram if we have two sequential if statements?

I'm studying if conditions in python. And I've noticed that in any diagram they always shows for the case : if do smth. elif do smth. else do smth.

So my question is how would you make a diagram for case : if do smth. if do smth.

Rails - passing extra parameters through a link

I have two tables in my application. The user table and the activities - the user has many activities (3 in total to be exact).

I have a home page with 3 buttons on it. If the user presses button one, I want to navigate to the activities index page and set the attribute activity_type to = 1. If the user presses button 2, I want to navigate to the activities index page and set the activity_type to = 2 etc. Right now I have:

<%= link_to 'Personal Activity', user_activities_path(:user_id => current_user.id, :activity_type => 1) %>
<%= link_to 'Physical Activity', user_activities_path(:user_id => current_user.id, :activity_type => 2) %>
<%= link_to 'Community Activity', user_activities_path(:user_id => current_user.id, :activity_type => 3) %>

In my activities/index.html.erb file I want to have three conditions:

If the activity_type = 1 for current_user
  Do X
Elsif the activity_type = 2 for current_user
  Do Y
Else
  Do X
End

It doesn't seem to be recognising the activity_type parameter I have included in the link. How do I do this?

Function with Else if not working in R

I have created a function in R using if else statement inside the function.

use.switch <- function(x)
{
 if is.character(x)
{
 switch(x,
        "ram" = 1,
        "mike" = 2,
        "king" = 3,
        "others")
} else
{
 Print("Kindly provide the correct input !!!")
}
}

If i run the above code i am getting the below error message,

**Error: could not find function "Print"

} Error: unexpected '}' in "}"**

Could anyone tell me what is wrong in the above code and how to correct it.

Regards, Mohan

Emit If block condition in optimized way

I need to generate complex if conditions in my code using IL instructions.

Like (a && b) || (c && (d || e))

The components are provided as && and || operations on two Operand instances. And each Operand may be an operation itself.

Previously conditional ?: operations were used to evaluate the whole value and then perform the check.

But the emitted code were very unoptimized. The IL from the example above may be decompiled as:

(a ? b : 0) ? 1 : (c ? (d ? 1 : e) : 0)

where 0 is false and 1 is true.

I need to make an optimal implementation without using ? : .

What design or algorithm can you recommend for such purpose? Or are there any existing projects from which I can use the code?

What the hell is going on with IF in java [duplicate]

This question already has an answer here:

The result of "status" is "ok" but it doesn't seem like this in if statement. The value of "result" is "default". What the hell o.O

post_data = new JSONObject(responseText);
System.out.println("status: " + post_data.getString("status"));
if (post_data.getString("status") == "ok") {
    System.out.println("if: ok");
    result = post_data.getString("url");
} else {
    result = "default";
}

samedi 30 janvier 2016

What is happening here when the else statement is not used?

This is coding bat exercise: Java > Warmup-2 > stringX

What is the second block of code doing? Why does it produce the wrong answer?

public String stringX(String str) {
String answer = "";
for (int i = 0; i < str.length(); i++) {
if (str.substring(i , i+1).equals("x") && i != 0 && i != str.length()-1) {
answer = answer + "";
}
else {
answer = answer + str.substring(i , i + 1);
}
}
return answer;
}

vs

public String stringX(String str) {
String answer = "";
for (int i = 0; i < str.length(); i++) {
if (str.substring(i , i+1).equals("x") && i != 0 && i != str.length()-1) {
answer = answer + "";
}
answer = answer + str.substring(i , i + 1);
}
return answer;
}

can't under stand why the queue function program works at the first time but don't work like expected after that

this is my code


#include <stdio.h>
#include <stdlib.h>

int Enqueue(int[],int,int*,int);
int Dequeue(int[],int,int*,int);
int show(int[],int*);

int main (void)
{
    int q[]={1,2,3,4,5,6,7,8,9,10};
    int n = sizeof(q)/sizeof(int);
    int numelem = n;
    int l=0;
    int e=0;
    int d=0;
    while(l!=4)
    {
        printf("°°°°menu items°°°°\n");
        printf("1-->enqueue\n");
        printf("2-->dequeue\n");
        printf("3-->show\n");
        printf("4-->exit\n");
        fflush (stdin);
        scanf("%d",&l);
        if(l==1)
        {
            printf("plz enter the element you want to add --> ");
            scanf("%d",&e);
            Enqueue(q,e,&numelem,n);
            //printf("Q");
        }    
        else if(l==2)
        {
            Dequeue(q,d,&numelem,n);
        }
        else if(l==3)
        {
            show(q,&numelem);
        }
        else if(l==4)
        {
            break;
        }
        else
        {
            printf("plz enter a number from the menu!!!!!\n");
        }
    }
    printf("bye bye\n");
}
int Enqueue(int q[],int e,int *numelem,int n)
{
    int inserted=0;
    n++;
    if(*numelem<n)
    {
        inserted=1;
        q[*numelem]=e;
        *numelem+=1;
    }

    return inserted;

}
int Dequeue(int q[],int d,int *numelem,int n)
{
    int deleted=0;
    if(*numelem==n)
    {
        deleted=1;
        d=q[0];
        *numelem-=1;
        n--;
    }
    for (int i=0;i<=n;i++)
    {
        q[i-1]=q[i];
    }
    printf("the deleted item is --> %d\n",d);
    return deleted;
}
int show(int q[],int *numelem)
{
    for (int i=0;i<*numelem;i++)
    {
        printf("%d,",q[i]);
    }
    printf("\n");
    return *numelem;
}


there are no compiler error


and when you enter Equeue of Dequeue for the first time it works


but if you try again in the same time the result is unexpected


I am a student who trying to do his homework so please don't be mean in the comments and thanks any way


plz help me

Android String if use

TextView text = (TextView)findViewById(R.id.postOutput);
    String x = text.getText().toString();
    if ("hata".equals(x)){
        Toast.makeText(getApplicationContext(), "hata", Toast.LENGTH_LONG).show();
    }

if structure does not work. Help please

How to use an if statement to check if user input is a certain variable type?

I'm creating a math program where a user inputs an answer. I want to display a message that says "All solutions must be entered as decimal numbers". How would I make sure that the user inputs a double and if not display that message. I've tried this so far:

if(userLetter.equalsIgnoreCase("a")) {
    System.out.print("What is the solution to the problem:" + " " + ran1Shift + " " + "+" + " " + ran2Shift + " = ");
    double userNum = input.nextDouble();
        if(userNum == additionAnswer){
            System.out.println("That's correct!");
        }
        else{
            System.out.println("The correct solution is: " + additionAnswer);
        }
    }

So basically I have it set now to display whether the answer is exactly true or false but how could I make another part which catches if the user enters a non-double? Thank you for your help :)

My code isnt writing to a list.The error is that the details are not displayed properly at the end

This is how the code is supposed to work: User is prompted to choose a drink, then a cuisine, then a dish. After this, the program displays the order the user wanted. The problem is when the customer enters in their details,the details are not displayed properly at the end. What the code is supposed to do is displayed at the bottom.

print("Welcome to Hungary house.")
addDrink = input("Do you want a drink?\n").lower()
drinkChoice = "None"
dish = ""
order = []

if addDrink == "yes":
    print ("What drink would you prefer?")
    print ("1: Fanta")
    print ("2: Coke")
    print ("3: Pepsi")
    print ("4: Sprite")
    drinkChoice = input("please select a drink from the options above\n")

    if drinkChoice == "1" or drinkChoice == "fanta":
        drinkChoice = "Fanta"
        order.insert(0,drinkChoice)
    if drinkChoice == "2" or drinkChoice == "coke":
        drinkChoice = "Coke"
        order.insert(0,drinkChoice)
    if drinkChoice == "3" or drinkChoice == "pepsi":
        drinkChoice = "Pepsi"
        order.insert(0,drinkChoice)
    if drinkChoice == "4" or drinkChoice == "sprite":
        drinkChoice = "Sprite"
        order.insert(0,drinkChoice)

print ("you have chosen this drink: " + drinkChoice)

foodGroup = input("Do you want Indian or Chinese food?\n").lower()
if foodGroup == "indian" or foodGroup == "Indian":
    dish = input("Do you want Curry or onion bhaji?\n").lower()
    if dish == "Curry":
        order.insert(1,dish)
        dish = input("Do you want Rice or Naan?\n").lower()
        if dish == "Rice":
            order.insert(2,dish) 
        if dish == "Naan":
            order.insert(2,dish)

    if dish == "onion bhaji":
        order.insert(1,dish)
        dish = input("Do you want Chilli or Peppers?\n").lower()
        if dish == "Chilli":
            order.insert(2,dish)
        if dish == "Peppers":
            order.insert(2,dish)

if foodGroup == "chinese" or foodGroup == "Chinese":
    dish = input("Do you want Chicken Wings or Noodles?\n").lower()
    if dish == "Chicken Wings":
        order.insert(1,dish)
        dish = input("Do you want Chips or Red peppers?\n").lower()
        if dish == "Chips":
            order.insert(2,dish) 
        if dish == "Red peppers":
            order.insert(2,dish)

    if dish == "Noodles":
        order.insert(1,dish)
        dish = input("Do you want Meatballs or Chicken?\n").lower()
        if dish == "Meatballs":
            order.insert(2,dish)
        if dish == "Chicken":
            order.insert(2,dish)

print ("You have ordered the following",order,"You are order number 294")

What the code is supposed to do is displayed below.

Welcome to Hungary house.
Do you want a drink?
If no, Move on to the next question
If yes, ask what drink the customer wants.
(Coke, Fanta, lemonade are the options)
If coke is chosen, set coke as drink
If Fanta is chosen, set Fanta as drink
If Lemonade is chosen, set Lemonade as drink

Do you want Indian or Chinese food?

If Indian food is entered ask the following questions
Do you want Curry or onion bhaji?
If curry is selected ask the following questions.
What toppings you want on top of your Curry?
Rice 
Or 
Naan
If user enters rice, add rice on to the curry.
If user enters Naan, add naan on to the curry.
If user enters onion ask the following questions.
What toppings do you want on top of your onion bhaji?
Chilli source
Or 
Naan 
If user enters Chilli source, add chilli source on to the onion bhaji.
If user enters Naan, add Naan on to the onion bhaji.

.

If Chinese food is entered ask the following questions.
Do you want Chicken wings or Noodles?
If Chicken wings is chosen ask,
Do you want with your Chicken wings?
Green Peppers
Or
Red Peppers
If Green pepper is chosen add that to the Green Peppers to the Chicken wings
If Red Peppers are chosen add that to the Chicken wings.
If the user enters Noodles ask the following questions.
Choose the toppings you want with Noodles.
Meatballs 
Or
Chicken 
If user enters Meatballs, add Meatballs to the Noodles.
If user enters Chicken, add Chicken to the Noodles. 

After this, display the order the user wanted, tell the customer that their order will come within the nextemphasized text 10-50 minutes. If they wish to cancel tell them to contact this number ‘077 3475 XXXXXX’.

Code is not displaying all of the order to the list and causes SyntaxError

This program is designed to ask a customer for their order, then display their order at the end. For some reason my code isn't working - and causing a SyntaxError as well. I have displayed the plan of the code below:

print("Welcome to Hungary house.")
addDrink = input("Do you want a drink?\n").lower()
drinkChoice = "None"
dish = ""
order = []

if addDrink == "yes":
    print ("What drink would you prefer?")
    print ("1: Fanta")
    print ("2: Coke")
    print ("3: Pepsi")
    print ("4: Sprite")
    drinkChoice = input("please select a drink from the options above\n")

    if drinkChoice == "1" or drinkChoice == "fanta":
        drinkChoice = "Fanta"
        order.insert(0,drinkChoice)
    if drinkChoice == "2" or drinkChoice == "coke":
        drinkChoice = "Coke"
        order.insert(0,drinkChoice)
    if drinkChoice == "3" or drinkChoice == "pepsi":
        drinkChoice = "Pepsi"
        order.insert(0,drinkChoice)
    if drinkChoice == "4" or drinkChoice == "sprite":
        drinkChoice = "Sprite"
        order.insert(0,drinkChoice)

print ("you have chosen this drink: " + drinkChoice)

foodGroup = input("Do you want Italian, Indian or Chinese food?\n")
if foodGroup == "italian" or foodGroup == "Italian":
    dish = input("Do you want Pasta or Pizza?\n")
    if dish == "pizza":
        dish = input("Do you want Grilled chicken or Seasonal vegetables?\n")
        if dish == "seasonal vegetables":
            order.insert(1,dish) 
        if dish == "grilled chicken":
            order.insert(1,dish)

    if dish == "pasta":
        dish = input("Do you want Vegetarian Toppings or meat toppings?\n")
        if dish == "Vegetarian Toppings":
            order.insert(1,dish)
        if dish == "meat toppings":
            order.insert(1,dish)

if foodGroup == "indian" or foodGroup == "Indian":
    dish = input("Do you want Curry or onion bhaji?\n")
    if dish == "Curry":
        dish = input("Do you want Rice or Naan?\n")
        if dish == "Rice":
            order.insert(1,dish) 
        if dish == "Naan":
            order.insert(1,dish)

    if dish == "onion bhaji":
        dish = input("Do you want Chilli or Peppers?\n")
        if dish == "Chilli":
            order.insert(1,dish)
        if dish == "Peppers":
            order.insert(1,dish)

if foodGroup == "chinese" or foodGroup == "Chinese":
    dish = input("Do you want Chicken Wings or onion Noodles?\n")
    if dish == "Chicken Wings":
        dish = input("Do you want Chips or Red peppers?\n")
        if dish == "Chips":
            order.insert(1,dish) 
        if dish == "Red peppers":
            order.insert(1,dish)

    if dish == "Noodles":
        dish = input("Do you want Meatballs or Chicken?\n")
        if dish == "Meatballs":
            order.insert(1,dish)
        if dish == "Chicken":
            order.insert(1,dish)            

print ("You have ordered",order"enjoy your meal")

This is how the code is supposed to work: User is prompted to choose a drink, then a cuisine, then a dish. After this, the program displays the order the user wanted.

How to have 3 conditions using both if and while Javascript

Javascript beginner here. I'm trying to compute a simple math function using a window prompt(What is 3+3=?). If the user gets the answer right I want it to report back (Correct!), but if they're one away from the correct answer (5 or 7) I want it to report back another window prompt saying (Very close please try again. What is 3+3?) But also, if they get the answer completely wrong(lets say they put in 2) I want it to report back (Incorrect please try again. What is 3+3=?) This third condition is what is giving me problems because I need 2 separate loops in the script and I'm not sure how to go about doing that.

This is my code so far, where I've got stuck is the third while loop

var answer = window.prompt("What is 3+3", "");
    answer=parseFloat(answer);

if(answer==6){
      document.write("Correct!");
}else while( answer==5 || answer==7){
      answer=window.prompt("Very Close Please Try again. What is 3+3", "");
}else while(answer!==6 && answer!==5 && answer!=7){
    answer=window.prompt("Incorrect. Please try again. What is 3+3", "");
}

also bonus points to anyone that can explain how I would use a random number and have answer to this number instead of the hard coded 3+3 and its answer.

PHP: syntax error, unexpected 'else'

I got a syntax error when trying to set an username in my header, handling the exception when no first name and last name is seated, using the username to fill the label, surely is a stupid error. I'm using Quadodo Login Script in my project by the easily implementing.

Here is the code:

if(isset($qls->user_info['firstname'] { 
  $realname = "$qls->user_info['firstname'] . ' ' . $qls->user_info['lastname']"
} else { 
  $realname = "$qls->user_info['username']"
};

Thanks a lot in advantage. Andrea

How can I get my code to conditionally loop back to its start?

I'm very much a beginner at Java. I am in my second week of my first course at college and already love programming. I've been trying to use some of the stuff I've learned in lecture and lab to create a little game but I'm having some issues.

The code is as follows:

public class MathGame {
public static void main(String args[]){

    System.out.println("~~~~Welcome to ____!~~~~~");
    System.out.println("Press 'S' to continue");

    char startGame;
    char correctStart = 'S';
    startGame = TextIO.getChar();
    if (startGame == correctStart){

        System.out.println("Both you and the computer will start with 20 lives");   //Game explanation
        System.out.println("Use different move options to reduce your opponents life");
        System.out.println("First one down to zero loses!");
        System.out.println("OK here we go:");


        int lifeTotal1 = 10;
        int lifeTotal2 = 10;
        int turnNum = 0;
        turnNum ++;

        System.out.println("Start of turn: " + turnNum);
        System.out.println("Your life total is " + lifeTotal1 + " your opponents life total is " + lifeTotal2);     //Starts turn
        System.out.println("Select a move:");
        System.out.println("Press 1 to do 3 damage");
        System.out.println("Press 2 to do a random amount of damage");
        System.out.println("Press 3 to heal 2 damage");

        int userAttack1;
        userAttack1 = TextIO.getInt();

        if(userAttack1 == 1){           //User attack #1 selected
            lifeTotal2 -=3; 
        }
        if(userAttack1 == 2){           //User attack #2 selected
            double random1 = Math.random();
            if (random1 > 0 && random1 <= .2){
                lifeTotal2 -= 1;
            }
            if (random1 > .2 && random1 <= .4){
                lifeTotal2 -= 2;
            }
            if (random1 > .4 && random1 <= .6){
                    lifeTotal2 -= 3;
            }
            if (random1 > .6 && random1 <= .8){
                    lifeTotal2 -= 4;
            }
            if (random1 > .8 && random1 <= 1){
                        lifeTotal2 -=5;
            }
        }

        if (userAttack1 == 3){
            lifeTotal1 += 2;
        }

    System.out.println("End of turn");
    System.out.println("Your current health is " + lifeTotal1);
    System.out.println("Your opponents current health is " + lifeTotal2);

    if (lifeTotal1 <= 0){
        System.out.println("Game over, you lose");
    if (lifeTotal2 <= 0){
        System.out.println("Game over, you win");
    }
        }else{

After the else statement I've literally just copy and pasted the code to start a new turn until one of the life totals gets down to 0. This is an issue though because it creates a finite number of turns. How can I get my code to keep looping until a life total reaches zero?

I understand the game is no where near complete. I would appreciate any help! Thanks so much

Java if else statement doesn't work with Scanner [duplicate]

This question already has an answer here:

I am trying to make a program that asks for the user's name, and prints "We have the same name" if the user enters "Charles". When I run it, I type in "Charles", but it prints "We don't have the same name". Any suggestions?

package testing;

import java.util.Scanner; public class testing {

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    String Name;
    System.out.print("Enter your name: ");
    Name = userInput.nextLine();
    System.out.println(Name);
    if(Name == "Charles"){
        System.out.println("We have the same name!");
    }
    else{
        System.out.println("We don't have the same name");
    }
}

}

Java: if statement works only after a system.out.println()

i need your help to solve this strange behavior! i've a class, that contains a public boolean variable: running. Through a button i can set "running" true or false. In the main class, in the main function i have what follows:

the point is that written in this way the code doesn't work! It works if i add a System.out.println(running); before the if condition! Do you know why?

i've also tried creating a method, inside the class, boolean isRunning() that return a boolean but it does not work.

public static void main(String[] args) {

Gui frame = new Gui();
frame.setVisible(true);


    String received = "";

    while(true){

        if (running ==  true){
            System.out.println(frame.running);

            try {
                Thread.sleep(1000);                
                } 
            catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }       
            ricevuti = frame.arduino.receivedstring;
            if(ricevuti.isEmpty()){
               // do something
                }
            else {
                int [] intArray = null;
                intArray = frame.arduino.parsing(ricevuti, " ");
                System.out.println(intArray.toString());
            }

        }
    }
}

Thank you so much!

Char compare in if statements not working properly

I have a couple of if statements comparing a private char of a class with a character (like 'c' or 'd'), but it isn't assigning the right value when I run it, and I don't know what the problem is. Here's the code:

ostream & operator<<(ostream &out, const Card &rhs)
{

    string string_suit;
    string string_rank;

    /*switch(rhs.suit)
    {
        case 'c': string_suit="Clubs"; 

        case 'd': string_suit="Diamonds"; 
                  break;
        case 'h': string_suit="Hearts"; 
                  break;
        case 's': string_suit="Spades"; 
                  break;
        default : string_suit= "error"; 
    }*/

    if(rhs.suit == 'c')
    {
    string_suit="Clubs";
    }

    else if(rhs.suit == 'd')
    {
    string_suit ="Diamonds";
    }

    else
    {
    string_suit = "error";
    }


    if(rhs.rank==1)
    string_rank="Ace";

    else if(rhs.rank==11)
    string_rank="Jack";

    else if(rhs.rank==12)
    string_rank="Queen";

    else if(rhs.rank==13)
    string_rank="King";


    else
   {

     ostringstream convert;
     convert << rhs.rank;
     string_rank=convert.str(); //rhs.rank;
   }   

    out<<string_rank<<" of "<<string_suit ;
    return out;


}

How can I use multiple operands in an if condition (ModX)

I am using the if-extra for ModX. Is it possible to use mutliple operands, meaning write this code in a shorter way:

  [[!If?
       &subject=`[[!getUrlParam? &name=`id`]]`
       &operator=`EQ`
       &operand=`1`
       &then=`do something`
    ]]


[[!If?
   &subject=`[[!getUrlParam? &name=`id`]]`
   &operator=`EQ`
   &operand=`2`
   &then=`do something`
]]


[[!If?
   &subject=`[[!getUrlParam? &name=`id`]]`
   &operator=`EQ`
   &operand=`3`
   &then=`do something`
]]

Couldn't find a way to do it.

Apply condition to MySQL as a result of IF statement

I have a query:

SELECT campaign_id, campaign_balance, campaign_email
FROM campaigns
WHERE campaign_unique = 0
LIMIT 1

But I only want to apply the WHERE campaign_unique = 0 condition to the above query when the following returns a one:

SELECT COUNT(earning_id) FROM earnings WHERE earning_ip = '77.166.56.152' LIMIT 1

Is there some way I can apply an IF statement to decide whether or not to apply a WHERE condition?

How to avoid short-circuited evaluation in JavaScript?

I need to execute both sides of an && statement, but this won't happen if the first part returns false. Example:

function checkSomething(x) {
    var not1 = x !== 1;
    if (not1) doSomething();

    return not1;
}

function checkAll() {
    return checkSomething(1)
        && checkSomething(2)
        && checkSomething(3)
}

checkAll();

The problem here is that doSomething() should be executed twice, but because checkSomething(1) returns false, the other checks won't be called. What is the easiest way to run all the checks and return the result?

I know I could save all the values in variables and check those subsequently, but that does not look very clean when I have a lot of checks, so I am looking for alternatives.

vendredi 29 janvier 2016

making if conditions faster

I'm trying to get this function to work and to run faster. It takes as input a matrix, and checks to see if x and y are both greater than 0 but less than 10. Having it run faster is also key because it currently takes long with all of these conditional statements

m 
   x  y
B -1 -1
C 50 11
D 50  5
A 51 10

val_10 = 10
myfun(m, val_10)

and the output should looks like this

     [,1] [,2]
[1,]    0   0
[2,]   10   10
[3,]   10    5
[4,]   10   10

but instead it looks like this

     [,1] [,2]
[1,]    0   -1
[2,]   10   11
[3,]   10    5
[4,]   10   10

m[1,2] should be 0 and m[2,2] should be 10 in the output

myfun looks like this

myfun = function(m, val_10){
v = matrix(NA, nrow = nrow(m), ncol = 2)
for (i in 1:nrow(m) ) {
    old = m[i, ]

    #check if smaller than 0
    if (m[i,1] < 0) {
        m[i, ] = c(0, old[2])
    }

    #check if bigger than val_10
    else if (m[i,1] > val_10 ){ 
        m[i, ] = c(val_10, old[2] )
    }

    #check if smaller than 0
    else if (m[i, 2] < 0){
        m[i, ] = c(old[1], 0)
    }

    #check if bigger than val_10
    else if (m[i, 2] > val_10){
        m[i, ] = c(old[1], val_10 )
    }

    v[i,] = m[i, ]
}
return(v)
}

Can't get nested IF's to work properly in C#. What am I doing wrong?

What am I doing wrong exactly? I am not certain if the "&&" in the if conditions is what is causing the issue or if it is something else. I get a red mark underneath the ">=" part of the condition in every single "if". Can someone tell me how to remedy the issue?

  static void Main(string[] args)
    {
        Int32 pointsEarned;
        string firstName;
        string lastName;
        Int32 percentageGrade;
        Console.WriteLine("Enter the student's first name.");
        firstName = Console.ReadLine();
        Console.WriteLine("Enter the student's last name.");
        lastName = Console.ReadLine();
        Console.WriteLine("Enter the amount of points earned.");
        pointsEarned = int.Parse(Console.ReadLine());
        percentageGrade = pointsEarned / 1000;
        if (percentageGrade <=100 && >= 90);
        {
            string finalGrade = "A";
        }
        else if (percentageGrade <=89 && >= 80 );
        {
            string finalGrade = "B";
        }
        else if (percentageGrade <= 79 && >= 70);
        {
            string finalGrade = "C";
        }
        else if (percentageGrade <= 69 && >= 60);
        {
            string finalGrade = "D";
        }
        else if (percentageGrade <= 59 && >= 0);
        {
            string finalGrade = "F";
        }


    }
}

}

Java finding the minimum value from Scanner input always resulting in zero

This is my first Java program. It is supposed to allow a user to enter int grades between 0 and 100. If the user enters a negative value, data entry ceases and statistics are displayed. I cannot incorporate static methods, math, or arrays.

I am having an issue with finding the minimum grade, minGrade. Regardless of what values are entered when the program is running, minGrade always results in zero. I have been tinkering with this for a while now to no avail.

The other issue I am having is that when I run the program, and I enter a bunch of int, but then enter some alphabet letters to test the error-checking, the program parses the user twice, instead of once.

"Please enter a numeric grade between 0 and 100, inclusive, and press Enter:"

The respective code is:

import java.util.Scanner;


public class Grades {

    public static void main(String[] args) 
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter the Course Code and and press Enter:");
        String courseCode = keyboard.nextLine();
        System.out.println("You entered: " + courseCode + "\n");

        int grade = 0;

        int numberOfGrades = 0;
        int maxGrade = 0;
        int minGrade =0;
        double avgGrade = 0;
        int sumGrades = 0;

        int sentinel = 0;



        do

        {


                **System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");**
                while(!keyboard.hasNextInt())
                {

                    System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");
                    keyboard.nextLine();

                }

                grade = keyboard.nextInt();
                if((grade <=100) && (grade >= 0))
                {
                    numberOfGrades++;
                    sumGrades += grade;
                    sentinel = 0;

                    if(maxGrade < grade)
                        maxGrade = grade;

                    **if(minGrade > grade)
                        minGrade= grade;**
                }
                else if(grade > 100)
                {

                    System.out.println("The entered number was greater than 100. Please enter a number between 0 and 100 inclusive, "
                            + "or input a negative number to exit Grade entry");
                    sentinel = 0;
                }
                else if(grade <0)
                {
                    grade = 0;//maybe?
                    sentinel = -1;

                }

        }
        while((grade >100) || (sentinel == 0));


        avgGrade = (sumGrades/numberOfGrades);



        System.out.println("You entered: " + "\ngrade: " + grade + "\n" + "sentinel: "+ sentinel +
                "\nSum of Grades: " + sumGrades +"\nNumber of Grades: "+ numberOfGrades +"\nAverage Grades: " + avgGrade
                + "\nMaxium Grade: "+ maxGrade+"\nMinimum Grade: "+minGrade);
    }

}

Any input on this, the form of my code for my first java program, or anything else would be greatly appreciated.

The last issue I am having is that the average grade always has a tenth place of zero. How can I get the tenth place to not be zero and the actual average amount?

C: why does my nested if else statement not work

I am making a greedy algorithm to calculate number of coins in a value in cents stored in a variable. I had it all working out basically, but I had no way of differentiating between singular and plural for the denominations, ( printing "1 quarters" instead of "1 quarter" for example) and the way how I was doing it with sequential if conditions for each denomination, I couldn't do the same for singular or plural differentiation for each coin since it would give me back two quarters and one quarter instead of either or, so I'm trying to use an if else statement but it says that the else statement basically has no if statement to relate to which I don't understand. My compiler also says that the if statement nested in the other one has "no body" for some reason.

Don't mind the scanf, I will change to a better input method once I get the rest figured out.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (void)
{
int n;
scanf("%d",&n);
int q = (n/25);
     if
(n > 24)
  {
      if (n > 49);
  {printf("%d quarters\n", q); }
  else
  {printf("one quarter\n");}
  }
    return 0;
}

Access array in if statement

I have JavaScript calculator wherein I have defined two arrays as follows:

var degInc, degArr = []; 
var radInc, radArr = [];
var PI = Math.PI;
var radStart = (-91*PI/2), radEnd = (91*PI/2);

 for (degInc = -8190; degInc <= 8190; degInc+=180) {
       degArr.push(degInc);
    }
 for (radInc = radStart; radInc <= radEnd; radInc+=PI) {
        var radIncFixed = radInc.toFixed(8);
       radArr.push(radIncFixed);
    }

to be used in conjunction with the tangent function (below) so as to display a value of Undefined in an input (HTML below) should the user attempt to take the tangent of these values (I have included other relavent function as well):

Input -

<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>

Functions -

function tan(form) {
  form.display.value = trigPrecision(Math.tan(form.display.value));
}

function tanDeg(form) {
  form.display.value = trigPrecision(Math.tan(radians(form)));
}

function radians(form) {
  return form.display.value * Math.PI / 180;
}

with jQuery -

$("#button-tan").click(function(){
        if (checkNum(this.form.display.value)) {
            if($("#button-mode").val() === 'DEG'){
                tan(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR RAD ARRAY
            } 
            else{
                tanDeg(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR DEG ARRAY
            }

        }
});

I would like to incorporate an array check within the .click function such that if the user input is contained in the array (degArr or radArr depending on the mode), the calculator returns Undefined. Now, I know how to display Undefined in the input display ($('#disp').val('Undefined')), but I cannot figure out how to configure an if statement that checks the relevant array. Is there a way to do so within the #button-tan function where I have commented?

Stop Moving object. If statement causing problems. (Objective-C)

I am working on my first project in objective-c and I am trying to make an object (that I have coded to move right) run code for the end of the game once it reaches a certain point. I run my app and the object just keeps moving right with no stop. I need to know what I need to do so that game over runs once the object reaches the given point. Any help would be greatly appreciated. I am just getting started with my first project so it is probably something very simple and obvious but I just have not been able to find the answer to my problem anywhere. Again Thanks.Here is my code.

        #import "Game.h"

    @interface Game ()

        @end


        @implementation Game

        -(IBAction)Play:(id)sender{


        PieceMovement = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(PieceMoving) userInfo:nil repeats:YES];

        Play.hidden = YES;

    }

    -(void)GameOver{
        Leave.hidden = NO;
        [PieceMovement invalidate];
    }



    -(void) PieceMoving{
        Piece.center = CGPointMake(Piece.center.x +5, Piece.center.y);

        if (Piece.center.y == 200) {
            [self GameOver];
        }

    }
    - (void)viewDidLoad{
        Leave.hidden = YES;

    }


    @end

-------Game.h

#import <UIKit/UIKit.h>

@interface Game : UIViewController

{
    IBOutlet UIImageView *Piece;
    IBOutlet UIImageView *Chunk;
    IBOutlet UIButton *Play;
    IBOutlet UIButton *Leave;



    NSTimer *PieceMovement;


}

-(IBAction)Play: (id)sender;

-(void)PieceMoving;
-(void)GameOver;

@end

--------Game.h

#import <UIKit/UIKit.h>

@interface Game : UIViewController

{
    IBOutlet UIImageView *Piece;
    IBOutlet UIImageView *Chunk;
    IBOutlet UIButton *Play;
    IBOutlet UIButton *Leave;



    NSTimer *PieceMovement;


}

-(IBAction)Play: (id)sender;

-(void)PieceMoving;
-(void)GameOver;

@end

C - Print list of Prime Numbers (recursion)

I'm having some problems with this C programming assignment that I have in school. I'm supposed to return the prime numbers from within a given range, and it has to be done using recursion.

The code I've got so far is this:

#include <stdio.h>
#include <stdlib.h>

int primeNumberList(int n, int m, int z);

int main()
{
    int n1 = 0,
        n2 = 10,
        d = 2;

        printf("n1 = %d | n2 = %d | d = %d\n\n", n1, n2, d);

        printf("Prime Numbers between %d and %d are: \n", n1, n2);

        primeNumberList(n1, n2, d);

        printf("\n\n");


    return 0;
}


int primeNumberList(int n, int m, int z){
    int notPrime = 0;

    if(n <= 1){
        primeNumberList(n+1, m, z);
    }
    else if(n < m)
    {
        if(z <= n/2)
        {
            if(n%z == 0)
            {
            notPrime = 1;
            z = 2;
            }
            else
            {
            primeNumberList(n, m, z+1);
            }
        }
        if(notPrime == 0)
        {
            printf("%d ", n);
        }
        primeNumberList(n+1, m, z);
    }
}

What happens when I run this, is that after it's gone through all the numbers up to the limit (in the function it's 'm'(n2 in main)) it won't break the recursion, but somehow manage to withdraw numbers from n, and keeps giving some other numbers that are not prime numbers. When I run it in debug, it seems to be looping at the end, but there's nothing there to loop... I've tried adding a "return 0;" or even a printf with some text, but it ignores it completely.

Can anyone see what I've done wrong here? Why doesn't it stop when "n < m"?

Thanks in advance!

Pomodoro Clock not Stopping after countdown

The clock works until it gets to zero which is where it is supposed to start the break timer. the issue is that it gets to zero then starts counting down in negative numbers. here is the function that has that code. By the way, I have the interval at 100 so I do not have to wait a long time when testing the clock.

//This function is the culprit
function start(){
   $("#start").addClass("disabled");
   $("#myreset").addClass("disabled");
   var secs = Number("59");

   var min = document.getElementById("sessiontime").innerHTML; 
   min = min-=1;

   if(min > -1){
      startcounter = setInterval(function(){
      secs--;

         if(secs > 9){
            document.getElementById("mytimer").innerHTML = min +":"+ secs;
               } else if(secs >=0 && secs < 10){
                  secs = "0"+secs;
                  document.getElementById("mytimer").innerHTML = min +":"+ secs;
                     } else if(secs < 0){
                        min--;
                        secs = 59;
                           } else if(secs === 0 && min === 0){
                              clearInterval(startcounter); 
                              var x =      document.getElementById("arrownumid").innerHTML;
                        mybreak(x);
                     }
      },100);

   }
}

Simpe if and else in C programming

I want to make this program say that if you enter 1 the screen will display "yes G is the 1st note in a G chord", if you enter anything else it will print "wrong!" and then loop back into the beginning, here is my attempt at it. Also, I know there are different ways to do this, but it is for a school assignment and the enum data-type is necessary, though this code is far reaching for just displaying use of enum, it bothers me I can't get this to work. Any pointers? (no pun intended).

    enum Gchord{G=1,B,D,};
    int main()                            
    {   printf( "What interval is G in the G chord triad \nEnter 1 2 or 3\n" );  
int note;
 scanf("%i",&note);    

if (note = 1 ){                 
    printf ("Yes G is %ist note in the G-chord\n",G )};
else(
printf("no, wrong");     
return(0):       
};

How to add class in angular using ng-repeat for adding a review purposes?

enter image description here

This is what i have so far, my data(retrieved via get: method expecting json) and the html part will do the ng-repeat for review in reviews; adding class filled. But it just add's filled to all. Open to any suggestion's, like this directives as well.

$scope.data = [{
    "_id": "56aa6f601c5e0d520e4a54ca",
    "index": 0,
    "picture": " http://ift.tt/23yGF9V",
    "rating": 5,
    "name": "Kelli Alexander",
    "comment": "Eu mollit officia enim cupidatat consequat. Elit ex reprehenderit sint veniam Lorem in ad non exercitation fugiat dolore esse ex. Exercitation occaecat ut dolore voluptate labore minim eiusmod ea quis. Consectetur deserunt id minim exercitation eu sit Lorem laboris. Nulla minim ea fugiat ex sit pariatur adipisicing incididunt officia nisi. Incididunt dolore consectetur sunt quis irure in. Labore ipsum deserunt dolor quis incididunt occaecat minim mollit mollit incididunt officia reprehenderit ut ipsum.\r\n",
    "registered": "2014-06-09T04:11:13 +05:00",
}, {
    "_id": "56aa6f602b63c7bef8e4ad4b",
    "index": 1,
    "picture": " http://ift.tt/23yGF9V",
    "rating": 3,
    "name": "Hopper Buck",
    "comment": "Eiusmod aliquip pariatur consequat et eu laboris. Mollit mollit reprehenderit enim sint incididunt dolor aliqua Lorem commodo aute aliqua aliquip. Et pariatur exercitation culpa irure occaecat. Elit id laboris quis culpa quis aute dolor consequat excepteur officia enim ullamco enim elit. Sunt pariatur reprehenderit quis commodo velit enim exercitation mollit.\r\n",
    "registered": "2014-04-11T03:22:35 +05:00",
}, {
    "_id": "56aa6f60fe9bae6d177b7137",
    "index": 2,
    "picture": " http://ift.tt/23yGF9V",
    "rating": 2,
    "name": "Vera Mcfadden",
    "comment": "Ipsum consectetur ipsum velit do nostrud officia excepteur. Laboris qui consectetur officia culpa est mollit ex. Ea qui proident ut aute consequat ea proident quis duis.\r\n",
    "registered": "2015-10-05T12:46:04 +05:00",
}, {
    "_id": "56aa6f60d60a0c80b87fa3ed",
    "index": 3,
    "picture": " http://ift.tt/23yGF9V",
    "rating": 3,
    "name": "Howard Christensen",
    "comment": "Pariatur commodo dolore ipsum aute cupidatat ipsum adipisicing voluptate sit voluptate commodo. Sint cupidatat eu sunt Lorem ad. Enim ex irure sit tempor culpa. Culpa cillum commodo duis laborum pariatur do aliqua culpa commodo consectetur eiusmod. Sit esse aute ad cupidatat do et Lorem ut tempor cillum. Proident consequat reprehenderit nulla excepteur elit ea exercitation adipisicing. Excepteur ullamco tempor ipsum ipsum Lorem tempor fugiat amet Lorem.\r\n",
    "registered": "2015-09-04T10:09:25 +05:00",
}, {
    "_id": "56aa6f60ba2f88f333bba049",
    "index": 4,
    "picture": " http://ift.tt/23yGF9V",
    "rating": 3,
    "name": "Burke Reilly",
    "comment": "Do ex culpa adipisicing commodo ut aute consectetur cillum est eiusmod ut minim excepteur. Reprehenderit ex incididunt occaecat commodo magna est commodo reprehenderit non ullamco. Lorem proident velit incididunt nostrud labore mollit laboris nostrud ut commodo fugiat. Sint aliqua laborum laboris mollit magna proident. Veniam anim ad in aute sunt reprehenderit ullamco nisi sunt velit consequat amet. Nisi ea amet in labore.\r\n",
    "registered": "2014-11-18T09:16:38 +06:00",
}, {
    "_id": "56aa6f6061f6d711988c5521",
    "index": 5,
    "picture": " http://ift.tt/23yGF9V",
    "rating": 3,
    "name": "Robyn Douglas",
    "comment": "Proident cupidatat incididunt ut anim sit excepteur esse ad veniam reprehenderit. Nisi dolor labore occaecat irure reprehenderit deserunt aute amet. Magna veniam sint velit esse laboris officia est in ipsum tempor voluptate quis sunt. Proident eu duis elit aliqua non anim consectetur consequat ut do.\r\n",
    "registered": "2015-12-18T01:58:11 +06:00",
}, {
    "_id": "56aa6f6018d679470f9c656c",
    "index": 6,
    "picture": " http://ift.tt/23yGF9V",
    "rating": 4,
    "name": "Avery Merritt",
    "comment": "Adipisicing proident consequat do aliquip. Anim magna deserunt ut culpa. In exercitation tempor quis in nisi nisi et velit nulla ea. Anim consequat mollit incididunt velit labore culpa qui consectetur in. Aliqua reprehenderit nostrud officia aliquip officia id amet ut proident aliquip adipisicing. Sunt incididunt minim et minim.\r\n",
    "registered": "2015-12-18T01:58:11 +06:00",
}];

add max 5 circles :

 <i class="ion-ios-circle-filled" ng-class="{filled: review.rating}" ng- repeat="n in range(5) track by $index"></i>

First do-while loop not functioning properly

There seems to be something with my code. My code detects non-integers and keep asking the user to input a positive #, but when you insert a negative #, it just ask the user to input a positive just once. What is wrong? Something with my do-while loop for sure. I'm just focusing on the firstN, then I could do the secondN.

import java.util.Scanner;

public class scratch {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int firstN = 0;
    int secondN = 0;
    boolean isNumber = false;
    boolean isNumPos = false;

    System.out.print("Enter a positive integer: ");

    do {
        if (input.hasNextInt()) {
            firstN = input.nextInt();
            isNumber = true;
        }
        if (firstN > 0) {
            isNumPos = true;
            isNumber = true;
            break;
        } else { 
            isNumPos = false;
            isNumber = false;
            System.out.print("Please enter a positive integer: ");
            input.next();
            continue;

        }

    } while (!(isNumber) || !(isNumPos));

    System.out.print("Enter another positive integer: ");
    do {
        if (input.hasNextInt()) {
            secondN = input.nextInt();
            isNumber = true;
        }
        if (secondN > 0) {
            isNumPos = true;
            isNumber = true;
        } else {
            isNumPos = false;
            isNumber = false;
            System.out.print("Please enter a positive integer: ");
            input.next();
        }

    } while (!(isNumber) || !(isNumPos));

    System.out.println("The GCD of " + firstN + " and " + secondN + " is " + gCd(firstN, secondN));

}

public static int gCd(int firstN, int secondN) {
    if (secondN == 0) {
        return firstN;
    } else
        return gCd(secondN, firstN % secondN);
}

}

looping through result array and adding var from if elseif

I have a query that sums a column as totalSales grouped by id. I then take that result and run a if elseif statement on it.

 /* execute query */
$result->execute();
/* bind result variables */
$result->bind_result($accountNumber, $accountName, $totalSales);

 //get amount needed for next tier
//create variables, one from query and empty to hold result
$needed = "";

while ($result -> fetch()) {

if     ($row['totalSales'] < 1001.00) {
        $needed = (1001.00 - $row['totalSales']);
}
elseif ($row['totalSales'] < 2501.00) {
        $needed = (2501.00 - $row['totalSales']);
}
elseif ($row['totalSales'] < 5001.00) {
        $needed = (5001.00 - $row['totalSales']);
}
elseif ($row['totalSales'] < 10001.00) {
        $needed = (10001.00 - $row['totalSales']);
}
elseif ($row['totalSales'] < 15001.00) {
        $needed = (15001.00 - $row['totalSales']);
}
};

Then I take the results and add them to an array again.

$customers[] = array(
    'AccountNumber' => $accountNumber,
    'AccountName' => $accountName,
    'Amount' => $totalSales,
    'Needed' => $needed
    );

I get only one result instead of 5 grouped together with the amount needed to get to the next tier.

I have tried to explode the array and do it separately then add a the result back in using array_push but didn't add it to the array with the rest of the associative array. Can this be done in the while loop or do I need to another way.

If statement works in console, not in source

I have the following if statement within a click function:

$('#rent-link').on('click', function() {
  $('.house-card:not(.sold)').fadeIn('fast');
  $('.for-sale').fadeOut('fast');
  $('.rental').fadeIn('fast');
  $('.sold').fadeOut('fast');
  $('.comm').fadeOut('fast');
  if ( $('.house-card:visible').length == 0 ) {
    $('#no-results').show();
  }
  return false;
});

All of the code is wrapped in a doc ready function so that can't be the problem. I am not sure why that when the parameters are set for this if statement to resolve true, it always resolves false. When I click #rent-link and then run the if statement alone in console it resolves true.

Thanks for the help.

multiple criteria from more than one column to create a new categorical variable

Normally if I want to assign a categorical variable based on the value of another variable I do something like this:

iris$Criteria <- ifelse(iris$Petal.Width>0.3,"High","Low")

However, I am not sure how to accomplish this task if I am basing the categorical variable on the value of two variables. I can do it like this:

iris$Criteria <- ifelse(iris$Petal.Width>0.3 & iris$Species=="setosa","High",
                    ifelse(iris$Petal.Width>1.3 & iris$Species=="versicolor","V_High","Low"))

But for a large dataset with many such comparisons the code get really clunky and more important almost unreadable. I am trying to make code that people can see the criteria I applied very quickly and easily. So I am wondering if people have a better strategy to do this.

Any help would be much appreciated.

Perl Session Variables Do Not Update During If Statement

This form on submit runs two types of AJAX calls, one just sends the form data and it gets stored into session variables (the first if statement) and the second polls the same form but hits the elsif statement to get a read out of what is being stored into the session variables.

The AJAX works and the session storage works, what seems to be the problem is that the session data isn't being updated whilst the first if statement is running.

The end goal of this program is to fire of many system scripts on submit and report back on their status via the polling AJAX. I've created a fake work script to test this even though I will be using non Perl scripts in the final version.

Like I said, it seems that if script 1 is complete, the session variable isn't updated until the entire if statement is over. I don't know how that is possible but I know for sure that the session variables are not being updated in real time as the poll comes back with either complete or null. (It only returns complete when I remove the $session->delete; line, which isn't meant to fire until after 30 seconds in this example.)

What I need is a solution so that as soon as a script finishes and updates the session storage, I can see that with my polling AJAX.

form.cgi

#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use CGI::Carp 'fatalsToBrowser'; # sends error messages to the browser!
use CGI::Session;
use JSON;

my $workTimer = 15; # In seconds.

my $query = CGI->new();
my $session = CGI::Session->new($query);
print $session->header();

if(defined $query->param('name') && defined $query->param('number') && defined $query->param('email')){

    $session->param('name', $query->param('name'));
    $session->param('number', $query->param('number'));
    $session->param('email', $query->param('email'));

    # 'inactive', 'in-progress', 'failed', 'complete' -> To be sent to client.
    $session->param('script1', 'inactive');
    $session->param('script2', 'inactive');

    # Set script 1 up.
    $session->param('script1', 'in-progress');
    my $script1 = `perl do-work.pl $workTimer` || $session->param('script1', 'failed');
    # Check the return value of the script.
    if($script1 != 1){
        $session->param('script1', 'failed');
    }else{
        $session->param('script1', 'complete');
    }

    # Set script 2 up.
    $session->param('script2', 'in-progress');
    my $script2 = `perl do-work.pl $workTimer` || $session->param('script2', 'failed');
    # Check the return value of the script.
    if($script2 != 1){
        $session->param('script2', 'failed');
    }else{
        $session->param('script2', 'complete');
    }

    # Clear session here!
    $session->delete;
}
elsif(defined $query->param('polling')){
    my @pollingArray = ();

    push(@pollingArray, $session->param('script1'));
    push(@pollingArray, $session->param('script2'));

    my $json->{"poll-reply"} = \@pollingArray;
    my $json_text = to_json($json);

    print "$json_text";
}
else{
    HTML goes here...
}

do-work.pl

#!/usr/bin/perl

use strict;
use warnings;

# Declare initial variables.
my $workDuration;
my $sec = time();

# Check for arguments.
if(1 == scalar $#ARGV + 1){
    my $var = $ARGV[0];
    if(!($var - int($var))){
        $workDuration = $var;
    }
    else{
        print 0;
        exit;
    }
}
else{
    print 0;
    exit;
}

# Run while loop for duration of work.
while(time() < $sec + ($workDuration)){
    # Do work here...
}

print 1;
exit;

app.js

var polling;

$('#submit').on("click", function(e){
    e.preventDefault();

    $.ajax({
        url: "/form/form.cgi",
        type: "post",
        data: {
            name: $('#name').val(),
            number: $('#number').val(),
            email: $('#email').val()
        },
        success: function(data){
            console.log(data);
        }
    });

    polling = pollingForStatus();
});

function pollingForStatus(){
    return window.setInterval(function(){ 
        $.ajax({
            url: "/form/form.cgi",
            type: "post",
            data: {
                polling: "poll"
            },
            success: function(data){
                console.log(data);
                if(data === "off"){
                    window.clearInterval(polling);
                }
            }
        }); 
    }, 1000);
}

Check username(u) and password(p) to display all outcomes -empty fields,wrong u,wrong p, wrong u and p,correct u and p depending on the input?

if(username or password field is empty) { display msg; } else if(username and password field is correct) { display msg } else if (username field is wrong) { display msg; } else if (password field is wrong) { display msg; } else (username and password field is wrong) { display msg; }

Excel using proper formula, Lookup vs Vlookup vs IF

Trying to write a formula for Excel, Using 2 worksheets. to classify the invoices

Worksheet 1 has Group Name and Group ID

Worksheet 2 has Group Name, invoice amount,invoice number

Trying to get the Group ID to worksheet 2, keeping in mind a ID can be use multiple times

Using formula below but the IDs I'm getting back aren't matching

=LOOKUP(F2,GROUP!C:C,ID!B:B)

Any help would be appreciated

How to compare strings in ada 95

I'm just strating to learn Ada 95 and I'm having some problems with comparing strings.

Here's the code:

    with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; 
with Ada.Command_Line;
with Ada.Strings.Unbounded;

procedure Test1 is

vad : String(1..9);
Amount : Integer;
Main : Integer;
Second : Integer;
Third : Integer;

begin
   Main := 1;
   Second := 0;
   Third := 0;

   Put("What do you want to do?");
   New_Line(1);
  Get(vad);
  New_Line(1);

  if Vad  = "fibonacci" then
     Put("How long do you want the sequence to be");
     New_Line(1);

     Get(Amount);
     New_Line(1);

      Amount := Amount -1;



      for I in 1 .. Amount loop
     Put(Main); 
     New_Line(1);
     --Put(" ");
     Third := Second;
     Second := Main;

     Main := (Second + third);
      end loop;

      New_Line(2);

  elsif Vad = "two" then
     Put("How long do you want the sequence to be?");
     New_Line(1);
     Get(Amount); 
     New_Line(1);
     for U in 1 .. Amount loop
    Put(U * 2);
    Put(", ");
     end loop;


  else
   Put("ok");

  end if;

end Test1;

As it is now, the if statement recognises when I type fibonacci, but when I type two it just goes to the 'else' part of the code.

Any ideas what might be wrong?

Thanks in advance.

CREATE VIEW with IF and ERROR

CREATE VIEW nextClass AS
SELECT date,id
FROM class
WHERE date >= CURDATE()
AND IF (
    date < CURDATE(),
    ERROR_MESSAGE('You cannot update previous classs'),
    CLOSE()
    )

Can someone help with the CREATE VIEW statement in SQL. I need to show all future classes and reject attempts to update previous classes. I have a syntax error in this code.

Javascript string compare if else

I'm fairly new to Javascript and not clear what is wrong with the code below. Basically I want to ask user to input a text string and compare to another text string. Then tell them whether their string is alphabetically higher or lower then the stored value. The code is below. When I test this in jsfiddle I only get the second alert message. any ideas?

var string1;
var string2;
string1 = prompt("tell me your string1?");
string2 = "green";

if ("string1" > "string2")
alert("your string is alphabetically higher");
else
alert ("your string is not alphabetically higher");

Bash script - errors: Host Verification failed and unexpected `then'

I wrote a really small script that uploads and moves a file or multiple files from folder to folder, uploads it, checks if the the file is on the server and if yes moves it locally to another folder.

But I am confronted with two error messages. The first one is

Host Verification failed

There is no indication on the line it happens in, but I guess because the file upload does not work, it has to be in line 4. The second error is

unexpected `then'

Suggestions where my mistakes are? I know the code isn't really safe and not well programmed, but in my mind it should work in theory.

#!/bin/bash
sudo find '/path/to/file' -type f -mmin +10 -exec mv '{}' '/path/to_new/folder' \;
sleep 3
sshpass -p 'password' scp /local/path/to_file/Z*.dat user@server:/destination/path/to/folder
sleep 3
Y=$(date +"%Y" | cut -c 4)
hour=$(date -d "1 hour ago" +"Z"$Y"%m%d%H%M")
sshpass -p 'password' ssh user@server 'if[ -f '/path/on/server/to_file/$hour.dat' ]; then echo yes; else echo no; fi'
x=$(echo yes)
z=$(echo no)
if [ "$x" == "yes" ]; then find '/path/to/file' -type f -mmin +10 -exec mv '{}' '/path/to_new/folder' \;;
fi

Thanks, BallerNacken

EDIT: Oh the unexpected `then' is probably due to the missing empty space between the if and the [

check if input is between two int or float then display or not display content

In javascript I need to check whiwh value user enter in an html input like this:

<input type="text" id="volume" class="form-control" name="voilume"></input>

<div id"button"></div>

Ineed to know if the input is between 0,5 and 8 (so I have int and float as you can understand).

So the value has to be >= 0,5 and <= 8

If value input if between 0,5 and 8 I have to display a button, else nothing to do. But I need to prevent if user change the value many times.

So if he enters 3 display a button in div id=button", if it changes for another value like 2 for example keep displaying the button, but if he changes value input for 100 I need to remove the button in div id="button".

for now I tried something like this in order to test if it works:

var input= $('#volume').val();
    if (input >= 0.5 && input <= 8) {
        $('#button').html('ok');
    } else {
      $('#button').empty();
    }

But it does not work.

Is there any way to set priority for the if condition rather than the next lines of code?

I have a api data,fetching it and showing it in website using angular js. i am just trying to store the api data in local storage other than fetching data from api everytime. so i coded like this.

       if($window.localStorage.cityApi){
            $scope.cities = JSON.parse($window.localStorage.cityApi);
        }
        AddCityService.init(function(city_response) {
            $scope.loading = false;
            $scope.cities = city_response.data;
            $scope.city = JSON.parse(JSON.stringify(getCity($stateParams._id)));
            $window.localStorage.cityApi = JSON.stringify($scope.cities);
        });

But the problem is,It is taking the data from api, not from the local storage. if i comment code of getting response from api. it will fetch from the local storage. if i mention api also along with the local, it will take the from api. i've checked in chrome developer tools. i can't use else condition too for this. can anyone tell me is there any way to do this.

apply function with external conditions

I have a dataframe df with random values

df <- data.frame(x1=runif(20,1,200),x2=runif(20,1,18),x3=runif(20,1,7),x4=runif(20,1,3),x5=runif(20,1,25),x6=runif(20,1,220),x7=runif(20,1,10),x8=runif(20,1,8),x9=runif(20,1,20),x10=runif(20,1,32))
df

           x1        x2       x3       x4        x5         x6       x7       x8        x9       x10
1   43.942462 14.983885 4.267664 2.591210 19.650770  95.710478 8.830253 7.089017  5.341859  3.574852
2  185.965077  8.099796 3.592361 1.953196  8.837645 111.846707 8.180938 3.355258 13.889081 26.878697
3   83.532083  2.782204 3.160955 1.892041 23.216698  80.521986 3.864614 6.799805 17.493065  9.246177
4   48.416861 17.019713 5.182366 2.501890  8.108828 219.419766 4.687034 6.785789  2.525997  7.145447
5   66.766778 11.716819 1.649946 2.136352  2.957554 126.164722 9.980739 1.919323 16.556541  5.447096
6   78.305312 12.148354 6.408544 2.644811 10.362618  53.112153 1.092853 1.360766  6.693875 17.108564
7   64.995759 13.385556 3.375907 1.923173 19.732286 219.780082 4.074889 4.609356  7.098822 25.412262
8  196.463100 17.491693 2.317492 2.573539 24.350820  36.696244 6.277854 6.247473  5.535765 12.121822
9   48.467431 11.659182 4.324854 1.380067 15.269617 102.453557 2.724937 1.481521 14.916894  3.451188
10 134.913063  8.927522 2.637946 1.526043 17.956797  49.671752 5.014152 4.737910  4.241197 28.916885
11 190.841615  2.639374 5.038702 2.806088 15.127840   8.841983 2.155842 7.589245 13.799412 28.025792
12  46.963826 11.212431 4.944327 2.937039 16.410549  25.048928 6.330826 5.006221  2.986566 17.005088
13  97.258821 17.847892 6.202023 2.228292 19.804482 159.922462 2.587568 4.175234  5.360039 15.812061
14 123.439971 15.415940 5.785273 2.075161 11.496406  12.449913 6.484951 7.911373 11.578242 22.398292
15   4.225315 11.775122 6.908108 2.980960 22.768381 109.853774 2.535843 7.293656 13.290552 29.302949
16  49.927327  4.086780 3.941200 1.129892 18.200466 164.281496 6.881178 6.199219  4.091858 29.963647
17 105.716881 12.421335 6.527660 2.767754 22.055987 208.188895 8.125112 7.702927  3.027778 20.080756
18 195.205248  5.749007 6.204989 1.815563  3.875226 200.608675 1.500572 7.116924  1.608354 13.292293
19  27.564433 16.788191 1.648707 2.360290 22.539064 192.914543 1.327605 6.096303  7.105979 22.650040
20 122.620812 11.475314 5.588179 1.884028  3.692936 200.056348 3.248232 1.562624 18.998767 29.424066

and a vector ind with certain values corresponding to each column in df. The values in ind are an indicator for a normalisation procedure.

ind
x1     x2     x3     x4     x5     x6     x7     x8     x9    x10 
0.800  1.000  0.400  0.010  6.000  0.100  0.180  0.006 10.000  1.000

Now I need to write a code that applies a desired function to each value in a column in df if its corresponding value in ind is equal to or above a certain threshold value.

For an example, if this threshold would be 0.8, the affected columns in df would be x1, x2, x5, x9, and x10.

I have tried something like apply(df,2,function(x)... but I'm not skilful enough to insert the ifelse that is clearly needed.

MS Word expression

I am try to make page numbers with IF statement like this

{ IF { PAGE } > 1 "{ PAGE }" "" }

And doing all like here: http://ift.tt/1KeIUJ1

If more than one page than site numbers will show up. But i cant make it working when i press CTRL + F9 and type this command its not working. Even only { PAGE } not working but when i put this command form menu its working... what i doing wrong?? Why its not working after CTRL + F9. and Typing PAGE. I know that i can preview it by ALT + F9

Sorry for not English Screenshot

enter image description here

BEFORE ALT + F9: enter image description here AFTER ALT + F9: enter image description here

jeudi 28 janvier 2016

MSQL IF statement Error

I'm trying to retrieve data of multiple parameters from a table of a MySQL based database.

I want check the count of date and if the count is equal to 24, I need to find max and min of multiple parameter and retrieve the data. I've used the below shown query, but it gives syntax error.

"SET @cnt=(select count(DATE) from DATA where ID=1111 and     DATA_DATE>='2016-01-24 00:00:00' and DATA_DATE<'2016-01-25 00:00:00')    \
       IF (@cnt=24) then \
            select MIN(parameter1),max(parameter2) from STATION_DATA where STATION_ID=6216 and DATA_DATE>='2016-01-24 00:00:00' and DATA_DATE<'2016-01-25 00:00:00' \
     END IF

But it gives syntax error . I'm a MySQL beginner and any help will be highly appreciated.

Thanks in advance.

Long elif chains vs dictionary with exec()

I am a novice to python and I have read a lot of tutorials on how to properly code. One thing that keep popping up is to never write the same line of code multiple times. I am unsure if long elif arguments count for that, but to me it just looks like bad code.

for exaple:

class answers(object):
    def __init__(self):
        self.x = 'hello world'

    def knight(self):
        print('Neee!')
    def bunny(self):
        print('Rawwww!')
    def pesant(self):
        print('Witch!')
    def dingo(self):
        print('Bad, wicked, naughty Zoot!')
foo = answers()    
egg = input("Sounds:")

if egg == "knight":
    foo.knight()
elif egg == 'bunny':
    foo.bunny()
elif egg == 'pesant':
    foo.pesant()
elif egg == 'dingo':
    foo.dingo()
else:
    print("I don't know?")

That works but I think the following code is looks cleaner.

class answers(object):
    def __init__(self):
        self.x = 'hello world'

    def knight(self):
        print('Neee!')
    def bunny(self):
        print('Rawwww!')
    def pesant(self):
        print('Witch!')
    def dingo(self):
        print('Bad, wicked, naughty Zoot!')

foo = answers()
responce = {'knight': 'foo.knight()', 'bunny': 'foo.bunny()', 'pesant': 'foo.pesant()', 'dingo': 'foo.dingo()'}

while True:
    try:
        egg = input('sounds:')
        exec(responce[egg])
    except KeyError:
        print("I don't know")

Both lines of code do the same thing, does it really matter which I use or is one better then the other?

side note, I know that exec() should not normally be used but I could not find another way to assign a function to a string.

pomodoro clock not stopping at zero

The clock works fine until it gets to zero which is where it is supposed to start the break timer. the issue is that it gets to zero then starts counting down in negative numbers. here is the function that has that code. By the way, I have the interval at 100 so I do not have to wait a long time when testing the clock.

function start(){
   $("#start").addClass("disabled");
   $("#myreset").addClass("disabled");
   var secs = Number("59");

   var min = document.getElementById("sessiontime").innerHTML; 
   min = min-=1;

   if(min > -1){
      startcounter = setInterval(function(){
      secs--;

         if(secs > 9){
            document.getElementById("mytimer").innerHTML = min +":"+ secs;
               } else if(secs >=0 && secs < 10){
                  secs = "0"+secs;
                  document.getElementById("mytimer").innerHTML = min +":"+ secs;
                     } else if(secs < 0){
                        min--;
                        secs = 59;
                           } else if(secs === 0 && min === 0){
                              clearInterval(startcounter); 
                              var x =      document.getElementById("arrownumid").innerHTML;
                        mybreak(x);
                     }
      },100);

   }
}

What is better if else or only if to return a value inside a funciton and why?

Hi a am hesitant to ask this but I need some advise about this sample code and what is better between the two function below.

function get_product($productType){
  $product =[];

  if('available'== $productType){
    $product = array('tshirt','pants','polo'); 
  }else if('out_of_stock' == $productType){
    $product = array('short');
  }
  return $product;
}

or

function get_product($productType){
  $product = array('tshirt','pants','polo');

  if('out_of_stock' == $productType){
    $product = array('short');
  }
  return $product;
}

I just want to get the opinion of some programmers.Thanks in advance.